body
stringlengths
25
86.7k
comments
list
answers
list
meta_data
dict
question_id
stringlengths
1
6
<p>The idea is to convert first 8 character from the C string to <code>uint64_t</code> or <code>uint32_t</code>, then to convert to Big Endian.</p> <p>The value can be stored and compared with same values and result will be compatible with <code>memcmp</code> or <code>strcmp</code>.</p> <p>The only exception is if both "strings" are 8 bytes long or 4 bytes long for <code>uint32_t</code> and are equal, the function must return sentinel value, e.g. <code>std::numeric_limits&lt;int&gt;::max()</code>, so caller to know he will need to compare the real strings in order to find the result.</p> <p>For simplicity, I assume code runs on Little Endian machine and convert to Big Endian is done by <code>__builtin_bswap64</code> (available on gcc and clang).</p> <p>Here is the code + some tests</p> <pre><code>#include &lt;cstdint&gt; #include &lt;cstring&gt; #include &lt;limits&gt; namespace sshhash_implementation{ constexpr auto bswap(uint64_t x){ return __builtin_bswap64(x); } constexpr auto bswap(uint32_t x){ return __builtin_bswap32(x); } template&lt;typename T&gt; T hash(const char *src){ constexpr auto capacity = sizeof(T); union{ char s[capacity]; T u = 0; }; strncpy(s, src, capacity); return bswap(u); } template&lt;typename T&gt; constexpr T mask(){ return bswap(T{ 0xFF } &lt;&lt; (sizeof(T) - 1) * 8); } template&lt;typename T&gt; int sscmp(T const a, T const b){ if (a &gt; b) return +1; if (a &lt; b) return -1; // equal, check size constexpr auto m = mask&lt;T&gt;(); if ( (a | b) &amp; m ) return std::numeric_limits&lt;int&gt;::max(); return 0; } } template&lt;typename T&gt; auto sshash(const char *s){ return sshhash_implementation::hash&lt;T&gt;(s); } auto sshash8(const char *s){ return sshash&lt;uint64_t&gt;(s); } auto sshash4(const char *s){ return sshash&lt;uint32_t&gt;(s); } template&lt;typename T&gt; auto sscmp(T a, T b){ return sshhash_implementation::sscmp(a, b); } auto sscmp8(uint64_t a, uint64_t b){ return sscmp(a, b); } auto sscmp4(uint32_t a, uint32_t b){ return sscmp(a, b); } #include &lt;cstdio&gt; template&lt;typename T = uint32_t&gt; void testC(const char *sa, const char *sb, bool const overflow){ auto const a = sshash&lt;T&gt;(sa); auto const b = sshash&lt;T&gt;(sb); int const x = strncmp(sa, sb, sizeof(T)); int const y = sscmp(a, b); bool const ok = [=](){ if (overflow) return x == 0 &amp;&amp; y == std::numeric_limits&lt;int&gt;::max(); else return x == y; }(); printf( "%-8s | %-8s | %2d | %2d | %-8s\n", sa, sb, x, y, ok ? "OK" : "Error" ); } template&lt;typename T = uint32_t&gt; void test(const char *sa, const char *sb, bool const overflow = false){ testC(sa, sb, overflow); testC(sb, sa, overflow); } int main(){ test("aaa" , "aaa" ); test("aaa" , "b" ); test("aaaa" , "b" ); test("aaa" , "bbbb" ); test("aaaa" , "bbbb" ); test("aaaa" , "aaaa", true ); } </code></pre>
[]
[ { "body": "<p>Since we assume GCC or Clang, we can easily make the code adapt to the target's endianness:</p>\n\n<pre><code>#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__\n constexpr auto hton(std::uint64_t x){\n return __builtin_bswap64(x);\n }\n\n constexpr auto hton(std::uint32_t x){\n return __builtin_bswap32(x);\n }\n#elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__\n constexpr auto hton(std::uint64_t x){\n return x;\n }\n\n constexpr auto hton(std::uint32_t x){\n return x;\n }\n#else\n#error Unsupported byte order\n#endif\n</code></pre>\n\n<p>I've used the conventional \"host to net\" name for the function, to be clearer.</p>\n\n<hr>\n\n<p>Some identifiers are misspelt: <code>std::uint32_t</code>, <code>std::uint64_t</code>, <code>std::strncpy</code>, <code>std::strncmp</code>, <code>std::printf</code>.</p>\n\n<hr>\n\n<p>This function is unnecessary:</p>\n\n<blockquote>\n<pre><code>template&lt;typename T&gt;\nauto sscmp(T a, T b){\n return sshhash_implementation::sscmp(a, b);\n}\n</code></pre>\n</blockquote>\n\n<p>Much simpler to write</p>\n\n<p>using sshhash_implementation::sscmp;</p>\n\n<hr>\n\n<p>No need for the immediately-executed lambda in <code>testC()</code>:</p>\n\n<blockquote>\n<pre><code>bool const ok = [=](){\n if (overflow)\n return x == 0 &amp;&amp; y == std::numeric_limits&lt;int&gt;::max();\n else\n return x == y;\n}();\n</code></pre>\n</blockquote>\n\n<p>That can be written as a simple expression:</p>\n\n<pre><code>bool const ok = overflow\n ? x == 0 &amp;&amp; y == std::numeric_limits&lt;int&gt;::max()\n : x == y;\n</code></pre>\n\n<hr>\n\n<p>In <code>mask()</code>, I think the constant <code>8</code> was intended to be <code>CHAR_BIT</code>, since it's converting a count of <code>char</code> to number of bits.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-08T14:21:12.587", "Id": "232062", "ParentId": "232059", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-08T13:08:07.300", "Id": "232059", "Score": "3", "Tags": [ "c++", "strings" ], "Title": "Small String hashing and compare" }
232059
<p>I have written a C function to parse an IP address that should match the regular expression <code>^\d+.\d+.\d+.\d+</code> and nothing else. Additionally all bytes are limited to 0-255.</p> <p>I tried to catch all invalid inputs, but I am unsure if there are any edge cases I missed or if it could be simplified.</p> <p>The function is intended to be used in an embedded system. Therefore I don't want to use external libraries (or anything in <code>stdio.h</code>) and code size is most important.</p> <p>I am not really looking for stylistic advice, but rather a functional review.</p> <pre><code>// Returns the number of characters parsed or 0 if not successful unsigned int StringToIp(uint8_t addr[4], const char* ipSrc, const size_t ipSrcLen) { char* ipPtr = ipSrc; int16_t current = -1; uint8_t addrIdx = 0; for (int i = 0; i &lt; ipSrcLen, addrIdx &lt; 4; i++) { char c = *ipPtr++; if (c == '.') { if (current == -1) return 0; // 2 consecutive dots or dot at beginning addr[addrIdx++] = current; current = -1; } else { uint8_t digit = c - '0'; if (digit &gt;= 10) { // Invalid character if (addrIdx == 3 &amp;&amp; current &gt;= 0) { // Invalid character at the end is treated as the end of the address addr[addrIdx++] = current; ipPtr--; break; } } if (current == -1) { // first digit of current byte current = digit; } else { // further digits current = current * 10 + digit; if (current &gt; 255) return 0; // current byte greater than 255 =&gt; invalid } } } if (addrIdx == 3 &amp;&amp; current &gt;= 0) { // write last byte (necessary if at end if string) addr[addrIdx++] = current; } if (addrIdx == 4) { // valid IP address return ipPtr - ipSrc; } else { // invalid IP address return 0; } } </code></pre> <p>I also wrote the inverse function. Here I am quite sure I got all cases, but the divisions are suboptimal, because the microcontroller has no dedicated divider. Which means extra code for the divisions has to be generated and this bloats the code size and reduces the speed (which is somewhat less important to me).</p> <p>Is there any why to avoid the divisions?</p> <pre><code>unsigned int IpToString(char ipDst[4*3+3+1], const uint8_t addr[4]) { char* ipPtr = ipDst; for (int i = 0; i &lt; 4; i++) { uint8_t current = addr[i]; uint8_t h = current / 100; current -= h * 100; uint8_t d = current / 10; current -= d * 10; uint8_t o = current; if (h &gt; 0) *ipPtr++ = '0' + h; if (h &gt; 0 || d &gt; 0) *ipPtr++ = '0' + d; *ipPtr++ = '0' + o; if (i &lt; 3) *ipPtr++ = '.'; } *ipPtr = '\0'; return ipPtr - ipBuffer; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-08T15:31:23.660", "Id": "452951", "Score": "2", "body": "For your second function, since you know the range will be 0-255, why not use a series of `if` statements? Compare with 200, 100, and then a binary search of 10's digits." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-08T16:59:38.260", "Id": "452962", "Score": "0", "body": "In the future, it is best to provide test cases as part of the code for review so that we can properly review the code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-08T18:18:43.363", "Id": "452973", "Score": "0", "body": "Rather than write your own, you could duplicate implementations of `inet_*` from `arpa/inet.h`, for example in [musl](https://git.musl-libc.org/cgit/musl/tree/src/network) [`inet_aton.c`](https://git.musl-libc.org/cgit/musl/tree/src/network/inet_aton.c) and [`inet_ntoa.c`](https://git.musl-libc.org/cgit/musl/tree/src/network/inet_ntoa.c). (Keep in mind to respect musl's license.)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-08T22:57:34.330", "Id": "453007", "Score": "0", "body": "How should `StringToIp(..., \"2.0004.6.8\", ...)` function? (4 digits in a byte)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-08T23:06:29.070", "Id": "453008", "Score": "0", "body": "@chux-ReinstateMonica At the moment it basically ignores the leading zeros which is fine I think, because it still represents a valid IP." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-08T23:08:59.910", "Id": "453009", "Score": "0", "body": "@esote These implementations are interesting, but rely on stdio.h and stdlib.h both of which I cannot use." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-09T04:33:23.637", "Id": "453024", "Score": "0", "body": "@LittleEwok Oh yes, sorry I forgot about that." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-15T10:06:36.067", "Id": "453895", "Score": "0", "body": "Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*. Consider posting a follow-up question with your new code and a link to this question instead." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-15T10:35:19.827", "Id": "453901", "Score": "0", "body": "@Mast I updated the code because the original contained bugs which are not all addressed in the answers and I did not want to leave it at that in case somebody decides to use this code. Otherwise no working version of my code can be found here. I probably could have written an answer myself but wanted to acknowledge the best given answer by accepting it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-15T10:37:13.170", "Id": "453902", "Score": "0", "body": "So post a new question with the improved code, link back from that question to this one and you could even link from this old question towards the new question. Make a little header of sorts on top of your post indicating where the improved code can be found." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-15T10:46:44.957", "Id": "453904", "Score": "0", "body": "@Mast Although I think you are right that is the standard procedure here, I am not convinced it is the best solution in my case since I don't want or need any further feedback and probably won't even get any. Therefore posting a new question will just lead to an unanswered question for eternity. But if being pedantic is more important than wanting to protect others from buggy code, you are absolutely right. I even intentionally left the original code in the question." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-15T11:10:51.873", "Id": "453906", "Score": "0", "body": "It has nothing to do with being pedantic. All answerers should review the same version of the code or a convoluted mess will happen. We can't have that, and the only way to prevent it is to disallow code-edits after answers come in. Can't be helped really." } ]
[ { "body": "<h3>Potential bugs</h3>\n\n<p>I just spent a few minutes reviewing this, so I'm not sure these are bugs, but you should have a look at them:</p>\n\n<ol>\n<li><p>The comma operator is not the same as <code>&amp;&amp;</code>. You have this code:</p>\n\n<pre><code>for (int i = 0; i &lt; ipSrcLen, addrIdx &lt; 4; i++) {\n</code></pre>\n\n<p>but I think you meant to use <code>&amp;&amp;</code> instead of <code>,</code>. I'm not sure it matters because I'm not sure what the chances are that you will get a mismatch between the string contents and the length, but it's a possible source of error.</p></li>\n<li><p>Incomplete error checking. In the \"invalid digit\" section of your loop, you have this check:</p>\n\n<pre><code>if (addrIdx == 3 &amp;&amp; current &gt;= 0) {\n</code></pre>\n\n<p>but you don't do anything if that condition is not true. If <code>addrIdx</code> is 0, 1, or 2 you don't handle the bad digit, but instead fall through. I think you need to catch those cases and fail gracefully.</p></li>\n</ol>\n\n<h3><code>IpToString</code></h3>\n\n<p>I mentioned this in the comments, but you know the range of values is small. So there's no reason not to replace your divisions with either a series of <code>if</code> statements or a lookup table. </p>\n\n<p>Unless you're writing a router or something, I don't expect the lookup table would pay for itself, so the <code>if</code> statements seem to be the way to go. Something like this:</p>\n\n<pre><code>need_tens_0 = FALSE\n\n// hundreds digit\nif number &gt;= 100:\n need_tens_0 = TRUE\n\n if number &gt;= 200:\n *ptr++ = '2'\n number -= 200\n else:\n *ptr++ = '1'\n number -= 100\n\n// tens digit (binary search)\nif number &gt;= 50:\n if number &gt;= 80:\n if number &gt;= 90:\n *ptr++ = '9'\n number -= 90\n else:\n *ptr++ = '8'\n number -= 80\n\n// ... buncha cases omitted ...\n\nelse if number &gt;= 10:\nelse:\n // \"6\" could be 56 or 106 or 216. Check if we need to insert a padding 0\n if need_tens_0:\n *ptr++ = '0'\n\n// Ones digit\n*ptr++ = '0' + number\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-08T16:18:59.970", "Id": "452958", "Score": "0", "body": "I think you are right about the comma operator. The compiler output is quite different if I use `&&` instead and does not change if I remove `i < ipSrcLen,`. So it seems `i < ipSrcLen` was being ignored completely. Thank you very much." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-08T16:23:13.967", "Id": "452959", "Score": "0", "body": "The second point is not true though, because anything else than `addrIdx >= 3` should be treated as an error and return 0, which it does.\nI ended up checking the hundreds with if and the tens with division, because that yielded the smallest code size. On a different architecture the binary search may be more efficient but not on mine." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-08T16:55:27.217", "Id": "452961", "Score": "0", "body": "If you hadn't answered this question, it might have been closed due to Lack of Concrete Context." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-08T15:56:47.970", "Id": "232065", "ParentId": "232063", "Score": "4" } }, { "body": "<p>Your compiler should be smart enough to <a href=\"https://stackoverflow.com/q/41183935\">replace the division by multiplication</a>. Here's an experiment I did with CLang on x86_64:</p>\n\n<pre class=\"lang-c prettyprint-override\"><code>#include &lt;inttypes.h&gt;\n\nuint8_t div8_100(uint8_t a) { return a / 100; }\nuint8_t div8_10(uint8_t a) { return a / 10; }\n</code></pre>\n\n<p>clang -O3 -Wall -Weverything -S div8.c</p>\n\n<pre><code>div8_100:\n movzbl %cl, %eax\n leal (%rax,%rax,4), %ecx\n leal (%rax,%rcx,8), %eax\n shrl $12, %eax\n retq\n\ndiv8_10:\n movzbl %cl, %eax\n imull $205, %eax, %eax\n shrl $11, %eax\n retq\n</code></pre>\n\n<p>This is fairly efficient code, and it is not using any exotic opcodes, therefore I expect it to be available on every architecture.</p>\n\n<p>In summary, as long as you divide by integer literals, there is no reason for the compiler to call any external division function.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-15T08:03:44.477", "Id": "453885", "Score": "0", "body": "I did not know that. Very good to know. That may be the reason why I did not get any benefit from replacing `/ 10` by @Austin Hastings proposed `if`` statements." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-10T15:10:59.667", "Id": "232149", "ParentId": "232063", "Score": "2" } } ]
{ "AcceptedAnswerId": "232065", "CommentCount": "12", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-08T14:44:10.307", "Id": "232063", "Score": "7", "Tags": [ "c", "strings", "parsing", "embedded", "ip-address" ], "Title": "Simple IP address parser in C" }
232063
<p>It is a simple Poker balance/bid tracker to automate calculations for players' scores.</p> <p>It is a project I made to practice the concepts of lists and indices. And thus heavily relies on indexing and list search.</p> <p>I know I could have used dictionaries, but I chose not to get familiar with previously mentioned concepts.</p> <p>I'm still learning using MIT online course, so I'm only familiar with a limited number of topics, including Branching and Iteration, String Manipulation / bisectional search / Guess And Check / Approximation, Decomposition / Abstraction / Function Definition, Sequences including lists, tuples, and Dictionaries.</p> <p>Please consider that when providing an answer.</p> <p>Kindly see if this code can be improved in any way without using dictionaries.</p> <pre class="lang-py prettyprint-override"><code>import string def new_line(n): ''' prints (n) new lines ''' for n in range(n): print() def x_player(list_secondary, string, list_primary): ''' returns the item from a list(list_primary) at the index of another string (string) in another list(list_secondary) ''' return list_primary[list_secondary.index(string)] def get_space(pos_list, pos_string, string, extra_length): ''' returns the given string(string) argument multiplied by the length of the longest string in a list(pos_list) minus the length of another_string (pos_string) plus any extra length determined by the user. ''' lengths = [ len(string) for string in pos_list] h_length = max(lengths) + extra_length return ( string * ( h_length - len(pos_string))) def list_players(player_names, player, list_): ''' prints the player name + appropriate space + an item at the index of : (player in player_names) from a different list (list_) ''' print ( player + get_space(player_names, player, ' ', 1) + ': '+ str(x_player(player_names, player, list_))) def list_balances(player_names, balances): ''' lists the player names and their balances. ''' print('Current Balances:') for player in player_names: list_players(player_names, player, balances) def list_bids(player_names, bids): ''' lists the player names and their bids ''' print('Current Bids:') for player in player_names: list_players(player_names, player, bids) def poker(): ''' starts the poker score counter ''' # ask for the number of players and their names. n_players = int(input('Number Of Players?... ')) player_names = [] for n in range(n_players): player = input('Player # ' + str(n+1) + ' .... ') player_names.append(player) # iniate lists for balances, bids and list to determine if a player has folded or not. balances = [ 90 for n in range(n_players)] bids = [10 for n in range(len(player_names))] fold_code = [ 0 for n in range(len(player_names)) ] #balance_codes = [ 0 for n in range(n_players)] # this variable will determine if a round is over or not. this_round = '' # total bid: total = sum(bids) # getting user's confirmation to start the counter. # this variable will not be used again. stop = input('Press Enter To Continue...') print('Starting Game...') # Intitial Balance / Bid listing. list_balances(player_names, balances) list_bids(player_names, bids) while True: # to determine if a round is over. if this_round == 'y': print('Who Won?') winner = input() # adding the total bid to the winner's balance. balances[player_names.index(winner)] += total new_line(1) print(winner, 'Won This Round') new_line(1) list_balances(player_names, balances) # checking for players who are out. # a for loop that iterates n_player times. to avoid # indices being out of range after removing a player from the list. for var in range(n_players): if 0 in balances: print (player_names[balances.index(0)].upper(), 'Is Out...') player_names.pop(balances.index(0)) bids.pop(balances.index(0)) balances.pop(balances.index(0)) # self-explanatory using the print statement. for a player in player_names: balances[player_names.index(player)] -= 10 # re-initializing bids and fold code after each round. # fold code is used to determine if a player has folded for the round. bids = [ 10 for n in range(len(player_names))] fold_code = [0 for n in range(len(player_names))] print('Deducting 10$ from all players for the new round...') new_line(1) list_balances(player_names, balances) new_line(1) list_bids(player_names, bids) new_line(1) print('-' * 35) for player in player_names: # if a player folds for the round the value in the list ( fold-code) 'at the same index' # gets assigned to be '1' therefore the loop ends and moves on to the next player. if fold_code[player_names.index(player)] == 1: continue # asking for user input ( player action for the round. print('&gt;' * 15, player.upper(), '&gt;' * 15 ) action = input () # c i.e : 'call', which then evaluates the difference between the max bid and # the current player's bid and later on in the program subtracts it from the \ # player's balance and adds it to the total bid. if action == 'c': bid = max(bids) - x_player(player_names, player, bids) print(player, 'Called...') # # r i.e : 'raise', does the same process using the 'bid' variable but adds the raise value to it. elif action == 'r': print('Raise By?') r = int(input()) bid = max(bids) - x_player(player_names, player, bids) + r print(player, 'Raised By', r) # fold makes the 'bid' variable = 0 and makes the program skip the player's turn until the round is over. elif action == 'f' : fold_code[player_names.index(player)] = 1 bid = 0 print(player, 'Folded For the round') # similar to fold but doesn't skip the player's turn else: bid = 0 print(player, 'Checked...') # deducting the 'bid' variable from the player's balance and adding it to the respective value in the bids list. balances[player_names.index(player)] -= bid bids[player_names.index(player)] += bid total = sum(bids) new_line(1) list_balances(player_names, balances) new_line(1) list_bids(player_names, bids) new_line(1) print('Total Bid : ' + str(total)) new_line(2) print('-' * 35) # the decision to end a round is left to the user, plans to implement automatic round termination has been made. print('Round Over?') this_round = input() new_line(20) poker() <span class="math-container">```</span> </code></pre>
[]
[ { "body": "<h1>Docstrings</h1>\n\n<p>You should always use triple double quotes for docstrings. <code>'''</code> should be replaced with <code>\"\"\"</code> </p>\n\n<h1>Comments</h1>\n\n<p>Don't fill your code with comments. The actual code is harder to read. Comments should be used only while explaining something which others can't understand by themselves.</p>\n\n<h1>Making the code shorter</h1>\n\n<p><strong>Functions other than poker</strong></p>\n\n<ul>\n<li><p>You can remove <code>import string</code> as you don't use it</p></li>\n<li><ol>\n<li>You can use <code>print()</code> instead of creating a new function</li>\n<li>You can use <code>list_players</code> directly, instead of <code>list_bids</code> or <code>list_balances</code> </li>\n</ol></li>\n</ul>\n\n<p><strong>In the poker function</strong> </p>\n\n<ul>\n<li><pre><code>n_players = int(input('Number Of Players?... '))\nplayer_names = []\n\nfor n in range(n_players):\n player = input('Player # ' + str(n+1) + ' .... ')\n player_names.append(player)\n</code></pre>\n\n<p>can be rewritten as</p>\n\n<pre><code>n_players = int(input('Number Of Players?... '))\nplayer_names = [input(f'Player # {n+1} .... ') for n in range(n_players)]\n</code></pre></li>\n<li><p>While beginning, len(player_names) is the same as <code>n_players</code>. Therefore, we can write</p>\n\n<pre><code>balances = [ 90 for n in range(n_players)] \nbids = [10 for n in range(len(player_names))]\nfold_code = [ 0 for n in range(len(player_names)) ]\n</code></pre>\n\n<p>as</p>\n\n<pre><code>balances = [90] * n_players\nbids = [10] * n_players\nfold_code = [0] * n_players\n</code></pre></li>\n</ul>\n\n<p>Final code after implementing the above ideas and making some negligible changes:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def get_space(pos_list, pos_string, string, extra_length):\n h_length = max(len(string) for string in pos_list) + extra_length\n return string * ( h_length - len(pos_string))\n\ndef list_players(player_names, n_players, list_):\n for i in range(n_players):\n print(player_names[i] + get_space(player_names, player_names[i], ' ', 1) + ': ' + str(list_[i]))\n\ndef poker():\n n_players = int(input('Number Of Players?... '))\n player_names = [input(f'Player # {n+1} .... ') for n in range(n_players)]\n\n balances = [90] * n_players\n bids = [10] * n_players\n fold_code = [0] * n_players\n\n total = sum(bids)\n\n input('Press Enter To Continue...')\n print('Starting Game...')\n\n this_round = ''\n\n while True:\n print('Current Balances:')\n list_players(player_names, n_players, balances)\n print('Current Bids:')\n list_players(player_names, n_players, bids)\n\n if this_round == 'y':\n print('Who Won?')\n winner = input()\n\n balances[player_names.index(winner)] += total\n\n print()\n print(winner, 'Won This Round')\n print()\n\n print('Current Balances:')\n list_players(player_names, n_players, balances)\n\n for var in range(n_players):\n if 0 in balances:\n ind_0 = balances.index(0)\n\n print(player_names[ind_0].upper(), 'Is Out...')\n\n n_players -= 1\n player_names.pop(ind_0)\n bids.pop(ind_0)\n balances.pop(ind_0)\n\n for player in player_names:\n balances[player_names.index(player)] -= 10\n\n bids = [10] * n_players\n fold_code = [0] * n_players\n\n print('Deducting 10$ from all players for the new round...')\n print()\n\n print('Current Balances:')\n list_players(player_names, n_players, balances)\n print()\n\n print('Current Bids:')\n list_players(player_names, n_players, bids)\n print()\n\n print('-' * 35)\n\n for player_index in range(n_players):\n player = player_names[player_index]\n\n if fold_code[player_names.index(player)] == 1:\n continue\n\n print('&gt;' * 15, player.upper(), '&gt;' * 15 )\n action = input()\n\n if action == 'c':\n bid = max(bids) - bids[player_index]\n print(player, 'Called...')\n\n elif action == 'r':\n print('Raise By?')\n r = int(input())\n bid = max(bids) - bids[player_index]\n print(player, 'Raised By', r)\n\n elif action == 'f':\n fold_code[player_names.index(player)] = 1\n bid = 0\n print(player, 'Folded For the round')\n\n else:\n bid = 0\n print(player, 'Checked...')\n\n balances[player_names.index(player)] -= bid\n bids[player_names.index(player)] += bid\n total = sum(bids)\n\n print()\n print('Current Balances:')\n list_players(player_names, n_players, balances)\n\n print()\n print('Current Biddings:')\n list_players(player_names, n_players, bids)\n\n print()\n print('Total Bid : ' + str(total))\n\n print()\n print()\n\n print('-' * 35)\n\n print('Round Over?')\n this_round = input()\n\nprint('\\n' * 20)\npoker()\n\n</code></pre>\n\n<p>If you have any suggestions or if you find any mistakes, please point them out in the comments.</p>\n\n<p>Hope this helps!</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-09T02:59:16.023", "Id": "453022", "Score": "1", "body": "Instead of calling `print() / print(whatever)`, couldn't one just do `print(\\nwhatever)`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-09T04:00:01.530", "Id": "453023", "Score": "0", "body": "@BruceWayne I did think of that, but don't you think it looks a bit ugly?\n\n`print('\\nwhatever')`\n\nI totes agree with you if you have to make the code shorter." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-09T09:31:28.650", "Id": "453030", "Score": "0", "body": "Can you please refer me to the Python Doc that states that docstrings should be written using \" \" \" instead of ' ' '" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-09T09:35:28.787", "Id": "453031", "Score": "0", "body": "Of course! [Here](https://www.python.org/dev/peps/pep-0257/) it is! \nIt says `For consistency, always use \"\"\"triple double quotes\"\"\" around docstrings.`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-09T10:06:34.600", "Id": "453033", "Score": "0", "body": "in :\n\n`def list_players(player_names, n_players, list_):\n for i in range(n_players):\n print(player_names[i] + get_space(player_names, player_names[i], ' ', 1) + ': ' + str(list_[i]))`\nn_players is varible as players who reach the balance of 0 are removed from the list\nwouldn't this cause an 'out of range' error?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-09T13:03:18.237", "Id": "453048", "Score": "0", "body": "If you notice carefully, the code is reducing 1 from `n_players` as players who reach balance of 0 are removed" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-09T15:13:18.840", "Id": "453062", "Score": "1", "body": "@Srivaths yeah perhaps, it's OP's call, I just wanted to mention another option instead of doing empty prints." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-08T17:48:16.543", "Id": "232071", "ParentId": "232066", "Score": "3" } }, { "body": "<p>There is a lot of room for improvement but I will stick to the index stuff.</p>\n\n<h1>Naming</h1>\n\n<p>Your function</p>\n\n<pre><code>def x_player(list_secondary, string, list_primary):\n '''\n returns the item from a list(list_primary) at\n the index of another string (string) in another list(list_secondary)\n '''\n\n return list_primary[list_secondary.index(string)]\n</code></pre>\n\n<ul>\n<li>has bad names for function and parameters. <code>x_player</code> suggest that it is about players but in fact it is an absolutely generic function. Even if used with players the qualifier <code>x_</code> does not give any hint what is happening or returned. also what is <code>list_primary</code> and what is <code>list_secondary</code>? The parameter name <code>string</code> is without any semantic hint. From the perspective of the function it even worse as the function is not limited to string type keys.</li>\n<li>has a bad docstring. the docstring is just a lengthy read of the code line below. A reader not familiar with your code has a hard time to understand the usage.</li>\n</ul>\n\n<p>What if we change the names and the docstring to</p>\n\n<pre><code>def get_value(keys, key, values):\n '''\n fakes a dict()\n '''\n return values[keys.index(key)]\n</code></pre>\n\n<p>All of a sudden it is absolutely clear, that this is a completely generic function that looks up values in a parallel list and may be used for any key type.</p>\n\n<h1>Consistency</h1>\n\n<p>You use your fake dict <code>x_player</code> for <code>bids</code> and <code>balances</code>, but you do not use it for <code>fold_code</code> where you do <code>fold_code[player_names.index(player)]</code> explicitly. Also there are explicit usages <code>balances[player_names.index(player)]</code> and <code>bids[player_names.index(player)]</code>. Either you think <code>fold_code[player_names.index(player)]</code> is readable, then avoid to create a function. Or you think that is somewhat hard to read, then create the function and use it throughout the code.</p>\n\n<p>For your dict-less implementation you have several lists of the same length. You first fill the key list <code>player_names</code> then you create the value lists inconsistently</p>\n\n<pre><code>balances = [ 90 for n in range(n_players)]\nbids = [10 for n in range(len(player_names))]\nfold_code = [ 0 for n in range(len(player_names)) ]\n</code></pre>\n\n<p>The first line I like the least, <code>n_players</code> is a helper for the input loop only. The real truth is <code>player_names</code>, the list lengths must match. So in terms of dependency to the real stuff your other lines are better. However thy are not pythonic in two ways. In python you nearly never loop over <code>range(len(x))</code>. So</p>\n\n<pre><code>bids = [10 for n in range(len(player_names))]\n</code></pre>\n\n<p>would read</p>\n\n<pre><code>bids = [10 for name in player_names]\n</code></pre>\n\n<p>which is less error prone. Also in python you use <code>_</code> when you do not need the variables you somehow get.</p>\n\n<pre><code>bids = [10 for name in player_names]\n</code></pre>\n\n<p>would read</p>\n\n<pre><code>bids = [10 for _ in player_names]\n</code></pre>\n\n<h1>Loops over player</h1>\n\n<p>You have a loop over <code>player_names</code> where you have multiple fake dict lookups for player attributes:</p>\n\n<pre><code>for player in player_names:\n # [...]\n if fold_code[player_names.index(player)] == 1:\n # [...]\n if action == 'c':\n bid = max(bids) - x_player(player_names, player, bids)\n</code></pre>\n\n<p>For this case your fake dict is not very efficient. Instead of retrieving player name and have many lookups you could also lookup the player index once</p>\n\n<pre><code>for player_idx, player in enumerate(player_names):\n # [...]\n if fold_code[player_idx] == 1:\n # [...]\n if action == 'c':\n bid = max(bids) - bids[player_idx]\n</code></pre>\n\n<p>That makes the code more readable.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-09T09:28:52.353", "Id": "453029", "Score": "0", "body": "Can you please elaborate why range(len(x)) is more prone to error?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-11T18:57:35.317", "Id": "453304", "Score": "0", "body": "Off by 1 is a typical error on loops. Of course it is hard to get your simple loop wrong. But if you access an element you type the container name twice `for i in range(len(container))` you access `container[i]`. When copy-pasting it is easy to get one name wrong. If you do `for i, e in enumerate(container):` you index/value tuple always matches. Or you may iterate over slices `for i, e in enumerate(container[5:-5:2]):`. `enumerate()` also works on generators, where `len()` is not available. Get used to use `enumerate()`." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-08T19:02:53.427", "Id": "232073", "ParentId": "232066", "Score": "3" } } ]
{ "AcceptedAnswerId": "232071", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-08T16:08:05.807", "Id": "232066", "Score": "8", "Tags": [ "python" ], "Title": "Simple Poker Counter" }
232066
<p>I have an MVC application that uses Active Directory membership for user authentication.</p> <p>After the user logs in, a <code>FormsAuthenticatedTicket</code> is created and encrypted. Then, in <code>Application_PostAuthenticateRequest</code> the ticket is decrypted and the deserialized user data is stored in a custom principal object.</p> <p>My problem is that when a user logs in after their cookie has expired, the ticket is encrypted with the current login data, but in global.asax the previous login's ticket is still decrypted. When debugging, I have seen the ticket data of the previous login of the same user with version 2.</p> <p>What mistake did I make?</p> <p>Web.config:</p> <pre><code>&lt;authentication mode="Forms"&gt; &lt;forms name=".ADAuthCookie" loginUrl="~/Account/Login"&gt; &lt;/forms&gt; &lt;/authentication&gt; &lt;membership defaultProvider="ADMembershipProvider"&gt; &lt;providers&gt; &lt;clear/&gt; &lt;add name="ADMembershipProvider" type="System.Web.Security.ActiveDirectoryMembershipProvider" connectionStringName ="ADconnectionString" attributeMapUsername="sAMAccountName" /&gt; &lt;/providers&gt; &lt;/membership&gt; </code></pre> <p>my post action login method</p> <pre><code> [HttpPost] [AllowAnonymous] public ActionResult Login(string userName, string password, bool rememberMe, string returnUrl) { if (string.IsNullOrWhiteSpace(userName) || string.IsNullOrWhiteSpace(password)) { ViewBag.Message = FormattedMessage.GetFormattedMessage("Veuillez Entrer l'utilisateur et/ou mot passe", TypeMessage.Danger, true); return this.View(); } if (Membership.ValidateUser(userName, password)) { FormsAuthentication.SetAuthCookie(userName, rememberMe); //JavaScriptSerializer js = new JavaScriptSerializer(); PrincipalContext principalContext = new PrincipalContext(ContextType.Domain); var userAD = UserPrincipal.FindByIdentity(principalContext, userName); var intervenant = unitOfWorkBll.UserBLL.GetAllFiltered(u =&gt; u.Matricule == userAD.EmployeeId, includes: "IntervenantRoles.Role, IntervenantStructures.Structure").SingleOrDefault(); //string userData = js.Serialize(intervenant); string userData = JsonConvert.SerializeObject(intervenant, Formatting.Indented, new JsonSerializerSettings { PreserveReferencesHandling = PreserveReferencesHandling.Objects }); FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, userName, DateTime.Now, DateTime.Now.AddMinutes(10),rememberMe, userData); string encryptedTicket = FormsAuthentication.Encrypt(ticket); HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket); Response.Cookies.Add(cookie); if (!string.IsNullOrWhiteSpace(returnUrl) ) { return this.Redirect(returnUrl); } return this.RedirectToAction("Index", "Home"); } ViewBag.Message= FormattedMessage.GetFormattedMessage("l'utilisateur et /ou le mot passe incorrect.", TypeMessage.Danger, true); return this.View(); } </code></pre> <p>global.asax</p> <pre><code>protected void Application_PostAuthenticateRequest(object sender, EventArgs e) { HttpCookie autoCookie = Request.Cookies[FormsAuthentication.FormsCookieName]; if (autoCookie != null) { FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(autoCookie.Value); Intervenant user = JsonConvert.DeserializeObject&lt;Intervenant&gt;(ticket.UserData/*, new JsonSerializerSettings { PreserveReferencesHandling = PreserveReferencesHandling.Objects }*/); CustomADPrincipal customADPrincipal = new CustomADPrincipal(user); ; HttpContext.Current.User = customADPrincipal; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-08T22:32:04.220", "Id": "453004", "Score": "2", "body": "Welcome to Code Review! I have edited your question to make it more clear. That being said, your question is currently off topic for two reasons. (1) it does not work; This site is only for reviewing working code. (2) you mention that you don't understand how it works; this site requires that you be the owner/maintainer of the code, and understand why it is implemented the way it is. As such I've voted to close as off topic. Please [edit](https://codereview.stackexchange.com/posts/232081/edit) your question once you're able to address these issues." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-08T22:02:30.203", "Id": "232081", "Score": "1", "Tags": [ "security", "authentication", "asp.net-mvc-4" ], "Title": "Decrypting a form always returns the previous authentication ticket values" }
232081
<p>I am making a program that scores a scrabble game and this is the basic version of it. Eventually I am going to add logic for double and triple words and letters but before I get too ahead of myself I would like to improve the basic code here.</p> <p>All suggestions are welcome.</p> <pre><code>def main(): letter_val = {" ": 0, "a": 1, "b": 3, "c": 3, "d": 2, "e": 1, "f": 4, "g": 2, "h": 4, "i": 1, "j": 8, "k": 5, "l": 1, "m": 3, "n": 1, "o": 1, "p": 3, "q": 10, "r": 1, "s": 1, "t": 1, "u": 1, "v": 4, "w": 4, "x": 8, "y": 4, "z": 10} players = [] """ Function to add as many players as there are in the game (uses scrabble rules for limit) """ def add_players(): while True: while len(players) &lt; 4: pla = input("Enter Player Names (can have up to 4) &gt;&gt;&gt; ") if pla: if pla not in (a for i in players for a in i): if len(players) &lt; 4: players.append([pla, 0]) print("Player {} added".format(pla)) else: return else: print("Name already in players' list") else: return else: return def home(undo_ind=False): option = input('Would you like to [A]dd a score, [V]iew scores, [U]ndo the last change, or [End] the game? &gt; ') class Score: def __init__(self): global temp_v, temp_p player = temp_p = input("Enter player to score&gt;&gt;&gt; ") if player in (a for i in players for a in i): try: word = input("Enter word to score&gt;&gt;&gt; ") value = temp_v = sum(letter_val[i.lower()] for i in word) except KeyError: print("Word must consist of letters only.") Score() for i in players: if i[0] == player: i[1] += value else: print("Player entered is not in player list.") home() @staticmethod def undo(): try: for i in players: if i[0] == temp_p: i[1] -= temp_v home(True) except NameError: print("No changes have been made.") home() @staticmethod def view_scores(): for i in players: print("Player %s has a score of %d" % (i[0], i[1])) home(undo_ind) if option.lower() == "a": Score() elif option.lower() == "v": Score.view_scores() elif option.lower() == "u" and undo_ind is False: Score.undo() elif option.lower() == "u" and undo_ind is True: print("No changes have been made.") home(True) elif option.lower() == "end": print("Final scores are:") for i in players: print("Player {} has a final score of {}.".format(i[0], i[1])) else: print("That is not a valid option.") home(undo_ind) add_players() home() if __name__ == "__main__": main() </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-20T06:11:29.460", "Id": "454470", "Score": "0", "body": "Follow up question posted [here](https://codereview.stackexchange.com/q/232673/100620)" } ]
[ { "body": "<p>I apologize that this answer became a \"stream of consciousness\"-type answer. I found it difficult to properly categorize what I wanted to say.</p>\n\n<hr>\n\n<p>There's a fair amount to be said in <code>add_players</code>. The way you have things set up is quite confusing. You have fairly deep nesting, and multiple returns at multiple different levels of nesting.</p>\n\n<p><code>if pla not in (a for i in players for a in i)</code> is also confusing. Think about <code>for i in players</code>. You're referring to each player as <code>i</code>? Also, your intent with that generator expression seems to be to flatten <code>players</code> so you can check if a name already exists. Flattening doesn't seem necessary though since each \"player\" is a name and score. Why check if a name is equal to a score?</p>\n\n<p>You also have a <code>while len(players) &lt; 4</code> inside of a <code>while True</code>. I can't really see the point of the <code>while True</code> though.</p>\n\n<p>I would also use much more descriptive names. Once you reduce the nesting, you'll have a lot more room to work with.</p>\n\n<p>Finally, <code>add_players</code> really shouldn't be adding to a global <code>players</code>. <code>players</code> should be returned from <code>add_players</code> and assigned at the call site.</p>\n\n<p>Altogether, I'd write this closer too:</p>\n\n<pre><code>def add_players():\n players = []\n\n while len(players) &lt; 4:\n new_name = input(\"Enter Player Names (can have up to 4) &gt;&gt;&gt; \")\n\n if new_name:\n if new_name not in (name for name, _ in players):\n players.append([new_name, 0])\n print(\"Player {} added\".format(new_name))\n\n else:\n print(\"Name already in players' list\")\n\n else:\n break\n\n return players\n</code></pre>\n\n<p>Notice now there's a single <code>return</code>, and it's returning the players for the caller to use.</p>\n\n<hr>\n\n<p>Please don't take this the wrong way, but the design of the rest of the program doesn't make much sense:</p>\n\n<ul>\n<li><p>Why is <em>everything</em> inside of <code>main</code>? Ideally, the <code>main</code> function should be a small function at the end of your program that just calls a few other functions.</p></li>\n<li><p>Why is a <code>Score</code> class <em>inside</em> of the <code>home</code> function?</p></li>\n<li><p><code>Score</code> also doesn't seem like it should even be a class. All of the methods of the class are static, and it seems like you're only using <code>Score</code> to score a word by calling the <code>Score</code> constructor. If you never use an instance of a class, it shouldn't be a class. Just make <code>Score</code> into a <code>score_word</code> function. I'd also pass a word into the function instead of asking inside of the function. Functions are harder to test when they produce their own data.</p></li>\n<li><p>You're catching a <code>NameError</code> in <code>undo</code>. I'm guessing this is in case <code>Score()</code> hadn't been called yet? Don't do this. I can't think of a time when it's ever appropriate to catch a <code>NameError</code>. Any time a <code>NameError</code> happens, it means you have flawed logic in your program. You should fix the issue instead of putting an <code>try/except</code> band-aid over it. If the function requires <code>temp_p</code> and <code>temp_v</code> (which need better names), you need to ensure that that data is available. Either pass it in, or ensure that they're properly initialized ahead of time.</p></li>\n</ul>\n\n<hr>\n\n<hr>\n\n<p>There's more that can be dug out here, but I need to start getting ready for work. I'll just make a few broad suggestions:</p>\n\n<ul>\n<li><p>Please take much more care when writing code. A lot of this code seems like it was written quickly without much second-thought. I would focus on the <em>intent</em> of the code before it's written.</p>\n\n<p>Ask yourself, \"What <em>exactly</em> should this code do?\", and \"What are the appropriate tools to do what I'm trying to do?\". Doing things like using classes as normal functions and writing code like <code>(a for i in players for a in i)</code> that <em>technically</em> works (but doesn't really do exactly what you want) makes your code hard to understand, and will make it difficult to add to later.</p></li>\n<li><p>Don't nest everything. Really, all of these functions should be \"top-level\", outside of everything else. If you nest thing <code>A</code> inside of thing <code>B</code>, that suggests that <code>A</code> is deeply connected to <code>B</code> and wouldn't have a valid meaning outside of <code>B</code>. Really though, that's not the case here. <code>Score</code> would have the same meaning even if it were outside of <code>home</code>, and all the functions would have the same meaning even if they were outside of <code>main</code>.</p>\n\n<p>Nesting conveys a certain association meaning, and if used improperly, gives the reader the wrong initial idea about how the code works. Nesting also forces you to use more indentation, which generally makes code harder to read.</p></li>\n</ul>\n\n<p>With the above criticisms out of the way, I'll note what is good here:</p>\n\n<ul>\n<li><p>You're following proper naming guidelines. You have functions starting with lowercase, classes starting with uppercase, and <code>_</code> to separate \"words\" in names. </p></li>\n<li><p>You're using idiomatic shortcuts like <code>if pla:</code> to check if a collection is empty or not.</p></li>\n<li><p>You tried to have all the functionality start from a <code>main</code> instead of being loose in the script. This makes code easier to run and test.</p></li>\n<li><p><code>letter_val</code> is a good use of a dictionary.</p>\n\n<ul>\n<li>I'll note though that it's a constant, <a href=\"https://www.python.org/dev/peps/pep-0008/#constants\" rel=\"nofollow noreferrer\">so it should be in all uppercase</a>.</li>\n</ul></li>\n</ul>\n\n<p>Keep at it. There's a lot to be improved here, but there's promise too.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-11T00:43:21.243", "Id": "453202", "Score": "0", "body": "thank you for all the suggestions, I will revise this code thoroughly and possibly get back with you to see how well you think it was revised." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-11T01:03:23.333", "Id": "453203", "Score": "0", "body": "@pythonier500 No problem. And it would be appropriate to post it as an entirely new review if you're happy with the suggestions here." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-11T01:09:41.227", "Id": "453204", "Score": "0", "body": "Ok, and just one more thing, would `if new_name not in (i[0] for i in players):` work similar to your suggestion?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-11T01:11:40.957", "Id": "453205", "Score": "0", "body": "@pythonier500 Yes, that would be the same in terms of functionality. Note though that `name` is more self-explanatory than `i[0]`. To understand what `i[0]` is, you need to look back in the code to see how `players` is made. `name` immediately tells you what it is though." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-11T01:41:02.463", "Id": "453207", "Score": "0", "body": "Alright thanks again, I have began reworking the code and will hopefully get back in touch after it is finished" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-09T16:58:01.840", "Id": "232109", "ParentId": "232083", "Score": "3" } } ]
{ "AcceptedAnswerId": "232109", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-08T22:56:07.430", "Id": "232083", "Score": "4", "Tags": [ "python", "python-3.x", "game" ], "Title": "Simple Scrabble Game Scorer" }
232083
<p>I created an area of shapes calculator. It's my first python script and I just wanted to get a few tips, thanks in advance!</p> <pre class="lang-py prettyprint-override"><code>#Area of selected polygons and polyhedrons calculator. import sys import math on=0 print("This is an area (or surface area) calculator for selected 2D and 3D shapes, press 0 to start.") start=input() if start=="0": on=1 print("Input 1 to navigate to 2D shapes, 2 to navigate to 3D shapes and q to terminate the program.") elif start=="q": sys.exit() else: print("Error! Command invalid, restart required.") while on==1: oink=input() if oink=="1": print("Enter 2 for any Oval/Circle, 3 for any Triangle, 4 for any convex Quadrilateral, 5 for regular Pentagon, 6 for regular Hexagon and 7 for any other regular 2D polygon.") spoink=input() if spoink=="2": print("You have selected, Oval/Circle, input length of major axis (axes will be equal for a circle.)") majoraxis=float(input()) print("Now, input length of minor axis.") minoraxis=float(input()) print("The area of your Oval/Circle is " + str(math.pi*(minoraxis/2)*(majoraxis/2))+(".")) elif spoink=="3": print("You have selected, Triangle, input height.") TRIHeight=float(input()) print("Input base") TRIBase=float(input()) print("The area of your Triangle is " + str((TRIBase*TRIHeight)/2)+(".")) elif spoink=="4": print("You have selected, Quadrilateral, input length of each of the four sides in A-B-C-D order.") QUA1=float(input()) QUA2=float(input()) QUA3=float(input()) QUA4=float(input()) print("Now, input 2 opposite angles.") QUAAng1=float(input()) QUAAng2=float(input()) s=((QUA1+QUA2+QUA3+QUA4)/2) print("The area of your Quadrilateral is " + str((math.sqrt(((s-QUA1)*(s-QUA2)*(s-QUA3)*(s-QUA4))-(((math.cos(QUA1*QUA2*QUA3*QUA4))*(math.cos(QUA1*QUA2*QUA3*QUA4)))*((QUAAng1+QUAAng2)/2)))))+(".")) elif spoink=="5": print("You have selected, Pentagon, input side length.") PenSidelength=float(input()) print("The area of your Pentagon is " + str(0.25*(math.sqrt(5*(5+(2*math.sqrt(5))))*(PenSidelength**2)))) elif spoink=="6": print("You have selected, Hexagon, input side length.") HexSidelength=float(input()) print("The area of your Hexagon is " + str(((3*math.sqrt(3))*(HexSidelength**2))/2)) elif spoink=="7": print("You have selected, regular Polygon, input numer of sides.") Poln=float(input()) print("Now, input side length") Pols=float(input()) print("The area of your regular Polygon is " + str(Poln*(Pols**2)*(1/math.tan(math.pi/Poln))/4)+(".")) elif spoink=="q": sys.exit() else: print("Error! Input invalid, reenter.") elif oink=="2": print("Enter 8 for Sphere, 9 for Tetrahedron, 10 for Cube/Cuboid, 11 for Octahedron, 12 for Dodecahedron and 13 for Icosahedron.") boink=input() if boink=="8": print("You have selected, Sphere, input radius.") radius=float(input()) print("The surface area of your Sphere is "+str(4*math.pi*(radius**2))+(".")) elif boink=="9": print("You have selected, Tetrahedron, input the edge length.") TETlen=float(input()) print("The surface area of your Tetrahedron is "+str((math.sqrt(3))*(TETlen**2))+(".")) elif boink=="10": print("You have selected, Cube/Cuboid, input the height.") CUBhei=float(input()) print("Now, input the width") CUBwid=float(input()) print("Finally, input the depth") CUBdep=float(input()) print("The surface area of your Cube/Cuboid is "+str(2*(CUBhei*CUBwid+CUBhei*CUBdep+CUBwid*CUBdep))+(".")) elif boink=="11": print("You have selected Octahedron, input side length.") OCTlen=float(input()) print("The surface area of your Octahedron is "+str((2*(OCTlen**2))*(math.sqrt(3)))+(".")) elif boink=="12": print("You have selected Dodecahedron, input side length.") DOClen=float(input()) print("The surface area of your Dodecahedron is "+str(3*(DOClen**2)*(math.sqrt(5*(5+(2*math.sqrt(5))))))+(".")) elif boink=="13": print("You have selected Icosahedron, input side length.") ICOlen=float(input()) print("The surface area of your Icosahedron is "+str(5*(ICOlen**2)*(math.sqrt(3)))+(".")) elif boink=="q": sys.exit() else: print("Error! Input invalid, reenter.") elif oink=="q": sys.exit() else: print("Error! Input invalid, reenter.") </code></pre>
[]
[ { "body": "<ul>\n<li>Whew, first, let's breathe.</li>\n</ul>\n\n<p>Don't you think everything's a bit congested? Let's put in a few newlines in between and add spaces between arithmetic operators.</p>\n\n<p>You have repeated <code>float(input())</code> exactly 22 times! How about we write a function that takes the input for you?</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def float_input():\n return float(input())\n</code></pre>\n\n<p>Now, you can call this function instead of using <code>float(input())</code>!</p>\n\n<ul>\n<li>How about defining some constants next? Even though you can't declare constants in python, we can treat it as such! </li>\n</ul>\n\n<p>For example, we can define <code>PI = math.pi</code> and using it instead of <code>math.pi</code>? The code would look shorter and sweeter. </p>\n\n<ul>\n<li>Next step is to use formatting! </li>\n</ul>\n\n<p><code>\"The area of your Triangle is {}\" + str((TRIBase * TRIHeight) / 2)+(\".\")</code> </p>\n\n<p>Could be changed to </p>\n\n<p><code>f\"The area of your Triangle is {(TRIBase * TRIHeight) / 2}.\"</code></p>\n\n<ul>\n<li>Write functions instead of lengthy formulas to make your code neater </li>\n</ul>\n\n<p>Here's the final code after applying all the points above and making a few more negligible changes!</p>\n\n<pre class=\"lang-py prettyprint-override\"><code># Imports and constants\nimport sys\nfrom math import sqrt, pi\n\nPI = pi\n\nfloat_input = lambda: float(input())\n\n\n# 2d functions\ndef area_of_triangle(height, base):\n return height * base / 2\n\n\ndef area_of_oval(majoraxis, minoraxis):\n return PI * (minoraxis / 2) * (majoraxis / 2)\n\n\ndef area_of_quadrilateral(side_length_list, ang1, ang2):\n s = sum(side_length_list)\n prod = mult = 1\n\n for i in side_length_list:\n prod *= i\n mult *= s - i\n\n return sqrt(mult - (pow(math.cos(prod), 2) * ((ang1 + ang2) / 2)))\n\n\ndef area_of_pentagon(side_length):\n return 0.25 * sqrt(5 * (5 + (2 * sqrt(5)))) * pow(side_length, 2)\n\n\ndef area_of_hexagon(side_length):\n return (3 * sqrt(3)) * (pow(side_length, 2)) / 2\n\n\ndef area_of_polygon(n, s):\n return n * pow(s, 2) * (1 / math.tan(PI / n)) / 4\n\n\n# 3d functions\ndef area_of_sphere(radius):\n return 4 * PI * (radius ** 2)\n\n\ndef area_of_tetrahedron(side_length):\n return pow(side_length, 2) * sqrt(3)\n\n\ndef area_of_cuboid(height, breadth, length):\n return 2 * (height * breadth + height * length + length * breadth)\n\n\ndef area_of_octahedron(side_length):\n return 2 * pow(side_length, 2) * sqrt(3)\n\n\ndef area_of_dodecahedron(side_length):\n return 3 * pow(side_length, 2) * sqrt(5 * (5 + 2 * sqrt(5)))\n\n\ndef area_of_icosahedron(side_length):\n return 5 * pow(side_length, 2) * sqrt(3)\n\n\n# The main function\ndef main():\n while True:\n print(\"This is an area (or surface area) calculator for selected 2D and 3D shapes, press 0 to start.\")\n start = input()\n\n if start == \"0\":\n print(\"Input 1 to navigate to 2D shapes, 2 to navigate to 3D shapes and q to terminate the program.\")\n\n elif start == \"q\":\n sys.exit()\n\n else:\n print(\"Error! Command invalid.\")\n continue\n\n while True:\n oink = input()\n\n if oink == \"1\":\n print(\n \"Enter 2 for any Oval/Circle, 3 for any Triangle, 4 for any convex Quadrilateral, 5 for regular Pentagon, 6 for regular Hexagon and 7 for any other regular 2D polygon.\")\n spoink = input()\n\n if spoink == \"2\":\n print(\n \"You have selected, Oval/Circle, input length of major axis (axes will be equal for a circle.)\")\n majoraxis = float_input()\n\n print(\"Now, input length of minor axis.\")\n minoraxis = float_input()\n\n print(f\"The area of your Oval/Circle is {area_of_oval(majoraxis, minoraxis)}\")\n\n elif spoink == \"3\":\n print(\"You have selected, Triangle, input height.\")\n height = float_input()\n\n print(\"Input base\")\n base = float_input()\n\n print(f\"The area of your Triangle is {area_of_triangle(height, base)}.\")\n\n elif spoink == \"4\":\n print(\"You have selected quadrilateral, input length of each of the four sides in A-B-C-D order.\")\n side_length_list = [float_input() for _ in range(4)]\n\n print(\"Now, input 2 opposite angles.\")\n\n ang1 = float_input()\n ang2 = float_input()\n\n print(f\"The area of your Quadrilateral is {area_of_quadrilateral(side_length_list, ang1, ang2)}\")\n\n elif spoink == \"5\":\n print(\"You have selected, Pentagon, input side length.\")\n side_length = float_input()\n print(f\"The area of your Pentagon is {area_of_pentagon(side_length)}\")\n\n elif spoink == \"6\":\n print(\"You have selected, Hexagon, input side length.\")\n side_length = float_input()\n print(f\"The area of your Hexagon is {area_of_hexagon(side_length)}\")\n\n elif spoink == \"7\":\n print(\"You have selected, regular Polygon, input numer of sides.\")\n n = float_input()\n\n print(\"Now, input side length\")\n s = float_input()\n\n print(f\"The area of your regular Polygon is {area_of_polygon(n, s)}.\")\n\n elif spoink == \"q\":\n sys.exit()\n\n else:\n print(\"Error! Input invalid, reenter.\")\n\n elif oink == \"2\":\n print(\n \"Enter 8 for Sphere, 9 for Tetrahedron, 10 for Cube/Cuboid, 11 for Octahedron, 12 for Dodecahedron and 13 for Icosahedron.\")\n boink = input()\n\n if boink == \"8\":\n print(\"You have selected, Sphere, input radius.\")\n radius = float_input()\n print(f\"The surface area of your Sphere is {area_of_sphere(radius)}.\")\n\n elif boink == \"9\":\n print(\"You have selected, Tetrahedron, input the edge length.\")\n side_length = float_input()\n print(f\"The surface area of your Tetrahedron is {area_of_tetrahedron(side_length)}.\")\n\n elif boink == \"10\":\n print(\"You have selected, Cube/Cuboid, input the height.\")\n height = float_input()\n\n print(\"Now, input the breadth\")\n breadth = float_input()\n\n print(\"Finally, input the length\")\n length = float_input()\n\n print(f\"The surface area of your Cube/Cuboid is {area_of_cuboid(height, breadth, length)}.\")\n\n elif boink == \"11\":\n print(\"You have selected Octahedron, input side length.\")\n side_length = float_input()\n print(f\"The surface area of your Octahedron is {area_of_octahedron(side_length)}.\")\n\n elif boink == \"12\":\n print(\"You have selected Dodecahedron, input side length.\")\n side_length = float_input()\n print(f\"The surface area of your Dodecahedron is {area_of_dodecahedron(side_length)}\")\n\n elif boink == \"13\":\n print(\"You have selected Icosahedron, input side length.\")\n side_length = float_input()\n print(f\"The surface area of your Icosahedron is {area_of_icosahedron(side_length)}\")\n\n elif boink == \"q\":\n sys.exit()\n\n else:\n print(\"Error! Input invalid, reenter.\")\n\n elif oink == \"q\":\n sys.exit()\n\n else:\n print(\"Error! Input invalid, re-enter.\")\n</code></pre>\n\n<p><strong>EDIT:</strong>\nI kept the names <code>onik</code>, <code>spoink</code>, and <code>boink</code> as it is, because I think the pronunciation is so cute!</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-09T14:43:41.880", "Id": "453060", "Score": "1", "body": "You should use `from math import sqrt` instead of using an import and an assignment. Use `from math import pi as PI` to import and rename." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-09T19:10:49.313", "Id": "453090", "Score": "0", "body": "@AJNeufeld Yes, I agree. I've edited my answer as such." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-10T15:48:48.760", "Id": "453166", "Score": "0", "body": "Thanks for the help, alot of this stuff I didn't know existed. If I may ask what is the point of putting everything in a function?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-11T10:36:28.170", "Id": "453231", "Score": "0", "body": "You don't have to repeat the code if you have functions. You could write a function for a formula `a` and call it for all instances you use that formula. For example, you could have a function `area_of_rectangle` and use `height * area_of_rectangle(length, breadth)` to get a cuboid.\n\nAlso, functions make the code intact without formulas laying everywhere around." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-09T09:47:01.757", "Id": "232093", "ParentId": "232084", "Score": "7" } }, { "body": "<p>Tool support suggestions:</p>\n\n<ol>\n<li><a href=\"https://github.com/ambv/black\" rel=\"noreferrer\"><code>black</code></a> can automatically format your code to be more idiomatic. </li>\n<li><a href=\"https://pypi.org/project/isort/\" rel=\"noreferrer\"><code>isort</code></a> can group and sort your imports.</li>\n<li><p><a href=\"https://gitlab.com/pycqa/flake8\" rel=\"noreferrer\"><code>flake8</code></a> with a strict complexity limit can give you more hints to write idiomatic Python:</p>\n\n<pre><code>[flake8]\nmax-complexity = 4\nignore = W503,E203\n</code></pre></li>\n<li><p>I would then recommend validating your <a href=\"https://docs.python.org/3/library/typing.html\" rel=\"noreferrer\">type hints</a> using a strict <a href=\"https://github.com/python/mypy\" rel=\"noreferrer\"><code>mypy</code></a> configuration:</p>\n\n<pre><code>[mypy]\ncheck_untyped_defs = true\ndisallow_any_generics = true\ndisallow_untyped_defs = true\nignore_missing_imports = true\nno_implicit_optional = true\nwarn_redundant_casts = true\nwarn_return_any = true\nwarn_unused_ignores = true\n</code></pre>\n\n<p>This ensures that anyone reading the code (including yourself) understand how it's meant to be called, which is very powerful in terms of modifying and reusing it.</p></li>\n</ol>\n\n<p>Basically the above gives some basic quality assurances which come with several advantages:</p>\n\n<ul>\n<li>Makes the code easier to read for anyone familiar with idiomatic Python.</li>\n<li>Smaller diffs which are easier to review and understand.</li>\n<li>Less risk of misunderstanding semantics.</li>\n</ul>\n\n<p>Specific suggestions, assuming the above are taken care of:</p>\n\n<ol>\n<li>The variable names need some work. <code>on</code>, <code>oink</code> and <code>spoink</code> give a reader absolutely no idea what the variables are used for. <code>spoink</code>, for example, could be <code>shape</code> or even <code>shape_name</code>.</li>\n<li>The various calculations belong in separate functions. The 2D and 3D functions could also be split into two separate files, for clarity.</li>\n<li>A common expectation for shell tools is that they are <em>not</em> interactive unless they absolutely have to be. So shell users would expect your script to take all the parameters it needs (using for example <a href=\"https://docs.python.org/3/library/argparse.html\" rel=\"noreferrer\"><code>argparse</code></a>) to produce an answer <em>non-interactively.</em> I might for example write a script like this to run like <code>./area.py circle 5</code> to calculate the area of a circle of radius 5.</li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-10T05:39:33.997", "Id": "453126", "Score": "0", "body": "I agree with you on all points, but don't you think it's a lot to digest for a beginner? The OP said `It's my first python script`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-10T06:06:01.690", "Id": "453128", "Score": "1", "body": "My approach is basically to give users as much actionable suggestions as I can. It's up to them how deep they want to dig into that. Basically this is the kind of code review I would have wanted to receive at an early stage, to prepare for the reality of production code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-10T15:52:40.843", "Id": "453167", "Score": "0", "body": "Thanks for the help, to clarify for your last point do you mean that I write so the user inputs preset commands with little to no instruction? Without any of the navigation or choice." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-10T18:56:36.873", "Id": "453170", "Score": "0", "body": "Basically, with `argparse` you can set up which arguments the script takes, and it'll add a `--help` option by default which shows what you have configured. So users can still get instruction on how to use it." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-09T09:59:39.593", "Id": "232094", "ParentId": "232084", "Score": "6" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-08T23:09:56.663", "Id": "232084", "Score": "7", "Tags": [ "python", "beginner", "python-3.x" ], "Title": "Area/Surface Area calculator of shapes" }
232084
<p>I am trying to learn <code>Rust</code> and I feel like a dummy every step of the way. </p> <p>I went through the tutorial on making lists in Rust. I am trying to apply the knowledge to implement a simple BST. </p> <p>The code looks pretty horrible though. Any suggestions on how it can be improved?</p> <pre><code>pub struct Tree&lt;T: Ord&gt; { root: Link&lt;T&gt;, } type Link&lt;T&gt; = Option&lt;Box&lt;Node&lt;T&gt;&gt;&gt;; pub struct Node&lt;T:Ord&gt; { elem: T, left: Link&lt;T&gt;, right: Link&lt;T&gt; } impl&lt;T: Ord&gt; Tree&lt;T&gt; { pub fn new() -&gt; Self { Tree {root: None} } pub fn add(&amp;mut self, elem: T) { let mut current; match self.root { None =&gt; { self.root = Some(Box::new(Node{elem: elem, left: None, right: None})); return; }, Some(_) =&gt; { current = self.root.as_mut(); } } loop { if elem &lt; current.as_ref().unwrap().elem { if current.as_ref().unwrap().left.is_none() { current.unwrap().left = Some(Box::new(Node{elem: elem, left: None, right: None})); break; } else { current = current.unwrap().left.as_mut(); } } else { if current.as_ref().unwrap().right.is_none() { current.unwrap().right = Some(Box::new(Node{elem: elem, left: None, right: None})); break; } else { current = current.unwrap().right.as_mut(); } } } } } #[cfg(test)] mod test { use super:: Tree; #[test] fn basics() { let mut tree = Tree::new(); tree.add(5); tree.add(3); tree.add(2); tree.add(4); assert_eq!(tree.root.as_ref().unwrap().elem, 5); assert_eq!(tree.root.as_ref().unwrap().left.as_ref().unwrap().elem, 3); assert_eq!(tree.root.as_ref().unwrap().left.as_ref().unwrap().left.as_ref().unwrap().elem, 2); assert_eq!(tree.root.as_ref().unwrap().left.as_ref().unwrap().right.as_ref().unwrap().elem, 4); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-09T00:27:54.007", "Id": "453017", "Score": "0", "body": "What behavior do you want when the element is already in the tree? Right now it inserts it to the right, but you may want to consider simply stopping when you find an element that's equal to the element you're inserting." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-09T00:35:02.330", "Id": "453019", "Score": "0", "body": "Yeah, that would probably make more sense. However, I am more focused here on Rust specific improvements, not about the BST algorithm behavior." } ]
[ { "body": "<p>There are a few things you can do to reduce repetition in your code. The first would be encapsulating your new <code>Node&lt;T&gt;</code> into a method.</p>\n\n<pre><code>impl&lt;T&gt; Node&lt;T&gt; {\n fn new(elem: T) -&gt; Self {\n Self {\n elem,\n left: None,\n right: None,\n }\n }\n}\n</code></pre>\n\n<p>Then all the constructions of <code>Node</code> in <code>add</code> can be replaced with <code>Node::new(elem)</code>.</p>\n\n<hr>\n\n<p>Another thing that can reduce verbosity is having <code>current</code> be an actual (boxed) node rather than an option. Right now you maintain the invariant that <code>current</code> is the <code>Some</code> variant of an <code>Option&lt;&amp;mut Box&lt;Node&lt;T&gt;&gt;&gt;</code> (<code>Link&lt;T&gt;</code>). By instead keeping the <code>&amp;mut Box&lt;Node&lt;T&gt;&gt;</code>, it'll allow you to reduce the number of <code>unwrap</code>s. Conceptually, this means that we're expressing the invariant using the type system.</p>\n\n<p>For example, to initialize <code>current</code>,</p>\n\n<pre><code>let mut current;\nmatch self.root {\n None =&gt; {\n self.root = Some(Box::new(Node::new(elem)));\n return;\n }\n Some(ref mut node) =&gt; {\n current = node;\n }\n}\n</code></pre>\n\n<p>(matching on <code>Some(ref mut node)</code> makes <code>node</code> a mutable reference - there are some other ways to get the same effect, but this is the clearest).</p>\n\n<p>Having this allows you to change the later blocks to</p>\n\n<pre><code>if elem &lt; current.elem {\n if current.left.is_none() {\n current.left = Some(Box::new(Node::new(elem)));\n break;\n } else {\n current = current.left.as_mut().unwrap();\n }\n}\n</code></pre>\n\n<hr>\n\n<p>My last major suggestion is to use matching to get rid of <em>all</em> the unwrapping. Blocks like</p>\n\n<pre><code>if current.left.is_none() {\n current.left = Some(Box::new(Node::new(elem)));\n break;\n} else {\n current = current.left.as_mut().unwrap();\n}\n</code></pre>\n\n<p>are just the poor man's match statement. They can be replaced by</p>\n\n<pre><code>match current.left {\n None =&gt; {\n current.left = Some(Box::new(Node::new(elem)));\n break;\n }\n Some(ref mut node) =&gt; {\n current = node;\n }\n}\n</code></pre>\n\n<p>(again, <code>ref mut node</code> means we're capturing a mutable reference).</p>\n\n<p>This could more succinctly be expressed using <code>if let</code>.</p>\n\n<pre><code>if let Some(ref mut node) = current.left {\n current = node;\n} else {\n current.left = Some(Box::new(Node::new(elem)));\n break;\n}\n</code></pre>\n\n<hr>\n\n<p>Now for some extra things. First, as I mentioned in the comments, the code as written handles duplicates by placing them to the right. This isn't necessarily what you want, but it's easy to change. The trait <code>Ord</code> provides a <code>cmp</code> method that has three possible outputs: <code>Less</code>, <code>Greater</code> or <code>Equal</code>. By doing a match on the output of <code>cmp</code>, we can handle all three.</p>\n\n<pre><code>match elem.cmp(&amp;current.elem) {\n std::cmp::Ordering::Less =&gt; {\n //...\n }\n std::cmp::Ordering::Equal =&gt; break,\n std::cmp::Ordering::Greater =&gt; {\n //...\n }\n}\n</code></pre>\n\n<p>If you don't want to type out the whole names, you could do <code>use std::cmp::Ordering::*;</code> inside the <code>fn add</code> block (or wherever else, but it's best to keep the scope small).</p>\n\n<hr>\n\n<p>This suggestion would be a pretty major rework of your code, but it leads to a much more elegant solution. As I said before, you maintain the invariant that <code>current</code> is a <code>Some</code> variant. I suggested that you could keep a <code>&amp;mut Box&lt;Node&lt;T&gt;&gt;</code> instead so that the invariant is expressed in the type of <code>current</code>. What you can do instead is not try to keep that invariant at all, but instead check whether current is <code>Some</code> or <code>None</code> at the <em>start</em> of the loop. Then you wouldn't need the initial test on <code>self.root</code>.</p>\n\n<pre><code>fn add(&amp;mut self, elem: T) {\n let mut current = &amp;mut self.root;\n loop {\n match current {\n Some(node) =&gt; {\n // check how elem compares to node.elem\n // assign node.left/right to current as appropriate (or break)\n }\n None =&gt; {\n // set the data behind `current` to a new node.\n // i.e. `*current = ...`\n }\n }\n }\n</code></pre>\n\n<hr>\n\n<p>Finally, just a fairly minor thing. Don't forget to run <code>cargo fmt</code> and <code>cargo clippy</code>. <code>cargo fmt</code> will make your code more readable to other Rust programmers and keep things in a consistent style. <code>cargo clippy</code> will give you a few helpful tips for making your code more idiomatic and sometimes help avoid logic errors.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-09T02:30:28.467", "Id": "453020", "Score": "0", "body": "This is awesome response, thanks a lot for spending time to give me all this advice" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-09T02:25:14.327", "Id": "232086", "ParentId": "232085", "Score": "4" } } ]
{ "AcceptedAnswerId": "232086", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-08T23:34:29.623", "Id": "232085", "Score": "3", "Tags": [ "tree", "rust" ], "Title": "Simple tree addition implementation" }
232085
<p>I have a function that accepts a range as an input. It works fine when I supply the function with a range like a1:a5, but not when I use an entire column like a:a.</p> <p>I could always loop over the whole column (ie. a:a) but that is so slow.</p> <p>Here is a simple example.</p> <pre><code>Function r_sum(r1 As Range) As Long For Each c In r1.Cells r_sum = r_sum + c.Value Next c End Function </code></pre> <p>How can I supply my functions with ranges (ie. a:a or 2:2, entire columns or rows) and have the function execute efficiently? How do excel's worksheet functions do it so well?</p> <p>The method I used above (ie. looping over every cell in the range) is so slow that I can't possibly imagine using such a technique, especially since many of the functions I have currently are complex and will crash the program. </p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-09T19:23:45.690", "Id": "453093", "Score": "0", "body": "Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*." } ]
[ { "body": "<p>What you have there is equivalent to <code>=SUM(A:A)</code> - which runs much faster as a native Excel function. Always use Native Excel in Excel itself before resorting to VBA.</p>\n\n<p>As a general note: if you are going to do something bespoke - convert the range to an array and work with the array. This has a significant performance improvement for a number of reasons which have been explained many times on this site. The key ones are that you are not switching between the Excel model and the VBA model each loop and that you can work with data types instead of objects.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-09T18:38:12.770", "Id": "453087", "Score": "0", "body": "I am aware of the existence of the sum function. The point was to show a very simple function that was easy to follow and would demonstrate how I would use a full column range as an argument. But converting the range to an array made the calculation a lot faster." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-09T18:47:28.057", "Id": "453088", "Score": "0", "body": "I revised the code of the function to convert the range to an array and use the array instead. In terms of performance, is this the best move I can make?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-10T00:04:40.427", "Id": "453114", "Score": "0", "body": "@dactyrafficle yes it is. And you should iterate arrays with a `For...Next` loop, too; `For Each...Next` works best with object collections, and incurs a serious performance penalty with arrays." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-09T06:20:12.303", "Id": "232089", "ParentId": "232088", "Score": "4" } }, { "body": "<p>On the advice of AJD I've made some changes to the initial code from my question, which I think constitutes an answer.</p>\n\n<p>The main issue with the code in the original post is working with the input range. But by storing the range's data as an array, the function performs much more quickly.</p>\n\n<pre><code>Function r_sum(r1 As Range) As Long\n\n Dim arr As Variant\n arr = r1.Value\n\n For Each a In arr\n r_sum = r_sum + a\n Next a\n\nEnd Function\n</code></pre>\n\n<p>In this way, I can supply my functions with an entire column or row range (or even multiple) and expect that the function will perform its calculations quickly enough for me to use them.</p>\n\n<p>That is basically what I was hoping for, and so I consider my question answered.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-10T04:39:26.377", "Id": "453123", "Score": "1", "body": "The normal protocol here is to select the most appropriate/useful answer for your needs and mark is as 'accepted' (the tick on the side). This then tells other viewers that the question has an accepted answer which is useful for the long-term exposure and curation of posts. Cheers." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-09T20:17:09.577", "Id": "232120", "ParentId": "232088", "Score": "2" } }, { "body": "<p>Using the Intersect method to trim off cells not in the Worksheet's UsedRange will greatly improve performance.</p>\n\n<pre><code> Function SumRange(Target As Range) As Double\n Dim result As Double\n Dim Cell As Range\n Set Target = Intersect(Target.Parent.UsedRange, Target)\n If Not Target Is Nothing Then\n For Each Cell In Target.Cells\n result = result + Cell.Value\n Next\n End If\n SumRange = result\nEnd Function\n</code></pre>\n\n<p>For maximum performance you should trim the target range and then load the values into an array.</p>\n\n<pre><code>Function SumRange(Target As Range) As Double\n Dim result As Double\n Dim values As Variant\n Dim item As Variant\n Set Target = Intersect(Target.Parent.UsedRange, Target)\n If Not Target Is Nothing Then\n values = Target.Value\n For Each item In values\n result = result + item\n Next\n End If\n SumRange = result\nEnd Function\n</code></pre>\n\n<p>It is a best practice <code>Option Explicit</code> to the top of the code module to ensure that you declare all your variables. This will help the compiler catch syntax and datatype errors.</p>\n\n<p>Avoid using underscores in you method names as the VBA uses them to indicate events.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-09T22:06:52.050", "Id": "453105", "Score": "0", "body": "this is really interesting. most of my sheets are in the <10000 rows area, so what you suggested is so relevant. I just ran a simulation. I generated random values in column A between rows 0-2000, and ran a sub routine executing first my revised function (range->arr), against one using your tip (intersect + range->arr) and the second was over 1000 times faster." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-09T21:12:34.433", "Id": "232124", "ParentId": "232088", "Score": "3" } } ]
{ "AcceptedAnswerId": "232124", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-09T04:54:07.570", "Id": "232088", "Score": "2", "Tags": [ "vba", "excel" ], "Title": "excel vba udf: entire column as fn parameter" }
232088
<p>Im trying to think of the most efficient way to structure an in memory leader board with the ability to read a specific rank quickly. Im talking about very micro optimisations as either way it will still be fast.</p> <pre><code>class Leaderboard { constructor() { this.leaderboard = []; } insert(name, score) { const player = new Player(name, score, new Date()); this.leaderboard.push(player); this.leaderboard.sort((a, b) =&gt; a.score - b.score); } getRank(rank) { if (isNaN(rank) || rank &lt; 1 || rank &gt; this.leaderboard.length) return null; return this.leaderboard[rank - 1]; } } class Player { constructor(name, score, date) { this.name = name; this.score = score; this.date = date; } } const leaderboard = new Leaderboard(); leaderboard.insert('john', 36); leaderboard.insert('pete', 23); leaderboard.insert('dave', 56); console.log(leaderboard.getRank(2)); </code></pre> <p>This is what I have come up with, any feedback is great and any small optimisations or completely different and better ways are welcome, thankyou</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-09T11:35:50.267", "Id": "453035", "Score": "0", "body": "Can you show a bit more about how it is used in a real context please?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-09T11:46:49.260", "Id": "453036", "Score": "0", "body": "Lets say its an api and the client sends the players name and score. (i know score shouldnt be on the client but its just an example)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-09T11:49:05.687", "Id": "453037", "Score": "0", "body": "We're usually not so happy to review hypothetical stub code without practical context here. I am going to close vote now, let's see how it develops." } ]
[ { "body": "<p>Your implementation depends on <code>this.leaderboard.sort((a, b) =&gt; a.score - b.score);</code>. Each and every time you insert, you sort again.</p>\n\n<p>Depending on your access pattern, you could defer the sorting from <em>adding</em> to <em>reading</em>.</p>\n\n<p>You could operate with a dictionary keeping the scores unorderd which makes inserting fast. And sort the entries only in case if you read them.</p>\n\n<p><em>For the sake of the example I used plain numbers</em></p>\n\n<pre><code>let leaderboard = {\n}\n\nconst addScore = (board, score) =&gt; {\n if(!board[score]) board[score] = []\n board[score].push(score)\n return board;\n}\n\nconst getcurrentRanks = (board) =&gt; {\n const scoreranks = Object.keys(board).sort((a,b)=&gt;b-a)\n return scoreranks.reduce((o,n )=&gt;{\n return o.concat(board[n]);\n }, []);\n}\n</code></pre>\n\n<p>But this has the downside of converging to your first implementation the more you read; e.g. for each time you insert a value you want to get all the ranks.</p>\n\n<p>Otherwise I would encourage you to look into <a href=\"https://en.wikipedia.org/wiki/Priority_queue\" rel=\"nofollow noreferrer\">priority queues</a>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-09T15:31:46.247", "Id": "453066", "Score": "0", "body": "Thankyou very much for this Thomas, Do you think some sort of hash table would be better for this?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-09T15:53:52.620", "Id": "453069", "Score": "0", "body": "The answer is like above: _it depends_ on your data. In general: no." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-09T14:42:39.203", "Id": "232101", "ParentId": "232095", "Score": "1" } }, { "body": "<p><strong><em>Tips and hints ...</em></strong></p>\n\n<p><em>Namings</em>:</p>\n\n<ul>\n<li><p><code>leaderboard</code> as <code>Leaderboard</code> class property could have a more straightforward and comprehensive name - <code>this.players</code> (as collection of <code>Player</code> instances)</p></li>\n<li><p><code>getRank</code> function may be perceived as the one that returns <em>rank</em>. <br>In real, it returns a <code>Player</code> instance for a specified <code>rank</code>. Thus, it's better named as <code>getByRank</code></p></li>\n</ul>\n\n<p><em>Design</em>:</p>\n\n<ul>\n<li><p>In terms of good design <code>Leaderboard</code> class should not be responsible for generating a new player with <code>new Player(name, score, new Date())</code>.<br>\n<code>insert</code> method would optimally accept <code>Player</code> instance as a single argument.<br>In other cases - <code>Player</code> instances could be generated via supplement factory like <code>PlayerFactory</code> class</p></li>\n<li><p>considering that <code>this.players</code> is an internal collection of <em>players</em>, a good idea is to prevent a mutation of it from the outer/client scope.<br>At least, you could stick to internal convention and named it as \"protected\" property <strong><code>this._players = []</code></strong> with further adding <strong><code>get</code></strong> accessor (used in \"strict\" mode):</p>\n\n<pre><code>get players() {\n return [...this._players];\n}\n</code></pre>\n\n<p>that will return a <strong>copy</strong> of <em>protected</em> collection to a client.</p></li>\n</ul>\n\n<hr>\n\n<p>New version:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>\"use strict\";\n\nclass Leaderboard\n{\n constructor()\n {\n this._players = [];\n }\n \n get players() {\n return [...this._players];\n }\n\n insert(player)\n {\n this._players.push(player);\n this._players.sort((a, b) =&gt; a.score - b.score);\n }\n\n getByRank(rank)\n {\n if (isNaN(rank) || rank &lt; 1 || rank &gt; this._players.length) return null;\n return this._players[rank - 1];\n }\n}\n\nclass Player\n{\n constructor(name, score, date)\n {\n this.name = name;\n this.score = score;\n this.date = date;\n }\n}\n\nconst leaderboard = new Leaderboard();\n\nleaderboard.insert(new Player('john', 36, new Date()));\nleaderboard.insert(new Player('pete', 23, new Date()));\nleaderboard.insert(new Player('dave', 56, new Date()));\n\nconsole.log(leaderboard.getByRank(2));</code></pre>\r\n</div>\r\n</div>\r\n</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-09T15:31:28.583", "Id": "453064", "Score": "0", "body": "Thankyou very much for this, Do you think some sort of hash table would be better for this?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-09T14:52:44.503", "Id": "232102", "ParentId": "232095", "Score": "1" } } ]
{ "AcceptedAnswerId": "232102", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-09T10:49:51.107", "Id": "232095", "Score": "2", "Tags": [ "javascript" ], "Title": "Making a simple leader board in memory" }
232095
<p>I'm working on a method to rotate <code>System.Enum</code> values that have the <code>[System.Flag]</code> attribute set. I've tried to think of cases where there is no work to do (set to <code>enumVar.ALL</code> or <code>enumVar.NONE</code> where no rotation can occur, or when a request is made to rotate 0 positions).</p> <p>The whole of it can be seen <a href="https://dotnetfiddle.net/Zdjjfg" rel="nofollow noreferrer">here</a>.</p> <p>For me, the biggest issues are:</p> <ol> <li><p>I haven't done much with bit shifting, and while I understand it conceptually, I have no practical experience. I was using shifting code like <code>inEnum &gt;&gt; positions | inEnum &lt;&lt; ~positions &lt;&lt; 1</code>, which worked great unless it had to roll back (going beyond the maximum value and moving a bit back to the beginning, or vice versa). The method used now works fine, but requires arithmetic rather than solely bit shifting. Obviously the performance hit is virtually non-existent unless this was being run an incredible number of times, but I'd like to understand if there's a way to make it work with just bit shifting.</p></li> <li><p>It seems kludgy, how I'm going about using the generic <code>TEnum</code> in the rotation code itself. <code>(TEnum)(object)(((int)(object)inEnum &lt;&lt; positions | (int)(object)inEnum &gt;&gt; (maxRotation - positions)) &amp; allValuesMask)</code> is quite a handful, but boxing/unboxing and casting were the only thing I could get to work with the generic. I'm looking to understand a cleaner way to do this sort of code, either a methodology I’m not familiar with, or less mangling to achieve the same result.</p></li> </ol> <p>Entire code:</p> <pre><code>using System; using System.Collections.Generic; using System.Linq; using System.Reflection; // Requires C# 7.3 or later (Roslyn 3.0 or later) for where TEnum : System.Enum public class Program { public static void Main() { CompassDirections dirs = CompassDirections.NORTH | CompassDirections.SOUTHEAST; #region Test functionality Console.WriteLine("Valid directions are: {0}\n", dirs); // Rotation as a standard method dirs = Rotate(dirs, 2); Console.WriteLine("Updated directions are: {0}\n", dirs); // Rotation as an extension method to TEnum dirs.Rotate(6); Console.WriteLine("Updated directions are: {0}\n", dirs); #endregion } // Standard method public static TEnum Rotate&lt;TEnum&gt;(TEnum inEnum, int positions = 1) where TEnum : System.Enum { if (positions == 0) { Console.WriteLine("Rotate&lt;TEnum&gt;() called to rotate 0 positions. No rotation will occur."); return inEnum; } // Currently doesn't support any underlying enum type but int if (Enum.GetUnderlyingType(inEnum.GetType()) != typeof(int)) throw new NotSupportedException("This method, Rotate&lt;TEnum&gt;(), is only valud on integer underlying types. The System,Enum '" + inEnum.GetType().Name + "' does not use such an underlying value."); if (!typeof(TEnum).GetCustomAttributes&lt;FlagsAttribute&gt;().Any()) throw new NotSupportedException("This method, Rotate&lt;TEnum&gt;(), is only valid for enums that have the [System.Flags] attribute set. The System.Enum '" + inEnum.GetType().Name + "' does not use that attribute."); /* WIP for supporting other underlying types Type t = Enum.GetUnderlyingType(inEnum.GetType()); List&lt;object&gt; values = new List&lt;object&gt;((object[])Enum.GetValues(inEnum.GetType())); var listType = typeof(List&lt;&gt;).MakeGenericType(t); */ List&lt;int&gt; values = new List&lt;int&gt;((int[])Enum.GetValues(inEnum.GetType())); if (values.Any(a =&gt; a &lt; 0)) throw new NotSupportedException("This method, Rotate&lt;TEnum&gt;(), is only valid for enums that contain no negative integer values. The System.Enum '" + inEnum.GetType().Name + "' includes negative values."); if (((int)(object)inEnum ^ 0) == 0) { Console.WriteLine("Rotate&lt;TEnum&gt;() called to rotate an enum that is set to 'NONE = 0'. No rotation will occur."); return inEnum; } int allValuesMask = values.Max(); if (((int)(object)inEnum ^ allValuesMask) == 0) { Console.WriteLine("Rotate&lt;TEnum&gt;() called to rotate an enum that is set to 'ALL', 'OMNI', or a similar status including all flags. No rotation will occur."); return inEnum; } // Remove 0/NONE and OMNI/ALL values.Remove(0); values.Remove(values.Max()); if (positions % values.Count == 0) { Console.WriteLine("Rotate&lt;ENum&gt;() called with perfect roundness positions % possiblePositions == 0. No rotation will occur."); return inEnum; } int maxRotation = Convert.ToString(values.Max(), 2).Length; while (Math.Abs(positions) &gt; maxRotation) { if (positions &gt; 0) positions -= maxRotation; else positions += maxRotation; } if (positions &gt; 0) { return (TEnum)(object)(((int)(object)inEnum &lt;&lt; positions | (int)(object)inEnum &gt;&gt; (maxRotation - positions)) &amp; allValuesMask); } else if (positions &lt; 0) { positions = Math.Abs(positions); return (TEnum)(object)(((int)(object)inEnum &gt;&gt; positions | (int)(object)inEnum &lt;&lt; (maxRotation - positions)) &amp; allValuesMask); } Console.WriteLine("Rotate&lt;TEnum&gt;() Unable to rotate - unknown condition."); return inEnum; } } public static class EnumExtensions { // Extension of TEnum public static void Rotate&lt;TEnum&gt;(this ref TEnum inEnum, int positions = 1) where TEnum : struct, System.Enum { if (positions == 0) { Console.WriteLine("Rotate&lt;TEnum&gt;() called to rotate 0 positions. No rotation will occur."); return; } // Currently doesn't support any underlying enum type but int if (Enum.GetUnderlyingType(inEnum.GetType()) != typeof(int)) throw new NotSupportedException("This method, Rotate&lt;TEnum&gt;(), is only valud on integer underlying types. The System,Enum '" + inEnum.GetType().Name + "' does not use such an underlying value."); if (!typeof(TEnum).GetCustomAttributes&lt;FlagsAttribute&gt;().Any()) throw new NotSupportedException("This method, Rotate&lt;TEnum&gt;(), is only valid for enums that have the [System.Flags] attribute set. The System.Enum '" + inEnum.GetType().Name + "' does not use that attribute."); List&lt;int&gt; values = new List&lt;int&gt;((int[])Enum.GetValues(inEnum.GetType())); if (values.Any(a =&gt; a &lt; 0)) throw new NotSupportedException("This method, Rotate&lt;TEnum&gt;(), is only valid for enums that contain no negative integer values. The System.Enum '" + inEnum.GetType().Name + "' includes negative values."); if (((int)(object)inEnum ^ 0) == 0) { Console.WriteLine("Rotate&lt;TEnum&gt;() called to rotate an enum that is set to 'NONE = 0'. No rotation will occur."); return; } int allValuesMask = values.Max(); if (((int)(object)inEnum ^ allValuesMask) == 0) { Console.WriteLine("Rotate&lt;TEnum&gt;() called to rotate an enum that is set to 'ALL', 'OMNI', or a similar status including all flags. No rotation will occur."); return; } // Remove 0/NONE and OMNI/ALL values.Remove(0); values.Remove(values.Max()); if (positions % values.Count == 0) { Console.WriteLine("Rotate&lt;ENum&gt;() called with perfect roundness positions % possiblePositions == 0. No rotation will occur."); return; } int maxRotation = Convert.ToString(values.Max(), 2).Length; while (Math.Abs(positions) &gt; maxRotation) { if (positions &gt; 0) positions -= maxRotation; else positions += maxRotation; } if (positions &gt; 0) { inEnum = (TEnum)(object)(((int)(object)inEnum &lt;&lt; positions | (int)(object)inEnum &gt;&gt; (maxRotation - positions)) &amp; allValuesMask); return; } else if (positions &lt; 0) { positions = Math.Abs(positions); inEnum = (TEnum)(object)(((int)(object)inEnum &gt;&gt; positions | (int)(object)inEnum &lt;&lt; (maxRotation - positions)) &amp; allValuesMask); return; } Console.WriteLine("Rotate&lt;TEnum&gt;() Unable to rotate - unknown condition."); return; } } [System.Flags] public enum CompassDirections { NONE = 0, NORTH = 1 &lt;&lt; 0, NORTHEAST = 1 &lt;&lt; 1, EAST = 1 &lt;&lt; 2, SOUTHEAST = 1 &lt;&lt; 3, SOUTH = 1 &lt;&lt; 4, SOUTHWEST = 1 &lt;&lt; 5, WEST = 1 &lt;&lt; 6, NORTHWEST = 1 &lt;&lt; 7, OMNI = ~(~0 &lt;&lt; 8) } </code></pre> <p>Output:</p> <pre class="lang-none prettyprint-override"><code>Valid directions are: NORTH, SOUTHEAST Updated directions are: EAST, SOUTHWEST Updated directions are: NORTH, SOUTHEAST </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-09T14:03:44.820", "Id": "453052", "Score": "4", "body": "Could you add example code that explains how the method works?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-09T14:30:58.183", "Id": "453056", "Score": "0", "body": "@JanDotNet - the fiddle has a simple use case I've used for testing. I didn't want to push a bunch of additional code into the post, but if that's the norm I certainly can. Didn't want folk to see the Wall of Code and ignore it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-09T14:33:07.850", "Id": "453057", "Score": "2", "body": "It would be best to include the entire class, and any unit test code for the class." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-09T14:38:44.660", "Id": "453059", "Score": "1", "body": "Ok, I've added the entire class, enum, and simple use-case." } ]
[ { "body": "<p>First of all, I like it that you thought about all edge cases that may occur and handle that cases!</p>\n\n<p>However, the result is a complicated method where lots of inputs can not be handled (which must be known by the user of the method - IMHO it is a kind of Liskov violation). At that point, you might ask yourself if an enum is the right data structure for representing your business use case.</p>\n\n<p>I know it's not a code review but maybe helpful anyway ;).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-09T14:35:30.260", "Id": "453058", "Score": "1", "body": "Thank you - my day job is in software QA, so edge cases are just how I think through problems lol. I get that many inputs cannot be handled, though NotSupportedExceptions exist for that reason, right? I plan to flesh it out so that other enum types will be valid, but for my current use case it works. Enum is ideal for me for two reasons: No overhead of an additional class to provide and work with the data, just a method; and readability in the code that utilizes the enums. I considered a custom class that basically contained only valid types and supporting methods, but it was unwieldy. :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-09T14:44:06.797", "Id": "453061", "Score": "0", "body": "Just a note, given strictly the compass directions as an example here, it also allows variation simply by updating the enum. I could get rid of ordinal directions and it would still work. Or I could add subordinal directions (NNE, ENE, ESE, SSE, SSW, WSW, WNW, NNW) and it would function as well." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-09T14:20:27.040", "Id": "232100", "ParentId": "232098", "Score": "5" } }, { "body": "<h2>Complexity</h2>\n<p>The function <code>Rotate()</code> is too complex (does too much). There is 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>Another reason to keep functions simple is that they are easier to write, debug, read, and maintain. As a suggestion, all the error checking can be moved into another function that <code>Rotate</code> calls, leave only the rotation portion in the <code>Rotate</code> function itself.</p>\n<h2>Be Consistent with the <code>if</code> Statements</h2>\n<p>This is partially about style, but also about maintainability. The <code>if</code> statements that contain <code>throw</code> statements do not have blocks of code, but most of the other <code>if</code> statements do. As time goes on code needs to be maintained, many times a bug fix may be a simple insertion of a new statement, it is easier to maintain the code if the <code>if</code> and <code>else</code> statements have blocks of code even if only a single statement is within the block. This is also true for loops.</p>\n<h2>Debug Code and Unused Code</h2>\n<p>The code contains this comment block:</p>\n<pre><code> /* WIP for supporting other underlying types\n Type t = Enum.GetUnderlyingType(inEnum.GetType());\n List&lt;object&gt; values = new List&lt;object&gt;((object[])Enum.GetValues(inEnum.GetType()));\n var listType = typeof(List&lt;&gt;).MakeGenericType(t);\n */\n</code></pre>\n<p>When posting code for review, it is better remove unused code and put debug code into</p>\n<pre><code>#if DEBUG\n...\n#endif // DEBUG\n</code></pre>\n<p>This makes it easier to review the code. Features that haven't been implemented are not meant for code reviews. Removing unused code makes the remaining code easier to read, debug and modify.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-09T16:20:36.357", "Id": "453074", "Score": "0", "body": "I’m not really sure how this violates SRP, given that the only function it performs is rotation." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-09T16:24:00.177", "Id": "453075", "Score": "0", "body": "@JesseWilliams It is performing error checking as well as rotation, as I said move the error checking into it's own function, call that function from rotate. The error checking may be valid in other functions if features are added to the program. Generally any function that doesn't fit in a screen is way too complex and probably doesn't follow SRP. In this case there is a clear violation of SRP." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-09T16:36:22.310", "Id": "453077", "Score": "0", "body": "Ok - thanks. Any thoughts regarding the two questions I had?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-09T17:06:38.563", "Id": "453078", "Score": "0", "body": "@JesseWilliams I might have used the enumType with dictionaries to achieve the same result." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-09T16:13:27.590", "Id": "232107", "ParentId": "232098", "Score": "1" } }, { "body": "<pre><code>int allValuesMask = values.Max();\n</code></pre>\n\n<p>You probably shouldn't assume that the enum has an explicit flag set for \"all of the above\". It's actually somewhat counter-intuitive to do that, since the enum are flags. If you want to collect all possible bit-flags, you could instead aggregate over all values in the enum:</p>\n\n<pre><code>int allValuesMask = values.Aggregate((element, aggregate) =&gt; element | aggregate);\n</code></pre>\n\n<p>The same goes for this bit of code:</p>\n\n<pre><code> // Remove 0/NONE and OMNI/ALL\n values.Remove(0);\n values.Remove(values.Max());\n</code></pre>\n\n<p>There's no explicit (documented) guarantee that <code>values.Max()</code> will set all flags, so removing it is dangerous.</p>\n\n<hr>\n\n<pre><code>(int)(object)inEnum\n</code></pre>\n\n<p>Boxing structs to and from objects is relatively expensive. Since you're doing this multiple times in your code, consider making a local variable.</p>\n\n<hr>\n\n<pre><code>int maxRotation = Convert.ToString(values.Max(), 2).Length;\n</code></pre>\n\n<p>This is kind of a hacky roundabout way of figuring out the amount of bits in <code>values.Max()</code>. If you're adamant on doing it like this, add a comment on what the line is supposed to accomplish.</p>\n\n<p>Other options of figuring this out is calculating <span class=\"math-container\">\\$\\lceil \\log_2x\\rceil\\$</span>:</p>\n\n<pre><code>int maxRotation = (int)Math.Ceiling(Math.Log(values.Max()) / Math.Log(2));\n</code></pre>\n\n<p>Or repeated right-shifting and comparing against 0. Any of these solutions should be in its own method, with proper name to document its purpose:</p>\n\n<pre><code>private static int NumberOfBits(int number) {\n if(number &lt; 0) {\n throw new ArgumentOutOfRangeException();\n }\n\n var counter = 0;\n while(number != 0) {\n counter++;\n number &gt;&gt;= 1;\n }\n return counter;\n}\n</code></pre>\n\n<p>Or </p>\n\n<pre><code>private static int NumberOfBits(int number) {\n if(number &lt; 0) {\n throw new ArgumentOutOfRangeException();\n }\n return (int)Math.Ceiling(Math.Log(number) / Math.Log(2));\n}\n</code></pre>\n\n<hr>\n\n<pre><code> while (Math.Abs(positions) &gt; maxRotation)\n {\n if (positions &gt; 0)\n positions -= maxRotation;\n else\n positions += maxRotation;\n }\n</code></pre>\n\n<p>This can be replaced with:</p>\n\n<pre><code>positions %= maxRotation;\n</code></pre>\n\n<hr>\n\n<p>Is there a difference between the two implementations you provided? Those should probably be one (private) method with two public overloads.</p>\n\n<hr>\n\n<p>Is there a specific reason you implemented the extension method as taking in a <code>ref</code> argument? It's counterintuitive, since we try to keep structs as immutable as possible. Even worse is that while generally in method calls the <code>ref</code> addition makes it really explicit that a parameter is called as ref, that's not visible here:</p>\n\n<pre><code>Rotate(ref compass, 5); // We can see that compass is added as ref, so we can expect it to be mutated.\ncompass.Rotate(5); // We can't see it here.\n</code></pre>\n\n<p>I know of no system library extension methods that modify their <code>this</code> argument in place. Look at <code>Linq</code> for example. Each of these returns their result. It might be beneficial to adhere to this expected behaviour.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-12T16:01:32.623", "Id": "453433", "Score": "0", "body": "Ah, a lot of good notes here - thank you @JAD. Especially, as simple as it is, the assumption that there'd be an ALL. Thank you - will definitely work through these a bit. As for the two implementations, it was just an exercise to see how they both worked. Chances are that the extension method will not survive, but it was something worth exploring." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-12T16:15:32.453", "Id": "453436", "Score": "1", "body": "@JesseWilliams the idea of an extension method is fine IMO, but don't make it `ref` :)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-11T09:12:50.590", "Id": "232174", "ParentId": "232098", "Score": "1" } } ]
{ "AcceptedAnswerId": "232174", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-09T13:18:02.463", "Id": "232098", "Score": "3", "Tags": [ "c#" ], "Title": "Method for rotating [Flags] Enums" }
232098
<p>This code extract data from generic mailbox mapped by MS Outlook I failed at recursive iteration in subfolders, so it stays as iterative one. Added ASCII encoding to deal with crazy national symbols in body/subjects. My main target is to ensure scalablity and prevent it being slow (iteration over 100 generic mailboxes)</p> <pre><code>import numpy as np import pyautogui as pg import time import datetime outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI") mailboxNamesList=['Generic_Mailbox'] #test input #mailboxName = pg.prompt('please input mailbox name and press enter', 'mailbox name') #main(mailboxName) start = time.time() date = datetime.date.today() - datetime.timedelta(days=30) class Calc(): def itemLoop(iterator, folderName, msg): arrFolder= [] iRow = 1 for iterator in msg: if iterator.Class == 43: mailDate=str(iterator.ReceivedTime)[0:10] mailDate=datetime.datetime.strptime(mailDate, '%Y-%m-%d').date() if date&lt;mailDate: line= [iRow] body=str(iterator.Body)[0:100].replace('\n', '').replace('\r', '').replace('\t', ''). replace(',', ' ') body=body.encode(encoding='ascii',errors='replace') line.append(folderName) line.append(str(iterator.SenderEmailAddress).encode(encoding='ascii',errors='replace')) line.append(str(iterator.Subject).encode(encoding='ascii',errors='replace')) line.append(str(iterator.ReceivedTime)) line.append(Calc.action(iterator)) line.append(body) line.append(iterator.Importance) line.append(iterator.Sensitivity) line.append(iterator.UnRead) line.append(iterator.Categories.replace(',', ';')) line.append(Calc.autoreply(iterator)) line.append(iterator.OutlookVersion) arrFolder.append(line) iRow +=1 npFolder=np.asarray(arrFolder) return(npFolder) def action(iterator): actionCode=iterator.PropertyAccessor.GetProperty("http://schemas.microsoft.com/mapi/proptag/0x10810003") if actionCode==102: actionDone="replied" if actionCode==103: actionDone="replied to all" if actionCode==104: actionDone="forwarded" if actionCode==0: actionDone="no action taken" return(actionDone) def autoreply(iterator): subject=str(iterator.Subject).encode(encoding='UTF-8',errors='replace').strip() ifAuto='No' autoList=['Auto', 'b"Auto', 'Out of Office', 'b"Out of Office'] for phrase in autoList: try: if subject[len(phrase)]==phrase: ifAuto='Yes' #move! except: pass return(ifAuto) def main(mailboxName): folder = outlook.Folders.Item(str(mailboxName)) inbox = folder.Folders.Item("Inbox") msg = inbox.Items arrMailbox=np.array([['index','Folder','SenderEmailAddress', 'Subject', 'ReceivedTime', 'Action taken', 'Body', 'Importance', 'Sensitivity', 'Not readed', 'Categories', 'Autoreply', 'OutlookVersion']]) for i in folder.Folders: if str(i)=='Inbox': box = folder.Folders.Item(str(i)) msg = box.Items print(str(i)+": "+str(len(msg))) arrFolder=Calc.itemLoop(i, 'inbox', msg) arrMailbox = np.concatenate((arrMailbox, arrFolder)) for j in i.Folders: subFolder=i.Folders box = subFolder.Item(str(j)) msg = box.Items print(str(j)+": "+str(len(msg))) arrFolder=Calc.itemLoop(j, box, msg) if arrFolder.size!=0: arrMailbox = np.concatenate((arrMailbox, arrFolder)) try: for k in j.Folders: subFolder=j.Folders box = subFolder.Item(str(k)) msg = box.Items if msg != None: print(str(k)+": "+str(len(msg))) arrFolder=Calc.itemLoop(k, box, msg) if arrFolder.size!=0: arrMailbox = np.concatenate((arrMailbox, arrFolder)) try: for l in k.Folders: subFolder=k.Folders print(str(l)+": "+str(len(msg))) arrFolder=Calc.itemLoop(l, box, msg) if arrFolder.size!=0: arrMailbox = np.concatenate((arrMailbox, arrFolder)) except: pass except: try: for l in k.Folders: subFolder=k.Folders print(str(l)+": "+str(len(msg))) arrFolder=Calc.itemLoop(l, box, msg) if arrFolder.size!=0: arrMailbox = np.concatenate((arrMailbox, arrFolder)) except: pass if str(i)=='Junk E-Mail' or str(i) == 'Deleted Items' or str(i) == 'Sent Items' : box = folder.Folders.Item(str(i)) msg = box.Items print(str(i)+": "+str(len(msg))) arrFolder=Calc.itemLoop(i, str(i), msg) if arrFolder.size!=0: arrMailbox = np.concatenate((arrMailbox, arrFolder)) np.savetxt(str(mailboxName)+'_'+ str(datetime.date.today()) +'.csv', arrMailbox, delimiter=',', fmt='%s') for i in mailboxNamesList: main(i) end = time.time() pg.alert(text=(str(end - start) + ' seconds'), title='DONE', button='PERFECT') <span class="math-container">```</span> </code></pre>
[]
[ { "body": "<h2>Capture global variables elsewhere</h2>\n\n<p>These:</p>\n\n<pre><code>outlook = win32com.client.Dispatch(\"Outlook.Application\").GetNamespace(\"MAPI\")\n\nmailboxNamesList=['Generic_Mailbox']\n\n#test input\n#mailboxName = pg.prompt('please input mailbox name and press enter', 'mailbox name')\n#main(mailboxName)\n\n\nstart = time.time()\n\ndate = datetime.date.today() - datetime.timedelta(days=30)\n</code></pre>\n\n<p>either belong as members of a class, or as local variables passed through function arguments.</p>\n\n<h2>lower_snake_case</h2>\n\n<p><code>itemLoop</code></p>\n\n<p>should be</p>\n\n<p><code>item_loop</code></p>\n\n<p>and so on for <code>arrFolder</code>, etc.</p>\n\n<h2>Naming</h2>\n\n<p>For this code:</p>\n\n<pre><code>for iterator in msg\n</code></pre>\n\n<p>Don't just call it <code>iterator</code>. Maybe call it <code>messages</code>. Name a thing based on its business purpose, not what type of Python variable it is.</p>\n\n<h2>Implicit slice start</h2>\n\n<pre><code>str(iterator.ReceivedTime)[0:10]\n</code></pre>\n\n<p>can be</p>\n\n<pre><code>str(iterator.ReceivedTime)[:10]\n</code></pre>\n\n<h2>Successive append</h2>\n\n<p>Rather than</p>\n\n<pre><code> line.append(folderName)\n line.append(str(iterator.SenderEmailAddress).encode(encoding='ascii',errors='replace'))\n line.append(str(iterator.Subject).encode(encoding='ascii',errors='replace'))\n line.append(str(iterator.ReceivedTime))\n line.append(Calc.action(iterator))\n line.append(body)\n line.append(iterator.Importance)\n line.append(iterator.Sensitivity)\n line.append(iterator.UnRead)\n line.append(iterator.Categories.replace(',', ';'))\n line.append(Calc.autoreply(iterator))\n line.append(iterator.\n</code></pre>\n\n<p>consider</p>\n\n<pre><code>line.extend([\n folderName,\n (str(iterator.SenderEmailAddress).encode(encoding='ascii',errors='replace'),\n # ...\n])\n</code></pre>\n\n<h2>Codes</h2>\n\n<p>For these numbers:</p>\n\n<pre><code> if actionCode==102:\n actionDone=\"replied\"\n if actionCode==103:\n actionDone=\"replied to all\"\n if actionCode==104:\n actionDone=\"forwarded\"\n if actionCode==0:\n actionDone=\"no action taken\"\n</code></pre>\n\n<p>make an <code>enum.Enum</code>, perhaps</p>\n\n<pre><code>class ActionCode(Enum):\n REPLIED = 102\n REPLIED_ALL = 103\n ...\n</code></pre>\n\n<h2>Return is a not a function</h2>\n\n<p>Drop the parens here:</p>\n\n<pre><code> return(actionDone)\n</code></pre>\n\n<h2>Don't swallow exceptions</h2>\n\n<p>This:</p>\n\n<pre><code> except: \n pass\n</code></pre>\n\n<p>needs to die. At the absolute most, catch the specific exception you need to ignore.</p>\n\n<h2>Boolean</h2>\n\n<p><code>autoreply</code> should not return <code>'Yes'</code> or <code>'No</code>', it should return a boolean, to optionally be stringified by other code.</p>\n\n<h2>Formatting</h2>\n\n<pre><code>str(i)+\": \"+str(len(msg))\n</code></pre>\n\n<p>should be</p>\n\n<pre><code>f'{i}: {len(msg)}'\n</code></pre>\n\n<h2>Use <code>is</code></h2>\n\n<p>This</p>\n\n<pre><code> if msg != None:\n</code></pre>\n\n<p>should be</p>\n\n<pre><code>if msg is not None\n</code></pre>\n\n<h2>Set membership</h2>\n\n<pre><code>if str(i)=='Junk E-Mail' or str(i) == 'Deleted Items' or str(i) == 'Sent Items' :\n</code></pre>\n\n<p>should be</p>\n\n<pre><code>if str(I) in {'Junk E-Mail', 'Deleted Items', 'Sent Items'}:\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-09T15:36:24.367", "Id": "232104", "ParentId": "232099", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-09T14:12:06.897", "Id": "232099", "Score": "3", "Tags": [ "python", "email", "iteration", "outlook" ], "Title": "Extracting mail data out of MS Outlook's generic mailbox" }
232099
<p>I wanted to understand how base64 encoding (and decoding) works so I implemented this tool in the spirit of "classic UNIX tools" (read from stdin, write to stdout).</p> <p>I'd like to get general feedback on style and implementation (hoping I got it right). Also, since I'm doing bit manipulation, should I worry about endianness?</p> <p><code>b64.c</code></p> <pre><code>#include &lt;stdio.h&gt; #include &lt;string.h&gt; #include &lt;stdlib.h&gt; #define USAGE "usage: b64 [-d]\n" \ " base64 encode/decode standard input to standard output\n" static void die(const char *reason); static void encode(void); static void decode(void); static int getcharskipn(void); static int isvalid(int c); static char enctable[] = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/', }; static int dectable[] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51 }; int main(int argc, char **argv) { if (argc == 1) encode(); else if (argc == 2 &amp;&amp; strcmp(argv[1], "-d") == 0) decode(); else die(USAGE); return 0; } static void die(const char *reason) { fprintf(stderr, reason); exit(EXIT_FAILURE); } static void encode(void) { int b1, b2, b3; unsigned long g; /* group of 4 6-bit indices for enctable built using 3 input bytes */ while ((b1 = getchar()) != EOF) { b2 = getchar(); b3 = getchar(); g = b1; g = (g &lt;&lt; 8) | (b2 == EOF ? 0 : b2); g = (g &lt;&lt; 8) | (b3 == EOF ? 0 : b3); putchar(enctable[(g &gt;&gt; 18) &amp; 0x3F]); putchar(enctable[(g &gt;&gt; 12) &amp; 0x3F]); putchar(b2 == EOF ? '=' : enctable[(g &gt;&gt; 6) &amp; 0x3F]); putchar(b3 == EOF ? '=' : enctable[g &amp; 0x3F]); } } static void decode(void) { int c1, c2, c3, c4; unsigned long g; /* group of 3 bytes built using dectable indexed by 4 input characters */ while ((c1 = getcharskipn()) != EOF) { c2 = getcharskipn(); c3 = getcharskipn(); c4 = getcharskipn(); if ( ! isvalid(c1) || c1 == '=' || ! isvalid(c2) || c2 == '=' || ! isvalid(c3) || ! isvalid(c4)) die("b64: invalid input\n"); g = dectable[c1]; g = (g &lt;&lt; 6) | dectable[c2]; g = (g &lt;&lt; 6) | (c3 == '=' ? 0 : dectable[c3]); g = (g &lt;&lt; 6) | (c4 == '=' ? 0 : dectable[c4]); putchar((g &gt;&gt; 16) &amp; 0xFF); if (c3 != '=') putchar((g &gt;&gt; 8) &amp; 0xFF); if (c4 != '=') putchar(g &amp; 0xFF); } } static int getcharskipn(void) { int c; if ((c = getchar()) == '\n') return getchar(); if (c == '\r') { if ((c = getchar()) == '\n') return getchar(); ungetc(c, stdin); return '\r'; } return c; } static int isvalid(int c) { return (c &gt;= 'A' &amp;&amp; c &lt;= 'Z') || (c &gt;= 'a' &amp;&amp; c &lt;= 'z') || (c &gt;= '0' &amp;&amp; c &lt;= '9') || c == '+' || c == '/' || c == '='; } </code></pre> <p><code>b64.test</code></p> <pre class="lang-sh prettyprint-override"><code>#!/bin/sh test_str() { printf "%s" "$1" &gt; original printf "%s" "$2" &gt; expected ./b64 &lt; original &gt; enc diff enc expected || exit 1 ./b64 -d &lt; enc &gt; dec diff dec original || exit 1 } test_rnd() { head -c "$1" /dev/urandom &gt; rnd ./b64 &lt; rnd &gt; enc ./b64 -d &lt; enc &gt; dec diff dec rnd || exit 1 } cleanup() { rm original expected rnd dec enc } test_str "" "" test_str "f" "Zg==" test_str "fo" "Zm8=" test_str "foo" "Zm9v" test_str "foob" "Zm9vYg==" test_str "fooba" "Zm9vYmE=" test_str "foobar" "Zm9vYmFy" test_str "foobarb" "Zm9vYmFyYg==" test_str "foobarba" "Zm9vYmFyYmE=" test_str "foobarbaz" "Zm9vYmFyYmF6" for i in `seq 1000 1024`; do test_rnd $i; done cleanup echo "all tests passed" </code></pre> <p><code>Makefile</code></p> <pre><code>.POSIX: CC := cc CFLAGS := -std=c89 -pedantic -Wall -Wextra -Werror PREFIX := /usr/local all: b64.debug b64.debug: b64.c $(CC) $(CFLAGS) -g -DDEBUG $^ -o $@ b64: b64.c $(CC) $(CFLAGS) -DNDEBUG $^ -o $@ test: b64 sh b64.test install: b64 mkdir -p $(DESTDIR)$(PREFIX)/bin cp b64 $(DESTDIR)$(PREFIX)/bin uninstall: rm $(DESTDIR)$(PREFIX)/bin/b64 clean: rm -f b64 b64.debug </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-09T15:31:42.997", "Id": "453065", "Score": "0", "body": "Looks like you've reimplemented [`uudecode`](https://linux.die.net/man/1/uudecode)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-09T15:38:14.417", "Id": "453067", "Score": "0", "body": "@Edward well I know I've \"reinvented the wheel\". I did it for learning. There is also [base64](https://linux.die.net/man/1/base64) from GNU and I guess countless many more." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-09T15:38:57.640", "Id": "453068", "Score": "1", "body": "It was just an observation, not a complaint! :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-09T22:49:35.317", "Id": "453108", "Score": "0", "body": "You may also want to avoid calling exit. Instead return the error And have it bubble up to the main function which will then return EXIT_FAILURE. Otherwise you risk some cleanup procedure not being called. Not that there Is one atm, but you never know how things Will evolve. Its a good practice to have just one exit point." } ]
[ { "body": "<p>All the code looks like you are very experienced since you didn't make any obvious mistakes.</p>\n\n<p>Some small things to consider:</p>\n\n<ul>\n<li><p>I'd compile the release binary with assertions enabled since I prefer an obvious crash over undefined behavior.</p></li>\n<li><p>Since you don't include <code>&lt;assert.h&gt;</code> at all, you don't need the <code>-DNDEBUG</code> flags at all since they won't make any difference.</p></li>\n<li><p>The headers from the C standard library should be sorted alphabetically.</p></li>\n<li><p>The function name <code>isvalid</code> is reserved for future versions of the C standard library, though I don't think that name will ever be taken. The name <code>isvalid</code> is way too unspecific to land in the standard library. In the narrow scope of a base64 encoder/decoder, the name is perfect.</p></li>\n<li><p>Your decision to have 18 table entries per line looks a bit arbitrary to me. I'd select 16 since that's how the code points in ASCII are arranged.</p></li>\n<li><p>The decoding table assumes that the execution character set is ASCII. Try running this program on an IBM machine. :)</p></li>\n<li><p>Since you already use the <code>const</code> keyword, it makes sense to use it for <code>enctable</code> and <code>dectable</code> as well.</p></li>\n<li><p>At the very end of the program, you could check <code>stdin</code> and <code>stdout</code> for I/O errors and in such a case return <code>EXIT_FAILURE</code>.</p></li>\n<li><p>Having a test suite with even fuzzing included makes the code trustworthy. :)</p></li>\n<li><p>The Makefile even works on ancient Solaris where <code>/bin/sh</code> does not even know about functions. In such a situation, one can just set <code>PATH</code> before running make and thereby provide a sane shell.</p></li>\n<li><p>Thank you for including <code>DESTDIR</code> in the Makefile. :)</p></li>\n<li><p>For installing the program, you should not use <code>cp</code>:</p>\n\n<ul>\n<li><p>It will overwrite the file in-place, which leads to problems if the program is still running while being overwritten.</p></li>\n<li><p>It doesn't overwrite write-protected files. Use <code>install -m 555 b64 $(DESTDIR)$(PREFIX)/bin/</code> instead.</p></li>\n</ul></li>\n</ul>\n\n<p>In my mind the program is ready to be used and packaged. You might write a manual page to make the distribution package complete.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-10T11:44:27.243", "Id": "453141", "Score": "0", "body": "thank you for your feedback! I didn't know about `install`, I definitely going to use it from now on =) To fix the \"IBM machine\" problem I think I could build `dectable` at runtime starting from `enctable` and maybe make `isvalid` dependent on `dectable` since I suspect that `isvalid` wouldn't work either on non-ascii machine. Does it make sense to you?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-10T14:40:04.897", "Id": "453158", "Score": "1", "body": "Sounds perfect." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-09T17:51:12.457", "Id": "232116", "ParentId": "232103", "Score": "5" } } ]
{ "AcceptedAnswerId": "232116", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-09T15:28:53.560", "Id": "232103", "Score": "7", "Tags": [ "c", "reinventing-the-wheel", "base64" ], "Title": "base64 encoding and decoding tool" }
232103
<p>I'm learning Rust and a few questions did arise during translation of my C++ code to Rust. There are comments in Rust code I'd like to be answered. Is there an idiomatic way to solve this task? The task was in simulating a random process - there are two chairs, which have different processing capacity and there is a flow of customers, who visit the chairs sequentially.</p> <p><em>Summary:</em> Shoe shine shop has two chairs, one for brushing (1) and another for polishing (2). Customers arrive according to PP with rate <span class="math-container">\$\lambda\$</span>, and enter only if first chair is empty. Shoe-shiners takes <span class="math-container">\$\exp(\mu_1)\$</span> time for brushing and <span class="math-container">\$\exp(\mu_2)\$</span> time for polishing. </p> <p>Code in C++:</p> <pre class="lang-cpp prettyprint-override"><code>#include &lt;map&gt; #include &lt;string&gt; #include &lt;random&gt; #include &lt;iostream&gt; #include &lt;numeric&gt; #include &lt;algorithm&gt; #include &lt;queue&gt; int main(int argc, char *argv[]) { if (argc &lt; 5) { std::cerr &lt;&lt; "not enough arguments!\nlambda, m1, m2, max_time"; return -1; } using distribution_t = std::exponential_distribution&lt;double&gt;; std::string event_names[3] = {"ARRIVED", "FIRST_FINISHED", "SECOND_FINISHED"}; std::string state_names[7] = {"EMPTY", "FIRST", "SECOND", "WAITING", "BOTH", "DROP", "INVALID"}; enum event_t { ARRIVED = 0, FIRST_FINISHED, SECOND_FINISHED }; enum state_t { EMPTY = 0, FIRST, SECOND, WAITING, BOTH, DROP, INVALID }; std::size_t state_to_clients[DROP] = {0, 1, 1, 2, 2}; // clang-format off // EMPTY FIRST SECOND WAITING BOTH state_t event_to_state[3][5] = { /* ARRIVED */ {FIRST, DROP, BOTH, DROP, DROP}, /* FIRST_FINISHED */ {INVALID, SECOND, INVALID, INVALID, WAITING}, /* SECOND_FINISHED */ {INVALID, INVALID, EMPTY, SECOND, FIRST}, }; // clang-format on double lambda = atof(argv[1]); double m1 = atof(argv[2]); double m2 = atof(argv[3]); double time_max = atof(argv[4]); std::mt19937_64 generator(std::random_device{}()); struct stats_t { std::size_t state_counts[DROP]{}; // max feasible event - BOTH std::size_t state_counts_with_drop[DROP]{}; double time_in_state[DROP]{}; double time_in_client[3]{}; // roflanEbalo double served_time = 0.0; std::size_t served_clients = 0; std::size_t arrived_clients = 0; std::size_t dropped_clients = 0; } stats; double times[3]{}; distribution_t dists[3] = {distribution_t(lambda), distribution_t(m1), distribution_t(m2)}; // mean = 1/param std::map&lt;double, event_t&gt; timeline; auto inserter = [&amp;timeline, &amp;generator](event_t event, double &amp;t, distribution_t &amp;dist) { double dt; do { dt = dist(generator); } while (!timeline.try_emplace(t + dt, event).second); t += dt; }; for (std::size_t i = 0; i &lt; 3; ++i) while (times[event_t(i)] &lt; time_max) inserter(event_t(i), times[i], dists[i]); double prev = 0; state_t state = EMPTY; std::queue&lt;double&gt; arriving_times; for (auto [time, event] : timeline) { if (argc &gt; 5) { std::cout &lt;&lt; "[PROCESSING]: " &lt;&lt; time &lt;&lt; " " &lt;&lt; event_names[event] &lt;&lt; std::endl; std::cout &lt;&lt; "[INFO]: " &lt;&lt; state_names[state] &lt;&lt; std::endl; } if (event == ARRIVED) ++stats.arrived_clients; state_t new_state = event_to_state[event][state]; switch (new_state) { case INVALID: break; case DROP: ++stats.state_counts_with_drop[state]; ++stats.dropped_clients; break; default: if (event == ARRIVED) arriving_times.push(time); else if (event == SECOND_FINISHED) { stats.served_time += time - arriving_times.front(); arriving_times.pop(); ++stats.served_clients; } stats.time_in_state[state] += time - prev; stats.time_in_client[state_to_clients[state]] += time - prev; prev = time; state = new_state; ++stats.state_counts[state]; break; } } std::transform(std::begin(stats.state_counts), std::end(stats.state_counts), std::begin(stats.state_counts_with_drop), std::begin(stats.state_counts_with_drop), std::plus&lt;std::size_t&gt;()); auto report = [&amp;state_names](std::string_view title, auto counts) { std::cout &lt;&lt; title &lt;&lt; std::endl; auto events = std::accumulate(counts, counts + DROP, 0.0); for (std::size_t i = 0; i &lt; DROP; ++i) std::cout &lt;&lt; state_names[i] &lt;&lt; ": " &lt;&lt; counts[i] / double(events) &lt;&lt; std::endl; std::cout &lt;&lt; std::endl; }; report("time in states: ", stats.time_in_state); report("entries in states: ", stats.state_counts); report("entries in states with dropouts: ", stats.state_counts_with_drop); std::cout &lt;&lt; "dropout: " &lt;&lt; stats.dropped_clients / double(stats.arrived_clients) &lt;&lt; std::endl; std::cout &lt;&lt; "average serving time: " &lt;&lt; stats.served_time / double(stats.served_clients) &lt;&lt; std::endl; std::cout &lt;&lt; "average number of clients: " &lt;&lt; (stats.time_in_client[1] + 2 * stats.time_in_client[2]) / std::accumulate(std::begin(stats.time_in_client), std::end(stats.time_in_client), 0.0) &lt;&lt; std::endl; // arr=(10 10 10); for i in {0..2}; do for param in {1..100}; do // darr=("${arr[@]}"); darr[i]=${param}; echo "${darr[@]}" &gt;&gt; ../out.txt &amp;&amp; // ./lab2.exe ${darr[@]} 1000000 &gt;&gt; ../out.txt; done; done } </code></pre> <p>Code in Rust:</p> <pre class="lang-rust prettyprint-override"><code>use std::collections::BTreeMap; use std::collections::VecDeque; use std::env; extern crate rand; use rand::distributions::*; extern crate ordered_float; pub use ordered_float::*; // variant is never constructed: `FirstFinished`, why do I get this message? I can see this variant printed when running the program #[derive(Copy, Clone, Debug, PartialEq)] enum Events { Arrived = 0, FirstFinished, SecondFinished, } #[derive(Copy, Clone, Debug, PartialEq)] enum States { Empty = 0, First, Second, Waiting, Both, Dropping, Invalid, } #[rustfmt::skip] #[derive(Debug, Default)] struct Stats { state_counts: [u32; States::Dropping as usize], state_counts_with_drop: [u32; States::Dropping as usize], time_in_state: [f64; States::Dropping as usize], time_in_client: [f64; 3], served_time: f64, served_clients: u32, arrived_clients: u32, dropped_clients: u32, } // 1 template function for this? Or any other way to cast integer to enum? Or I should use libraries for this? impl From&lt;usize&gt; for States { fn from(s: usize) -&gt; States { let tmp: u8 = s as u8; unsafe { std::mem::transmute(tmp) } } } impl From&lt;usize&gt; for Events { fn from(s: usize) -&gt; Events { let tmp: u8 = s as u8; unsafe { std::mem::transmute(tmp) } } } //what do I need lifetime 'a for? Is there supertrait that specifies multiple traits? ("Number", "container", idk) //Or can I just say that allowed types are f64 and i32? fn report&lt;'a, T&gt;(title: &amp;str, counts: &amp;'a [T; States::Dropping as usize]) where T: std::iter::Sum&lt;&amp;'a T&gt; + std::ops::Div + Copy + Into&lt;f64&gt; + std::fmt::Display, { println!("{}", title); let events: T = counts.iter().sum(); for i in 0..(States::Dropping as usize) { println!( "{:?}: {}", Into::&lt;States&gt;::into(i), Into::&lt;f64&gt;::into(counts[i]) / Into::&lt;f64&gt;::into(events) // How to call Into properly? this looks bad ); } println!(); } fn main() { let state_to_clients: [usize; States::Dropping as usize] = [0, 1, 1, 2, 2]; #[rustfmt::skip] let event_to_state: [[States; 5]; 3] = [ // EMPTY FIRST SECOND WAITING BOTH /* Arrived */ [States::First, States::Dropping, States::Both, States::Dropping, States::Dropping], /* First_Finished */ [States::Invalid, States::Second, States::Invalid, States::Invalid, States::Waiting], /* Second_Finished */ [States::Invalid, States::Invalid, States::Empty, States::Second, States::First], ]; let args: Vec&lt;String&gt; = env::args().collect(); if args.len() &lt; 5 { panic!("Not enough arguments!"); } let (lambda, m1, m2, time_max) = ( args[1].parse::&lt;f64&gt;().unwrap(), args[2].parse::&lt;f64&gt;().unwrap(), args[3].parse::&lt;f64&gt;().unwrap(), args[4].parse::&lt;f64&gt;().unwrap(), ); let mut rng = rand::thread_rng(); let mut stats = Stats::default(); let mut times: [f64; 3] = Default::default(); let mut dists: [Exp; 3] = [Exp::new(lambda), Exp::new(m1), Exp::new(m2)]; // I don't like OrderedFloat because it's a wrapper. Is there a way to implement Ord for floats and keep nice syntax? // Maybe it's the problem of algorithm. Any proposals? let mut timeline: BTreeMap&lt;OrderedFloat&lt;f64&gt;, Events&gt; = BTreeMap::new(); let mut inserter = |event: &amp;Events, t: &amp;mut f64, distribution: &amp;mut Exp| { let mut dt; //Is it ok to emulate do while loops like this? while { dt = OrderedFloat(distribution.sample(&amp;mut rng)); let key = OrderedFloat(*t + Into::&lt;f64&gt;::into(dt)); match timeline.get(&amp;key) { Some(_) =&gt; true, None =&gt; { timeline.insert(key, *event); false } } } {} *t += Into::&lt;f64&gt;::into(dt); }; for i in 0..3 { while times[i] &lt; time_max { inserter(&amp;i.into(), &amp;mut times[i], &amp;mut dists[i]); } } let mut prev = 0f64; let mut state = States::Empty; let mut arriving_times = VecDeque::&lt;f64&gt;::new(); for (time, event) in timeline { if args.len() &gt; 5 { println!("[PROCESSING]: {} {:?}", time, event); println!("[INFO]: {:?}", state); } if event == Events::Arrived { stats.arrived_clients += 1; } let new_state = event_to_state[event as usize][state as usize]; match new_state { States::Dropping =&gt; { stats.state_counts_with_drop[state as usize] += 1; stats.dropped_clients += 1; } States::Invalid =&gt; (), _ =&gt; { if event == Events::Arrived { arriving_times.push_back(Into::&lt;f64&gt;::into(time)); } else if event == Events::SecondFinished { stats.served_time += Into::&lt;f64&gt;::into(time) - arriving_times.front().unwrap(); arriving_times.pop_front(); stats.served_clients += 1; } stats.time_in_state[state as usize] += Into::&lt;f64&gt;::into(time) - prev; stats.time_in_client[state_to_clients[state as usize] as usize] += Into::&lt;f64&gt;::into(time) - prev; prev = Into::&lt;f64&gt;::into(time); state = new_state; stats.state_counts[state as usize] += 1; } }; } for (i, element) in stats.state_counts_with_drop.iter_mut().enumerate() { *element += stats.state_counts[i]; } report("time in states: ", &amp;stats.time_in_state); report("entries in states: ", &amp;stats.state_counts); report( "entries in states with dropouts: ", &amp;stats.state_counts_with_drop, ); println!( "dropout: {}\naverage serving time: {}\naverage number of clients: {}", (stats.dropped_clients as f64) / (stats.arrived_clients as f64), stats.served_time / (stats.served_clients as f64), (stats.time_in_client[1] + 2.0f64 * stats.time_in_client[2]) / stats.time_in_client.iter().sum::&lt;f64&gt;() ); } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-10T06:04:45.043", "Id": "453127", "Score": "0", "body": "It seems to me that your use of a state transition table is very C++ and not really in keeping with Rust style. I'd like to offer more concrete advice, but I'm having trouble understanding the logic of your table. I'd have thought it would Invalid to Arrive when not in the empty state. But you either transition to Dropping or Both. I'm guessing that Dropping means that the client left before the shoe shine was finished, and you are interpreting \"Arrive\" in a non-empty state as \"Depart.\" But then I can't figure out what the Both state is doing." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-10T06:06:51.197", "Id": "453129", "Score": "0", "body": "You seem to transition to the Both state if the client leaves while the left-shoe is being shined? But it would seem that the second shoe wouldn't be shined in that case, so its odd to call it Both. And I can't figure out any logic to the transition to the First or Waiting states from that state." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-10T14:44:55.937", "Id": "453160", "Score": "0", "body": "I took another look this morning and I now think both versions are solving the wrong problem. I edited my answer with details. Hope this helps!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-10T23:21:51.793", "Id": "453192", "Score": "0", "body": "@winston-ewert It's allowed to receive a client on the first chair while the second is occupied. \"BOTH\" state means both clients are getting served. \"WAITING\" means client on the first chair awaits for the other one to finish." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-14T12:26:59.363", "Id": "453765", "Score": "2", "body": "Please don't edit the question after it has been answered, the point is to allow every reviewer to see the same code. For more information see this help page https://codereview.stackexchange.com/help/someone-answers" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-14T12:54:14.020", "Id": "453772", "Score": "0", "body": "If you want to get a second review, the preferred way is start a new question and link it back to this question." } ]
[ { "body": "<p>Forgive me, I am unable to review the rust code because I do not know rust, I am only reviewing the c++ code..</p>\n\n<h2>Use System Defined Exit Codes</h2>\n\n<p>Returning <code>-1</code> as an exit code from a c++ program is rather uncommon, the generally accepted values to return from a c++ program are zero for success and one for failure. What is even better is that if the cstdlib header is included then the symbolic constants <a href=\"https://en.cppreference.com/w/cpp/utility/program/EXIT_status\" rel=\"noreferrer\"><code>EXIT_SUCCESS</code> and <code>EXIT_FAILURE</code></a> are available for use which makes the program more readable and very portable.</p>\n\n<pre><code>int main(int argc, char *argv[]) {\n if (argc &lt; 5) {\n std::cerr &lt;&lt; \"not enough arguments!\\nlambda, m1, m2, max_time\";\n return EXIT_FAILURE;\n }\n</code></pre>\n\n<p>In the error message above, unless the user is familiar with what <code>lambda</code>, <code>m1</code>, <code>m2</code> and <code>max_time</code> are the message may be unclear to the user.</p>\n\n<h2>Complexity</h2>\n\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\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=\"noreferrer\">Single Responsibility Principle</a> states:</p>\n\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\n<p>There are many possible functions in <code>main()</code>:<br>\n - Process the command line arguments<br>\n - Process the states<br>\n - An <code>inserter</code> function rather than a lambda declaration<br>\n - A <code>report</code> function rather than a lambda declaration<br>\n - Print the output </p>\n\n<p>The declarations for the <code>stats_t</code> struct, and the enums <code>event_t</code> and <code>state_t</code> should be moved out of <code>main()</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-09T17:44:59.450", "Id": "232113", "ParentId": "232106", "Score": "10" } }, { "body": "<h1>Correctness of the solution</h1>\n\n<p>On reflection, I'm not sure either the C++ or the Rust code solves the problem as stated. I'm not completely sure I understand the shoe shine shop model so I may be wrong. Here's what it looks like the code does: you generate a bunch of random events of all kinds, and order them in time. Then you process the events one by one starting with the earliest. But that doesn't make sense!</p>\n\n<blockquote>\n <p>Customers arrive according to PP with rate <span class=\"math-container\">\\$\\lambda\\$</span>, and enter only if first chair is empty. Shoe-shiners takes <span class=\"math-container\">\\$\\exp(\\mu_1)\\$</span> time for brushing and <span class=\"math-container\">\\$\\exp(\\mu_2)\\$</span> time for polishing. </p>\n</blockquote>\n\n<p>The way I'm reading it, your random variables should be ordered <em>not</em> with respect to other events of the same kind, but with respect to the <em>order of events in the shop</em>. A shop can't finish shining a shoe before it has been brushed, and it can't finish brushing a shoe before any customers have arrived. Therefore, you need to schedule a <code>FirstFinished</code> event with respect to the <code>Arrived</code> event that initiated it, not with respect to the previous <code>FirstFinished</code> event.</p>\n\n<p>A <code>BTreeMap</code> isn't the right solution to this problem. One way to solve it might be a priority queue with both the event kind and the time of the event (possibly a <code>BinaryHeap&lt;(OrderedFloat&lt;f64&gt;, Events)&gt;</code>). Your event queue starts out filled with only <code>Arrival</code>s, randomly distributed according to <span class=\"math-container\">\\$PP(\\lambda)\\$</span>. As you process the queue, you pull off an arrival, and schedule the <code>FirstFinished</code> event at some time in the future <em>relative to the arrival time</em>. Then you pull off the next event, which could either be another <code>Arrival</code> (which you would have to drop) or the <code>FirstFinished</code> event you just pushed on (which would enable you to transition to the next state, and schedule the <code>SecondFinished</code> event), and continue processing.</p>\n\n<blockquote>\n <p>I thought so too, but my group mate guessed that it doesn't make a difference. When the results produced by this program matched theoretical ones, I was convinced. Out of interest I just programmed your version of the solution and the results are the same.</p>\n</blockquote>\n\n<p>Okay, I'm not an expert but I do think this is technically true, because the expected time remaining until the next event does not depend on the time since the last event. So from a pure results perspective your colleague may be correct. However, there are still two good reasons to write the solution the way it is formulated:</p>\n\n<ol>\n<li>You are relying, perhaps unaware, on a feature unique to exponential distributions. Suppose you were asked to model the same problem, but use a normal distribution for the time it takes to brush or shine shoes (which is probably more reasonable, anyway). Your current code can't be easily changed to account for that; you'll have to rewrite it. Also, if somebody else came along after you, they might not realize this code depends on an exponential distribution; they are likely to be confused (as I was).</li>\n<li>Generating a lot of random numbers has performance implications. Consider the difference between <code>cargo run 1 50 50 10</code> and <code>cargo run 1 1000000000 1000000000 10</code>. These simulations should serve roughly the same number of customers, but the second one calculates nearly two billion random numbers that never get used!</li>\n</ol>\n\n<p>That said, a lot of the advice I have to give here is applicable generally, so let's proceed as if the program's behavior is correct as written. I will restrict myself to comments on the Rust code, as that's what I am more familiar with.</p>\n\n<h1>Versions</h1>\n\n<p>You may be using an older version of Rust. <code>extern crate</code> declarations are not\nneeded anymore in the 2018 edition. If you're still on 2015, that's fine; I just\nthought you might like to know.</p>\n\n<p>Most distributions in the <code>rand::distributions</code> module have been moved to a separate\ncrate, <code>rand_distr</code>. The old versions are deprecated; I got warnings about it during compilation. I don't know how long ago\nthis change was made; you might want to update your dependencies. Again, not necessarily a problem, just FYI.</p>\n\n<h1>Style</h1>\n\n<p>Thank you for using <code>rustfmt</code>.</p>\n\n<p><code>States</code> and <code>Events</code> should be named <code>State</code> and <code>Event</code>, because each <code>enum</code>\nrepresents a <em>single</em> state or event, not several.</p>\n\n<p>Star imports (like <code>use rand::distributions::*;</code>) are usually inadvisable, like <code>using namespace</code> in C++,\nbecause they pollute the module namespace. If you have a lot of them you can\neasily lose track of which names come from where. You're only using a couple\nof specific names here, so just write them explicitly:</p>\n\n<pre><code>use rand::distributions::{Distribution, Exp};\npub use ordered_float::OrderedFloat;\n</code></pre>\n\n<p>(Seeing as nothing else is marked <code>pub</code>, that can presumably go too.)</p>\n\n<p>Don't loop over integers and then index into a slice. Instead, loop over the slice, and possibly throw an <code>.iter().enumerate()</code> in if you need access to the index, so</p>\n\n<pre><code>for i in 0..s.len() { /* do something with s[i] */ }\n</code></pre>\n\n<p>becomes</p>\n\n<pre><code>for element in s { /* do something with element */ }\n// or\nfor (i, element) in s.iter().enumerate() { /* if you need i too */ }\n</code></pre>\n\n<h1>Questions</h1>\n\n<h2>Variant is never constructed</h2>\n\n<pre><code>// variant is never constructed: `FirstFinished`, why do I get this message? I can see this variant printed when running the program\n</code></pre>\n\n<p>This looks like a compiler bug in that it doesn't realize that converting from\nan integer, with or without <code>unsafe</code>, can create variants without naming them.</p>\n\n<h2>Integer to <code>enum</code> conversions</h2>\n\n<pre class=\"lang-rust prettyprint-override\"><code>// 1 template function for this? Or any other way to cast integer to enum? Or I should use libraries for this?\nimpl From&lt;usize&gt; for States {\n fn from(s: usize) -&gt; States {\n let tmp: u8 = s as u8;\n unsafe { std::mem::transmute(tmp) }\n }\n}\n</code></pre>\n\n<p>There is no reason to use <code>unsafe</code> here. In fact, as written it is incorrect,\nbecause passing a <code>usize</code> that doesn't correspond to a valid <code>States</code> could\ncause undefined behavior. As long as you're using safe Rust, the compiler\nprotects you from unsafety; when you use <code>unsafe</code>, you assume responsibility\nfor writing a <em>safe abstraction</em> that can't be used unsafely.</p>\n\n<p><s>C-like <code>enum</code>s implement the <code>TryInto</code> trait, which you should use instead.\nYou can replace the bodies of both functions with <code>s.try_into().unwrap()</code>.</s> Oops, this was a blunder on my part. <code>TryFrom</code>/<code>TryInto</code> are not automatically implemented for C-like enums; that was a requested feature that I thought had been implemented, and compiled when I tried it but actually is incorrect. Instead you should probably just write <code>TryFrom</code> yourself; <a href=\"https://stackoverflow.com/a/57578431/3650362\">here's one example</a>. However, converting enums to integers isn't particularly idiomatic in Rust; if you rewrite the code to use a <code>match</code> as under \"Design concerns\" below, it's not necessary.</p>\n\n<h2><code>report</code></h2>\n\n<pre class=\"lang-rust prettyprint-override\"><code>//what do I need lifetime 'a for? Is there supertrait that specifies multiple traits? (\"Number\", \"container\", idk)\n//Or can I just say that allowed types are f64 and i32?\nfn report&lt;'a, T&gt;(title: &amp;str, counts: &amp;'a [T; States::Dropping as usize])\nwhere\n T: std::iter::Sum&lt;&amp;'a T&gt; + std::ops::Div + Copy + Into&lt;f64&gt; + std::fmt::Display,\n{\n</code></pre>\n\n<blockquote>\n <p>What do I need <code>'a</code> for?</p>\n</blockquote>\n\n<p>Not much, in this example. Named lifetimes are all about specifying\nrelationships, in this case, the relationship between <code>counts</code>, which is a\nreference, and <code>Sum&lt;&amp;T&gt;</code> which is a trait satisfied by <code>T</code>. You have <code>T:\nSum&lt;&amp;'a T&gt;</code>, which means that you can add a bunch of <code>&amp;'a T</code>s and get the sum\nas a <code>T</code>. You have a bunch of <code>&amp;'a T</code>s (the slice) and you need a <code>T</code>, so\nthat's the right constraint. There's not much more to it than that.</p>\n\n<blockquote>\n <p>Is there a supertrait that specifies multiple [number-like] traits?</p>\n</blockquote>\n\n<p>There are traits like that, defined in the <code>num_traits</code> crate. You usually\nwant <code>num_traits::Num</code> to do general math on a generic type. But it's not\nreally needed here; if you change the <code>events</code> line to</p>\n\n<pre><code> let events: f64 = counts.iter().copied().map(Into&lt;f64&gt;::into).sum();\n</code></pre>\n\n<p>you only need <code>T: Copy + Into&lt;f64&gt;</code> to implement the whole function. (This line looks pretty ugly; probably there's something nice and elegant I'm overlooking.)</p>\n\n<h2>Calling <code>into</code></h2>\n\n<pre class=\"lang-rust prettyprint-override\"><code> Into::&lt;States&gt;::into(i),\n Into::&lt;f64&gt;::into(counts[i]) / Into::&lt;f64&gt;::into(events) // How to call Into properly? this looks bad\n</code></pre>\n\n<p>If you really need to specify the type argument to <code>Into</code>, that's how you\nwould do it, but that's unusual. Most of the time you can just write\n<code>.into()</code>. When the types implement <code>From</code>, that is also often somewhat\ncleaner.</p>\n\n<pre class=\"lang-rust prettyprint-override\"><code> States::from(i),\n counts[i].into() / events.into()\n</code></pre>\n\n<p>You have several other <code>into</code>s scattered in this loop:</p>\n\n<pre><code> for (time, event) in timeline { ... }\n</code></pre>\n\n<p>But they're all turning <code>time</code>, which is an <code>OrderedFloat&lt;f64&gt;</code>, into a\nregular <code>f64</code>. You don't need to do that; because <code>OrderedFloat</code> is just a\nnewtype struct, you can just access the inner value with <code>.0</code>. Or in this\ncase, since you don't actually need the <code>OrderedFloat</code> inside the loop, you\nmay use a destructuring pattern to pull it out as you iterate.</p>\n\n<pre><code> for (OrderedFloat(time), event) in timeline { ... }\n</code></pre>\n\n<h2><code>OrderedFloat</code></h2>\n\n<pre class=\"lang-rust prettyprint-override\"><code> // I don't like OrderedFloat because it's a wrapper. Is there a way to implement Ord for floats and keep nice syntax?\n // Maybe it's the problem of algorithm. Any proposals?\n let mut timeline: BTreeMap&lt;OrderedFloat&lt;f64&gt;, Events&gt; = BTreeMap::new();\n</code></pre>\n\n<p>Not really, you need to decide somehow how to handle NaNs. If NaNs aren't a\npossibility, maybe floating-point numbers aren't an appropriate type. An\nalternative might be to pick a unit, like 1 nanosecond, and just keep all your\ntimes and durations as integers, only converting them for display purposes.</p>\n\n<h2>Emulating <code>do</code> loops</h2>\n\n<pre class=\"lang-rust prettyprint-override\"><code> //Is it ok to emulate do while loops like this?\n while {\n /* loop body that returns true or false */\n } {}\n</code></pre>\n\n<p>I mean, I guess it works, but ew. Just use <code>loop</code> and have <code>if condition {\nbreak; }</code> in there somewhere.</p>\n\n<h1>Design concerns</h1>\n\n<p><code>main</code> is too long. pacmaninbw's advice applies as well to Rust as to C++. I'd try to move some of that logic out to methods of <code>State</code>.</p>\n\n<p>I like the way you use <code>derive(Default)</code> to avoid doing unnecessary work;\nthat feels nice and idiomatic.</p>\n\n<p>The <code>Invalid</code> state of your machine makes me slightly uncomfortable. There are\nuses for such things but it looks like you could get rid of it entirely and\njust panic immediately when you encounter an invalid state/event combination,\nrather than making your state temporarily invalid until the next loop\niteration.</p>\n\n<p>There's another thing that also seems awkward to me, and that's the repeated\nuse of <code>States::Dropping as usize</code> for an array size. This use of <code>enum</code>s is\nnormal in C but in Rust it just feels out of place; <code>enum</code> is not just a\nrenamed integer but a full-featured sum type. Ideally, you would make use of\nthis to write a <code>next_state</code> function that is statically guaranteed to cover\nall the bases:</p>\n\n<pre class=\"lang-rust prettyprint-override\"><code>fn next_state(sr: State, event: Event) -&gt; Option&lt;State&gt; {\n match sr {\n State::Empty =&gt; match event {\n Event::Arrived =&gt; Some(State::First),\n _ =&gt; None,\n }\n State::First =&gt; match event {\n Event::Arrived =&gt; Some(State::Dropping),\n Event::FirstFinished =&gt; Some(State::Second),\n _ =&gt; None,\n }\n /* ... */\n }\n}\n</code></pre>\n\n<p>Turning this into a macro so you can keep the nice table format in the source\ncode seems pretty doable.</p>\n\n<h1>Miscellaneous tips</h1>\n\n<pre class=\"lang-rust prettyprint-override\"><code> let event_to_state: [[States; 5]; 3] = [\n // EMPTY FIRST SECOND WAITING BOTH\n /* Arrived */ [States::First, States::Dropping, States::Both, States::Dropping, States::Dropping],\n /* First_Finished */ [States::Invalid, States::Second, States::Invalid, States::Invalid, States::Waiting],\n /* Second_Finished */ [States::Invalid, States::Invalid, States::Empty, States::Second, States::First],\n ];\n</code></pre>\n\n<p>This is a bit long and noisy compared to the C++ version; you can trim it down\nby adding a <code>use States::*;</code>. Also it should be a <code>const</code> (not quite like C's <code>const</code>; more analogous to <code>constexpr</code> in C++).</p>\n\n<pre class=\"lang-rust prettyprint-override\"><code> use States::*;\n #[rustfmt::skip]\n const EVENT_TO_STATE: [[States; 5]; 3] = [\n // EMPTY FIRST SECOND WAITING BOTH\n /* Arrived */ [First, Dropping, Both, Dropping, Dropping],\n /* First_Finished */ [Invalid, Second, Invalid, Invalid, Waiting],\n /* Second_Finished */ [Invalid, Invalid, Empty, Second, First],\n ];\n</code></pre>\n\n<p>I might consider using a declarative macro instead of a generic function for\n<code>report</code>. It's internal, the abstraction is mostly syntax and the trait bounds\nare not terribly interesting.</p>\n\n<blockquote>\n <p>I don't really like macros since I come from c++. Are they widely used by Rust community?</p>\n</blockquote>\n\n<p>Yes. Declarative macros (those defined with <code>macro_rules!</code>) are quite different from preprocessor macros (fancy text substitution) like in C.</p>\n\n<ul>\n<li>They resemble C++ templates in that they must be syntactically valid at definition, but don't type check until instantiated.</li>\n<li>Macros are hygienic (names defined in the macro don't leak to the outer scope, or vice versa).</li>\n<li>They are also scoped, so they don't leak out of the function or module in which they are defined.</li>\n</ul>\n\n<p>As with any form of metaprogramming, it's possible to go overboard, but you shouldn't be afraid of using a macro now and again to reduce repetitive code that can't easily be made into a function or generic. Procedural macros are a different story, but they're even more infrequently needed.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-10T23:15:43.070", "Id": "453190", "Score": "0", "body": "Thank you for such an extensive and detailed reply!\n\nCorrectness: I thought so too, but my group mate guessed that it doesn't make a difference. When the results produced by this program matched theoretical ones, I was convinced. Out of interest I just programmed your version of the solution and the results are the same.\n\nInteger to enum conversions: I can't seem to find any information about enums implementing TryInto trait - it doesn't work, should I derive them from something?\n\nReport: I don't really like macros since I come from c++. Are they widely used by Rust community?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-10T23:15:54.707", "Id": "453191", "Score": "0", "body": "Design concerns: Invalid state is in fact a valid state - state-machine just ignores it because this state breaks rules of the real world(leaving empty chair)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-10T23:58:28.803", "Id": "453197", "Score": "0", "body": "As for \"invalid\" being a valid state - yes, that's my point. If the state can not happen in the scenario being modeled, but it can occur in the machine, the machine is not a good model. I'll take a stab at a more rigorous solution and share it here later." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-11T17:39:34.587", "Id": "453284", "Score": "0", "body": "@rogday I have updated the post with responses to your questions that were in comments previously, and some extra detail. (If you click the \"edited X hours ago\" link you can see what the changes were, so you don't have to read the whole thing again)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-16T02:11:46.760", "Id": "453992", "Score": "1", "body": "@rogday I can always use some practice with C++, so I tried to write this simulator in C++ *as if* in Rust. [Here's what I came up with.](https://gist.github.com/trentj/e6389b268463927b4b8c796ee8a5411f) It is a bit longer than yours, but does some extras, and some of the verbosity is just writing long C++ versions of something that is short in Rust (like `#[derive(Debug)]`). More importantly, it doesn't have a `Dropping` or an `Invalid` state, and it uses `enum class`, no integer conversions. I make no claim about it being *good* (fast, idiomatic) C++ -- I don't specialize in that language." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-16T11:06:39.767", "Id": "454018", "Score": "1", "body": "I need Dropping state to calculate statistics. Also, there is a priority_queue, which doesn't require pop_heap functions. Why don't you like transition table? Isn't it much simpler than nested if statements? Anyway, I was asked not to edit my question, so if you'd like to take a look at my implementation of your treeless way, https://codereview.stackexchange.com/questions/232390/shoe-shine-shop-model-in-rust-and-c-follow-up" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-16T13:08:50.823", "Id": "454030", "Score": "1", "body": "Thanks, I didn't know about `priority_queue`. I actually don't have anything against the transition table, but I do dislike turning `enum`s into integers in order to index it, because it depends on the order of variants in the `enum` and isn't type safe. If you add another state to the machine or decide to reorder them (as I did), the `match` will either fail to compile or continue working exactly as before, whereas the transition table will silently change its behavior, possibly invoking UB, while the compiler at most issues a warning." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-16T13:10:20.277", "Id": "454031", "Score": "0", "body": "I find the state table format to be equally readable which is why I'd go with the `match` in Rust. C++ just doesn't have `match` so I'm stuck with the ugly `if`-`else` tree." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-16T13:18:51.033", "Id": "454032", "Score": "0", "body": "I agree. But what about switch statement?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-16T13:32:21.383", "Id": "454033", "Score": "1", "body": "`switch` doesn't work with non-integers and `enum class`es are not integers. I'd have to go back to regular non-type-safe `enum`s for that to work. (Unless there's a way to make `static_cast` predictable for an `enum class`?) I'd still be stuck with a nested `switch` instead of a nicely formatted state table like in Rust, which partially defeats the purpose. And all the `default:`s and `break;`s that are logically necessary but syntactically optional make `switch` fragile at the best of times. Just doesn't seem worth it to me." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-16T14:05:29.203", "Id": "454035", "Score": "0", "body": "You shouldn't think of `Dropping` as a state, because the machine spends no time in it. You're using it as if it were a state but really it's just a second output from the state machine. [version 2 with drop counting](https://gist.github.com/trentj/e6389b268463927b4b8c796ee8a5411f)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-23T17:13:49.287", "Id": "454929", "Score": "0", "body": "@rogday To correct my earlier comment: [`enum class`es *do* work in a `switch`](https://stackoverflow.com/questions/9062082/switch-statements-with-strongly-typed-enumerations); however, tuples unfortunately do not. Maybe in C++23 or something." } ], "meta_data": { "CommentCount": "12", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-10T00:07:09.247", "Id": "232131", "ParentId": "232106", "Score": "16" } }, { "body": "<p>You’ll often hear Haskel programmers talk about making invalid states impossible to express. The Rust community has taken this to heart and developed <a href=\"https://hoverbear.org/blog/rust-state-machine-pattern/\" rel=\"noreferrer\">a state machine pattern that uses structs and traits rather than enums</a>.</p>\n\n<p>This pattern has many benefits, but to quote some of the main ones from the article:</p>\n\n<blockquote>\n <ul>\n <li>Transition errors are caught at compile time! For example you can't\n even create a Filling state accidentally without first starting with a\n Waiting state. (You could on purpose, but this is beside the matter.)</li>\n <li>Transition enforcement happens everywhere.</li>\n </ul>\n</blockquote>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-11T12:29:11.900", "Id": "453240", "Score": "1", "body": "Thanks for the link on statemachines! it's something I'd be comfortable doing in other languages but this way of handling it in rust is very nice." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-10T10:49:25.597", "Id": "232141", "ParentId": "232106", "Score": "7" } } ]
{ "AcceptedAnswerId": "232131", "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-09T16:07:18.647", "Id": "232106", "Score": "17", "Tags": [ "c++", "comparative-review", "rust", "statistics" ], "Title": "Shoe shine shop model in Rust" }
232106
<p>I am using <code>react-flow-chart</code> for a job project, but it doesn't implement zoom, and I would like to take the reigns and try applying it myself. I took a linear algebra class in college, but I am not very good at transformations. I could make my job a lot easier if I directly use CSS transforms and have it do the heavy lifting for me.</p> <h1>Code</h1> <p>I have put the in a CodeSandbox repo and have organized it as best as I could for clarity, so I recommend viewing the complete code from there, and fork it for significant changes.</p> <h1><a href="https://codesandbox.io/s/agitated-wood-ksfbs?fontsize=14" rel="nofollow noreferrer">https://codesandbox.io/s/agitated-wood-ksfbs?fontsize=14</a></h1> <h2>App.js</h2> <pre class="lang-js prettyprint-override"><code>export const App = () =&gt; { const [squares, setSquares] = useState([[0, 0], [20, 20], [50, 20]]); const [canvasPosition, setCanvasPosition] = useState([0, 0]); const onPositionChanged = R.curry((index, pos) =&gt; { if (index === "canvas") return setCanvasPosition(pos); setSquares(R.update(index, pos)); }); return ( &lt;Canvas position={canvasPosition} onPositionChanged={onPositionChanged} squares={squares} /&gt; ); }; </code></pre> <h2>Canvas.js</h2> <p>This is the part where I calculate each square's position and render it</p> <pre class="lang-js prettyprint-override"><code>const calculateSquarePosition = R.pipe( mult(scale), add(canvas), add(drag) ); const onSquarePositionChanged = index =&gt; R.pipe( add(neg(drag)), add(neg(canvas)), mult(1 / scale), onPositionChanged(index) ); const renderSquare = (pos, index) =&gt; ( &lt;Square key={index} scale={scale} position={calculateSquarePosition(pos)} onPositionChanged={onSquarePositionChanged(index)} /&gt; ); </code></pre> <p>The part where I handle zooming by mouse wheel:</p> <pre class="lang-js prettyprint-override"><code> const onWheel = event =&gt; { const wheelDelta = event.deltaY; const newScale = R.pipe( R.add(wheelDelta * 0.001), clamp(0.2, 8) )(scale); const screenPos = getClientPos(event); const canvasToMouse = add(canvas, neg(screenPos)); const normalizedCanvasToMouse = normalize(canvasToMouse); const distance = length(canvasToMouse); const newDistance = (distance / scale) * newScale; const newCanvasToMouse = mult(newDistance, normalizedCanvasToMouse); const newCanvas = add(screenPos, newCanvasToMouse); onPositionChanged("canvas", newCanvas); setScale(newScale); }; </code></pre> <h1>Explanation</h1> <p>My app consists of a <code>Canvas,</code> which has a specified width and height. I made a <code>useDrag</code> hook that allows it to listen for drag events and gives the <code>drag displacement</code> which can be used to translate the <code>canvas position</code>, which mostly moves all the <code>Square</code>s together (as the <code>Canvas</code> can be considered the parent element). <code>Square</code>s are also draggable.</p> <p>Things get more complicated when the scale is involved as I have to translate view coords to scaled view coords etc. correctly.</p> <p>I want to know what changes I should make to make the transformations, state management, and just the math work for me in the most natural way. I feel like there should a better way, but I am not sure how.</p> <p>The ultimate goal is to transfer what I know into the <code>react-flow-chart</code> and implement the zoom myself, and hopefully give a pull request (my first ever.)</p> <p>Please let me know of <em>anything</em> that could be improved in this code. I welcome any criticism/feedback.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-09T16:34:21.843", "Id": "232108", "Score": "3", "Tags": [ "javascript", "css", "functional-programming", "matrix", "react.js" ], "Title": "How would you convert this code to best take advantage of CSS transform for panning/zooming?" }
232108
<p>I have just created an encryption program with a friend. I wanted to know if anyone here could give me back any feedback on it.</p> <p>Here is how the program works:</p> <p>Imagine you want to encrypt the word 'hi'.</p> <p>Depending on the key generated with the program, the computer will choose between 2 strings of two letters randomly for every letter that needs to be encrypted. The strings are embedded in an encryption/decryption key.</p> <p>Example: 'h' when encrypted will be either 'tn' or 'io', and 'i' when encrypted will be either 'ac' or 'vu'.</p> <p>So when 'hi' will be encrypted, it can be:</p> <p>'tnac'; 'tnvu'; 'ioac'; 'iovu'</p> <p>It is chosen randomly by the computer, so it is impossible to predict what outcome will be.</p> <pre><code>####################################################################### # # # AGENCRYPTION program V.1.1 # # Made by Elio Hayman and Valentino Magniette # # Have fun # # # ####################################################################### version = 'Version 1.1' from random import * import tkinter as tk current_key = '' account = '' in_debug = False def debug(text): if in_debug: print('[Debug]', text) key = '' def decrypt(crypted): debug(crypted) global current_key key = current_key if key == '': print('[Error] Please insert a key before utilisation. To do so, do readkey &lt;yourKey&gt;.') return basemsg = '' key_list = [] while not key == '': key_list.append(key[:5]) key = key[5:] new_key = [] for i in key_list: new_key_thing = [] new_key_thing.append(i[0]) new_key_thing.append(i[1:3]) new_key_thing.append(i[3:]) new_key.append(new_key_thing) key = new_key searchlength = 1 msgleft = crypted found = False while len(msgleft) &gt; 0: searchlength = 0 found = False while found == False: if searchlength == 0 and len(msgleft) &gt; 0: for x in key: if found == False: if msgleft[0] in x[1:]: basemsg = basemsg + x[0] msgleft = msgleft[1:] found = True elif searchlength &gt; 0 and len(msgleft) &gt; 0: for x in key: if found == False: if msgleft[:searchlength-1] in x[1:]: basemsg = basemsg + x[0] msgleft = msgleft[searchlength-1:] found = True searchlength += 1 basemsg = basemsg.replace('^', ' ') return basemsg def encrypt(message): global current_key key = current_key if key == '': print('[Error] Please insert a key before utilisation. To do so, do readkey &lt;yourKey&gt;.') return message = message.replace(' ', '^') endmsg = '' key_list = [] while not key == '': key_list.append(key[:5]) key = key[5:] new_key = [] for i in key_list: new_key_thing = [] new_key_thing.append(i[0]) new_key_thing.append(i[1:3]) new_key_thing.append(i[3:]) new_key.append(new_key_thing) for char in message: for x in new_key: if x[0] == char: endmsg = endmsg + x[randint(1, len(x)-1)] break return endmsg def readkey(input_key): all_chars = 'aabcdefghijklmnopqrstuvwxyz1234567890&amp;²é~"#\'{([-|è`_\\çà@)]=}°+.+-*/,?;:!§ù%*µ$£¤^¨ABCDEFGHIJKLMNOPQRSTUVWXYZ' key_list = [] if len(input_key) == 779: print('Key loading...') parts = list() for i in range(109): key_part = input_key[:5] letter = key_part[0] part1 = key_part[1:3] part2 = key_part[3:5] list_thing = list() list_thing.append(letter) list_thing.append(part1) list_thing.append(part2) parts.append(input_key[:5]) input_key = input_key[5:] print('Key inserted') print('Caution, this key will only stay in the program as long as it is running or when replaced by another one') else: print('[Error] This key is unsupported by the program. Make sure it is correct and that you are using the latest version.') return None return ''.join(parts) def genkey(): all_chars = 'aabcdefghijklmnopqrstuvwxyz1234567890&amp;²é~"#\'{([-|è`_\\ç^à@)]=}°+.+-*/,?;:!§ù%*µ$£¤^¨ABCDEFGHIJKLMNOPQRSTUVWXYZ' char_list = list('aabcdefghijklmnopqrstuvwxyz1234567890&amp;²é~"#\'{([-|è`_\\ç^à@)]=}°+.+-*/,?;:!§ù%*µ$£¤^¨ABCDEFGHIJKLMNOPQRSTUVWXYZ') shuffle(char_list) all_chars = ''.join(char_list) key = list() security = 2 for x in range(len(all_chars)*security): valid = False while valid == False: char1 = all_chars[randint(0,35)] char2 = all_chars[randint(0,35)] if not (char1 + char2) in key: key.append(char1 + char2) valid = True speshul_chars_letters = list() for i in range(117): valid = False while valid == False: char1 = all_chars[randint(0,35)] char2 = all_chars[randint(0,35)] if not (char1 + char2) in key or (char1 + char2) in speshul_chars_letters: speshul_chars_letters.append(char1 + char2) valid = True key_list = [] for i in all_chars: chars = [i] for xx in range(security): chars.append(key[0]) del key[0] key_list.append(chars) key_text = '' key_text_list = [] for y in key_list: key_text_list.append(''.join(y)) speshul_chars_letters_text = ''.join(speshul_chars_letters) return ''.join(key_text_list) + speshul_chars_letters_text import tkinter as tk from time import * mw = tk.Tk() mw.title('AGE v1.1') mw.geometry("800x500") mw.resizable(0, 0) back = tk.Frame(master=mw,bg='#24b1db') back.pack_propagate(0) back.pack(fill=tk.BOTH, expand=1) mode = 0 def purgescreen(): if mode == 1: encryption_text_input.destroy() encryption_text_output.destroy() encrypt_main.destroy() elif mode == 2: decryption_text_input.destroy() decryption_text_output.destroy() decrypt_main.destroy() elif mode == 3: keygen_text_output.destroy() keygen_main.destroy() directapply_main.destroy() elif mode == 4: keyread_text_input.destroy() keyread_main.destroy() elif mode == 5: info_main.destroy() info_copyright.destroy() info_website.destroy() info_terms.destroy() info_version.destroy() elif mode == 6: help_main.destroy() elif mode == 7: welcome_main.destroy() def encrypt_shortcut(): message = encryption_text_input.get("1.0",'end-1c') encrypted = encrypt(message) encryption_text_output.delete("1.0","end") encryption_text_input.delete("1.0","end") encryption_text_output.insert("1.0",encrypted) def encryption_button(): global encryption_text_input global encryption_text_output global encrypt_main global mode purgescreen() mode = 1 encryption_text_input = tk.Text(back, height=10, width=70) encryption_text_input.place(relx=.25 , rely=0) encryption_text_output = tk.Text(back, height=10, width=70) encryption_text_output.place(relx=.25, rely=.6) encrypt_main = tk.Button(master=back, text='Encrypt', command=encrypt_shortcut) encrypt_main.config(height=3, width=15) encrypt_main.place(relx=.5, rely=.4) def decrypt_shortcut(): message = decryption_text_input.get("1.0",'end-1c') decrypted = decrypt(message) decryption_text_output.delete("1.0","end") decryption_text_input.delete("1.0","end") decryption_text_output.insert("1.0",decrypted) def decryption_button(): global decryption_text_input global decryption_text_output global decrypt_main global mode purgescreen() mode = 2 decryption_text_input = tk.Text(back, height=10, width=70) decryption_text_input.place(relx=.25 , rely=0) decryption_text_output = tk.Text(back, height=10, width=70) decryption_text_output.place(relx=.25, rely=.6) decrypt_main = tk.Button(master=back, text='Decrypt', command=decrypt_shortcut) decrypt_main.config(height=3, width=15) decrypt_main.place(relx=.5, rely=.4) def keygen_shortcut(): key = genkey() key = ''.join(key) keygen_text_output.delete("1.0",'end') keygen_text_output.insert("1.0",key) def apply_shortcut(): key = keygen_text_output.get("1.0","end-1c") global current_key current_key = key def keygen_button(): global keygen_text_output global keygen_main global mode global directapply_main purgescreen() mode = 3 keygen_text_output = tk.Text(back, height=15, width=70) keygen_text_output.place(relx=.25 , rely=.4) keygen_main = tk.Button(master=back, text='Generate Key', command=keygen_shortcut) keygen_main.config(height=3, width=15) keygen_main.place(relx=.4, rely=.2) directapply_main = tk.Button(master=back, text='Apply Key', command=apply_shortcut) directapply_main.config(height=3, width=15) directapply_main.place(relx=.6, rely=.2) def keyread_shortcut(): key = keyread_text_input.get("1.0","end-1c") keyread_text_input.delete("1.0","end") global current_key current_key = key def keyread_button(): global keyread_text_input global keyread_main global mode purgescreen() mode = 4 keyread_text_input = tk.Text(back, height=15, width=70) keyread_text_input.place(relx=.25, rely=.1) keyread_main = tk.Button(master=back, text='Insert Key', command=keyread_shortcut) keyread_main.config(height=3, width=15) keyread_main.place(relx=.5, rely=.7) def info_button(): global info_main global info_copyright global info_website global info_version global info_terms global mode purgescreen() mode = 5 info_main = tk.Label(master=back, text='This program is made by \n Valentino Magniette and iWaroz.', bg='#24b1db') info_main.config(height=3, width=70) info_main.place(relx=.25, rely=.1) info_copyright = tk.Label(master=back, text='Copying this program or resseling it \n without permission from its creators is forbidden.', bg='#24b1db') info_copyright.config(height=3, width=70) info_copyright.place(relx=.25, rely=.3) info_terms = tk.Label(master=back, text='AGencryption and its creators are not responsible for any legal problems regarding \n encrypting sensible documentation that the authorities want decrypted. ', bg='#24b1db') info_terms.config(height=3, width=70) info_terms.place(relx=.25, rely=.5) info_website = tk.Label(master=back, text='You can get the program for free at: http://realtasting.com/AGE-Version1.exe', bg='#24b1db') info_website.config(height=3, width=70) info_website.place(relx=.25, rely=.7) info_version = tk.Label(master=back, text='Version 1.1', bg='#24b1db') info_version.config(height=3, width=70) info_version.place(relx=.25, rely=.9) def help_button(): global help_main global mode purgescreen() mode = 6 help_main = tk.Label(master=back, text='If any help is needed. \n Go to our discord with the link \n https://discord.gg/YVDBudA', bg='#24b1db') help_main.config(height=3, width=50) help_main.place(relx=.35, rely=.5) global welcome_main purgescreen() mode = 7 welcome_main = tk.Label(master=back, text='Welcome to AGE \n This is a program which is used for encryption \n You can encrypt an unlimited ammount of text securely for free \n To start, you will need an encryption/decryption key for it to work \n Have fun!!', bg='#24b1db') welcome_main.config(height=10, width=50) welcome_main.place(relx=.35, rely=.35) encryption_main = tk.Button(master=back, text='Encryption', command=encryption_button) encryption_main.config(height=4, width=20) encryption_main.place(relx=.095, rely=.07, anchor="c") decryption_main = tk.Button(master=back, text='Decryption', command=decryption_button) decryption_main.config(height=4, width=20) decryption_main.place(relx=.095, rely=.21, anchor="c") generator_main = tk.Button(master=back, text='Key Generator', command=keygen_button) generator_main.config(height=4, width=20) generator_main.place(relx=.095, rely=.35, anchor="c") reader_main = tk.Button(master=back, text='Key reader', command=keyread_button) reader_main.config(height=4, width=20) reader_main.place(relx=.095, rely=.49, anchor="c") information_main = tk.Button(master=back, text='Information', command=info_button) information_main.config(height=4, width=20) information_main.place(relx=.095, rely=.63, anchor="c") help_main = tk.Button(master=back, text='Help', command=help_button) help_main.config(height=4, width=20) help_main.place(relx=.095, rely=.77, anchor="c") quit_main = tk.Button(master=back, text='Quit', command=mw.destroy) quit_main.config(height=4, width=20) quit_main.place(relx=.095, rely=.91, anchor="c") mw.mainloop() <span class="math-container">```</span> </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-10T01:38:01.097", "Id": "453117", "Score": "11", "body": "The encryption is not secure; it could be defeated using frequency analysis. But I'm guessing you knew it might not be secure and did it for fun anyway." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-10T08:10:40.950", "Id": "453136", "Score": "0", "body": "`Here is how the program works` describing this is not half bad. If you added the purpose of this code (may be as mundane as *completing a practice programming project*), it may be easier to give advice (such as *putting information **in** the source code makes it less likely that code snippets float around lacking that information*)." } ]
[ { "body": "<p>First, congratulations! Being able to produce something usable with another person is an incredibly important skill, and especially in programming. Please don't worry about the amount of suggestions below – I'm treating this like any other Python review.</p>\n\n<h2>Specific suggestions</h2>\n\n<ol>\n<li><p>Module documentation, like the lines at the top of your file, is usually written within triple double quotes, like this:</p>\n\n<pre><code>\"\"\"\nAGENCRYPTION […]\n\"\"\"\n</code></pre>\n\n<p>You can also use this to write multi-line strings without having to embed <code>\\n</code> escape characters within them.</p></li>\n<li>It would be handy to be able to set the debugging flag from the command line rather than having to modify the code. You can do that by using either <a href=\"https://docs.python.org/3/library/argparse.html\" rel=\"noreferrer\"><code>argparse</code></a> to add a <code>--debug</code> flag or by checking whether <code>os.environ[\"DEBUG\"]</code> is not empty.</li>\n<li><code>from [something] import *</code> is a handy shortcut, but it makes the code harder to read. Consider when you're looking at a line containing a call to <code>randint</code> somewhere. You might want to see how <code>randint</code> is implemented, to understand whether it's doing what you expect. To do so in a simple text editor you would have to first search for the string \"randint\", and once you confirm that it's not defined locally you'd have to look through each of the <code>*</code> imports to see where it's defined. If you <code>from random import randint</code> instead it's really easy to find.</li>\n<li>Using <code>global</code> can also be handy, but it makes the interactions between the various parts of your code much harder to understand. The standard fix for this is to simply remove a single mention of the <code>global</code> keyword and instead pass parameters around until each piece of code gets exactly what it needs from the caller. You can then repeat this until there are no more globals.</li>\n<li>The string consisting of all valid key characters is repeated a few times. If you pull it out into a constant such as <code>KEY_CHARACTERS = \"[…]\"</code> at the top of your file you can just refer to that in the rest of your code.</li>\n<li>This program mixes GUI (TK) code with encryption code. It would be good to split the GUI code into its own file, and importing the relevant functions there. This makes it possible to understand and use the encryption code on its own, for example if you want to create a GUI with a different toolkit.</li>\n<li><p>If you try to import your file in another file Python will actually <em>run</em> the code. This which means the code isn't actually reusable. The way to work around this is to create a <code>main</code> function in your file and call it only when your script is run from the shell:</p>\n\n<pre><code>if __name__ == \"__main__\":\n main()\n</code></pre>\n\n<p>Your <code>main</code> function actually does the work of instantiating and running the GUI, which means the various functions can be imported without side effects.</p></li>\n<li><code>\"\".join(key)</code> should be unnecessary, because <code>genkey</code> already returns a string.</li>\n<li>The various modes should probably be an <a href=\"https://docs.python.org/3/library/enum.html\" rel=\"noreferrer\"><code>enum</code></a> with values like <code>ENCRYPTION</code> and <code>DECRYPTION</code> - that way the \"magic numbers\" assigned to <code>mode</code> are instead human readable variable references such as <code>modes.ENCRYPTION</code>.</li>\n<li>You probably already know this, but I need to warn about it just in case: you should not use this code to transfer actual secrets. Cryptography is really, really difficult, and there are existing systems like PGP (available from tools like <code>gnupg</code>) to do this. If you want to know how they work there is a lot of advanced maths and difficult code involved.</li>\n</ol>\n\n<h2>Tool support suggestions</h2>\n\n<ol>\n<li><a href=\"https://github.com/ambv/black\" rel=\"noreferrer\"><code>black</code></a> can automatically format your code to be more idiomatic. It'll do things like adjusting the vertical and horizontal spacing, while keeping the functionality of the code unchanged.</li>\n<li><a href=\"https://pypi.org/project/isort/\" rel=\"noreferrer\"><code>isort</code></a> can group imports (built-ins first, then libraries and finally imports from within your project) and sort them.</li>\n<li><p><a href=\"https://gitlab.com/pycqa/flake8\" rel=\"noreferrer\"><code>flake8</code></a> can give you more hints to write idiomatic Python:</p>\n\n<pre><code>[flake8]\nmax-complexity = 4\nignore = W503,E203\n</code></pre></li>\n<li><p>I would then recommend validating your <a href=\"https://docs.python.org/3/library/typing.html\" rel=\"noreferrer\">type hints</a> using a strict <a href=\"https://github.com/python/mypy\" rel=\"noreferrer\"><code>mypy</code></a> configuration:</p>\n\n<pre><code>[mypy]\ncheck_untyped_defs = true\ndisallow_any_generics = true\ndisallow_untyped_defs = true\nignore_missing_imports = true\nno_implicit_optional = true\nwarn_redundant_casts = true\nwarn_return_any = true\nwarn_unused_ignores = true\n</code></pre>\n\n<p>This ensures that anyone reading the code (including yourself) understand how it's meant to be called, which is very powerful in terms of modifying and reusing it. For example, it looks like the <code>genkey</code> signature should be <code>def genkey() -&gt; str:</code> to show that it returns a string, and <code>debug</code>'s signature should be <code>def debug(text: str) -&gt; None:</code> to show that it takes a string (as opposed to for example <code>bytes</code> or <code>StringIO</code>) and does not return anything.</p></li>\n</ol>\n\n<h2>General suggestions</h2>\n\n<ol>\n<li>Using a free IDE like PyCharm Community or Visual Studio Code is incredibly helpful to write non-trivial code. I can't possibly go into detail here, but if you explore an IDE you'll find literally hundreds of helpful features, such as highlighting unused variables, automatically pulling out variables and inlining them, and spell checking.</li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-10T12:37:27.317", "Id": "453145", "Score": "1", "body": "\"The standard fix for this is to simply remove a single mention of the global keyword and instead pass parameters around until each piece of code gets exactly what it needs from the caller\". I'd say the given code is a great example of how classes can vastly simplify the code and make it more structured *and* avoid the use of global.. having a dozen parameters on a function isn't particularly great either." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-10T18:59:54.003", "Id": "453171", "Score": "1", "body": "@Voo Good point. I avoided mention of OOP here because I thought it would be appropriate for a follow-up review once OP gets rid of all the globals. Moving directly from globals to OOP is two steps in one go IMO, and that's often harmful in terms of coming up with a good structure." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-09T21:06:42.660", "Id": "232123", "ParentId": "232110", "Score": "18" } }, { "body": "<p>In addition to the <a href=\"https://codereview.stackexchange.com/a/232123/15863\">great answer</a> already provided by <a href=\"https://codereview.stackexchange.com/users/716/l0b0\">l0b0</a>, a few comments.</p>\n\n<h2>1. code structure</h2>\n\n<p>Some blocks could be extracted to functions. For instance, the following block inside <code>encrypt</code>:</p>\n\n<pre><code> new_key_thing = []\n new_key_thing.append(i[0])\n new_key_thing.append(i[1:3])\n new_key_thing.append(i[3:])\n new_key.append(new_key_thing)\n</code></pre>\n\n<p>Could be refactored to:</p>\n\n<pre><code>new_key.append(do_transformation(i))\n</code></pre>\n\n<p>Re-iterating on the new code, you could use Python's <code>map</code> operation, which is very handy, or you could use Python's cool feature of <a href=\"https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions\" rel=\"noreferrer\">list comprehension</a>. Here's an example of refactoring (note that I also renamed from <code>i</code>, which is more used to be an index number to <code>k</code>, which indicates it's a key):</p>\n\n<pre><code>newkey = [do_transformation(k) for k in key_list]\n</code></pre>\n\n<h2>2. Magic numbers</h2>\n\n<p>In some places the code includes magic numbers like 3, 5 and more. Instead of using those numbers as are, try to give them meaningful names.</p>\n\n<p>For instance, dealing with magic number 5 (I hope I got the intention correctly, but even if that's not the case, you can see what the general idea is):</p>\n\n<pre><code>CHUNK_SIZE = 4 \n\nwhile not key == '':\n key_list.append(key[:(CHUNK_SIZE + 1)])\n key = key[(CHUNK_SIZE + 1):]\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-09T22:06:16.127", "Id": "232127", "ParentId": "232110", "Score": "12" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-09T17:07:50.560", "Id": "232110", "Score": "13", "Tags": [ "python", "beginner", "cryptography" ], "Title": "A randomized encryption program" }
232110
<p>I'm currently learning about Entity-Component-System architecture Data-Driven design as a way to counter bad OOP design and optimize data fetching as a CPU friendly operation.</p> <p>I'm trying to write a simple ECS system that tries to follows these principals:</p> <ul> <li>CPU friendly by storing entities/components in contiguous chunk of memory and minimize cache miss</li> <li>Not set an upper bound to number of entities/components/systems in the system</li> </ul> <p>My basic implementation so far is as follows:</p> <p><code>Entity</code> class with a counting <code>m_ID</code> member being incremented for each newly created entity.</p> <p>An <code>std::vector&lt;Entity*&gt;</code> for containing children entities.</p> <p>A <code>std::vector&lt;bool&gt;</code> for containing the signature of what components the entity uses. I've chosen <code>std::vector&lt;bool&gt;</code> over <code>std::bitset&lt;S&gt;</code> since I wish to be able as a requirement to add/remove components in runtime and I do not wish to set an upper-bound to the size of components an entity have so I cannot know size in compile time, so I've decided to use the <code>std::vector&lt;bool&gt;</code> specialization that stores each <code>bool</code> as 1 bit which save some space and allows for growth.</p> <p>An <code>std::unordered_map&lt;unsigned int, unsigned int&gt;</code> where the key is the component's ID and the value is an index into a <code>std::vector&lt;unsigned int, std::vector&lt;ComponentBase&gt;&gt;</code> map of component's ID to components vector residing in <code>ECSManager</code> class.</p> <p><code>Component</code> class with a unique ID per component type using templates to generate a unique <code>Component&lt;T&gt;::ID</code> for each component type.</p> <p><code>System</code> class containing <code>std::vector&lt;bool&gt;</code> responsible for holding the signature of what entities the system wants to operate on depends on if they have a sufficient components signature.</p> <p>Now I'm sure my implementation is not nearly close to what my requirements are, for example I'm not really sure if it's CPU friendly as an ECS should be since I rely heavily on <code>std::unordered_map</code> which is implemented by a linked list. But to be honest I'm not sure at all so this is why I'm posting my implementation here hoping for a feedback on what's good and what's not and how I can maybe make it better.</p> <p><code>ComponentBase.h</code>:</p> <pre><code>#pragma once #include &lt;atomic&gt; static std::atomic&lt;unsigned int&gt; s_CurrentId; class ComponentBase { public: inline static unsigned GetID() { return ++s_CurrentId; } }; </code></pre> <p><code>Component.h</code>:</p> <pre><code>#pragma once #include "ComponentBase.h" template &lt;typename T&gt; class Component : public ComponentBase { public: static const unsigned int ID = ComponentBase::GetID(); }; </code></pre> <p><code>Entity.h</code>:</p> <pre><code>#pragma once #include &lt;vector&gt; #include &lt;unordered_map&gt; class Entity { private: unsigned int m_Id; std::vector&lt;Entity*&gt; m_Children; std::vector&lt;bool&gt; m_Signature; std::unordered_map&lt;unsigned int, unsigned int&gt; m_ComponentsIndex; protected: Entity(); friend class ComponentManager; friend class Scene; public: Entity(const Entity&amp; other) = delete; virtual ~Entity(); Entity&amp; operator=(const Entity&amp; other) = delete; inline unsigned int GetID() { return m_Id; } void AddChild(Entity* entity); inline const std::vector&lt;Entity*&gt;&amp; GetChildren() const { return m_Children; } void AddComponent(unsigned int componentID, unsigned int index); void RemoveComponent(unsigned int componentID); inline const std::vector&lt;bool&gt;&amp; GetSignature() const { return m_Signature; } inline const std::unordered_map&lt;unsigned int, unsigned int&gt;&amp; GetComponentsIndex() const { return m_ComponentsIndex; } }; </code></pre> <p><code>Entity.cpp</code>:</p> <pre><code>#include "Entity.h" #include &lt;atomic&gt; static std::atomic&lt;unsigned int&gt; s_CurrentId; Entity::Entity() : m_Id(s_CurrentId++) { } Entity::~Entity() { for (const auto&amp; child : m_Children) delete child; } void Entity::AddChild(Entity* entity) { m_Children.push_back(entity); } void Entity::AddComponent(unsigned int componentID, unsigned int index) { m_Signature[componentID] = true; m_ComponentsIndex[componentID] = index; } void Entity::RemoveComponent(unsigned int componentID) { m_Signature[componentID] = false; m_ComponentsIndex.erase(componentID); } </code></pre> <p><code>System.h</code>:</p> <pre><code>#pragma once #include &lt;vector&gt; #include "Entity.h" class System { private: std::vector&lt;bool&gt; m_ComponentIDs; protected: System(std::vector&lt;unsigned int&gt;&amp; componentIDs); public: virtual ~System(); virtual void Update() = 0; }; </code></pre> <p><code>System.cpp</code>:</p> <pre><code>#include "System.h" System::System(std::vector&lt;unsigned int&gt;&amp; componentIDs) { for (const auto&amp; componentID : componentIDs) m_ComponentIDs[componentID] = true; } System::~System() { } </code></pre> <p><code>ECSManager.h</code>:</p> <pre><code>#pragma once #include &lt;vector&gt; #include &lt;unordered_map&gt; #include "../Entity.h" #include "ComponentBase.h" class ECSManager { private: std::unordered_map&lt;unsigned int, std::vector&lt;ComponentBase&gt;&gt; m_Components; std::unordered_map&lt;unsigned int, Entity&gt; m_Entities; private: ECSManager(); public: const Entity&amp; CreateEntity() { Entity e; m_Entities.emplace(e.GetID(), std::move(e)); return m_Entities[e.GetID()]; } template &lt;typename TComponent, typename... Args&gt; void AddComponent(unsigned int entityId, Args&amp;&amp;... args) { unsigned int componentID = TComponent::ID; if (m_Components[componentID] == m_Components.end()) m_Components[componentID] = std::vector&lt;TComponent&gt;(); m_Components[componentID].push_back(T(std::forward&lt;Args&gt;(args)...)); m_Entities[entityId].AddComponent(componentID, m_Components[componentID].size() - 1); if (m_Signatures[m_Entities[entityId].GetSignature()] == m_Signatures.end()) m_Signatures[m_Entities[entityId].GetSignature()] = std::vector&lt;unsigned int&gt;(); m_Signatures[m_Entities[entityId].GetSignature()].push_back(entityId); } template &lt;typename TComponent&gt; TComponent&amp; GetComponent(Entity&amp; entity) { return m_Components[TComponent::ID][entity.GetComponentsIndex()[TComponent::ID]]; } template &lt;typename TComponent&gt; std::vector&lt;TComponent&gt;&amp; GetComponents() { unsigned int componentID = TComponent::ID; return m_Components[componentID]; } std::vector&lt;Entity&amp;&gt; GetEntities(std::vector&lt;bool&gt; componentIDs) { std::vector&lt;Entity&amp;&gt; entities; for (auto&amp; entity : m_Entities) { const auto&amp; entitySignature = entity.second.GetSignature(); if (componentIDs.size() &gt; entitySignature.size()) continue; bool equal = true; for (std::size_t i = 0; i != componentIDs.size(); i++) { if (componentIDs[i] &amp; entitySignature[i] == 0) { equal = false; break; } } if (!equal) continue; entities.push_back(entity.second); } return entities; } }; <span class="math-container">```</span> </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-11T18:11:24.087", "Id": "453288", "Score": "0", "body": "\"*CPU friendly by storing entities/components in contiguous chunk of memory and minimize cache miss*\" and \"*An `std::vector<Entity*>` for containing children entities*\" do not go together. It doesn't help that your `Entity*`s are neatly organized in contiguous memory when you must dereference them and the `Entity`s are all over the place because you used dynamic memory. If you do it \"correctly\" the ECS will have no inheritance at all. You do not need `ComponentBase`. `template <class Component> std::vector<Component> components;` is your friend." } ]
[ { "body": "<ol>\n<li>Since class <code>Entity</code> deletes its children in the destructor - it has ownership over the data. According to modern C++ guidelines you don't pass ownership via raw pointers nor class should own any data it has only a raw pointer to (except for most basic classes I suppose). Use <code>std::unique_ptr&lt;Entity&gt;</code> instead of <code>Entity*</code> - besides safety it will automatically implement your custom trivial destructor. It will also automatically mark your class <code>Entity</code> to be non-copyable.</li>\n<li>Just write <code>virtual ~System() = default;</code> instead of making a custom empty constructor in .cpp.</li>\n<li><code>System(std::vector&lt;unsigned int&gt;&amp; componentIDs);</code> replace with <code>System(const std::vector&lt;unsigned int&gt;&amp; componentIDs);</code> since it doesn't modify <code>componentIDs</code>.</li>\n<li>Template function <code>AddComponent</code> doesn't compile or work. Your compiler might not scream since you don't use it at any point in your code but it is wrong in many places. Core review is for reviewing working code not debugging non-working code.</li>\n<li>There is something terribly wrong with your approach to the <code>ECSManager::m_Components</code>. It won't do what you want it to do.</li>\n<li><code>std::vector&lt;Entity&amp;&gt;</code> doesn't compile... <code>std::vector</code> cannot hold native references. Use <code>std::reference_wrapper</code> for it.</li>\n</ol>\n\n<p>I assume there many other errors. Please test your code prior to posting it on code review. If you fail to make something work, you can post it on StackOverflow first.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-09T17:59:10.313", "Id": "453081", "Score": "0", "body": "Thanks for the feedback, about the `AddComponent` why wouldn't it work, and what so terrible about `ECSManager::m_Components` is terribly wrong? Also about `std::vector<Entity&>` this you're right. But besides that you I'm looking for more feedback regarding to the requirements of the ECS system less so much about the nitty gritty things of cpp like default destructors and what not." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-09T18:06:21.233", "Id": "453083", "Score": "0", "body": "@Jorayen `AddComponent` simply doesn't compile and I assume you want `m_Components` to reference some other type but it stores only base type. You lose all the components' info. You ought to store them via a pointers." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-09T18:08:48.673", "Id": "453084", "Score": "0", "body": "Oh should've made it `std::unordered_map<unsigned int, std::vector<ComponentBase*>> m_Components;` my bad" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-09T17:47:18.837", "Id": "232114", "ParentId": "232111", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-09T17:07:54.993", "Id": "232111", "Score": "1", "Tags": [ "c++", "c++11", "design-patterns", "entity-component-system" ], "Title": "How well does this ECS implementation follow these principles?" }
232111
<p>I'm working on a site where you can read about different songs, listen to them, rate them etc, same with their singer.</p> <p>I've been thinking about how I could create a simple, yet perfectly working pagination script using PHP, and yesterday at night I came up with the code which you will see below.</p> <p>So first this is the final result of the code below:</p> <p><strong>Desktop view</strong></p> <p><a href="https://i.stack.imgur.com/TibW6.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/TibW6.jpg" alt="enter image description here"></a> </p> <p><strong>Mobile view</strong></p> <p><a href="https://i.stack.imgur.com/BhoXN.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/BhoXN.jpg" alt="enter image description here"></a></p> <p>The <code>function</code> which returns the number of comments:</p> <pre><code>function countComments($ID,$table){ $st=$this-&gt;conn-&gt;prepare("SELECT COUNT(*) FROM ".$table."_comments WHERE ".$table."ID=?"); $st-&gt;execute([$ID]); return $st-&gt;fetchall(); } </code></pre> <hr> <p>Deciding which table to choose the comments from, based on which <code>ID</code> is set, song or singer:</p> <pre><code>if(isset($_GET['songid'])){ $table="song"; $ID=$_GET['songid']; } else{ $table="singer"; $ID=$_GET['singerid']; } </code></pre> <hr> <p>Storing the number of comments in the <code>total</code> variable, then setting <code>all</code> variable equal with <code>total</code>:</p> <pre><code>$countComments=$comments-&gt;countComments($ID,$table); $total; foreach($countComments as $key){ $total=$key[0]; } $all=$total; </code></pre> <hr> <p>Then counting the number of pages:</p> <pre><code>$page=1; $limit_end=15; $limit_start=($_GET['page']*$limit_end)-$limit_end; while($all&gt;$limit_end){ $page++; $all-=$limit_end; } $all_pages=$page; $page_diff=$all_pages-$_GET['page']; </code></pre> <hr> <p>Defining the links, based on which <code>ID</code> is set, song or singer:</p> <pre><code>if(isset($_GET['songid'])){ $next_link="/comments/song/".$_GET['songid']."/".($_GET['page']+1); $prev_link="/comments/song/".$_GET['songid']."/".($_GET['page']-1); $next_next_link="/comments/song/".$_GET['songid']."/".($_GET['page']+2); $prev_prev_link="/comments/song/".$_GET['songid']."/".($_GET['page']-2); $last_link="/comments/song/".$_GET['songid']."/".$page; $first_link="/comments/song/".$_GET['songid']."/1"; } else{ $next_link="/comments/singer/".$_GET['singerid']."/".($_GET['page']+1); $prev_link="/comments/singer/".$_GET['singerid']."/".($_GET['page']-1); $next_next_link="/comments/singer/".$_GET['singerid']."/".($_GET['page']+2); $prev_prev_link="/comments/singer/".$_GET['singerid']."/".($_GET['page']-2); $last_link="/comments/singer/".$_GET['singerid']."/".$page; $first_link="/comments/singer/".$_GET['singerid']."/1"; } </code></pre> <hr> <p>Here's the <code>function</code> that returns with the page buttons, using <code>Heredoc</code>:</p> <pre><code>function pageButtons($link,$page,$button_class,$mobile){ return &lt;&lt;&lt;HTML &lt;a href="{$link}"&gt; &lt;button type="button" class="btn btn-sm {$button_class} page-buttons"&gt; &lt;span class="d-none d-lg-block"&gt; {$page} &lt;/span&gt; &lt;span class="d-block d-lg-none font-weight-bold"&gt; {$mobile} &lt;/span&gt; &lt;/button&gt; &lt;/a&gt; HTML; } </code></pre> <hr> <p>And finally the code which shows the result:</p> <pre><code>&lt;div class="text-center m-2 page-buttons-container"&gt; &lt;span&gt; &lt;span class="font-weight-bold"&gt; &lt;?php echo $all_pages; ?&gt; &lt;/span&gt; &lt;span&gt; pages &lt;/span&gt; &lt;/span&gt; &lt;br&gt; &lt;?php if($_GET['page']&gt;1){ if(($_GET['page']+1)-3&gt;1){ echo $comments-&gt;pageButtons($first_link,"First","btn-outline-light","&lt;i class='fas fa-angle-double-left'&gt;&lt;/i&gt;"); } if(($_GET['page']+1)-1&gt;1){ echo $comments-&gt;pageButtons($prev_link,"Prev","btn-outline-light","&lt;i class='fas fa-angle-left'&gt;&lt;/i&gt;"); } if(($_GET['page']+1)-2&gt;1){ echo $comments-&gt;pageButtons($prev_prev_link,$_GET['page']-2,"btn-outline-light",$_GET['page']-2); } if(($_GET['page']+1)-1&gt;1){ echo $comments-&gt;pageButtons($prev_link,$_GET['page']-1,"btn-outline-light",$_GET['page']-1); } } ?&gt; &lt;select class="form-control m-0 p-0 d-inline bg-transparent text-info border-info all-pages"&gt; &lt;?php for ($i=1; $i &lt; $all_pages+1; $i++) { ?&gt; &lt;option class="text-dark" &lt;?php if($_GET['page']==$i){ echo "selected"; } ?&gt; value="&lt;?php echo isset($_GET['songid'])?'/comments/song/':'/comments/singer/'; echo isset($_GET['songid'])?$_GET['songid']:$_GET['singerid']; echo'/'.$i; ?&gt;"&gt; &lt;?php echo $i; ?&gt; &lt;/option&gt; &lt;?php } ?&gt; &lt;/select&gt; &lt;?php if($all_pages&gt;$_GET['page']){ if($page_diff&gt;=1){ echo $comments-&gt;pageButtons($next_link,$_GET['page']+1,"btn-outline-light",$_GET['page']+1); } if($page_diff&gt;=2){ echo $comments-&gt;pageButtons($next_next_link,$_GET['page']+2,"btn-outline-light",$_GET['page']+2); } if($page_diff&gt;=1){ echo $comments-&gt;pageButtons($next_link,"Next","btn-outline-light","&lt;i class='fas fa-angle-right'&gt;&lt;/i&gt;"); } if($page_diff&gt;=3){ echo $comments-&gt;pageButtons($last_link,"Last","btn-outline-light","&lt;i class='fas fa-angle-double-right'&gt;&lt;/i&gt;"); } } ?&gt; &lt;/div&gt; </code></pre> <p>There's a short Jquery code for the <code>select</code> to work, which is the following:</p> <pre><code> $(".all-pages").on("change",function(){ $(this).find("option").each(function(){ if($(this).is(":selected")){ location.href=$(this).attr("value"); } }); }); </code></pre> <p>And a little bit of CSS</p> <pre><code>@media (max-width: 776px){ .page-buttons-container .page-buttons{ width:20px !important; border-radius: 100% !important; padding:0 !important; } .all-pages{ border-radius: 100%; width: 25px; height:25px; border-width: 2px; } } .all-pages { -webkit-appearance: none; -moz-appearance: none; text-indent: 1px; text-overflow: ''; text-indent: 8px; width: 30px; height:30px; border-width: 2px; } </code></pre> <p>I'd like to ask your opinion/review on this code. Is it good enough, or there are still ways to improve it, make it simpler, more understandable/readable, or anything else?</p> <p>If you have any questions, or you don't understand something in the code, feel free to ask it.</p>
[]
[ { "body": "<p>First of all, it is very good you decided to ask.<br>\nAlso, it is also very good you are using count(*) to get the count. </p>\n\n<p>For the rest follow the review.</p>\n\n<ol>\n<li><p>There must be a single table with comments where the comment type is distinguished by means a dedicated field. Which makes your code would be</p>\n\n<pre><code>function countComments($ID, $type){\n $st = $this-&gt;conn-&gt;prepare(\"SELECT COUNT(*) FROM comments WHERE ID=? and type=?\");\n $st-&gt;execute([$ID, $type]);\n return $st-&gt;fetchColumn();\n}\n</code></pre></li>\n<li><p>The code to get <code>$total</code> variable a good example of a cargo cult code.</p>\n\n<ul>\n<li>why define $total if it gets assigned the line below? </li>\n<li>why loop over a result that contains only one row? </li>\n<li>I don't really get why do you need <code>$all</code> variable</li>\n<li><p>Finally, <a href=\"https://phpdelusions.net/pdo#fetchcolumn\" rel=\"nofollow noreferrer\">PDO supports different fetch types</a>, there is no point in using fetchAll() in <code>countComments</code>(). So the code should be just</p>\n\n<pre><code>$total = $comments-&gt;countComments($ID, $type);\n</code></pre></li>\n</ul></li>\n<li><p>I don't really get what does your counting the number of pages do, but all examples I've seen are doing it in a single move, </p>\n\n<pre><code>$all_pages = ceil($total/$per_page);\n</code></pre></li>\n<li><p>The code in Defining the links is essentially duplicated. Why not to define only different parts and then have a single block of code</p>\n\n<pre><code>$type = isset($_GET['songid']) ? 'song' : 'singer';\n$id = $_GET[$type.'id'];\n$base_link = \"/comments/$type/$id/\";\n\n$next_link = $base_link.($_GET['page']+1);\n$prev_link = $base_link.($_GET['page']-1);\n$next_next_link = $base_link.($_GET['page']+2);\n$prev_prev_link = $base_link.($_GET['page']-2);\n$last_link = $base_link.$page;\n$first_link = $base_link.\"1\";\n</code></pre></li>\n</ol>\n\n<p>That's for starter, hope someone will cover the rest</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-09T18:21:39.903", "Id": "453085", "Score": "0", "body": "Thank you for ypur answer, the code you provided definitely are better and simpler, especially the 4th one with the links, I really like it. I've realized I overcomplicated things, like counting the pages. About merging the two tables: it's been in plan for a while, and I wanted to solve it the same way you did. I've already did it with other tables(like comment reports), but I really just forgot about this one." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-09T17:50:43.493", "Id": "232115", "ParentId": "232112", "Score": "2" } } ]
{ "AcceptedAnswerId": "232115", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-09T17:22:10.773", "Id": "232112", "Score": "3", "Tags": [ "php", "object-oriented", "pdo", "pagination" ], "Title": "PHP complete pagination code" }
232112
<p><code>vstrsepf</code> is string parsing utility function born from the idea of using <code>strsep</code> and <code>strtol</code> with a <code>sscanf</code>-like interface. </p> <p>This is an attempt to build a safer <code>scanf</code> for embedded system application.</p> <p>Some key design choices:</p> <ul> <li>Will destroy its input string (by adding '\0').</li> <li>No dynamic memory allocation.</li> <li>Reentry safe (RTOS and thread support)</li> <li>No string copy, only pointer address are changed.</li> <li>No floating point support.</li> </ul> <p>Usage example 1:</p> <pre><code>// Parse IP string char test[] = "192.168.0.13"; char const* const format = "%3d.%3d.%3d.%3d"; uint32_t answer0 = 0; uint32_t answer1 = 0; uint32_t answer2 = 0; uint32_t answer3 = 0; int16_t n = strsepf(test, format, &amp;answer0, &amp;answer1, &amp;answer2, &amp;answer3); TEST_ASSERT_EQUAL(192, answer0); TEST_ASSERT_EQUAL(168, answer1); TEST_ASSERT_EQUAL(0, answer2); TEST_ASSERT_EQUAL(13, answer3); TEST_ASSERT_EQUAL(4, n); </code></pre> <p>Usage example 2:</p> <pre><code>// Parse NMEA (GPS) message char test[] = "$GPBWC,081837,,,,,,T,,M,,N,*13"; char const* const format = "$%*sBWC,%d,%*s,%*s,%*s,%*s,%*s,%s,"; uint32_t answer0 = 0; char* answer1 = NULL; int16_t n = strsepf(test, format, &amp;answer0, &amp;answer1); TEST_ASSERT_EQUAL(81837, answer0); TEST_ASSERT_EQUAL_STRING("T", answer1); TEST_ASSERT_EQUAL(2, n); </code></pre> <p>Try it online: <a href="https://onlinegdb.com/BkTDY5EoS" rel="noreferrer">https://onlinegdb.com/BkTDY5EoS</a></p> <hr> <p><code>strtol_s.h</code> A safer implementation of strtol (needed for strsepf).</p> <pre><code>long strtol_s(const char* buff, uint8_t base, int8_t* err) { char* end; errno = 0; const long sl = strtol(buff, &amp;end, base); if (end == buff) { *err = -1; //&lt; not a decimal number } else if ('\0' != *end) { *err = -2; //&lt; extra characters at end of input } else if ((LONG_MIN == sl || LONG_MAX == sl) &amp;&amp; ERANGE == errno) { *err = -3; //&lt; out of range of type long } else if (sl &gt; INT_MAX) { *err = -4; //&lt; greater than INT_MAX } else if (sl &lt; INT_MIN) { *err = -5; //&lt; less than INT_MIN } else { *err = 0; //&lt; ok } return sl; } </code></pre> <p><code>vstrsepf.h</code> The string parser</p> <pre><code>/* * `vstrsepf` is string parsing utility function born from * the idea of using `strsep` with a `sscanf` interface. * * It is designed to be a safer `scanf` for embedded system application. * * Some key design choices: * - Will destroy its input string (by adding '\0'). * - No dynamic memory allocation * - No string copy, only pointer address are changed. * - No floating point support. * * ARGUMENTS: * @param: mutStr - mutable input string. * @param: fmt - format string. * @param: arg - Aguments lists (va_list) * * FORMAT SPECIFIER: * * | Specifier | Descriptions | * |-------------|-----------------------------------------------------------------| * | %i, %d, %u, | Any number of digits* | * | %o | Any number of octal digits (0-7)* | * | %x | Any number of hexadecimal digits (0-9, a-f, A-F* | * | %% | A % followed by another % matches a single %. | * | %s | A string with any character in it. A terminating null character | * | | is automatically added at the end of the stored sequence.# | * * FORMAT OPTIONAL SPECIFIER: * * | O Specifier | Descriptions | * |-------------|-----------------------------------------------------------------| * | * | An optional starting asterisk indicates that the data is to be | * | | read from the stream but ignored. | * | width | Specifies the maximum number of characters to be read in the | * | | current reading operation. | * * */ int16_t vstrsepf(char mutStr[], char const* fmt, va_list arg) { if (mutStr == NULL || fmt == NULL) { return -1; } #define SUPPORTED_SPECIFIER "dibouxs%" int count = 0; while (*mutStr &amp;&amp; *fmt) { // printf("fmt = %c, s=%c\n", *fmt, *mutStr); if (*fmt == '%') { fmt++; // A format specifier follows this prototype: [=%[*][width][modifiers]type=] char specifierType = '\0'; bool noAssignFlag = false; size_t width = 0; for (; *fmt; fmt++) { if (strchr(SUPPORTED_SPECIFIER, *fmt)) { specifierType = *fmt; fmt++; break; //&lt; Specifier type is always the last element of a specifier string } if (*fmt == '*') { noAssignFlag = true; } else if (*fmt &gt;= '1' &amp;&amp; *fmt &lt;= '9') { char const* tc; for (tc = fmt; isdigit(*fmt); fmt++) ; width = strtol(tc, (char**)&amp;fmt, 10); fmt--; } } if (specifierType == '%') { mutStr++; //&lt; `%%` is just the `%` character. continue; } char* token; const bool continueUntilTheEnd = (*fmt == '\0'); if (continueUntilTheEnd) { token = mutStr; } else { char termination[] = { *fmt, '\0' }; token = strsep(&amp;mutStr, termination); if (token == NULL) { return -1; //&lt; no token found } fmt++; } if (noAssignFlag) { continue; //&lt; ignore it. } if (width &gt; 0) { if (width &lt; strlen(token)) { return -1; } } int8_t strtolErr = 0; switch (specifierType) { /********************************* * Scan string *********************************/ case 's': { char** ptr = va_arg(arg, char**); if (ptr == NULL) { return -1; } *ptr = token; count++; } break; /********************************* * Scan int *********************************/ case 'd': /* FALLTHROUGH */ case 'i': /* FALLTHROUGH */ case 'u': { uint8_t base = 10; uint32_t* ptr = va_arg(arg, uint32_t*); if (ptr == NULL) { return -1; } *ptr = strtol_s(token, base, &amp;strtolErr); if (strtolErr &lt; 0) { return -1; } count++; } break; case 'x': { uint8_t base = 16; uint32_t* ptr = va_arg(arg, uint32_t*); if (ptr == NULL) { return -1; } *ptr = strtol_s(token, base, &amp;strtolErr); if (strtolErr &lt; 0) { return -1; } count++; } break; case 'o': { uint8_t base = 8; uint32_t* ptr = va_arg(arg, uint32_t*); if (ptr == NULL) { return -1; } *ptr = strtol_s(token, base, &amp;strtolErr); if (strtolErr &lt; 0) { return -1; } count++; } break; case 'b': { uint8_t base = 2; uint32_t* ptr = va_arg(arg, uint32_t*); if (ptr == NULL) { return -1; } *ptr = strtol_s(token, base, &amp;strtolErr); if (strtolErr &lt; 0) { return -1; } count++; } break; /********************************* * We don't know. *********************************/ default: { return -1; } } } else { /* !(*fmt == '%') */ if (*fmt != *mutStr) { return -1; } else { fmt++; mutStr++; } } // END if (*fmt == '%') } // END while (*mutStr &amp;&amp; *fmt) return count; } </code></pre> <p><code>strsepf.h</code> An arguments wrapper</p> <pre><code>int16_t strsepf(char mutStr[], char const* fmt, ...) { int16_t rc; va_list arg; va_start(arg, fmt); rc = vstrsepf(mutStr, fmt, arg); va_end(arg); return rc; } </code></pre> <hr> <p>While robustness and speed are my priorities, all suggestions are welcome.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-09T20:58:50.223", "Id": "453100", "Score": "1", "body": "I see that `strtol_s` returns a highly specific error message and `vstrsepf` just projects it to a binary and returns -1 on error. Could you think of a way of including that information?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-09T21:56:54.590", "Id": "453104", "Score": "0", "body": "Great point. \nTo be honest, I mostly reused `strtol_s` from an old project. I could return better info about what failed with an enum." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-02T14:00:19.217", "Id": "455893", "Score": "0", "body": "I would strongly recommend to never design APIs revolving around variable arguments. The printf/scanf familes of functions are some of the buggiest, most dangerous functions - not just in in the history of C - but in the history of programming. It is not something you should look at for inspiration! Variable argument functions is a completely superfluous feature, originating from a time in the 1960-1970s where programming languages needed to brag about having lots of features, long before good programming practice was invented and established." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-05T18:09:28.777", "Id": "460021", "Score": "0", "body": "@Lundin \nWhile I do see the problem associated with variable arguments function, it seems like a valuable feature for building flexible API in c.\n\nDo you have an alternative in mind ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-07T07:47:20.013", "Id": "460229", "Score": "0", "body": "@gberth Pretty much all major C APIs out there use pointers to struct. And if needed, the structs can implement some manner of polymorphism." } ]
[ { "body": "<p>Small review</p>\n\n<p><strong>Bug</strong></p>\n\n<p><code>case 'u': { ... *ptr = strtol_s(token, base, &amp;strtolErr);</code> can form the wrong value as <code>strtol()</code> can limit values to 2<sup>31</sup>-1. Same with <code>'x'</code>. Better to use <code>strtoul()</code>.</p>\n\n<p><strong>Type conflagration</strong></p>\n\n<p><code>long strtol_s()</code> looks like a function to convert a string to <code>long</code> yet it errors when out of <code>int</code> range and is curiously used in the code only for <code>uint32_t</code>.</p>\n\n<p>I'd expect a <code>uin32_t strtou32_s()</code> or the like. Maybe something like <a href=\"https://stackoverflow.com/a/29378380/2410359\"><code>strto_subrange()</code></a>?</p>\n\n<p><strong>Reduce error values</strong></p>\n\n<p>In <code>strtol_s()</code>, as <code>(LONG_MIN == sl || LONG_MAX == sl) &amp;&amp; ERANGE == errno</code> generates the same error value, I'd expect <code>sl &gt; INT_MAX</code> and <code>sl &lt; INT_MIN</code> to generate one same error value.</p>\n\n<p><strong>Error checking omission?</strong></p>\n\n<p>Interesting <code>width = strtol(tc, (char**)&amp;fmt, 10);</code> lacks range checking.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-01T20:24:48.157", "Id": "455810", "Score": "0", "body": "Thanks i will make sure to improve it." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-11T08:40:21.137", "Id": "232173", "ParentId": "232119", "Score": "3" } } ]
{ "AcceptedAnswerId": "232173", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-09T19:56:53.540", "Id": "232119", "Score": "8", "Tags": [ "c", "strings", "embedded" ], "Title": "strsepf() - Parsing string using strsep with a scanf-like interface" }
232119
<p>I’d like to start by apologising for the mess that is my code. I know that it’s really hard to parse, inefficient, and probably not idiomatic. I just don’t know how to fix it which is why I'm here.</p> <p>The whole thing is a project for school. Basically what I’m doing is scraping data from an online database with information about the expression of certain genes in certain cells. I then feed this data into a perceptron model to try to predict the effects of certain genes on cell morphology. I know that it would be all-around better in every way to use a framework for both parts (e.g TensorFlow, Scrapy) but as it is for school, I’m limited to "standard libraries".</p> <pre class="lang-py prettyprint-override"><code>import numpy as np import csv from sklearn.preprocessing import LabelEncoder from sklearn.preprocessing import OneHotEncoder from bs4 import BeautifulSoup import requests class Scraper: def create_genes(self, amazonia_list): #'http://amazonia.transcriptome.eu/list.php?section=display&amp;id=388' results = requests.get(amazonia_list) list_page = results.text soup = BeautifulSoup(list_page, 'html.parser') table = soup.find('div', class_='field') rows = table.find_all('tr') with open('data/genes.csv', 'w') as file: fieldnames = [] for row in rows: header_sections = row.find_all('th') for item in header_sections: fieldnames.append(item.get_text()) writer = csv.writer(file, delimiter=',', lineterminator='\n') writer.writerow(fieldnames) for row in rows: body_sections = row.find_all('td') gene = [] for i in range(len(body_sections)): gene.append(body_sections[i].get_text()) writer.writerow(gene) fieldnames = [] body_sections = [] gene = [] rows = [] def genes_length(self): with open('data/genes.csv', 'r') as file: return len(file.readlines()) def label_id(self, line_num): with open('data/genes.csv', 'r') as file: reader = csv.DictReader(file, delimiter=',') for line in reader: if (reader.line_num == line_num): return line["List Item"] def link(self, id): link = "http://amazonia.transcriptome.eu/expression.php?section=displayData&amp;probeId=" + str(id) + "&amp;series=HBI" return link def abbreviation(self, id): with open('data/genes.csv', 'r') as file: reader = csv.DictReader(file, delimiter=',') for line in reader: if (line["List Item"] == id): return line["Abbreviation"] def create_data(self): with open('data/data.csv', 'w') as output: fieldnames = ["Gene", "Samples", "Signal", "p-Value"] writer = csv.writer(output, delimiter=',', lineterminator='\n') writer.writerow(fieldnames) for line in range(Scraper.genes_length(self)): results = requests.get(Scraper.link(self, Scraper.label_id(self, line))) page = results.text soup = BeautifulSoup(page, 'html.parser') table = soup.find_all('tr') for row in table: gene = [] entries = row.find_all('td') for i in range(3): gene.append(entries[i].get_text()) entry = [] entry.append(Scraper.abbreviation(self, Scraper.label_id(self, line))) entry += gene writer.writerow(entry) fieldnames = [] table = [] gene = [] entry = [] def main(self): Scraper.create_genes(self, 'http://amazonia.transcriptome.eu/list.php?section=display&amp;id=388') Scraper.create_data(self) class Model: def nonlin(self, X, deriv = False): if (deriv == True): return X * (1 - X) else: return 1 / (1 + np.exp(-X)) def init_data(self): scraper = Scraper() scraper.main() with open('data/data.csv', 'r') as file: reader = csv.reader(file, delimiter=',') headers = next(reader) data = list(reader) data = np.array(data, dtype=object) abbreviation = data[:,0] cell = data[:,1] signal = data[:,2] p_value = data[:,3] onehot_encoder = OneHotEncoder(sparse=False) abbreviation = abbreviation.reshape(len(abbreviation), 1) abbreviation_encoded = onehot_encoder.fit_transform(abbreviation) cell = cell.reshape(len(cell), 1) cell_encoded = onehot_encoder.fit_transform(cell) abbreviation_encoded = np.array(abbreviation_encoded) cell_encoded = np.array(cell_encoded) p_value = np.array(p_value) signal = np.array(signal) input = np.column_stack((abbreviation_encoded, cell_encoded, p_value)) output = signal data = [] abbreviation = [] cell = [] abbreviation_encoded = [] cell_encoded = [] p_value = [] return input, output def error(self, out, Y): sum = 0 error = (1/2) * ((Y - out) ** 2) rows = np.shape(error)[0] columns = np.shape(error)[1] for row in range(rows): for column in range(columns): sum += out[row][column] mean = sum / (rows * columns) return round(mean * 100, 2) def layer_out(self, layer_input, layer_weights): net = np.dot(layer_input, layer_weights) out = nonlin(net) return net, out def update_weights(self, layer_input, layer_weights, Y): net, out = layer_out(layer_input, layer_weights) self.weight_delta = -(Y - out) * (net * (1 - net)) * layer_input net = [] out = [] return weight_delta def main(self): X, Y = Model.init_data(self) for epoch in range(100000): print("Training Epoch:", epoch, "-", (epoch/10000) * 100, "%") inputs = np.shape(X)[1] hidden_neurons = 2 * inputs output_neurons = np.shape(Y)[0] input_weights = np.multiply(2, np.random.rand(inputs, hidden_neurons)) - 1 hidden_weights = 2 * (np.random.rand(hidden_neurons, output_neurons)) - 1 output_weights = 2 * (np.random.rand(output_neurons, 0)) - 1 l1 = Model.layer_out(self, X, input_weights) input_weights += Model.update_weights(self, X, input_weights) h1 = Model.layer_out(self, l1, hidden_weights) first_hidden_weights += Model.update_weights(self, l1, hidden_weights) output = Model.layer_out(self, h1, output_weights) output_weights += Model.update_weights(self, h1, output_weights) print("Predicted:\n", output) print("\nActual:\n", Y) print("\n Mean Error:\n", Model.error(self, output, Y),"%") model = Model() model.main() <span class="math-container">```</span> </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-09T23:42:22.010", "Id": "453111", "Score": "0", "body": "One thing - your function `id` shadows python's built in `id` function - consider changing that to _id or something." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-09T23:49:48.513", "Id": "453113", "Score": "0", "body": "That function identifies the label for part of the data. It shouldn't make too much difference but I changed it to `label_id()`. Thank you!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-10T01:21:06.753", "Id": "453116", "Score": "1", "body": "Yes, it won't make a difference in terms of functionality, and actually I am not sure if pep-8 cares if function names are shadowed within classes ... at least, my IDE doesn't seem to complain. However, I think in general best practice is to use variable names that are not built-ins. Hope I could help." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-10T13:01:03.163", "Id": "453147", "Score": "1", "body": "Does or doesn't the code currently work as intended?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-10T13:24:06.797", "Id": "453149", "Score": "1", "body": "If you really are restricted to standard libraries, are you allowed to use `sklearn`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-11T02:57:41.573", "Id": "453209", "Score": "1", "body": "That's actually a good point. The purpose of the exercise is that I'm supposed to build the model from scratch for the experience. I think my use of `sklearn` just for encoding is okay because it's not like I'm using `keras` and not doing any of the work. I mostly included that line to keep people from telling me to just use a library instead of trying to do it myself; the requirement exists but I assume it is lax." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-11T11:32:22.993", "Id": "453235", "Score": "0", "body": "@MilanCapoor: Your code actually fails for me, because the one-hot encoder cannot deal with string values, apparently?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-11T12:58:21.797", "Id": "453243", "Score": "0", "body": "Also, your epochs in the training don't do *anything*. You re-initialize it every iteration, so your final output is just the last of many one-iteration runs." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-11T13:10:40.493", "Id": "453244", "Score": "0", "body": "And finally, the signature of `update_weights` seems to be wrong and/or used in a wrong way. You supply it with `self, l1, hidden_weights`, but it takes `self, layer_input, layer_weights, Y`." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "9", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-09T21:28:38.370", "Id": "232125", "Score": "1", "Tags": [ "python", "web-scraping", "machine-learning" ], "Title": "Homemade web-scraper that feeds perceptron with hidden layer" }
232125
<p>I wrote a (very) simply Python3 password manager to familiarize myself with Sqlite3, and for fun. I am aware that there are already a variety of password managers out there, but I wanted something simple and <em>secure(?)</em> to replace the very insecure bashrc function that I use to generate random passwords and store them with a quick description on the fly. I tried writing a password manager in bash that used hashing and GPG, but decided it was easier to do in Python.</p> <p>I am looking for advice on how to improve the security of my program. I have implemented features such as:</p> <ul> <li>Timeout if idle</li> <li>Remove key from memory before exit</li> <li>Master key is hashed with sha256 and salted</li> </ul> <p>The entire program is available <a href="https://github.com/darkerego/clipw" rel="nofollow noreferrer">here</a> on github, but the functionality I am looking for advise on is the hashing and crypto functions:</p> <p>Hash Lib:</p> <pre><code>import hmac import random import string from _hashlib import pbkdf2_hmac from getpass import getpass from os import urandom, mkdir from typing import Tuple from lib.clipw_conf import debug, config_dir, config_file class HashPass(object): """ Wrapper Class for password hashing functions """ def __init__(self): """ Empty __init__ function """ pass def hash_new_password(self, password: str) -&gt; Tuple[bytes, bytes]: """ Hash the provided password with a randomly-generated salt and return the salt and hash to store in the database. :return salt, password hash """ salt = urandom(16) pw_hash = pbkdf2_hmac('sha256', password.encode(), salt, 100000) return salt, pw_hash def check_pw_padding(self, pw): """ Check that password length is AES compliant, add padding if not :param pw: password :return: password with buffering """ pw_len = len(pw) if pw_len &lt;= 8: while pw_len % 8 != 0: pw += '0' pw_len = (len(pw)) if pw_len &lt;= 16: while pw_len % 16 != 0: pw += '0' pw_len = (len(pw)) if pw_len &lt;= 32: while pw_len % 32 != 0: pw += '0' pw_len = (len(pw)) return pw def is_correct_password(self, salt: bytes, pw_hash: bytes, password: str) -&gt; bool: """ Given a previously-stored salt and hash, and a password provided by a user trying to log in, check whether the password is correct. """ return hmac.compare_digest( pw_hash, pbkdf2_hmac('sha256', password.encode(), salt, 100000) ) def generate_hash(self, pw): """ Generate a Hash and Salt from a password :param self: password to hash :return: salt and hash """ salt, pw_hash = self.hash_new_password(pw) salt = salt.hex() pw_hash = pw_hash.hex() if self.is_correct_password(bytes.fromhex(salt), bytes.fromhex(pw_hash), pw): if debug: print('Test Succeeded!') print("Salt: %s" % salt) print("Hash: %s" % pw_hash) return salt, pw_hash else: return False def store_master_password(self): """ Upon init, store users master key to disc :return: True on success """ try: mkdir(config_dir) except FileExistsError as err: pass else: print('Created config directory %s' % config_dir) # hash a password while True: pw = getpass('Password: ') pw2 = getpass('Confirm: ') try: assert pw == pw2 except AssertionError: print('Passwords do not match. Try again') else: pw_len = len(pw) if pw_len &gt; 32 or pw_len &lt; 8: print('Password must be at least 8 and no more than 32 characters.') else: s, p = self.generate_hash(pw) hash_str = str(s + ":" + p) with open(config_file, 'w+') as f: f.write(hash_str) return True def get_master_password(self): """ Function to create an AES friendly Master Password to encrypt all the passwords in the database... Because they key needs to be either 8 or 16 characters, we will add padding until it if an appropriate length. :return: byte encoded password string """ with open(config_file, 'r') as ff: master_hash = ff.read() _salt = master_hash.split(':')[0] _hash = master_hash.split(':')[1] master_pw = getpass("Master Password: ") if self.is_correct_password(bytes.fromhex(_salt), bytes.fromhex(_hash), master_pw): print('Success!') master_pw = self.check_pw_padding(master_pw) return master_pw.encode() else: print('Incorrect Password') exit(1) def store_password(self): """ Function to get a password and confirm user enters it twice correctly. :return: password """ while True: pw = getpass('Password: ') pw2 = getpass('Confirm: ') try: assert pw == pw2 except AssertionError: print('Passwords do not match.') else: return pw def random_password(self, n: int = 12) -&gt; object: """ Generate a random password of length n :param n: length of password to generate :return: password string """ random_source = string.ascii_letters + string.digits + string.punctuation password = random.choice(string.ascii_lowercase) password += random.choice(string.ascii_uppercase) password += random.choice(string.digits) password += random.choice(string.punctuation) for i in range(n): password += random.choice(random_source) password_list = list(password) random.SystemRandom().shuffle(password_list) password = ''.join(password_list)[:n] return password </code></pre> <blockquote> <p>I am curious about the function <code>check_pw_padding</code>, which adds padding to the key that it is of a compliant length for the AES functions. I want the user to be able to enter a key of arbitraty length, however I need that key to work with AES-CTR mode, which means it must be either 8, 16, or 32 bytes characters long. I believe I am following standard practice here, but I wanted to ask the community for advice on whether or not my implimentation follows best practice.</p> </blockquote> <p>AES Library:</p> <pre><code>import pyaes import base64 from .clipw_conf import * class HandleAes(object): """ AES Encrypt/Decrypt Function """ def __init__(self, key): self.key = key def remove_from_mem(self): self.key = None def encrypt_data(self, data): """ ENCRYPTION AES CRT mode - 256 bit (8, 16, or 32 byte) key :param data: data to encrypt :return: base64 wrapper AES encrypted data """ aes = pyaes.AESModeOfOperationCTR(self.key) ciphertext = aes.encrypt(data) encoded = base64.b64encode(ciphertext).decode('utf-8') if debug: print('Encrypted data:', encoded) # show the encrypted data return encoded def decrypt_data(self, data): """ DECRYPTION AES CRT mode decryption requires a new instance be created :param data: base64 encoded ciphertext :return: plaintext """ aes = pyaes.AESModeOfOperationCTR(self.key) # decrypted data is always binary, need to decode to plaintext decoded = base64.b64decode(data) decrypted = aes.decrypt(decoded).decode('utf-8') if debug: print('Decrypted data:', decrypted) return decrypted </code></pre> <blockquote> <p>Is AES-CTR sufficient for this use case? I want to use a stream cipher because the data I am storing is going to be of arbitrary length. Of course, I could always add padding to the data that it stores, but if I don't need to do that, and if this library is secure and I can reuse it, that would be great. <a href="https://security.stackexchange.com/questions/27776/block-chaining-modes-to-avoid/27780#27780">This answer</a> says that CTR is safe. Does my implementation follow best practice? Specifically, is it <em>sufficient</em>, or even <em>necessary</em> to ensure the key is cleared from memory by assisinging the variable None (in function <code>remove_from_mem</code>)</p> </blockquote> <p>SQL Lib:</p> <pre><code>import sqlite3 from .clipw_conf import * class Sql: """ Wrapper object to handle sqlite functions """ def __init__(self): self.database_file = database_file def open(self): """ Connect to SQL database """ try: self.sqlite_connection = sqlite3.connect(self.database_file) except Exception as err: print('Error connecting to database:', err) else: return self.sqlite_connection def close(self): """ Close connection to SQL database :return: """ try: self.sqlite_connection.close() except Exception as err: print('Error closing database:', err) return False def init_database(self): """ Function to init database on first run. :return: """ sqlite_connection = self.open() try: sqlite_create_table_query = '''CREATE TABLE Password_Store ( id INTEGER PRIMARY KEY, desc text NOT NULL, pass_hash text NOT NULL);''' cursor = sqlite_connection.cursor() print("Successfully Connected to SQLite") cursor.execute(sqlite_create_table_query) sqlite_connection.commit() print("SQLite table created") return True except sqlite3.Error as error: print("Error while creating a sqlite table:", error) return False finally: self.close() def edit_database(self, id, data, field): """ Broken function to update a field of a row in the table :param id: primary key id for WHERE clause :param data: edited field data to replace in current db entry :param field: either desc (description) or pass_hash (password hash of entry) :return: True om success, false om fail """ # sqlite_connection = self.sqlite_connection sqlite_connection = self.open() try: cursor = sqlite_connection.cursor() # define our sqlite connection print("Connected to SQLite") if field == 'pass_hash': # updating password field cursor.execute('''Update Password_Store SET pass_hash = ? WHERE id = ?''', (data, id)) # 2md failed method else: cursor.execute('''UPDATE Password_Store SET desc = ? WHERE id = ?''', (data, id)) sqlite_connection.commit() print("Record Updated successfully ") return True except sqlite3.Error as error: print("Failed to update sqlite table", error) return False finally: self.close() def append_database(self, new_passwd, pw_description): """ :param new_passwd: entry's password to append :param pw_description: entry's password description to append :return: """ # sqlite_connection = self.sqlite_connection sqlite_connection = self.open() try: cursor = sqlite_connection.cursor() if debug: print("Connected to SQLite") data_copy = cursor.execute("select count(*) from Password_Store") values = data_copy.fetchone() id = int(values[0]) + 1 sqlite_insert_with_param = """INSERT INTO 'Password_Store' ('id', 'desc', 'pass_hash') VALUES (?, ?, ?);""" data_tuple = (id, pw_description, new_passwd) cursor.execute(sqlite_insert_with_param, data_tuple) sqlite_connection.commit() if debug: print("Python Variables inserted successfully into SqliteDb_developers table") except sqlite3.Error as error: print("Failed to insert Python variable into sqlite table:", error) return False else: print('Stored password ok.') finally: self.close() def open_database(self): """ Open the database :return: list(entries in database) """ # sqlite_connection = self.sqlite_connection sqlite_connection = self.open() try: cursor = sqlite_connection.cursor() if debug: print("Connected to SQLite") sqlite_select_query = """SELECT * from Password_Store""" cursor.execute(sqlite_select_query) records = cursor.fetchall() if debug: print("Total rows are: ", len(records)) id_desc = [] for row in records: _id = int(row[0]) _desc = str(row[1]) id_desc.append([_id, _desc]) return id_desc except sqlite3.Error as error: print("Failed to read data from sqlite table", error) return False except Exception as err: print('Unknown error:', err) finally: self.close() def select_from_db(self, id): """ Grab a certain password from the database :param id: primary key of password to get :return: aes encrypted password """ # sqlite_connection = self.sqlite_connection sqlite_connection = self.open() try: cursor = sqlite_connection.cursor() if debug: print("Connected to SQLite") sql_select_query = """select * from Password_Store where id = ?""" cursor.execute(sql_select_query, (id,)) record = cursor.fetchone() if debug: print("Sql library: Retrieving ID:", id) return record except sqlite3.Error as error: print("Failed to read data from sqlite table", error) return False finally: self.close() def delete_from_database(self, id): sqlite_connection = self.open() try: cursor = sqlite_connection.cursor() if debug: print("Connected to SQLite") # Deleting single record now sql_delete_query = """DELETE from Password_Store where id = ?""" cursor.execute(sql_delete_query, (id,)) sqlite_connection.commit() return "Record deleted successfully " except sqlite3.Error as error: print("Failed to delete record from sqlite table", error) return False finally: self.close() </code></pre> <p>Config Lib</p> <pre><code>debug = False from os import getenv config_dir = getenv('HOME') + '/.clipw' config_file = config_dir + '/clipw.conf' database_file = config_dir + '/clipw.db' </code></pre> <p>Main Logic:</p> <pre><code>#!/usr/bin/env python3 """ CliPassWord Manager - A Very Simple Python3 Powered Command Line Password Manager Author: Darkerego ~ November, 2019 &lt;xelectron@protonmail.com&gt; """ import argparse import shutil import signal import threading from os import mkdir, kill, getpid from os.path import isfile from sys import argv from lib import aes_lib from lib import passlib from lib import sql_functions from lib.clipw_conf import * def get_input(_type: str or int, _prompt: str): """ Functions to get and validate input. :param _type: input type: str or int :param _prompt: input prompt :return: input """ if _type == 'int': while True: try: io = int(input(_prompt)) except TypeError: print('Enter a valid integer.') else: return io elif _type == 'str': while True: try: io = str(input(_prompt)) except TypeError: print('Enter a valid string.') else: return io def get_selection(_prompt: str, opts: list, _type: int or str): """ Function to handle selecting input from a list of options :param _type: :param _prompt: input prompt :param opts: list of choices :return: selected option """ while True: try: selection = _type(input(_prompt)) except TypeError: print('Invalid input type.') else: if selection in opts: return selection else: print("%d is not a valid option" % selection) def init_database(): """ Initialize the database :return: """ print('Initializing database ... %s' % database_file) try: mkdir(config_dir) except FileExistsError: pass if isfile(database_file): remove_db = input('[!] Database file found, would you like to delete it? (y/n) :') if remove_db.lower() == 'y': print('Making a backup of current database ...') shutil.move(database_file, database_file + '.orig') sql_ = sql_functions.Sql() hash_pass_ = passlib.HashPass() hash_pass_.store_master_password() if sql_.init_database(): print('Successfully initialized the database.') sql_.close() aes.remove_from_mem() def store_pass(): """ Store a password from standard input :return: """ pw_description = input('Password Description: ') new_pass = hash_pass.store_password() encrypted_pw = aes.encrypt_data(new_pass) sql.append_database(encrypted_pw, pw_description) return True def generate_random_pw(pw_len=None): pw_description = input('Password Description: ') if not pw_len: pw_len = [8] new_pw = hash_pass.random_password(pw_len[0]) encrypted_pw = aes.encrypt_data(new_pw) sql.append_database(encrypted_pw, pw_description) # print(str('Password: %s' % new_pw)) return new_pw def open_db(): """ Function to open the database and retrieve an entry :return: """ id_desc = sql.open_database() print('--------------------------------------------------------------') print(' Password Database: ') print('--------------------------------------------------------------') for i in id_desc: print('ID: ', i[0], "Description", i[1]) print('--------------------------------------------------------------') get_entry = get_input('int', 'Enter ID of password to decrypt: ') ret = sql.select_from_db(id=get_entry) if ret is None: print('%d is not a valid entry. Try again.' % get_entry) else: print("Id: ", ret[0]) print("Description:", ret[1]) hashed = ret[2] try: decrypted = aes.decrypt_data(hashed) except UnicodeDecodeError as err: print('Error decrypting password:', err) except Exception as err: print('Error decrypting password:', err) else: print('Password:', decrypted) def edit_db_entry(): """ Function to edit a database entry :return: """ id_desc = sql.open_database() ids = [] for i in id_desc: print('ID: ', i[0], "Description", i[1]) ids.append(i[0]) entry_edit = get_selection(_prompt='Enter ID of entry to edit: ', opts=ids, _type=int) ret = sql.select_from_db(id=entry_edit) print('Fields: ') print('ID:', ret[0]) print('[1] Description', ret[1]) show_pass = input('Show password (y/n)? : ') if show_pass == 'y': hashed = ret[2] decrypted = aes.decrypt_data(hashed) print('[2] Password:', decrypted) else: print('[2] Password: x-x-x-x-x') edit_field = get_selection('Enter field of entry to edit. (1: Description, 2: Password)', opts=[1, 2], _type=int) if edit_field == 1: new_description = input('Description: ') try: sql.edit_database(id=entry_edit, field='desc', data=new_description) except Exception as err: print('Error editing entry:', err) else: return True if edit_field == 2: suggest_password = input('Generate new random password? (y/n): ') if suggest_password == 'y': new_pw = hash_pass.random_password(16) else: new_pw = input('Enter new password: ') if new_pw is not None: encrypted_pw = aes.encrypt_data(new_pw) try: sql.edit_database(id=entry_edit, field='pass_hash', data=encrypted_pw) except Exception as err: print('Error editing entry:', err) else: return True else: print('Error: password is None.') return False def delete_entry_from_db(): """ Function to delete an entry from the database. :return: """ id_desc = sql.open_database() ids = [] for i in id_desc: print('ID: ', i[0], "Description", i[1]) ids.append(i[0]) get = get_selection(_prompt='Entry to delete: ', opts=ids, _type=int) if debug: print('Retrieving: ', get) ret = sql.delete_from_database(id=get) if ret: print(ret) else: print('Error deleting from database.') return False def get_args(): """ Argument parser :return: argparse generated object """ parser = argparse.ArgumentParser(description='Python Cli Password Manager') parser.add_argument('--init', '--init_database', dest='init_db', action='store_true', help='Re|Init Database') parser.add_argument('-i', '--interactive', dest='interactive', action='store_true', default=False, help='Interactive mode') parser.add_argument('-t,', '--timeout', default=600, type=int, dest='timeout', help='Override timeout - close after' 'this amount of seconds.') parser.add_argument('-o', '--open', dest='open', help='Open the password database', action='store_true') parser.add_argument('-s', '--store', dest='store', action='store_true', help='Enter and store a new password in' ' the database') parser.add_argument('-e', '--edit', dest='edit', help='Edit an entry.', action='store_true') parser.add_argument('-d', '--delete', dest='delete', help='Delete an entry', action='store_true') parser.add_argument('-r', '--random', dest='gen_random', help='Generate and store a random password of n length', type=int, default=None, nargs="*") return parser.parse_args() def cleanup(): """ Cleanup function for security :return: """ aes.remove_from_mem() class TimeOutTime: """ Empty object to hold specified timeout seconds """ def __init__(self, secs): """ Init Function :param secs: seconds before timeout """ self.secs = secs def get(self): """ Return specified seconds :return: secs """ return int(self.secs) def app(): """ Program main logic :return: -- print to stdout """ args = get_args() try: program_name = argv[0] except Exception: program_name = 'clipw' global sql, hash_pass, aes if args.init_db: init_database() exit(0) else: if not (args.open or args.store or args.edit or args.delete or args.gen_random or args.interactive): print("Run %s -i for interactive or --help for usage" % program_name) exit(1) sql = sql_functions.Sql() hash_pass = passlib.HashPass() aes = aes_lib.HandleAes(key=hash_pass.get_master_password()) if args.interactive: timeout = args.timeout to = TimeOutTime(timeout) wd = Watchdog(to.get()) wd.start() print('Running in interactive mode. ') while True: try: action = get_selection("Enter action: store (s), generate: (g), open and select entry: (o), " "edit entry: " "(e), delete entry: (d), quit program (q) ", opts=["s", "g", "o", "e", "d", "q"], _type=str) except KeyboardInterrupt: break except Exception as err: print(err) else: try: sql = sql_functions.Sql() except Exception as err: if debug: print('Error with SQL:', err) pass wd.refresh() action = action.lower() print('Selected:', action) if action == 's': store_pass() elif action == 'g': pw_len = get_input('int', 'Password Length: ') ret = generate_random_pw([pw_len]) if ret: print('Password:', ret) elif action == 'o': open_db() elif action == 'e': edit_db_entry() elif action == 'd': delete_entry_from_db() elif action == 'q': break else: raise ValueError('Invalid Selection') print('Quitting...') wd.do_expire() if args.store: store_pass() if args.gen_random is not None: pw_len = args.gen_random ret = generate_random_pw(pw_len) if ret: print("Password", ret) if args.open: open_db() if args.edit: edit_db_entry() if args.delete: delete_entry_from_db() # Remove the master key from memory on exit cleanup() class Watchdog: def __init__(self, _timeout=600): self.timeout = _timeout self._t = None self.wd_debug = False # debug messages def do_expire(self): cleanup() kill(getpid(), signal.SIGKILL) def _expire(self): print("\nTimeout expired, exiting for security...") self.do_expire() def start(self): if self._t is None: self._t = threading.Timer(self.timeout, self._expire) self._t.start() def stop(self): if self._t is not None: self._t.cancel() self._t = None def refresh(self): if self.wd_debug: print('Debug message: watchdog refresh.') if self._t is not None: self.stop() self.start() def main(): try: app() except KeyboardInterrupt: print('Caught Signal, exiting ...') finally: exit(0) if __name__ == "__main__": main() </code></pre> <p>Other Notes &amp; Questions:</p> <ul> <li>Is there a "cleaner" way to kill the process if it's been idle for (in this case) ten minutes? It seems kind of of "hacky" to use <code>os.kill()</code>, but I can't seem to find a way to simply use <code>exit(0)</code> while importing functions from multiple libaries. </li> <li>I know this program is kind of rudimentary right now. I intend on adding additional fields to the database such as (timestamp) "created" and "last modified", as well as more details like "username" and "url", instead of just having an id and description for each corresponding password.</li> <li>I am trying to think of a good method for securely sharing a database between different devices. Personally I just use ssh in these cases, however a friend of mine said he would like an easier way to do it. I considered perhaps encrypting the database again with an "export password" and then uploading to a service like spruge.us or termbin.com, so that the user could retrieve and import the database easily on another device. (Thoughts on this?)</li> <li>I am mostly looking for critique on how the program handles password hashing and the encryption functionality, however am open to any other suggestions and critique. Thank you for taking the time to review this code!</li> </ul>
[]
[ { "body": "<p>I'm going to review each lib separately, so there might be duplicates.</p>\n\n<h1>Hash Library</h1>\n\n<h2>Returns</h2>\n\n<p>In your <code>generate_hash</code> method, you have this section of code:</p>\n\n<pre><code>...\n return salt, pw_hash\nelse:\n return False\n</code></pre>\n\n<p>The else is unnecessary here, as the first return will exit the method. It should look like this instead:</p>\n\n<pre><code>...\n return salt, pw_hash\nreturn False\n</code></pre>\n\n<h2>Types</h2>\n\n<p>In some methods, you use types to display what parameters are accepted and what values are returned, but in other methods you do not. I would recommend being consistent to one idea: using types or not using them. My personal preference is using types to have as much description about the methods I write.</p>\n\n<p>When returning two different types of values in a method, use <code>Union</code>. It allows you to do something like this:</p>\n\n<pre><code>def get_master_password(self) -&gt; Union[str, None]:\n</code></pre>\n\n<p>This says it will either return a string, or None. You can describe this possible behavior in the method docstring.</p>\n\n<h2>Asserts</h2>\n\n<p>Instead of using try and catches, you can assert <em>with</em> an error message as such:</p>\n\n<pre><code>assert pw == pw2, 'Passwords do not match. Try again'\n</code></pre>\n\n<h2>Naming</h2>\n\n<p>Personally, I see <code>pw</code> and <code>pw2</code> as less than desirable variable names. Names like <code>password</code> and then <code>confirm_password</code> can be more descriptive. The same when working with files, you use <code>ff</code> when <code>with open(...) as file</code> is more clear.</p>\n\n<h2>Inheritance</h2>\n\n<p>Subclassing from <code>object</code> isn't required, as it's a python 2 feature. You don't need to inherit from object to have new style in python 3. All classes are new-style. <a href=\"https://stackoverflow.com/questions/54867/what-is-the-difference-between-old-style-and-new-style-classes-in-python\">Here</a> is a StackOverflow post that explains what new-style is.</p>\n\n<h2>Init Method</h2>\n\n<p>If you don't need an <code>init</code> method, don't bother writing one. It's unnecessary code.</p>\n\n<hr>\n\n<h1>AES Library</h1>\n\n<p>Nothing much to review, just going to reiterate not having to inherit from object when creating a new class and the possible use of types. For example:</p>\n\n<pre><code>def encrypt_data(self, data):\n</code></pre>\n\n<p>can be</p>\n\n<pre><code>def encrypt_data(self, data: str) -&gt; str:\n</code></pre>\n\n<p>(I'm assuming the data passed is a string)</p>\n\n<hr>\n\n<h1>SQL Library</h1>\n\n<h2>Reserved Names</h2>\n\n<p>I wouldn't use <code>id</code> within this program, as it's a reserved name in python. A fix most python developers use (from what I've seen) is <code>_id</code> or <code>id_</code>. You use <code>_id</code> in some parts of your program, so I would recommend using it everywhere.</p>\n\n<p>The same goes with <code>open</code>. I would suggest a method like <code>connect_to_database</code>.</p>\n\n<h2>Types</h2>\n\n<p>Again, types.</p>\n\n<h2>Docstring Formatting</h2>\n\n<p>Just some food for thought about your docstrings. This is your <code>edit_database</code> docstring:</p>\n\n<pre><code>\"\"\"\nBroken function to update a field of a row in the table\n:param id: primary key id for WHERE clause\n:param data: edited field data to replace in current db entry\n:param field: either desc (description) or pass_hash (password hash of entry)\n:return: True om success, false om fail\n\"\"\"\n</code></pre>\n\n<p>It's a little clunky and slightly hard to read since it's one block of code. Personally, I would separate the method description, parameters accepted, and values returned:</p>\n\n<pre><code>\"\"\"\nBroken function to update a field of a row in the table\n\n:param id: primary key id for WHERE clause\n:param data: edited field data to replace in current db entry\n:param field: either desc (description) or pass_hash (password hash of entry)\n\n:return: True om success, false om fail\n\"\"\"\n</code></pre>\n\n<p>Now everything looks neater and you can differentiate the parts of the docstring.</p>\n\n<hr>\n\n<h1>Main Logic</h1>\n\n<h2>String Formatting</h2>\n\n<p>This</p>\n\n<pre><code>print('Initializing database ... %s' % database_file)\n</code></pre>\n\n<p>can be</p>\n\n<pre><code>print(f'Initializing database ... {database_file}')\n</code></pre>\n\n<p>Using <code>f\"\"</code> strings allows you to directly place variables in your strings without having to use <code>%s</code> or <code>.format(...)</code>.</p>\n\n<h2><code>or</code> in parameters</h2>\n\n<p>This</p>\n\n<pre><code>def get_input(_type: str or int, _prompt: str):\n</code></pre>\n\n<p>can be</p>\n\n<pre><code>def get_input(_type: Union[str, int], _prompt: str) -&gt; Union[str, int]:\n</code></pre>\n\n<p>It utilizes <code>typing</code>s <code>Union</code> instead of using a built in keyword such as <code>or</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-14T22:43:40.920", "Id": "453857", "Score": "0", "body": "Awesome review, thanks so much! Definitely a lot of great tips in there, I will refactor my code using your suggestions. I always wondered how to use `Union`, I did not know you could use `assert` in that manner (much cleaner) . Do you have any insight on whether or not my encryption functionality is implemented properly and is reasonably secure? Thanks again!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-14T09:01:33.080", "Id": "232372", "ParentId": "232128", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-09T23:24:37.170", "Id": "232128", "Score": "3", "Tags": [ "python", "python-3.x", "cryptography", "hashcode", "aes" ], "Title": "CliwPw - Yet Another Python3 Password Manager" }
232128
<p>This is a lightweight version of <code>std::shared_ptr&lt;T&gt;</code> called <code>res_ptr&lt;T&gt;</code></p> <p>This post is a continuation of: <a href="https://codereview.stackexchange.com/questions/231599/a-lightweight-version-of-stdshared-ptrt">A lightweight version of std::shared_ptr&lt;T&gt;</a></p> <p>Revisited the code due to review from @TobySpeight and @MartinYork. Fixed errors and implemented full support for all types of data.</p> <p><code>std::shared_ptr&lt;T&gt;</code> stores a whole control block for managing reference counters (2 in total for <code>weak_ptr</code> support) and a pointer to deleter so it can deal with casting between classes without virtual destructor. And most probably it stores it else where via additional allocation. Honestly, I am not too sure on all details of its implementation and I might be wrong on some points.</p> <p><code>res_ptr&lt;T&gt;</code> stores the reference counter together with the data, it is achieved by wrapping T inside a class. A certain downside of it is that <code>res_ptr&lt;T&gt;</code> cannot take ownership over a pointer to <code>T</code> unless <code>T</code> inherits from the reference counter class <code>resource</code>.</p> <p>In case <code>T</code> inherits from class <code>resource</code> then no wrapping occurs and you can freely cast <code>res_ptr&lt;T&gt;</code> to <code>res_ptr&lt;U&gt;</code> whenever both <code>T</code> inherits from <code>U</code> and <code>U</code> inherits from <code>resource</code>. It is left to the user to decide how exactly <code>T</code> and <code>U</code> derive from <code>resource</code>, whether to use <code>virtual</code> inheritance to deal with diamond problem or not. Also you can cast any <code>res_ptr&lt;T&gt;</code> to <code>res_ptr&lt;resource&gt;</code> and backwards is also possible via dynamic casting (or some unsafe operations).</p> <p>Also implemented support for casting from <code>std::unique_ptr&lt;res_version&lt;T&gt;&gt;</code>. It is possible to cast to <code>std::unique_ptr&lt;res_version&lt;T&gt;&gt;</code> via function <code>release</code> that relinquishes ownership over the data without reallocating it even if reference counter reaches 0.</p> <p><code>res_version&lt;T&gt;</code> is an alias for the container class that <code>res_ptr&lt;T&gt;</code> uses for storing <code>T</code>. If <code>T</code> inherits from <code>resource</code> then <code>res_version&lt;T&gt;</code> is simply <code>T</code>.</p> <p><code>make_resource&lt;T&gt;</code> is a helper function for instantiating <code>res_ptr&lt;T&gt;</code>.</p> <p><code>res_ptr</code> doesn't support vector versions like <code>std::unique_ptr&lt;T[]&gt;</code>. And I haven't tested for unions.</p> <p>Due to an initialization of the <code>std::atomic</code> inside <code>resource</code> it is not fully portable currently. Sorry for the issue. If there are any other issues with portability please let me know.</p> <p>Here is a full working version of the code together with a test:</p> <pre><code> #include &lt;iostream&gt; #include &lt;atomic&gt; #include &lt;cstddef&gt; #include &lt;type_traits&gt; #include &lt;utility&gt; class resource { public: virtual ~resource() = default; resource() = default; // moving / copying does not alter the reference counter resource(resource&amp;&amp;) noexcept : resource() {}; resource(const resource&amp;) noexcept : resource() {}; resource&amp; operator = (resource&amp;&amp;) noexcept {return *this;}; resource&amp; operator = (const resource&amp;) noexcept {return *this;}; void add_ref() const noexcept { m_refcount.fetch_add(1ull, std::memory_order_relaxed); } std::size_t reduce_ref() const noexcept { return m_refcount.fetch_sub(1ull, std::memory_order_relaxed)-1; } std::size_t count() const noexcept { return m_refcount.load(std::memory_order_relaxed); } private: mutable std::atomic&lt;std::size_t&gt; m_refcount = 0; }; template&lt;typename T, typename Enable = void&gt; class res_version_ref; template&lt;typename T&gt; class res_version_ref&lt;T, typename std::enable_if_t&lt;std::is_base_of_v&lt;resource, T&gt;&gt;&gt; { public: using type = T; }; template&lt;typename T&gt; class res_inheritance : public T, public resource { public: template&lt;typename... Args&gt; res_inheritance(Args&amp;&amp;... args): T(std::forward&lt;Args&gt;(args)...) {}; }; template&lt;typename T&gt; class res_version_ref&lt;T, typename std::enable_if_t&lt;!std::is_base_of_v&lt;resource, T&gt; &amp;&amp; std::is_class_v&lt;T&gt;&gt;&gt; { public: using type = res_inheritance&lt;T&gt;; }; template&lt;typename T, typename Enable = void&gt; class res_container; template&lt;typename T&gt; class res_container&lt;T, typename std::enable_if_t&lt;!std::is_abstract_v&lt;T&gt;&gt;&gt;: public resource { public: template&lt;typename... Args&gt; res_container(Args&amp;&amp;... args): m_data(std::forward&lt;Args&gt;(args)...) {}; T m_data; }; template&lt;typename T&gt; class res_version_ref&lt;T, typename std::enable_if_t&lt;!std::is_class_v&lt;T&gt;&gt;&gt; { public: using type = res_container&lt;T&gt;; }; template&lt;typename T&gt; using res_version = typename res_version_ref&lt;T&gt;::type; template&lt;typename T&gt; inline T* GetDataPtr(res_container&lt;T&gt;* ptr) { return &amp;ptr-&gt;m_data; } template&lt;typename T&gt; inline T* GetDataPtr(res_inheritance&lt;T&gt;* ptr) { return static_cast&lt;T*&gt;(ptr); } template&lt;typename T&gt; inline T* GetDataPtr(T* ptr) { return ptr; } template&lt;typename T&gt; class res_ptr { public: template&lt;typename U&gt; friend class res_ptr; constexpr res_ptr() noexcept = default; constexpr res_ptr(std::nullptr_t) noexcept {}; template&lt;typename U, std::enable_if_t&lt;std::is_base_of_v&lt;res_version&lt;T&gt;, U&gt;, int&gt; = 0&gt; explicit res_ptr( U* ptr) noexcept : m_ptr(static_cast&lt;res_version&lt;T&gt;*&gt;(ptr)) { if(m_ptr) m_ptr-&gt;add_ref(); }; template&lt;typename U, std::enable_if_t&lt;std::is_base_of_v&lt;res_version&lt;T&gt;, U&gt;, int&gt; = 0&gt; explicit res_ptr( std::unique_ptr&lt;U&gt; ptr) noexcept : m_ptr(static_cast&lt;res_version&lt;T&gt;*&gt;(ptr.release())) { if(m_ptr) m_ptr-&gt;add_ref(); }; ~res_ptr() { clear(); } // copy ctor res_ptr( const res_ptr&amp; ptr) noexcept : m_ptr(ptr.get()) { if (m_ptr) m_ptr-&gt;add_ref(); }; // copy ctor cast template&lt;typename U, std::enable_if_t&lt;std::is_base_of_v&lt;res_version&lt;T&gt;, res_version&lt;U&gt;&gt; &amp;&amp; !std::is_same_v&lt;res_version&lt;T&gt;, res_version&lt;U&gt;&gt;,int&gt; = 0&gt; res_ptr( const res_ptr&lt;U&gt; &amp; ptr) noexcept : m_ptr(static_cast&lt;res_version&lt;T&gt;*&gt;(ptr.m_ptr)) { if (m_ptr) m_ptr-&gt;add_ref(); }; // move ctor res_ptr( res_ptr&amp;&amp; ptr) noexcept : m_ptr(std::exchange(ptr.m_ptr, nullptr)) {}; // move ctor cast template&lt;typename U, std::enable_if_t&lt;std::is_base_of_v&lt;res_version&lt;T&gt;, res_version&lt;U&gt;&gt; &amp;&amp; !std::is_same_v&lt;res_version&lt;T&gt;, res_version&lt;U&gt;&gt;,int&gt; = 0&gt; res_ptr( res_ptr&lt;U&gt;&amp;&amp; ptr) noexcept : m_ptr(static_cast&lt;res_version&lt;T&gt;*&gt;(std::exchange(ptr.m_ptr, nullptr))) {}; // copy res_ptr&amp; operator = ( const res_ptr&amp; other) noexcept { if (this != &amp;other) { clear(); m_ptr = other.m_ptr; if (m_ptr) m_ptr-&gt;add_ref(); } return *this; } // move res_ptr&amp; operator = ( res_ptr&amp;&amp; other) noexcept { if (this != &amp;other) { clear(); m_ptr = std::exchange(other.m_ptr,nullptr); } return *this; } // copy cast template&lt;typename U, std::enable_if_t&lt;std::is_base_of_v&lt;res_version&lt;T&gt;, res_version&lt;U&gt;&gt; &amp;&amp; !std::is_same_v&lt;res_version&lt;T&gt;, res_version&lt;U&gt;&gt;, int&gt; = 0&gt; res_ptr&amp; operator = ( const res_ptr&lt;U&gt;&amp; other) noexcept { clear(); m_ptr = static_cast&lt;res_version&lt;T&gt;*&gt;(other.m_ptr); if (m_ptr) m_ptr-&gt;add_ref(); return *this; } // move cast template&lt;typename U, std::enable_if_t&lt;std::is_base_of_v&lt;res_version&lt;T&gt;, res_version&lt;U&gt;&gt; &amp;&amp; !std::is_same_v&lt;res_version&lt;T&gt;, res_version&lt;U&gt;&gt;, int&gt; = 0&gt; res_ptr&amp; operator = ( res_ptr&lt;U&gt;&amp;&amp; other) noexcept { clear(); m_ptr = static_cast&lt;res_version&lt;T&gt;*&gt;(std::exchange(other.m_ptr,nullptr)); return *this; } // move cast unique_ptr template&lt;typename U, std::enable_if_t&lt;std::is_base_of_v&lt;res_version&lt;T&gt;, U&gt;, int&gt; = 0&gt; res_ptr&amp; operator = ( std::unique_ptr&lt;U&gt; other) noexcept { clear(); m_ptr = static_cast&lt;res_version&lt;T&gt;*&gt;(other.release()); if(m_ptr) m_ptr-&gt;add_ref(); return *this; } T* operator -&gt; () const noexcept { return GetDataPtr&lt;T&gt;(m_ptr); } T&amp; operator * () const noexcept { return *GetDataPtr&lt;T&gt;(m_ptr); } T* get() const noexcept { return GetDataPtr&lt;T&gt;(m_ptr); } explicit operator bool() const noexcept { return m_ptr != nullptr; } void clear() { if (m_ptr &amp;&amp; (m_ptr-&gt;reduce_ref() == 0ull)) { delete m_ptr; } } auto release() -&gt; res_version&lt;T&gt;* { if (m_ptr) { m_ptr-&gt;reduce_ref(); } return std::exchange(m_ptr, nullptr); } template&lt;typename U&gt; bool operator == ( const res_ptr&lt;U&gt;&amp; other) noexcept { return (void*)m_ptr == (void*)other.m_ptr; } template&lt;typename U&gt; bool operator != ( const res_ptr&lt;U&gt;&amp; other) noexcept { return (void*)m_ptr != (void*)other.m_ptr; } auto get_impl_ptr() const -&gt; res_version&lt;T&gt;* { return m_ptr; } private: res_version&lt;T&gt;* m_ptr = nullptr; }; template&lt;typename T, typename... Args&gt; res_ptr&lt;T&gt; make_resource(Args&amp;&amp; ... args) { return res_ptr&lt;T&gt;(new res_version&lt;T&gt;(std::forward&lt;Args&gt;(args)...)); } template&lt;typename PDerived, typename PBase&gt; res_ptr&lt;PDerived&gt; resource_dynamic_cast(const res_ptr&lt;PBase&gt;&amp; uPtr) noexcept { res_version&lt;PDerived&gt;* ptr = dynamic_cast&lt;res_version&lt;PDerived&gt;*&gt;(uPtr.get_impl_ptr()); return res_ptr&lt;PDerived&gt;(ptr); } // testing code class MyClassA: public resource { public: MyClassA() = default; MyClassA(int A, int B): m_dataA(A), m_dataB(B) {}; public: int m_dataA; int m_dataB; }; class MyClassB: public MyClassA { public: MyClassB() = default; MyClassB(int A, int B, int C): MyClassA(A,B), m_dataC(B) {}; public: int m_dataC; }; class MyClassC: public virtual resource { public: MyClassC() = default; MyClassC(int A): m_dataC(A) {}; public: int m_dataC; }; class MyClassD: public virtual resource { public: MyClassD() = default; MyClassD(int A): m_dataD(A) {}; public: int m_dataD; }; class MyClassF: public MyClassC, public MyClassD { public: MyClassF() = default; MyClassF(int A, int B, int C): MyClassC(A), MyClassD(B), m_dataF(C) {}; public: int m_dataF; }; int main() { res_version&lt;int&gt; A(5); A.add_ref(); res_version&lt;std::string&gt; B("abs"); B.add_ref(); res_version&lt;MyClassA&gt; C(2,3); C.add_ref(); std::cout &lt;&lt; "A data " &lt;&lt; *GetDataPtr(&amp;A) &lt;&lt; "\n"; std::cout &lt;&lt; "B data "&lt;&lt; *GetDataPtr(&amp;B) &lt;&lt; "\n"; std::cout &lt;&lt; "C data " &lt;&lt; GetDataPtr(&amp;C)-&gt;m_dataA &lt;&lt; " " &lt;&lt; GetDataPtr(&amp;C)-&gt;m_dataB &lt;&lt; "\n"; res_ptr&lt;int&gt; pA(&amp;A); res_ptr&lt;std::string&gt; pB(&amp;B); res_ptr&lt;MyClassA&gt; pC(&amp;C); res_ptr&lt;resource&gt; prA = pA; res_ptr&lt;resource&gt; prB = pB; res_ptr&lt;resource&gt; prC = pC; std::cout &lt;&lt; "A count " &lt;&lt; A.count() &lt;&lt; "\n"; std::cout &lt;&lt; "B count " &lt;&lt; B.count() &lt;&lt; "\n"; std::cout &lt;&lt; "C count " &lt;&lt; C.count() &lt;&lt; "\n"; res_ptr&lt;int&gt; pA2 = resource_dynamic_cast&lt;int&gt;(prA); res_ptr&lt;std::string&gt; pB2 = resource_dynamic_cast&lt;std::string&gt;(prB); res_ptr&lt;MyClassA&gt; pC2 = resource_dynamic_cast&lt;MyClassA&gt;(prC); std::cout &lt;&lt; "A count " &lt;&lt; A.count() &lt;&lt; "\n"; std::cout &lt;&lt; "B count " &lt;&lt; B.count() &lt;&lt; "\n"; std::cout &lt;&lt; "C count " &lt;&lt; C.count() &lt;&lt; "\n"; std::cout &lt;&lt; "A2 data " &lt;&lt; *pA2 &lt;&lt; "\n"; std::cout &lt;&lt; "B2 data " &lt;&lt; *pB2 &lt;&lt; "\n"; std::cout &lt;&lt; "C2 data " &lt;&lt; pC2-&gt;m_dataA &lt;&lt; " " &lt;&lt; pC2-&gt;m_dataB &lt;&lt; "\n"; res_ptr&lt;MyClassB&gt; D = make_resource&lt;MyClassB&gt;(1,2,3); res_ptr&lt;MyClassA&gt; DA = D; std::cout &lt;&lt; "DA data " &lt;&lt; DA-&gt;m_dataA &lt;&lt; " "&lt;&lt; DA-&gt;m_dataB &lt;&lt; " count " &lt;&lt; DA-&gt;count() &lt;&lt; "\n"; std::cout &lt;&lt; "DA == PA ? " &lt;&lt; (int)(DA == pA) &lt;&lt; "\n"; std::cout &lt;&lt; "DA == D ? " &lt;&lt; (int)(DA == D) &lt;&lt; "\n"; res_ptr&lt;MyClassB&gt; D2 = resource_dynamic_cast&lt;MyClassB&gt;(DA); std::cout &lt;&lt; "D2 == D ? " &lt;&lt; (int)(D2 == D) &lt;&lt; "\n"; res_ptr&lt;MyClassF&gt; FF = make_resource&lt;MyClassF&gt;(1,2,3); res_ptr&lt;MyClassC&gt; FC = FF; res_ptr&lt;MyClassD&gt; FD = FF; std::cout &lt;&lt; "FC " &lt;&lt; FC-&gt;m_dataC &lt;&lt; "\n"; std::cout &lt;&lt; "FD " &lt;&lt; FD-&gt;m_dataD &lt;&lt; "\n"; std::cout &lt;&lt; "FF count " &lt;&lt; FF-&gt;count() &lt;&lt; "\n"; res_ptr&lt;MyClassF&gt; FF2 = resource_dynamic_cast&lt;MyClassF&gt;(FC); std::cout &lt;&lt; "FF2 " &lt;&lt; FF2-&gt;m_dataF &lt;&lt; "\n"; std::unique_ptr&lt;res_version&lt;int&gt;&gt; UP = std::make_unique&lt;res_version&lt;int&gt;&gt;(5); std::unique_ptr&lt;res_version&lt;int&gt;&gt; UP2 = std::make_unique&lt;res_version&lt;int&gt;&gt;(8); res_ptr&lt;int&gt; AA(std::move(UP)); AA = std::move(UP2); std::cout &lt;&lt; "AA " &lt;&lt; *AA &lt;&lt; "\n"; std::cout &lt;&lt; "AA " &lt;&lt; AA.get_impl_ptr()-&gt;count() &lt;&lt; "\n"; res_ptr&lt;int&gt; AA2(std::make_unique&lt;res_version&lt;int&gt;&gt;(8)); std::cout &lt;&lt; "AA2 " &lt;&lt; *AA2 &lt;&lt; "\n"; std::cout &lt;&lt; "AA2 " &lt;&lt; AA2.get_impl_ptr()-&gt;count() &lt;&lt; "\n"; AA2 = AA2; std::cout &lt;&lt; "AA2 " &lt;&lt; *AA2 &lt;&lt; "\n"; std::cout &lt;&lt; "AA2 " &lt;&lt; AA2.get_impl_ptr()-&gt;count() &lt;&lt; "\n"; AA2 = std::move(AA2); std::cout &lt;&lt; "AA2 " &lt;&lt; *AA2 &lt;&lt; "\n"; std::cout &lt;&lt; "AA2 " &lt;&lt; AA2.get_impl_ptr()-&gt;count() &lt;&lt; "\n"; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-06T05:50:03.153", "Id": "470757", "Score": "0", "body": "Good talk that touches on writing a custom shared_ptr: https://www.youtube.com/watch?v=Qq_WaiwzOtI" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-09T23:44:08.703", "Id": "232130", "Score": "2", "Tags": [ "c++", "memory-management", "c++14", "pointers" ], "Title": "A lightweight version of std::shared_ptr<T> V2" }
232130
<p>This is a follow-up review of <a href="https://codereview.stackexchange.com/questions/231898/calculate-the-sum-of-interior-angles-of-a-polygon">Calculate the sum of interior angles of a polygon</a>.</p> <p>Using the helpful answers from the original post, I have integrated the suggestions which are in order from first to last:</p> <ul> <li>Adding checks to <code>scanf()</code>.</li> <li>Using <code>main(void)</code> in place of <code>main(...)</code>.</li> <li>Passing <code>char *</code> directly to <code>printf()</code>.</li> <li>Made conditionals simpler.</li> <li><code>main()</code> is broken up into several functions and subroutines.</li> </ul> <p>I am seeking a second peer review because I have also added changes not suggested in the original post which are:</p> <ul> <li>Using enumerations to convey error information.</li> <li>Heavier error-checking in function <code>askAgain()</code>.</li> </ul> <pre class="lang-c prettyprint-override"><code>#include &lt;stdio.h&gt; #include &lt;string.h&gt; #include &lt;stdbool.h&gt; /* Keep string constants of the questions. */ const char* howManySides = "How many sides does the shape have? "; const char* askAnotherShape = "Would you like to find interior angles for another polygon? (0 or 1) "; /* Table of polygon names from 3 to 12 sides */ const char* names[] = { "a triangle", "a quadrilateral", "a pentagon", "a hexagon", "a heptagon", "an octagon", "a nonagon", "a decagon", "a hendecagon", "a dodecagon" }; enum errorType {noError, errNegSides, errZeroSides, errInsufSides}; static int getSumInteriorAngles(const unsigned int numSides) { return 180 * (numSides - 2); } /* Print a specific type of error based on its enumeration. */ static void printError(const enum errorType eType) { switch(eType) { case errNegSides: printf("The number of sides cannot be negative...\n"); break; case errZeroSides: printf("The number of sides cannot be zero...\n"); break; case errInsufSides: printf("The shape must have at least 3 sides...\n"); break; } } /* Takes a number of polygon sides and returns a type of error if the number of sides invalid or no error type if the number of sides is valid. */ static enum errorType isSidesValid(const int numSides) { if(numSides &lt; 0) return errNegSides; else if(numSides == 0) return errZeroSides; else if(numSides &lt; 3) return errInsufSides; else return noError; } static int getUserInput(void) { int userInput; bool isValidResponse = false; while(!isValidResponse) { /* Ask for the number of sides. */ printf(howManySides); /* We're looking for exactly 1 argument, so if there's less than that, then something went wrong with the conversion. */ if(scanf("%i", &amp;userInput) &lt; 1) { printf("Not a number...\n"); fflush(stdin); /* This check failed, so repeat the question. */ continue; } isValidResponse = true; } return userInput; } static int getNumSides(void) { int numSides; /* Initialize the checks flag to false and make it true only when all checks pass. */ bool passedAllChecks = false; while(!passedAllChecks) { numSides = getUserInput(); /* If the input was a valid number, then we have to check if the number of sides makes sense. */ enum errorType returnError = isSidesValid(numSides); if(returnError != noError) { /* If the number doesn't make sense for a number of sides, then print the specific error and repeat the question. */ printError(returnError); continue; } /* All checks passed. Exit the loop and return the number of sides. */ passedAllChecks = true; } return numSides; } static int askAgain(void) { int userResponse = 0; bool isValidResponse = false; while(!isValidResponse) { printf(askAnotherShape); /* Weed out non-integers and other weirdness. */ if(scanf("%i", &amp;userResponse) &lt; 1) { printf("Not a valid response...\n"); fflush(stdin); continue; } /* Restrict valid input to 0 or 1. */ if((userResponse != 0) &amp;&amp; (userResponse != 1)) { printf("Please choose 0 or 1...\n"); continue; } isValidResponse = true; } return userResponse; } static void printResult(int numSides) { /* Assume we're dealing with a polygon without a special name, in which case, we'll refer to it non-specifically. */ const char *name = "this polygon"; /* If we have a name for this polygon, then get it from the table. */ if(numSides &lt;= 12) { name = names[numSides - 3]; } printf("The sum of the interior angles of %s is %i\n", name, getSumInteriorAngles(numSides)); } int main(void) { do { printResult(getNumSides()); } while(askAgain()); return 0; } <span class="math-container">```</span> </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-11T17:45:56.647", "Id": "453285", "Score": "0", "body": "@Jamal Thank you for the edit. Can you explain why some of the function references have a ```)``` missing while others have matching parentheses? Thanks." } ]
[ { "body": "<h2>String as formats</h2>\n\n<p>Code uses <code>printf(howManySides);</code> yet <code>howManySides</code> is not described as a <em>format</em>. Such practice can lead to trouble when the string contains a <code>%</code>. Do not use a string as a <em>format</em> unless it is clearly stated in its definition that it is a <em>format</em>.</p>\n\n<pre><code>// printf(howManySides);\nfputs(howManySides, stdout);\n</code></pre>\n\n<h2>Ensure output before input</h2>\n\n<p><code>stdout</code> may be byte, line, or fully buffered. Insure output is seen before requesting user input. Often printing a <code>'\\n'</code> is sufficient - except that the code here does not have that in the prompts. <code>fflush(stdout)</code> always works.</p>\n\n<pre><code>printf(howManySides);\nfflush(stdout); // add\nif(scanf(\"%i\", &amp;userInput) &lt; 1) {\n</code></pre>\n\n<h2>Avoid undefined behavior</h2>\n\n<p>See why not to use <a href=\"https://stackoverflow.com/questions/2979209/using-fflushstdin\"><code>fflush(stdin)</code></a>.</p>\n\n<p>Tip: ditch <code>scanf()</code>; use <code>fgets()</code> for robust error handing.</p>\n\n<h2>Infinite loop</h2>\n\n<p>Should <code>scanf(\"%i\", &amp;userInput) &lt; 1)</code> return <code>EOF</code> due to end-of-file, code loops infinitely. Instead, when the return is <code>EOF</code>, consider ending the program or at least get out of the loop.</p>\n\n<h2>Avoid magic numbers</h2>\n\n<p>Rather than hard code <code>3, 12</code> and their effects in various places in code, create constants.</p>\n\n<pre><code>#define POLY_MIN 3\n#define POLY_N (sizeof names/sizeof names[0])\n#define POLY_MAX (POLY_N + POLY_MIN - 1)\n\n// if(numSides &lt;= 12) {\n// name = names[numSides - 3];\nif(numSides &lt;= POLY_MAX) {\n name = names[numSides - POLY_MIN];\n</code></pre>\n\n<h2>Avoid naked equations</h2>\n\n<p>Sure <code>180 * (numSides - 2)</code> is grade school math, yet often a reference is useful.</p>\n\n<pre><code>// en.wikipedia.org/wiki/Internal_and_external_angles#Properties\nreturn 180 * (numSides - 2);\n</code></pre>\n\n<hr>\n\n<h1>Minor stuff</h1>\n\n<h2>Curious type selection</h2>\n\n<p>Unclear why <code>getSumInteriorAngles()</code> uses <code>unsigned</code>. Function is only used once and it is called with <code>int</code></p>\n\n<pre><code>// static int getSumInteriorAngles(const unsigned int numSides)\nstatic int getSumInteriorAngles(const int numSides)\n</code></pre>\n\n<h2>Sometimes <code>const</code>, sometimes not</h2>\n\n<p>Some functions declare parameters as <code>const</code> and others do not, even though the parameter is not modified in both. Hmmm. IAC, I see it more as clutter than useful. As with such style issues, code to your group's coding standard.</p>\n\n<h2><code>do</code> loop candidate</h2>\n\n<pre><code>bool isValidResponse = false;\nwhile(!isValidResponse) {\n ...\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-11T19:10:05.887", "Id": "453308", "Score": "0", "body": "Thank you for your review. In ```getUserInput()```, how can I use ```fgets()``` to check if the input is strictly an integer?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-11T19:21:34.507", "Id": "453314", "Score": "0", "body": "I would use `strtol` (`stdlib.h`) and check the result carefully, then cast to `int` when you are sure it's between `[INT_MIN, INT_MAX]` (`limits.h`.) https://pubs.opengroup.org/onlinepubs/9699919799/functions/strtol.html" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-11T23:30:18.103", "Id": "453340", "Score": "1", "body": "@Neil Also when the result is outside the `int` range, it should be set to `INT_MAX/INT_MIN` and set `errno`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-12T00:41:39.367", "Id": "453345", "Score": "0", "body": "As seen in https://stackoverflow.com/a/29378380/2472827 or https://stackoverflow.com/a/57860925/2472827." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-11T07:56:24.180", "Id": "232172", "ParentId": "232135", "Score": "4" } }, { "body": "<p>We can eliminate the magic number <code>12</code> here:</p>\n\n<blockquote>\n<pre><code>/* If we have a name for this polygon, then get it from the table. */\nif(numSides &lt;= 12) {\n name = names[numSides - 3];\n}\n</code></pre>\n</blockquote>\n\n<p>The common idiom for determining the number of elements in an array works by using the size of the array and the size of each element:</p>\n\n<pre><code>static const int max_sides = sizeof names / sizeof *names;\n</code></pre>\n\n<p>We can eliminate the constant <code>3</code> even more easily, by including dummy (unused) elements at the beginning of the array:</p>\n\n<pre><code>/* polygon names up to 12 sides */\nconst char* names[] = {\n \"(point)\",\n \"(line)\",\n \"(line)\",\n \"a triangle\",\n \"a quadrilateral\",\n \"a pentagon\",\n \"a hexagon\",\n</code></pre>\n\n<p>Here, I've included some descriptive strings for the invalid cases, which makes debugging easier should we accidentally use one of them. We could save a tiny bit of program size by making them null pointers instead.</p>\n\n<p>With those changes, the code I quoted becomes this:</p>\n\n<pre><code>/* If we have a name for this polygon, then get it from the table. */\n\nstatic const int max_sides = sizeof names / sizeof *names;\n\nif (numSides &lt; max_sides) {\n name = names[numSides];\n}\n</code></pre>\n\n<p>Or, making it constant:</p>\n\n<pre><code>const char *const name = numSides &lt; max_sides\n ? names[numSides]\n : \"this polygon\";\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-12T09:15:03.707", "Id": "232231", "ParentId": "232135", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-10T01:33:16.057", "Id": "232135", "Score": "8", "Tags": [ "c" ], "Title": "Calculate the sum of interior angles of a polygon - follow-up" }
232135
<p>This challenge took me forever. I spent a lot of time messing with regular expressions, but couldn't get it to work. I ended up coming up with this abomination. If anybody wants to take the time I'm interested in simpler ways to accomplish this task. (I'm a brand new pythoner)</p> <pre><code>def is_stressful(subj): """ recognise a stressful email subject we are looking for any of: all uppercase, or ending in 3 !!!, or containing 'help', 'asap', or 'urgent' despite have extraneous spellings """ import string flagged_words = ['help', 'asap', 'urgent'] if subj[-3:] == '!!!': # check for ending in at least 3 !!! return True if subj.isupper(): # check for uppercase return True stripped = "".join(c for c in subj if c not in string.punctuation) # get rid of confusing characters wordlist = stripped.lower().split(' ') # make the list to check for word in wordlist: # first easy check, everything is spelled correctly if word in flagged_words: return True for word in wordlist: # start the annoying check, getting rid of extra letters in flagged words r = 0 # our word list counter getgood = [] badletters = [] while r &lt; len(flagged_words): # start the loop for i, l in enumerate(word): # going through each character if l in flagged_words[r]: # checking for good letters if l not in getgood: getgood.append(l) # no repeats except for 'a' in asap (don't know a good way for this) elif l == 'a' and getgood.count('a') &lt; 2: getgood.append(l) else: badletters.append(False) # make sure we don't spell flagged words accidentally r += 1 # go to the next word in list i = 0 # reset letter counter if ''.join(getgood) in flagged_words and all(badletters): # our final check return True getgood = [] # reset the loop badletters = [] # reset the loop return False </code></pre> <p>My tests:</p> <pre><code>print(is_stressful("H!E!L!P! its urGent asAP")) print(is_stressful("asaaap")) print(is_stressful("Headlamp, wastepaper bin and supermagnificently")) print(is_stressful("I neeed advice!!!!")) </code></pre> <p>Thanks for any tips!</p>
[]
[ { "body": "<p><strong><em>Improvements with a new solution:</em></strong></p>\n\n<ul>\n<li><p><code>import string</code>. If the function is a top-level commonly used function - better to move that <em>import</em> at the top of enclosing module.<br>Though in my proposed solution <code>string</code> won't be used.</p></li>\n<li><p><code>flagged_words</code>. Instead of generating a list of flagged words on every function's call - make it a constant with immutable data structure defined in the outer scope:</p>\n\n<pre><code>FLAGGED_WORDS = ('help', 'asap', 'urgent')\n</code></pre></li>\n<li><p>empty <code>subj</code>. To avoid multiple redundant checks/conditions on empty <code>subj</code> argument, if such would be passed in, a better way is handling an empty string at start:</p>\n\n<pre><code>subj = subj.strip()\nif not subj:\n raise ValueError('Empty email subject!')\n</code></pre></li>\n<li><p><code>if subj[-3:] == '!!!'</code> and <code>if subj.isupper()</code> checks lead to the same result.<br>That's a sign for applying <em>Consolidate conditional expression</em> technique - the conditions are to be combined with logical <code>or</code> operator</p></li>\n<li><p>the last <code>for ... while ... for</code> traversal looks really messy and over-complicated.<br>When trying to untangle that, your test cases allowed me to make an assumption that the crucial function (besides of trailing <code>!!!</code> chars and all upper-cased letters) should <em>catch</em>:</p>\n\n<ul>\n<li>exact word match with any of the <em>flagged</em> words, like <code>urGent asAP</code> (test case #1)</li>\n<li>exact word match with repetitive <em>allowed</em> chars like <code>asaaap</code> (test case #2) </li>\n</ul>\n\n<p>and should <strong>not</strong> allow strings that contain only words which combine both allowed and unallowed chars like <code>Headlamp</code> or <code>wastepaper</code> (though they contain <code>he..l..p</code>, <code>.as....ap..</code>) (test case #3)</p></li>\n</ul>\n\n<hr>\n\n<p>Instead o going into a mess of splitting/loops I'd suggest a complex <em>regex</em> solution that will cover both <em>exact word matching</em> and <em>exact matching with repetitive allowed chars</em> cases.<br>The underlying predefined pattern encompasses the idea of <em>quantifying</em> each char in each <em>flagged</em> word like <code>h+e+l+p+</code> with respect for word boundaries <code>\\b</code>:</p>\n\n<pre><code>import re\n\nFLAGGED_WORDS = ('help', 'asap', 'urgent')\n\n\ndef quantify_chars_re(words):\n \"\"\"Adds `+` quantifier to each char for further use in regex patterns\"\"\"\n return [''.join(c + '+' for c in w) for w in words]\n\n\nRE_PAT = re.compile(fr\"\\b({'|'.join(quantify_chars_re(FLAGGED_WORDS))})\\b\", re.I)\n\n\ndef is_stressful(subj):\n \"\"\"\n Recognize a stressful email subject\n we are looking for any of: all uppercase, or ending in 3 !!!, or\n containing 'help', 'asap', or 'urgent' despite have extraneous spellings\n \"\"\"\n\n subj = subj.strip()\n if not subj:\n raise ValueError('Empty email subject!')\n\n if subj.isupper() or subj[-3:] == '!!!' or RE_PAT.search(subj):\n return True\n\n return False\n\n\nif __name__ == \"__main__\":\n print(is_stressful(\"H!E!L!P! its urGent asAP\"))\n print(is_stressful(\"asaaap\"))\n print(is_stressful(\"Headlamp, wastepaper bin and super-magnificently\"))\n print(is_stressful(\"I neeed advice!!!!\"))\n</code></pre>\n\n<p>The output:</p>\n\n<pre><code>True\nTrue\nFalse\nTrue\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-10T22:49:10.443", "Id": "453187", "Score": "0", "body": "That messy complicated loop I made was exactly why I posted this. I'm glad you were at least able to decipher what it was trying to accomplish. (my test cases) the regex was my initial attempt, but I need a lot more practice understanding. Your code is very clean and concise. I learned a lot from it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-10T22:55:47.773", "Id": "453189", "Score": "0", "body": "Your quantify_chars is a very elegant solution. What was difficult for me with regex is returning proper results on the flagged words that were spelled with extra letters." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-11T07:56:27.593", "Id": "453217", "Score": "0", "body": "@spence, you're welcome, glad to help" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-11T08:55:26.617", "Id": "453223", "Score": "0", "body": "`FLAGGED_WORDS` should probably be a `set`. As long as it contains only three words it doesn't matter, but it will probably contain more. And it's spelled qua**n**tify." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-11T09:14:49.340", "Id": "453226", "Score": "1", "body": "@Graipher, thanks for a spelling hint \"qua**n**tify\" (I also noted \"recogni**s**e\")" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-11T09:23:57.983", "Id": "453227", "Score": "1", "body": "@Graipher A frozenset, in that case. There's a good reason to make it immutable." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-11T10:00:36.033", "Id": "453230", "Score": "0", "body": "@RomanPerekhrest Just a little nitpicking: *recognise* vs. *recognize* is a British vs. American English thing. Depending on what you aim for, either could be correct." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-10T09:54:09.493", "Id": "232139", "ParentId": "232138", "Score": "3" } } ]
{ "AcceptedAnswerId": "232139", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-10T07:58:02.587", "Id": "232138", "Score": "2", "Tags": [ "python", "python-3.x", "strings" ], "Title": "Simple Email Subject Filtering (python)" }
232138
<p>As my applications rely on VT-100 emulation, I found that I had to do quite a few workarounds to determine the number of visible characters in a string with embedded VT-100 control codes. So that led to the design of this 73 byte snippet.</p> <p>Function would be called as follows;</p> <pre><code> xor edx, edx ; ARG1 - DX = 0 Search for first NULL. mov ecx, edx ; ARG1 - Not more than ECX chars. mov esi, SignOn ; ARG0 - Pointer to ASCII string. call FindChr ; Length of string returned in RAX. </code></pre> <p>with text @ 0x40017c</p> <pre><code>SignOn db 27, '[2J', 27, '[1;37m', 27, '[2;000H' db 'Horizons Buisness ', 27, '[42m&amp; Personal Finance' db 27, '[40;39m', 0 </code></pre> <p>which returns<br> RAX = 0x24 = 36<br> RCX = 0xffffffbc = negated (0x44 = 68)<br> RSI = 0x4001c0</p> <blockquote> <p>Assembled using NASM 2.13.02</p> </blockquote> <pre><code>; ============================================================================= ; Search for character defined in DL but not past one in DH for a maximum ; count of ECX. Ignore VT-100 control codes but there are considered in ; total buffer size specified in RCX. ; ENTER: RSI = Pointer to ASCII string. ; ECX = Maximum interations (if 0 then 4,294,967,295). ; DL = unsigned char to match. ; DH = not beyond this character (terminator). ; LEAVE: EAX = Total printable characters. ; RSI = Points to match char in DL or RSI+1 if DH. ; = If SF (overflow) end of buffer + 1. ; ECX = Bytes remaining ; = If SF -1 (0xffffffff) ; DX = Unchanged. ; Total length of string can be derived from either ; negating ECX if ECX was zero on entry ; or ECX - original ECX - 1 ; FLAGS: ZF = Match found (DL) ; NZ = Match found (DH) ; JS = ECX exhausted (overflow) ESC equ 27 ; 0x1b o033 11011b ; ------------------------------------------------------------------------- FindChr: push rbx xor ebx, ebx ; Set initial character count. ; As this is essentially a do -&gt; while (maxCount &gt;=0) if there is a ; non-zero value in ECX it must be zero indexed so the proper number of ; of characters are evaluated. test ecx, ecx jz $ + 4 dec ecx ; Zero index max buffer count. .L0: mov al, [rsi] cmp al, ESC ; Test for beginning of VT-100 code first. jnz .J0 ; ---------- ; If the next character is left bracket, then it is a VT-100 code. cmp byte [rsi+1], '[' jnz .J0 ; NZ = Consider ESC a printable char .l0: dec ecx jz .done - 2 lodsb cmp al, 'A' jae .j0 ; There are two codes that are not terminated with an alphabetic char ; that are used to select fonts. cmp al, '(' jz .L0 cmp al, ')' jnz .l0 ; Must be still inside control code ; This works as we are only concered with alphabetic chars. .j0: and al, 0x5f ; Convert to upper case cmp al, 'Z' jbe .L0 ; CY or ZF we are at end of VT-100 code. jmp .l0 ; Continue scanning inside VT-100 code ; ---------- .J0: cmp al, dl ; Is char we are looking for? jz .done ; ZF = Stay at char just read and exit inc rsi ; Bump pointer to next character cmp al, dh ; Is it delimiter jnz .J1 test esi, esi ; So NZ is set. jmp .done ; Return with SF. .J1: inc ebx ; Bump count of printable characters dec ecx ; and maximum buffer count jnz .L0 dec ecx ; Sets sign flag .done: mov eax, ebx ; Return char count in RAX pop rbx ret </code></pre> <p><strong>NOTE</strong> The need for pointer to first printable character arose, so I've made this amendment.</p> <pre><code> .J1: inc ebx ; Bump count of printable characters dec ecx ; and maximum buffer count jz .done - 2 ; This will set a pointer to first printable character in string test rdi, rdi jnz .L0 ; Update pointer to address just before current RSI mov rdi, rsi dec rdi jmp .L0 </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-10T17:36:34.063", "Id": "453168", "Score": "0", "body": "Why did you decide to write this code in assembler, instead of the simpler C?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-10T19:48:51.947", "Id": "453177", "Score": "0", "body": "@RolandIllig Simpler is a subjective term in so much as if you understand C, then it may very well be, but even at that, C will never come in as tight as assembly. Probably in no small part to System V ABI. In this case, two of the values would need to have been passed by reference. Secondly, many of my functions because the calculation or comparison has already been done, assert flags that the caller can use, eliminating redundant comparisons. My primary objective is algorithmic flow to pack as much computing with the least amount of code. In assembly I need only understand instruction set." } ]
[ { "body": "<p>Your code is a nightmare.</p>\n\n<p>This is mainly because all the jump labels have very similar names: L0, l0, j0, J0, J1. What the hell do they mean? Please use more descriptive names for them.</p>\n\n<p>The assembly code you are using does not make use of any advanced features of machine language. Instead, only the variable names get worse. It's far easier for a human reader to guess what <code>str</code> means than to guess what <code>esi</code> means. As another example, <code>needle</code> and <code>terminator</code> are much more intuitive than <code>dl</code> and <code>dh</code>.</p>\n\n<p>You happily mix 32-bit registers (<code>ecx</code>) with 64-bit registers (<code>rsi</code>). This is confusing.</p>\n\n<p>A single example string is not enough to make an exhaustive test suite. You need at least enough examples to cover each path of the code.</p>\n\n<p>There is no <code>JS</code> flag in the x86 instruction set.</p>\n\n<p>There is no guarantee near <code>Return with SF</code> that <code>test esi, esi</code> really sets the sign flag.</p>\n\n<p>I rewrote your code in C, just for fun, and it became 50% the size. It's possible to cut that code down by another 50% by using higher-level control structures instead of only <code>goto</code>. Most of the saving comes from just deleting comments that describe on the assembler level what the C code can express directly.</p>\n\n<p>Basically what you wrote is just a little state machine with a couple of special cases. Nothing you would really need assembler for. Especially not since the VT100 escape sequences are so closely coupled with I/O that it's usually not worth squeezing the last bit of performance out of this code.</p>\n\n<p>Debugging a C program is easier as well, since you have named variables and you cannot get confused by the <code>edi</code> register, which is always visible in the debug view but not relevant for this piece of code.</p>\n\n<p>Here's my try of transforming the code to C, just to give you something to play with. It's still far from good code, but at least any good IDE can rename variables to make the helpful names guide the human reader.</p>\n\n<pre class=\"lang-c prettyprint-override\"><code>#include &lt;stdbool.h&gt;\n#include &lt;stddef.h&gt;\n\nstruct str_width_result {\n size_t width;\n const unsigned char *end;\n size_t remaining;\n bool found;\n bool eof;\n};\n\nstatic struct str_width_result\nstr_width(const char *str, size_t str_size, char needle, char terminator)\n{\n const unsigned char *rsi = str;\n size_t ecx = str_size;\n unsigned char dl = needle;\n unsigned char dh = terminator;\n unsigned char ESC = 0x1B;\n size_t ebx = 0;\n if (ecx == 0) ecx--;\n\nL0:\n if (rsi[0] != ESC) goto J0;\n if (rsi[1] != '[') goto J0;\n\nl0:\n ecx--;\n if (ecx == 0) goto done_minus_2;\n\n unsigned char al = *rsi++;\n if (al &gt;= 'A') goto j0;\n\n if (al == '(') goto L0;\n if (al == ')') goto l0;\n\nj0:\n al &amp;= 0x5f;\n if (al &lt;= 'Z') goto L0;\n goto l0;\n\nJ0:\n if (al == dl) goto done;\n\n rsi++;\n if (al == dh) goto J1;\n\nJ1:\n ebx++;\n ecx--;\n if (ecx != 0) goto L0;\n\ndone_minus_2:\n ecx--;\n\ndone:;\n\n struct str_width_result result = {\n .width = ebx,\n .end = rsi,\n .remaining = ecx,\n .found = false, // TODO\n .eof = false // TODO\n };\n return result;\n}\n\n#define ESC \"\\033\"\n\n#include &lt;stdio.h&gt;\n\nint main(void)\n{\n const char str[] =\n ESC \"[2J\" ESC \"[1;37m\" ESC \"[2;000H\"\n \"Horizon Business \"\n ESC \"[42m\" \"&amp; Personal Finance\"\n ESC \"[40;39m\";\n\n struct str_width_result result = str_width(str, sizeof str, '\\0', '\\0');\n\n printf(\"%zu %p\\n\", result.width, (void *)result.end);\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-10T23:53:36.373", "Id": "453194", "Score": "0", "body": "I definitely agree about the labels, but as the editor I'm using doesn't auto complete, I try to stay away from more typing than I have too. On that note, I do agree, if it isn't intuitive for the person that hasn't written it, then it might just as well be written in hieroglyphs. Yes, `JS` should have been `SF`. The use of 64 vs 32 bit registers is not random. I make use of sign extension and where I know pointers are in the lower half. No point using `XOR RAX,RAX` when `XOR EAX,EAX` does exactly the same thing and save 1 byte of opcode" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-11T00:01:24.410", "Id": "453199", "Score": "0", "body": "I am curious to see how you compiled your code to bring the object size of `str_width` to 44 bytes as my version with ammendment added is 88. Even more interesting would be how you'd make it 50% less than that again. I'm not trying to be factious as I've always been curious about this as my HLL skills have not yielded similar results." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-10T23:11:34.880", "Id": "232167", "ParentId": "232140", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-10T10:37:10.297", "Id": "232140", "Score": "3", "Tags": [ "console", "linux", "assembly" ], "Title": "Ubuntu 18.04.3 ASCII strings length with embedded VT100 control codes" }
232140
<p>I have a simple integer sorting problem at hand and to solve it, I am planning to write a variation of bubble sort. It seems to be working fine but I am not sure about it's complexity in big-O. What it could be ?</p> <pre><code>public class TempBubbleSort { static Integer[] myArray = {10,9,8,7,6,5,4,3,2,1}; static int counter = 0; public static void main(String[] args) { for(int anchor=0; anchor&lt;myArray.length; anchor++) { for(int compare=anchor+1; compare&lt;myArray.length; compare++) { counter++; // sort ascending if(myArray[anchor] &gt; myArray[compare]) { int tmp = myArray[compare]; myArray[compare] = myArray[anchor]; myArray[anchor] = tmp; } } } System.out.println("Comparision Count : "+counter); for(int i : myArray) System.out.println(i); } } </code></pre> <p>Output when you run above is : </p> <pre><code>Comparision Count : 45 1 2 3 4 5 6 7 8 9 10 </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-10T11:28:17.480", "Id": "453139", "Score": "0", "body": "There already better sorting algorithms which you can just use. Why struggling with writing worse on your own?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-10T11:40:32.867", "Id": "453140", "Score": "0", "body": "Also note that `static Integer[] myArray = {10,9,8,7,6,5,4,3,2,1};` hits an edge case." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-10T12:02:55.617", "Id": "453142", "Score": "0", "body": "Agreed with @πάνταῥεῖ. I realize that what I had written is more similar selection sort than bubble. And complexity will in closer to selection sort. Thanks for your input." } ]
[ { "body": "<p>Strictly answering your question about what the <span class=\"math-container\">\\$Big-O\\$</span> run-time complexity,</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>public class TempBubbleSort \n{\n\nstatic Integer[] myArray = {10,9,8,7,6,5,4,3,2,1};\n\nstatic int counter = 0;\n\npublic static void main(String[] args)\n{\n // **This is O(n), as we're touching every point in your array.\n for(int anchor=0; anchor&lt;myArray.length; anchor++)\n {\n // **This is O(n-1), but since we don't care about constants as n grows, we consider this as O(n)\n for(int compare=anchor+1; compare&lt;myArray.length; compare++)\n {\n // **Everything in here then is a bunch of constant operations so we'll just ignore them.\n counter++;\n // sort ascending\n if(myArray[anchor] &gt; myArray[compare])\n {\n int tmp = myArray[compare];\n myArray[compare] = myArray[anchor];\n myArray[anchor] = tmp;\n }\n }\n }\n // **So the total of the brunt of your work would be O(n)*O(n) or O(n^2), because for every element in your array n, you touch every other element in your array, so you can look at it as touching n things in your array, n times.\n\n System.out.println(\"Comparision Count : \"+counter);\n\n // **In case you're curious, this is also O(n)\n for(int i : myArray)\n System.out.println(i);\n\n // **Which would bring the grand total to O(n^2+n), again with Big O notation, we only care about what happens as n continues to grow, and since n^2 grows faster than n, as our n gets super big, the second term n becomes insignificant, so we look at this overall total as O(n^2). In fact, for any polynomial time complexity, you can safely drop all terms that are not your largest degree.\n}\n\n\n}\n\n</code></pre>\n\n<p>In closing, its usually easy to tell the time-complexity of simple iterative functions like this by the number of nested for loops you have, which can be a good rule of thumb for a nice approximate guess for time complexity in a pinch.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-14T21:06:59.520", "Id": "232409", "ParentId": "232142", "Score": "3" } } ]
{ "AcceptedAnswerId": "232409", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-10T11:20:03.813", "Id": "232142", "Score": "0", "Tags": [ "java", "sorting" ], "Title": "Complexity of bubble sort" }
232142
<p>This game is made for JFrame. You can control using the arrows. The numbers in the cells are the degrees of the number 2. It is possible to change the initial position of the window, its size, and the number of rows-columns(they are equal) in the field. You can also change the width of the frames of the cells, indent between them. You can adjust what degree of the number 2 you need to get in order to win. I hope that you point out to me weaknesses in my code, if any.</p> <p><a href="https://i.stack.imgur.com/pKrA5.png" rel="noreferrer"><img src="https://i.stack.imgur.com/pKrA5.png" alt="normal"></a> <a href="https://i.stack.imgur.com/kw8E0.png" rel="noreferrer"><img src="https://i.stack.imgur.com/kw8E0.png" alt="mod"></a></p> <p>main method:</p> <pre><code> final int windowXPos = 100; final int windowYPos = 100; final int windowWidthAndHeight = 800; final int spacesBetweenCells = 4; final int widthOfFrame = 4; final int inARow = 4; final int valueOfCellToWin = 11; GameWindow2048 window = new GameWindow2048(windowXPos,windowYPos, windowWidthAndHeight, spacesBetweenCells, widthOfFrame, inARow, valueOfCellToWin); </code></pre> <p>class Area skeleton:</p> <pre><code>public class Area { Cell[][] area; final int valueOfCellToWin; public Area(int inARow, int valueOfCellToWin) { area = new Cell[inARow][inARow]; fillAreaWithEmpty(); addNewCell(); addNewCell(); this.valueOfCellToWin = valueOfCellToWin; } private void fillAreaWithEmpty() { for(int y = 0; y &lt; area.length; y++) { for(int x = 0; x &lt; area[0].length; x++) { area[y][x] = new Cell(); area[y][x].setEmpty(); } } } void playAgain() { fillAreaWithEmpty(); addNewCell(); addNewCell(); } boolean isWin() {} boolean addNewCell(){} void makeAMove(Direction direction) {} private int getAmountOfEmptyCells() {} } </code></pre> <p>class Area full code:</p> <pre><code>public class Area { Cell[][] area; final int valueOfCellToWin; public Area(int inARow, int valueOfCellToWin) { area = new Cell[inARow][inARow]; fillAreaWithEmpty(); addNewCell(); addNewCell(); this.valueOfCellToWin = valueOfCellToWin; } private void fillAreaWithEmpty() { for(int y = 0; y &lt; area.length; y++) { for(int x = 0; x &lt; area[0].length; x++) { area[y][x] = new Cell(); area[y][x].setEmpty(); } } } void playAgain() { fillAreaWithEmpty(); addNewCell(); addNewCell(); } boolean isWin() { for(int y = 0; y &lt; area.length; y++) { for(int x = 0; x &lt; area[0].length; x++) { if(area[y][x].getPowerOf2() == valueOfCellToWin) { return true; } } } return false; } boolean addNewCell(){ int amountOfEmptyCells = getAmountOfEmptyCells(); int numOfCellToFill; int counterOfEmptyCells = 0; if(amountOfEmptyCells == 0) { return false; } numOfCellToFill = Math.abs(new Random().nextInt()%amountOfEmptyCells)+1; out: for(int y = 0; y &lt; area.length; y++) { for(int x = 0; x &lt; area[0].length; x++) { if(area[y][x].isEmpty()) { counterOfEmptyCells++; if(counterOfEmptyCells == numOfCellToFill) { area[y][x].setBeginNumber(); break out; } } } } return true; } void makeAMove(Direction direction) { if(direction == Direction.UP) { for(int x = 0; x &lt; area[0].length; x++) { for(int y = 1; y &lt;= area.length - 1; y++) { if(y == 0) { continue; } if(area[y][x].isEmpty()) { continue; } if(area[y-1][x].isEmpty()) { //empty above - move there area[y-1][x].setPowerOf2(area[y][x].getPowerOf2()); area[y][x].setEmpty(); y-=2; //as we may need to move this cell even higher. continue; } if(area[y][x].getPowerOf2() == area[y-1][x].getPowerOf2()) { // are the same? make a merge area[y][x].setEmpty(); area[y-1][x].increasePowerOf2(); // merging occurs, above the cell y-1 x there are no empty cells according to the algorithm, therefore we do not return } } } } if(direction == Direction.DOWN) { for(int x = 0; x &lt; area[0].length; x++) { for(int y = area.length - 2; y &gt;= 0; y--) { if(y == area.length - 1) { continue; } if(area[y][x].isEmpty()) { continue; } if(area[y+1][x].isEmpty()) { area[y+1][x].setPowerOf2(area[y][x].getPowerOf2()); //empty below - move there area[y][x].setEmpty(); y+=2; //as we may need to move this cell even lower. continue; } if(area[y][x].getPowerOf2() == area[y+1][x].getPowerOf2()) { area[y][x].setEmpty(); area[y+1][x].increasePowerOf2(); // merging occurs, below the cell y + 1 x there are no empty cells according to the algorithm, so do not return } } } } if(direction == Direction.RIGHT) { for(int y = 0; y &lt; area.length; y++) { for(int x = area[0].length - 2; x &gt;=0; x--) { if(x == area.length - 1) { continue; } if(area[y][x].isEmpty()) { continue; } if(area[y][x+1].isEmpty()) { area[y][x+1].setPowerOf2(area[y][x].getPowerOf2()); area[y][x].setEmpty(); x+=2; //as we may need to move this cell to the right. continue; } if(area[y][x].getPowerOf2() == area[y][x+1].getPowerOf2()) { area[y][x].setEmpty(); area[y][x+1].increasePowerOf2(); //merging occurs, to the right of the cell y x+1 there are no empty cells according to the algorithm, so do not return } } } } if(direction == Direction.LEFT) { for(int y = 0; y &lt; area.length; y++) { for(int x = 1; x &lt;= area[0].length-1; x++) { if(x == 0) { continue; } if(area[y][x].isEmpty()) { continue; } if(area[y][x-1].isEmpty()) { area[y][x-1].setPowerOf2(area[y][x].getPowerOf2()); area[y][x].setEmpty(); x-=2; // as we may need to move this cell to the left. continue; } if(area[y][x].getPowerOf2() == area[y][x-1].getPowerOf2()) { area[y][x].setEmpty(); area[y][x-1].increasePowerOf2(); //merging occurs, to the left of the cell y x-1 there are no empty cells according to the algorithm, so do not return } } } } } private int getAmountOfEmptyCells() { int amountOfEmptyCells = 0; for(int y = 0; y &lt; area.length; y++) { for(int x = 0; x &lt; area[0].length; x++) { if(area[y][x].isEmpty()) { amountOfEmptyCells++; } } } return amountOfEmptyCells; } Cell[][] getArea() { return area; } } </code></pre> <p>enum GamesState fullcode:</p> <pre><code>enum GamesState{ CONTINUETHEGAME, WIN, DEFEAT } </code></pre> <p>class Cell fullcode:</p> <pre><code>class Cell{ private int powerOf2; // 0 - is emptyCell void setBeginNumber() { powerOf2 = (Math.abs(new Random().nextInt()%10) != 9) ? 1 : 2; } void increasePowerOf2() { this.powerOf2++; } int getPowerOf2() { return powerOf2; } boolean isEmpty() { return powerOf2 == 0; } void setPowerOf2(int powerOf2) { this.powerOf2 = powerOf2; } void setEmpty() { this.powerOf2 = 0; } } </code></pre> <p>class Component:</p> <pre><code>public class Component extends JPanel { final Cell[][] area; final int windowWidthAndHeight; final int widthOfOneCellInsideFrame; final int spacesBetweenCells; final int widthOfFrame; final int widthOfRectOfFrame; final int fontSize; final Font font; GamesState statusOfGame = GamesState.CONTINUETHEGAME; public Component(Cell[][] area, int windowWidthAndHeight, int spacesBetweenCells, int widthOfFrame) { this.area = area; this.windowWidthAndHeight = windowWidthAndHeight; this.spacesBetweenCells = spacesBetweenCells; this.widthOfFrame = widthOfFrame; widthOfOneCellInsideFrame = (windowWidthAndHeight - (2 * area.length * widthOfFrame + (area.length - 1) * spacesBetweenCells)) / area.length; widthOfRectOfFrame = widthOfFrame * 2 + widthOfOneCellInsideFrame; fontSize = widthOfOneCellInsideFrame / 3; font = new Font("Tahoma", Font.BOLD|Font.ITALIC, fontSize); } @Override public void paintComponent(Graphics gr){ gr.clearRect(0, 0, windowWidthAndHeight, windowWidthAndHeight); gr.setColor(Color.lightGray); gr.fillRect(0,0, windowWidthAndHeight, windowWidthAndHeight); System.out.println(statusOfGame); if(statusOfGame == GamesState.CONTINUETHEGAME) { printArea(gr); } else if (statusOfGame == GamesState.WIN){ gr.setColor(Color.BLUE); gr.setFont(new Font("Tahoma", Font.BOLD|Font.ITALIC, windowWidthAndHeight / 25)); gr.drawString("U WON! If u wanna play again, press 'r'", windowWidthAndHeight/6,windowWidthAndHeight/3); } else { gr.setColor(Color.RED); gr.setFont(new Font("Tahoma", Font.BOLD|Font.ITALIC, windowWidthAndHeight / 25)); gr.drawString("DEFEAT! If u wanna try again, press 'r'", windowWidthAndHeight/6,windowWidthAndHeight/3); } } void printArea(Graphics gr) { for(int y = 0, YPos; y &lt; area.length; y++) { for(int x = 0, XPos; x &lt; area[0].length; x++) { YPos = 2 * y * widthOfFrame; XPos = 2 * x * widthOfFrame; if(y != 0) { YPos += y * (spacesBetweenCells + widthOfOneCellInsideFrame); } if(x != 0) { XPos += x * (spacesBetweenCells + widthOfOneCellInsideFrame); } gr.setColor(Color.BLACK); gr.fillRect(XPos,YPos, widthOfRectOfFrame, widthOfRectOfFrame); gr.setColor(Color.BLUE); gr.fillRect(XPos + widthOfFrame,YPos + widthOfFrame, widthOfOneCellInsideFrame, widthOfOneCellInsideFrame); gr.setColor(Color.MAGENTA); if(!area[y][x].isEmpty()) { gr.setFont(font); gr.drawString(Integer.toString(area[y][x].getPowerOf2()), XPos + widthOfFrame + (widthOfOneCellInsideFrame / 2) - fontSize / 4, YPos + widthOfFrame + (widthOfOneCellInsideFrame / 2) - fontSize / 4); } } } } public void setGameState(GamesState statusOfGame) { this.statusOfGame = statusOfGame; } } </code></pre> <p>class GameWindow2048 with enum Direction:</p> <pre><code>public class GameWindow2048 extends JFrame{ final int windowWidthAndHeight; final int spacesBetweenCells; final int widthOfFrame; final Area area; final Component component; Direction directionTemp; GamesState statusOfGame = GamesState.CONTINUETHEGAME; public GameWindow2048(int windowXPos, int windowYPos, int windowWidthAndHeight, int spacesBetweenCells, int widthOfFrame, int inARow, int valueOfCellToWin){ // сделать builder this.windowWidthAndHeight = windowWidthAndHeight; this.spacesBetweenCells = spacesBetweenCells; this.widthOfFrame = widthOfFrame; addKeyListener(new myKey()); setFocusable(true); setBounds(windowXPos,windowYPos,windowWidthAndHeight,windowWidthAndHeight + 20); //20 - калибровка setTitle("2048"); Container container = getContentPane(); area = new Area(inARow, valueOfCellToWin); component = new Component(area.getArea(), windowWidthAndHeight - 14, spacesBetweenCells, widthOfFrame); //14 - калибровка container.add(component); setVisible(true); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } public class myKey implements KeyListener{ public void keyReleased(KeyEvent e) { //game if(statusOfGame == GamesState.CONTINUETHEGAME) { directionTemp = getDirection(e); if(directionTemp != null) { area.makeAMove(directionTemp); if(!area.addNewCell()) { statusOfGame = GamesState.DEFEAT; component.setGameState(statusOfGame); } if(area.isWin()) { System.out.println("Win"); statusOfGame = GamesState.WIN; component.setGameState(statusOfGame); } } component.repaint(); } else { System.out.println(e.getKeyCode()); if(e.getKeyCode() == 82) { area.playAgain(); statusOfGame = GamesState.CONTINUETHEGAME; component.setGameState(statusOfGame); component.repaint(); } } } Direction getDirection(KeyEvent e) { switch(e.getKeyCode()) { case 39: return Direction.RIGHT; case 37: return Direction.LEFT; case 38: return Direction.UP; case 40: return Direction.DOWN; default: return null; } } public void keyPressed(KeyEvent e){} public void keyTyped(KeyEvent e){} } enum Direction{ RIGHT, LEFT, UP, DOWN } } </code></pre>
[]
[ { "body": "<p>I have some suggestions for your code, for me it's a good point you have separated graphic part from logic encapsulating game logic in two classes <code>Cell</code> and <code>Area</code>. Your class <code>Cell</code> at the moment just contains an integer value, so instead of declaring a matrix <code>Area</code> of <code>Cell</code> objects you could use a matrix of ints and redefine class <code>Area</code> like the code below:</p>\n\n<pre><code>public class Area {\n private int[][] area;\n private final int valueOfAreaToWin;\n private final int n;\n\n public Area(int n, int valueOfCellToWin) {\n this.area = new int[n][n];\n this.valueOfAreaToWin = valueOfCellToWin;\n this.n = n;\n }\n}\n</code></pre>\n\n<p>If you can try to do just initialization of fields in your class constructor and nothing else.\nThe use of a matrix of ints simplifies all the methods of your class because you modify a matrix of ints instead of calling methods of <code>Cell</code> class like the code below:</p>\n\n<pre><code>private void fillAreaWithZeros() {\n for (int[] row : area) {\n Arrays.fill(row, 0);\n }\n}\n\npublic int getAmountOfZeros() {\n int amount = 0;\n for (int i = 0; i &lt; n; ++i) {\n for (int j = 0; j &lt; n; ++j) {\n if (area[i][j] == 0) {\n ++amount;\n }\n }\n }\n return amount;\n}\n\npublic boolean isWin() {\n for (int i = 0; i &lt; n; ++i) {\n for (int j = 0; j &lt; n; ++j) {\n if (area[i][j] == 0) { return false; }\n }\n }\n return true;\n}\n</code></pre>\n\n<p>When you iterate over matrix elements, try to use <em>n</em>, <em>m</em> for number of rows and columns, <em>i</em> and <em>j</em> for indexes because they are expected to be usually found when you work with matrices.\nIn your method <code>addNewCell</code> I found the following code:</p>\n\n<blockquote>\n<pre><code>out:\nfor(int y = 0; y &lt; area.length; y++) {\n for(int x = 0; x &lt; area[0].length; x++) {\n if(area[y][x].isEmpty()) {\n counterOfEmptyCells++;\n if(counterOfEmptyCells == numOfCellToFill) {\n area[y][x].setBeginNumber();\n break out;\n }\n }\n }\n}\n</code></pre>\n</blockquote>\n\n<p>It is legitime to use a <em>label</em> but this complicates readibility of your code, to obtain the same behaviour you can create a <code>boolean</code> condition and check it inside your outer loop like below:</p>\n\n<pre><code>boolean cond = true;\nfor(int i = 0; i &lt; n &amp;&amp; cond; ++i) {\n for(int j = 0; j &lt; n; ++j) {\n if(area[i][j] == 0) {\n counterOfEmptyCells++;\n if(counterOfEmptyCells == numOfCellToFill) {\n int value = Math.abs(random.nextInt() % 10) != 9 ? 1 : 2;\n area[i][j] = value;\n cond = false;\n break;\n }\n }\n }\n}\n</code></pre>\n\n<p>Inside the inner if <code>cond</code> will be set to <code>false</code> before breaking the inner for, and the next check of the outer for will find cond equal to false and will terminate.</p>\n\n<p>Note: as @drekbour said in his comment below in this case because the composite loop is the last instruction of the method it is better directly return false inside the inner loop.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-11T21:57:13.107", "Id": "453332", "Score": "1", "body": "On that last point, why not just `return true` instead of checking `cond` all the time. This is the last activity of that method so nothing is gained by either variant compared to just returning." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-12T07:33:11.750", "Id": "453366", "Score": "0", "body": "@drekbour Good point, I add it to my answer as a note." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-12T07:35:50.010", "Id": "453367", "Score": "1", "body": "i think it is a **good** idea to have a cell class - since it's not a mere `integer` but it's really a `cell`. it's an antipattern: primitive obsession. Ever since the cell class provides very helpful methods..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-12T07:55:45.207", "Id": "453371", "Score": "0", "body": "the other things pointed out are very helpful +1" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-12T10:38:15.483", "Id": "453395", "Score": "0", "body": "@MartinFrank You are right for my primitive obsession :-) From the description of the game I found online it seems cells contain just a value initially set to zero that can be incremented in the game , so I thought about a matrix representing an internal state to simplify method calls. If there are game variations with cells containing more than one field, as you said it's a good idea to maintain the concept of cell." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-12T10:42:24.483", "Id": "453397", "Score": "0", "body": "i admire you being honest - primitive obsession is also one of my own very weakness...." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-13T10:22:23.540", "Id": "453584", "Score": "1", "body": "I should point out that OO-obsession is also a thing that needs moderating :) If you need to write any kind of computer player, you _may_ end up with many copies of the \"board\" in some kind of tree/search algorithm. Representing the state as a (single?) primitive array makes notable difference to your allocation rate and CPU cost." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-11T17:11:39.070", "Id": "232196", "ParentId": "232145", "Score": "5" } }, { "body": "<p>some minor issues</p>\n\n<h2>dry - dont repeat yourself</h2>\n\n<p><code>Area.moveADirection</code>is full of redundant code - try to create a method for all that is in common - may i suggest a method <code>void move (int dx, int dy)</code> that is applyable for <strong>any</strong> direction?</p>\n\n<p>another repetation is your code to iterate through cells in the <code>Area</code> class</p>\n\n<pre><code>for(int y = 0; y &lt; area.length; y++) {\n for(int x = 0; x &lt; area[0].length; x++) {\n ...\n }\n}\n</code></pre>\n\n<p>you could instead provide a method for that <code>List&lt;Cell&gt; getCells()</code>and use the java8 stream api for example:</p>\n\n<pre><code>private int getAmountOfEmptyCells() {\n //written straight out of my head without any compiler verification\n return getCells().stream().mapToInt(c -&gt; c.isEmpty?0:1).sum();\n}\n</code></pre>\n\n<h2>segregation of concerns</h2>\n\n<p>your cell should be able to draw itself. if it would do so, you could simplify your draw code in <code>Component</code>:</p>\n\n<pre><code>void printArea(Graphics gr) {\n area.getCells().forEach(c -&gt; c.draw(gr, XPos,YPos);\n}\n</code></pre>\n\n<p>and the cell would know how to draw itself, new code for <code>Cell</code> class:</p>\n\n<p><code>public void draw(Graphics grm int xpos, int ypos){...};</code></p>\n\n<h2>naming convention</h2>\n\n<p><code>public class myKey implements KeyListener</code> should be uppercase</p>\n\n<p><code>for(int y = 0, YPos; y &lt; area.length; y++) {</code> YPos should be <code>yPos</code> at least... where do you define <code>YPos??</code>, same for XPos</p>\n\n<h2>complexity</h2>\n\n<p>create a configuration object for your constructor to hanlde all those arguments - you can then even provide default parameters</p>\n\n<pre><code>class Configuration {\n final int windowXPos = 100;\n final int windowYPos = 100;\n final int windowWidthAndHeight = 800;\n final int spacesBetweenCells = 4;\n final int widthOfFrame = 4;\n final int inARow = 4;\n final int valueOfCellToWin = 11;\n}\n</code></pre>\n\n<p>that results into</p>\n\n<pre><code>Configuration defaultConfig = new Configuration();\ndefaultConfig.windowXPos = 123; //example to override default values\nGameWindow2048 window = new GameWindow2048(defaultConfig);\n</code></pre>\n\n<h2>input handling</h2>\n\n<p>instead of directly listening to keyevent you should use keybinding, see the <a href=\"https://docs.oracle.com/javase/tutorial/uiswing/misc/keybinding.html\" rel=\"nofollow noreferrer\">javaDoc tutorial page</a> </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-12T08:55:57.793", "Id": "453380", "Score": "1", "body": "hm, about \"Configuration\" - its a builder pattern. I thought about it, but didn’t think of setting default values." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-12T10:36:37.223", "Id": "453394", "Score": "0", "body": "best you would offer (aside from default constructor) a constructor from file, where you have all those settings already in a properties file." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-13T10:32:49.927", "Id": "453588", "Score": "1", "body": "Re. separation of concerns. I agree the drawing of a cell should be separated from drawing of the board. I'm not so keen on putting AWT code directly into the `Cell` class which is clearly a \"Model\" layer entity. The UI layer should be totally divorced from model as it's (IMO) the most common \"major change\" made to any game." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-13T10:48:48.807", "Id": "453595", "Score": "0", "body": "@drekbour i definitely agree with you, it's not a goof idea to drag that AWT dependency into thr model. I was too fast on my anser" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-13T10:54:28.867", "Id": "453598", "Score": "1", "body": "oops. awt -> swing. There you go, that was a fast change of UI technology! :)" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-12T07:55:02.950", "Id": "232229", "ParentId": "232145", "Score": "5" } }, { "body": "<p>Others have discussed some broad concepts. I'll add some small but concrete items:</p>\n\n<p><strong>1</strong> A new <code>Cell</code> starts with 0 by default. Do one or the other not both:</p>\n\n<pre><code>area[y][x] = new Cell();\narea[y][x].setEmpty();\n</code></pre>\n\n<p><strong>2</strong> There is no need to keep recomputing <code>getAmountOfEmptyCells()</code>, you could keep a counter in <code>Area</code> that is updated with each <code>Cell</code></p>\n\n<p><strong>3</strong> Please make all fields <code>private</code> unless they are intended to be shared (you should always default to private in an OO language).</p>\n\n<p><strong>4</strong> Don't call your class <code>Component</code> :) It is very well known existing piece of AWT/Swing (your <code>JFrame</code> already extends <a href=\"https://docs.oracle.com/javase/7/docs/api/java/awt/Component.html\" rel=\"nofollow noreferrer\"><code>java.awt.Component</code></a>!). I think possibly <code>Area</code> is a little general as well. Try something like <code>Board</code>/<code>BoardUI</code> instead of <code>Area</code>/<code>Component</code>.</p>\n\n<p><strong>5</strong> Avoid having two sources of <code>gameState</code>. I actually think this should live inside <code>Area</code>. </p>\n\n<pre><code>statusOfGame = GamesState.DEFEAT;\ncomponent.setGameState(statusOfGame);\n</code></pre>\n\n<p><strong>6</strong> <code>GameWindow2048.myKey</code> is a classname in lower case!</p>\n\n<p><strong>7</strong> The logic in <code>GameWindow2048.myKey</code> which makes actually moves and changes <code>gameState</code> would be better located inside <code>Area</code>. It is part of your \"core\" layer and a trigger (such as a key press) should only <em>call</em> the logic. Imagine having more triggers for the same action (swipe on a tablet, mouse-drag on desktop, voice control, mind control ...)</p>\n\n<p><strong>8</strong> <code>Area</code> should be constructed externally and <em>passed in</em> to your UI layer. This is the key tenet that lets you keep \"ui\" and \"core\" separate.</p>\n\n<pre><code>area = new Area(inARow, valueOfCellToWin);\n</code></pre>\n\n<p><strong>9</strong> <code>Direction</code> should be moved into <code>Area</code>. Again, the \"core\" layer should have zero knowledge of UI classes.</p>\n\n<p><strong>10</strong> <code>area[0].length</code> I think it is reasonable for <code>Area</code> to have an <code>int size;</code> field instead of doing this.</p>\n\n<p><strong>11</strong></p>\n\n<pre><code>(Math.abs(new Random().nextInt()%10) != 9) ? 1 : 2;\n</code></pre>\n\n<p>I think perhaps it would be better like</p>\n\n<pre><code>private static final Random r = new Random();\n...\npowerOf2 = r.nextInt(10) == 9 ? 2 : 1; // 10% chance of a \"2\"\n</code></pre>\n\n<p><strong>12</strong> Seeing this inside a for loop scares me as a reader! Perhaps the inner loop should be going the other direction to keep pushing cells?</p>\n\n<pre><code>y-=2; //as we may need to move this cell even higher\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-13T11:58:39.007", "Id": "232316", "ParentId": "232145", "Score": "6" } } ]
{ "AcceptedAnswerId": "232316", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-10T12:27:27.323", "Id": "232145", "Score": "8", "Tags": [ "java", "game", "2048" ], "Title": "2048 graphic game" }
232145
<p>I wrote a simple script to log HDD and CPU temps to a log file. If those temperatures reach a threshold, it will shutdown the server. I also made the script make sure the log files don't get over a certain file size. Any ways to improve the code would be greatly appreciated, as I am a noob to programming. </p> <pre><code>#!/bin/bash # Check HDD Temps, CPU temp.. shut down server if any exceed acceptable limit # Using hddtemp to check HDD temps, sensors command to check CPU temp. date=$(TZ='America/Los_Angeles' date) HDD1=$(sudo hddtemp /dev/sdb | cut -d":" -f1,2) HDD2=$(sudo hddtemp /dev/sdc | cut -d":" -f1,2) T1=$(sudo hddtemp /dev/sdb | cut -d":" -f3 | cut -d" " -f2 | cut -c1-2) T2=$(sudo hddtemp /dev/sdc | cut -d":" -f3 | cut -d" " -f2 | cut -c1-2) CPU1=$(sensors | grep "Core" | head -1 | cut -d"+" -f2 | cut -d"." -f1) CPU2=$(sensors | grep "Core" | tail -1 | cut -d"+" -f2 | cut -d"." -f1) base_file='/home/brandon/logs/temp1.log' file='/home/brandon/logs/temp' log='.log' error='.error' find_lowest_file_num() { local lowest_file_num=$(ls /home/brandon/logs/ | grep temp | cut -d"p" -f2 | cut -d"." -f1 | sort -rn | tail -1) if [ -z "$lowest_file_num" ] then touch $base_file echo 1 else echo $lowest_file_num fi } find_highest_file_num() { local highest_file_num=$(ls /home/brandon/logs/ | grep temp | cut -d"p" -f2 | cut -d"." -f1 | sort -rn | head -1) # if highest_file_num is empty, that means there is no temp files, so create one if [ -z "$highest_file_num" ] then touch $base_file echo 1 #else return highest_file_num else echo $highest_file_num fi } highest_file_num=$(find_highest_file_num) lowest_file_num=$(find_lowest_file_num) get_curr_highest_file() { local h=${file}${highest_file_num}${log} echo $h } get_curr_lowest_file() { local l=${file}${lowest_file_num}${log} echo $l } curr_file=$(get_curr_highest_file) echo "HDD1: ${HDD1} Temp:${T1}C ${date} " &gt;&gt; $curr_file echo "HDD2: ${HDD2} Temp:${T2}C ${date} " &gt;&gt; $curr_file echo "CPU Core 1 Temp:${CPU1}C ${date} " &gt;&gt; $curr_file echo "CPU Core 2 Temp:${CPU2}C ${date} " &gt;&gt; $curr_file #if files get bigger than 1000k, make a new one if [ $(du -k $curr_file | cut -f1) -gt 1000 ] then let "highest_file_num++" touch $(get_curr_highest_file) fi if [ $(du -k /home/brandon/logs | cut -f1) -gt 100000 ] then rm -f $(get_curr_lowest_file) fi if [ $T1 -gt 50 ] || [ $T2 -gt 50 ] || [ $CPU1 -gt 80 ] || [ $CPU2 -gt 80 ] then echo "HIGH TEMPS DETECTED!!! HDD1 Temp: ${T1}C HDD2 Temp: ${T2}C ${date}" &gt;&gt; ${curr_file}${error} echo "CPU1: ${CPU1}C, CPU2: ${CPU2} ${date}" &gt;&gt; ${curr_file}${error} echo "Shutting down..." &gt;&gt; ${curr_file}${error} sudo shutdown now fi </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-10T14:01:12.073", "Id": "453154", "Score": "0", "body": "can you post a sample raw output of `hddtemp /dev/sdb` and `sensors` commands?" } ]
[ { "body": "<p>Here is my revision. I changed it that instead of hardcoding the user's home directory the script can just get that from <code>env</code>. Also, I would run this directly as a root account chron task rather than configuring <code>sudo</code> to be able to run <code>shutdown</code> and <code>hddtemp</code>. Finally, instead of using <code>if -z</code> to check for a file's existance, I would use <code>test -f</code> or something. Anyway, not bad at all for a 'noob', I'd give yourself more credit! Here is my version:</p>\n\n<pre><code>#!/bin/bash\n# Check HDD Temps, CPU temp.. shut down server if any exceed acceptable limit\n# Using hddtemp to check HDD temps, sensors command to check CPU temp.\ndate=$(TZ='America/Los_Angeles' date)\n# Consider running as root directly instead of requiring sudo (unless you want \\\n# to configure a nonroot user to be able to use `hddtemp` and `shutdown`) \\ \n# which would work, but since you're running as chron, I would just run \\\n# it as a root cron job\ntest $(id -u) == 0 || {echo 'This script must be run as root'; exit 1}\nHDD1=$(hddtemp /dev/sdb | cut -d\":\" -f1,2) \nHDD2=$(hddtemp /dev/sdc | cut -d\":\" -f1,2)\nT1=$(sudo hddtemp /dev/sdb | cut -d\":\" -f3 | cut -d\" \" -f2 | cut -c1-2)\nT2=$(sudo hddtemp /dev/sdc | cut -d\":\" -f3 | cut -d\" \" -f2 | cut -c1-2)\nCPU1=$(sensors | grep \"Core\" | head -1 | cut -d\"+\" -f2 | cut -d\".\" -f1)\nCPU2=$(sensors | grep \"Core\" | tail -1 | cut -d\"+\" -f2 | cut -d\".\" -f1)\nlogdir=\"/home/$USER/templogs\"\nbase_file=\"${logdir}/temp1.log\"\nfile=\"${logdir}/temp\"\nlog='.log'\nerror='.error'\ntest -d $logdir||mkdir $logdir 2&gt;/dev/null\n\nfind_lowest_file_num() {\n local lowest_file_num=$(ls ${logdir}/ | grep temp | cut -d\"p\" -f2 | cut -d\".\" -f1 | sort -rn | tail -1)\n\n if [ -z \"$lowest_file_num\" ]\n then\n touch $base_file\n echo 1\n else\n echo $lowest_file_num\n fi\n}\n\nfind_highest_file_num() {\n local highest_file_num=$(ls ${logdir}/ | grep temp | cut -d\"p\" -f2 | cut -d\".\" -f1 | sort -rn | head -1)\n\n # How about using `test` instead of ` if -z`? \n\n test -f \"$highest_file_num\" || { &gt;\"$highest_file_num\" ; echo 'Created temp file' ;} &amp;&amp; echo \"highest_file_num is present\"\n\n}\n\nhighest_file_num=$(find_highest_file_num)\nlowest_file_num=$(find_lowest_file_num)\n\nget_curr_highest_file() {\n local h=${file}${highest_file_num}${log}\n echo $h\n}\n\nget_curr_lowest_file() {\n local l=${file}${lowest_file_num}${log}\n echo $l\n}\n\ncurr_file=get_curr_highest_file\n\necho \"HDD1: ${HDD1} Temp:${T1}C ${date} \" &gt;&gt; $curr_file\necho \"HDD2: ${HDD2} Temp:${T2}C ${date} \" &gt;&gt; $curr_file\necho \"CPU Core 1 Temp:${CPU1}C ${date} \" &gt;&gt; $curr_file\necho \"CPU Core 2 Temp:${CPU2}C ${date} \" &gt;&gt; $curr_file\n\n#if files get bigger than 1000k, make a new one\nif [ $(du -k $curr_file | cut -f1) -gt 1000 ]\nthen\n let \"highest_file_num++\"\n touch $(get_curr_highest_file)\nfi\n\nif [ $(du -k $logdir | cut -f1) -gt 100000 ]\nthen\n rm -f $(get_curr_lowest_file)\nfi\n\nif [ $T1 -gt 50 ] || [ $T2 -gt 50 ] || [ $CPU1 -gt 80 ] || [ $CPU2 -gt 80 ]\nthen\n echo \"HIGH TEMPS DETECTED!!! HDD1 Temp: ${T1}C HDD2 Temp: ${T2}C ${date}\" &gt;&gt; ${curr_file}${error}\n echo \"CPU1: ${CPU1}C, CPU2: ${CPU2} ${date}\" &gt;&gt; ${curr_file}${error}\n echo \"Shutting down...\" &gt;&gt; ${curr_file}${error}\n shutdown now # I would run this as root directly\nelse\n echo \"Temps ok: HDD1: ${T1}, HDD2: ${T2}, CPU1: ${CPU1}, CPU2: ${CPU2}\"\nfi\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-10T20:07:21.350", "Id": "232157", "ParentId": "232147", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-10T13:51:08.483", "Id": "232147", "Score": "3", "Tags": [ "bash", "unix" ], "Title": "Linux HDD/CPU Temperature Logging Bash Script to run every minute in crontab" }
232147
<p>I'm learning C++, data structures and algorithms and I have implemented a (Doubly) Linked List class for practice. Some STL functionalities are deliberately missing for now (e.g. some functions overloads, rbegin/rend/crbegin/crend, relational operators and many others). I would like to know if my approach is correct before implementing other functionalities. For example, I never implemented an iterator class before, so I opted to get a review on this first version before implementing a reverse iterator. Also, I learned from a standard book how to sort an array using merge sort, but not a linked list, so I'm curious to know if my approach to List::sort <a href="https://en.wikipedia.org/wiki/Merge_sort#Top-down_implementation_using_lists" rel="noreferrer">(based on this pseudocode)</a> is clear and efficient, and how I could improve it. </p> <p>I'm learning C++ through a C++11 book and trying to learn C++14 and C++17 best practices on the fly. I appreciate any advice on how make it more compatible with modern best practices. I'm using g++ compiler with -std=c++17 flag.</p> <p><strong>List.h</strong></p> <pre><code>#ifndef LIST_H #define LIST_H #include &lt;initializer_list&gt; #include &lt;memory&gt; namespace algorithms { template&lt;typename T&gt; class List { private: struct Node { Node() = default; Node(Node* right, Node* left, const T&amp; value): next(right), prev(left), value(value) {} Node(Node* right, Node* left, T&amp;&amp; value): next(right), prev(left), value(std::move(value)) {} Node(Node* right, Node* left): next(right), prev(left) {} template&lt;typename... Args&gt; Node(Node* right, Node* left, Args&amp;&amp;... args): next(right), prev(left), value(std::forward&lt;Args&gt;(args)...) {} Node* next { nullptr }; Node* prev { nullptr }; T value {}; }; public: using size_type = std::size_t; using reference = T&amp;; using const_reference = const T&amp;; class const_iterator { public: using iterator_category = std::bidirectional_iterator_tag; using value_type = T; using difference_type = List::size_type; using pointer = const value_type*; using reference = const value_type&amp;; const_iterator() = default; void swap(const_iterator&amp; iterator) noexcept { using std::swap; swap(node, iterator.node); } bool operator==(const const_iterator&amp; iterator) const noexcept { return node == iterator.node; } bool operator!=(const const_iterator&amp; iterator) const noexcept { return node != iterator.node; } reference operator*() const { return node-&gt;value; } reference operator-&gt;() const { return node-&gt;value; } // Prefix operators const_iterator&amp; operator++() { node = node-&gt;next; return *this; } const_iterator&amp; operator--() { node = node-&gt;prev; return *this; } // Postfix operators const_iterator operator++(int) { const_iterator old(*this); node = node-&gt;next; return old; } const_iterator operator--(int) { const_iterator old(*this); node = node-&gt;prev; return old; } protected: Node* node { nullptr }; explicit const_iterator(Node* ptr): node(ptr) {} friend class List; }; class iterator: public const_iterator { public: using iterator_category = std::bidirectional_iterator_tag; using value_type = T; using difference_type = List::size_type; using pointer = value_type*; using reference = value_type&amp;; iterator() = default; reference operator*() { return this-&gt;node-&gt;value; } const reference operator*() const { return const_iterator::operator*(); } reference operator-&gt;() { return this-&gt;node-&gt;value; } const reference operator-&gt;() const { return const_iterator::operator-&gt;(); } // Prefix operators iterator&amp; operator++() { this-&gt;node = this-&gt;node-&gt;next; return *this; } iterator&amp; operator--() { this-&gt;node = this-&gt;node-&gt;prev; return *this; } // Postfix operators iterator operator++(int) { iterator old(*this); ++(*this); return old; } iterator operator--(int) { iterator old = *this; ++(*this); return old; } protected: explicit iterator(Node* ptr): const_iterator(ptr) {} friend class List; }; // Constructors and Destructor List() = default; List(size_type initial_size, const T&amp; value); explicit List(size_type inital_size); template&lt;typename InputIt&gt; List(InputIt first, InputIt last); List(std::initializer_list&lt;T&gt; initializer); List(const List&amp; list); List(List&amp;&amp; list) noexcept; List&amp; operator=(const List&amp; list); List&amp; operator=(List&amp;&amp; list) noexcept; ~List(); // Iterators iterator begin() noexcept; const_iterator begin() const noexcept; const_iterator cbegin() const noexcept; iterator end() noexcept; const_iterator end() const noexcept; const_iterator cend() const noexcept; // Capacity size_type size() const noexcept; bool empty() const noexcept; // Modifiers template&lt;typename InputIt&gt; void assign(InputIt first, InputIt last); void assign(std::initializer_list&lt;T&gt; initializer); iterator insert(const_iterator position, const T&amp; value); iterator insert(const_iterator position, T&amp;&amp; value); template&lt;typename InputIt&gt; iterator insert(const_iterator position, InputIt first, InputIt last); template&lt;typename... Args&gt; iterator emplace(const_iterator position, Args&amp;&amp;... args); template&lt;typename... Args&gt; reference emplace_back(Args&amp;&amp;... args); void push_back(const T&amp; value); void push_back(T&amp;&amp; value); void pop_back(); template&lt;typename... Args&gt; reference emplace_front(Args&amp;&amp;... args); void push_front(const T&amp; value); void push_front(T&amp;&amp; value); void pop_front(); iterator erase(const_iterator position); iterator erase(const_iterator first, const_iterator last); void clear() noexcept; void resize(size_type new_size, const T&amp; value); void resize(size_type new_size); void swap(List&amp; list) noexcept; // Accessors reference front(); const_reference front() const; reference back(); const_reference back() const; // Operations // Merge two sorted lists; no copies are made template&lt;typename Compare = std::less&lt;&gt;&gt; void merge(List&amp; list, Compare compare = Compare()); template&lt;typename Compare = std::less&lt;&gt;&gt; void sort(Compare compare = Compare()); template&lt;typename Function&gt; size_type remove_if(Function function); size_type remove(const T&amp; value); void splice(const_iterator position, List&amp; list, const_iterator first, const_iterator last); void splice(const_iterator position, List&amp; list, const_iterator iterator); void splice(const_iterator position, List&amp; list); void reverse() noexcept; size_type unique(); template&lt;typename BinaryFunction&gt; size_type unique(BinaryFunction binary_function); private: using Alloc = std::allocator&lt;T&gt;; using NodeAlloc = typename std::allocator_traits&lt;Alloc&gt;::template rebind_alloc&lt;Node&gt;; NodeAlloc node_allocator; Node* head { create_head() }; size_type current_size { 0 }; Node* create_head(); template&lt;typename... Args&gt; Node* create_node(Node* next, Node* prev, Args&amp;&amp;... args); void destroy_node(Node* node); template&lt;typename... Args&gt; iterator insert_internal(const_iterator position, Args&amp;&amp;... args); template&lt;typename... Args&gt; void resize_internal(size_type new_size, Args&amp;&amp;... args); template&lt;typename Function&gt; size_type remove_if_internal(Function function); template&lt;typename BinaryFunction&gt; size_type unique_internal(BinaryFunction binary_function); // Sorting utility functions template&lt;typename Compare&gt; const_iterator merge_sort(const_iterator first, size_type size, Compare compare); template&lt;typename Compare&gt; const_iterator merge(const_iterator first1, const_iterator first2, Compare compare); }; // Non-member swap function template&lt;typename T&gt; void swap(List&lt;T&gt;&amp; left, List&lt;T&gt;&amp; right) noexcept; } #include "List.inl" #endif // LIST_H </code></pre> <p><strong>List.inl</strong></p> <pre><code>#include &lt;iterator&gt; namespace algorithms { // Constructors and Destructor template&lt;typename T&gt; List&lt;T&gt;::List(size_type initial_size, const T&amp; value) { resize(initial_size, value); } template&lt;typename T&gt; List&lt;T&gt;::List(size_type inital_size) { resize(inital_size); } template&lt;typename T&gt; template&lt;typename InputIt&gt; List&lt;T&gt;::List(InputIt first, InputIt last) { insert(begin(), first, last); } template&lt;typename T&gt; List&lt;T&gt;::List(std::initializer_list&lt;T&gt; initializer): List(initializer.begin(), initializer.end()) {} template&lt;typename T&gt; List&lt;T&gt;::List(const List&amp; list): List(list.begin(), list.end()) {} template&lt;typename T&gt; List&lt;T&gt;::List(List&amp;&amp; list) noexcept { list.swap(*this); } template&lt;typename T&gt; List&lt;T&gt;&amp; List&lt;T&gt;::operator=(const List&amp; list) { List temp(list); temp.swap(*this); return *this; } template&lt;typename T&gt; List&lt;T&gt;&amp; List&lt;T&gt;::operator=(List&amp;&amp; list) noexcept { list.swap(*this); return *this; } template&lt;typename T&gt; List&lt;T&gt;::~List() { clear(); destroy_node(head); } // Iterators template&lt;typename T&gt; typename List&lt;T&gt;::iterator List&lt;T&gt;::begin() noexcept { return iterator(head-&gt;next); } template&lt;typename T&gt; typename List&lt;T&gt;::const_iterator List&lt;T&gt;::begin() const noexcept { return const_iterator(head-&gt;next); } template&lt;typename T&gt; typename List&lt;T&gt;::const_iterator List&lt;T&gt;::cbegin() const noexcept { return const_iterator(head-&gt;next); } template&lt;typename T&gt; typename List&lt;T&gt;::iterator List&lt;T&gt;::end() noexcept { return iterator(head); } template&lt;typename T&gt; typename List&lt;T&gt;::const_iterator List&lt;T&gt;::end() const noexcept { return const_iterator(head); } template&lt;typename T&gt; typename List&lt;T&gt;::const_iterator List&lt;T&gt;::cend() const noexcept { return const_iterator(head); } // Capacity template&lt;typename T&gt; typename List&lt;T&gt;::size_type List&lt;T&gt;::size() const noexcept { return current_size; } template&lt;typename T&gt; bool List&lt;T&gt;::empty() const noexcept { return current_size == 0; } // Modifiers template&lt;typename T&gt; template&lt;typename InputIt&gt; void List&lt;T&gt;::assign(InputIt first, InputIt last) { clear(); insert(begin(), first, last); } template&lt;typename T&gt; void List&lt;T&gt;::assign(std::initializer_list&lt;T&gt; initializer) { clear(); insert(begin(), initializer.begin(), initializer.end()); } template&lt;typename T&gt; typename List&lt;T&gt;::iterator List&lt;T&gt;::insert(const_iterator position, const T&amp; value) { return emplace(position, value); } template&lt;typename T&gt; typename List&lt;T&gt;::iterator List&lt;T&gt;::insert(const_iterator position, T&amp;&amp; value) { return emplace(position, value); } template&lt;typename T&gt; template&lt;typename InputIt&gt; typename List&lt;T&gt;::iterator List&lt;T&gt;::insert(const_iterator position, InputIt first, InputIt last) { iterator iterator; while (first != last) { iterator = insert(position, *first++); } return iterator; } template&lt;typename T&gt; template&lt;typename... Args&gt; typename List&lt;T&gt;::iterator List&lt;T&gt;::emplace(const_iterator position, Args&amp;&amp;... args) { return insert_internal(position, std::forward&lt;Args&gt;(args)...); } template&lt;typename T&gt; template&lt;typename... Args&gt; typename List&lt;T&gt;::reference List&lt;T&gt;::emplace_back(Args&amp;&amp;... args) { auto iterator = insert_internal(end(), std::forward&lt;Args&gt;(args)...); return *iterator; } template&lt;typename T&gt; void List&lt;T&gt;::push_back(const T&amp; value) { insert_internal(end(), value); } template&lt;typename T&gt; void List&lt;T&gt;::push_back(T&amp;&amp; value) { insert_internal(end(), value); } template&lt;typename T&gt; void List&lt;T&gt;::pop_back() { erase(const_iterator(head-&gt;prev)); } template&lt;typename T&gt; template&lt;typename... Args&gt; typename List&lt;T&gt;::reference List&lt;T&gt;::emplace_front(Args&amp;&amp;... args) { auto iterator = insert_internal(begin(), std::forward&lt;Args&gt;(args)...); return *iterator; } template&lt;typename T&gt; void List&lt;T&gt;::push_front(const T&amp; value) { insert_internal(begin(), value); } template&lt;typename T&gt; void List&lt;T&gt;::push_front(T&amp;&amp; value) { insert_internal(begin(), value); } template&lt;typename T&gt; void List&lt;T&gt;::pop_front() { erase(const_iterator(head-&gt;next)); } template&lt;typename T&gt; typename List&lt;T&gt;::iterator List&lt;T&gt;::erase(const_iterator position) { auto node_to_destroy = position.node; auto next_node = node_to_destroy-&gt;next; auto prev_node = node_to_destroy-&gt;prev; // Link the node before position.node to the node after position.node prev_node-&gt;next = next_node; next_node-&gt;prev = prev_node; // Unlink the node to be destroyed from the list and destroy it node_to_destroy-&gt;next = node_to_destroy; node_to_destroy-&gt;prev = node_to_destroy; destroy_node(node_to_destroy); --current_size; return iterator(next_node); } template&lt;typename T&gt; typename List&lt;T&gt;::iterator List&lt;T&gt;::erase(const_iterator first, const_iterator last) { if (first == begin() &amp;&amp; last == end()) { clear(); } else { while (first != last) { first = erase(first); } } return iterator(last.node); } template&lt;typename T&gt; void List&lt;T&gt;::clear() noexcept { Node* node = head-&gt;next; head-&gt;next = head; head-&gt;prev = head; for (Node* next_node; node != head; node = next_node) { next_node = node-&gt;next; destroy_node(node); } current_size = 0; } template&lt;typename T&gt; void List&lt;T&gt;::resize(size_type new_size, const T&amp; value) { resize_internal(new_size, value); } template&lt;typename T&gt; void List&lt;T&gt;::resize(size_type new_size) { resize_internal(new_size); } template&lt;typename T&gt; void List&lt;T&gt;::swap(List&amp; list) noexcept { using std::swap; swap(this-&gt;head, list.head); swap(this-&gt;current_size, list.current_size); } // Accessors template&lt;typename T&gt; typename List&lt;T&gt;::reference List&lt;T&gt;::front() { return head-&gt;next-&gt;value; } template&lt;typename T&gt; typename List&lt;T&gt;::const_reference List&lt;T&gt;::front() const { return head-&gt;next-&gt;value; } template&lt;typename T&gt; typename List&lt;T&gt;::reference List&lt;T&gt;::back() { return head-&gt;prev-&gt;value; } template&lt;typename T&gt; typename List&lt;T&gt;::const_reference List&lt;T&gt;::back() const { return head-&gt;prev-&gt;value; } // Operations template&lt;typename T&gt; template&lt;typename Compare&gt; void List&lt;T&gt;::merge(List&amp; list, Compare compare) { if (this == &amp;list) { return; } iterator this_it { begin() }; iterator other_it { list.begin() }; while (this_it != end() &amp;&amp; other_it != list.end()) { // return true if other &lt; this using the custom comparison function if (compare(*other_it, *this_it)) { auto node_to_merge = other_it; ++other_it; splice(this_it, list, node_to_merge, other_it); } else { ++this_it; } } // If other_it did not exhaust the list, splice it to the end of the list if (other_it != list.end()) { splice(end(), list, other_it, list.end()); } } template&lt;typename T&gt; template&lt;typename Compare&gt; void List&lt;T&gt;::sort(Compare compare) { merge_sort(begin(), size(), compare); } template&lt;typename T&gt; template&lt;typename Function&gt; typename List&lt;T&gt;::size_type List&lt;T&gt;::remove_if(Function function) { return remove_if_internal(function); } template&lt;typename T&gt; typename List&lt;T&gt;::size_type List&lt;T&gt;::remove(const T&amp; value) { return remove_if_internal([&amp;value = value](const T&amp; node_value) { return value == node_value; }); } template&lt;typename T&gt; void List&lt;T&gt;::splice(const_iterator position, List&amp; list, const_iterator first, const_iterator last) { if (this == &amp;list) { return; } auto size_change = std::distance(first, last); auto position_node = position.node; auto prev_node = position_node-&gt;prev; auto first_node = first.node; auto last_node = last.node-&gt;prev; // Link the node before first.node to the node at last.node in the list passed as argument auto new_first = first_node-&gt;prev; new_first-&gt;next = last.node; last.node-&gt;prev = new_first; // Insert the nodes in range [first; last[ between position and it's previous node first_node-&gt;prev = prev_node; last_node-&gt;next = position_node; prev_node-&gt;next = first_node; position_node-&gt;prev = last_node; current_size += size_change; list.current_size -= size_change; } template&lt;typename T&gt; void List&lt;T&gt;::splice(const_iterator position, List&amp; list, const_iterator iterator) { if (this == &amp;list) { return; } splice(position, list, iterator, const_iterator(iterator.node-&gt;next)); } template&lt;typename T&gt; void List&lt;T&gt;::splice(const_iterator position, List&amp; list) { if (this == &amp;list) { return; } splice(position, list, list.begin(), list.end()); } template&lt;typename T&gt; void List&lt;T&gt;::reverse() noexcept { using std::swap; for (auto iterator = begin(); iterator != end(); ) { auto current_node = iterator.node; ++iterator; swap(current_node-&gt;next, current_node-&gt;prev); } auto new_first = head-&gt;prev; auto new_last = head-&gt;next; head-&gt;next = new_first; head-&gt;prev = new_last; } template&lt;typename T&gt; typename List&lt;T&gt;::size_type List&lt;T&gt;::unique() { return unique_internal([](const T&amp; lhs, const T&amp; rhs) { return lhs == rhs; }); } template&lt;typename T&gt; template&lt;typename BinaryFunction&gt; typename List&lt;T&gt;::size_type List&lt;T&gt;::unique(BinaryFunction binary_function) { return unique_internal(binary_function); } // Private template&lt;typename T&gt; typename List&lt;T&gt;::Node* List&lt;T&gt;::create_head() { Node* node = node_allocator.allocate(1); // Construct Node in storage pointed by node; node-&gt;next and node-&gt;prev points to node itself node_allocator.construct(node, node, node); return node; } template&lt;typename T&gt; template&lt;typename... Args&gt; typename List&lt;T&gt;::Node* List&lt;T&gt;::create_node(Node* next, Node* prev, Args&amp;&amp;... args) { Node* new_node = node_allocator.allocate(1); node_allocator.construct(new_node, next, prev, std::forward&lt;Args&gt;(args)...); return new_node; } template&lt;typename T&gt; void List&lt;T&gt;::destroy_node(Node* node) { node_allocator.destroy(node); node_allocator.deallocate(node, 1); } template&lt;typename T&gt; template&lt;typename... Args&gt; typename List&lt;T&gt;::iterator List&lt;T&gt;::insert_internal(const_iterator position, Args&amp;&amp;... args) { Node* next_node = position.node; Node* previous_node = next_node-&gt;prev; Node* new_node = create_node(next_node, previous_node, std::forward&lt;Args&gt;(args)...); previous_node-&gt;next = new_node; next_node-&gt;prev = new_node; ++current_size; return iterator(new_node); } template&lt;typename T&gt; template&lt;typename... Args&gt; void List&lt;T&gt;::resize_internal(size_type new_size, Args&amp;&amp;... args) { if (size() &lt; new_size) { auto to_add = new_size - size(); for (size_type i = 0; i &lt; to_add; ++i) { insert_internal(end(), std::forward&lt;Args&gt;(args)...); } } else { auto to_destroy = size() - new_size; for (size_type i = 0; i &lt; to_destroy; ++i) { pop_back(); } } } template&lt;typename T&gt; template&lt;typename Function&gt; typename List&lt;T&gt;::size_type List&lt;T&gt;::remove_if_internal(Function function) { auto previous_size = size(); for (auto iterator = begin(); iterator != end(); ) { if (function(*iterator)) { auto to_erase = iterator; iterator = erase(to_erase); } else { ++iterator; } } return previous_size - size(); } template&lt;typename T&gt; template&lt;typename BinaryFunction&gt; typename List&lt;T&gt;::size_type List&lt;T&gt;::unique_internal(BinaryFunction binary_function) { auto previous_size = size(); auto iterator = begin(); auto back_iterator = iterator; ++iterator; while (iterator != end()) { if (binary_function(*back_iterator, *iterator)) { auto to_erase = iterator; iterator = erase(to_erase); } else { back_iterator = iterator; ++iterator; } } return previous_size - size(); } template&lt;typename T&gt; template&lt;typename Compare&gt; typename List&lt;T&gt;::const_iterator List&lt;T&gt;::merge_sort(const_iterator first, size_type size, Compare compare) { // Base case if (size &lt;= 1) { // Temporarily unlink the node from the list first.node-&gt;next = head; first.node-&gt;prev = head; return first; } auto half_size = size / 2; auto mid = std::next(first, half_size); first = merge_sort(first, half_size, compare); mid = merge_sort(mid, size - half_size, compare); return merge(first, mid, compare); } template&lt;typename T&gt; template&lt;typename Compare&gt; typename List&lt;T&gt;::const_iterator List&lt;T&gt;::merge(const_iterator first1, const_iterator first2, Compare compare) { Node* lesser_node; Node* greater_node; // first1 and first2 each points to the start of two sublists, both ending at head. // The merge operation reorder the nodes without creating any new node; only the links // of the nodes are changed. At the end, the resulting list is sorted and head-&gt;next // points to the start of the list and head-&gt;prev points to the end of the list. while (first1.node != head || first2.node != head) { if (first1.node == head) { while (first2.node-&gt;next != head) { ++first2; } head-&gt;prev = first2.node; break; } else if (first2.node == head) { while (first1.node-&gt;next != head) { ++first1; } head-&gt;prev = first1.node; break; } else if (compare(*first1, *first2)) // first1 &lt; first2 using the custom comparison function { lesser_node = first1.node; greater_node = first2.node; ++first1; } else { lesser_node = first2.node; greater_node = first1.node; ++first2; } greater_node-&gt;prev-&gt;next = lesser_node; lesser_node-&gt;prev = greater_node-&gt;prev; lesser_node-&gt;next = greater_node; greater_node-&gt;prev = lesser_node; } // Returns iterator to the first node at the merged list return const_iterator(head-&gt;next); } // Non-member swap function template&lt;typename T&gt; void swap(List&lt;T&gt;&amp; left, List&lt;T&gt;&amp; right) noexcept { left.swap(right); } } </code></pre> <p><strong>EDIT:</strong> </p> <p>As asked in the comments, the code bellow shows one example of how to use the class. It compiles and runs using g++ -std=c++17 -g -Wall main.cpp -o main. (I'm assuming that the List.h and List.inl files are in the same folder as main.cpp) </p> <p>Running it with valgrind gave me no memory leaks and running it with GDB gave no errors. I've written more test cases, however I feel that the code in this post is already very long so I will post a not too large test.</p> <pre><code>#include &lt;algorithm&gt; #include &lt;cassert&gt; #include &lt;iostream&gt; #include &lt;string&gt; #include &lt;vector&gt; #include "List.h" void test_sort() { namespace algs = algorithms; algs::List&lt;int&gt; ascending { 3, 9, 1, 2, 4, 6, 5, 8, 7 }; ascending.sort(); assert(std::is_sorted(ascending.begin(), ascending.end())); assert(ascending.size() == 9); // Assertion: no element was lost during the sort assert(ascending.back() == 9); algs::List&lt;int&gt; descending { -9, -7, -5, -3, -1, 1, 3, 5, 7, 9 }; descending.sort(std::greater&lt;&gt;()); assert(std::is_sorted(descending.begin(), descending.end(), std::greater&lt;&gt;())); assert(descending.size() == 10); assert(descending.back() == -9); auto string_comparison = [](const std::string&amp; lhs, const std::string&amp; rhs) { return lhs.size() == rhs.size() ? (lhs &lt; rhs) : lhs.size() &lt; rhs.size(); }; algs::List&lt;std::string&gt; strings { "deque", "list", "vector", "stack", "graph", "set", "queue", "map" }; strings.sort(string_comparison); assert(std::is_sorted(strings.begin(), strings.end(), string_comparison)); assert(strings.size() == 8); assert(strings.back() == "vector"); } void test_remove() { namespace algs = algorithms; algs::List&lt;std::string&gt; list { "Alpha", "Beta", "Alpha", "Gamma", "Alpha", "Delta", "Alpha" }; auto old_size = list.size(); auto removed = list.remove("Alpha"); assert(list.size() + removed == old_size); old_size = list.size(); removed = list.remove_if([](const auto&amp; string) { return string.size() == 5; }); assert(list.size() + removed == old_size); assert(list.size() == 1); } int main() { test_sort(); test_remove(); std::cout &lt;&lt; "End of Test" &lt;&lt; std::endl; return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-11T12:33:19.427", "Id": "453242", "Score": "1", "body": "The templated `Node` constructor already covers the others besides the default one and you can fix that by defaulting `right` and `left` to `nullptr`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-11T15:35:59.300", "Id": "453259", "Score": "0", "body": "Could you please supply a test case that runs and shows how to use this class." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-11T22:58:06.290", "Id": "453337", "Score": "1", "body": "@pacmaninbw Done" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-13T10:35:32.653", "Id": "453590", "Score": "0", "body": "@nwp Sorry for the late response, but this seems to be a good suggestion, it simplifies the Node class a lot. I didn't notice that. thanks!" } ]
[ { "body": "<p>The code looks nice! Here are my suggestions.</p>\n\n<h1>Testing</h1>\n\n<p>Your code passes your test, but there are quite a few bugs that can be easily caught by testing! Make sure that <em>every functionality is tested</em> so you don't miss some bugs.</p>\n\n<h1>The compiler flags</h1>\n\n<p>Right now, you are using this command to compile the code:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>g++ -std=c++17 -g -Wall main.cpp -o main\n</code></pre>\n\n<p>There are three additional flags that you should normally use:</p>\n\n<ul>\n<li><p><code>-pedantic-errors</code> &mdash; raises errors on non-standard GCC extensions, which are enabled by default.</p></li>\n<li><p><code>-Werror</code> &mdash; turns warning into errors. It forces you to ensure that your code is warning-free.</p></li>\n<li><p><code>-Wextra</code> &mdash; enables additional warnings that help catch common bugs.</p></li>\n</ul>\n\n<h1>Allocators</h1>\n\n<p>I see that you are playing a bit with allocators in the insertion functions. However, allocators are a way for users to customize the allocation, deallocation, construction, and destruction behavior of the container. Using a default allocator + allocator traits to allocate the nodes is a big overkill if you don't want to support allocators. Simply use <code>new</code> and <code>delete</code>:</p>\n\n<pre><code>new Node{T(std::forward&lt;Args&gt;(args)...), prev, next}; // instead of create_node\ndelete node; // instead of destroy_node\n</code></pre>\n\n<p>If you <em>do</em> want to support allocators, though, then the data model of the class has to be changed. The node will consist of raw memory instead of a subobject: (just the idea, not tested)</p>\n\n<pre><code>struct Node {\n Node* prev{nullptr};\n Node* next{nullptr};\n std::aligned_storage_t&lt;sizeof(T), alignof(T)&gt; storage;\n\n T* address()\n {\n return std::launder(reinterpret_cast&lt;T*&gt;(&amp;storage));\n }\n T&amp; value()\n {\n return *address();\n }\n};\n</code></pre>\n\n<p>Then, you use</p>\n\n<ul>\n<li><p><code>allocate</code> to allocate a node,</p></li>\n<li><p>placement new to construct the node,</p></li>\n<li><p><code>construct</code> to construct the element,</p></li>\n<li><p><code>destroy</code> to destroy the element,</p></li>\n<li><p><code>~Node</code> to destroy the node (not needed if your <code>Node</code> class is trivially destructible), and</p></li>\n<li><p><code>deallocate</code> to deallocate a node: (just the idea, not tested)</p></li>\n</ul>\n\n\n\n<pre><code>auto node_allocator()\n{\n return NodeAlloc(alloc);\n}\n\ntemplate &lt;typename... Args&gt;\nNode* create_node(Node* prev, Node* next, Args&amp;&amp;... args)\n{\n auto n_alloc = node_allocator();\n\n auto* node = NTraits::allocate(n_alloc, 1);\n ::new (node) Node{prev, next};\n NTraits::construct(n_alloc, node.address(), std::forward&lt;Args&gt;(args)...);\n\n return node;\n}\n\nvoid destroy_node(Node* node)\n{\n NTraits::destroy(n_alloc, node.address());\n NTraits::deallocate(n_alloc, node);\n}\n</code></pre>\n\n<p>where <code>Allocator</code> is the allocator template parameter, <code>alloc</code> is the <code>Allocator</code> member, and</p>\n\n<pre><code>using Traits = std::allocator_traits&lt;Allocator&gt;;\nusing NAlloc = typename Traits::template rebind_alloc&lt;Node&gt;;\nusing NTraits = typename Traits::template rebind_traits&lt;Node&gt;;\n</code></pre>\n\n<h1>The node class</h1>\n\n<p>The node class is <em>way</em> too convoluted. Since we have aggregate initialization, the node class can be as simple as</p>\n\n<pre><code>struct Node {\n T value;\n Node* prev{nullptr};\n Node* next{nullptr};\n};\n</code></pre>\n\n<p>And this is even more powerful than the constructors:</p>\n\n<pre><code>Node{T(args)} // initializes value from '(args)'\nNode{T{args}} // initializes value from '{args}'\nNode{{args}} // copy-initializes value from '{args}'\n</code></pre>\n\n<p>In all cases, you can append the prev and next pointers. There is no redundant move involved here, thanks to guaranteed copy elision introduced in C++17.</p>\n\n<h1>The iterator classes</h1>\n\n<p><strong>BUG</strong> This is wrong:</p>\n\n<pre><code>using difference_type = List::size_type;\n</code></pre>\n\n<p><code>difference_type</code> has to be a signed type. Use <code>std::ptrdiff_t</code> instead.</p>\n\n<p>When swapping builtin pointers, you can call <code>std::swap</code> directly. And the swap function of the iterator classes can be removed &mdash; <code>std::swap</code> works correctly.</p>\n\n<p><code>operator!=</code> is generally implemented in terms of <code>operator==</code>. Similarly, the postfix <code>++</code> and <code>--</code> are implemented in terms of the prefix <code>++</code> and <code>--</code>. <code>operator*</code> and <code>operator-&gt;</code> can be noexcept. <code>operator-&gt;</code> should return a pointer, not a reference.</p>\n\n<p><strong>BUG</strong> <code>const reference</code> doesn't do what you expect. It is an attempt to add a top-level const to a reference type, and thus is equivalent to <code>reference</code>. What you want is <code>const T&amp;</code>.</p>\n\n<p>I don't really like making <code>iterator</code> derive from <code>const_iterator</code> &mdash; especially considering the added <code>this-&gt;</code> clutter. Just writing two independent classes and adding a <code>iterator(const_iterator)</code> constructor seems good enough. That's primarily a matter of taste, though.</p>\n\n<h1>The constructors, destructor, and assignment operators</h1>\n\n<p><strong>BUG</strong> The <code>(it, it)</code> constructor should be constrained with SFINAE. Right now <code>List&lt;unsigned int&gt;(5, 5)</code> will call the <code>(it, it)</code> version instead of the <code>(size, value)</code> version. Like this:</p>\n\n<pre><code>template &lt;typename InputIt, typename = typename std::iterator_traits&lt;InputIt&gt;::iterator_category&gt;\nList(InputIt first, InputIt last);\n</code></pre>\n\n<p>Note: It's better to just define everything in the class IMO. Otherwise, the out-of-class definition will look like this:</p>\n\n<pre><code>template &lt;typename T&gt;\ntemplate &lt;typename InputIt, typename&gt; // note: default template argument is not repeated\nList&lt;T&gt;::List(InputIt first, InputIt last)\n{\n insert(begin(), first, last);\n}\n</code></pre>\n\n<p>The copy and move assignment operators can be unified with the <a href=\"https://stackoverflow.com/q/3279543\">copy-and-swap idiom</a>:</p>\n\n<pre><code>// note: 1. take by value; 2. noexcept\nList&amp; operator=(List list) noexcept\n{\n swap(list);\n return *this;\n}\n</code></pre>\n\n<p>The <code>noexcept</code> here makes move assignment <code>noexcept</code>, but not copy assignment.</p>\n\n<p><code>inital_size</code> is a misspell.</p>\n\n<h1><code>begin</code> and <code>end</code></h1>\n\n<p><code>cbegin</code> and <code>cend</code> should delegate to <code>begin</code> and <code>end</code>.</p>\n\n<p>When defining the functions out of class, you can use a trailing return type instead of <code>typename List&lt;T&gt;::</code>:</p>\n\n<pre><code>template&lt;typename T&gt;\nauto List&lt;T&gt;::begin() noexcept -&gt; iterator\n</code></pre>\n\n<h1><code>assign</code></h1>\n\n<p>The <code>assign</code> functions can be modified to provide strong exception guarantee:</p>\n\n<pre><code>template &lt;typename InputIt&gt; // also SFINAE this\nvoid assign(InputIt first, InputIt last)\n{\n *this = List(first, last); // creates new list first, destroys old elements after\n}\n\nvoid assign(std::initializer_list&lt;T&gt; ilist)\n{\n *this = List(ilist);\n}\n</code></pre>\n\n<h1>Insertion</h1>\n\n<p>You can implement <code>insert_internal</code> in <code>emplace</code> directly. No need to separate.</p>\n\n<p><code>push_back</code> can use <code>emplace_back</code> directly.</p>\n\n<h1>Deletion</h1>\n\n<p>This feels wrong:</p>\n\n<pre><code>if (first == begin() &amp;&amp; last == end())\n{\n clear();\n}\n</code></pre>\n\n<p>Special-casing <code>begin</code> and <code>end</code> really doesn't feel right. It should be possible to treat all iterators equally, so <code>clear()</code> can just be <code>erase(begin(), end())</code>.</p>\n\n<h1><code>resize</code></h1>\n\n<p>I can see why you extract a separate <code>_internal</code> here, but this is really an <s>absurd</s> <em>unusual</em> but creative usage of perfect forwarding. More seriously, <code>insert_internal(end(), ...)</code> can be simplified to <code>emplace_back(...)</code>.</p>\n\n<h1><code>remove</code> &amp; <code>unique</code></h1>\n\n<p>Again, there is no need to have an <code>_internal</code> when it is the same as the non-<code>_internal</code> version. <code>[&amp;value = value]</code> can be simplified to <code>[&amp;value]</code> in the lambda capture.</p>\n\n<p><strong>BUG</strong> There is a big problem with the <code>remove</code>: when an element from the list is passed as a <code>const T&amp;</code> argument, it will be accessed after destruction.</p>\n\n<pre><code>List&lt;int&gt; list{1, 2, 1, 2};\nlist.remove(list.front()); // undefined behavior\n</code></pre>\n\n<p>One solution is to collect the removed elements as another <code>List</code> and destroy them together at the end.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-14T20:44:59.030", "Id": "453844", "Score": "0", "body": "First, thanks a lot for the very detailled review! I really learned a lot, specially about C++ features that I wasn't aware of, like SFINAE and copy elision.I'll search more about it. About the Iterator: as said, I never implemented an iterator class before and to use inheritance seems to be a common advice(eg. [this](https://stackoverflow.com/a/34551616) and [this](https://stackoverflow.com/a/8054856)) on SO to avoid code duplication and to be able to pass a iterator variable to a const_iterator parameter.Do you have any suggestion for an alternative implementation without using inheritance?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-14T20:46:40.060", "Id": "453845", "Score": "0", "body": "2)About Insertion: did I used the allocators in any inconsistent way? If so, just for reference, how could I make it more consistent (even if more complex)? I was using allocators only for practice; most books only use new/delete, as you suggested. \nAbout resize: I will make the recommended modifications regarding insert_internal, thanks. Could you suggest a more usual implementation? Both resize(size_type, const T&) and resize(size_type) will have basically identical implementations. Is there any a better way to avoid code duplication and improve my current usage of perfect forwarding?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-15T09:55:00.460", "Id": "453894", "Score": "1", "body": "@M.ars I have updated my answer to address your concerns. Note that there's nothing wrong with your usage of perfect forwarding in `resize` - just that I didn't see it before." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-15T11:29:49.103", "Id": "453907", "Score": "1", "body": "Consider adding `-Weffc++` to the warnings." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-15T15:40:19.970", "Id": "453932", "Score": "0", "body": "@L.F. Thanks for the clarifications and recommendations. I will search more about the functions you used to change the data model and fix all the bugs/bad practices (and improve my future tests)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-16T05:14:13.860", "Id": "453996", "Score": "0", "body": "@Toby Hmm ... personally I don’t use -Weffc++, but I can see that it can be useful." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-13T12:50:43.040", "Id": "232318", "ParentId": "232150", "Score": "2" } } ]
{ "AcceptedAnswerId": "232318", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-10T15:14:35.660", "Id": "232150", "Score": "9", "Tags": [ "c++", "beginner", "linked-list", "reinventing-the-wheel", "c++17" ], "Title": "Simplified Linked List Implementation in C++" }
232150
<p>The goal of the project is to automate sending the same e-mail to a list of people with the same text (except the salutation "Dear Name of Person") with an HTML signature and a PDF attachment.</p> <p>For this purpose, I have:</p> <ol> <li><p>An Excel list with Name, E-Mail, Subject and a "sent?" field (that has to be marked once the e-mail is sent) as seen on this picture: <a href="https://imgur.com/pxYiRvx" rel="nofollow noreferrer">https://imgur.com/pxYiRvx</a></p></li> <li><p>an HTML file with the e-mail template. To avoid having too much code in the python file, I saved the HTML e-mail separately. The text was written very simple between p tags and the signature was created with the help of the following tool: <a href="https://www.hubspot.com/email-signature-generator?utm_source=create-signature" rel="nofollow noreferrer">https://www.hubspot.com/email-signature-generator?utm_source=create-signature</a></p></li> <li><p>The send_email.py file, which code is shown here:</p></li> </ol> <pre class="lang-py prettyprint-override"><code>#!/usr/bin/python import smtplib import pandas as pd from email.message import EmailMessage import openpyxl #E-Mail Credentials EMAIL_ADDRESS = 'example@gmail.com' EMAIL_PASSWORD = 'Password1!' #/// ----- /// #Read HTML E-Mail Template with open('template.html', 'r') as f: html_string = f.read() #/// ----- /// #Load XLS Workbook for writing file = "EmailList.xlsx" wb = openpyxl.load_workbook(file) ws = wb.active #/// ----- /// #1.1 Loading E-Mail Recipient List with Pandas for reading email_list = pd.read_excel("EmailList.xlsx") #1.2 Get all the Names, Email Addreses, Subjects and Messages xls_names = email_list['Name'] xls_emails = email_list['Email'] xls_subjects = email_list['Subject'] #1.3 Loop through the emails for index in range(len(xls_emails)): name = xls_names[index] email = xls_emails[index] subject = xls_subjects[index] #1.4 Create E-Mail (loop) msg = EmailMessage() msg['Subject'] = subject msg['From'] = EMAIL_ADDRESS msg['To'] = email msg.set_content(html_string.format(name=name), subtype='html') #Load Attachments files = ['halle.pdf'] for file in files: with open(file, 'rb') as f: file_data = f.read() file_name = f.name msg.add_attachment(file_data, maintype='application', subtype='octet-stream', filename=file_name) #try to send mail with smtplib.SMTP_SSL('smtp.gmail.com', 465) as smtp: smtp.login(EMAIL_ADDRESS, EMAIL_PASSWORD) try: smtp.send_message(msg) print('\n Email to {} successfully sent!\n'.format(email)) #loop for check feedback in XLS for column in ws.iter_cols(1): for cell in column: if cell.value == email: ws.cell(row=cell.row, column=4).value = 'check!' wb.save("EmailList.xlsx") except Exception as e: print('\n\n Email to {} could not be sent :( because {}'.format(email, str(e))) </code></pre> <p>The questions I have are:</p> <ol> <li>Is the code ok?</li> <li>Do I need to have a plain text alternative for the HTML e-mail? Or is this overrated? </li> <li>I saw many many posts importing and using MIMEMultipart, MIMETextimport, MIMEBase****t and what not. I did not use it, but of course I am wondering if I have something wrong?</li> </ol>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-12T05:48:36.290", "Id": "453364", "Score": "0", "body": "Is this code OK? Sure, however there are lots of things you could improve upon. First comes to mind is using argparse so that your variables are not hardcoded. Do you NEED to have a plain text alt message? Best practice says so: https://litmus.com/blog/best-practices-for-plain-text-emails-a-look-at-why-theyre-important. Finally, you may as well use the built in MIME functions. Perhaps take a look at my SMTP program, which has functionality for what you are trying to do in addition to many other things (like email spoofing). Hope this helps... https://github.com/darkerego/SmtpRelaySpoof" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-10T16:23:13.283", "Id": "232152", "Score": "2", "Tags": [ "python", "excel", "email" ], "Title": "E-Mail Automatisation Project with smtplib but did not use MIMEMultipart" }
232152
<p>I have been developing multilanguage website based on Symfony4. Structure of one of the tables:</p> <pre><code>+-----------+--------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +-----------+--------------+------+-----+---------+----------------+ | id | int(11) | NO | PRI | NULL | auto_increment | | title_en | varchar(255) | NO | | NULL | | | title_fr | varchar(255) | NO | | NULL | | | title_de | varchar(255) | NO | | NULL | | | parent_id | int(11) | NO | | NULL | | </code></pre> <p>What is the optimal way to select appropriate column in template depending on user locale?</p> <p>How bad will look the approach below to get needed entity field ?</p> <p> <p>namespace App\Entity;</p> <p>use Doctrine\ORM\Mapping as ORM;</p> <pre><code>/** * Category * * @ORM\Table(name="category") * @ORM\Entity */ class Category { /** * @var int * * @ORM\Column(name="id", type="integer", nullable=false) * @ORM\Id * @ORM\GeneratedValue(strategy="IDENTITY") */ private $id; /** * @var string * * @ORM\Column(name="title_en", type="string", length=255, nullable=false) */ private $titleEn; /** * @var string * * @ORM\Column(name="title_fr", type="string", length=255, nullable=false) */ private $titleFr; /** * @var string * * @ORM\Column(name="title_de", type="string", length=255, nullable=false) */ private $titleDe; /** * @var int * * @ORM\Column(name="parent_id", type="integer", nullable=false) */ private $parentId = '0'; public function getId(): ?int { return $this-&gt;id; } public function getLocalizedTitle(): ?string { $locale='title'.ucfirst($GLOBALS['request']-&gt;getLocale()); return $this-&gt;{$locale}; } public function getTitleEn(): ?string { return $this-&gt;titleEn; } public function setTitleEn(string $titleEn): self { $this-&gt;titleEn = $titleEn; return $this; } public function getTitleDe(): ?string { return $this-&gt;titleDe; } public function setTitleDe(string $titleDe): self { $this-&gt;titleDe = $titleDe; return $this; } public function getParentId(): ?int { return $this-&gt;parentId; } public function setParentId(int $parentId): self { $this-&gt;parentId = $parentId; return $this; } } </code></pre> <p>Then in view to get field we just use </p> <pre><code>{{ job.category.getLocalizedTitle }} </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-10T19:09:27.477", "Id": "453173", "Score": "0", "body": "This code already works and suggests improvements based on better performance and readability" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-10T19:17:31.617", "Id": "453174", "Score": "3", "body": "I think this isn't a sustainable approach that will scale well. Consider keying your resources with an ID *and* a language code instead; that way adding support for a new language doesn't require schema + code changes, just the new data." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-12T08:58:30.970", "Id": "453382", "Score": "1", "body": "@MathieuGuindon Something like a single JSON per language?" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-10T18:16:52.310", "Id": "232154", "Score": "3", "Tags": [ "php", "symfony4" ], "Title": "Symfony 4 translate Entity fields" }
232154
<p>This code inputs a weighted edgelist, positive and negative sentiment seed words, and a target word. The program computes the sum of the weights along shortest paths from the seed words to the target and from the target to the seed words, as it generates 9 output values.</p> <p>The program is very slow. Running large edgelist files takes days, rather than minutes or seconds.</p> <p>How can this program be sped up?</p> <pre><code>from tkinter import Tk, X, Y, TOP, BOTTOM, LEFT, RIGHT, BOTH, END from tkinter import filedialog, messagebox from tkinter.ttk import Frame, Button, Entry, Label, Progressbar import os, glob, time import pandas as pd root = Tk() root.geometry(&quot;600x400+300+300&quot;) def read_edge_list(filename): edges = {} words = set() with open(filename) as fp: lines = fp.readlines() for line in lines: token = line.split() if len(token) != 3: continue word1 = token[0] word2 = token[1] freq = token[2] words = words | {word1, word2} if not word1 in edges.keys(): edges[word1] = {} if not word2 in edges[word1]: edges[word1][word2] = {} edges[word1][word2] = freq return edges, words def read_sentiment(filename): with open(filename, encoding='utf-8-sig') as fp: lines = fp.readlines() words = {line.strip() for line in lines} return words def read_target_word(): word = input(&quot;Please input target word: &quot;) return word def run_shortest_path_algorithm(edges, positive, negative, target): positivedict = {} negativedict = {} for source in positive: dist1 = dijkstra(edges, source, target) dist2 = dijkstra(edges, target, source) if dist1 and dist2: positivedict[source] = dist1 + dist2 for source in negative: dist1 = dijkstra(edges, source, target) dist2 = dijkstra(edges, target, source) if dist1 and dist2: negativedict[source] = dist1 + dist2 return positivedict, negativedict def calculate_statistics_summary(positivedict, negativedict, positivewords, negativewords): numpositive = len(positivedict) numnegative = len(negativedict) actualnumpositive = len(positivewords) actualnumnegative = len(negativewords) sumpositive = sum(positivedict.values()) sumnegative = sum(negativedict.values()) if actualnumpositive == 0: s1 = 0 else: s1 = sumpositive / actualnumpositive if actualnumnegative == 0: s2 = 0 else: s2 = sumnegative / actualnumnegative if numnegative == 0: s3 = 0 else: s3 = s1 * numpositive / numnegative if s2 == 0: s4 = 0 else: s4 = s3 / s2 if numpositive == 0: s5 = 0 else: s5 = sumpositive / numpositive if numnegative == 0: s6 = 0 else: s6 = sumnegative / numnegative if numnegative == 0: s7 = 0 else: s7 = s5 * numpositive / numnegative if s6 == 0: s8 = 0 else: s8 = s7 / s6 s9 = s3 - s2 return [s1, s2, s3, s4, s5, s6, s7, s8, s9] def write_output_file(): pass def dijkstra(graph, start, end): shortest_paths = {start: (None, 0)} current_node = start visited = set() while current_node != end: visited.add(current_node) if current_node not in graph: destinations = [] else: destinations = graph[current_node].keys() weight_to_current_node = shortest_paths[current_node][1] for next_node in destinations: weight = int(graph[current_node][next_node]) + weight_to_current_node if next_node not in shortest_paths: shortest_paths[next_node] = (current_node, weight) else: current_shortest_weight = shortest_paths[next_node][1] if current_shortest_weight &gt; weight: shortest_paths[next_node] = (current_node, weight) next_destinations = {node: shortest_paths[node] for node in shortest_paths if node not in visited} if not next_destinations: return None current_node = min(next_destinations, key=lambda k: next_destinations[k][1]) #path = [] #while current_node is not None: #path.append(current_node) #next_node = shortest_paths[current_node][0] #current_node = next_node #path = path[::-1] #return path return shortest_paths[end][1] class SentimentWindow(Frame): def __init__(self): super().__init__() self.initUI() self.initPositiveDir = None self.initNegativeDir = None self.initSaveDir = None self.summary = pd.DataFrame(columns=['S1', 'S2', 'S3', 'S4', 'S5', 'S6', 'S7', 'S8', 'S9']) def initUI(self): self.master.title(&quot;Sentiment&quot;) self.pack(fill=BOTH, expand=True, padx=15, pady=15) frmEdges = Frame(self) frmEdges.pack(fill=X, expand=True) lblEdges = Label(frmEdges, text=&quot;Select the directory of edge list.&quot;) lblEdges.pack(expand=True, fill=X, side=TOP, pady=2) frmEdgesPath = Frame(frmEdges) frmEdgesPath.pack(expand=True, fill=X, side=BOTTOM, pady=2) self.entEdgesPath = Entry(frmEdgesPath, width=60) self.entEdgesPath.pack(expand=True, fill=X, side=LEFT) btnEdgesPath = Button(frmEdgesPath, width=20, text=&quot;Load Edges&quot;, command=self.loadEdges) btnEdgesPath.pack(expand=True, side=RIGHT) frmPositive = Frame(self) frmPositive.pack(fill=X, expand=True) lblPositive = Label(frmPositive, text=&quot;Select the positive file.&quot;) lblPositive.pack(expand=True, fill=X, side=TOP, pady=2) frmPositivePath = Frame(frmPositive) frmPositivePath.pack(expand=True, fill=X, side=BOTTOM, pady=2) self.entPositivePath = Entry(frmPositivePath, width=60) self.entPositivePath.pack(expand=True, fill=X, side=LEFT) btnPositivePath = Button(frmPositivePath, width=20, text=&quot;Load Positive&quot;, command=self.loadPositive) btnPositivePath.pack(expand=True, side=RIGHT) frmNegative = Frame(self) frmNegative.pack(fill=X, expand=True) lblNegative = Label(frmNegative, text=&quot;Select the negative file.&quot;) lblNegative.pack(expand=True, fill=X, side=TOP, pady=2) frmNegativePath = Frame(frmNegative) frmNegativePath.pack(expand=True, fill=X, side=BOTTOM, pady=2) self.entNegativePath = Entry(frmNegativePath, width=60) self.entNegativePath.pack(expand=True, fill=X, side=LEFT) btnNegativePath = Button(frmNegativePath, width=20, text=&quot;Load Negative&quot;, command=self.loadNegative) btnNegativePath.pack(expand=True, side=RIGHT) frmTarget = Frame(self) frmTarget.pack(fill=X, expand=True) lblTarget = Label(frmTarget, text=&quot;Input the target word.&quot;) lblTarget.pack(expand=True, fill=X, side=TOP, pady=2) self.entTarget = Entry(frmTarget) self.entTarget.pack(fill=X, expand=True, pady=2) frmRun = Frame(self) frmRun.pack(fill=X, expand=True, pady=20) self.proRun = Progressbar(frmRun, value=0) self.proRun.pack(fill=X, expand=True, side=LEFT) btnRun = Button(frmRun, text = &quot;Run&quot;, width=20, command=self.run) btnRun.pack(side=RIGHT, padx=20) def loadEdges(self): edgesFolderName = filedialog.askdirectory() if edgesFolderName: self.entEdgesPath.delete(0, END) self.entEdgesPath.insert(0, edgesFolderName) def loadPositive(self): if self.initPositiveDir is None: self.initPositiveDir = &quot;/&quot; positiveFileName = filedialog.askopenfilename(initialdir=self.initPositiveDir, title=&quot;Open Positive File&quot;, filetypes=((&quot;Text file&quot;, &quot;*.txt&quot;),)) if positiveFileName: self.initPositiveDir = positiveFileName self.entPositivePath.delete(0, END) self.entPositivePath.insert(0, positiveFileName) def loadNegative(self): if self.initNegativeDir is None: self.initNegativeDir = &quot;/&quot; negativeFileName = filedialog.askopenfilename(initialdir=self.initNegativeDir, title=&quot;Open Positive File&quot;, filetypes=((&quot;Text file&quot;, &quot;*.txt&quot;),)) if negativeFileName: self.initNegativeDir = negativeFileName self.entNegativePath.delete(0, END) self.entNegativePath.insert(0, negativeFileName) def run(self): edgesFolderName = self.entEdgesPath.get() if not os.path.isdir(edgesFolderName): messagebox.showerror(&quot;Invalid Path&quot;, &quot;The directory of edge list is invalid.&quot;) return positiveFileName = self.entPositivePath.get() if not os.path.isfile(positiveFileName): messagebox.showerror(&quot;Invalid Path&quot;, &quot;The positive filename is invalid.&quot;) return negativeFileName = self.entNegativePath.get() if not os.path.isfile(negativeFileName): messagebox.showerror(&quot;Invalid Path&quot;, &quot;The negative filename is invalid.&quot;) return targetWord = self.entTarget.get() if targetWord is None or len(targetWord) &lt;= 0: messagebox.showerror(&quot;No Target&quot;, &quot;Please input the target word.&quot;) os.chdir(edgesFolderName) edgefiles = glob.glob(&quot;*.pr&quot;) if len(edgefiles) &lt;= 0: messagebox.showerror(&quot;No Edge File&quot;, &quot;Cannot find the edge files.&quot;) positivewords = read_sentiment(positiveFileName) negativewords = read_sentiment(negativeFileName) self.summary.drop(self.summary.index, inplace=True) self.proRun[&quot;value&quot;] = 0.0 self.proRun.update() root.config(cursor=&quot;wait&quot;) root.update() time.sleep(0.300) for index, edgefile in enumerate(edgefiles): edges, words = read_edge_list(edgefile) if targetWord not in words: messagebox.showerror(&quot;Invalid Target&quot;, &quot;Target does not exist in &quot; + edgefile) else: possiblepositive = positivewords &amp; words possiblenegative = negativewords &amp; words positivedict, negativedict = \ run_shortest_path_algorithm(edges, possiblepositive, possiblenegative, targetWord) statistics_summary = calculate_statistics_summary(positivedict, negativedict, positivewords, negativewords) self.summary.loc[edgefile] = statistics_summary self.proRun[&quot;value&quot;] = 100 * (index + 1) / len(edgefiles) self.proRun.update() root.config(cursor=&quot;&quot;) if self.summary.shape[0] &gt; 0: self.summary.loc['mean'] = self.summary.mean() self.summary.loc['std'] = self.summary.std() if self.initSaveDir is None: self.initSaveDir = &quot;/&quot; outputFile = filedialog.asksaveasfilename(initialdir=self.initSaveDir, title=&quot;Save Summary File&quot;, filetypes=((&quot;Text file&quot;, &quot;*.txt&quot;),)) self.initSaveDir = outputFile if outputFile: with open(outputFile, 'w') as outfp: self.summary.to_string(outfp) app = SentimentWindow() root.mainloop() </code></pre> <p>Some data files for this program:</p> <ul> <li><p><a href="https://drive.google.com/file/d/1zDOSMFz0AooXrs9WJ0noC3oD9cWg_562/view?usp=sharing" rel="nofollow noreferrer">small edgelists</a></p> </li> <li><p><a href="https://drive.google.com/file/d/18NR_bPjb9OU03n7MO08GwELrK7gqXEKE/view?usp=sharing" rel="nofollow noreferrer">a big file that will run for days</a></p> </li> <li><p><a href="https://docs.google.com/document/d/1Y0eFolLWjqoHiFnHD7TOS-9z5h1xxmvUiENS1TEv9yU/edit?usp=sharing" rel="nofollow noreferrer">the negative seed file</a></p> </li> <li><p><a href="https://docs.google.com/document/d/1FAct8O-rRN6qsdTU3praW6hy2ckMf1s1mA9K2gy7WYI/edit?usp=sharing" rel="nofollow noreferrer">the positive seed file</a></p> <p>Set the target word to <code>bp</code>.</p> </li> </ul> <p>Here's <a href="https://docs.google.com/document/d/1erSpyXxy3eMehBCiYJudf7tnQgIneT9H7Ot2_wGYBBI/edit?usp=sharing" rel="nofollow noreferrer">the code in a file</a>.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-10T20:56:15.967", "Id": "453181", "Score": "0", "body": "How are these files supposed to be opened?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-10T23:48:37.957", "Id": "453193", "Score": "1", "body": "For all the comments in the code, I can't tell whether it tries to implement a standard algorithm for *shortest path* or something home-grown. (I can take a guess given the function names that it uses one as a partial solution.)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-11T03:39:51.857", "Id": "453210", "Score": "0", "body": "It uses Dijkstra's algorithm. Wondering if using igraph's implementation would be better." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-11T06:47:53.977", "Id": "453215", "Score": "0", "body": "It appears to me that your Dijkstra's algorithm implementation is not using a priority queue?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-12T19:13:52.547", "Id": "453486", "Score": "0", "body": "How would a priority queue work?" } ]
[ { "body": "<p><em>Just going to comment on style</em></p>\n\n<h1>Method Naming</h1>\n\n<p>Method names should be in <code>snake_case</code>. You got it right with the class names, as they should be <code>PascalCase</code>, but method names are in <code>snake_case</code>.</p>\n\n<h1>Ternary Operations</h1>\n\n<p>Your huge block of if statements in <code>calculate_statistics_summary</code> can be reduced to one line each, utilizing the ternary operator:</p>\n\n<pre><code>s1 = 0 if actualnumpositive == 0 else sumpositive / actualnumpositive\ns2 = 0 if actualnumnegative == 0 else sumnegative / actualnumnegative\ns3 = 0 if numnegative == 0 else s1 * numpositive / numnegative\ns4 = 0 if s2 == 0 else s3 / s2\ns5 = 0 if numpositive == 0 else sumpositive / numpositive\ns6 = 0 if numnegative == 0 else sumnegative / numnegative\ns7 = 0 if numnegative == 0 else s5 * numpositive / numnegative\ns8 = 0 if s6 == 0 else s7 / s6\ns9 = s3 - s2\n</code></pre>\n\n<h1>Type Hints</h1>\n\n<p>You should use type hints to make it clear what types of parameters are acceptable to methods, and what type are returned, if any. For example:</p>\n\n<pre><code>def calculate_statistics_summary(positivedict, negativedict, positivewords, negativewords):\n</code></pre>\n\n<p>can be this (added spacing to make it readable)</p>\n\n<pre><code>def calculate_statistics_summary(\n positivedict: dict,\n negativedict: dict,\n positivewords: set,\n negativewords: set\n) -&gt; List[float]:\n</code></pre>\n\n<p>Now it's much clearer what types are passed to the method, and that a list containing floats (from my interpretation) is being returned.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-10T20:33:08.267", "Id": "232160", "ParentId": "232155", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-10T18:51:03.337", "Id": "232155", "Score": "5", "Tags": [ "python", "performance" ], "Title": "python program for computing shortest paths" }
232155
<p>I've created a function in python to print some information through it. I'm trying to supply list of alphabets to the function along with the type those alphabets fall under.</p> <p>When I execute the function, It checks whether the value of the type is None. If it is None, it executes the except block to fetch one.</p> <p>I've tried with (working one):</p> <pre><code>def get_info(alpha,alpha_type): print("checking value of item:",alpha_type) try: if not alpha_type:raise return alpha,alpha_type except Exception: alpha_type = "vowel" return get_info(alpha,alpha_type) if __name__ == '__main__': main_type = None for elem in ["a","e","o"]: result = get_info(elem, alpha_type=main_type) main_type = result[1] print(result) </code></pre> <p>Output it produces (as expected):</p> <pre><code>checking value of item: None checking value of item: vowel ('a', 'vowel') checking value of item: vowel ('e', 'vowel') checking value of item: vowel ('o', 'vowel') </code></pre> <p>Although the value of the type is None when an alphabet is supplied to the function, ain't there already the value of previous type (when run twice) stored in the memory. However, When I try like the following, I get messy output:</p> <pre><code>def get_info(alpha,alpha_type): print("checking value of item:",main_type) try: if not alpha_type:raise return alpha,alpha_type except Exception: alpha_type = "vowel" return get_info(alpha,alpha_type) if __name__ == '__main__': for elem in ["a","e","o"]: print(get_info(elem,alpha_type=None)) </code></pre> <p>Output the second function produces:</p> <pre><code>checking value of item: None checking value of item: vowel ('a', 'vowel') checking value of item: None checking value of item: vowel ('e', 'vowel') checking value of item: None checking value of item: vowel ('o', 'vowel') </code></pre> <p>I would like to get the expected output (what the first function produces) following the design of the second function, so that I don't need to influence the result from outside of the function.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-11T08:43:05.010", "Id": "453221", "Score": "0", "body": "You could abuse a mutable default argument to persist state. But that would be a very ugly hack. If you need to keep a state, either do it separately in a variable external to the function (if it is a state of the surrounding code), or make this into a class which can keep the state together with the method (if it is a state inherently tied to the function)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-11T08:51:54.320", "Id": "453222", "Score": "0", "body": "With abuse I mean something like [this](https://tio.run/##bY5Bq8IwEITv/RVDTg30IOip0OO7evRSSgi4wUBNwiYV@@trbEWjvD1lZ77JbJjTxbv9spzJwNT3BsaOpNIcqDt6Rw2U@ij9INsKeaz5cLARzic88c19ThHr2wEd@vc@vCGmNLFD2bp6NOaC4of2n0RZsBtesVii2kbCSY8T/TF7rsWR6IzkEacQxhka6/mecdE3QmC6WT/F7KyAzfCGCFlV60FOX0kpdB2EUldtnVJiKwxsXapNfWiQH1J@ifufXWjRICb@laOQclke)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-11T11:11:05.973", "Id": "453234", "Score": "0", "body": "I don't get it, if instead of your `for elem in [\"a\", \"e\", \"o\"]` I use `for elem in \"abc\"` I also have 3 vowels... What's the point?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-11T12:10:37.170", "Id": "453238", "Score": "0", "body": "Consider the `list of alphabets` as `list of links` and the `alpha_type` is a random proxy. The above function is supposed to reuse the samy proxy until invalid. Thanks." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-11T12:30:34.587", "Id": "453241", "Score": "0", "body": "Considering the output isn't as expected, the code doesn't work properly. Please take a look at the [help/on-topic]." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-11T16:27:12.590", "Id": "453267", "Score": "0", "body": "Well, if your (real) code fetches URLs through proxies, why are you posting about letters and vowels? We could propose optimizations that removes the `alpha_type` parameter and this would waste everyone's time. Why don't you post your real code instead?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-12T04:26:13.260", "Id": "453354", "Score": "0", "body": "Your suggestion worked out @Graipher. Thanks." } ]
[ { "body": "<p>First, your code reformatted properly so it's more legible:</p>\n\n<pre><code>def get_info(alpha, alpha_type):\n\n print(\"checking value of item:\", alpha_type)\n\n try:\n if not alpha_type:\n raise\n\n return alpha, alpha_type\n\n except Exception:\n alpha_type = \"vowel\"\n return get_info(alpha, alpha_type)\n\n\nif __name__ == '__main__':\n main_type = None\n for elem in [\"a\", \"e\", \"o\"]:\n result = get_info(elem, alpha_type=main_type)\n main_type = result[1]\n print(result)\n</code></pre>\n\n<p>Take 20 minutes and read over <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP8</a>. It's Python's style guide and dictates how code should look. Most notably, you should have spaces after commas, and you shouldn't try to shove things onto one line in most cases (like you're doing with <code>raise</code>).</p>\n\n<hr>\n\n<p>Your code is abusing <code>try</code> and <code>raise</code>. It doesn't make any sense to <code>raise</code> in a <code>try</code> just to go to the <code>except</code>. You should just use make use of the <code>if</code> that you already have:</p>\n\n<pre><code>def get_info(alpha, alpha_type):\n\n print(\"checking value of item:\", alpha_type)\n\n if not alpha_type:\n return get_info(alpha, \"vowel\")\n\n else:\n return alpha, alpha_type\n</code></pre>\n\n<hr>\n\n<p>Honestly, I don't understand what you're trying to do here, so that's really all I can comment on. I just wanted to point out the formatting and needless use of <code>try</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-10T20:57:44.087", "Id": "232161", "ParentId": "232156", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-10T20:01:52.780", "Id": "232156", "Score": "1", "Tags": [ "python", "python-3.x" ], "Title": "Reuse the value of previous type instead of None" }
232156
<p>Hope someone can help me out in reviewing this code to make it faster.</p> <p>My goal is to create a graph recursively: </p> <ol> <li>query for a node and its neighbors from a db (not present here)</li> <li>add it and its neighbours to a graph</li> <li>until you find a target, recurse (1, 2) for each neighbour</li> </ol> <p>I also set a control <code>maxNodes</code> in case target is not found.</p> <p>I don't want to process twice a node and tried some optimisation with <code>node_processed</code> and <code>node_to_process</code>: </p> <p>if a node was already processed (<code>node_processed</code>) so that its children already added to the graph, then skip it and go to the next in <code>node_to_process</code>.</p> <p>I tried to implement a second version making use of an adjacency list with lists and sets, I was able to achieve 2 order magnitude faster performance, but the resulting graphs were not exactly the same, with qualitative worse results. Because of this, the second version was considered inappropriate for the question and I remove it.</p> <p>Networx has neat interface to access data, but in this case it is too slow.</p> <p>Could you help in feedback how to make this function significantly faster ? Intended use is real-time sub-graph extraction.</p> <p><strong>EDITED: to abide with comments for making question on topic</strong></p> <p>I put here the function for computing a sub-graph recursively: for clarity, focus on the construct_simply_subgraph() and subgraph().</p> <p>The inner function <code>is_target_in_neighbors( parent, target)</code> just return an edge_list in the form of <code>[(parent, neighbor1, edge1_weight), (parent, neighbor2, edge2_weight) ... ]</code> and a boolean is_found, that tells if the searched target node is present in the edge_list.</p> <p>So let's use a mockup data here, and generate a db:</p> <pre><code>import random number_of_ids = 6000000 db_nodes = set(random.randrange(1, number_of_ids) for i in range(number_of_ids)) def generate_neighbors(parent, max_number_of_neighbors): generate_weight = lambda x : round( random.uniform(0, 1) , x) neighbors = set([random.choice( list(db_nodes - {parent}) ) for _ in range(0, max_number_of_neighbors)]) return sorted( [(parent, neighbor, generate_weight(3)) for neighbor in neighbors] , key= lambda x :x[2], reverse=True) # will take long while db = { u : generate_neighbors( u, random.randrange(50, 500) ) for u in db_nodes} </code></pre> <p>Use:</p> <pre><code># start node a = random.choice(list(db.keys())) # target b = random.choice(list(db.keys())) # compute a subgraph make_subgraph(a, b) </code></pre> <p>Now, let get a subgraph of a node, attempting to reach out to a target node:</p> <pre><code>import networkx as nx def make_subgraph(fromNode, toNode, weight = True, toComplete = False): #iterate g = nx.Graph() maxNodes =10000 nodes_processed = [] nodes_to_process = [] # helper function returning parents' neighbors # check if target node is among them def is_target_in_neighbors( parent, target): weighted_edge_list = db[parent] if not weight: return [(u, v) for (u, v, w) in neighbors ], target in [t[1] for t in weighted_edge_list] else: return weighted_edge_list, target in [t[1] for t in weighted_edge_list] def construct_simple_sub_graph(startNode, g): edge_list, is_found = is_target_in_neighbors( startNode, toNode) if weight: g.add_weighted_edges_from( edge_list ) else: g.add_edges_from( edge_list ) nodes_processed.append( startNode ) for node in list(g.nodes): # if not has not yet been processed: add it to a "TODO" list of nodes to be processed; otherwise, remove it from the TODO if node not in nodes_processed: if node not in nodes_to_process: nodes_to_process.append( node ) else: if node in nodes_to_process: nodes_to_process.remove( node ) return g def subgraph(fromNode, g): while not ( g.has_node( fromNode) and g.has_node( toNode) ): for node in nodes_to_process: #print('Iterations has', g.number_of_nodes()) g = construct_simple_sub_graph( node, g) if (g.number_of_nodes() &gt; maxNodes) : return g return g else: return g g = construct_simple_sub_graph( fromNode, g) g = subgraph(fromNode, g) # complete ? if toComplete: for node in nodes_to_process: if node not in nodes_processed: g = construct_simple_sub_graph( node, g ) print('Found {} edges, {} nodes, {} remaining'.format( g.number_of_edges(), g.number_of_nodes() , len(nodes_to_process)) ) return g </code></pre> <p><strong>Could you help improve performance ?</strong></p> <p>Performance Test on actual db: 26s </p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-10T20:49:40.367", "Id": "453179", "Score": "1", "body": "Welcome to Code Review! At the moment the question has several issues. The code looks incomplete and the `//` style comments make it strictly speaking invalid Python code. The last part of the question also seems to indicate that the code is not working as intended. All of these points make if [off-topic](/help/dont-ask) for this site. To fix this, [provide the complete working code](/help/on-topic)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-10T21:13:03.937", "Id": "453184", "Score": "0", "body": "@AlexV I used pseudo-code as `//` to clarify and focus on the essential part. Both the snippets works, but I the second snippet offers slightly different results, although it computes much faster. So question is about performance with networkx (first snippet) which I tried to rework out with the snippet above as a comparison. According to https://codereview.stackexchange.com/help/on-topic this is a performance and correctness question; for the second snippet, it is suggested SO, however since code execute and I post here asking for answer related to performance and logic. Can it be ok here?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-11T09:48:07.293", "Id": "453228", "Score": "2", "body": "As the downvotes tell you, \"stubby\"/pseudo code is not well received here." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-11T14:12:33.440", "Id": "453246", "Score": "0", "body": "Edited to make the question well received here. Please reconsider down-voting: first function is working correctly, to the best of my knowledge. I post question here to improve performance. The second function is an attempt to improve the performance, but I obtain slightly different results than the first. If yet not ok with the policy, I will remove it and leave only the first function. Please advice, thank you." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-11T16:27:01.647", "Id": "453266", "Score": "0", "body": "Considering the 2nd version doesn't produce the correct results, does its speed matter? Does the function matter at all, if it doesn't work?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-11T18:46:30.707", "Id": "453303", "Score": "0", "body": "@Mast thank you for asking. Yes speed it matters, for I want to use that function in applications to extract subgraph in \"real-time\". The second function matter because 2 order of magnitude faster than the first (1 st fetch a subgraph of 10K nodes in 26s, 2nd a subgraph of 4K nodes in 150ms). It works as well however, when I run other analytics (e.g. shortest path) the results are less \"insightful\" than the first function. That is because of how the subgraph is constructed. I wish to improve performance of first and receive feedback for improving coding-skills to use graphs in real-time." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-14T09:54:27.197", "Id": "453736", "Score": "0", "body": "@Mast and Moderators : I edited the question but I see the question is still on hold : are there other changes I should do to put it on-topic and receive feedback ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-14T10:15:39.357", "Id": "453742", "Score": "0", "body": "Please make sure you've indented your code correctly. That's very important with Python, since a bit of whitespace more or less makes a lot of difference in how the code is executed." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-14T10:18:43.613", "Id": "453744", "Score": "0", "body": "Can you provide a usage example of the working code, to show what kind of data you throw at it? The first code works, right? If the second code doesn't produce the correct result, I still think it has no value as code. However, it does show what you've tried, which may or may not help future reviewers point you in the right direction. So while I disagree with you that the second function matters, there's no need to remove it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-14T13:55:41.177", "Id": "453784", "Score": "0", "body": "Hi Mast, yes, my intention for the second function is to show what I've done, in the spirit of StackOverflow to help other reviewers. Anyway this is my first question on CodeReview, and really, not a problem to remove it if it raises confusion. I will edit again the question to include kind of data the function take. Thank you." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-15T01:58:08.177", "Id": "453867", "Score": "0", "body": "The first function is missing an import for `nx`. A reviewer should be able to copy and paste the code and run it. That said, you say the first function works, and you want help making it faster. In my opinion, if you delete everything after \"Could you help improve performance?\" it would be an on topic question. As an aside, the second function changes the list `nodes_to_process` while it is being iterated over, which is probably a cause of the errors." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-15T10:28:12.550", "Id": "453900", "Score": "0", "body": "@RootTwo Thank you for your interest in this question. `Nodes_to_process` was copied, to avoid a same object to be changed while being iterated over. However I deleted the second function to meet yours and Mast's comments. Hope now the question can be marked as on topic." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-15T12:05:24.857", "Id": "453913", "Score": "0", "body": "So an improvement I have done is to replace use of lists with dictionary, that dramatically improved the performance. Graph is similar, not exactly the same though, and for the sake of comprehension I'd like to understand why. Could not post it as an answer, though. It would be interesting to see others feedback." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "13", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-10T20:32:28.560", "Id": "232159", "Score": "0", "Tags": [ "python", "performance", "recursion", "comparative-review", "graph" ], "Title": "Recursion on graphs - networkx VS adjacency lists with native lists, sets or numpy vectors ( python )" }
232159
<p>The Library is meant to be re-used for both the browser and the nodejs runtime environment, publishing this code for a code review to make it better and concise.</p> <p><strong>Question</strong>: How to build a library in an elegant way that's usable on both platforms, Browser Landscape and NodeJS runtime environment.</p> <p>Following implementation takes care of that, but seeking for any room for improvement.</p> <hr /> <h2>Import</h2> <p><strong>nodeJS</strong> convenience_product.js</p> <pre><code>let MyLib; // import for either browser and the nodeJS if (typeof module !== 'undefined' &amp;&amp; typeof module.exports !== 'undefined') { MyLib = require(&quot;../dist/mylib&quot;); } else { MyLib = window.MyLib; } class ConvenienceProduct extends MyLib.Product { constructor() { console.log(&quot;Hello ConvenienceProduct&quot;); } } </code></pre> <p><strong>Browser</strong> index.html</p> <pre><code>&lt;head&gt; &lt;script src=&quot;../dist/mylib.js&quot;&gt;&lt;/script&gt; &lt;script src=&quot;convenience_product.js&quot;&gt;&lt;/script&gt; &lt;/head&gt; </code></pre> <hr /> <h2>Export</h2> <p><strong>nodeJS + Browser</strong> dist/mylib.js</p> <pre><code>&quot;use strict&quot;; (() =&gt; { // using IIFE to avoid polluting browser namespace /** @class MyLib.Product **/ // this helps in code hinting class Product { } let MyLib = { Product: Product } if (typeof window !== &quot;undefined&quot;) { window.MyLib = MyLib; } else { module.exports = MyLib; } })(); </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-10T22:52:10.520", "Id": "453188", "Score": "0", "body": "how can I improve this question?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-11T00:04:58.363", "Id": "453200", "Score": "1", "body": "Describing the purpose of the code, *presenting* it to reviewers, would probably help ;-)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-11T00:18:33.100", "Id": "453201", "Score": "0", "body": "while implementation of the class doesn't matter and remains empty, the purpose of the code is to build a library that functions in both the browser as well as the nodejs runtime" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-11T09:53:04.187", "Id": "453229", "Score": "0", "body": "Implementation always matters on Code Review, please see the [help/on-topic]." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-10T22:44:49.217", "Id": "232165", "Score": "1", "Tags": [ "javascript", "node.js", "library" ], "Title": "Proper imports and exports for nodejs and the browser" }
232165
<p>I have a short test to validate that all committed files in the repo are formatted. I'm new to go so not sure what the best wat to do it is. </p> <p>The error handling, in particular, is rather gruesome as it takes up roughly half of the lines.</p> <pre class="lang-py prettyprint-override"><code>package pack import ( "os" "os/exec" "path/filepath" "testing" ) func TestFormatting(t *testing.T) { var commandArgs []string commandArgs = append(commandArgs, "-l") root := "../.." err := filepath.Walk(root, func(path string, info os.FileInfo, err error) error { if filepath.Ext(path) != ".go" { return nil } absPath, e := filepath.Abs(path) if e != nil { return e } commandArgs = append(commandArgs, absPath) return nil }) if err != nil { t.Logf(err.Error()) t.Fail() } out, err := exec.Command("gofmt", commandArgs...).Output() if err != nil { t.Logf(err.Error()) t.Fail() } output := string(out) if output != "" { t.Logf("Testing Formatting") t.Logf(output) t.Fail() } } </code></pre> <p>How can it be improved?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-09T14:39:40.213", "Id": "456875", "Score": "0", "body": "I usually have a small utility function `func fatalIfErr(testing.BT, error)` that calls Fatal if err is not not. So I can do `fatalIfErr(t, err)` to avoid repeating myself." } ]
[ { "body": "<blockquote>\n <p>a short test to validate that all committed files in the repo are\n formatted.</p>\n</blockquote>\n\n<hr>\n\n<p>Here are some notes I made while reading your code.</p>\n\n<hr>\n\n<p>For a real-world code review, code should be correct, maintainable, reasonably efficient, and, most importantly, readable.</p>\n\n<p>Writing code is a process of stepwise refinement.</p>\n\n<p>Define the problem with an outline of a solution.</p>\n\n<pre><code>// checkGoFmt checks that Go source files have been formatted with go fmt or gofmt.\n// checkGoFmt returns a newline separated list of files\n// whose formatting differs from gofmt's and any error.\nfunc checkGoFmt(root string) (string, error) {\n // Command gofmt\n // https://golang.org/cmd/gofmt/\n // $ gofmt -help\n // usage: gofmt [flags] [path ...]\n // -l list files whose formatting differs from gofmt's\n // $\n}\n</code></pre>\n\n<p>Read the documentation for the <code>gofmt</code> command.</p>\n\n<p>Write some code to construct and run the <code>gofmt</code> command. The <code>goFiles</code> function is a stub.</p>\n\n<pre><code>func goFiles(root string) ([]string, error) {\n var files []string\n return files, nil\n}\n\n// checkGoFmt checks that Go source files have been formatted with go fmt or gofmt.\n// checkGoFmt returns a newline separated list of files\n// whose formatting differs from gofmt's and any error.\nfunc checkGoFmt(root string) (string, error) {\n // Command gofmt\n // https://golang.org/cmd/gofmt/\n // $ gofmt -help\n // usage: gofmt [flags] [path ...]\n // -l list files whose formatting differs from gofmt's\n // $\n\n files, err := goFiles(root)\n if err != nil {\n return \"\", err\n }\n if len(files) == 0 {\n return \"\", nil\n }\n\n args := make([]string, 0, 1+len(files))\n args = append(args, \"-l\")\n args = append(args, files...)\n out, err := exec.Command(\"gofmt\", args...).Output()\n return string(out), err\n}\n</code></pre>\n\n<p>Pay attention to program structure. The specific implementation of <code>goFiles</code> is hidden from <code>checkGoFmt</code>. If the end result is not as expected, start by looking at the list of files returned from <code>goFiles</code>. Consider writing a test for the <code>goFiles</code> function. <code>checkGoFmt</code> can be called from a <code>testing</code> package function or a program <code>main</code> function. </p>\n\n<p>The documentation for <code>gofmt</code> states: \"Without an explicit path, it processes the standard input.\" To ensure that <code>TestGoFormatting</code> does not wait on <code>stdin</code>, check that at least one Go file is found. Also, if there is nothing to do then exit.</p>\n\n<p>If possible, make reasonable estimates of slice capacity to minimize allocations.</p>\n\n<p>Read the documentation for <code>filepath.Walk</code> and <code>filepath.WalkFunc</code>.</p>\n\n<blockquote>\n <p>func Walk</p>\n \n <p><code>func Walk(root string, walkFn WalkFunc) error</code></p>\n \n <p>Walk walks the file tree rooted at root, calling walkFn for each file\n or directory in the tree, including root. All errors that arise\n visiting files and directories are filtered by walkFn.</p>\n \n <p><code>type WalkFunc</code></p>\n \n <p>WalkFunc is the type of the function called for each file or directory\n visited by Walk. The path argument contains the argument to Walk as a\n prefix; that is, if Walk is called with \"dir\", which is a directory\n containing the file \"a\", the walk function will be called with\n argument \"dir/a\". The info argument is the os.FileInfo for the named\n path.</p>\n \n <p>If there was a problem walking to the file or directory named by path,\n the incoming error will describe the problem and the function can\n decide how to handle that error (and Walk will not descend into that\n directory). In the case of an error, the info argument will be nil. If\n an error is returned, processing stops. The sole exception is when the\n function returns the special value SkipDir. If the function returns\n SkipDir when invoked on a directory, Walk skips the directory's\n contents entirely. If the function returns SkipDir when invoked on a\n non-directory file, Walk skips the remaining files in the containing\n directory.</p>\n \n <p>type WalkFunc func(path string, info os.FileInfo, err error) error</p>\n</blockquote>\n\n<p>Write code for the <code>goFiles</code> stub.</p>\n\n<pre><code>func goFiles(root string) ([]string, error) {\n var files []string\n\n err := filepath.Walk(root, func(path string, info os.FileInfo, err error) error {\n if err != nil {\n return err\n }\n if info == nil {\n return nil\n }\n if !info.Mode().IsRegular() {\n return nil\n }\n if filepath.Ext(path) != \".go\" {\n return nil\n }\n absPath, e := filepath.Abs(path)\n if e != nil {\n return e\n }\n files = append(files, absPath)\n return nil\n })\n if err != nil {\n return nil, err\n }\n\n return files, nil\n}\n</code></pre>\n\n<p>If an error is passed to the <code>WalkFunc</code> don't ignore it.</p>\n\n<p>Don't <code>panic</code> if the <code>info</code> argument is <code>nil</code>.</p>\n\n<p>The documentation for <code>gofmt</code> states: \"Given a file, it operates on that file; given a directory, it operates on all .go files in that directory, recursively.\"</p>\n\n<p>Only process regular files. If the directory is processed too, the file will be duplicated. For example,</p>\n\n<pre><code>├── fmt.dir.go\n│ ├── fmt.file.go\n</code></pre>\n\n<p><code>fmt.dir.go</code> and <code>fmt.file.go</code> will be appended to the <code>files</code> list and <code>fmt.file.go</code> will be formatted twice, once as a member of directory <code>fmt.dir.go</code> and once as <code>file fmt.file.go</code>.</p>\n\n<p>Read the documentation for the Go <code>testing</code> package.</p>\n\n<p>Write a Go <code>testing</code> package function.</p>\n\n<pre><code>// TestGoFormatting checks that Go source files have been formatted.\nfunc TestGoFormatting(t *testing.T) {\n // TODO: Set root to a variable value?\n root := \"../..\"\n out, err := checkGoFmt(root)\n if err != nil {\n t.Error(err)\n }\n if len(out) &gt; 0 {\n t.Error(out)\n }\n}\n</code></pre>\n\n<p>The Go <code>testing</code> package prints the test function name, <code>TestGoFormatting</code>, on failure, There is no need for redundant logging of a test title. <code>TestGoFormatting</code> is more meaningful than <code>TestFormatting</code>. The <code>testing</code> package <code>T.Error</code> method merges the <code>T.Log</code> and <code>T.Fail</code> methods. Eliminate redundant argument <code>error.Error()</code> methods.</p>\n\n<p>Obtaining a value for <code>root</code> requires more thought.</p>\n\n<p>We can also write a program <code>main</code> function.</p>\n\n<pre><code>func main() {\n exit := 0\n // TODO: Set root to a variable value?\n root := \"../..\"\n out, err := checkGoFmt(root)\n if err != nil {\n exit = 2\n fmt.Fprintln(os.Stderr, err)\n }\n if len(out) &gt; 0 {\n exit = 2\n fmt.Fprintln(os.Stderr, out)\n }\n os.Exit(exit)\n}\n</code></pre>\n\n<p>And so on.</p>\n\n<p>In Go, don't ignore errors.</p>\n\n<hr>\n\n<p>Here is the complete code for a first draft of <code>TestGoFormatting</code>, a <code>testing</code> function:</p>\n\n<pre><code>package pack\n\nimport (\n \"os\"\n \"os/exec\"\n \"path/filepath\"\n \"testing\"\n)\n\nfunc goFiles(root string) ([]string, error) {\n var files []string\n\n err := filepath.Walk(root, func(path string, info os.FileInfo, err error) error {\n if err != nil {\n return err\n }\n if info == nil {\n return nil\n }\n if !info.Mode().IsRegular() {\n return nil\n }\n if filepath.Ext(path) != \".go\" {\n return nil\n }\n absPath, e := filepath.Abs(path)\n if e != nil {\n return e\n }\n files = append(files, absPath)\n return nil\n })\n if err != nil {\n return nil, err\n }\n\n return files, nil\n}\n\n// checkGoFmt checks that Go source files have been formatted with go fmt or gofmt.\n// checkGoFmt returns a newline separated list of files\n// whose formatting differs from gofmt's and any error.\nfunc checkGoFmt(root string) (string, error) {\n // Command gofmt\n // https://golang.org/cmd/gofmt/\n // $ gofmt -help\n // usage: gofmt [flags] [path ...]\n // -l list files whose formatting differs from gofmt's\n // $\n\n files, err := goFiles(root)\n if err != nil {\n return \"\", err\n }\n if len(files) == 0 {\n return \"\", nil\n }\n\n args := make([]string, 0, 1+len(files))\n args = append(args, \"-l\")\n args = append(args, files...)\n out, err := exec.Command(\"gofmt\", args...).Output()\n return string(out), err\n}\n\n// TestGoFormatting checks that Go source files have been formatted.\nfunc TestGoFormatting(t *testing.T) {\n // TODO: Set root to a variable value?\n root := \"../..\"\n out, err := checkGoFmt(root)\n if err != nil {\n t.Error(err)\n }\n if len(out) &gt; 0 {\n t.Error(out)\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-14T20:31:55.603", "Id": "232406", "ParentId": "232166", "Score": "5" } } ]
{ "AcceptedAnswerId": "232406", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-10T22:57:55.627", "Id": "232166", "Score": "7", "Tags": [ "unit-testing", "formatting", "go" ], "Title": "Writing a test to validate that the repo is formatted" }
232166
<p>I want to use an <code>std::array</code>, but am operating on sufficiently large arrays that stack allocation is not reasonable (and fails using default stack size). I also needed a function that performed much like <code>std::transform</code>, but always in-place. The issue is that many of these transformations change the "type". All of these types, in my usage, are simply the same templated type with different non-type template arguments associated with them. I don't want to have many arrays allocated to move data through the system because these type changes, only when a copy is strictly necessary.</p> <p>To that end, I wrote a pretty crappy implementation of both by wrapping <code>std::unique_ptr</code> and <code>std::array</code>.</p> <pre class="lang-cpp prettyprint-override"><code>template &lt;typename T, size_t SZ, typename Deleter = std::default_delete&lt;T&gt;&gt; class unique_heap_array { private: // members std::unique_ptr&lt;std::array&lt;T, SZ&gt;&gt; p {nullptr}; public: // pointer member types using deleter_type = typename decltype(p)::deleter_type; using element_type = typename decltype(p)::element_type; using element_pointer_type = typename decltype(p)::pointer; public: // array member types using value_type = typename element_type::value_type; using size_type = typename element_type::size_type; using difference_type = typename element_type::difference_type; using reference = typename element_type::reference; using const_reference = typename element_type::const_reference; using pointer = typename element_type::pointer; using const_pointer = typename element_type::const_pointer; using iterator = typename element_type::iterator; using const_iterator = typename element_type::const_iterator; using reverse_iterator = typename element_type::reverse_iterator; using const_reverse_iterator = typename element_type::const_reverse_iterator; public: // pointer member function auto get_deleter() const noexcept { return p.get_deleter(); } explicit operator bool() const noexcept { return p; } auto borrow_ptr() const noexcept { return p.get(); } auto release_ptr() noexcept { return p.release(); } void reset_ptr(element_pointer_type ptr) noexcept { p.reset(ptr); } void reset_ptr(std::nullptr_t ptr) noexcept { p.reset(ptr); } void reset_ptr() noexcept { p.reset(new element_type); } void swap(unique_heap_array&amp; other) noexcept { p.swap(other.p); } public: // array members functions auto at(size_type i) { return p-&gt;at(i); } auto at(size_type i) const { return p-&gt;at(i); } auto operator[](size_type i) { return (*p)[i]; } auto operator[](size_type i) const { return (*p)[i]; } auto begin() { return p-&gt;begin(); } auto begin() const { return p-&gt;begin(); } auto cbegin() const { return p-&gt;cbegin(); } auto end() { return p-&gt;end(); } auto end() const { return p-&gt;end(); } auto cend() const { return p-&gt;cend(); } auto rbegin() { return p-&gt;rbegin(); } auto rbegin() const { return p-&gt;rbegin(); } auto crbegin() const { return p-&gt;crbegin(); } auto rend() { return p-&gt;rend(); } auto rend() const { return p-&gt;rend(); } auto crend() const { return p-&gt;crend(); } auto data() const { return p-&gt;data(); } constexpr bool empty() const noexcept { return SZ == 0; } constexpr auto size() const noexcept { return SZ; } constexpr auto max_size() const noexcept { return SZ; } void fill(const T&amp; value) { p-&gt;fill(value); } public: // constructors unique_heap_array() { reset_ptr(); } unique_heap_array(std::nullptr_t) { } unique_heap_array(element_pointer_type ptr) { reset_ptr(ptr); } public: // copy and move constructiona and assignment unique_heap_array(const unique_heap_array&lt;T, SZ, Deleter&gt;&amp;) = delete; unique_heap_array(unique_heap_array&lt;T, SZ, Deleter&gt;&amp;&amp;) = default; unique_heap_array&lt;T, SZ, Deleter&gt;&amp; operator=(const unique_heap_array&lt;T, SZ, Deleter&gt;&amp;) = delete; unique_heap_array&lt;T, SZ, Deleter&gt;&amp; operator=(unique_heap_array&lt;T, SZ, Deleter&gt;&amp;&amp;) = default; public: // destructor ~unique_heap_array() = default; public: // inplace data and type transformation template &lt;typename O, typename OutTypeDeleter = std::default_delete&lt;O&gt;, typename F&gt; auto transform(F&amp;&amp; func) { static_assert((sizeof(O) == sizeof(T)) &amp;&amp; (alignof(O) &lt;= alignof(T)), "input and output types are not compatible"); auto res = unique_heap_array&lt;O, SZ, OutTypeDeleter&gt;(reinterpret_cast&lt;std::array&lt;O, SZ&gt;*&gt;(borrow_ptr())); std::transform(begin(), end(), res.begin(), func); release_ptr(); return res; } template &lt;typename O, typename OutTypeDeleter = std::default_delete&lt;O&gt;, typename F, typename T2, typename Deleter2&gt; auto transform(F&amp;&amp; func, const unique_heap_array&lt;T2, SZ, Deleter2&gt;&amp; other) { static_assert((sizeof(O) == sizeof(T)) &amp;&amp; (alignof(O) &lt;= alignof(T)), "input and output types are not compatible"); auto res = unique_heap_array&lt;O, SZ, OutTypeDeleter&gt;(reinterpret_cast&lt;std::array&lt;O, SZ&gt;*&gt;(borrow_ptr())); std::transform(begin(), end(), other.begin(), res.begin(), func); release_ptr(); return res; } }; template &lt;typename T, size_t SZ, typename Deleter&gt; bool operator==(const unique_heap_array&lt;T, SZ, Deleter&gt;&amp; a, const unique_heap_array&lt;T, SZ, Deleter&gt;&amp; b) { return *a.borrow_ptr() == *b.borrow_ptr(); } template &lt;typename T, size_t SZ, typename Deleter&gt; bool operator!=(const unique_heap_array&lt;T, SZ, Deleter&gt;&amp; a, const unique_heap_array&lt;T, SZ, Deleter&gt;&amp; b) { return *a.borrow_ptr() != *b.borrow_ptr(); } template &lt;typename T, size_t SZ, typename Deleter&gt; bool operator&lt;(const unique_heap_array&lt;T, SZ, Deleter&gt;&amp; a, const unique_heap_array&lt;T, SZ, Deleter&gt;&amp; b) { return *a.borrow_ptr() &lt; *b.borrow_ptr(); } template &lt;typename T, size_t SZ, typename Deleter&gt; bool operator&lt;=(const unique_heap_array&lt;T, SZ, Deleter&gt;&amp; a, const unique_heap_array&lt;T, SZ, Deleter&gt;&amp; b) { return *a.borrow_ptr() &lt;= *b.borrow_ptr(); } template &lt;typename T, size_t SZ, typename Deleter&gt; bool operator&gt;(const unique_heap_array&lt;T, SZ, Deleter&gt;&amp; a, const unique_heap_array&lt;T, SZ, Deleter&gt;&amp; b) { return *a.borrow_ptr() &gt; *b.borrow_ptr(); } template &lt;typename T, size_t SZ, typename Deleter&gt; bool operator&gt;=(const unique_heap_array&lt;T, SZ, Deleter&gt;&amp; a, const unique_heap_array&lt;T, SZ, Deleter&gt;&amp; b) { return *a.borrow_ptr() &gt;= *b.borrow_ptr(); } template &lt;std::size_t i, typename T, size_t SZ, typename Deleter&gt; auto get(unique_heap_array&lt;T, SZ, Deleter&gt;&amp; p) { return std::get&lt;i&gt;(*p.borrow_ptr()); } template &lt;std::size_t i, typename T, size_t SZ, typename Deleter&gt; auto get(const unique_heap_array&lt;T, SZ, Deleter&gt;&amp; p) { return std::get&lt;i&gt;(*p.borrow_ptr()); } </code></pre> <p>The transform function works by reinterpreting the array as the output type, performing an <code>std::transform</code> on the array in-place, then invalidating the input pointer afterward, returning the output type array created from the stolen pointer.</p> <p>Example usage using similar types:</p> <pre class="lang-cpp prettyprint-override"><code>#include &lt;cstdint&gt; template &lt;int FracSize_&gt; struct FixedFractional { static constexpr auto FracSize = FracSize_; int64_t value; }; template &lt;int OutFracSize, int InFracSize&gt; FixedFractional&lt;OutFracSize&gt; resize(FixedFractional&lt;InFracSize&gt; a) { if (InFracSize &lt; OutFracSize) { return {a.value &lt;&lt; (OutFracSize - InFracSize)}; } else { return {a.value &gt;&gt; (InFracSize - OutFracSize)}; } } template &lt;int AFracSize, int BFracSize&gt; auto operator+ (FixedFractional&lt;AFracSize&gt; a, FixedFractional&lt;BFracSize&gt; b) { constexpr auto ResFracSize = std::max(AFracSize, BFracSize); auto resVal = resize&lt;ResFracSize&gt;(a).value + resize&lt;ResFracSize&gt;(b).value; return FixedFractional&lt;ResFracSize&gt; {resVal}; } int main() { auto a = unique_heap_array&lt;FixedFractional&lt;6&gt;, 100'000&gt;(); auto unaryXfer = [](decltype(a[0]) t) { return resize&lt;4&gt;(t); }; auto b = a.transform&lt;decltype(unaryXfer(a[0]))&gt;(unaryXfer); // a is released, further usage is a seg fault // b uses a's memory where it stores the resized integers from a auto c = unique_heap_array&lt;FixedFractional&lt;12&gt;, 100'000&gt;(); auto binaryXfer = [](decltype(c[0]) t, decltype(b[0]) v) { return t + v; }; auto d = c.transform&lt;FixedFractional&lt;decltype(binaryXfer(c[0], b[0]))::FracSize&gt;&gt;(binaryXfer, b); // c is now released // d uses c's memory to store the piecewise addition of b and c } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-11T03:49:12.200", "Id": "453211", "Score": "0", "body": "Can you include an example type transformation? I suspect the best option may be to adjust your types and then use a vector." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-11T04:14:51.310", "Id": "453212", "Score": "0", "body": "The types cannot be \"adjusted\" without moving the bounds to runtime which completely trashes performance. And correct me if I'm wrong, `std::vector` code won't generate SIMD instructions due to the runtime size. Performance is a **REQUIREMENT**, hence the effort." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-11T05:03:14.047", "Id": "453213", "Score": "0", "body": "The compiler can generate SIMD on a vector. https://godbolt.org/z/75C5xS. You could also consider std::valarray" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-11T15:32:50.287", "Id": "453257", "Score": "0", "body": "The variable `s` in the example is not defined within the scope of the example and possibly makes this question off-topic due to `Lack of Concrete Context`. Instead of the 2 line example could you provide a test case that actually runs?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-11T22:03:08.107", "Id": "453333", "Score": "0", "body": "Thanks for posting an example. Are you sure you need to store the FracSize as a static member of each fraction? Why not store it (possibly as a static contexpr member) of the array type?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-11T23:39:17.537", "Id": "453341", "Score": "0", "body": "The `FixedFractional` type is meant to also be used in the singular context as well, so it's a matter of DRY. And associating the size with the array means that I've lost a potential generic container. You could make an array *specifically* for this family of \"types\", but it seems like it's more effort and less generic." } ]
[ { "body": "<p>These are wrong. It doesn't make sense for operators on the array to succeed if the pointer is null. I would remove the <code>constexpr</code> and <code>noexcept</code> from the first three and access the array's member functions through the pointer so that it will segfault.</p>\n\n<pre><code> constexpr bool empty() const noexcept { return SZ == 0; }\n constexpr auto size() const noexcept { return SZ; }\n constexpr auto max_size() const noexcept { return SZ; }\n</code></pre>\n\n<p>The <code>noexcept</code> in this is wrong, all allocation can throw.</p>\n\n<pre class=\"lang-cpp prettyprint-override\"><code> void reset_ptr() noexcept { p.reset(new element_type); }\n</code></pre>\n\n<p>These constructors could be <code>noexcept</code>.</p>\n\n<pre class=\"lang-cpp prettyprint-override\"><code> unique_heap_array(std::nullptr_t) { }\n unique_heap_array(element_pointer_type ptr) { reset_ptr(ptr); }\n</code></pre>\n\n<p>If you remove the <code>Deleter</code> parameter so that you don't have to potentially feed it to <code>transform</code>, you can deduce the output type and not have to require the user to determine the output type. You could probably find a way to support the deleter, but it's rarely used and even if defaulted you would still have to call it with the empty argument list <code>transform&lt;&gt;(...)</code>, which some people find annoying. I would remove <code>Deleter</code> entirely from the class and the <code>get_deleter</code> method as well.</p>\n\n<pre class=\"lang-cpp prettyprint-override\"><code> template &lt;typename F&gt;\n auto transform(F&amp;&amp; func)\n {\n using O = decltype(func((*this)[0]));\n static_assert((sizeof(O) == sizeof(T)) &amp;&amp;\n (alignof(O) &lt;= alignof(T)),\n \"input and output types are not compatible\");\n auto res = unique_heap_array&lt;O, SZ&gt;(reinterpret_cast&lt;std::array&lt;O, SZ&gt;*&gt;(borrow_ptr()));\n std::transform(begin(), end(), res.begin(), func);\n release_ptr();\n return res;\n }\n template &lt;typename F, typename T2&gt;\n auto transform(F&amp;&amp; func, const unique_heap_array&lt;T2, SZ&gt;&amp; other)\n {\n using O = decltype(func((*this)[0], other[0]));\n static_assert((sizeof(O) == sizeof(T)) &amp;&amp;\n (alignof(O) &lt;= alignof(T)),\n \"input and output types are not compatible\");\n auto res = unique_heap_array&lt;O, SZ&gt;(reinterpret_cast&lt;std::array&lt;O, SZ&gt;*&gt;(borrow_ptr()));\n std::transform(begin(), end(), other.begin(), res.begin(), func);\n release_ptr();\n return res;\n }\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-12T00:05:59.470", "Id": "232219", "ParentId": "232168", "Score": "0" } }, { "body": "<p>Now for something completely different!</p>\n\n<p>I re-analyzed my problem and determined that I didn't really need to implement the above data structure. How my program works is that I have many modules (that change) that are connected together to perform operations on large arrays of data. Ideally, I want minimal memory usage for both performance and scalability, so I must reuse memory allocations in my calculations to store the temporary calculations that get sent from module to module, copying only when necessary.</p>\n\n<p>The best solution to this problem is to allocate all the memory up front and give ownership of it to an entity that sits above all the modules that shuffles the data through the system. As the system runs through an iteration of data processing it gives <em>handles</em> to the memory locations it allocated to each of the modules for I/O. These handles claim no ownership. The handles can be initialized with a borrowed pointer, and then later invalidated in a call to <code>transform</code>. And only one \"view\" of the memory space should exist at a time, seeing as each view could be as a different type.</p>\n\n<p>I found this example of a non-owning observer smart pointer written by Howard Hinnant in <a href=\"http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2013/n3514.pdf\" rel=\"nofollow noreferrer\">this proposal</a>. They went on to modify it to add copy semantics, but the original implementation serves my purposes better.</p>\n\n<pre class=\"lang-cpp prettyprint-override\"><code>struct no_delete {\n template &lt;typename T&gt;\n void operator() (T*) {}\n};\n\ntemplate &lt;typename T&gt;\nusing unique_handle = std::unique_ptr&lt;T, no_delete&gt;;\n\ntemplate &lt;typename T&gt;\nauto get_handle_to(T&amp; a) {\n return unique_handle&lt;T&gt;(&amp;a);\n}\n</code></pre>\n\n<p>Transform can be as follows.</p>\n\n<pre class=\"lang-cpp prettyprint-override\"><code>template &lt;typename I, size_t SZ, typename F&gt;\nauto transform(unique_handle&lt;std::array&lt;I, SZ&gt;&gt;&amp; in, F&amp;&amp; func)\n{\n using O = decltype(func((*in)[0]));\n auto out = unique_handle&lt;std::array&lt;O, SZ&gt;&gt;(reinterpret_cast&lt;std::array&lt;O, SZ&gt;*&gt;(in.get()));\n std::transform(in-&gt;begin(), in-&gt;end(), out-&gt;begin(), func);\n in.release();\n return out;\n}\n\ntemplate &lt;typename I, size_t SZ, typename I2, typename F&gt;\nauto transform(unique_handle&lt;std::array&lt;I, SZ&gt;&gt;&amp; in, const unique_handle&lt;std::array&lt;I2, SZ&gt;&gt;&amp; in2, F&amp;&amp; func)\n{\n using O = decltype(func((*in)[0], (*in2)[0]));\n auto out = unique_handle&lt;std::array&lt;O, SZ&gt;&gt;(reinterpret_cast&lt;std::array&lt;O, SZ&gt;*&gt;(in.get()));\n std::transform(in-&gt;begin(), in-&gt;end(), in2-&gt;begin(), out-&gt;begin(), func);\n in.release();\n return out;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-19T04:23:00.220", "Id": "232623", "ParentId": "232168", "Score": "0" } } ]
{ "AcceptedAnswerId": "232623", "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-11T02:36:54.493", "Id": "232168", "Score": "6", "Tags": [ "c++", "performance", "array" ], "Title": "Heap-allocated fixed size array with memory-reusing type transformation function" }
232168
<p>I would appreciate any review of the following script I recently posted on <a href="https://github.com/AndreiBorac/gitcrypto" rel="nofollow noreferrer">GitHub (gitcrypto)</a>. Most notably, I would be interested in a review of the cryptographic aspects (I am not an expert in this field):</p> <ul> <li><p>Is there a way to break the encryption from the files in the "export" directory alone without knowing the passphrase?</p></li> <li><p>Is there a way to tamper with an "export" directory? I.e., without necessarily being able to decrypt, is there a way to meddle with files besides the evident (truncation, or causing an error).</p></li> <li><p>Are there any other tricks that can be pulled?</p></li> </ul> <pre><code>#!/usr/bin/env bash # -*- mode: ruby; -*- # copyright (c) 2019 by Andrei Borac # released under the MIT license, for details see the LICENSE file # the header below is valid bash script as well as valid Ruby code NIL2=\ =begin exec env -i PATH="$(echo /{usr/{local/,},}{s,}bin | tr ' ' ':')" DBUS_SESSION_BUS_ADDRESS="$DBUS_SESSION_BUS_ADDRESS" ruby -E BINARY:BINARY -I . -e 'load("'"$0"'");' -- "$@" =end nil; require("open3"); require("digest"); require("openssl"); # generally aiming for 128-bit equivalent security # 8192-bit prime from https://tools.ietf.org/html/rfc3526 G=2 P=" FFFFFFFF FFFFFFFF C90FDAA2 2168C234 C4C6628B 80DC1CD1 29024E08 8A67CC74 020BBEA6 3B139B22 514A0879 8E3404DD EF9519B3 CD3A431B 302B0A6D F25F1437 4FE1356D 6D51C245 E485B576 625E7EC6 F44C42E9 A637ED6B 0BFF5CB6 F406B7ED EE386BFB 5A899FA5 AE9F2411 7C4B1FE6 49286651 ECE45B3D C2007CB8 A163BF05 98DA4836 1C55D39A 69163FA8 FD24CF5F 83655D23 DCA3AD96 1C62F356 208552BB 9ED52907 7096966D 670C354E 4ABC9804 F1746C08 CA18217C 32905E46 2E36CE3B E39E772C 180E8603 9B2783A2 EC07A28F B5C55DF0 6F4C52C9 DE2BCBF6 95581718 3995497C EA956AE5 15D22618 98FA0510 15728E5A 8AAAC42D AD33170D 04507A33 A85521AB DF1CBA64 ECFB8504 58DBEF0A 8AEA7157 5D060C7D B3970F85 A6E1E4C7 ABF5AE8C DB0933D7 1E8C94E0 4A25619D CEE3D226 1AD2EE6B F12FFA06 D98A0864 D8760273 3EC86A64 521F2B18 177B200C BBE11757 7A615D6C 770988C0 BAD946E2 08E24FA0 74E5AB31 43DB5BFC E0FD108E 4B82D120 A9210801 1A723C12 A787E6D7 88719A10 BDBA5B26 99C32718 6AF4E23C 1A946834 B6150BDA 2583E9CA 2AD44CE8 DBBBC2DB 04DE8EF9 2E8EFC14 1FBECAA6 287C5947 4E6BC05D 99B2964F A090C3A2 233BA186 515BE7ED 1F612970 CEE2D7AF B81BDD76 2170481C D0069127 D5B05AA9 93B4EA98 8D8FDDC1 86FFB7DC 90A6C08F 4DF435C9 34028492 36C3FAB4 D27C7026 C1D4DCB2 602646DE C9751E76 3DBA37BD F8FF9406 AD9E530E E5DB382F 413001AE B06A53ED 9027D831 179727B0 865A8918 DA3EDBEB CF9B14ED 44CE6CBA CED4BB1B DB7F1447 E6CC254B 33205151 2BD7AF42 6FB8F401 378CD2BF 5983CA01 C64B92EC F032EA15 D1721D03 F482D7CE 6E74FEF6 D55E702F 46980C82 B5A84031 900B1C9E 59E7C97F BEC7E8F3 23A97A7E 36CC88BE 0F1D45B7 FF585AC5 4BD407B2 2B4154AA CC8F6D7E BF48E1D8 14CC5ED2 0F8037E0 A79715EE F29BE328 06A1D58B B7C5DA76 F550AA3D 8A1FBFF0 EB19CCB1 A313D55C DA56C9EC 2EF29632 387FE8D7 6E3C0468 043E8F66 3F4860EE 12BF2D5B 0B7474D6 E694F91E 6DBE1159 74A3926F 12FEE5E4 38777CB6 A932DF8C D8BEC4D0 73B931BA 3BC832B6 8D9DD300 741FA7BF 8AFC47ED 2576F693 6BA42466 3AAB639C 5AE4F568 3423B474 2BF1C978 238F16CB E39D652D E3FDB8BE FC848AD9 22222E04 A4037C07 13EB57A8 1A23F0C7 3473FC64 6CEA306B 4BCBC886 2F8385DD FA9D4B7F A2C087E8 79683303 ED5BDD3A 062B3CF5 B3A278A6 6D2A13F8 3F44F82D DF310EE0 74AB6A36 4597E899 A0255DC1 64F31CC5 0846851D F9AB4819 5DED7EA1 B1D510BD 7EE74D73 FAF36BC3 1ECFA268 359046F4 EB879F92 4009438B 481C6CD7 889A002E D5EE382B C9190DA6 FC026E47 9558E447 5677E9AA 9E3050E2 765694DF C81F56E8 80B96E71 60C980DD 98EDD3DF FFFFFFFF FFFFFFFF".split.join.to_i(16); def itobig(x) out = []; while (x &gt; 0) out &lt;&lt; (x % 256); x /= 256; end return out.map{|x| x.chr; }.reverse.join; end def bigtoi(str) return str.bytes.inject(0){|s, i| ((s &lt;&lt; 8) + i); }; end def drygest(data) return bigtoi(Digest::SHA256.digest(data)); end def kdf(phrase) out = Digest::SHA256.digest(phrase); 1000000.times{ out = Digest::SHA256.digest((phrase + out)); }; return bigtoi(out); end def pinentry() stdout, stderr, status, = Open3.capture3("bash", "-c", "set -o xtrace ; ( echo GETPIN ; echo BYE ) | pinentry-gnome3"); raise if (!(status.success?)); raise if (!(stdout.lines.length == 4)); raise if (!(stdout.lines[0] == "OK Pleased to meet you\n")); raise if (!(stdout.lines[1][0..1] == "D ")); raise if (!(stdout.lines[1][-1] == "\n")); raise if (!(stdout.lines[2] == "OK\n")); return stdout.lines[1][2..-2]; end COMMON_FUNCTIONS = ' set -o xtrace set -o errexit set -o nounset set -o pipefail function target() { mkdir -p ./.gitcrypto/tmp if sudo mountpoint -q ./.gitcrypto/tmp then if [ "${1-}" == "fresh" ] then sudo umount ./.gitcrypto/tmp if sudo mountpoint -q ./.gitcrypto/tmp then exit 1 fi sudo mount -t tmpfs none ./.gitcrypto/tmp fi else sudo mount -t tmpfs none ./.gitcrypto/tmp fi mkdir -p ./.gitcrypto/tmp/{bundle,review,export,rescue} } function git_repack_all() { fn=./.VOY2EnPHzhKUQb8z git cat-file --batch-check --batch-all-objects | egrep -o "^[0-9a-f]{40}" &gt;"$fn" mkdir -p ./.git/objects/newpack cat "$fn" | git pack-objects ./.git/objects/newpack/pack rm -f "$fn" rm -f ./.git/objects/pack/pack-* mv ./.git/objects/newpack/* ./.git/objects/pack/ rmdir ./.git/objects/newpack } function recover_to_from() { to="$1" from="$2" ( cd "$to" git init lastref= i=1000000000 while [ -f "$from"/"$i".bundle ] do lastref="$(git bundle unbundle "$from"/"$i".bundle | cut -d " " -f 1)" git tag -f gitcrypto-focal-point "$lastref" if [ "$(( (i % 1000) ))" == "0" ] then git_repack_all fi i="$(( (i+1) ))" done git tag -d gitcrypto-focal-point || true if [ "$lastref" != "" ] then git branch master "$lastref" git_repack_all fi ) } ' def main() if (ARGV[0] == "keygen") raise if (!(system("bash", "-c", COMMON_FUNCTIONS + ' [ -d ./.git ] mkdir -p ./.gitcrypto/cfg '))); phrase = pinentry; a = kdf(phrase); ga = G.to_bn.mod_exp(a, P).to_i; IO.write("./.gitcrypto/cfg/pubkey", itobig(ga)); end if (ARGV[0] == "trykey") phrase = pinentry; a = kdf(phrase); ga = G.to_bn.mod_exp(a, P).to_i; raise if (!(ga == bigtoi(IO.read("./.gitcrypto/cfg/pubkey")))); end if (ARGV[0] == "backup") raise if (!(system("bash", "-c", COMMON_FUNCTIONS + ' [ -d ./.git ] ORIGINAL_HEAD_HASH="$(git rev-parse --verify HEAD)" target fresh function emit_parents() { git cat-file -p "$1" |\ ( parents=() cparents=() while read line do if [ "${line:0:7}" == "parent " ] then parents+=("${line:7}") cparents+=("^${line:7}") fi if [ "${line:0:7}" == "author " ] then break fi done cat &gt;/dev/null declare -p parents declare -p cparents ) } git log --full-history --date-order --reverse --format=format:"%H"$'"'"'\n'"'"' | sed -e '"'"'/^$/d'"'"' |\ ( i=1000000000 while read hash do eval "$(emit_parents "$hash")" git tag -f gitcrypto-focal-point "$hash" git bundle create ./.gitcrypto/tmp/bundle/"$i".bundle gitcrypto-focal-point "${cparents[@]}" i="$(( (i+1) ))" done git tag -d gitcrypto-focal-point || true ) recover_to_from ./.gitcrypto/tmp/review ./../bundle RESTORE_HEAD_HASH="$(git rev-parse --verify HEAD)" [ "$RESTORE_HEAD_HASH" == "$ORIGINAL_HEAD_HASH" ] '))); $stderr.puts("encrypting ..."); ga = bigtoi(IO.read("./.gitcrypto/cfg/pubkey")); 1.times{ i = 1000000000; fn = nil; while (File.exists?((fn = "./.gitcrypto/tmp/bundle/#{i}.bundle"))) $stderr.puts("i=#{i}"); payload = IO.read(fn); b = drygest(payload); gb = G.to_bn.mod_exp(b, P).to_i; IO.write("./.gitcrypto/tmp/export/#{i}.key", itobig(gb)); sym = Digest::SHA256.digest(itobig(ga.to_bn.mod_exp(b, P).to_i)); cipher = OpenSSL::Cipher.new("aes-256-ctr"); cipher.encrypt; cipher.iv = "0"*16; cipher.key = sym; IO.write("./.gitcrypto/tmp/export/#{i}.enc", (cipher.update(payload) + cipher.final)); i += 1; end }; $stderr.puts("encrypted"); end if (ARGV[0] == "rescue") raise if (!(system("bash", "-c", COMMON_FUNCTIONS + ' target preserve [ ! -d ./.git ] '))); $stderr.puts("decrypting ..."); phrase = pinentry; a = kdf(phrase); 1.times{ i = 1000000000; fnk = nil; fne = nil; while (File.exists?((fnk = (ARGV[1] + "/#{i}.key"))) &amp;&amp; File.exists?((fne = (ARGV[1] + "/#{i}.enc")))) $stderr.puts("i=#{i}"); gb = bigtoi(IO.read(fnk)); sym = Digest::SHA256.digest(itobig(gb.to_bn.mod_exp(a, P).to_i)); cipher = OpenSSL::Cipher.new("aes-256-ctr"); cipher.decrypt; cipher.iv = "0"*16; cipher.key = sym; payload = (cipher.update(IO.read(fne)) + cipher.final); b = drygest(payload); gb2 = G.to_bn.mod_exp(b, P).to_i; raise if (!(gb2 == gb)); IO.write("./.gitcrypto/tmp/rescue/#{i}.bundle", payload); i += 1; end }; $stderr.puts("decrypted"); raise if (!(system("bash", "-c", COMMON_FUNCTIONS + ' recover_to_from . ./.gitcrypto/tmp/rescue '))); end end main; puts("+OK (gitcrypto.rb)"); </code></pre>
[]
[ { "body": "<p>Generally you'd expect a protocol specification, not just code. The protocol should also have a security section with the security claims and how those are reached.</p>\n\n<p>The protocol is a password based hybrid cryptosystem using a DL based derivation of a symmetric key.</p>\n\n<p>Non standard PBKDF, no salt, large iteration count. Unfortunately I don't see any way of updating the iteration count or any versioning.</p>\n\n<pre><code>def kdf(phrase)\n out = Digest::SHA256.digest(phrase);\n\n 1000000.times{\n out = Digest::SHA256.digest((phrase + out));\n };\n\n return bigtoi(out);\nend\n</code></pre>\n\n<p>Non-statically sized output. Not a huge problem, but non-standard.</p>\n\n<pre><code>def itobig(x)\n out = [];\n\n while (x &gt; 0)\n out &lt;&lt; (x % 256);\n x /= 256;\n end\n\n return out.map{|x| x.chr; }.reverse.join;\nend\n</code></pre>\n\n<p>This is probably a typo, what's a <code>drygest</code>?</p>\n\n<pre><code>def drygest(data)\n return bigtoi(Digest::SHA256.digest(data));\nend\n</code></pre>\n\n<p>Here the iv is not used because of the uniqueness of <code>gb</code> it seems, which makes the symmetric key unique. This is deterministic encryption, which means that files with the same contents and same password will be easily recognizable.</p>\n\n<pre><code>cipher = OpenSSL::Cipher.new(\"aes-256-ctr\");\ncipher.decrypt;\ncipher.iv = \"0\"*16;\ncipher.key = sym;\n</code></pre>\n\n<p>Otherwise CTR doesn't contain any method of verifying if the file has changed. It allows any bit of the file to be flipped at the discretion of an attacker. This is especially an issue in source files where a 0 / false can be easily turned into a 1 / true. This seems to be caught by the comparison of the stored <code>gb</code> with a calculated version of it <code>gb2</code>, however those values seem to be derived from the hash over the data and the public key, neither of which are secret. The payload is only written after the verification is complete and a raise is called if the decryption fails. There is no specific error message returned though.</p>\n\n<p>As everything is deterministic, the output value of <code>gb</code> is also deterministic. This makes it even easier to detect dupes.</p>\n\n<p>As I don't see any specific inclusion of the file name into the encryption scheme it does mean that encrypted files can be replaced by other encrypted files, even if they would be signed.</p>\n\n<hr>\n\n<p>All in all an interesting effort, I wish I could call it secure. Using a standardized, hybrid cryptosystem and some kind of signature generation / verification would be more secure though.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-29T22:18:28.847", "Id": "238171", "ParentId": "232169", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-11T03:22:07.357", "Id": "232169", "Score": "7", "Tags": [ "ruby", "cryptography", "git" ], "Title": "Incremental, encrypted backups for git" }
232169
<p>Here is an attempt to leverage Java's BigInteger class to implement the RSA algorithm, as well as md5 and sha512 hashing functions to generate keys for what I hope to be strong cryptography. My prayer is that some of my ideas are novel and not just wrong.</p> <ul> <li><strong>This is a test, this is only a test.</strong> 'Keys' are generated, the message is encrypted, displayed, decrypted, displayed, and all tossed out with the bathwater.</li> <li><strong>This implementation ignores salting.</strong> I suppose my thought here is that computational complexity (time) and memory requirements for a large enough key would dissuade an adversary from successfully utilizing a rainbow table.</li> <li><strong>I understand using a sieve of Eratosthenes to pick out a value for e is overkill,</strong> expensive, and could be functionally reproduced here by taking a pseudo-random number and finding <code>nextProbablePrime()</code>. I've included it hoping to get feedback on this implementation.</li> <li><strong>I am a total novice.</strong> I was a New Media major. I want to learn. I humbly request any time and thoughts you wish to impart. Running time is ~1m; half due to the sieve, half for the 1000 iterations of <code>nextProbablyPrime()</code>. </li> </ul> <p><strong>RSATest.java</strong>: (Usage: java RSATest "some password" "some message")</p> <pre><code>import java.math.BigInteger; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; public class RSATest { //seive array for lower 2b primes public static byte[] a = new byte[(Integer.MAX_VALUE/20)+1]; public static BigInteger p=BigInteger.ONE,q=BigInteger.ONE,t; public static MessageDigest sha,md5; public static int lp = 3; // last prime sieved //method returns prime number after hash with given digest public static BigInteger h(byte[] ba, MessageDigest md){ BigInteger t=(new BigInteger(md.digest(ba))).abs().nextProbablePrime(); md.update(t.toByteArray()); return t; } public static void main(String[] args) { BigInteger e,n,t,d,sec,cy,dec; byte[] a,ar; String secret; int itr, itr2; //itr: iterations if(args.length!=2){ System.out.println("HELP - parameters: \"password\" \"message\""); System.exit(1); } secret=args[1]; //TODO: reject palindromes? a=args[0].getBytes(); ar = (new StringBuilder(args[0])).reverse().toString().getBytes(); //init sha and md5 digest methods with string try { sha = MessageDigest.getInstance("SHA-512"); sha.update(a); md5 = MessageDigest.getInstance("MD5"); md5.update(a); } catch (NoSuchAlgorithmException ex) { ex.printStackTrace(); System.exit(0); } //generate primes from hash of string and its reverse p=p.multiply(h(a,sha)).nextProbablePrime(); p=p.multiply(h(a,md5)).nextProbablePrime(); p=p.multiply(h(ar,sha)).nextProbablePrime(); p=p.multiply(h(ar,md5)).nextProbablePrime(); sha.update(p.toByteArray()); md5.update(p.toByteArray()); q=q.multiply(h(ar,sha)).nextProbablePrime(); q=q.multiply(h(ar,md5)).nextProbablePrime(); sha.update(q.toByteArray()); md5.update(q.toByteArray()); q=q.multiply(h(a,sha)).nextProbablePrime(); q=q.multiply(h(a,md5)).nextProbablePrime(); //increase computational time and ensure primality of p/q itr = p.mod(BigInteger.valueOf(1000)).intValue(); itr2 = 1000-itr; for(int i = 1;i&lt;itr;i++)p=p.nextProbablePrime(); for(int x = 1;x&lt;itr2;x++)q=q.nextProbablePrime(); while(!p.isProbablePrime(Integer.MAX_VALUE))p=p.nextProbablePrime(); while(!q.isProbablePrime(Integer.MAX_VALUE))q=q.nextProbablePrime(); System.out.println("P:"+p.toString(10)); System.out.println("Q:"+q.toString(10)); //for exponent //aquire one of the lower primes using sieve //pseudo random prime between 7 and int max si(p.mod(BigInteger.valueOf(Integer.MAX_VALUE)).intValue()); e = BigInteger.valueOf(lp); //rsa encrypt and decrypt n = p.multiply(q); t = p.subtract(BigInteger.ONE).multiply(q.subtract(BigInteger.ONE)); d = e.modInverse(t); sec = new BigInteger(secret.getBytes()); //cypher text cy = sec.modPow(e,n); System.out.println("C:"+cy.toString(16)); //decrypted text dec = cy.modPow(d,n); System.out.println("D:"+(new String(dec.toByteArray()))); } //sieve of eratosthenes public static void si(int max){ s(3); s(7); for(int i=11;i&lt;max;i+=10){ if(t(i))s(i); if(0&lt;(i+2)&amp;&amp;t(i+2))s(i+2); if(0&lt;(i+6)&amp;&amp;t(i+6))s(i+6); if(0&lt;(i+8)&amp;&amp;t(i+8))s(i+8); } } //get test bit from sieve public static boolean t(int i){ return (a[i/20]&amp;b(i))==0; } //int value to bit mask used in sieve public static byte b(int i){ return (byte)(1&lt;&lt;(((i%20)/2)-((i%20)/5)+((i%20)/10))); } //sieve forward prime value i public static void s(int i) { lp=i;for(int w=3*i;w&gt;0;w+=(((w+i+i)%5)==0?4*i:2*i))a[w/20]|=b(w); } } </code></pre> <p>Is there any value here? My ambition is to understand the computational and cryptographic theory and translate this into best practices. I apologize for the terrible naming of variables and methods, heinous runtime, useless commenting, unnecessary golfing, and using spaces over tabs.</p> <p><strong>Example output:</strong></p> <pre><code>&gt;java RSATest "password" "test" P:10090275631957288744610599659040664305405434722352094636668421960416506099994666827664511624543986219997911864288607312795882978242921884901347541608283715814165727102775081158850275803219608306098677869589957898032998379673745817876752829320076809618549060139888917446177159027216418146574898873844039044426500320311838804799370581535223413777861948749552759092994514733751610983813 Q:5425365986445829161530505882662909832813406327751968505626162017780151029106074817664839063991268038579259781345806774068118642908105542837724653877104358137779083102271171002417267868641163457971958213047417570560412152250447538894719454784926316581576607321753609289397778946058304937920474724957098706683798464369444644490724812822892582670707683075052137846220273984681853710951 C:105ed567b39e1a87f8c1a3cb370bb528da8a12e69a93d691a5f5ac18d1af691d129f660b4e730eaa9a16c548e20281730ebbad1485a4b4ce79d13061926bc513c66515c5dab3c8e15af2075546abd57814a53876fa113c4d1ae67b63c6e7bf16babde1c85b4ac02c5c23b296accb4836558dcd8b2c66865c6ed027dbfecd4f0f544d14d441c2c73b13bc43269b0ffd9a068f2a5a068b521aff9ba545efa01642df749a5bb639771d7d5c20d6edd23f4739640e5d63eecf3227c2157bfa391a6e617a4049cd3dc84f455933d75cd51a97fd9c7493eb52436be866a909ff6bb598306ec7cfb0ab49551e6e11ca7183a346740ae469545a9237ce201fe4f93d82dbe1ef795e39ea37a154b6c5027e76644d2a250c43363dc0e56addaac3f2e1a343429ffc7ede3144ad822ae4022ba5b1f704c8374fc220fed38c6094e59a D:test </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-11T17:31:57.447", "Id": "453283", "Score": "1", "body": "Why do you use this unnecessary golfing and the terrible variable names? If you don't have good reason to do so, you should clean up your code before the first review comes in. There's more interesting things to comment about than bad names and unreadable code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-11T18:41:23.077", "Id": "453301", "Score": "0", "body": "You are likely correct, but to answer your question, this formatting allows me to understand and hold the code in my mind better, with condensed functional blocks rather than being able to read it like a book. I find the extra white space and verbosity to be excessive and it gives me buffer overflow. `h(a,sha)` could be `bigIntFromHashedStringWithMsgDigest(inputPassword,sha512msgDigest)` and I would have to break `p=p.multiply(h(a,sha)).nextProbablePrime();` into multiple lines to avoid wrapping over 80 characters. This would obfuscate the important ways these highly repetitive lines differ." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-11T22:25:40.503", "Id": "453334", "Score": "1", "body": "`h` probably would be `HashToPrime`. e also doesn't need to be prime, incrementing it until its gcd with (p-1)(q-1) is 1 will do (while starting at 3). Also this search strategy for p and q is somewhat unneccessarily complex (more usual would be to generate a large random buffer, convert to integer and then take the next prime)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-11T23:18:51.590", "Id": "453338", "Score": "0", "body": "@SEJPM, thank you. Regarding P's and Q's, I suppose I could seed a pseudo-random number generator based on the argument given and maintain a deterministic outcome. The unnecessary complexity here is perhaps a misguided attempt on my part to create some distance from the output of extremely fast algorithms (sha/md5) to pad what may be a fairly weak input." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-12T00:40:58.107", "Id": "453344", "Score": "0", "body": "Thanks for explaining why this programming style makes sense to you. I had just been confused because you apologized. Since the style makes sense to you and is required for you to read the code efficiently, you could just explain exactly this in the question. I can accept many styles as correct, I just need to know that they are intentional." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-12T00:52:47.763", "Id": "453346", "Score": "0", "body": "@RolandIllig Thank you for understanding. My apology was intended as just that, in an awkward attempt to respect the priorities of CodeReview, an apparent emphasis on style, but move beyond and get to the meat, functionality. This might be why I'm seemingly un-hirable." } ]
[ { "body": "<blockquote>\n <p>Here is an attempt to leverage Java's <code>BigInteger</code> class to implement the RSA algorithm, as well as md5 and sha512 hashing functions to generate keys for what I hope to be strong cryptography. My prayer is that some of my ideas are novel and not just wrong.</p>\n</blockquote>\n\n<p>If you start at cryptography, you should not start by making up your own schemes and <em>hoping</em> that they are correct. And you should write a paper in case you want to test your scheme, and clearly describe your goals and techniques. A code review is not what is expected for new schemes.</p>\n\n<blockquote>\n <p>I apologize for the terrible naming of variables and methods, heinous runtime, useless commenting, unnecessary golfing, and using spaces over tabs.</p>\n</blockquote>\n\n<p>No, that's not how you develop. You should correctly name your variables, perform your spacing etc. <em>when writing</em> the program. Don't expect you get time to polish up your \"proof of concept\" and always expect that you need to share your code with others, if just to ask questions or to make sure it is readable after you've checked it into a shared code repository / versioning system such as Git.</p>\n\n<p>Personally I prefer spaces over tabs, especially since that's more compatible with e.g. Markdown and other tools that expect text / disrespect tabs.</p>\n\n<hr>\n\n<pre><code>//seive array for lower 2b primes\n</code></pre>\n\n<p>Do a spellcheck or use an IDE that does this.</p>\n\n<pre><code> public static byte[] a = new byte[(Integer.MAX_VALUE/20)+1];\n</code></pre>\n\n<p>What is <code>a</code>? What is this 20? What is <code>1</code>? Why is <code>a</code> not a constant, written as <code>A</code>?</p>\n\n<pre><code> public static BigInteger p=BigInteger.ONE,q=BigInteger.ONE,t;\n</code></pre>\n\n<p>Statics are supposed to be constants. Don't use more than one statement per line unless there is a compelling reason to do otherwise. <code>t</code> is especially hidden here.</p>\n\n<pre><code> public static MessageDigest sha,md5;\n</code></pre>\n\n<p>You later use these instances to hide program state, don't do that.</p>\n\n<pre><code> public static int lp = 3; // last prime sieved\n</code></pre>\n\n<p>Place comments before the line, as they may disappear if you e.g. refactor the name <code>lp</code> into something that makes sense.</p>\n\n<pre><code> public static BigInteger h(byte[] ba, MessageDigest md){\n</code></pre>\n\n<p><code>ba</code> is not a good name as it doesn't tell what <code>ba</code> is used for. <code>seed</code> would probably be a better name.</p>\n\n<pre><code> BigInteger t=(new BigInteger(md.digest(ba))).abs().nextProbablePrime();\n</code></pre>\n\n<p>So you use a hash, then <code>abs</code> (probably not knowing about <code>new BigInteger(1, byte[])</code> and then go for <code>nextProbablePrime</code>, using <code>ba</code> for the entropy required to create a random prime. Ugh.</p>\n\n<pre><code> md.update(t.toByteArray());\n</code></pre>\n\n<p>Then, using a static method, you have an undocumented side effect in <code>md</code>, storing the state in a globally accessible class variable. Bad stuff all round.</p>\n\n<pre><code> BigInteger e,n,t,d,sec,cy,dec;\n byte[] a,ar;\n String secret;\n int itr, itr2; //itr: iterations\n</code></pre>\n\n<p>In Java, you declare the variables when you use them, not before, minimizing scope and therefore state you have to keep track of.</p>\n\n<pre><code> secret=args[1];\n</code></pre>\n\n<p>A string is not a secret but a password.</p>\n\n<pre><code> a=args[0].getBytes();\n</code></pre>\n\n<p>Here <code>a</code> depends on the platform default encoding, which differs in Java. Known bad practice.</p>\n\n<pre><code> sha = MessageDigest.getInstance(\"SHA-512\");\n sha.update(a);\n md5 = MessageDigest.getInstance(\"MD5\");\n md5.update(a);\n</code></pre>\n\n<p>Absolutely unclear why you need two hashes, and why you would ever use MD5 for anything new.</p>\n\n<pre><code> //generate primes from hash of string and its reverse\n p=p.multiply(h(a,sha)).nextProbablePrime();\n p=p.multiply(h(a,md5)).nextProbablePrime();\n p=p.multiply(h(ar,sha)).nextProbablePrime();\n p=p.multiply(h(ar,md5)).nextProbablePrime();\n sha.update(p.toByteArray());\n md5.update(p.toByteArray());\n q=q.multiply(h(ar,sha)).nextProbablePrime();\n q=q.multiply(h(ar,md5)).nextProbablePrime();\n sha.update(q.toByteArray());\n md5.update(q.toByteArray());\n q=q.multiply(h(a,sha)).nextProbablePrime();\n q=q.multiply(h(a,md5)).nextProbablePrime();\n</code></pre>\n\n<p>Great, now we have got no idea what is hashed or not, and it is not documented. Besides that, we call <code>nextProbablePrime()</code> as if it is a computationally efficient operation, which it definitely is <em>not</em>. As the input is only the amount of bytes in the hash operation, the result will be a list of tiny primes. Not useful at all. The variable reuse is horrid as well.</p>\n\n<pre><code> //increase computational time and ensure primality of p/q\n itr = p.mod(BigInteger.valueOf(1000)).intValue();\n</code></pre>\n\n<p>Why would you ever want to increase computation time? What are you trying to strengthen? What use is it if the result is only in the range 0..999, something that can be easily brute forced?</p>\n\n<pre><code> itr2 = 1000-itr;\n for(int i = 1;i&lt;itr;i++)p=p.nextProbablePrime();\n for(int x = 1;x&lt;itr2;x++)q=q.nextProbablePrime();\n while(!p.isProbablePrime(Integer.MAX_VALUE))p=p.nextProbablePrime();\n while(!q.isProbablePrime(Integer.MAX_VALUE))q=q.nextProbablePrime();\n</code></pre>\n\n<p>Whatever. Why?</p>\n\n<p>Got bored. Encryption and decryption (using raw, insecure RSA) in the same method. Trash programming, no clear description. Exceptionally bad exception handling. The variable <code>secret</code> holds the plaintext, normally I would stop reading at <em>that</em>.</p>\n\n<p>Don't see any \"meat\" in there because I have no idea what you are even trying to accomplish.</p>\n\n<p>Start by learning cryptography and take a few lessons in structured programming. Then Effective Java and a style guide or two. Start over and post again when you're done, because this should put some blushes on your face. If it doesn't now, it will when you've studied these fields. You are just not ready what you've tried in the question.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-14T20:56:48.377", "Id": "461319", "Score": "0", "body": "I appreciate that you took the time. I'll clarify the sparse bits, so you can see what is happening.\n\nA password is taken from standard in and the reverse is also stored. Both are hashed two ways; all four results used to index two deterministic pseudo-random primes, p and q; which are stepped forward another 1000 slow iterations. These values are used to test something equivalent to RSA. Separately, a byte-packed sieve for integer primes ending in 1,3,7, and 9.\n\nA) by using modInverse and modPow of BigInteger am I implementing RSA and B) what do you think of this sieve over the int space?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-14T21:37:41.850", "Id": "461324", "Score": "0", "body": "I'm not the best person to answer that question. It seems to me that you do a lot of \"slowing down\", but if the end result is that p and q are on the small side then all seems for nought to me. You need to formally describe your goals, the algorithm, and the perceived attacks and how those are averted. Before that, asking for a review of the scheme is not going to get any serious reactions (well, unless you are lucky, there is always that possibility)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-14T22:14:22.220", "Id": "461330", "Score": "0", "body": "P and Q are roughly in the order of twice the bits of the sha and md5 hashes put together. The only small-ish values are the number of iterations each are stepped forward within the set of primes to prevent a table-based attack and the prime value chosen for exponentiation, which is not a fixed value here." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-14T22:21:52.357", "Id": "461332", "Score": "0", "body": "Even if you combine MD5 and SHA-512 output bit sizes, you would still only have 128 + 512 = 640 bits. That's very far from secure for either the DL or RSA problem, so you would have to somehow prove that your scheme is secure. Saying that 640 bits is enough for everyone is not going to cut it, RSA has already been broken for such key sizes. And RSA generally requires primes that are in the same ballpark w.r.t. the number of bits. \"Smallish\" for RSA is still huge in human scale." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-14T22:39:03.847", "Id": "461333", "Score": "0", "body": "PQ is greater than 2500 bit" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-14T22:44:35.567", "Id": "461334", "Score": "0", "body": "I've added example output above." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-13T19:48:07.867", "Id": "235574", "ParentId": "232170", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-11T04:09:28.023", "Id": "232170", "Score": "7", "Tags": [ "java", "beginner", "primes", "cryptography", "sieve-of-eratosthenes" ], "Title": "Understanding RSA key generation and implementation in Java" }
232170
<p>This is my Python 3.6+ version of the <em>Hangman</em> game, with graphics generated with <code>print</code> and <code>.format</code>. I've never written code professionally so I would like to know what must be changed to reflect good practice, efficiency, clarity of comments.</p> <pre class="lang-py prettyprint-override"><code>from random import randint import os WORDS = ["word", "object","radiant","wave","stream","jazz","wisdom","flow", "california", "metal", "book", "hero", "democracy", "beet", "tissue", "shall", "imminent", "delightful", "magnificent", "awful", "switzerland", "unbelievable","none","plus","one", "crocodile", "architecture", "monotheism", "philosophy", "practical"] LIMIT = 8 answers = [f"Find the word in less than {LIMIT} guesses. Good luck!\n", "Correct!\n", "Wrong guess.\n", "Wrong input. Type a single letter or 'exit'\n", "You already tried that letter.\n"] word = WORDS[randint(0, len(WORDS) - 1)].upper() wrong_guesses = [] eval_guess = 0 #index for the 'answers' list outcome = "" last_tried = "" #last letter tried # build hidden word: hidden_word = ["_" for i in range(len(word))] # Prints the hangman progress, default value is zero def display_hangman(counter=0): if counter == 1: print("{:^34}{}{:^31}{}{:^31}{}{:^30}".format(' _____\n ','| |\n',' | \n',' | \n',' | \n',' |\n','|\n')) elif counter == 2: print("{:^34}{}{:^31}{}{:^31}{}{:^30}".format(' _____\n ','| |\n',' | O\n',' | \n',' | \n',' |\n','|\n')) elif counter == 3: print("{:^34}{}{:^31}{}{:^31}{}{:^30}".format(' _____\n ','| |\n',' | O\n',' | \\\n',' | \n',' |\n','|\n')) elif counter == 4: print("{:^34}{}{:^31}{}{:^31}{}{:^30}".format(' _____\n ','| |\n',' | O\n',' | \\|\n',' | \n',' |\n','|\n')) elif counter == 5: print("{:^34}{}{:^31}{}{:^31}{}{:^30}".format(' _____\n ','| |\n',' | O\n',' | \\|/\n',' | \n',' |\n','|\n')) elif counter == 6: print("{:^34}{}{:^31}{}{:^31}{}{:^30}".format(' _____\n ','| |\n',' | O\n',' | \\|/\n',' | |\n',' |\n','|\n')) elif counter == 7: print("{:^34}{}{:^31}{}{:^31}{}{:^30}".format(' _____\n ','| |\n',' | O\n',' | \\|/\n',' | |\n',' | / \n','|\n')) elif counter == 8: print("{:^34}{}{:^31}{}{:^31}{}{:^30}".format(' _____\n ','| |\n',' | O\n',' | \\|/\n',' | |\n',' | / \\\n','|\n')) else: print("{:^34}{}{:^31}{}{:^31}{}{:^30}".format(' _____\n ','| \n',' | \n',' | \n',' | \n',' |\n','|\n')) # clear the screen def clear_screen(): os.system('cls' if os.name=='nt' else 'clear') # display the messages of the game def display_messages(wrong_guesses, hidden_word, eval_guess=0, LIMIT=8, outcome="", last_tried=""): clear_screen() print(f"\n{' HANGMAN ':*^36}") display_hangman(len(wrong_guesses)) if outcome == 1: print(f"{'YOU WIN!':^36}\nYou rightly guessed: {word}") print("\nYou also tried: ", wrong_guesses) elif outcome == 0: print(f"{'GAME OVER.':^36}\n{'The word was:':^15}{word}") print("\nYou guessed:", hidden_word, "\nYou tried:", wrong_guesses) else: print(hidden_word,"\n") print(f"{answers[eval_guess]}") print(f"Wrong guesses: {wrong_guesses} Wrong guesses remaining: {LIMIT - len(wrong_guesses)}") print(f"Length: {len(hidden_word)} last letter tried: {last_tried}") # core of the game while True: if len(wrong_guesses) == LIMIT: display_messages(wrong_guesses,hidden_word,outcome=0) break if "_" not in hidden_word: display_messages(wrong_guesses,hidden_word,outcome=1) break # messages function display_messages(wrong_guesses,hidden_word, eval_guess, LIMIT, outcome, last_tried) # user interaction prompt = input("Pick a letter or type 'exit' to quit: ").upper() #make input uppercase regardless if prompt.lower() == "exit": print("Bye.") break if prompt.isalpha() and len(prompt) == 1: # check if input single letter if prompt in wrong_guesses or prompt in hidden_word: # If letter already tried eval_guess = 4 elif prompt in word: # correct guess last_tried = prompt # update last tried letter eval_guess = 1 # set the answer to 'Correct!' for i in range(len(word)): if prompt == word[i]: hidden_word[i] = prompt # replace "_" with the letter elif prompt not in wrong_guesses: # Wrong guess. Add wrong letter to the wrong guesses list eval_guess = 2 # set the answer to 'Wrong guess!' wrong_guesses.append(prompt) last_tried = prompt else: eval_guess = 3 # wrong input' </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-11T07:46:30.860", "Id": "453216", "Score": "2", "body": "If you're using 3.6+, any particular reason you haven't used f-strings?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-11T15:12:21.673", "Id": "453251", "Score": "0", "body": "I couldn't quite figure out how to convert the .format spacing into f-strings.Also I was trying to store each 'print' as a string that could be called later on, but it was giving me an error saying that tuples cannot be iterated. I can expand on that in my post if need be." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-11T15:22:55.957", "Id": "453253", "Score": "0", "body": "Correct me if I'm wrong but it seems that backslash ('\\') are not allowed in f-strings and I need them for new lines '\\n'" } ]
[ { "body": "<h1>Style</h1>\n\n<p>The code is what I would call \"visually dense\" (in lack of a better description). By that I mean, that it's hard to spot where a \"block of code\", e.g. a function, ends. A few well placed blank lines could work wonders here. There are well established <a href=\"https://www.python.org/dev/peps/pep-0008/#blank-lines\" rel=\"nofollow noreferrer\">guidelines</a> codified in the \"official\" <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">Style Guide for Python Code</a> (aka PEP 8):</p>\n\n<ul>\n<li>top-level functions or classes should be separated by two blank lines</li>\n<li>inside of classes functions use single blank lines where appropriate</li>\n</ul>\n\n<p>You will also often find that <code>import</code>s are also <a href=\"https://www.python.org/dev/peps/pep-0008/#imports\" rel=\"nofollow noreferrer\">separated from the following code by two blank lines</a>.</p>\n\n<p>The style guide also has something to say about <a href=\"https://www.python.org/dev/peps/pep-0008/#whitespace-in-expressions-and-statements\" rel=\"nofollow noreferrer\">whitespace in expressions and statements</a>. The basic recommendation here would be to have a single blank space around operators like <code>=</code> (you do this - good!) and also have a single blank space after <code>,</code>, e.g. when calling functions (you do this sometimes - get consistent here) or when declaring <code>list</code>s (you don't do this, but you should).</p>\n\n<p>Fortunately, you are not left alone with this task. There are a lot of tools to help you readable and consistent Python code. Some of them are listed in <a href=\"https://codereview.meta.stackexchange.com/a/5252/92478\">this answer on Code Review Meta</a>.</p>\n\n<h1>Naming</h1>\n\n<p><code>answers</code> should likely also be capitalized like words, since it's essentially a constant value you never intend to change. Apart from that the variable names follow a consistent style and have meaningful names.</p>\n\n<h1>Documentation</h1>\n\n<p>You seem to be willing to document your code. That's great! Python has a well established documentation string convention, shortly <a href=\"https://www.python.org/dev/peps/pep-0008/#documentation-strings\" rel=\"nofollow noreferrer\">outlined</a> in the Style Guide, and <a href=\"https://www.python.org/dev/peps/pep-0257/\" rel=\"nofollow noreferrer\">described in more detail in PEP 257</a>. If you put the documentation immediately after the function definition and enclose the <code>\"\"\"Description in triple quotes\"\"\"</code>, Python IDEs and the built-in <code>help(...)</code> function can easily pick it up. This is very convenient for larger projects.</p>\n\n<p>Example:</p>\n\n<pre><code>def clear_screen():\n \"\"\"Clear the screen\n\n This function is supposed to work on Linux and Windows.\n \"\"\"\n os.system('cls' if os.name == 'nt' else 'clear')\n</code></pre>\n\n<h1>The code</h1>\n\n<p>Instead of <code>answers</code> (maybe soon <code>ANSWERS</code>) being a list and working with integer indices to select the appropriate answer, consider changing it to a <code>dict</code>. Then you could either use descriptive keys like <code>\"correct\"</code>, <code>\"wrong\"</code>, or <code>\"already_tried\"</code> or even an <a href=\"https://docs.python.org/3/library/enum.html\" rel=\"nofollow noreferrer\"><code>enum</code></a> to make it clearer which output you are trying to print. This will help you to get rid of all the \"magic numbers\" in your code, which are very error prone if you ever try to change one and miss a spot.</p>\n\n<p><code>display_messages(...)</code> has an empty string as default argument for <code>outcome</code>, but then checks against integer values in the body. Expecting your input to be of a different type than the default argument is something to avoid, since it may confuse someone using that function. The general fallback in such cases is usually <code>None</code>. Another approach might be to make use of <a href=\"https://docs.python.org/3/library/typing.html\" rel=\"nofollow noreferrer\">type hints</a> in Python 3.6 and later. Type hints can automatically be checked by external tools like <a href=\"https://pylint.org/\" rel=\"nofollow noreferrer\">pylint</a> or <a href=\"http://mypy-lang.org/\" rel=\"nofollow noreferrer\">mypy</a> to make sure the code \"is safe to run\" without actually running it (so called static code analysis).</p>\n\n<p><code>display_hangman(...)</code> is a prime example of code duplication. All the <code>print(...)</code>s are basically doing the same thing, only with different inputs. This means the code can easily be refactored to become more like</p>\n\n<pre><code>def display_hangman(counter=0):\n \"\"\"Prints the hangman progress, default value is zero\"\"\"\n gallow = ( # this was the else case before\n ' _____\\n ', '| \\n', ' | \\n', ' | \\n', ' | \\n', ' |\\n', '|\\n'\n )\n if counter == 1:\n gallow = (\n ' _____\\n ', '| |\\n', ' | \\n', ' | \\n', ' | \\n', ' |\\n', '|\\n'\n )\n elif counter == 2:\n ...\n elif counter == 8:\n gallow = (\n ' _____\\n ', '| |\\n', ' | O\\n', ' | \\\\|/\\n', ' | |\\n', ' | / \\\\\\n', '|\\n'\n )\n\n print(\"{:^34}{}{:^31}{}{:^31}{}{:^30}\".format(*gallow))\n</code></pre>\n\n<p>As you can see clearly, there is now only a single place where the <code>print(...)</code>ing happens. The elements of the gallow are stored as a tuple (a list would work too), ready to be used in <code>.format(...)</code>. Using a tuple/list allows us to do <code>\"...\".format(*gallow)</code> which is shorthand for <code>\"...\".format(gallow[0], gallow[1], ..., gallow[6])</code>. This is called <a href=\"https://docs.python.org/3/tutorial/controlflow.html#unpacking-argument-lists\" rel=\"nofollow noreferrer\">argument list unpacking</a> in Python. The slight downside of this is that this neat trick will only work with <code>.format(...)</code>, but not with f-strings. But that's something I can live with, you will have to decide what works best for yourself.\nCarefully adapting the format specifier would also likely make it possible to move each of those <code>\\n</code> into the format string, although I did just check my hypothesis for the first gallow.</p>\n\n<p>When collecting user input, you convert it to uppercase to have it in a normalized format, only to then do <code>prompt.lower() == \"exit\"</code> literally in the next line. I can see no particular reason not to use <code>prompt == \"EXIT\"</code>.</p>\n\n<p>You should likely wrap the code titled with <code># core of the game</code> into a function as well (the generic <code>main()</code> comes to my mind). The games state could then be stored into the function, instead of on a global scope (I'm looking at you <code>wrong_guesses</code>!). That would also make it easily possible to play several rounds of your game without having to remember which global variables need to be reset in order to avoid trouble.</p>\n\n<p>Once this is done, it's time to look at the infamous <code>if __name__ == \"__main__\":</code> which is very often found in Python scripts. This little line of code tells the interpreter to run the code surrounded by that <code>if</code> block only when called like <code>python hangman.py</code>. Omitting this piece of code would also start your game if you ever try to do something like <code>from hangman import clear_screen</code> (code reusability is cooooool).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-11T16:44:06.603", "Id": "453272", "Score": "0", "body": "Wow Thank you very much for the super detailed answer! I have to say that I'm not entirely familiar with dictionaries and still trying to grasp OOP but your insights make me want to refactor that program now. \nHaving 'outcome' as 'None', of course! Actually every suggestions make sense. Going to save this post for later use, thanks again!\n\nThe only thing that I still wonder is, per my comment above, if it's possible to replicate the 'display_hangman' function using Python 3.6x f-string instead of the '.format'. The problem is that I can't add backslashes '\\' to f-string." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-11T16:46:04.633", "Id": "453273", "Score": "0", "body": "Thanks to your comment under your question I just now fully understood why you didn't use f-strings all the way through. I going to add a word on that in a few moments." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-11T17:20:22.847", "Id": "453280", "Score": "0", "body": "@TeaGlass See my newly added thoughts on `display_hangman(...)`. Seems like `\"...\".format(...)` will stick with us, but for a good reason! :-)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-12T13:27:23.163", "Id": "453414", "Score": "0", "body": "Thanks a lot @AlexV! I incorporated the changes and I have more things to learn. I'll keep this thread as a reference for the future." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-11T15:32:02.167", "Id": "232188", "ParentId": "232171", "Score": "3" } } ]
{ "AcceptedAnswerId": "232188", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-11T05:43:23.937", "Id": "232171", "Score": "5", "Tags": [ "python", "python-3.x", "hangman" ], "Title": "Python 3.6 Hangman game with .format graphics" }
232171
<p>This is the 26th exercise I solved from <a href="https://app.codility.com/programmers/lessons/1-iterations/" rel="noreferrer">Codility.</a> It scores 100%. I think I improved a lot since I started with this lessons, around 2 months ago, but still every post I made had things to be improved. What do you think about this code?</p> <blockquote> <p>Task description</p> </blockquote> <hr> <blockquote> <p>A non-empty array A consisting of N integers is given.<br> A pair of integers (P, Q), such that 0 ≤ P ≤ Q &lt; N, is called a slice of array A.<br> The sum of a slice (P, Q) is the total of A[P] + A[P+1] + ... + A[Q].</p> <p>Write a function:</p> <p>class Solution { public int solution(int[] A); }</p> <p>that, given an array A consisting of N integers, returns the maximum sum of any slice of A.</p> <p>For example, given array A such that:</p> <p>A[0] = 3<br> A[1] = 2 <br> A[2] = -6 <br>A[3] = 4 <br>A[4] = 0 <br>the function should return 5 because:</p> <p>(3, 4) is a slice of A that has sum 4, (2, 2) is a slice of A that has sum −6, (0, 1) is a slice of A that has sum 5, no other slice of A has sum greater than (0, 1). Write an efficient algorithm for the following assumptions:</p> <p>N is an integer within the range [1..1,000,000]; each element of array A is an integer within the range [−1,000,000..1,000,000]; the result will be an integer within the range [−2,147,483,648..2,147,483,647].</p> </blockquote> <p>[PS: I'll upvote suggestions about sites that can help me get better at databases that follow a similar approach to codility]</p> <pre><code>using System; class Solution { public int solution(int[] A) { var lastAddend = 0; var accumulator = 0 ; var maxSliceSum = A.Length &gt; 0 ? A[0] : 0 ; foreach(var addend in A) { var maxLastPair = Math.Max(addend, lastAddend + addend); accumulator = maxLastPair &gt; accumulator + addend ? maxLastPair : accumulator + addend; maxSliceSum = Math.Max(maxSliceSum, accumulator); lastAddend = addend; } return maxSliceSum; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-12T13:13:35.600", "Id": "453413", "Score": "0", "body": "More a review on the task: (P, Q) is not a pair of integers but a pair of indexes. This is dramatically different and liable to set people on the wrong foot." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-12T15:23:03.820", "Id": "453426", "Score": "1", "body": "@Flater That's a bit misleading. (P,Q) definitely is a pair of integers. And it is also a pair of indices. A better description would be to say it is a pair of integer indices. I really dont see the ambiguity the way you do. But I can imagine you see it. Nevertheless if you read this sentence: `The sum of a slice (P, Q) is the total of A[P] + A[P+1] + ... + A[Q].` then the ambiguity is gone. Anyway the task description is copied from the lesson in question, it is not work of the OP, so you can't really blame the OP for providing this slightly ambiguous description..." } ]
[ { "body": "<p>Two minor remarks:</p>\n\n<ol>\n<li><p>For consistency sake, this</p>\n\n<pre><code>accumulator = maxLastPair &gt; accumulator + addend ? maxLastPair : accumulator + addend;\n</code></pre>\n\n<p>can be implemented similar to the other statements as </p>\n\n<pre><code>accumulator = Math.Max(maxLastPair, accumulator + addend);\n</code></pre></li>\n<li><p>Some comments would be welcome in the loop. What exactly is the idea behind the different variables you keep. It took me a while to convince myself that your method was working as it should.</p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-11T14:19:41.887", "Id": "453247", "Score": "0", "body": "That line you mention was written like that cause I couldn't get how the accumulator was supposed to handle 1 or 2 tests. So I did it as trial and error, until it worked, I should have tried to improve that line once it was working properly. Thanks!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-11T13:42:06.927", "Id": "232179", "ParentId": "232177", "Score": "5" } }, { "body": "<p>It might actualy be faster if you:</p>\n\n<p>1) Avoid calling <code>Math.Max</code> if you can decide without evaluating the arguments (at least in some cases anyway).</p>\n\n<p>2) Avoid repeating expressions.</p>\n\n<p>3) Avoid writes when value is not changing.</p>\n\n<pre><code>using System;\n\nclass Solution {\n public int solution(int[] A) {\n var lastAddend = 0;\n var accumulator = 0 ; \n var maxSliceSum = A.Length &gt; 0 ? A[0] : 0 ;\n foreach(var addend in A)\n {\n // (1)+(2) var maxLastPair = Math.Max(addend, lastAddend + addend);\n // addend &gt;= lastAdded + addend -&gt; 0 &gt;= lastAddend\n var maxLastPair = 0 &gt;= lastAddend ? addend : lastAddend + addend;\n // (2) accumulator = maxLastPair &gt; accumulator + addend ? maxLastPair : accumulator + addend;\n accumulator = Math.Max(maxLastPair, accumulator + addend);\n // (3) maxSliceSum = Math.Max(maxSliceSum, accumulator);\n if (accumulator &gt; maxSliceSum) maxSliceSum = accumulator;\n lastAddend = addend;\n }\n return maxSliceSum;\n }\n}\n</code></pre>\n\n<p>EDIT:</p>\n\n<p>This can actualy be optimized further:</p>\n\n<p>Here you can see that <code>addend</code> is always component of <code>maxLastPair</code>:</p>\n\n<pre><code>var maxLastPair = 0 &gt;= lastAddend ? addend : lastAddend + addend;\n</code></pre>\n\n<p>So let me split it:</p>\n\n<pre><code>var lastAddendIfPositive = lastAddend &gt; 0 ? lastAddend : 0;\nvar maxLastPair = lastAddendIfPositive + addend;\n</code></pre>\n\n<p>Now let me replace the usage on the next line, and get rid of <code>maxLastPair</code> variable:</p>\n\n<pre><code>accumulator = Math.Max(lastAddendIfPositive + addend, accumulator + addend);\n</code></pre>\n\n<p>This is actualy the same as:</p>\n\n<pre><code>accumulator = Math.Max(lastAddendIfPositive, accumulator) + addend;\n</code></pre>\n\n<p>Now you see you save lastAddend to only use it if it is positive, so change the last loop line:</p>\n\n<pre><code>lastAddendIfPositive = addend &gt; 0 ? addend : 0;\n</code></pre>\n\n<p>And so you get rid of the first statement in the loop.</p>\n\n<p>And we can actualy replace the <code>Math.Max()</code> with a conditional, as the function is so trivial that it is only meaningful as callback, otherwise it is just an unnecesary function call.</p>\n\n<p>Now you can see that <code>lastAddendIfPositive</code> is only used if it is greater than <code>accumulator</code> and so we can get rid of this variable as well.</p>\n\n<p>The final result looks like this:</p>\n\n<pre><code>class Solution {\n public int solution(int[] A) {\n var accumulator = 0 ; \n var maxSliceSum = A.Length &gt; 0 ? A[0] : 0 ;\n foreach(var addend in A)\n {\n accumulator += addend;\n if (accumulator &gt; maxSliceSum) maxSliceSum = accumulator;\n if (addend &gt; 0) {\n if (addend &gt; accumulator) accumulator = addend;\n } else {\n if (accumulator &lt; 0) accumulator = 0;\n }\n }\n return maxSliceSum;\n }\n}\n</code></pre>\n\n<p>EDIT2:\nBtw im not sure about this line:</p>\n\n<pre><code>var maxSliceSum = A.Length &gt; 0 ? A[0] : 0 ;\n</code></pre>\n\n<p>Your specification sais the input array is non empty. So you better throw exception if it is empty. Returning zero seems rather odd, because sum of empty set of values is rather undefined than it is zero.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-11T18:59:44.977", "Id": "232203", "ParentId": "232177", "Score": "5" } } ]
{ "AcceptedAnswerId": "232203", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-11T12:58:01.150", "Id": "232177", "Score": "6", "Tags": [ "c#", "performance", "beginner", "programming-challenge", "array" ], "Title": "Find the largest sum of any slice inside an array" }
232177
<p>I have this angular service that is working perfectly but I'm feeling that it isn't very readable.<br> How would you refactor it?<br> (Simple tips as "try this instead of that..." are very welcome. I'm looking for different approaches.)</p> <pre class="lang-js prettyprint-override"><code>import { Injectable } from '@angular/core'; import { concat } from 'rxjs'; import { map, concatMap, toArray } from 'rxjs/operators'; import { EntityApiAbstration } from 'src/app/shared/abstraction-classes'; import { FeathersService } from './feathers.service'; import { UsersService } from '../state/users.service'; import { Assistencia, EventoCronologico, User } from 'src/app/shared/models'; import { lensProp, view, set, clone } from 'ramda'; @Injectable({ providedIn: 'root' }) export class AssistenciasApiService extends EntityApiAbstration { private usersAPI = this.usersService; private sanitize(arr: any[] | null): any[] | null { if (!arr) { return arr; } return arr.map(item =&gt; ({ id: item.id, qty: item.qty })); } private deserialize&lt;T&gt;(obj: T, objPropName: string) { const lens = lensProp(objPropName); if (typeof view(lens, obj) === 'string') { return set(lens, JSON.parse(view(lens, obj)), obj); } return obj; } private fullyDetailedAssistencia$ = (assistenciaFromApi: Assistencia) =&gt; this.usersAPI.get(assistenciaFromApi.cliente_user_id) .pipe( map((res: User[]) =&gt; res[0]), map(cliente =&gt; ( { ...assistenciaFromApi, cliente_user_name: cliente.nome, cliente_user_contacto: cliente.contacto } as Assistencia) ), map(assistencia =&gt; this.deserialize(assistencia, 'registo_cronologico')), map(assistencia =&gt; this.deserialize(assistencia, 'material')), map(assistencia =&gt; this.deserialize(assistencia, 'encomendas')), concatMap(assistencia =&gt; concat( ...assistencia.registo_cronologico .map(evento =&gt; this.usersAPI.get(evento.tecnico_user_id) .pipe( map((user: User[]) =&gt; ({ ...evento, tecnico: user[0].nome }) as EventoCronologico) )) ) .pipe( toArray(), map(registo_cronologico =&gt; ({ ...assistencia, registo_cronologico }) as Assistencia) ) ), map(assistencia =&gt; { const registo = clone(assistencia.registo_cronologico); const registoFiltered = registo.filter( evento =&gt; evento.estado === 'em análise' || evento.estado === 'contacto pendente' || evento.estado === 'orçamento pendente' || evento.estado === 'aguarda material' || evento.estado === 'concluído' ); const lastEvento = registoFiltered ? registoFiltered[registoFiltered.length - 1] : null; const tecnico = lastEvento ? lastEvento.tecnico : null; return ({ ...assistencia, tecnico } as Assistencia); }) ) constructor( protected feathersService: FeathersService, private usersService: UsersService) { super(feathersService, 'assistencias'); } find(query?: object) { const assistencias$ = super.find(query) .pipe( concatMap(assistencias =&gt; concat(...assistencias.map(this.fullyDetailedAssistencia$)) .pipe(toArray()) ), ); return assistencias$; } get(id: number) { const assistencia$ = super.get(id) .pipe( map(assistencias =&gt; assistencias[0]), concatMap(this.fullyDetailedAssistencia$), map(assistencia =&gt; [assistencia]) ); return assistencia$; } create(data: Assistencia, actionType?: string) { const assistencia$ = super.create({ ...data, material: this.sanitize(data.material), encomendas: this.sanitize(data.encomendas) }) .pipe( map(assistencias =&gt; assistencias[0]), concatMap(this.fullyDetailedAssistencia$), map(assistencia =&gt; [assistencia]) ); return assistencia$; } patch(id: number, data: Assistencia, actionType?: string) { const assistencia$ = super.patch(id, { ...data, material: this.sanitize(data.material), encomendas: this.sanitize(data.encomendas) }) .pipe( map(assistencias =&gt; assistencias[0]), concatMap(this.fullyDetailedAssistencia$), map(assistencia =&gt; [assistencia]) ); return assistencia$; } onCreated() { const assistencia$ = super.onCreated() .pipe( map(assistencias =&gt; assistencias[0]), concatMap(this.fullyDetailedAssistencia$), map(assistencia =&gt; [assistencia]) ); return assistencia$; } onPatched() { const assistencia$ = super.onPatched() .pipe( map(assistencias =&gt; assistencias[0]), concatMap(this.fullyDetailedAssistencia$), map(assistencia =&gt; [assistencia]) ); return assistencia$; } } </code></pre> <p>Explanation of the service: This service sits between the application and the API. <code>fullyDetailedAssistencia$</code> receives an object (assistencia) from API and fetchs the API again for it's parents (basically it's trying to make a NoSQL DB behave to the application as if it was a SQL DB)</p> <pre class="lang-js prettyprint-override"><code>// Assistencia.model.ts import { Artigo } from './artigo.model'; import { Encomenda } from './encomenda.model'; export interface Assistencia { id: number; cliente_user_id: number; cliente_user_name?: string; cliente_user_contacto?: number; registo_cronologico: EventoCronologico[]; // JSON.stringify(data: EventoCronologico[]) tecnico?: string; // tecnico is extrated &amp; filtered from registo_cronologico categoria: string; marca: string; modelo: string; cor: string; serial: string; problema: string; orcamento: number; relatorio_interno: string; relatorio_cliente: string; material: Partial&lt;Artigo&gt;[]; encomendas: Partial&lt;Encomenda&gt;[]; preco: number; estado: string; createdAt: string; updatedAt: string; } export interface EventoCronologico { tecnico_user_id: number; tecnico?: string; relatorio_interno?: string; relatorio_cliente?: string; material?: Partial&lt;Artigo&gt;[]; encomendas?: Partial&lt;Encomenda&gt;[]; preco?: number; estado: string; updatedAt: string; } <span class="math-container">```</span> </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-11T13:33:22.263", "Id": "232178", "Score": "1", "Tags": [ "javascript", "typescript", "angular-2+", "rxjs" ], "Title": "Refactor this RXJS code" }
232178
<p>I am learning Python, so pardon me if this is the very crude approach. I am trying to generate a random string using alphanumeric characters. Following is my code:</p> <pre><code>#Generating random 6 character string from list 'range'. def code(): # List of characters [a-zA-Z0-9] chars = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','0','1','2','3','4','5','6','7','8','9'] code = '' for i in range(6): n = random.randint(0,61) # random index to select element. code = code + chars[n] # 6-character string. return code </code></pre> <p>What I am trying to do is pick six random elements from the list of characters and append them.</p> <p>Is there any better approach?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-11T14:26:37.840", "Id": "453252", "Score": "0", "body": "Check out this link. [\\[Is there a Python Library that contains a list of all the ascii characters?\\]](https://stackoverflow.com/q/5891453/601770)" } ]
[ { "body": "<p>You can use a string for <code>chars</code> to avoid the hassle of all the quotes and commas.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-11T17:11:36.227", "Id": "453278", "Score": "0", "body": "Thanks for pointing that out." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-11T14:25:54.310", "Id": "232181", "ParentId": "232180", "Score": "2" } }, { "body": "<p><strong><em>Simplicity + improvements:</em></strong></p>\n\n<ul>\n<li><code>chars</code> list. Instead of hardcoding all <em>lowercase</em>, <em>uppercase</em> and <em>digit</em> chars - <a href=\"https://docs.python.org/3/library/string.html\" rel=\"noreferrer\"><code>string</code></a> module provides a convenient constants <strong><code>string.ascii_letters</code></strong> and <strong><code>string.digits</code></strong></li>\n<li><code>random.randint(0,61)</code>. Instead of generating random index for further search on <code>chars</code> sequence - <a href=\"https://docs.python.org/3/library/random.html?highlight=random#random.choice\" rel=\"noreferrer\"><code>random.choice</code></a> already allows getting a random element from a specified sequence</li>\n<li><code>for ...</code> loop is easily replaced with <a href=\"https://www.python.org/dev/peps/pep-0289/\" rel=\"noreferrer\"><em>generator</em> expression</a></li>\n</ul>\n\n<hr>\n\n<p>The final version:</p>\n\n<pre><code>import random\nimport string\n\n\ndef random_alnum(size=6):\n \"\"\"Generate random 6 character alphanumeric string\"\"\"\n # List of characters [a-zA-Z0-9]\n chars = string.ascii_letters + string.digits\n code = ''.join(random.choice(chars) for _ in range(size))\n return code\n\nif __name__ == \"__main__\":\n print(random_alnum())\n print(random_alnum())\n print(random_alnum())\n</code></pre>\n\n<p>Sample output:</p>\n\n<pre><code>g7CZ2G\nbczX5e\nKPS7vt\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-11T14:49:25.200", "Id": "453249", "Score": "3", "body": "You can make `chars` a global, return `code` directly and change the `i` loop variable to `_`, which is an unofficial sign for \"i'm not using this name\" This is the best answer so far regardless, though. +1" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-11T16:21:31.167", "Id": "453263", "Score": "9", "body": "Since this is python 3.6, you can remove the for loop by using [`''.join(random.choices(chars, k=6))`](https://docs.python.org/3/library/random.html#random.choices)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-11T17:09:37.017", "Id": "453276", "Score": "0", "body": "Thanks for the answer. It really is an improvement over my code. I will keep the question open for more idea." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-11T23:29:20.610", "Id": "453339", "Score": "0", "body": "Also, using the `secrets` module is smart because it uses the best RNG on the system (`random.SystemRandom` if it's available, otherwise a weaker RNG)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-12T09:42:18.167", "Id": "453385", "Score": "2", "body": "@GregSchmit Depends if you need a cryptographically secure RNG or not." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-12T16:43:06.863", "Id": "453448", "Score": "0", "body": "@MartinBonnersupportsMonica In my experience, every time someone asks how to generate random characters for a string, it's because that string will be used as some kind of secret." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-11T14:32:50.287", "Id": "232184", "ParentId": "232180", "Score": "13" } }, { "body": "<p>Python's <a href=\"https://docs.python.org/3/library/string.html\" rel=\"nofollow noreferrer\"><code>string</code></a> library has predefined constants for ASCII letters and digits. So after <code>import string</code>, <code>chars</code> could be expressed as <code>chars = string.ascii_letters + string.digits</code>. <code>chars</code> could also become a module-level constant, since it does not change in <code>code()</code>. According to <a href=\"https://www.python.org/dev/peps/pep-0008/#constants\" rel=\"nofollow noreferrer\">PEP8, the official Style Guide for Python code</a>, the name would then become <code>CHARS</code>.</p>\n\n<p>The <code>random</code> module also features <code>random.choice</code> and <code>random.choices</code> (versions later than Python 3.6), which either draw a single or a given number of samples from a sequence, in your case <code>chars</code>. You could then do</p>\n\n<pre><code>code = \"\".join(random.choice(chars) for _ in range(6))\n</code></pre>\n\n<p>or</p>\n\n<pre><code>code = \"\".join(random.choices(chars, k=6))\n</code></pre>\n\n<p>depending on what is available to you.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-11T17:10:25.470", "Id": "453277", "Score": "0", "body": "Thanks for the mention of modules. I wasn't aware of those." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-11T14:37:01.320", "Id": "232185", "ParentId": "232180", "Score": "5" } } ]
{ "AcceptedAnswerId": "232184", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-11T14:02:34.420", "Id": "232180", "Score": "8", "Tags": [ "python", "python-3.x", "strings" ], "Title": "Generating a random string of 6 characters long in Python 3.6.2" }
232180
<p>The Fizz Buzz challenge is well-known and should not need any explanations, right?<br> I recently got a bit bored and came up with a solution for Fizz Buzz using LINQ and even asynchronous code and a lot of extension methods. Actually, it's only Extension methods!<br> So, I thought, let's share it and have a review of my code!</p> <pre><code>using System; using System.Collections.Generic; using System.Linq; namespace FizzBuzzApp { using IntEnum = IEnumerable&lt;int&gt;; using Pair = KeyValuePair&lt;int, string&gt;; using PairEnum = IEnumerable&lt;KeyValuePair&lt;int, string&gt;&gt;; using StringEnum = IEnumerable&lt;string&gt;; public static class FizzBuzzClass { public static T DoThis&lt;T&gt;(this T data, Action&lt;T&gt; action) { action(data); return data; } public static T DoThis&lt;T&gt;(this T data, Action action) { action(); return data; } public static IEnumerable&lt;T&gt; DoThis&lt;T&gt;(this IEnumerable&lt;T&gt; data, Action&lt;T&gt; action) { foreach (var item in data) { action(item); yield return item; } } public static T IfThis&lt;T&gt;(this T data, Func&lt;T, bool&gt; condition, Func&lt;T, T&gt; action) =&gt; condition(data) ? action(data) : data; public static T IfThis&lt;T&gt;(this T data, Func&lt;T, bool&gt; condition, Func&lt;T, T&gt; onTrue, Func&lt;T, T&gt; onFalse) =&gt; condition(data) ? onTrue(data) : onFalse(data); public static IntEnum MakeIntArray(this int count, int start = 0) =&gt; Enumerable.Range(start, count); public static Pair NewPair(this int key) =&gt; new Pair(key, string.Empty); public static Pair NewPair(this Pair pair, string data) =&gt; new Pair(pair.Key, data.Trim()); public static PairEnum MakePairs(this IntEnum data, bool asynchronous) =&gt; asynchronous ? data.AsParallel().Select(NewPair) : data.Select(NewPair); public static IOrderedEnumerable&lt;Pair&gt; SortPairs(this IEnumerable&lt;Pair&gt; data) =&gt; data.OrderBy(p =&gt; p.Key); public static bool IsFizz(this Pair data) =&gt; data.Key % 3 == 0; public static Pair DoFizz(this Pair data) =&gt; data.NewPair("Fizz " + data.Value); public static Pair Fizz(this Pair data) =&gt; data.IfThis(IsFizz, DoFizz); public static PairEnum Fizz(this PairEnum data, bool asynchronous) =&gt; asynchronous ? data.AsParallel().Select(Fizz) : data.Select(Fizz); public static bool IsBuzz(this Pair data) =&gt; data.Key % 5 == 0; public static Pair DoBuzz(this Pair data) =&gt; data.NewPair(data.Value + " Buzz"); public static Pair Buzz(this Pair data) =&gt; data.IfThis(IsBuzz, DoBuzz); public static PairEnum Buzz(this PairEnum data, bool asynchronous) =&gt; asynchronous ? data.AsParallel().Select(Buzz) : data.Select(Buzz); public static bool IsNumber(this Pair data) =&gt; string.IsNullOrEmpty(data.Value); public static Pair DoNumber(this Pair data) =&gt; data.NewPair(data.Key.ToString()); public static Pair Number(this Pair data) =&gt; data.IfThis(IsNumber, DoNumber); public static PairEnum Number(this PairEnum data, bool asynchronous) =&gt; asynchronous ? data.AsParallel().Select(Number) : data.Select(Number); public static StringEnum Values(this PairEnum data) =&gt; data.Select(p =&gt; p.Value); public static string Combine(this StringEnum data) =&gt; string.Join(", ", data); public static string FizzBuzz(this int count, bool asynchronous = false) =&gt; count.MakeIntArray() .MakePairs(asynchronous) .Fizz(asynchronous) .Buzz(asynchronous) .Number(asynchronous) .SortPairs() .Values() .Combine(); } </code></pre> <p>To use it, just use <code>100.FizzBuzz(true);</code> for the asynchronous version.<br> Now, the thing is that it's full one-liner extension methods. It's definitely not something a beginner would write. But is it well-written for experts?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-14T18:52:11.607", "Id": "453835", "Score": "1", "body": "\"It's definitely not something a beginner would write.\" It's not something anyone *should* write except for fun. I'm not sure being a beginner or expert has anything to do with it." } ]
[ { "body": "<p>Parallel computing and asynchonous computing are two separate things. While they might be similar in some cases, the two terms have two very distinct meanings in C#-land:</p>\n\n<ol>\n<li>Asynchronous computing is used for the <code>async</code>/<code>await</code> and <code>Task&lt;T&gt;</code> idioms.</li>\n<li>Parallel computing is what you are doing here, using <code>plinq</code>: processing streams of data in different threads in parallel.</li>\n</ol>\n\n<p>With that said, you're not using the features of Plinq to the fullest. Instead of passing the (incorrectly named) <code>asynchronous</code> to each of the methods, <code>count.MakeIntArray().AsParallel()</code> would have sufficed to make the entire thing parallel.</p>\n\n<hr>\n\n<p>I think you went a bit overboard with the amount of extension methods you created, while gaining little for it in return. What if a new request would come to say something new on every number modulo 10? Now you have to make changes in 4 methods (or more accurately, create 4 more methods) to account for these changes!</p>\n\n<p>Instead you could have made the <code>Fizz</code> and <code>Buzz</code> methods two versions of a more generic <code>Substitute</code> method:</p>\n\n<pre><code>public string Substitute(int number, Func&lt;int, bool&gt; when, string with);\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-11T15:26:39.250", "Id": "453254", "Score": "0", "body": "Great catch on that asynchronous/parallel part. But including the .AsParallel() call in the method chain would require me to make two chains. One for parallel and the other for sequential." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-11T15:28:57.653", "Id": "453255", "Score": "2", "body": "@WimtenBrink You can store the chain in a variable. `IEnumerable<int> sequence = count.MakeIntArray(); if(asynchronous){sequence = sequence.AsParallel(); } sequence.MakePairs().Fizz()... etc`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-11T15:32:39.877", "Id": "453256", "Score": "0", "body": "As for going overboard, that was a bit of a purpose here. :-) A generic Substitute could be used but I wanted to have each specific condition as a separate method. After all, there is only one condition for when to Fizz and one for when to Buzz. But the Substitute method is in it! I called it the IfThis() method. But I want the condition and replacement functions to be reusable. It's an exercise in going overboard with reusability." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-11T15:51:38.330", "Id": "453261", "Score": "0", "body": "How about `public static IEnumerable<T> DoParallel<T>(this IEnumerable<T> data, bool parallel) => parallel ? data.AsParallel() : data;`? Then I can use .DoParallel(true) instead." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-11T16:03:56.290", "Id": "453262", "Score": "0", "body": "Wait... For whatever reason, including AsParallel() into the method chain doesn't make it go parallel! All actions are still executed inside a single thread. So storing the chain variable as either parallel or not isn't working..." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-11T15:22:27.380", "Id": "232187", "ParentId": "232183", "Score": "25" } }, { "body": "<p>While your goals may be admirable, I think that, when performance takes a large hit, the whole approach needs to be re-examined. This is atleast 5X's slower than a comparable one liner, even after removing the <code>Combine()</code> method and just returning an <code>IEnumerable&lt;string&gt;</code>. </p>\n\n<p>If someone wanted to test with different terms(ie 7 and 9) and/or different words(ie \"Fazz\" and \"Bizz\") your code would need to be modified and re-compiled.</p>\n\n<p>The <code>DoThis</code> method doesn't check that the <code>data</code> is an appropriate parameter for the <code>action</code>.</p>\n\n<p>The methods particular to <code>Fizz</code> and <code>Buzz</code> basically are just duplicated code. It would seem to me that methods that also take the appropriate <code>Fizz</code> or <code>Buzz</code> value would still be useable but would eliminate much of the duplication.</p>\n\n<p>Here's the one liner I used as comparison:</p>\n\n<pre><code>using kvp = KeyValuePair&lt;int, string&gt;;\n\n/// &lt;summary&gt;\n/// Creates IEnumerable&lt;string&gt; with the appropriate FizzBuzz values.\n/// &lt;/summary&gt;\n/// &lt;param name=\"terms\"&gt; This must be 2 elements long&lt;/param&gt;\npublic static IEnumerable&lt;string&gt; FizzBuzz(this int limit, bool parallel = false,\n params KeyValuePair&lt;int, string&gt;[] terms)\n{\n if(terms.Length != 2)\n {\n throw new ArgumentException(\"'terms' length must be 2\");\n }\n if (parallel)\n {\n return Enumerable.Range(1, limit)\n .AsParallel()\n .Select(x =&gt;\n {\n var fizz = x % terms[0].Key == 0;\n var buzz = x % terms[1].Key == 0;\n return (fizz &amp;&amp; buzz) ? $\"{terms[0].Value}{terms[1].Value}\" : (fizz || buzz) \n ? fizz ? terms[0].Value : terms[1].Value : x.ToString();\n });\n\n }\n else\n {\n return Enumerable.Range(1, limit)\n .Select(x =&gt;\n {\n var fizz = x % terms[0].Key == 0;\n var buzz = x % terms[1].Key == 0;\n return (fizz &amp;&amp; buzz) ? $\"{terms[0].Value}{terms[1].Value}\" : (fizz || buzz) \n ? fizz ? terms[0].Value : terms[1].Value : x.ToString();\n });\n }\n\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-11T21:37:18.290", "Id": "453330", "Score": "0", "body": "It's not about performance but about reusability. I turned a small problem into even smaller parts. But testing for other terms is possible by adding an IfThis() in the method chain with a condition and a new key/value that would be used." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-11T21:38:54.150", "Id": "453331", "Score": "0", "body": "As for the DoThis(), one of the three versions is meant to use an unrelated condition to the time, like a timer or maybe a key event. It's meant to be independent. The other has the data type as a parameter for the action. (I'm using DoThis() in another project with a timer that counts 100 milliseconds.)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-11T21:17:22.537", "Id": "232210", "ParentId": "232183", "Score": "11" } }, { "body": "<p>Understanding your code was a bit of a challenge (albeit an interesting one). </p>\n\n<p>Overall, I see a lot of function definitions that don't seem to accomplish anything. Why did you write</p>\n\n<pre><code>public static IOrderedEnumerable&lt;Pair&gt; SortPairs(this IEnumerable&lt;Pair&gt; data) =&gt; data.OrderBy(p =&gt; p.Key);\n</code></pre>\n\n<p>and then write</p>\n\n<pre><code>.SortPairs()\n</code></pre>\n\n<p>when you could have just written</p>\n\n<pre><code>.OrderBy(p =&gt; p.Key)\n</code></pre>\n\n<p>to begin with?</p>\n\n<p>The only possible advantage of what you've done is that it's easier to read <code>.SortPairs()</code> than it is to read <code>.OrderBy(p =&gt; p.Key)</code>... but the thing is, it <strong><em>isn't</em></strong> easier to read <code>.SortPairs()</code> than it is to read <code>.OrderBy(p =&gt; p.Key)</code>. So you haven't gained anything. You've lost something, too: when I'm looking at the definition of <code>FizzBuzz</code>, now I have to go find the definition of <code>SortPairs</code> in order to see what it does.</p>\n\n<p>Likewise, instead of defining <code>count.MakeIntArray()</code> as <code>Enumerable.Range(0, count)</code>, you could have just written <code>Enumerable.Range(0, count)</code> to begin with. Writing <code>count.MakeIntArray()</code> serves no purpose other than making me spend an extra 15 seconds in order to understand what this code does.</p>\n\n<p>And likewise, instead of writing <code>data.IfThis(IsFizz, DoFizz)</code>, you could have just written <code>IsFizz(data) ? DoFizz(data) : data</code> to begin with. And so on and so forth and so on and so forth.</p>\n\n<p>So, what's my advice to you?</p>\n\n<p>Separating different pieces of logic into separate functions is a great idea... but only to a certain extent. The possible advantages of putting logic into a function include:</p>\n\n<ul>\n<li>The calling code may be easier to understand if it uses a function name than if it uses the logic directly. For example, it's easier to understand what <code>.OrderBy(p =&gt; p.Key)</code> does than to look at an entire sorting algorithm and understand what <em>it</em> does. (But it is <em>not</em> easier to understand what <code>.SortPairs()</code> does than to understand what <code>.OrderBy(p =&gt; p.Key)</code> does.)</li>\n<li>The logic may be used in multiple places. If so, putting it in a function makes it so that you can change it everywhere by changing it just once. (But you're only using <code>.SortPairs()</code> in one place.)</li>\n<li>You may want to pass the logic into a higher-order function. (But you're not doing that with <code>.SortPairs()</code>.)</li>\n<li>Putting logic in a function may allow you to make your code easier to understand by putting that function in a more appropriate place. For example, if you have a form that needs to display sales tax, then putting the sales tax logic in a function would allow you to put that logic somewhere else besides the form class. (But you're not putting the definition of <code>.SortPairs()</code> in a more appropriate place.)</li>\n<li>Putting logic in a function may make that logic reusable, as you mention yourself a few times. (But the functions you've written are never going to be useful for anything besides FizzBuzz, are they? Where's the reusability?)</li>\n</ul>\n\n<p>The cost of defining an additional function is small, but not zero. Make sure that you're getting a benefit from that cost—especially if you're paying that cost 24 times in a 33-line class. Each function definition took me about 15 seconds to follow, meaning that your code took me an extra 6 minutes to understand, for little if any benefit. </p>\n\n<p>The bottom line: if you're not getting any benefits from defining a function, don't define a function!</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-12T15:12:46.587", "Id": "453423", "Score": "0", "body": "Reason for making that many tiny extension methods is basically making them reusable. Separation logic into too fine details is pure overkill but a good practice to have done once, and to have seen once. To be honest, the whole FizzBuzz problem can be solved with a single Linq query with no custom extension methods. But I also wrote it to better understand deferred execution and aggregating in Linq, which are interesting concepts. And finally, I was curious in doing it parallel, which is still tricky." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-12T15:31:00.223", "Id": "453429", "Score": "4", "body": "@WimtenBrink Yep, it's certainly a good exercise. Now, I'm a little curious: you say that you're making these functions reusable, but when, how and why are you imagining these functions might be reused?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-12T16:26:59.383", "Id": "453441", "Score": "0", "body": "I make them reusable to train myself in making code more reusable. It's a challenge when you've been programming for nearly 40 years and want to completely focus on the more modern techniques. But more important, by defining my own SortPair() method, I can make sure all pair lists are sorted the same way so if they need to be sorted in descending order, I just need to change the code in one place. But this code is just training..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-12T20:03:03.343", "Id": "453495", "Score": "8", "body": "@Wim The first thing to learn when thinking about making things super duper reusable without a current need is understanding YAGNI." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-13T13:58:19.477", "Id": "453626", "Score": "5", "body": "A good rule of thumb is to only make something reusable once you've used it three times. Before that, it's hard to predict what, if any, context you'll want to reuse it in." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-13T18:18:51.600", "Id": "453651", "Score": "2", "body": "This is about abstraction, not reusability. Do you gain any added insight by replacing `IsFizz(data) ? DoFizz(data) : data` with `data.IfThis(IsFizz, DoFizz)`? No, you're not. You're just re-stating what the first piece of code is doing. However, replacing `Enumerable.Range(0, count)` with `count.MakeIntArray()` **is** a valuable abstraction. It clarifies _why_ `Enumerable.Range(0, count)` is being called." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-13T18:39:17.233", "Id": "453655", "Score": "0", "body": "@KrzysztofCzelusniak I *almost* agree with you, but I don't see what helpful information the name \"MakeIntArray\" provides. After all, I can see at a glance that `Enumerable.Range(0, count)` makes an int array (well, an int enumerable). But I would agree with you on, say, defining `MichiganSalesTax = 0.06m` and then writing `MichiganSalesTax` instead of `0.06m`; *that* would be a valuable definition." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-13T18:59:07.117", "Id": "453657", "Score": "1", "body": "@TannerSwett for someone just learning, or someone writing for people who are just learning Linq concepts, it isn't necessarily a given that Enumerable.Range is understood for what it is at a glance. In this context giving it a name (even if the name is a lie) can certainly be helpful." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-13T19:15:58.957", "Id": "453662", "Score": "0", "body": "@Mr.Mindor Oh yeah, that's a good point." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-13T20:57:47.523", "Id": "453681", "Score": "0", "body": "@TannerSwett, I agree with you that `MakeIntArray` isn't the best name/abstraction. I was just trying to make a counterpoint because the discussion started focusing on reusability when abstraction is also important. Although you do mention that in the first bullet point of your answer." } ], "meta_data": { "CommentCount": "10", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-12T15:01:23.160", "Id": "232251", "ParentId": "232183", "Score": "15" } }, { "body": "<p>The comments mention being <em>reusable</em> as the main goal of the code. It is however far from it. </p>\n\n<p>The main issues I see with most of the extension methods above:</p>\n\n<ul>\n<li>Looking at the name of the methods (and parameters) I can't always tell what the outcome will be.</li>\n<li>When the outcome is pretty clear, the implementation reveals surprinzing, totally unexpected side-effects.</li>\n</ul>\n\n<p>Here are some of the questions I would ask if I saw these methods in a library I would like to reuse:</p>\n\n<ul>\n<li><code>Pair NewPair(this int key)</code> - How does an int become a pair? What will the key/value look like?</li>\n<li><code>IntEnum MakeIntArray</code> - Why does it say <em>Array</em> but return <code>IEnumerable</code>?</li>\n<li><code>Pair NewPair(this Pair pair, string data)</code> - Why does it trim data?</li>\n<li><code>IOrderedEnumerable&lt;Pair&gt; SortPairs(this IEnumerable&lt;Pair&gt; data)</code> - Sort them by what? Key, value, both? How are items compared?</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-12T18:40:55.560", "Id": "232271", "ParentId": "232183", "Score": "9" } }, { "body": "<p>I would argue your garden-variety C# developer is pretty sharp with LINQ as it is, rather than abstracted away, and also hopefully keeping up with modern C# innovations such as first-class Tuple support. Your take becomes a two-liner which I would argue is just as readable and maintainable. If you are wanting real maintainability, usability, and extensibility, first look to separating the concerns (into different classes), segregating them via interfaces or delegates as needed, then injecting those dependencies where they're required. I'm not going to go into all that -- feel free to look at those \"Enterprise FizzBuzz\" links on the question. However, here's the short version that I described at the beginning (yes, I am aware the output is slightly different but matches most original FizzBuzz challenges):</p>\n\n<pre><code>public static string FizzBuzz(this int count, bool parallel = false)\n{\n IEnumerable&lt;int&gt; range = Enumerable.Range(0, count);\n\n return string.Join(\n \", \",\n (parallel ? range.AsParallel() : range)\n .Select(key =&gt; (Key: key, Value: string.Empty))\n .Select(data =&gt; data.Key % 3 == 0 ? (data.Key, Value: \"Fizz\") : data)\n .Select(data =&gt; data.Key % 5 == 0 ? (data.Key, Value: data.Value + \"Buzz\") : data)\n .Select(data =&gt; string.IsNullOrEmpty(data.Value) ? (data.Key, Value: data.Key.ToString()) : data)\n .OrderBy(p =&gt; p.Key)\n .Select(p =&gt; p.Value));\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-12T19:25:44.557", "Id": "232275", "ParentId": "232183", "Score": "7" } }, { "body": "<p>Now, I fully congratulate you on the exercise - it's an interesting problem and I think a great learning opportunity. However, to learn from this we must acknowledge it's shortcomings.</p>\n\n<p>I think the biggest, most glaring issue for me is that this decomposes business logic beyond the simplest possible implementation! Take a second and look at these three lines:</p>\n\n<pre><code> public static Pair DoFizz(this Pair data) =&gt; data.NewPair(\"Fizz \" + data.Value);\n public static Pair DoBuzz(this Pair data) =&gt; data.NewPair(data.Value + \" Buzz\");\n public static Pair DoNumber(this Pair data) =&gt; data.NewPair(data.Key.ToString());\n</code></pre>\n\n<p>Now, why does 'Fizz' get prepended and yet 'Buzz' get suffixed? Why does <code>DoNumber</code> simply take a brand new value?</p>\n\n<p>Simple: there's an implicit dependency here between the business logic that has been obfuscated under the layers of fluent methods.</p>\n\n<p>To put it another way, what happens if we change the order of these methods? For example: <code>...Number(asynchronous).Fizz(asynchronous).Buzz(asynchronous)...</code>? I think the results would not be what one would expect. </p>\n\n<p>Other issues:</p>\n\n<ul>\n<li>There's to much focus on <em>what</em> you are doing, rather than <em>how</em> you are doing it. You've decomposed the business logic... into separate, unreusable steps...rather than finding the common algorithm.</li>\n</ul>\n\n<p>One possible alternative solution would be to try and implement a case statement in Linq. Something like:</p>\n\n<pre><code>public IEnumerable&lt;T2&gt; Case&lt;T1, T2&gt;(Func&lt;T1, bool&gt; match, T2 result, Func&lt;T1, bool&gt; match2, T2 result2...)\n</code></pre>\n\n<ul>\n<li>The code is incredibly hard to read (due to the above)... it took me a good 15 minutes, with access to the entire source, to understand what was happening. KISS.\n\n<ul>\n<li>Take <code>public static IntEnum MakeIntArray(this int count, int start = 0) =&gt; Enumerable.Range(start, count);</code> - It doesn't return an Array, IntEnum is a confusing alias (especially as C# has 'enums' already), and it hides a method that C# developers are already familiar with. </li>\n</ul></li>\n<li>The asynchronous... isn't asynchronous as others have mentioned.</li>\n<li>It's not really LINQ - sure, it's Fluent and uses <code>IEnumerable&lt;T&gt;</code>'s... but it's not really extending the Query language to help me <em>query</em> things... it's just hardcoded business logic. Think the difference between <code>.First(p =&gt; p.name)</code> and <code>.FirstName()</code>.</li>\n</ul>\n\n<p>To leave on a good note, I do think this is the beginning of a good idea:</p>\n\n<pre><code> public static string Combine(this StringEnum data) =&gt; string.Join(\", \", data);\n</code></pre>\n\n<p>However, I'd call it <code>Join</code> and make it an alias of <code>String.Join</code>. It's an operation that's generic, and I often find it useful.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-13T04:27:04.573", "Id": "232293", "ParentId": "232183", "Score": "9" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-11T14:28:32.653", "Id": "232183", "Score": "18", "Tags": [ "c#", "linq", "fizzbuzz", "extension-methods" ], "Title": "Solving Fizz Buzz using LINQ in C#" }
232183
<p>Not long ago, I was asked about how many lines of code I have written in C++ and could not answer that question. For this reason and to become more familiar with Bash shell scripting, I wrote a small system to monitor the lines of code written in a specific subdirectory.</p> <p>Currently, I count the lines of code at 5 seconds interval and write the difference (if favorable) to a file.</p> <p>As mention above, I am not familiar with bash scripting and hope to get some helpful feedback.</p> <p>I would appreciate the advice, especially in the following areas:</p> <ul> <li>Code style (readability, naming conventions)</li> <li>Efficiency (how to avoid unnecessary complexity)</li> <li>How can I prevent a long list of extension as used currently in my approach (<code>-name "*.py" -o -name "*.cpp" -o -name "*.h"</code>). Can I do something like <code>[py, cpp, h, ...]</code> instead?</li> </ul> <pre><code>count_lines () { N="$(find ./ -name "*.py" -o -name "*.cpp" -o -name "*.h" | \ xargs grep -cve "^\s*$" | grep -oP '(?&lt;=:).*' | \ awk '{s+=$1} END {print s}')" echo "$N" } FILE_NAME="counter.log" touch $FILE_NAME SUM=0 while true; do NUM1=$(count_lines) sleep 5; NUM2=$(count_lines) DIFF=$((NUM2-NUM1)) if [ "$DIFF" -gt 0 ]; then SUM=$((SUM+DIFF)) fi echo "${SUM} ${NUM2}" &gt;&gt; $FILE_NAME done </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-19T22:52:06.917", "Id": "458335", "Score": "0", "body": "I think this script is using an inappropriate language for the job, though I'm biased. I have a personal rule that I would recommend following: The set of acceptable bash scripts consists exclusively of scripts with precisely one line, to start your choice of python, ruby, go, swift, or whatever other \"real\" language you fancy. Seriously, the value of `N` includes: xargs, 3 pipes, an in-line AWK program, 2 calls 2 grep, and an entire clusterf*** of commas, dots, dashes and other sigils. I absolutely guarantee you that you won't remember what all those flags mean in 6 months time." } ]
[ { "body": "<p>This isn't any shorter, but it is more dynamic:</p>\n\n<pre class=\"lang-bsh prettyprint-override\"><code>exts=( py cpp h )\n\ncount_lines() {\n local find_args=( -false )\n for ext in \"${exts[@]}\"; do\n find_args+=( -o -name \"*.$ext\" )\n done\n\n find ./ \"${find_args[@]}\" -print0 |\n xargs -o grep -cve \"^\\s*$\" |\n grep -oP '(?&lt;=:).*' |\n awk '{s+=$1} END {print s}'\n}\n</code></pre>\n\n<p>The extensions reside in a bash array that can live in the global scope. It's one place to store your list of interesting files.</p>\n\n<p>In count_lines you can build up an array of arguments to pass on to <code>find</code>. I'm using <code>-false</code> as the first one so that it's simple to add <code>-o -name \"*.something</code> in the loop.</p>\n\n<p>You don't need to capture the command output only to print it on the next line. Just let the commands print to stdout directly.</p>\n\n<p>I added <code>-print0</code> to find and <code>-0</code> to xargs. These options work well together to be able to handle any filename, regardless of any whitespace in the name.</p>\n\n<p>Note you don't need to use line continuations when the line ends with a pipe (or with a &amp;&amp; or ||) -- bash understands that the pipeline continues on the next line.</p>\n\n<p>About your <code>awk</code> command: if your goal is to count lines, don't you want <code>{s+=1}</code> or <code>{s++}</code> instead of <code>{s+=$1}</code>? The latter will only sum any filenames that look like numbers:</p>\n\n<pre class=\"lang-bsh prettyprint-override\"><code>$ touch 5 8 a b c\n$ ls | awk '{sum += $1; count++} END {print sum, count}'\n13 5\n\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-11T15:37:23.490", "Id": "232190", "ParentId": "232186", "Score": "5" } }, { "body": "<h3>Unnecessary capturing of output</h3>\n\n<p>It's strange in <code>count_lines</code> to capture the output of <code>find</code> only to <code>echo</code> it.</p>\n\n<p>Instead of:</p>\n\n<blockquote>\n<pre><code>N=\"$(pipeline)\"\necho \"$N\"\n</code></pre>\n</blockquote>\n\n<p>This is the same thing, with fewer processes:</p>\n\n<pre><code>pipeline\n</code></pre>\n\n<h3>Complicated counting of lines</h3>\n\n<p>You used a <code>grep</code> to count lines, then another <code>grep</code> to remove other junk to keep only counts, then an <code>awk</code> to sum counts. It would be a lot simpler to use <code>wc</code>.</p>\n\n<p>Instead of:</p>\n\n<blockquote>\n<pre><code>xargs grep -cve \"^\\s*$\" | grep -oP '(?&lt;=:).*' | \\\nawk '{s+=$1} END {print s}'\n</code></pre>\n</blockquote>\n\n<p>You could write:</p>\n\n<pre><code>xargs grep -ve \"^\\s*$\" | wc -l\n</code></pre>\n\n<h3>Calling <code>count_lines</code> more than necessary?</h3>\n\n<p>The <code>while</code> loop calls <code>count_lines</code>, waits for 5 seconds, then calls <code>count_lines</code> again, and prints some stats, then starts over again.\nThe printing of stats is a fast operation,\nso some <code>count_lines</code> calls look wasteful.</p>\n\n<p>It would be better to call <code>count_lines</code> only once per iteration,\nand compare values to the call in the previous iteration.\n(This also means you'll need to call it once before the loop too, to initialize.)</p>\n\n<h3>Other minor issues</h3>\n\n<p>Capitalized variable names are not recommended in scripts.</p>\n\n<p>Always double-quote variables used in command line arguments, for example <code>touch \"$filename\"</code> instead of <code>touch $filename</code>.</p>\n\n<p><code>;</code> at the end of a line is unnecessary.</p>\n\n<p>Instead of <code>diff=$((a - b))</code> you can write <code>((diff = a - b))</code>.\nBtw, <code>((sum += diff))</code> also works.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-28T20:19:06.670", "Id": "233134", "ParentId": "232186", "Score": "4" } }, { "body": "<h2>Open the toolbox</h2>\n\n<p>The hard part may be accomplished using <code>watch</code>, the filtering may be done using <code>sed</code>.</p>\n\n<pre><code>#!/bin/bash -eu\n# Number of lines of code in a directory\n\nfiles=(*.py *.h *.cpp)\n\nshopt -s nullglob\n\nif [[ $# -ne 1 ]]; then\n echo \"usage: wc_code directory\"\n exit 1\nfi\n\nif [[ ! -d $1 ]]; then\n echo \"no such directory: $1\"\n exit 1\nfi\n\ncd \"$1\" &amp;&amp; sed '/^[[:space:]]*$/d' ${files[@]} | wc -l\n</code></pre>\n\n<p><code>wc_code</code> is the script name located in the search path. <code>/home/user/dir</code> is a directory containing source files.</p>\n\n<pre><code>prompt% watch wc_code /home/user/dir\n</code></pre>\n\n<p>Note: the sample code may be improved, it may also depend on your preferences. For instance, the previous script may be replaced by <code>watch 'sed /^[[:space:]]*$/d *.py *.cpp *.h | wc -l'</code>.</p>\n\n<h2>See Also</h2>\n\n<ul>\n<li>for a concise explanation about using the shell: <a href=\"https://unix.stackexchange.com/a/169765/286944\">Why is using a shell loop to process text considered bad practice?</a></li>\n<li>for a conceptual overview of commands: <a href=\"http://www.gnu.org/software/coreutils/manual/coreutils.html#Opening-the-software-toolbox\" rel=\"nofollow noreferrer\">Opening the software toolbox</a></li>\n</ul>\n\n<p><em>My personal opinion is that we can easily achieve the same task in broad stokes. The number of lines of source code is not necessarily a determining criterion.</em></p>\n\n<pre><code>watch wc -l *.py .*cpp *.h\n</code></pre>\n\n<h2>Retrospective</h2>\n\n<p>If your task is specific it is probably better to develop a new program than to create a shell script because shell utilities can perform <em>common tasks.</em></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-19T20:03:35.530", "Id": "234342", "ParentId": "232186", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-11T15:11:36.157", "Id": "232186", "Score": "7", "Tags": [ "bash", "linux" ], "Title": "Monitor progress of written lines of code" }
232186
<p>I have a <code>char tempBuffer</code> which stores say <code>my!string!hello!</code>. After every <code>!</code> is encountered that token is moved to a <code>char codeBuffer</code> and the rest of the characters are shifted to the begiinging of <code>tempBuffer</code>. So after <code>my</code> is moved to <code>codeBuffer</code>, <code>tempBuffer</code> contains <code>string!hello!</code>. </p> <p>I have currently implemented it as follows: </p> <pre><code>while (tempBuffer[0] != '\0') { /* Read input contents into tempBuffer */ bytesReadTotal = read(fd, tempBuffer, BUFFER_SIZE); /* Copy contents of tempBuffer into codeBuffer till delimiter is found*/ for (startOfBlock = 0; startOfBlock &lt; strlen(tempBuffer); startOfBlock++){ if (tempBuffer[startOfBlock] != opt.separator[0]) codeBuffer[startOfBlock] = tempBuffer[startOfBlock]; else break; } if (tempBuffer[startOfBlock] == '\0') break; /* Copy contents of tempBuffer into temp2Buffer from new block position*/ for (int i = 0; i &lt; strlen((char*) tempBuffer); i++) { temp2Buffer[i] = tempBuffer[startOfBlock + 1]; startOfBlock++; } /* Copy contents of temp2Buffer to tempBuffer */ for (startOfTB = 0; startOfTB &lt; strlen((char*) temp2Buffer); startOfTB++) { tempBuffer[startOfTB] = temp2Buffer[startOfTB]; } /* Reset all contents of tempBuffer after last copied position to '\0' to avoid overlap */ tempBuffer[startOfTB] = '\0'; } </code></pre> <p>I would like to avoid multiple copy operations.How can I improve this code?</p>
[]
[ { "body": "<p>C's string implementation is <a href=\"https://en.wikipedia.org/wiki/Null-terminated_string\" rel=\"nofollow noreferrer\">null-terminated</a>. Thus, as long as,</p>\n\n<ol>\n<li>one doesn't care about the original string, (this may not be possible if you have a <code>const char *</code>,) and</li>\n<li>one has at least one <code>char</code> that one is willing to discard per block, (usually the block delimiter,) to turn into '\\0',</li>\n</ol>\n\n<p>one can do this in place without copying. This tokenizing is very common, and <code>string.h</code> from the standard library has functions that will help. For example, <code>strtok</code>, (and thread-safe extension to the ISO C standard, <code>strtok_r</code>,) or non-standard, but <code>strsep</code> is an improvement, (possible <a href=\"https://opensource.apple.com/source/Libc/Libc-167/string.subproj/strsep.c.auto.html\" rel=\"nofollow noreferrer\">implementation</a>.) In this code, this takes advantage that <code>argv</code> is writable and uses it to come up with some strings which are separated by <code>strchr</code>.</p>\n\n<pre><code>#include &lt;string.h&gt;\n#include &lt;stdio.h&gt;\n#include &lt;assert.h&gt;\n\n/** One could probably store this, but printing it is easier. */\nstatic void print(const char *p) { printf(\"codeBuffer &lt;- %s\\n\", p); }\n\n/** `str0` is a string that get separated by '!'. */\nstatic void str_sep_bang(char *str0, void (*const callback)(const char *)) {\n char *str1;\n assert(str0 &amp;&amp; callback);\n for( ; ; ) {\n if((str1 = strchr(str0, '!'))) *str1 = '\\0';\n if(*str0 != '\\0') callback(str0);\n if(!str1) break;\n str0 = str1 + 1;\n }\n}\n\nint main(int argc, char **argv) {\n int i;\n for(i = 1; i &lt; argc; i++) {\n printf(\"You passed: %s.\\n\", argv[i]);\n str_sep_bang(argv[i], &amp;print);\n }\n return 0;\n}\n</code></pre>\n\n<p>This prints out,</p>\n\n<pre><code>bin/stringthing foo\\!bar\\!baz\\!qux \\!\\!\nYou passed: foo!bar!baz!qux.\ncodeBuffer &lt;- foo\ncodeBuffer &lt;- bar\ncodeBuffer &lt;- baz\ncodeBuffer &lt;- qux\nYou passed: !!.\n</code></pre>\n\n<p>However, if one needs to store these values, you need space, (an array of <code>char *</code>, same as is passed in <code>argv</code>.) Usually that involves dynamic allocation or static allocation of the maximum size. As well, accessing this list is only valid while the data from the underlying string doesn't change or go out-of-scope; this is why crossing different modules typically involves duplication of the underlying data.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-11T20:53:50.427", "Id": "232207", "ParentId": "232192", "Score": "1" } } ]
{ "AcceptedAnswerId": "232207", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-11T16:12:19.087", "Id": "232192", "Score": "1", "Tags": [ "c", "array" ], "Title": "Shift part of char array to the same array after encountering a delimiter" }
232192
<p>I'm just use the <code>add_filter('the_content', function($content){});</code> for filtering anchor tags in a post.</p> <p>Basically, I want filter anchor tags to appropriate format. I want to add custom attributes like <code>rel="nofollow noopener"</code> and <code>target="_blank"</code> if the anchor tag linked to external of my WordPress site.</p> <p>Instead checking and replace if <code>rel</code> or <code>target</code> is already exists in the anchor tag, I just need to retrieve the value of <code>href</code> and the value of the anchor tag itself (<code>&lt;a&gt;value&lt;/a&gt;</code>). So I can force create an anchor tags with my preferred custom attributes.</p> <p>Here's my current working function:</p> <pre><code>add_filter('the_content', function($content) { $internal = get_home_url(); return preg_replace_callback('#&lt;a.*?href="([^"]*)".*?&gt;([^&gt;]*)&lt;/a&gt;#i', function($match) use ($internal) { if(stripos($match[1], $internal) || strpos($match[1], "#") == 0) { return "&lt;a href=\"$match[1]\"&gt;$match[2]&lt;/a&gt;"; } else { return "&lt;a href=\"$match[1]\" rel=\"nofollow noopener\" target=\"_blank\"&gt;$match[2]&lt;/a&gt;"; } }, $content); }); </code></pre> <p>I'm worried about performance because this function <a href="https://developer.wordpress.org/reference/hooks/the_content/#more-information" rel="nofollow noreferrer">run each user read a post</a>. Any suggestions are welcome.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-11T18:20:42.463", "Id": "453292", "Score": "0", "body": "How many posts with approx how many links are we talking? I don't think this would be a performance issue unless your are processing a significant number of links. (like 100s per second)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-11T18:22:20.963", "Id": "453293", "Score": "0", "body": "If you are worried about performance. I would say write a JavaScript function to handle displayed links. Takes all the work out of the server and onto clients computers." } ]
[ { "body": "<p>I must recommend that you favor accuracy over performance. After all, what good is a fast loading site if it doesn't provide the correct/intended content.</p>\n\n<p>When parsing valid html, please always leverage a good dom parser. Regex is \"dom-unaware\" and therefore is more vulnerable to breakage.</p>\n\n<p>Here is a demonstration of how to use DOMDocument and XPath to articulately replace hyperlinks in your document in a stable manner:</p>\n\n<p>Code: (<a href=\"https://3v4l.org/6jqUc\" rel=\"nofollow noreferrer\">Demo</a>)</p>\n\n<pre><code>$html = &lt;&lt;&lt;HTML\n&lt;div&gt;\n&lt;a href=\"#\"&gt;hello&lt;/a&gt; &lt;abbr href=\"sneaky.com\"&gt;FYI&lt;/abbr&gt; &lt;a title=\"goodbye\"&gt;later&lt;/a&gt;\n&lt;a href=https://example.com&gt;no quoted attributes&lt;/a&gt;\n&lt;A href=\"https://external.com\"\ntitle=\"some title\"\ndata-key=\"{\\'key\\':\\'adf0a8dfq&lt;&gt;*1$4%\\'\"&gt;a link with data attribute&lt;/A&gt;\nand\nthis is &lt;a title=\"hello\"&gt;not a hyperlink&lt;/a&gt; but simply an anchor tag\n&lt;a href=\"#jumpTo\"&gt;Jumper&lt;/a&gt;\n&lt;/div&gt;\nHTML;\n\n$internal = 'https://example.com';\n\n$dom = new DOMDocument; \n$dom-&gt;loadHTML($html, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);\n$xpath = new DOMXPath($dom);\nforeach ($xpath-&gt;query(\"//a[@href]\") as $node) {\n $replacementNode = $dom-&gt;createElement(\"a\", $node-&gt;nodeValue);\n $href = $node-&gt;getAttribute('href');\n $replacementNode-&gt;setAttribute('href', $href); \n if($href[0] != \"#\" &amp;&amp; stripos($href, $internal) === false) {\n $replacementNode-&gt;setAttribute('rel', 'nofollow noopener');\n $replacementNode-&gt;setAttribute('target', '_blank');\n }\n $node-&gt;parentNode-&gt;replaceChild($replacementNode, $node);\n}\necho $dom-&gt;saveHTML();\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>&lt;div&gt;\n&lt;a href=\"#\"&gt;hello&lt;/a&gt; &lt;abbr href=\"sneaky.com\"&gt;FYI&lt;/abbr&gt; &lt;a title=\"goodbye\"&gt;later&lt;/a&gt;\n&lt;a href=\"https://example.com\"&gt;no quoted attributes&lt;/a&gt;\n&lt;a href=\"https://external.com\" rel=\"nofollow noopener\" target=\"_blank\"&gt;a link with data attribute&lt;/a&gt;\nand\nthis is &lt;a title=\"hello\"&gt;not a hyperlink&lt;/a&gt; but simply an anchor tag\n&lt;a href=\"#jumpTo\"&gt;Jumper&lt;/a&gt;\n&lt;/div&gt;\n</code></pre>\n\n<p>Will this be slow? Well, I presume it will be slower than regex but then that is the cost of implementing a superior processing tool. If you need to gain performance, investigate other avenues which will not spoil your content. This is not a task where a shortcut is a good idea.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-12T02:39:42.917", "Id": "453348", "Score": "1", "body": "+1 for the anchor tag example in multiple cases" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-12T03:17:18.907", "Id": "453351", "Score": "0", "body": "After trying this code, I think you missing some cases where if anchor tag has attributes `href=\"/\"` that should detect as internal and `href=\"https://external.com?utm_source=https://example.com\"` that should detect as external" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-12T03:18:43.820", "Id": "453352", "Score": "0", "body": "Extend as you need for your project. You didn't provide any sample input data, so I fabricated some." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-12T04:39:47.147", "Id": "453355", "Score": "0", "body": "According to the constraints of CodeReview, all posted questions are expected to be correct and producing the desired output. My answer uses the same logic as was implemented in your posted snippeted. Now that I have answered, you are not permitted to change your posted code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-12T06:56:44.220", "Id": "453365", "Score": "0", "body": "Yes of course. BTW your answer is awesome and very helpful." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-11T22:26:19.640", "Id": "232214", "ParentId": "232194", "Score": "2" } } ]
{ "AcceptedAnswerId": "232214", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-11T16:44:08.013", "Id": "232194", "Score": "2", "Tags": [ "php", "regex", "wordpress" ], "Title": "Replace anchor tags and force create new tag with custom attributes" }
232194
<p>I build this silly app to get the commenters' information on some PR, mostly for learning how to use API's and for improving my JS dom skills.</p> <p>Although it is working, it's mostly spaghetti code and very disorganized, so I am sure there is a lot of room for improvement.</p> <p>I would like to get some feedback on how to better organize my code and structure it so it can easily grow and can be more maintainable.</p> <p>This is the JS file (probably need to split into modules/classes, but don't know where to start):</p> <pre><code>function createElement(type, options = {}) { const element = document.createElement(type) Object.keys(options).forEach(option =&gt; { element[option] = options[option] }) return element } function createUser(user) { const userHtml = { avatarUrl: createElement('img', { src: user.avatar_url, }), login: createElement('a', { href: user.html_url, textContent: user.login, }), } if (user.name) { const name = createElement('div', { textContent: user.name, }) userHtml.name = name userHtml.name.classList.add('name') } userHtml.avatarUrl.classList.add('avatar') userHtml.login.classList.add('login') return userHtml } function renderPullRequestInfo(pullRequest) { const { login } = createUser(pullRequest.user) const title = createElement('a', { id: 'title', href: pullRequest.html_url, textContent: pullRequest.title, }) document.querySelector('#pull-request-info').append(title, login) } function renderUsers(users) { const fragment = document.createDocumentFragment() const title = document.createElement('h3') if (users.length === 0) { title.textContent = 'No reviewers found :(.' } else { title.textContent = 'Reviewers:' users.forEach(user =&gt; { if (user.name) { const li = createElement('li') const { avatarUrl, login, name } = createUser(user) li.append(avatarUrl, login, name) fragment.appendChild(li) } }) const ul = document.querySelector('#user-list') ul.before(title) ul.appendChild(fragment) } } async function fetchGithubApi(endpoint) { const githubApiUrl = 'https://api.github.com' const response = await fetch( endpoint.startsWith(githubApiUrl) ? endpoint : `${githubApiUrl}${endpoint}`, { headers: { Accept: 'application/vnd.github.v3+json' }, } ) const data = await response.json() return data } async function getPullRequestData(event) { event.preventDefault() document.querySelector('#pull-request-url-messages').textContent = '' document.querySelector('#user-list').innerHTML = '' document.querySelector('#pull-request-info').innerHTML = '' try { const pullRequestUrl = new URL( document.querySelector('#pull-request-url').value ) const pullRequestPath = `/repos${pullRequestUrl.pathname.replace( /\/pull\//, '/pulls/' )}` const pullRequest = await fetchGithubApi(pullRequestPath) renderPullRequestInfo(pullRequest) if (pullRequest.state === 'open') { const allComments = await Promise.all([ fetchGithubApi(pullRequest.review_comments_url), fetchGithubApi(pullRequest.comments_url), ]) const uniqueUsersUrls = [ ...new Set( allComments .flat() .filter(comment =&gt; comment.user.login !== pullRequest.user.login) .map(comment =&gt; comment.user.url) ), ] const users = await Promise.all( uniqueUsersUrls.map(uniqueUserUrl =&gt; fetchGithubApi(uniqueUserUrl)) ) renderUsers(users) } else { document.querySelector('#pull-request-url-messages').textContent = 'The pull request is already closed!' } } catch (e) { document.querySelector('#pull-request-url-messages').textContent = e } } document .querySelector('#pull-request-form') .addEventListener('submit', getPullRequestData) </code></pre> <p>And this is the index.html:</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html lang="en"&gt; &lt;head&gt; &lt;meta charset="UTF-8" /&gt; &lt;meta name="viewport" content="width=device-width, initial-scale=1.0" /&gt; &lt;meta http-equiv="X-UA-Compatible" content="ie=edge" /&gt; &lt;title&gt;Pull Request Reviewers&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;header class="container"&gt; &lt;h1&gt;Pull Request Reviewers&lt;/h1&gt; &lt;/header&gt; &lt;main class="container"&gt; &lt;form id="pull-request-form"&gt; &lt;input id="pull-request-url" type="text" placeholder="Enter the full pull request url here" /&gt; &lt;button&gt;Go!&lt;/button&gt; &lt;div id="pull-request-url-messages"&gt;&lt;/div&gt; &lt;/form&gt; &lt;div id="pull-request-info"&gt;&lt;/div&gt; &lt;ul id="user-list"&gt;&lt;/ul&gt; &lt;/main&gt; &lt;script src="index.js"&gt;&lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
[]
[ { "body": "<p>For a framework-less vanilla JS/DOM it's pretty much fine as is.<br>\nI can only suggest a few minor/cosmetic points to consider:</p>\n\n<ul>\n<li>extract things from the big DOM event handler so it contains only the major flow and rename it from <code>getPullRequestData</code> to something else because your function also renders the data but <code>getXXX</code> implies only the action of getting - I would use a generic name like <code>onsubmit</code> since the function isn't reusable and this name tells exactly what it actually is.</li>\n<li>shorten some names because verbosity can make simple things look complicated</li>\n<li>sometimes <code>then</code> + <code>catch</code> may convey the flow better than <code>await</code> + try/catch</li>\n</ul>\n\n<pre><code>function onsubmit(event) {\n event.preventDefault()\n byId('user-list').textContent = ''\n byId('pull-request-info').textContent = ''\n renderStatus('')\n fetchPR()\n .then(async pr =&gt; {\n renderPrInfo(pr)\n renderPrBody(pr.state === 'open' &amp;&amp; await fetchUsers(pr))\n })\n .catch(renderStatus)\n}\n</code></pre>\n\n<ul>\n<li>since you're not writing a low-level library, there should be no need to use createDocumentFragment explicitly, instead just accumulate the elements in an array and pass it to <code>append</code>, which will allow us to express the intent and flow more explicitly:</li>\n</ul>\n\n<pre><code>function renderUsers(users) {\n const ul = byId('user-list')\n const title = createElement('h3', {\n textContent: users.length\n ? 'Reviewers:'\n : 'No reviewers found :(.',\n })\n ul.before(title)\n ul.append(...users.map(renderUser).filter(Boolean))\n}\n</code></pre>\n\n<ul>\n<li>use <code>createElement</code>'s second props parameter more in <code>createUser</code></li>\n<li>add a third parameter <code>children</code> to <code>createElement</code></li>\n<li>use <code>Object.assign</code> in <code>createElement</code></li>\n<li>make <code>createUser</code> return an array so it can be used directly in <code>append</code></li>\n<li>shorten <code>.map(item =&gt; singleArgFunction(item))</code> to <code>.map(singleArgFunction)</code></li>\n<li>add JSDoc comments describing what the function does and its params/returned value, some IDE provide convenient plugins or built-in functionality to simplify the task</li>\n<li>see if you like declaring functions in the order that loosely follows the execution flow from more generalized to more specific</li>\n</ul>\n\n<pre><code>const apiUrl = 'https://api.github.com'\nconst apiOptions = {\n headers: {\n Accept: 'application/vnd.github.v3+json',\n },\n}\n\nbyId('pull-request-form').addEventListener('submit', onsubmit)\n\nfunction onsubmit(event) {\n event.preventDefault()\n byId('user-list').textContent = ''\n byId('pull-request-info').textContent = ''\n renderStatus('')\n fetchPR()\n .then(async pr =&gt; {\n renderPrInfo(pr)\n renderPrBody(pr.state === 'open' &amp;&amp; await fetchUsers(pr))\n })\n .catch(renderStatus)\n}\n\nfunction fetchPR() {\n const { pathname } = new URL(byId('pull-request-url').value)\n const url = `/repos${pathname.replace('/pull/', '/pulls/')}`\n return fetchGithubApi(url)\n}\n\nasync function fetchUsers(pr) {\n const allComments = await Promise.all([\n fetchGithubApi(pr.review_comments_url),\n fetchGithubApi(pr.comments_url),\n ])\n const userUrls = allComments\n .flat()\n .filter(({ user }) =&gt; user.login !== pr.user.login)\n .map(({ user }) =&gt; user.url)\n const uniqUrls = [...new Set(userUrls)]\n return Promise.all(uniqUrls.map(fetchGithubApi))\n}\n\nasync function fetchGithubApi(endpoint) {\n const url = endpoint.startsWith(apiUrl) ? endpoint : `${apiUrl}${endpoint}`\n return (await fetch(url, apiOptions)).json()\n}\n\nfunction renderStatus(status) {\n byId('pull-request-url-messages').textContent = status\n}\n\nfunction renderPrInfo(pr) {\n const title = createElement('a', {\n id: 'title',\n href: pr.html_url,\n textContent: pr.title,\n })\n byId('pull-request-info').append(title, createAvatar(pr.user))\n}\n\nfunction renderPrBody(users) {\n if (users) {\n renderUsers(users)\n } else {\n renderStatus('The pull request is already closed!')\n }\n}\n\nfunction renderUsers(users) {\n const ul = byId('user-list')\n const title = createElement('h3', {\n textContent: users.length\n ? 'Reviewers:'\n : 'No reviewers found :(.',\n })\n ul.before(title)\n ul.append(...users.map(renderUser).filter(Boolean))\n}\n\nfunction renderUser(user) {\n return user.name &amp;&amp; createElement('li', {}, createUser(user))\n}\n\nfunction createUser(user) {\n return [\n createAvatar(user),\n createElement('a', {\n href: user.html_url,\n className: 'login',\n textContent: user.login,\n }),\n user.name &amp;&amp;\n createElement('div', {\n className: 'name',\n textContent: user.name,\n }),\n ].filter(Boolean)\n}\n\nfunction createAvatar(user) {\n return createElement('img', {\n src: user.avatar_url,\n className: 'avatar',\n })\n}\n\nfunction createElement(type, options = {}, children) {\n const element = document.createElement(type)\n Object.assign(element, options)\n if (children) element.append(...children)\n return element\n}\n\nfunction byId(elementId) {\n return document.getElementById(elementId)\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-12T21:39:35.057", "Id": "453502", "Score": "0", "body": "Thanks for taking the time to provide this suggestions, I found them very valuable, I'll be digesting and working on them." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-12T16:15:18.630", "Id": "232260", "ParentId": "232195", "Score": "3" } } ]
{ "AcceptedAnswerId": "232260", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-11T17:06:06.917", "Id": "232195", "Score": "2", "Tags": [ "javascript" ], "Title": "Interface for getting Github PRs commenters using Github API" }
232195
<p>I've the following code working on stackblitz editor as shown in <a href="https://stackblitz.com/edit/react-ts-gsdc4g" rel="nofollow noreferrer">this URL</a>.</p> <p>Right now I have only 2 tabs. Let's say if in future I have 20 tabs, I don't want to have 20 different <code>this.initGrid();</code> for each tabs.Is it possible to create a separate file for first tab(something like <code>firsttab.tsx</code>) , the functionality is defined in <code>private initGrid;</code> and create a second file like <code>secondtab.tsx</code>, the functionality is defined in <code>private initGrid2;</code> so that I can follow the same procedure when I have 20 tabs? Please let me know how to proceed?</p> <p>Here's my complete code inside <code>index.tsx</code>: </p> <pre><code>import React, { Component } from "react"; import { render } from "react-dom"; import "jqwidgets-scripts/jqwidgets/styles/jqx.base.css"; import JqxButton from "jqwidgets-scripts/jqwidgets-react-tsx/jqxbuttons"; import * as ReactDOM from "react-dom"; import JqxWindow from "jqwidgets-scripts/jqwidgets-react-tsx/jqxwindow"; import JqxInput from "jqwidgets-scripts/jqwidgets-react-tsx/jqxinput"; import JqxChart, { IChartProps } from "jqwidgets-scripts/jqwidgets-react-tsx/jqxchart"; import JqxGrid, { IGridProps, jqx } from "jqwidgets-scripts/jqwidgets-react-tsx/jqxgrid"; import JqxTabs from "jqwidgets-scripts/jqwidgets-react-tsx/jqxtabs"; import JqxDropDownList, { IDropDownListProps } from "jqwidgets-scripts/jqwidgets-react-tsx/jqxdropdownlist"; interface AppProps {} interface AppState { name: string; } interface IProps extends IGridProps { rendertoolbar1: IGridProps["rendertoolbar"]; dropdownlistSource: IDropDownListProps["source"]; } class App extends Component&lt;{}, IProps&gt; { private myTabs = React.createRef&lt;JqxTabs&gt;(); private gridElement = React.createRef&lt;HTMLDivElement&gt;(); private gridElementTwo = React.createRef&lt;HTMLDivElement&gt;(); private myGrid = React.createRef&lt;JqxGrid&gt;(); private myGrid2 = React.createRef&lt;JqxGrid&gt;(); private myWindow = React.createRef&lt;JqxWindow&gt;(); private myWindowTWO = React.createRef&lt;JqxWindow&gt;(); private date = React.createRef&lt;JqxInput&gt;(); private sAndP500 = React.createRef&lt;JqxInput&gt;(); constructor(props: {}) { super(props); this.saveBtn = this.saveBtn.bind(this); this.cancelBtn = this.cancelBtn.bind(this); this.saveBtntwo = this.saveBtn.bind(this); this.cancelBtntwo = this.cancelBtn.bind(this); const rendertoolbar = (toolbar: any): void =&gt; { const addRowClick = () =&gt; { //const datarow = this.generaterow(); //this.myGrid.current!.addrow(null, datarow); this.myWindow.current!.open(); }; const addRowClickTwo = () =&gt; { //const datarow = this.generaterow(); //this.myGrid.current!.addrow(null, datarow); this.myWindowTWO.current!.open(); }; ReactDOM.render( &lt;div style={{ margin: "5px" }}&gt; &lt;div id="buttonContainer2" style={{ float: "left", marginLeft: "5px" }} &gt; &lt;JqxButton onClick={addRowClickTwo} width={125} value={"Add New NASDAQ"} /&gt; &lt;/div&gt; &lt;/div&gt;, toolbar[0] ); }; const rendertoolbar1 = (toolbar: any): void =&gt; { const addRowClick = () =&gt; { //const datarow = this.generaterow(); //this.myGrid.current!.addrow(null, datarow); this.myWindow.current!.open(); }; const addRowClickTwo = () =&gt; { //const datarow = this.generaterow(); //this.myGrid.current!.addrow(null, datarow); this.myWindowTWO.current!.open(); }; ReactDOM.render( &lt;div style={{ margin: "5px" }}&gt; &lt;div id="buttonContainer1" style={{ float: "left" }}&gt; &lt;JqxButton onClick={addRowClick} width={135} value={"Add New Us Index"} /&gt; &lt;/div&gt; &lt;/div&gt;, toolbar[0] ); }; this.state = { rendertoolbar, rendertoolbar1, // dropdownlistSource: ["Affogato", "Americano", "Bicerin", "Breve"] dropdownlistSource: [ { value: 0, label: "Affogato" }, { value: 1, label: "Americano" }, { value: 2, label: "Bicerin" }, { value: 3, label: "Breve" } ] //source: new jqx.dataAdapter(source) }; } public render() { return ( &lt;JqxTabs ref={this.myTabs} // @ts-ignore width={400} height={560} initTabContent={this.initWidgets} onSelected={this.onTabSelected} &gt; &lt;JqxWindow ref={this.myWindow} width={250} height={230} resizable={false} isModal={false} autoOpen={false} modalOpacity={"0.01"} position={{ x: 68, y: 368 }} &gt; &lt;div&gt;Add New US Indexes&lt;/div&gt; &lt;div style={{ overflow: "hidden" }}&gt; &lt;table&gt; &lt;tbody&gt; &lt;tr&gt; &lt;td align={"right"}&gt;Date:&lt;/td&gt; &lt;td align={"left"}&gt; &lt;JqxInput ref={this.date} width={150} height={23} /&gt; &lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td align={"right"}&gt;S &amp; P 500:&lt;/td&gt; &lt;td align={"left"}&gt; &lt;JqxInput ref={this.sAndP500} width={150} height={23} /&gt; &lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td align={"right"}&gt;DropDownList:&lt;/td&gt; &lt;td align={"left"}&gt; &lt;JqxDropDownList width={100} height={20} source={this.state.dropdownlistSource} selectedIndex={0} /&gt; &lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td align={"right"} /&gt; &lt;td style={{ paddingTop: "10px" }} align={"right"}&gt; &lt;JqxButton style={{ display: "inline-block", marginRight: "5px" }} onClick={this.saveBtn} width={50} &gt; Save &lt;/JqxButton&gt; &lt;JqxButton style={{ display: "inline-block", marginRight: "5px" }} onClick={this.cancelBtn} width={50} &gt; Cancel &lt;/JqxButton&gt; &lt;/td&gt; &lt;/tr&gt; &lt;/tbody&gt; &lt;/table&gt; &lt;/div&gt; &lt;/JqxWindow&gt; &lt;JqxWindow ref={this.myWindowTWO} width={250} height={230} resizable={false} isModal={false} autoOpen={false} modalOpacity={"0.01"} position={{ x: 68, y: 368 }} &gt; &lt;div&gt;Add New NASDAQ&lt;/div&gt; &lt;div style={{ overflow: "hidden" }}&gt; &lt;table&gt; &lt;tbody&gt; &lt;tr&gt; &lt;td align={"right"}&gt;Date:&lt;/td&gt; &lt;td align={"left"}&gt; &lt;JqxInput ref={this.date} width={150} height={23} /&gt; &lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td align={"right"}&gt;S &amp; P 500:&lt;/td&gt; &lt;td align={"left"}&gt; &lt;JqxInput ref={this.sAndP500} width={150} height={23} /&gt; &lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td align={"right"} /&gt; &lt;td style={{ paddingTop: "10px" }} align={"right"}&gt; &lt;JqxButton style={{ display: "inline-block", marginRight: "5px" }} onClick={this.saveBtntwo} width={50} &gt; Save &lt;/JqxButton&gt; &lt;JqxButton style={{ display: "inline-block", marginRight: "5px" }} onClick={this.cancelBtntwo} width={50} &gt; Cancel &lt;/JqxButton&gt; &lt;/td&gt; &lt;/tr&gt; &lt;/tbody&gt; &lt;/table&gt; &lt;/div&gt; &lt;/JqxWindow&gt; &lt;ul&gt; &lt;li style={{ marginLeft: 30 }}&gt; &lt;div style={{ height: 20, marginTop: 5 }}&gt; &lt;div style={{ float: "left" }}&gt; &lt;img width="16" height="16" src="./../images/catalogicon.png" /&gt; &lt;/div&gt; &lt;div style={{ marginLeft: 4, verticalAlign: "middle", textAlign: "center", float: "left" }} &gt; US Indexes &lt;/div&gt; &lt;/div&gt; &lt;/li&gt; &lt;li&gt; &lt;div style={{ height: 20, marginTop: 5 }}&gt; &lt;div style={{ float: "left" }}&gt; &lt;img width="16" height="16" src="./../images/pieicon.png" /&gt; &lt;/div&gt; &lt;div style={{ marginLeft: 4, verticalAlign: "middle", textAlign: "center", float: "left" }} &gt; NASDAQ compared to S&amp;P 500 &lt;/div&gt; &lt;/div&gt; &lt;/li&gt; &lt;/ul&gt; &lt;div style={{ overflow: "hidden" }}&gt; &lt;div id="jqxGrid" ref={this.gridElement} /&gt; &lt;div style={{ marginTop: 10, height: "15%" }} /&gt; &lt;/div&gt; &lt;div style={{ overflow: "hidden" }}&gt; &lt;div id="jqxGrid2" ref={this.gridElementTwo} /&gt; &lt;div style={{ marginTop: 10, height: "15%" }} /&gt; &lt;/div&gt; &lt;/JqxTabs&gt; ); } private initGrid = () =&gt; { const source = { datafields: [{ name: "Date" }, { name: "S&amp;P 500" }, { name: "NASDAQ" }], datatype: "csv", //url: './assets/nasdaq_vs_sp500.txt' localdata: `1/2/2014,1831.98,4143.07 1/3/2014,1831.37,4131.91 1/6/2014,1826.77,4113.68 1/7/2014,1837.88,4153.18 1/8/2014,1837.49,4165.61 1/9/2014,1838.13,4156.19 1/10/2014,1842.37,4174.67 1/13/2014,1819.2,4113.3 1/14/2014,1838.88,4183.02 1/15/2014,1848.38,4214.88 1/16/2014,1845.89,4218.69 1/17/2014,1838.7,4197.58 1/21/2014,1843.8,4225.76 1/22/2014,1844.86,4243 1/23/2014,1828.46,4218.88 1/24/2014,1790.29,4128.17 1/27/2014,1781.56,4083.61 1/28/2014,1792.5,4097.96 1/29/2014,1774.2,4051.43 1/30/2014,1794.19,4123.13 1/31/2014,1782.59,4103.88 2/3/2014,1741.89,3996.96 2/4/2014,1755.2,4031.52 2/5/2014,1751.64,4011.55 2/6/2014,1773.43,4057.12 2/7/2014,1797.02,4125.86` }; const dataAdapter = new jqx.dataAdapter(source, { async: false, loadError: (xhr: any, status: any, error: any) =&gt; { console.log(xhr, status, error); //alert('Error loading "' + source.url + '" : ' + error); } }); const columns: IGridProps["columns"] = [ { cellsformat: "d", datafield: "Date", text: "Date", width: 250 }, { datafield: "S&amp;P 500", text: "S&amp;P 500", width: 150 }, { datafield: "NASDAQ", text: "NASDAQ" } ]; const grid = ( &lt;JqxGrid ref={this.myGrid} width={"100%"} height={400} source={dataAdapter} columns={columns} showtoolbar={true} rendertoolbar={this.state.rendertoolbar1} /&gt; ); render(grid, this.gridElement.current!); }; private saveBtn(): void { this.myWindow.current!.hide(); } private cancelBtn(): void { this.myWindow.current!.hide(); } private initGrid2 = () =&gt; { const source = { datafields: [{ name: "Date" }, { name: "S&amp;P 500" }, { name: "NASDAQ" }], datatype: "csv", //url: './assets/nasdaq_vs_sp500.txt' localdata: `1/2/2014,1831.98,4143.07 1/3/2014,1831.37,4131.91 1/6/2014,1826.77,4113.68 1/7/2014,1837.88,4153.18 1/8/2014,1837.49,4165.61 1/9/2014,1838.13,4156.19 1/10/2014,1842.37,4174.67 1/13/2014,1819.2,4113.3 1/14/2014,1838.88,4183.02 1/15/2014,1848.38,4214.88 1/16/2014,1845.89,4218.69 1/17/2014,1838.7,4197.58 1/21/2014,1843.8,4225.76 1/22/2014,1844.86,4243 1/23/2014,1828.46,4218.88 1/24/2014,1790.29,4128.17 1/27/2014,1781.56,4083.61 1/28/2014,1792.5,4097.96 1/29/2014,1774.2,4051.43 1/30/2014,1794.19,4123.13 1/31/2014,1782.59,4103.88 2/3/2014,1741.89,3996.96 2/4/2014,1755.2,4031.52 2/5/2014,1751.64,4011.55 2/6/2014,1773.43,4057.12 2/7/2014,1797.02,4125.86` }; const dataAdapter = new jqx.dataAdapter(source, { async: false, loadError: (xhr: any, status: any, error: any) =&gt; { console.log(xhr, status, error); //alert('Error loading "' + source.url + '" : ' + error); } }); const columns: IGridProps["columns"] = [ { cellsformat: "d", datafield: "Date", text: "Date", width: 250 }, { datafield: "S&amp;P 500", text: "S&amp;P 500", width: 150 }, { datafield: "NASDAQ", text: "NASDAQ" } ]; const grid = ( &lt;JqxGrid ref={this.myGrid2} width={"100%"} height={400} source={dataAdapter} columns={columns} showtoolbar={true} rendertoolbar={this.state.rendertoolbar} /&gt; ); render(grid, this.gridElementTwo.current!); }; private saveBtntwo(): void { this.myWindowTWO.current!.hide(); } private cancelBtntwo(): void { this.myWindowTWO.current!.hide(); } private initWidgets = (tab: any) =&gt; { switch (tab) { case 0: this.initGrid(); break; case 1: this.initGrid2(); break; } }; private onTabSelected = (event: any) =&gt; { switch (event.args.item) { case 0: // this.hideButton(); break; case 1: // this.showButton(); break; } }; } render(&lt;App /&gt;, document.getElementById("root")); </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-12T14:11:19.907", "Id": "453418", "Score": "0", "body": "To close voters, please comment. This is working, complete code to me." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-12T14:55:44.103", "Id": "453420", "Score": "0", "body": "@konijn I believe in this forum, code is supposed to work for everyone. My question is about refactoring." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-12T15:28:02.923", "Id": "453428", "Score": "0", "body": "This question has 3 close votes and no comments from the close voters, I was trying to figure out what triggered those votes and prevent any 'off topic close votes'" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-11T17:58:47.667", "Id": "232197", "Score": "2", "Tags": [ "javascript", "react.js" ], "Title": "Move the contents of two tabs into two separate files and import two files into index.tsx" }
232197
<p>I know there is this thing called "Eratosthenes" but that requires the allocation of a large array while I want to find (small) prime numbers fast, yet without needing too much memory. So I wrote PrimeTable.cs with this content:</p> <pre><code>using System; using System.Collections.Generic; using System.Linq; namespace Primes { public static class PrimeTable { private static readonly List&lt;long&gt; PrimeNumbers = new List&lt;long&gt;(); public static long MaxValue { get; private set; } = 1; public static bool IsPrime(this long value) { if (value &gt; MaxValue) { var longCount = Primes(true).TakeWhile(p =&gt; p &lt;= value).LongCount(); } return PrimeNumbers.Contains(value); } public static long IndexOfPrime(this long value) =&gt; IsPrime(value) ? Primes().TakeWhile(p =&gt; p &lt; value).LongCount() : -1; public static long NextPrime(this long value) =&gt; Primes().First(p =&gt; p &gt; value); public static long PreviousPrime(this long value) =&gt; Primes().TakeWhile(p =&gt; p &lt; value).LastOrDefault(); public static IEnumerable&lt;long&gt; Primes(bool skipLast = false) { if (!skipLast) foreach (var l in PrimeNumbers) { yield return l; } while (MaxValue &lt; long.MaxValue) { var max = (int)Math.Sqrt(++MaxValue); if (PrimeNumbers.Where(p =&gt; p &lt;= max).All(p =&gt; MaxValue % p != 0)) { PrimeNumbers.Add(MaxValue); yield return MaxValue; } } } } } </code></pre> <p>The reason for this is because I want to stop looking after a certain value has been found. This is mere practice of my skills in enumerations and extension methods and I'm trying to be a bit creative. </p> <p>So when I ask <code>11L.IsPrime()</code> it will be true while <code>99L.IsPrime()</code> will be false. But it won't calculate prime numbers over 11 until I ask if 99L is a prime. Then it won't go past 99. This keeps the number of calculations to a minimum. </p> <p>The Primes() method is an enumerator that will basically continue calculating nearly forever and would thus take a while if I wasn't using deferred execution. But because of deferred execution, I can just stop enumerating at any moment and later continue the enumeration as it already knows the values it has had. </p> <p>The IsPrime() is what I want to use in general, to check if a number is a prime or not. To do so, it needs to make sure it has calculated all primes up to the given number and if not, just calculate the remaining primes. It skips the primes it already knows but I have to find a better way to aggregate the enumeration as without the LongCount() in the end, it won't enumerate. It's deferred execution, after all. So, is there a better way to aggregate here?<br> I can't just use <code>return Primes().Contains(value);</code> as it would run almost forever when checking 99L. </p> <p>The IndexOfPrime() will tell me the index of a prime number or -1 if it's not a prime. </p> <p>The NextPrime() method is interesting, though. It will tell me the first prime number after a given value.<br> The PreviousPrime() method is trickier as I can't just ask for the last item less than value. It would enumerate nearly forever again. </p> <p>The MaxValue field is just for debugging purposes so you can asl how far it has goine while enumerating...</p> <p>The next challenge: can this be improved by using PLinq? If so, how? </p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-11T18:06:21.327", "Id": "453286", "Score": "2", "body": "_\"I know there is this thing called \"Eratosthenes\"\"_ It's called the _Sieve of Eratosthenes_ to be precise. Eratosthenes was an ancient Greek philosopher and mathematician." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-11T18:09:17.223", "Id": "453287", "Score": "0", "body": "@πάνταῥεῖ Yeah, I know. :) I've implemented a variant of that also but as I said, it eats up a lot of memory. You need to allocate a large array and scratch all multiples of prime values found. But allocating an array for long.MaxValue items is just not done..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-11T18:12:36.270", "Id": "453290", "Score": "2", "body": "A packed bitset would be enough, and won't need to allocate that much memory. You only need to know `true` or `false` at specific positions." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-11T18:35:59.667", "Id": "453299", "Score": "0", "body": "See [here](https://docs.microsoft.com/en-us/dotnet/api/system.collections.bitarray?view=netframework-4.8) for more information." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-11T18:38:17.500", "Id": "453300", "Score": "3", "body": "You want to test primes up to `Long.MaxValue`? According to WolframAlpha there are about 2.11214×10^17 primes under this value, which would take \n1.6897×10^9 GB of RAM to store `long`, where you'd need 1.153×10^9 GB for the equivalent sieve. Maybe you didn't implement the sieve correctly?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-11T19:13:39.223", "Id": "453310", "Score": "0", "body": "@πάνταῥεῖ A packed bitset for long.MaxValue values would still be huge. And while I don't want to go that high, using the sieve method would still eat up a huge amount of bits and I would have to change a whole lot of bits for every prime found. Yes, I would need a lot of memory if I ever get that high. But this way, I don't have to set billions of flags to false every time. It calculates step by step." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-11T20:59:42.193", "Id": "453322", "Score": "2", "body": "I think worrying about 64 bit primes is overly ambitious here because you will run out of memory well before you get near Int32.MaxValue, let alone Int64.MaxValue. And performance will degrade dramatically and specifically due to LINQ enumerations such as `PrimeNumbers.Where(p => p <= max).All(p => MaxValue % p != 0)`, again well before you hit Int32.MaxValue." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-11T21:04:00.650", "Id": "453323", "Score": "1", "body": "This [link](https://codereview.stackexchange.com/questions/104736/sieve32fastv2-a-fast-parallel-sieve-of-eratosthenes) Sieve32FastV2 will sieve all `UInt32` primes in about 40 seconds and use under 300 MB memory." } ]
[ { "body": "<p>There are many, many problems with this implementation, but they pretty much all come down to two major problems: first, you do a linear-time operation when a constant-time or log-time operation would suffice, and second, your code is chock-full of expressions that are useful for both their values and their side effects, which makes for code that is confusing.</p>\n\n<pre><code>return PrimeNumbers.Contains(value);\n</code></pre>\n\n<p><code>PrimeNumbers</code> is a sorted list, but you check to see if a value is in it by starting from the beginning and searching every element in it. Do a binary search.</p>\n\n<pre><code>public static long IndexOfPrime(this long value) =&gt; \n IsPrime(value) ? Primes().TakeWhile(p =&gt; p &lt; value).LongCount() : -1;\n</code></pre>\n\n<p>This is bizarre. You use <code>IsPrime</code> for its side effect, and then do a linear search of the primes <em>in a list</em> to get their index. <strong>You have a list</strong>. Just search the list for the index!</p>\n\n<p>This was a good attempt but it has turned into an object lesson in what not to do. <strong>The fundamental strategy here is very sound and you should keep it</strong>, but the details around that strategy are confusing and inefficient. This is not a good use of LINQ.</p>\n\n<p>What I would do here is refactor the program so that it does a smaller number of things and does them better. For example, suppose instead of this business of constantly enumerating <code>Primes</code>, you instead made two methods:</p>\n\n<ul>\n<li><code>EnsureUpTo(n)</code> -- makes sure that the list is filled in up to <code>n</code>.</li>\n<li><code>NearestIndexOf(n)</code> -- uses an <strong>efficient</strong> search to return the index of <code>n</code>, or, if <code>n</code> is not prime, the index of the nearest prime to <code>n</code>.</li>\n<li><code>Prime(i)</code> returns the <code>i</code>th prime.</li>\n</ul>\n\n<p>From this simple interface you can answer all your questions:</p>\n\n<ul>\n<li><p>You can determine if <code>n</code> is a prime by running <code>EnsureUpTo(n)</code> and then <code>i = NearestIndex(n)</code> and then <code>m = Prime(i)</code>. If <code>n == m</code> then <code>n</code> is prime, otherwise it is composite.</p></li>\n<li><p>You can get the next or previous prime similarly; run <code>i = NearestIndex(n)</code> and then <code>Prime(i-1)</code> and <code>Prime(i+1)</code> are the next and previous. </p></li>\n</ul>\n\n<hr>\n\n<p>Your routine for computing primes you don't already know also could use some work:</p>\n\n<pre><code> var max = (int)Math.Sqrt(++MaxValue);\n</code></pre>\n\n<p>A number of problems here. Computing square roots is expensive; it is always better to do <code>p * p &lt;= m</code> than <code>p &lt;= Sqrt(m)</code>.</p>\n\n<p>The increment is also suspicious. Fully half the time you will be incrementing it to an even number! After you are at 3, increment it by 2. Or, even better, notice that once you are above 5, you can pick any six numbers in order and at most two of them will be prime. That is, of 5, 6, 7, 8, 9 and 10 we know that 6, 8 and 10 are divisible by 2. We know that 6 and 9 are divisible by 3, so we only need to check 5 and 7. But that also goes for 11, 12, 13, 14, 15, 16: 12, 14, 15 and 16 cannot be prime, so we only have to check 11 and 13. And then 17, 18, 19, 20, 21, 22 we only check 17 and 19. And so on.</p>\n\n<p>So what you can do is increment <code>MaxValue</code> by 6 every time after you get to 5, and then check MaxValue and MaxValue + 2 for primality, and you do much less work.</p>\n\n<pre><code>if (PrimeNumbers.Where(p =&gt; p &lt;= max).All(p =&gt; MaxValue % p != 0))\n</code></pre>\n\n<p>Again, this is <strong>really bad</strong> because <strong>LINQ does not know that the list is sorted</strong>. You check the <em>entire</em> list, which is O(n) in the size of the list, for elements smaller than <code>max</code>, but you could be bailing out once you get to the first that is larger than <code>max</code>. <code>Where</code> is not the right sequence operator here. You want <code>Until(p =&gt; p &gt; max)</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-12T03:28:57.913", "Id": "453353", "Score": "0", "body": "Good points! You're right, an EnsureUpTo() method would be better. As for the list being sorted... I had not really considered that, as it's a side effect. A binary search would indeed be better. But a SortedList<> requires a key and value, so maybe I need a SortedSet for Primes?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-12T18:58:59.293", "Id": "453477", "Score": "0", "body": "@WimtenBrink: A sorted `List<T>` of primes is fine. `BinarySearch` is a member of `List<T>`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-12T19:03:05.120", "Id": "453479", "Score": "2", "body": "@WimtenBrink: A `SortedList` maintains the sort property for you, but you don't need that; you are already ensuring that the list is always sorted by only appending larger items after smaller." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-12T19:45:20.063", "Id": "453491", "Score": "0", "body": "But it would mean implementing my own binary search. Done that a gazillion times already so I rather reuse an existing one. The SortedSet might be an option..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-12T19:52:47.793", "Id": "453493", "Score": "2", "body": "@WimtenBrink: `List<T>` has a binary search method on it. https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1.binarysearch?view=netframework-4.8" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-11T23:33:44.927", "Id": "232218", "ParentId": "232198", "Score": "10" } }, { "body": "<p>I have never seen a post proclaiming “optimized for speed” that uses so much LINQ enumeration. There might be a good reason for that. Don’t get me wrong. I like LINQ. It has nice syntactic sugar but is not known for being highly performant.</p>\n\n<p>I have run some performance tests with your code, so let’s understand my test machine: CPU is an Intel I7-6700 with 4 cores/8 logical processors at 3.40 Ghz, 16GB RAM, .NET Framework 4.8, and Visual Studio 2019. What happens when I run:</p>\n\n<pre><code>var number = 10_000_000;\n\nvar sw = new Stopwatch();\nvar flag = PrimeTable.IsPrime(number);\nsw.Stop();\n\nConsole.WriteLine($\"Number: {number}, IsPrime: {flag}, Elapsed: {sw.Elapsed}\");\n</code></pre>\n\n<p>Your code, supposedly “optimized for speed” returns:</p>\n\n<pre><code>Number: 10000000, IsPrime: False, Elapsed: 00:14:50.8241307\n</code></pre>\n\n<p><strong>ALMOST 15 MINUTES?!</strong> Which makes me wonder: did you even test your own code? If you did not bother, but rather just felt in your mind that it should be fast, then SHAME ON YOU. But if you did performance tests, and walked away thinking it was fast, then SHAME ON YOU 1000 TIMES.</p>\n\n<p>The biggest disconnect I see with your code come from your first sentence, which ends with</p>\n\n<blockquote>\n <p>I want to find (small) prime numbers fast, yet without needing too\n much memory.</p>\n</blockquote>\n\n<p>You never bother to define <strong>small</strong>. Is it 1000, 100_000, or 1 million? What is <strong>small</strong> in your mind? You never define it and yet you then use (A) performance dragging LINQ enumerations, and (B) memory consuming List for the <code>PrimeTable</code> both of which are in conflict with your stated objectives.</p>\n\n<p>(As an aside, if you want something small, one can use a very fast, small sieve of Eratosthenes, say of with an upper limit of 1 or 10 million. On my machine, it took a sieve 0.13 seconds (not 15 minutes) to generate the sieve for 10 million and return a fully populated list of primes. That is small, fast, and uses limited memory. The downside is that is does not grow. I am pondering making a sieve that can expand on-demand but that’s a topic for another day.)</p>\n\n<p>When working with sets of primes, generally there are 2 ways to proceed. Either you keep a table of the known primes, or you keep a table of all numbers (usually only the odds) with a flag to denote prime or not. Both come with their own set of advantages and disadvantages. After you weigh your objectives over the advantages/disadvantages, you then pick your poison, and should try to provide a practical solution. You chose a prime table.</p>\n\n<p>Your <code>PrimeTable</code> seems to be unbounded, other than it would be limited by <code>Int64.MaxValue</code>. Except it’s really constrained earlier in that the index to <code>PrimeTable</code> is limited to <code>Int32.MaxValue</code>. On a more practical level, you are limited further in .NET’s memory usage. On my machine, I can have <code>List&lt;Int64&gt;</code> of <code>134_217_728</code> primes before throwing a memory error. Consider further:</p>\n\n<p>For 31 bit primes, that is all of <code>Int32</code>, there will be <code>105_097_565</code> primes and the last known prime is <code>2_147_483_647</code>. For 32 bit primes, that is all of <code>UInt32</code>, there will be <code>203_280_221</code> primes and the last known prime is <code>4_294_967_291</code>. I got this from using a sieve. Granted it takes less than 45 seconds to generate the entire sieve, which you may scoff at, but then again it took 15 minutes for yours to tell me that 10 million is not a prime.</p>\n\n<p>If you defined your <code>PrimeTable</code> to be a <code>List&lt;UInt32&gt;</code>, you could hold all <code>203_280_221</code> primes in memory. Granted it may take months for your app to find them all.</p>\n\n<p>On to other topics, I don’t like the static property named <code>MaxValue</code>. There is no written standard, but generally when I see a property named <code>MaxValue</code>, I tend to think of it as a value that never changes. You state that it’s only for debugging, but some very critical logic for producing primes depends on it.</p>\n\n<p><strong>Suggestions for improvement</strong></p>\n\n<p>Follow Eric Lippert's advice to use an efficient search instead of performance killing LINQ enumerations.</p>\n\n<p>I would suggest starting out practical with <code>Int32</code> instead of <code>Int64</code>. However, since I am working with your current code, I am using <code>long</code> below.</p>\n\n<p>At the very least, I would initialize <code>PrimeTable</code> to be:</p>\n\n<pre><code>private static readonly List&lt;long&gt; PrimeNumbers = new List&lt;long&gt;() { 2 };\n</code></pre>\n\n<p>But why stop there? Why not start it with:</p>\n\n<pre><code>private static readonly List&lt;long&gt; PrimeNumbers = new List&lt;long&gt;() { 2, 3, 5, 7, 11, 13, 17, 19 };\n</code></pre>\n\n<p>Once you do that, you can add 2 very nice properties:</p>\n\n<pre><code>public static int KnownPrimeCount =&gt; PrimeNumbers.Count;\npublic static long LargestKnownPrime =&gt; PrimeNumbers.Last();\n</code></pre>\n\n<p>And maybe <code>LargestKnownPrime</code> can make <code>MaxValue</code> go away.</p>\n\n<p>Another suggestion is that since you have a list in memory, why not expose that to the user? Perhaps:</p>\n\n<pre><code>public static IReadOnlyList&lt;long&gt; KnownPrimes =&gt; PrimeNumbers;\n</code></pre>\n\n<p><strong>IsPrime – Horrible Implementation</strong></p>\n\n<p>As shown above, it took almost 15 minutes to determine that 10 million is not a prime. Let’s start out with a couple of quick improvements for the very top of IsPrime:</p>\n\n<pre><code>if (value &lt; 2) { return false; }\nif (value % 2 == 0) { return value == 2; }\n</code></pre>\n\n<p>The performance still is bad if I were to use 10_000_001. The problem is that checking an individual number for primality is a very different task than generating a list of a whole bunch of primes. There is no need to use to <code>PrimeTable</code> just to determine primality, but since you have it, you could use it. But I would use it as-is and not try to grow the table.</p>\n\n<pre><code>public static bool IsPrime(this long value)\n{\n if (value &lt; 2) { return false; }\n if (value % 2 == 0) { return value == 2; }\n if (value &lt;= LargestKnownPrime)\n {\n // determine using fast lookup to PrimeTable\n return from_table_via_fast_lookup;\n }\n // compute without modifying PrimeTable\n // https://codereview.stackexchange.com/questions/196196/get-prime-divisors-of-an-int32-using-a-wheel\n // https://codereview.stackexchange.com/questions/92575/optimized-ulong-prime-test-using-6k-1-in-parallel-threads-with-c\n return something;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-16T16:49:21.463", "Id": "454049", "Score": "0", "body": "I did say \"ENUMERATION optimized for speed\". I want a list of prime numbers to be generated on the fly, if need be. Using a sieve would be faster, but would require the allocation of a huge amount of data. I need something to walk through. Something that can be part of a method chain combined with Skip() and Take() to show pages of primes." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-16T16:50:27.027", "Id": "454050", "Score": "0", "body": "You also miss the fact that I used a long, not int. A long is an int64 value! I could have used uint64 instead but your suggestion to replace long with uint32 makes no sense. I'd be using a smaller data type." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-16T15:29:32.477", "Id": "232504", "ParentId": "232198", "Score": "1" } }, { "body": "<p>I was hoping to see you come out with an improved Version 2 with a new posting. I began to write some code for an answer to you, but that code diverged so much from your original that it warrants being its own post for review:</p>\n\n<p><a href=\"https://codereview.stackexchange.com/questions/233209/prime-number-table-i-e-listint/233590#233590\">Prime Number Table, i.e. List&lt;int&gt;</a></p>\n\n<p>This is similar to yours, was inspired by yours, but eventually has different goals and objectives than yours. A least one goal we have in common is a desire to provide a many primes quickly to a consumer.</p>\n\n<p>I do use a faster lookup to index, which was highly recommended to you.</p>\n\n<p>I also expose the table to the consumer as a readonly list. For all the time, energy, and memory you use to build this table, I see no reason to hide it away.</p>\n\n<p>My implementation doesn't carry the same side effects as yours, but again this is a design decision (our different goals) in that I restrict any methods using the index to the known primes, i.e. those already in my table. I do not look past or add to the known primes on many calls. </p>\n\n<p>Where we absolutely differ is that I use a sieve to initialize my prime table. For most responsiveness in an app, I use time rather than prime count as the driving factor. The sieve is temporary, creates the prime table, and its memory returned to later be GC'ed. And it is much, much faster than generating primes using naive methods.</p>\n\n<p>You take some issue with sieves due to allocation. I would ask you to instead look at it with an open mind and an opportunity to learn new things. </p>\n\n<p>Let's compare the memory used by a sieve versus a <code>List&lt;int&gt;</code> along with an upperLimit of 10 million. There are <code>664_579</code> primes in that list. This requires <code>2_658_316</code> bytes.</p>\n\n<p>If one use a <code>bool[]</code> and only used odd numbers, the array would need <code>5_000_001</code> items, and each item is a byte. This is almost twice the size of the <code>List&lt;int&gt;</code>.</p>\n\n<p>However, I do not use a <code>bool[]</code> but instead use a <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.collections.bitarray?view=netframework-4.8\" rel=\"nofollow noreferrer\">Systems.Collection.BitArray</a>. Here each odd number is only 1 bit. Note the underlying values in a bit array are provided by an <code>int</code>, where a single <code>int</code> provides 32 bits. Thus my <code>BitArray</code> of <code>5_000_001</code> bits requires <code>156_282</code> integers, or <code>625_128</code> bytes. Thus my <code>BitArray</code> is 0.25 the size of the <code>List&lt;int&gt;</code>. </p>\n\n<p>So I can prove that <a href=\"https://codereview.stackexchange.com/a/233590/54031\">sieve is much faster</a> than your naive methods, and a sieve with a <code>BitArray</code> uses less memory than a `List'. </p>\n\n<p>I would encourage to try an improved implementation of your own and would welcome a chance to see and review it.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-04T18:56:00.110", "Id": "459916", "Score": "0", "body": "Yeah, I know the bitarray. And I understand the sieve. But I'm mostly interested in the lower prime numbers while still being able to get the higher values. But more importantly, I want to have an enumerator that returns me prime numbers as soon as it has calculated them." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-04T19:00:05.740", "Id": "459917", "Score": "0", "body": "The problem with a sieve of 1 million entries is that you have to go through it for every found prime. So first 500,000 times for multiples of 2, then 333,333 times for multiples of 3, 200,000 for multiples of 5, etc. So it's slow for lower primes but fast for higher ones. Basically, I should use the sieve only once I get past a certain threshold and expand the sieve regularly. So 1 million, 2 million, 5 million, 10 million, etc." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-07T14:14:43.603", "Id": "233592", "ParentId": "232198", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-11T18:01:37.333", "Id": "232198", "Score": "3", "Tags": [ "c#", "performance", "primes" ], "Title": "A prime numbers enumeration optimized for speed" }
232198
<p>I am trying to get all image urls which are valid and unique.To make sure i wont end up using the same image again i calculate hash of the image and store it in a text file and read the text file again.if there is any better way to do this, please let me know.Overall any speed optimisation would be really helpful, thanks in advance.</p> <pre><code>import multiprocessing as mp import socket # Set the default timeout in seconds timeout = 20 socket.setdefaulttimeout(timeout) from PIL import Image import hashlib import os import pickle def getImages(val): # import pdb;pdb.set_trace() #Dowload images f = open('image_files.txt', 'a') k = open('image_hash.txt', 'a') try: url=val # preprocess the url from the input val local=url.split('/')[-1] #Filename Generation From Global Varables And Rand Stuffs... urllib.request.urlretrieve(url,local) md5hash = hashlib.md5(Image.open(local).tobytes()) image_hash = md5hash.hexdigest() k.write(image_hash+'\n') z = open('image_hash.txt', 'r') a = z.readlines() image_hash_list = [c.strip('\n') for c in a] if image_hash not in image_hash_list: os.remove(local) f.write(url+'\n') print("DONE - " + url) return 1 else: os.remove(local) except Exception as e: # print(e) print("CAN'T DOWNLOAD - " + url ) return 0 files = "Identity.txt" lst = list(open(files)) lst = [l.replace("\n", "") for l in lst] lst = lst[::-1] pool = mp.Pool(processes=12) res = pool.map(getImages, lst) print ("tempw") </code></pre> <p>Here identity.txt file looks like this,</p> <pre class="lang-none prettyprint-override"><code>http://url1.com http://url2.com ... </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-11T19:28:33.880", "Id": "453318", "Score": "0", "body": "1) what is the point of `if image_hash not in image_hash_list:` condition? since you inevitably write `image_hash` into `'image_hash.txt'`, then - read from it and it will be there; 2) why not check if `url` is already in `'image_files.txt'` beforehand ? 3) how does `\"Identity.txt\"` look like?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-12T05:27:39.340", "Id": "453361", "Score": "0", "body": "nice catch, fixed it locally, identity.txt is a text file with all urls with duplicates and junk data" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-12T05:36:04.497", "Id": "453363", "Score": "0", "body": "Consider storing your hashes in an sqlite3 database instead of a flat file. This is typically a more efficient and fast method of storing/retrieving data." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-12T07:56:08.437", "Id": "453372", "Score": "0", "body": "@Ryan, considering the above comments, would you mind to update your question (as you mentioned *\" fixed it locally\"*) and post a short fragment of `Identity.txt` ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-12T08:56:54.150", "Id": "453381", "Score": "0", "body": "@RomanPerekhrest Hey i have made required edits.Thanks." } ]
[ { "body": "<p>here's a few comments in no particular order.</p>\n\n<p>Have a look over PEP8. It's Python's style guide which helps keep Python code consistent and readable. Things like naming functions which <code>snake_case</code>, constants as <code>CAPS</code>, proper spacing around operators, commenting style and placement, spacing between imports, etc.</p>\n\n<p>It's recommended to use a context manager for opening files, this prevents them from being left open and the indentation makes it clear when a file is being used. You can open two files at once like so:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>with open('file_one.txt', 'a') as file_one, open('file_two.txt', 'a') as file_two:\n ...\n</code></pre>\n\n<p>Instead of using <code>return</code> to handle errors, just raise the error itself. Catch the specific exception (ValueError, TypeError, etc (<em>not</em> <code>Exception</code> or worse <code>BaseException</code>)) then raise it with a message like so:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>except TypeError:\n raise TypeError('Reason for failure message')\n</code></pre>\n\n<p>If you want to continue having caught the error, you can print the error message and continue instead:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>except TypeError as exc:\n print(f'Reason for failure: {exc}; continuing ...')\n</code></pre>\n\n<p>A better way of storing lines from a file to a list would be to use <code>readlines()</code> and <code>strip()</code>. <code>readlines()</code> converts a file to a list where each item is a line in the file, and <code>strip()</code> can remove unwanted linebreaks and whitespace.</p>\n\n<p>Wrap the code you're going to run with:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>if __name__ == '__main__':\n ...\n</code></pre>\n\n<p>This stops any old code being executed if importing it as a module.</p>\n\n<p>Why do you take <code>val</code> as an argument then immediately rename it to <code>url</code>? Just take <code>url</code> as the argument, it's more descriptive. You've also used <code>url</code> in your except block where it may not have been defined. It wouldn't fail in this example but it could have done if you wrote code like this elsewhere.</p>\n\n<p>Your variable names could be much improved. No single letter variables! Make them descriptive and avoid putting their type in the name. <code>k</code> -> <code>hash_file</code>; <code>image_hash_list</code> -> <code>image_hashes</code>; etc.</p>\n\n<p>You're importing <code>pickle</code> but not using it. You're also using <code>urllib</code> without importing it.</p>\n\n<p>You're calling <code>os.remove(local)</code> regardless of the if condition. Put this outside the if check.</p>\n\n<p>There are a few other nitpicks and I can't speak to what the code is actually doing as it's not something I'm familiar with, but I hope that helps.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-12T11:36:39.037", "Id": "232241", "ParentId": "232200", "Score": "3" } }, { "body": "<p>You should split your function up into smaller pieces. This way it gets a lot easier to reason about them individually, and to change them if needed.</p>\n\n<p>You don't really need the <code>image_hash.txt</code> file, unless your number of URLs is more than a million or so. But if that is the case, you are probably better off using a database for this.</p>\n\n<p>Since you are running this in parallel, your output is not deterministic. For two URLs pointing to the same image, the one that is determined to be the \"true\" URL depends on which is checked first, which may vary from run to run. This just sounds like bad design. Instead, just group image URLs by their image hashes. I opted to return the class name of the exception for invalid URLs, so you can find all of those grouped together as well (and still debug it if you have a <code>NameError</code> or <code>TypeError</code> somewhere in your code).</p>\n\n<p>Instead of getting the filename from the URL and saving to that file, I would just keep the image in memory. This should be a lot faster than writing it to disk, just to immediately read it again for the hashing. Note that if a link to a very large file is passed, this might fill up your RAM (but it would also fill your disk in that case, and for RAM at least the process will be automatically killed by the OS, whereas for disk you won't notice until it is too late and have to do it manually). Fortunately <code>PIL.Image.open</code> can directly deal with a <code>io.BytesIO</code> object, so we don't need to do anything fancy. If you need to check images larger than your RAM, have a look at a previous revision of this answer, where I used a <code>tempfile.SpooledTemporaryFile</code> which gets written to disk in that case.</p>\n\n<p>I personally prefer <code>requests</code> over <code>urllib</code>, since it covers all of the basic usage. Including raising an error if the connection fails, following redirects, etc.</p>\n\n<pre><code>from collections import defaultdict\nimport hashlib\nimport io\nfrom itertools import tee\nimport multiprocessing\nfrom PIL import Image\nimport requests\n\n\ndef get_hash(file):\n md5hash = hashlib.md5(Image.open(file).tobytes())\n return md5hash.hexdigest()\n\ndef process_url(url):\n try:\n r = requests.get(url, allow_redirects=True)\n r.raise_for_status()\n return get_hash(io.BytesIO(r.content))\n except Exception as e:\n return type(e).__name__\n\ndef get_urls(file_name):\n with open(file_name) as f:\n return {line.strip() for line in f}\n\ndef get_hashes(urls):\n n = multiprocessing.cpu_count() - 1\n with multiprocessing.Pool(processes=n) as pool:\n return pool.map(process_url, urls)\n\ndef invert_dict(d):\n d2 = defaultdict(set)\n for key, value in d.items():\n d2[value].add(key)\n return dict(d2)\n\ndef main():\n urls = get_urls('image_files.txt')\n hashes = dict(zip(urls, get_hashes(urls)))\n groups = invert_dict(hashes)\n print(groups)\n\nif __name__ == \"__main__\":\n main()\n</code></pre>\n\n<p>For a file containing the following lines (our two avatars, yours with a slightly different URL as well, and mine with a misspelled URL), the result is as expected:</p>\n\n<pre><code>https://www.gravatar.com/avatar/8d627cb69cbceed874a485cd7cb3fa86?s=328&amp;d=identicon&amp;r=PG&amp;f=1\nhttps://www.gravatar.com/avatar/8d627cb69cbceed874a485cd7cb3fa86?s=328&amp;d=identicon&amp;r=PG\nhttps://www.gravatar.com/avatar/b869ca5adc52b16ef56ab1fb6ed5fe97?s=328&amp;d=identicon&amp;r=PG\nhttps://www.avatar.com/avatar/b869ca5adc52b16ef56ab1fb6ed5fe97?s=328&amp;d=identicon&amp;r=PG\n</code></pre>\n\n\n\n<pre><code>{'242edcfd4ee09f9d734497a32c04fc06': {'https://www.gravatar.com/avatar/8d627cb69cbceed874a485cd7cb3fa86?s=328&amp;d=identicon&amp;r=PG&amp;f=1', \n 'https://www.gravatar.com/avatar/8d627cb69cbceed874a485cd7cb3fa86?s=328&amp;d=identicon&amp;r=PG'},\n '3b7e2db9a0246462880635b9eeef45f3': {'https://www.gravatar.com/avatar/b869ca5adc52b16ef56ab1fb6ed5fe97?s=328&amp;d=identicon&amp;r=PG'},\n 'OSError': {'https://www.avatar.com/avatar/b869ca5adc52b16ef56ab1fb6ed5fe97?s=328&amp;d=identicon&amp;r=PG'}}\n</code></pre>\n\n<p>This even has both the forward and backward dictionaries around for later, so if you need the hash of a URL, or the URL(s) of a hash, you can get both. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-12T13:40:58.727", "Id": "232247", "ParentId": "232200", "Score": "3" } } ]
{ "AcceptedAnswerId": "232247", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-11T18:16:22.363", "Id": "232200", "Score": "2", "Tags": [ "python", "performance", "multiprocessing" ], "Title": "hash image url and if valid store image url" }
232200
<p>So, few months ago I did a HackerRank test for a company. The problem was to create a function which receive a list of names and returns a list of unique usernames. For example: </p> <p>For the list of <code>names = ['john', 'john', 'tom', 'john']</code><br> The function must return: <code>= ['john', 'john1', 'tom', 'john2']</code></p> <p>My code was: </p> <pre><code>def username_system(u, memo={}, users=[]): copy_u = u.copy() try: name = copy_u[0] except IndexError: return users if name in memo.keys(): memo[name] += 1 username = name + str(memo[name]) users.append(username) copy_u.remove(name) return username_system(copy_u, memo, users) else: username = name users.append(username) memo.update({name: 0}) copy_u.remove(name) return username_system(copy_u, memo, users) return users </code></pre> <p>I'd like to know, what could I improve in this code? I used memoization to make it faster. Also, I think this code is in O(n), but I'm not sure. Is that right?</p>
[]
[ { "body": "<ul>\n<li><a href=\"https://docs.python.org/2/library/collections.html#collections.defaultdict\" rel=\"nofollow noreferrer\"><code>defaultdict</code></a> gives you a major headstart on this one. </li>\n<li>Include some \"\"\"python <a href=\"https://www.python.org/dev/peps/pep-0257/\" rel=\"nofollow noreferrer\">docstring</a>\"\"\"</li>\n<li>decompose into a neat single username method and a <a href=\"https://www.digitalocean.com/community/tutorials/understanding-list-comprehensions-in-python-3\" rel=\"nofollow noreferrer\">list-comprehension</a> to apply this to an input list.</li>\n</ul>\n\n<p>The below is not self-contained (<code>users</code> resides as a global variable) but solves the problem succinctly.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>from collections import defaultdict\n\nusers = defaultdict(lambda: -1) # All names start at -1\n\n\ndef new_username(name):\n \"\"\"Generate unique username for given name\"\"\"\n users[name] += 1\n return f\"{name}{'' if users[name] == 0 else users[name]}\"\n\n\ndef username_system(names):\n return [new_username(n) for n in names] # list comprehension\n\n\nnames = ['john', 'john', 'tom', 'john']\nprint(username_system(names))\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-12T08:05:26.873", "Id": "453375", "Score": "0", "body": "This fails for `username_system(['john', 'john', 'john1'])` (it returns `['john', 'john1', 'john1']`)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-12T11:31:13.073", "Id": "453404", "Score": "1", "body": "Interesting. Given the input is a \"list of names\" I'm going to assume the only missed code here is to validate input name is only alphabetical characters - john1 is not a name (unless you're a rapper)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-12T17:20:05.093", "Id": "453457", "Score": "0", "body": "Yes, it was just a list of names." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-11T20:40:04.457", "Id": "232206", "ParentId": "232201", "Score": "2" } }, { "body": "<p>I would warn you from using such an approach - it may lead to <em>buggy</em> and <strong><em>unexpected</em></strong> results.<br>Consider the following situation:</p>\n\n<pre><code>names = ['john', 'john', 'tom', 'john']\nres1 = username_system(names)\nprint(res1) # ['john', 'john1', 'tom', 'john2']\n\nlst = ['a']\nres2 = username_system(names, users=lst)\nprint(res2) # ['a', 'john3', 'john4', 'tom1', 'john5']\n</code></pre>\n\n<p>Looking at the 2nd <code>print</code> result ...<br>\nUsing a <em>mutable</em> data structures as function default arguments is considered as a fragile approach - Python \"memorizes\"(retains) that mutable arguments content/value between subsequent function's calls. Furthermore, you use 2 of such.<br>Though in some cases it may be viable for defining a specific internal recursive functions - I'd suggest a more robust and faster approach.</p>\n\n<p>As you're mentioned about <em>\"memoization\", \"to make it faster\", \"O(N)\"</em> here's a <em>deterministic profiling</em> stats for your initial function:</p>\n\n<pre><code>import cProfile\n\n# def username_system(...)\nnames = ['john', 'john', 'tom', 'john']\ncProfile.run('username_system(names)')\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code> 27 function calls (23 primitive calls) in 0.000 seconds\n\n Ordered by: standard name\n\n ncalls tottime percall cumtime percall filename:lineno(function)\n 1 0.000 0.000 0.000 0.000 &lt;string&gt;:1(&lt;module&gt;)\n 5/1 0.000 0.000 0.000 0.000 test.py:3(username_system)\n 1 0.000 0.000 0.000 0.000 {built-in method builtins.exec}\n 4 0.000 0.000 0.000 0.000 {method 'append' of 'list' objects}\n 5 0.000 0.000 0.000 0.000 {method 'copy' of 'list' objects}\n 1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}\n 4 0.000 0.000 0.000 0.000 {method 'keys' of 'dict' objects}\n 4 0.000 0.000 0.000 0.000 {method 'remove' of 'list' objects}\n 2 0.000 0.000 0.000 0.000 {method 'update' of 'dict' objects}\n</code></pre>\n\n<p>As you may observe even for that simple input list of 4 names <code>username_system</code> function is called 5 times.</p>\n\n<hr>\n\n<p>Instead, we'll rely on supplementary <a href=\"https://docs.python.org/3/library/collections.html#collections.defaultdict\" rel=\"nofollow noreferrer\"><code>collections.defaultdict</code></a> object that conveniently provides the <em>initial</em> value.<br>Then, traversing over a copy of initial user names only entries that occur more than <strong>1</strong> time (within a dict keys view) will be appended with <em>incremented ordinal suffix</em>:</p>\n\n<pre><code>from collections import defaultdict\n\ndef get_unique_usernames(user_names):\n d = defaultdict(int)\n uniq_unames = user_names[:]\n\n for i, name in enumerate(uniq_unames):\n if name in d:\n uniq_unames[i] += str(d[name])\n d[name] += 1\n\n return uniq_unames\n\n\nif __name__ == \"__main__\": \n names = ['john', 'john', 'tom', 'john']\n print(get_unique_usernames(names)) # ['john', 'john1', 'tom', 'john2']\n</code></pre>\n\n<hr>\n\n<p>Comparison of <em>Time execution</em> performance:</p>\n\n<p><em>initial setup:</em></p>\n\n<pre><code>from timeit import timeit\n\nnames = ['john', 'john', 'tom', 'john']\n</code></pre>\n\n<hr>\n\n<p><strong><code>username_system</code></strong> function:</p>\n\n<pre><code>print(timeit('username_system(names)', 'from __main__ import names, username_system', number=10000))\n0.027410352995502762\n</code></pre>\n\n<p><strong><code>get_unique_usernames</code></strong> function:</p>\n\n<pre><code>print(timeit('get_unique_usernames(names)', 'from __main__ import names, get_unique_usernames', number=10000))\n0.013344291000976227\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-11T21:36:04.153", "Id": "453329", "Score": "1", "body": "Thank you so much! That was of great help!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-12T08:04:09.203", "Id": "453374", "Score": "0", "body": "This fails for `get_unique_usernames(['john', 'john', 'john1'])` (it returns `['john', 'john1', 'john1']`)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-12T08:09:47.153", "Id": "453376", "Score": "0", "body": "@FlorianBrucker, such a condition (if relevant) should be stated in the OP's question as a specific *edge* case" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-11T21:14:48.430", "Id": "232209", "ParentId": "232201", "Score": "10" } }, { "body": "<h1>Recursion</h1>\n\n<p>Recursion is a bad idea if a simple loop does the job and if you have little control over recursion depth.</p>\n\n<pre><code>In [1]: import sys\nIn [2]: sys.getrecursionlimit()\nOut[2]: 1000\n</code></pre>\n\n<p>Of course you can set a higher limit, but you may run into a stack overflow. But lets refactor your code first.</p>\n\n<h1>Code repetition</h1>\n\n<p>Code repetition is one of the ugliest things you can do. copy pasted code is a real pitfall when you forget o update the other execution paths. We change </p>\n\n<pre><code>def username_system(u, memo={}, users=[]):\n copy_u = u.copy()\n try:\n name = copy_u[0]\n except IndexError:\n return users\n if name in memo.keys():\n memo[name] += 1\n username = name + str(memo[name])\n users.append(username)\n copy_u.remove(name)\n return username_system(copy_u, memo, users)\n else:\n username = name\n users.append(username)\n memo.update({name: 0})\n copy_u.remove(name)\n return username_system(copy_u, memo, users)\n return users\n</code></pre>\n\n<p>to</p>\n\n<pre><code>def username_system(u, memo={}, users=[]):\n copy_u = u.copy()\n try:\n name = copy_u[0]\n except IndexError:\n return users\n if name in memo.keys():\n memo[name] += 1\n username = name + str(memo[name])\n else:\n memo.update({name: 0})\n username = name\n users.append(username)\n copy_u.remove(name)\n return username_system(copy_u, memo, users)\n return users\n</code></pre>\n\n<p>We immediately see the unreachable code at the end and remove the last line</p>\n\n<h1>Try/catch instead of if/else</h1>\n\n<p>You misuse exception handling for a simple test. We replace</p>\n\n<pre><code>try:\n name = copy_u[0]\nexcept IndexError:\n return users\n</code></pre>\n\n<p>by</p>\n\n<pre><code>if len(copy_u) == 0:\n return users\nname = copy_u[0]\n</code></pre>\n\n<h1>Avoid unnecessary copies</h1>\n\n<p>Where you iterate over your list you do</p>\n\n<pre><code>copy_u = u.copy()\n</code></pre>\n\n<p>for no reason. This your absolute performance killer as it is of quadratic complexity. We can delete that line and the code is still working. If we want to save the initial list we do</p>\n\n<pre><code>print(username_system(names.copy()))\n</code></pre>\n\n<p>in our main function.</p>\n\n<h1>Be careful about remove()</h1>\n\n<p><code>list.remove()</code> searches(!) for a value and deletes it from the list. You already know which index to delete, so use <code>del</code>.\nIn your case <code>remove()</code>has no negative impact to complexity as the element is found immediately at the front. However the code is more readable when you use <code>del</code> as this tells everybody that no search is done.</p>\n\n<p>Current status</p>\n\n<pre><code>def username_system(u, memo={}, users=[]):\n if len(u) == 0:\n return users\n\n name = u[0]\n if name in memo.keys():\n memo[name] += 1\n username = name + str(memo[name])\n else:\n memo.update({name: 0})\n username = name\n users.append(username)\n del u[0]\n return username_system(u, memo, users)\n</code></pre>\n\n<h1>And now the subtle bug</h1>\n\n<p>If you call your function multiple times there is some persistence</p>\n\n<pre><code>print(\"given:\", names)\nprint(\"returns:\", username_system(names.copy()))\nprint(\"given:\", names)\nprint(\"returns:\", username_system(names.copy()))\n</code></pre>\n\n<p>prints</p>\n\n<pre><code>given: ['john', 'john', 'tom', 'john']\nreturns: ['john', 'john1', 'tom', 'john2']\ngiven: ['john', 'john', 'tom', 'john']\nreturns: ['john', 'john1', 'tom', 'john2', 'john3', 'john4', 'tom1', 'john5']\n</code></pre>\n\n<p>How is that? You do default params in your function. This default value is created only once. If you alter the value, which is possible on containers like <code>list</code> the altered value persists. When you call your function the second time <code>memo</code>and <code>users</code> are initialized to the previously used objects and continue the up-count. That can be solved like</p>\n\n<pre><code>def username_system(u, memo=None, users=None):\n memo = memo or {}\n users = users or []\n</code></pre>\n\n<h1>Some other python stuff</h1>\n\n<pre><code>if name in memo.keys():\n</code></pre>\n\n<p>can be replaced by</p>\n\n<pre><code>if name in memo:\n</code></pre>\n\n<p>The default iteration over a <code>dict()</code> gives the keys. Use <code>dict.keys</code> only if you e. g. want to copy keys to a list().</p>\n\n<p>In the module <code>collections</code> there is a class <code>Counter</code> which does exactly what your <code>memo</code> does. We use it like</p>\n\n<pre><code>from collections import Counter\n\ndef username_system(u, memo=None, users=None):\n memo = memo or Counter()\n users = users or []\n # [...]\n if name in memo:\n username = name + str(memo[name])\n else:\n username = name\n memo[name] += 1\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-12T07:55:37.690", "Id": "453370", "Score": "0", "body": "You have an extra `return` in your second code block under \"Code Repetition\"" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-12T12:12:00.763", "Id": "453410", "Score": "1", "body": "@Gloweye: Right. And I have an extra line in the text that says that 'We immediately see the unreachable code at the end and remove the last line'. :-)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-12T12:19:21.577", "Id": "453412", "Score": "0", "body": "Ah, ok. Perhaps I read a bit to quickly :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-12T17:18:11.300", "Id": "453456", "Score": "0", "body": "Thank you! That was an amazing answer!" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-11T21:54:38.983", "Id": "232213", "ParentId": "232201", "Score": "4" } } ]
{ "AcceptedAnswerId": "232209", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-11T18:42:46.437", "Id": "232201", "Score": "6", "Tags": [ "python", "performance", "python-3.x", "programming-challenge" ], "Title": "Receive a list of names and return a list of users - HackerRank test" }
232201
<p>Now that I finally have time to look back at this code I wrote over a year ago. I need help with streamlining the code I have written. I had to write a significant amount of <code>IF</code> statements to get this to work, but im thinking using functions anbd maybe dictionaries would be a much more efficient way to go about this code. My skills are still not the greatest, so some thoughts and examples with how to set this code up to not only run more efficiently, but also streamline the code itself will be of great use. This code does run and gives the desired results.</p> <p>This code runs a SQL search from a IBM AS/400 server based on the criteria entered in by a user on a UserForm.</p> <pre class="lang-vb prettyprint-override"><code>Dim wsCity As Range, wsState As Range, wsAgeL As Range, wsAgeU As Range, wsGender As Range, wsDOB As Range, wsAge As Range Dim strConn As String, strSQL As String, uName As String, empName As String, lableCap As String, sqlCity As String, sqlState As String, sqlGender As String Dim CS As New ADODB.Connection, RS As New ADODB.Recordset Private Sub Search_Click() Dim wsDD As Worksheet Dim DOBRange As Range, AgeRange As Range Dim CitySQL As String, StateSQL As String, DOBSQL As String, CustSQL As String, sqlAgeLStr As String, sqlAgeUStr As String, sqlAgeBStr As String Dim lastRowDOB As Long, lastRowAge As Long, i As Long, lastx As Long Dim cell Dim x As Long, a As Integer, aLower As Integer, aUpper As Integer Set CS = CreateObject("ADODB.Connection") Set RS = CreateObject("ADODB.Recordset") Set wsCity = DE.Range("City") Set wsState = DE.Range("State") Set wsDOB = DE.Range("DOB") Set wsGender = DE.Range("Gender") Set wsAgeL = DE.Range("AgeLower") Set wsAgeU = DE.Range("AgeUpper") aLower = wsAgeL aUpper = wsAgeU sqlAgeLStr = "TIMESTAMPDIFF(256, CHAR(TIMESTAMP(CURRENT TIMESTAMP) - TIMESTAMP(DATE(DIGITS(DECIMAL(cfdob7 + 0.090000, 7, 0))), CURRENT TIME))) &gt;= " &amp; aLower &amp; "" &amp; "" Debug.Print sqlAgeLStr sqlAgeUStr = "TIMESTAMPDIFF(256, CHAR(TIMESTAMP(CURRENT TIMESTAMP) - TIMESTAMP(DATE(DIGITS(DECIMAL(cfdob7 + 0.090000, 7, 0))), CURRENT TIME))) &gt;= " &amp; aUpper &amp; "" &amp; "" Debug.Print sqlAgeUStr sqlAgeBStr = "TIMESTAMPDIFF(256, CHAR(TIMESTAMP(CURRENT TIMESTAMP) - TIMESTAMP(DATE(DIGITS(DECIMAL(cfdob7 + 0.090000, 7, 0))), CURRENT TIME))) BETWEEN " &amp; aLower &amp; " AND " &amp; aUpper &amp; "" Debug.Print sqlAgeBStr Application.ScreenUpdating = False strConn = REDACTED FOR PUBLIC VIEWING sqlCity = wsCity.Value sqlState = wsState.Value sqlGender = wsGender.Value strSQL = "SELECT " &amp; _ "cfna1,CFNA2,CFNA3,CFCITY,CFSTAT,LEFT(CFZIP,5) FROM CNCTTP08.JHADAT842.CFMAST CFMAST " &amp; _ "WHERE cfdob7 != 0 AND cfdob7 != 1800001 AND CFDEAD = 'N' AND " a = 0 'SEARCHES BY CITY ONLY If wsCity.Value &lt;&gt; vbNullString And wsState.Value = vbNullString And wsGender.Value = vbNullString And _ wsAgeL = vbNullString And wsAgeU = vbNullString Then a = 1 'SEARCHES BY CITY AND STATE If wsCity.Value &lt;&gt; vbNullString And wsState.Value &lt;&gt; vbNullString And wsGender.Value = vbNullString And _ wsAgeL = vbNullString And wsAgeU = vbNullString Then a = 2 'SEARCHES BY CITY AND GENDER If wsCity.Value &lt;&gt; vbNullString And wsState.Value = vbNullString And wsGender.Value &lt;&gt; vbNullString And _ wsAgeL = vbNullString And wsAgeU = vbNullString Then a = 3 'SEARCHES BY CITY AND AGE LOWER If wsCity.Value &lt;&gt; vbNullString And wsState.Value = vbNullString And wsGender.Value = vbNullString And _ wsAgeL &lt;&gt; vbNullString And wsAgeU = vbNullString Then a = 4 'SEARCHES BY CITY AND AGE UPPER If wsCity.Value &lt;&gt; vbNullString And wsState.Value = vbNullString And wsGender.Value = vbNullString And _ wsAgeL = vbNullString And wsAgeU &lt;&gt; vbNullString Then a = 5 'SEARCHES BY CITY AND FULL AGE RANGE If wsCity.Value &lt;&gt; vbNullString And wsState.Value = vbNullString And wsGender.Value = vbNullString And _ wsAgeL &lt;&gt; vbNullString And wsAgeU &lt;&gt; vbNullString Then a = 6 'SEARCHES BY CITY, GENDER AND FULL AGE RANGE If wsCity.Value &lt;&gt; vbNullString And wsState.Value = vbNullString And wsGender.Value &lt;&gt; vbNullString And _ wsAgeL &lt;&gt; vbNullString And wsAgeU &lt;&gt; vbNullString Then a = 7 'SEARCHES BY CITY, STATE AND GENDER If wsCity.Value &lt;&gt; vbNullString And wsState.Value &lt;&gt; vbNullString And wsGender.Value &lt;&gt; vbNullString And _ wsAgeL = vbNullString And wsAgeU = vbNullString Then a = 8 'SEARCHES BY CITY, STATE, GENDER AND LOWER AGE If wsCity.Value &lt;&gt; vbNullString And wsState.Value &lt;&gt; vbNullString And wsGender.Value &lt;&gt; vbNullString And _ wsAgeL &lt;&gt; vbNullString And wsAgeU = vbNullString Then a = 9 'SEARCHES BY CITY, STATE, GENDER, UPPER AGE RANGE If wsCity.Value &lt;&gt; vbNullString And wsState.Value &lt;&gt; vbNullString And wsGender.Value &lt;&gt; vbNullString And _ wsAgeL = vbNullString And wsAgeU &lt;&gt; vbNullString Then a = 10 'SEARCHES BY CITY, STATE, GENDER, FULL AGE RANGE If wsCity.Value &lt;&gt; vbNullString And wsState.Value &lt;&gt; vbNullString And wsGender.Value &lt;&gt; vbNullString And _ wsAgeL &lt;&gt; vbNullString And wsAgeU &lt;&gt; vbNullString Then a = 11 'SEARCHES BY STATE If wsCity.Value = vbNullString And wsState.Value &lt;&gt; vbNullString And wsGender.Value = vbNullString And _ wsAgeL = vbNullString And wsAgeU = vbNullString Then a = 12 'SEARCHES BY STATE AND GENDER If wsCity.Value = vbNullString And wsState.Value &lt;&gt; vbNullString And wsGender.Value &lt;&gt; vbNullString And _ wsAgeL = vbNullString And wsAgeU = vbNullString Then a = 13 'SEARCHES BY STATE AND AGE LOWER If wsCity.Value = vbNullString And wsState.Value &lt;&gt; vbNullString And wsGender.Value = vbNullString And _ wsAgeL &lt;&gt; vbNullString And wsAgeU = vbNullString Then a = 14 'SEARCHES BY STATE AND AGE UPPER If wsCity.Value = vbNullString And wsState.Value &lt;&gt; vbNullString And wsGender.Value = vbNullString And _ wsAgeL = vbNullString And wsAgeU &lt;&gt; vbNullString Then a = 15 'SEARCHES BY STATE AND FULL AGE RANGE If wsCity.Value = vbNullString And wsState.Value &lt;&gt; vbNullString And wsGender.Value = vbNullString And _ wsAgeL &lt;&gt; vbNullString And wsAgeU &lt;&gt; vbNullString Then a = 16 'SEARCHES BY STATE, GENDER AND AGE LOWER If wsCity.Value = vbNullString And wsState.Value &lt;&gt; vbNullString And wsGender.Value &lt;&gt; vbNullString And _ wsAgeL &lt;&gt; vbNullString And wsAgeU = vbNullString Then a = 17 'SEARCHES BY STATE, GENDER AND AGE UPPER If wsCity.Value = vbNullString And wsState.Value &lt;&gt; vbNullString And wsGender.Value &lt;&gt; vbNullString And _ wsAgeL = vbNullString And wsAgeU &lt;&gt; vbNullString Then a = 18 'SEARCHES BY STATE, GENDER AND FULL AGE RANGE If wsCity.Value = vbNullString And wsState.Value &lt;&gt; vbNullString And wsGender.Value &lt;&gt; vbNullString And _ wsAgeL &lt;&gt; vbNullString And wsAgeU &lt;&gt; vbNullString Then a = 19 'SEARCHES BY GENDER If wsCity.Value = vbNullString And wsState.Value = vbNullString And wsGender.Value &lt;&gt; vbNullString And _ wsAgeL = vbNullString And wsAgeU = vbNullString Then a = 20 'SEARCHES BY GENDER AND AGE LOWER If wsCity.Value = vbNullString And wsState.Value = vbNullString And wsGender.Value &lt;&gt; vbNullString And _ wsAgeL &lt;&gt; vbNullString And wsAgeU = vbNullString Then a = 21 'SEARCHES BY GENDER AND AGE UPPER If wsCity.Value = vbNullString And wsState.Value = vbNullString And wsGender.Value &lt;&gt; vbNullString And _ wsAgeL = vbNullString And wsAgeU &lt;&gt; vbNullString Then a = 22 'SEARCHES BY GENDER AND FULL AGE RANGE If wsCity.Value = vbNullString And wsState.Value = vbNullString And wsGender.Value &lt;&gt; vbNullString And _ wsAgeL &lt;&gt; vbNullString And wsAgeU &lt;&gt; vbNullString Then a = 23 'SEARCHES BY LOWER AGE RANGE If wsCity.Value = vbNullString And wsState.Value = vbNullString And wsGender.Value = vbNullString And _ wsAgeL &lt;&gt; vbNullString And wsAgeU = vbNullString Then a = 24 'SEARCHES BY UPPER AGE RANGE If wsCity.Value = vbNullString And wsState.Value = vbNullString And wsGender.Value = vbNullString And _ wsAgeL = vbNullString And wsAgeU &lt;&gt; vbNullString Then a = 25 'SEARCHES BY FULL AGE RANGE If wsCity.Value = vbNullString And wsState.Value = vbNullString And wsGender.Value = vbNullString And _ wsAgeL = vbNullString And wsAgeU = vbNullString Then a = 26 'SEARCHES BY CITY, STATE, FULL AGE RANGE If wsCity.Value &lt;&gt; vbNullString And wsState.Value &lt;&gt; vbNullString And wsGender.Value = vbNullString And _ wsAgeL &lt;&gt; vbNullString And wsAgeU &lt;&gt; vbNullString Then a = 27 Select Case a Case Is = 1 'SEARCHES BY CITY ONLY strSQL = strSQL &amp; "CFCITY= '" &amp; UCase(wsCity.Value) &amp; "' AND " &amp; _ "CFSEX != 'O'" Case Is = 2 'SEARCHES BY CITY AND STATE strSQL = strSQL &amp; "CFSEX != 'O' AND " &amp; _ "CFCITY = '" &amp; UCase(wsCity.Value) &amp; "' AND " &amp; _ "CFSTAT = '" &amp; UCase(wsState.Value) &amp; "'" Case Is = 3 'SEARCHES BY CITY AND GENDER strSQL = strSQL &amp; "CFCITY = '" &amp; UCase(wsCity.Value) &amp; "' AND " &amp; _ "CFSEX = '" &amp; wsGender &amp; "'" Case Is = 4 'SEARCHES BY CITY AND AGE LOWER strSQL = strSQL &amp; "CFCITY = '" &amp; UCase(wsCity.Value) &amp; "' AND " &amp; _ sqlAgeLStr Case Is = 5 'SEARCHES BY CITY AND AGE UPPER strSQL = strSQL &amp; "CFCITY = '" &amp; UCase(wsCity.Value) &amp; "' AND " &amp; _ sqlAgeUStr Case Is = 6 'SEARCHES BY CITY AND FULL AGE RANGE strSQL = strSQL &amp; "CFCITY = '" &amp; UCase(wsCity.Value) &amp; "' AND " &amp; _ sqlAgeBStr Case Is = 7 'SEARCHES BY CITY, GENDER, AND FULL AGE RANGE strSQL = strSQL &amp; "CFCITY = '" &amp; UCase(wsCity.Value) &amp; "' AND " &amp; _ "CFSEX = '" &amp; UCase(wsGender.Value) &amp; "' AND " &amp; _ sqlAgeBStr Case Is = 8 'SEARCHES BY CITY, STATE AND GENDER strSQL = strSQL &amp; "CFCITY = '" &amp; UCase(wsCity.Value) &amp; "' AND " &amp; _ "CFSTAT = '" &amp; UCase(wsState.Value) &amp; "' AND " &amp; _ "CFSEX = '" &amp; wsGender &amp; "'" Case Is = 9 'SEARCHES BY CITY, STATE, GENDER AND LOWER AGE strSQL = strSQL &amp; "CFCITY = '" &amp; UCase(wsCity.Value) &amp; "' AND " &amp; _ "CFSTAT = '" &amp; UCase(wsState.Value) &amp; "' AND " &amp; _ "CFSEX = '" &amp; wsGender &amp; "' AND " &amp; _ sqlAgeLStr Case Is = 10 'SEARCHES BY CITY, STATE, GENDER, UPPER AGE RANGE strSQL = strSQL &amp; "CFCITY = '" &amp; UCase(wsCity.Value) &amp; "' AND " &amp; _ "CFSTAT = '" &amp; UCase(wsState.Value) &amp; "' AND " &amp; _ "CFSEX = '" &amp; wsGender &amp; "' AND " &amp; _ sqlAgeUStr Case Is = 11 'SEARCHES BY CITY, STATE, GENDER, FULL AGE RANGE strSQL = strSQL &amp; "CFCITY = '" &amp; UCase(wsCity) &amp; "' AND " &amp; _ "CFSTAT = '" &amp; UCase(wsState) &amp; "' AND " &amp; _ "CFSEX = '" &amp; UCase(wsGender) &amp; "' AND " &amp; _ sqlAgeBStr Case Is = 12 'SEARCHES BY STATE strSQL = strSQL &amp; "CFSTAT= '" &amp; UCase(wsState.Value) &amp; "'" Case Is = 13 'SEARCHES BY STATE AND GENDER strSQL = strSQL &amp; "CFSTAT = '" &amp; UCase(wsState.Value) &amp; "' AND " &amp; _ "CFSEX = '" &amp; wsGender &amp; "'" Case Is = 14 'SEARCHES BY STATE AND AGE LOWER strSQL = strSQL &amp; "CFSTAT = '" &amp; UCase(wsState.Value) &amp; "' AND " &amp; _ sqlAgeLStr Case Is = 15 'SEARCHES BY STATE AND AGE UPPER strSQL = strSQL &amp; "CFSTAT = '" &amp; UCase(wsState.Value) &amp; "' AND " &amp; _ sqlAgeUStr Case Is = 16 'SEARCHES BY STATE AND FULL AGE RANGE strSQL = strSQL &amp; "CFSTAT = '" &amp; UCase(wsState.Value) &amp; "') AND " &amp; _ sqlAgeBStr Case Is = 17 'SEARCHES BY STATE, GENDER AND AGE LOWER strSQL = strSQL &amp; "CFSTAT = '" &amp; UCase(wsState.Value) &amp; "' AND " &amp; _ "CFSEX = '" &amp; wsGender &amp; "' AND " &amp; _ sqlAgeLStr Case Is = 18 'SEARCHES BY STATE, GENDER AND AGE UPPER strSQL = strSQL &amp; "CFSTAT = '" &amp; UCase(wsState.Value) &amp; "' AND " &amp; _ "CFSEX = '" &amp; wsGender &amp; "' AND " &amp; _ sqlAgeUStr Case Is = 19 'SEARCHES BY STATE, GENDER AND FULL AGE RANGE strSQL = strSQL &amp; "CFSTAT = '" &amp; UCase(wsState.Value) &amp; "' AND " &amp; _ "CFSEX = '" &amp; wsGender &amp; "' AND " &amp; _ sqlAgeBStr Case Is = 20 'SEARCHES BY GENDER strSQL = strSQL &amp; "CFSEX = '" &amp; wsGender &amp; "'" Case Is = 21 'SEARCHES BY GENDER AND AGE LOWER strSQL = strSQL &amp; "CFSEX = '" &amp; wsGender &amp; "' AND " &amp; _ sqlAgeLStr Case Is = 22 'SEARCHES BY GENDER AND AGE UPPER strSQL = strSQL &amp; "CFSEX = '" &amp; wsGender &amp; "' AND " &amp; _ sqlAgeUStr Case Is = 23 'SEARCHES BY GENDER AND FULL AGE RANGE strSQL = strSQL &amp; "CFSEX = '" &amp; wsGender &amp; "' AND " &amp; _ sqlAgeBStr Case Is = 24 'SEARCHES BY LOWER AGE RANGE strSQL = strSQL &amp; "CFSEX != 'O' AND " &amp; _ sqlAgeLStr Case Is = 25 'SEARCHES BY UPPER AGE RANGE strSQL = strSQL &amp; "CFSEX != 'O' AND " &amp; _ sqlAgeUStr Case Is = 26 'SEARCHES BY FULL AGE RANGE strSQL = strSQL &amp; "CFSEX != 'O' AND " &amp; _ sqlAgeBStr Case Is = 27 'SEARCHES BY CITY, STATE, FULL AGE RANGE strSQL = strSQL &amp; "CFCITY = '" &amp; UCase(wsCity) &amp; "' AND " &amp; _ "CFSTAT = '" &amp; UCase(wsState.Value) &amp; "' AND " &amp; _ sqlAgeBStr End Select strSQL = strSQL &amp; " ORDER BY cfna1 ASC" Debug.Print strSQL DataEntry.Hide CS.Open (strConn) RS.Open strSQL, CS MarketingList.Range("B2").CopyFromRecordset RS RS.Close CS.Close Set RS = Nothing Set CS = Nothing Application.ScreenUpdating = True MarketingList.Activate FormatHeaders SearchComplete.Show End Sub Private Sub AgeLower_AfterUpdate() Set wsAgeL = DE.Range("AgeLower") wsAgeL = Format(DataEntry.AgeLower, "0") End Sub Private Sub AgeUpper_AfterUpdate() Set wsAgeU = DE.Range("AgeUpper") wsAgeU = Format(DataEntry.AgeUpper, "0") End Sub Private Sub City_AfterUpdate() Set wsCity = DE.Range("City") wsCity = DataEntry.City End Sub Private Sub Male_Click() Set wsGender = DE.Range("Gender") Select Case DataEntry.Male Case Is = True wsGender = "M" Case Is = False wsGender = vbNullString End Select End Sub Function OrdDateToDate(OrdDate As String) As Long Dim TheYear As Integer Dim TheDay As Integer Dim TheDate As Long TheYear = CInt(Left(OrdDate, 4)) TheDay = CInt(Right(OrdDate, 3)) TheDate = DateSerial(TheYear, 1, TheDaDE) OrdDateToDate = TheDate End Function Private Sub Female_Click() Set wsGender = DE.Range("Gender") Select Case DataEntry.Female Case Is = True wsGender = "F" Case Is = False wsGender = vbNullString End Select End Sub </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-11T18:58:04.860", "Id": "453305", "Score": "1", "body": "I'm sure reviewers will mention something about ADODB commands and parameters, but before we *shred this code to pieces* (aka \"review\"), can you confirm that this is the only procedure in the module? Basically what I'm curious about, is all these declarations outside the `Search_Click()` procedure scope: it would be helpful to know why they're where they are. Consider reviewing [Rubberduck](http://rubberduckvba.com) inspections, too; it can pick up and warn you about a lot of things reviewers will also tell you about. Cheers!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-11T19:02:35.187", "Id": "453306", "Score": "0", "body": "It isnt the only procedure in the module, but the other procedures are just from a UserForm that is used to pass certain information to a hidden sheet. I can post the other procedures, but I didnt think they were of relevance to this. I wish i could use RubberDuck on my work computer, but alas the higher ups said no." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-11T19:03:29.550", "Id": "453307", "Score": "0", "body": "We like bonus context. Feel free to post the procedures." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-11T19:12:14.833", "Id": "453309", "Score": "0", "body": "added the other procedures from the module :) Tear it apart lol." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-11T19:14:40.550", "Id": "453311", "Score": "0", "body": "So, all that code is in the code-behind of a `UserForm` module? (side note, you don't need any admin privs to install Rubberduck)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-11T19:15:48.947", "Id": "453312", "Score": "1", "body": "@MathieuGuindon That is correct this code is all in the UserForm module." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-11T19:17:33.737", "Id": "453313", "Score": "0", "body": "In that case I'd suggest just grabbing the whole module and pasting it in as a single code block, makes it easier for reviewers to copy/paste. Is `Option Explicit` not specified at the top of the module? ;-)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-11T19:21:57.350", "Id": "453315", "Score": "1", "body": "@MathieuGuindon I placed all the code into one block. This was one of my first attempts at VBA, so i didnt place the `Option Explicit` at the top like I do with all my other code now. I will add it in. Thanks for the reminder. Unfortunately, in regards to RubberDuck I do need admin rights to download anything on my work computer :(" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-11T19:26:59.383", "Id": "453316", "Score": "1", "body": "Ah, yes, requiring admin rights to fight evil, I know that problem. No problem, Mat is a walking, talking rubberduck." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-11T19:28:02.987", "Id": "453317", "Score": "1", "body": "You don't need to edit your code further (at least in this question). The problems with it are perfectly reviewable :-)" } ]
[ { "body": "\n\n<p>Let's start with the easy stuff.\nAt first glance the code looks horrendous but after taking a closer look well it is horrendous. JK for the most part you need to learn a few tricks that will greatly simplify the code.</p>\n\n<h2>Miscellaneous</h2>\n\n<p>As is, I see no reason for the class members because everyone of these fields are being set at each point of use. In this way, if one of the references changes you will have to update the reference at each point of use. </p>\n\n<p>If would make more sense to set the fields one time when the userform is initialized.</p>\n\n<blockquote>\n<pre class=\"lang-vb prettyprint-override\"><code>Private rCity As Range, rState As Range, rAgeL As Range, rAgeU As Range, rGender As Range, rDOB As Range, rAge As Range\n\nPrivate Sub UserForm_Initialize()\n Set rCity = DE.Range(\"City\")\n Set rState = DE.Range(\"State\")\n Set rDOB = DE.Range(\"DOB\")\n Set rGender = DE.Range(\"Gender\")\n Set rAgeL = DE.Range(\"AgeLower\")\n Set rAgeU = DE.Range(\"AgeUpper\")\nEnd Sub\n</code></pre>\n</blockquote>\n\n<p>Why prefix the ranges with <code>ws</code>? Typically, <code>ws</code> signifies <code>Worksheet</code>.</p>\n\n<blockquote>\n<pre class=\"lang-vb prettyprint-override\"><code>wsCity As Range, wsState As Range, wsAgeL As Range, wsAgeU As Range, wsGender As Range, wsDOB As Range, wsAge As Range\n</code></pre>\n</blockquote>\n\n<p>Why use the New keyword if you are going to set the instances using CreateObject? There is no reason for Connection and Recordset to be fields. They should be local variables.</p>\n\n<blockquote>\n<pre class=\"lang-vb prettyprint-override\"><code>CS As New ADODB.Connection, RS As New ADODB.Recordset\n</code></pre>\n</blockquote>\n\n<p>What the heck are you setting a class member field for in a control AfterUpdate event? </p>\n\n<blockquote>\n<pre class=\"lang-vb prettyprint-override\"><code>Private Sub City_AfterUpdate()\n\n Set wsCity = DE.Range(\"City\")\n\n wsCity = DataEntry.City\nEnd Sub\n</code></pre>\n</blockquote>\n\n<p>Use helper variables to simplify and clarify you code. Unless you want to ensure that the user changes the value then don't bother setting your fields here. </p>\n\n<p>Use <code>Me</code> instead of <code>DataEntry</code>.</p>\n\n<blockquote>\n<pre class=\"lang-vb prettyprint-override\"><code>Private Sub City_Change() \n DE.Range(\"City\") = Me.City.Value\nEnd Sub\n</code></pre>\n</blockquote>\n\n<h2>Sub Search_Click()</h2>\n\n<p>This is a bit of a mess. To begin with this <code>Search_Click()</code> is doing too much. </p>\n\n<ul>\n<li>Setting Class Members</li>\n<li>Establishing a Connection</li>\n<li>Building a Query String</li>\n<li>Executing the Query</li>\n<li>Transferring the </li>\n</ul>\n\n<p>The fewer tasks that a method performs the easier it is to test and modify.</p>\n\n<p>By combining all the <code>If</code> statements using <code>If</code> and <code>ElseIf</code>, you could eliminate the <code>Select Case</code> block.</p>\n\n<blockquote>\n<pre class=\"lang-vb prettyprint-override\"><code>If Len(wsCity.Value) &gt; 0 And Len(wsState.Value) = 0 And Len(wsGender.Value) = 0 And Len( If Len(wsCity.Value) &gt; 0 And Len(wsState.Value) = 0 And Len(wsGender.Value) = 0 And Len(wsAgeL) = 0 And Len(wsAgeU) = 0 Then\n Rem SEARCHES BY CITY ONLY\n strSQL = strSQL &amp; \"CFCITY= '\" &amp; UCase(wsCity.Value) &amp; \"' AND CFSEX != 'O'\"\nElseIf Len(wsCity.Value) &gt; 0 And Len(wsState.Value) &gt; 0 And Len(wsGender.Value) = 0 And Len(wsAgeL) = 0 And Len(wsAgeU) = 0 Then\n Rem SEARCHES BY CITY AND STATE\n strSQL = strSQL &amp; \"CFSEX != 'O' AND \" &amp; _\n \"CFCITY = '\" &amp; UCase(wsCity.Value) &amp; \"' AND \" &amp; _\n \"CFSTAT = '\" &amp; UCase(wsState.Value) &amp; \"'\"\nElseIf Len(wsCity.Value) &gt; 0 And Len(wsState.Value) = 0 And Len(wsGender.Value) &gt; 0 And Len(wsAgeL) = 0 And Len(wsAgeU) = 0 Then\n Rem SEARCHES BY CITY AND GENDER\n strSQL = strSQL &amp; \"CFCITY = '\" &amp; UCase(wsCity.Value) &amp; \"' AND \" &amp; _\n \"CFSEX = '\" &amp; wsGender &amp; \"'\"\n Rem More Clauses\n\nEnd If\n</code></pre>\n</blockquote>\n\n<p>Alternately, you could eliminate the <code>If</code> clause by using <code>Select Case True</code>.</p>\n\n<blockquote>\n<pre class=\"lang-vb prettyprint-override\"><code>Select Case True\n Rem SEARCHES BY CITY ONLY\n Case Len(wsCity.Value) &gt; 0, Len(wsState.Value) = 0, Len(wsGender.Value) = 0, Len(wsAgeL) = 0, Len(wsAgeU) = 0\n strSQL = strSQL &amp; \"CFCITY= '\" &amp; UCase(wsCity.Value) &amp; \"' AND CFSEX != 'O'\"\n Rem SEARCHES BY CITY AND STATE\n Case Len(wsCity.Value) &gt; 0, Len(wsState.Value) &gt; 0, Len(wsGender.Value) = 0, Len(wsAgeL) = 0, Len(wsAgeU) = 0\n strSQL = strSQL &amp; \"CFSEX != 'O' AND \" &amp; _\n \"CFCITY = '\" &amp; UCase(wsCity.Value) &amp; \"' AND \" &amp; _\n \"CFSTAT = '\" &amp; UCase(wsState.Value) &amp; \"'\"\n Rem SEARCHES BY CITY AND GENDER\n Case Len(wsCity.Value) &gt; 0, Len(wsState.Value) = 0, Len(wsGender.Value) &gt; 0, Len(wsAgeL) = 0, Len(wsAgeU) = 0\n strSQL = strSQL &amp; \"CFCITY = '\" &amp; UCase(wsCity.Value) &amp; \"' AND \" &amp; _\n \"CFSEX = '\" &amp; wsGender &amp; \"'\"\n Rem More Cases\nEnd Select\n</code></pre>\n</blockquote>\n\n<p>I would write a Function in a public module to return the SQL. This function would take all its arguments through parameters and not rely on global variables or worksheet ranges. This will break the dependency to the current workbook structure and make if far easier to test your code.</p>\n\n<pre class=\"lang-vb prettyprint-override\"><code>Function getCFMASTSQL(City As String, State As String, DOB As Single, Gender As String, AgeLower As String, AgeUpper As String) As String\n Const BaseSQL As String = \"SELECT cfna1, CFNA2, CFNA3, CFCITY, CFSTAT, LEFT(CFZIP,5) FROM CNCTTP08.JHADAT842.CFMAST CFMAST \"\n\n Dim Wheres As New Collection\n\n If DOB &gt; 0 Then\n Wheres.Add \"cfdob7 = \" &amp; DOB\n Else\n Wheres.Add \"cfdob7 != 0\"\n Wheres.Add \"cfdob7 != 1800001\"\n Wheres.Add \"CFDEAD = 'N'\"\n End If\n\n If Len(AgeLower) &gt; 0 And Len(AgeUpper) &gt; 0 Then\n Wheres.Add \"TIMESTAMPDIFF(256, CHAR(TIMESTAMP(CURRENT TIMESTAMP) - TIMESTAMP(DATE(DIGITS(DECIMAL(cfdob7 + 0.090000, 7, 0))), CURRENT TIME))) BETWEEN \" &amp; AgeLower &amp; \" AND \" &amp; AgeUpper\n ElseIf Len(AgeLower) &gt; 0 Then\n Wheres.Add \"TIMESTAMPDIFF(256, CHAR(TIMESTAMP(CURRENT TIMESTAMP) - TIMESTAMP(DATE(DIGITS(DECIMAL(cfdob7 + 0.090000, 7, 0))), CURRENT TIME))) &gt;= \" &amp; AgeLower\n ElseIf Len(AgeUpper) &gt; 0 Then\n Wheres.Add \"TIMESTAMPDIFF(256, CHAR(TIMESTAMP(CURRENT TIMESTAMP) - TIMESTAMP(DATE(DIGITS(DECIMAL(cfdob7 + 0.090000, 7, 0))), CURRENT TIME))) &lt;= \" &amp; AgeUpper\n End If\n\n If Len(Gender) &gt; 0 Then\n Wheres.Add \"CFSEX = '\" &amp; Gender &amp; \"'\"\n Else\n Wheres.Add \"CFSEX != 'O'\"\n End If\n\n If Len(City) &gt; 0 Then Wheres.Add \"CFCITY = '\" &amp; UCase(City) &amp; \"'\"\n If Len(State) &gt; 0 Then Wheres.Add \"CFSTAT = '\" &amp; UCase(State) &amp; \"'\"\n\n Dim SQL As String\n\n If Wheres.Count &gt; 0 Then\n Dim Values() As String\n ReDim Values(1 To Wheres.Count)\n\n Dim n As Long\n\n For n = 1 To Wheres.Count\n Values(n) = Wheres(n)\n Next\n\n SQL = BaseSQL &amp; vbNewLine &amp; \"WHERE \" &amp; Join(Values, \" AND \")\n Else\n SQL = BaseSQL\n End If\n\n getCFMASTSQL = SQL\nEnd Function\n</code></pre>\n\n<p><a href=\"https://i.stack.imgur.com/9ZTYC.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/9ZTYC.png\" alt=\"Immediate Window\"></a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-12T14:40:39.170", "Id": "453419", "Score": "0", "body": "Thank you very much. I knew the code on the `Search_Click` was horrendous :). I didnt even think of just testing the length within a `Select Case` statement. I am going to try to implement the function for the SQL as well. I will let you know if i have any additional questions. Thanks again." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-12T19:04:49.707", "Id": "453480", "Score": "0", "body": "I have run through this and implemented the function and it all works excellently. Thank you again for the tips and help with this. It is much appreciated!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-13T05:44:37.933", "Id": "453541", "Score": "0", "body": "@ZackE thank you for excepting my answer" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-13T13:22:24.530", "Id": "453620", "Score": "0", "body": "My pleasure. I did make some changes to the function since all of those options are optional and also changed it to `ByVal`" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-12T13:27:43.157", "Id": "232246", "ParentId": "232202", "Score": "3" } } ]
{ "AcceptedAnswerId": "232246", "CommentCount": "10", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-11T18:50:18.490", "Id": "232202", "Score": "3", "Tags": [ "sql", "vba", "excel", "db2" ], "Title": "VBA and SQL to return SQL results to Excel" }
232202
<p>I've written a python script that solves a restricted variant of Subset Product by using integer factorization. The purpose of the script is for my empirical observations of the similarities between factorization and the <a href="https://cs.stackexchange.com/questions/7907/is-the-subset-product-problem-np-complete">NP-complete problem.</a></p> <p>The code compares two sets (or lists) from the original input <code>arr</code> and the factor list <code>res</code>. Because of the comparison, it is able to find the divisors and multiply them to see if they arrive to the target product. </p> <p>Before using the code be aware that input must be positive integers only.</p> <pre><code>print('Solves restricted Subset Product') print('Where only non-repeating integers exist in list') print('Subset Product Solver') arr = list(map(int, input('Enter numbers WITH SPACES: ').split(' '))) print('enter your target integer: ') target = int(input()) # Here I am using the same algorithm # for integer factorization for a # restricted variant of subset product res = []; for i in range(1, target+1): if target % i == 0: res.append(i) compare_sets = set(res) &amp; set(arr) # These lines of code multiply all elements # in compare_sets. def multiplyList(compare_sets) : # Multiply elements one by one result = 1 for x in compare_sets: result = result * x return result # Driver code k = multiplyList(compare_sets) # This loop is intended to comb through the # compare_sets list. To make sure I don't go # over and miss the target integer for i in compare_sets: if k / i == target: if len(compare_sets) &gt; 1: compare_sets.remove(i) print('yes, a subset product exists') print(compare_sets) quit() if k == target: if len(compare_sets) &gt; 1: print('yes, a subset product exists') print(set(res) &amp; set(arr)) quit() else: print('no') quit() print('no') </code></pre> <h2>Question</h2> <p><em>Are my variable names funky and should be re-written? What part of the code is the worst in terms of time complexity (ignoring factoring)? What more efficient "pythonic" methods can I use to improve the code?</em></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-11T21:11:38.157", "Id": "453324", "Score": "0", "body": "If the content is to hard to understand. Or the code is too long. I'm willing to improve the post." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-11T21:13:04.723", "Id": "453325", "Score": "0", "body": "I'm not sure why this was downvoted. It seems fine." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-11T21:13:49.533", "Id": "453326", "Score": "0", "body": "@Carcigenicate I think it could've been the title. I edited it." } ]
[ { "body": "<pre><code>res = [];\nfor i in range(1, target+1):\n if target % i == 0:\n res.append(i)\n</code></pre>\n\n<p>This has a couple notable things. First, Python doesn't use semi-colons in the vast majority of cases. They aren't necessary. Also, whenever you have a loop whose only purpose is to create a list, you'll likely want a <a href=\"https://www.python.org/dev/peps/pep-0202/#rationale\" rel=\"nofollow noreferrer\">list comprehension</a> instead:</p>\n\n<pre><code>res = [i for i in range(1, target + 1) if target % i == 0]\n</code></pre>\n\n<p>Whatever is on the left end (<code>i</code> in this case) gets appended to a new list. It can also be \"guarded\" using an <code>if</code> on the right end. Once you get used to seeing this syntax, it tends to read really nicely.</p>\n\n<p>I also wouldn't write <code>target+1</code> without any spaces. <a href=\"https://www.python.org/dev/peps/pep-0008/#other-recommendations\" rel=\"nofollow noreferrer\">PEP8</a> recommends one space on each side of a binary operator unless you have a good reason to omit them.</p>\n\n<hr>\n\n<pre><code>result = 1\nfor x in compare_sets: \n result = result * x \nreturn result\n</code></pre>\n\n<p>The line in the loop could make use of a compound-assignment operator to be more terse:</p>\n\n<pre><code>result *= x\n</code></pre>\n\n<p>This loop though is just carrying out a transformation of an \"accumulator\" (<code>result</code>). This is the ideal case for <a href=\"https://docs.python.org/3/library/functools.html#functools.reduce\" rel=\"nofollow noreferrer\"><code>reduce</code></a>:</p>\n\n<pre><code>from operator import mul\nfrom functools import reduce\n\nresult = reduce(mul, compare_sets)\n</code></pre>\n\n<p><code>reduce</code> is a function from Functional Programming. It and <code>map</code> are the standard ways of working with lists at a low level in FP. Python decided to tuck it away in <code>functools</code>, but it's a very useful function. And <code>mul</code> is just:</p>\n\n<pre><code>def mul(a, b):\n \"Same as a * b.\"\n return a * b\n</code></pre>\n\n<p><code>operator</code> contains many similar \"first order\" versions of operators for cases like this.</p>\n\n<hr>\n\n<p>I wouldn't have top-level code like you do here. If you try to load this file by importing it or opening it in a REPL, the whole thing is forced to run, even if you just wanted to use or test a single function. Everything that isn't a function or constant definition should ideally be tucked away inside a <code>main</code>. That way you can control when the code is executed. I'd also be hesitant to call <code>quit</code> here. That also makes code harder to work with. Again, if you have this open in a REPL, <code>quit</code> will kill the REPL. I'd just change those <code>quit</code>s to <code>return</code>s once this is inside a <code>main</code>.</p>\n\n<hr>\n\n<p>And your naming isn't too bad. I would use much more descriptive names than <code>i</code> and <code>k</code> though unless those are straight from the equations involved (and even then description always helps).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-11T21:31:58.623", "Id": "232211", "ParentId": "232208", "Score": "8" } } ]
{ "AcceptedAnswerId": "232211", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-11T21:00:08.797", "Id": "232208", "Score": "5", "Tags": [ "python", "python-3.x" ], "Title": "Solving Subset-Product in Python" }
232208
<p>So I was doing some challenges on codewars.com and came across the following challenge (I managed to close the browser so could not submit my answer and therefore could not see the best possible solutions). </p> <p>Given an array of at least 3 integers, all the elements in the array are either even or oneven EXCEPT for 1 element --> </p> <p><code>[2, 4, 0, 100, 4, 11, 2602, 36]</code></p> <p>OR:</p> <p><code>[160, 3, 1719, 19, 11, 13, -21]</code></p> <p>All the elements are either even or oneven except for one where it is the other way around. Return the element that is the odd one out, so:</p> <p><code>findOutlier([2, 4, 0, 100, 4, 11, 2602, 36]) //should return 11</code></p> <p><code>findOutlier([160, 3, 1719, 19, 11, 13, -21]) //should return 160</code></p> <p>I got a working solution but there has to be a better way of doing this.. My solution:</p> <pre><code>function findOutlier(integers){ let evenCount = 0; let oddCount = 0; for(let i = 0; i &lt; integers.length; i++) { if(integers[i] % 2 === 0) { evenCount += 1; } else { oddCount += 1 } } let idx = integers.find(function(index) { if(evenCount &gt; 2) { return index % 2 === 1 } else { return index % 2 === 0 } }) return idx } <span class="math-container">```</span> </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-12T05:07:26.157", "Id": "453358", "Score": "0", "body": "The title states *Find **Index** ...* but the above approach returns **value**. What's the actual intention?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-12T17:29:58.440", "Id": "453462", "Score": "1", "body": "Value... I'm sorry. It was late in the evening, my bad hehe." } ]
[ { "body": "<p>You only need to iterate the first 3 numbers of the array.</p>\n\n<pre><code>for(let i = 0; i &lt; 3; i++) {\n</code></pre>\n\n<p>You are iterating through the array twice. You should only iterate once. You can do this by setting the values in the first loop:</p>\n\n<pre><code>let evenCount = 0;\nlet oddCount = 0;\nlet evenNumber = 0;\nlet oddNumber = 0;\n\nfor(let i = 0; i &lt; 3; i++) {\n if(integers[i] % 2 === 0) {\n evenCount++;\n evenNumber = integers[i];\n } else {\n oddCount++;\n oddNumber = integers[i];\n }\n}\n\nreturn evenCount &gt; 1 ? oddNumber : evenNumber;\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-12T07:47:56.687", "Id": "453368", "Score": "1", "body": "Awesome, good point about only needing to iterate through the first 3 elements. Thanks a lot for your alternate solution!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-11T22:50:20.543", "Id": "232216", "ParentId": "232212", "Score": "3" } }, { "body": "<p>As pointed out in dustytrash's answer you need only check the first 3 items to find out if you are hunting for odd or even values.</p>\n\n<p>There are also some optimizations you can add to reduce the number of statements and clauses.</p>\n\n<p>Rather than use two variables in the first loop to locate even or odd you can use just one and count up for odd and down for even. Also using a while loop is slightly more performant in this situation so we get the opening lines as</p>\n\n<pre><code>function findOutlier(items){\n var oddEven = 0, i = 3;\n while (i--) { \n oddEven += items[i] % 2 ? -1 : 1;\n }\n // more code to follow\n</code></pre>\n\n<p>Once out of the loop <code>oddEven</code> will be less than zero if we are looking of even;</p>\n\n<p>Rather than use a statement and two constants to check each item for the remainder we can set that before the search.</p>\n\n<pre><code> oddEven = oddEven &gt; 0 ? 1 : 0;\n</code></pre>\n\n<p>Then we can use <code>Array.find</code> to locate the item returning it directly rather than waste time assigning it to a variable to return as you did.</p>\n\n<pre><code> return items.find(val =&gt; val % 2 === oddEven);\n}\n</code></pre>\n\n<p>The whole thing will look like</p>\n\n<pre><code>function findOutlier(items){\n var oddEven = 0, i = 3;\n while (i--) { oddEven += items[i] % 2 ? -1 : 1 }\n oddEven = oddEven &gt; 0 ? 1 : 0;\n return items.find(val =&gt; val % 2 === oddEven);\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-12T07:48:40.150", "Id": "453369", "Score": "0", "body": "Thanks a lot for your solution! I'll play around with it a bit to really grasp what's going on. Again TY!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-12T02:50:12.863", "Id": "232223", "ParentId": "232212", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-11T21:37:23.287", "Id": "232212", "Score": "4", "Tags": [ "javascript" ], "Title": "Find Index of SINGLE odd / even number in array" }
232212
<p><strong>Environment</strong></p> <p><a href="https://nasm.us/" rel="nofollow noreferrer">NASM</a> is required to build this program, and <a href="https://www.dosbox.com/" rel="nofollow noreferrer">DosBox</a> is required to run it. I'd recommend installing these using the <a href="https://scoop.sh/" rel="nofollow noreferrer">Scoop Package Manager</a>. Feel free to ignore install statements for any programs you have installed already.</p> <blockquote> <pre><code>iwr -useb get.scoop.sh | iex scoop install git scoop install dosbox scoop install nasm </code></pre> </blockquote> <p><strong>Building</strong></p> <blockquote> <pre><code>nasm -f bin -o helper.com helper.asm </code></pre> </blockquote> <p><strong>Running</strong></p> <p>Load DosBox, then mount the path where <code>helper.com</code> resides to any available drive. For those unfamiliar, it can be any drive in the A-Z range.</p> <pre><code>mount H: C:\Users\T145\Desktop\ H: dir helper.com </code></pre> <p><strong><em>helper.asm</em></strong></p> <pre class="lang-lisp prettyprint-override"><code>bits 16 org 0x100 section .text _main: lea di, [prompt] call putstring lea di, [string] call getstring lea di, [hello] call putstring lea di, [string] call putstring mov ah, 0x4c ; standard exit code mov al, 0 int 0x21 ; no parameters ; returns a char in ax getchar: mov ah, 0 ; call interrupt x16 sub interrupt 0 int 0x16 mov ah, 0 ret ; takes a char to print in dx ; no return value putchar: mov ax, dx ; call interrupt x10 sub interrupt xE mov ah, 0x0E mov cx, 1 int 0x10 ret ; takes an address to write to in di ; writes to address until a newline is encountered ; returns nothing getstring: call getchar ; read a character cmp ax, 13 ; dos has two ascii characters for new lines 13 then 10 je .done ; its not a 13, whew... cmp ax, 10 ; check for 10 now je .done ; its not a 10, whew... mov [di], al ; write the character to the current byte inc di ; move to the next address mov dx, ax ; dos doesn't print as it reads like windows, let's fix that call putchar jmp getstring .done: mov dx, 13 ; write a newline for sanity call putchar mov dx, 10 call putchar ret ; takes an address to write to in di ; writes to address until a newline is encountered ; returns nothing putstring: cmp byte [di], 0 ; see if the current byte is a null terminator je .done ; nope keep printing .continue: mov dl, [di] ; grab the next character of the string mov dh, 0 ; print it call putchar inc di ; move to the next character jmp putstring .done: ret section .data prompt: db "Please enter your first name: ", 0 string: times 20 db 0 hello: db "Hello, ", 0 </code></pre> <p><strong><em>Output</em></strong></p> <p><a href="https://i.stack.imgur.com/bPBck.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/bPBck.png" alt="output"></a></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-13T06:41:57.960", "Id": "453553", "Score": "0", "body": "Is there a particular reason you're using BIOS interrupts instead of DOS?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-13T11:57:24.277", "Id": "453606", "Score": "0", "body": "@Shift_Left No, not really. Idk wym by usage of DOS over BIOS interrupts tbh. This is my first time messing around w/ 16-bit assembly. I've read through [this official documentation page](https://www.nasm.us/doc/nasmdoc8.html) on the topic, but that's about it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-12T11:57:16.980", "Id": "457368", "Score": "0", "body": "This is not Win16, it is 8086 DOS." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-13T01:30:38.250", "Id": "457463", "Score": "0", "body": "@ecm Ty for that clarification; I'll be sure to use it in future questions relating to 16 bit NASM running on DOSBOX" } ]
[ { "body": "\n\n<h2>There's plenty to optimize here!</h2>\n\n<p>In NASM you get the address simply by writing <code>mov di, prompt</code>. This has a shorter encoding than <code>lea di, [prompt]</code>. (In MASM this would be <code>mov di, offset prompt</code> giving the same benefit over the <code>lea</code> form).</p>\n\n<p>Instead of writing the pair <code>mov ah, 0x4c</code> <code>mov al, 0</code>, you could combine these in 1 instruction as <code>mov ax, 0x4C00</code>. This shaves off 1 byte from the program.</p>\n\n<p>Your <em>getchar</em> returns a <strong>byte</strong> in <code>AX</code> and your <em>putchar</em> expects a <strong>byte</strong> in <code>DX</code>. You would be better off if you used <code>AL</code> and <code>DL</code>. This would avoid those several <code>mov ah, 0</code> and <code>mov dh, 0</code> instructions.</p>\n\n<p>Your <em>putchar</em> code uses the BIOS.Teletype function 0x0E. This function does not expect anything in the <code>CX</code> register. What it does require is that you specify the displaypage in the <code>BH</code> register. Simply add <code>mov bh, 0</code> here. And if it's even possible that your program has to run on the graphical video mode then it would make sense to write <code>mov bx, 0x0007</code> because then the color for the character is taken from the <code>BL</code> register.</p>\n\n<p>I see that the <em>getstring</em> code also checks for the linefeed code 10. No one does that. If the user presses the <kbd>Enter</kbd> key, you'll receive the carriage return code 13 and that's the only code that you need to check. The linefeed code only comes into play when outputting.</p>\n\n<p>The pair of instructions <code>mov [di], al</code> <code>inc di</code> (3 bytes) can be replaced by the 1-byte instruction <code>stosb</code>. Given that your program is in the .COM file format we have <code>DS</code>=<code>ES</code> and the direction flag is almost certainly going to be clear. Ideal for using the string primitive assembly instructions. This also means that your <em>putstring</em> routine could use <code>lodsb</code> if you're willing to trade in <code>DI</code> for <code>SI</code> as the input parameter.</p>\n\n<p>An interesting optimization comes from eliminating a <em>tail call</em>. You wrote <code>call putchar</code> directly followed by <code>ret</code>. This is equivalent to writing <code>jmp putchar</code>. Both shorter and faster this way!</p>\n\n<h2>Make it better</h2>\n\n<ul>\n<li><p>Your <em>getstring</em> procedure must not allow the user to input more than 19 characters. Anything more would overflow the 20-byte buffer.</p></li>\n<li><p>Your <em>getstring</em> procedure should store (in the buffer) a terminating zero when the finishing <kbd>Enter</kbd> key arrives. This way the buffer can be used repeatedly and not just this one time.</p></li>\n<li><p>In assembly we want to avoid all kinds of jumping because those are more time consuming than many other instructions.<br>\nYour <em>putstring</em> code uses a <code>je</code> and a <code>jmp</code> instruction on each iteration of the loop. The code below only uses the <code>jne</code> instruction on each iteration.</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>; IN (di)\nputstring:\n jmp .first\n.continue:\n call putchar\n inc di ; move to the next character\n.first:\n mov al, [di] ; grab the next character of the string\n cmp al, 0\n jne .continue\n ret\n\n; IN (al)\nputchar:\n mov ah, 0x0E ; BIOS.Teletype\n mov bx, 0x0007\n int 0x10\n ret\n</code></pre>\n\n<p>Using <code>DX</code> as the input for <em>putchar</em> is a poor choice, not only because <code>DL</code> would be enough, but especially because you need the character in <code>AL</code> anyway. So why not move it there in the first place?</p></li>\n</ul>\n\n<h2>Be consistent</h2>\n\n<p>Always write your numbers the same way. You wrote <code>mov ah, 0x4c</code> and also <code>mov ah, 0x0E</code>.<br>\nI suggest you use capitals for the hexadecimal digits and always write as many digits as will fit in the destination. So don't write stuff like <code>mov ah, 0xE</code>.<br>\nIn case you're wondering why I make this suggestion. Using uppercase hexadecimal digits enhances the contrast with the lowercase <code>0x</code> prefix or lowercase <code>h</code> suffix. Readability is very important in a program.</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>mov ah, 0x4C\nmov ah, 0x0E\n</code></pre>\n\n<p>or</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>mov ah, 4Ch\nmov ah, 0Eh\n</code></pre>\n\n<p>For many programmers function numbers are easiest recognized when expressed in hexadecimal.\nYou could thus write <code>mov ah, 0x00</code> <code>int 0x16</code> in your <em>getchar</em> routine.</p>\n\n<hr>\n\n<p>As a final note, your labels are well chosen and the comments that you've added are all to the point. Congrats...</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-13T15:02:03.983", "Id": "232325", "ParentId": "232221", "Score": "3" } }, { "body": "<p>In the face of all else the assembler assumes a 16bit flat binary, so all that is required is;</p>\n\n<blockquote>\n <p>~$ nasm ?.asm -o?.com</p>\n</blockquote>\n\n<p>Although not wrong, but even <strong>bits 16</strong> is redundant. In operating system development you might <strong>use32</strong> or <strong>use64</strong> to utilize those instruction sets, but it would still be a flat binary file. Otherwise, the only thing that makes this type of executable unique is;</p>\n\n<pre><code> org 0x100\n</code></pre>\n\n<p>This establishes the entry point, so a label like <strong>main</strong> is unnecessary unless it is required to branch back to the beginning of the application.</p>\n\n<p>As to the question I asked in your original post, knowing what resources you have to deal with is monumentally important. DOS provides a lot of utility that can be found <a href=\"http://www.ctyme.com/intr/int.htm\" rel=\"nofollow noreferrer\">here</a>, therefore this</p>\n\n<pre><code> mov dx, Prompt\n mov ah, WRITE\n int DOS\n</code></pre>\n\n<p>replaces all of this</p>\n\n<pre><code> putstring:\n cmp byte [di], 0 ; see if the current byte is a null terminator\n je .done ; nope keep printing\n .continue:\n mov dl, [di] ; grab the next character of the string\n mov dh, 0 ; print it\n call putchar\n inc di ; move to the next character\n jmp putstring\n .done:\n ret\n</code></pre>\n\n<p>by terminating string with what DOS expects as so</p>\n\n<pre><code> Prompt db 13, 10, 13, 10, 'Please enter your first name: $'\n</code></pre>\n\n<p>and because CR/LF is embedded in string now, this can be eliminated.</p>\n\n<pre><code> mov dx, 13 ; write a newline for sanity\n call putchar\n mov dx, 10\n call putchar\n</code></pre>\n\n<p>Input as such</p>\n\n<pre><code>; Read string from operator\n mov dx, InpBuff\n mov ah, READ\n int DOS\n\n; To a buffer specified with Max input of 128 chars. -1 is just a place holder\n; which will be replace by the number of characters entered.\n\n InpBuff: db 128, -1 \n</code></pre>\n\n<p>The input is terminated with 0x0D and must be replaced with '$'. This little snippet does that.</p>\n\n<pre><code>; Terminate this input with '$'\n mov bx, dx\n movzx ax, byte [bx+1]\n inc al\n inc al\n add bx, ax\n mov byte [bx], '$'\n</code></pre>\n\n<p>replaces these</p>\n\n<pre><code> ; no parameters\n ; returns a char in ax\n getchar:\n mov ah, 0 ; call interrupt x16 sub interrupt 0\n int 0x16\n mov ah, 0\n ret\n\n ; takes an address to write to in di\n ; writes to address until a newline is encountered\n ; returns nothing\n getstring:\n call getchar ; read a character\n cmp ax, 13 ; dos has two ascii characters for new lines 13 then 10\n je .done ; its not a 13, whew...\n cmp ax, 10 ; check for 10 now\n je .done ; its not a 10, whew...\n mov [di], al ; write the character to the current byte\n inc di ; move to the next address\n mov dx, ax ; dos doesn't print as it reads like windows, let's fix that\n call putchar\n jmp getstring\n</code></pre>\n\n<p>So all in all this code is almost 50% smaller (91 bytes vs 163) and only because I've utilized what DOS provides. If I was to have utilized BIOS calls, then my code would not have been that much smaller, maybe 5-10 %.</p>\n\n<pre><code> org 0x100\n\n DOS equ 33 ; = 21H\n WRITE equ 9\n READ equ 10\n\n ; Display initial prompting\n mov dx, Prompt\n mov ah, WRITE\n int DOS\n\n ; Read string from operator\n mov dx, InpBuff\n mov ah, READ\n int DOS\n\n ; Terminate this input with '$'\n mov bx, dx\n movzx ax, byte [bx+1]\n inc al\n inc al\n add bx, ax\n mov byte [bx], '$'\n\n ; Display next prompting\n push dx ; We will want this pointer again\n mov dx, hello\n mov ah, WRITE\n int DOS\n\n pop dx\n inc dx ; Bump over max and actual lengths\n inc dx\n int DOS \n ret\n\n Prompt db 13, 10, 13, 10, 'Please enter your first name: $'\n hello db 10, 10, 9, 'Hello, $'\n InpBuff: db 128, -1 \n</code></pre>\n\n<p>I changed the formatting of hello slightly just you can see the difference and experiment a little and replace 10's with 13's @ hello and watch what happens.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-13T18:39:15.980", "Id": "453654", "Score": "0", "body": "Wow, that's amazing! Just out of curiosity, why do you `inc dx` twice after popping, and have `-1` on the tail of `InpBuff`? To the last point, there's no [ASCII](https://www.asciitable.com/) code for it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-13T19:02:16.990", "Id": "453658", "Score": "0", "body": "DX is pointing to the very beginning of InBuf, so it has to be incremented twice to point to the actual text. -1 is just a place holder so when I'm looking for the string or that section of the buffer in debug, it's easy to identify, otherwise it doesn't need to be there. I used inc twice has it's one byte shorter than `add dx,2`. The second byte of InBuff will be replace with the number of characters entered." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-13T16:02:58.657", "Id": "232332", "ParentId": "232221", "Score": "2" } } ]
{ "AcceptedAnswerId": "232332", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-12T01:05:55.863", "Id": "232221", "Score": "6", "Tags": [ "windows", "assembly", "nasm" ], "Title": "String helper functions in NASM Win16 Assembly" }
232221
<p>I am working on the class question find the longest common substring from 2 strings but I would like to return the longest common substring instead of just size of longest common substring.like</p> <pre><code>s1 = 'abcdex', s2 = 'xbcdey' =&gt; 'bcde' s1 = 'abcxyx', s2 = 'xbcydey' =&gt; 'bc' </code></pre> <p>The way I do it is using dynamic programming to create a memo table and update each cell that required space <span class="math-container">\$O(n * m)\$</span>. How can I implement the code so I can only using space as <span class="math-container">\$O(n)\$</span>?</p> <pre><code> def longestCommonSubstring(self, s1, s2): """ :type s: str :rtype: str """ m, n = len(s1), len(s2) dp = [[''] * (n + 1) for _ in range(m + 1)] max_len = '' for i, ic in enumerate(s1): for j, jc in enumerate(s2): dp[i][j] = dp[i - 1][j - 1] + ic if ic == jc else '' max_len = dp[i][j] if len(max_len) &lt; len(dp[i][j]) else max_len return max_len </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-12T05:25:25.470", "Id": "453360", "Score": "3", "body": "I have rolled-back the latest edit to your question. Please see [What should I do when someone answers my question](https://codereview.stackexchange.com/help/someone-answers) for what you can and/or should do when someone answers your question; in particular, the **What should I _not_ do** section." } ]
[ { "body": "<p>You don't specify what <code>n</code> is, so I'm going to assume that <code>n</code> is the total combined length of the two strings <code>s1</code> and <code>s2</code> that are input.</p>\n\n<p>Imagine you have a <a href=\"https://en.wikipedia.org/wiki/Hash_function\" rel=\"nofollow noreferrer\">hashing function</a> <code>h(s)</code> that computes a fixed-size hash value for a given string <code>s</code>. That is, given a string <code>s = \"abc\"</code> the function <code>h(s)</code> will return some number <code>X</code> that is computed from <code>s</code>, so that changing the contents of <code>s</code> will change the returned value <code>X</code>. </p>\n\n<p>If you keep an array of hash values for the substrings of a given length <code>k</code> for each starting position <code>i</code>, you will have a total size of <code>sizeof(h(s1)) * (n - 2k + 2)</code> which is easily <span class=\"math-container\">\\$O(n)\\$</span>.</p>\n\n<p>So, start from the longest possible substring and work your way down, computing the hashes of all substrings then checking to see if the two strings share a common substring. If two hashes are equal you can compare the resulting substrings and return if you find a match. If you get to <code>k==1</code> and find no match, then there's no match to be had.</p>\n\n<p>With that outline, I'll point out that python provides a built-in called <a href=\"https://docs.python.org/3/library/functions.html?highlight=hash#hash\" rel=\"nofollow noreferrer\"><code>hash()</code></a> that does what you want.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-12T04:40:52.027", "Id": "453356", "Score": "2", "body": "This is not a review of the OP's code, but an alternate solution." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-12T03:42:29.557", "Id": "232225", "ParentId": "232224", "Score": "-2" } }, { "body": "<h2>PEP 8</h2>\n\n<p>You are following most of the PEP 8 style guidelines. One that you are breaking is method names should be <code>snake_case</code>; your function should be named <code>longest_common_substring</code>.</p>\n\n<h2>Tricky Code</h2>\n\n<p>Your <code>dp</code> matrix is properly allocated to the size <code>m+1</code> by <code>n+1</code>.</p>\n\n<p>When you index your matrix, you access <code>[i-1][j-1]</code> with <span class=\"math-container\">\\$0 \\le i \\lt m\\$</span> and <span class=\"math-container\">\\$0 \\le j \\lt n\\$</span>. This means you never access the last allocated row <code>m</code> or the last allocated column <code>n</code>, but instead rely on accessing the <code>-1</code> row and the <code>-1</code> column wrapping around to reach these \"unused\" spaces. This is \"surprising\" code at best, and \"crashing\" code if translated to a different programming language.</p>\n\n<p>It would be better to add one to the indices used to index the <code>dp</code> matrix. The simplest way would be to start the <code>i</code> and <code>j</code> enumerations at one:</p>\n\n<pre><code> for i, ic in enumerate(s1, 1):\n for j, jc in enumerate(s2, 1):\n</code></pre>\n\n<h2>Useless <code>else</code></h2>\n\n<p>Expand out this <code>... if ... else ...</code> statement:</p>\n\n<pre><code> max_len = dp[i][j] if len(max_len) &lt; len(dp[i][j]) else max_len\n</code></pre>\n\n<p>Initially, this produces:</p>\n\n<pre><code> if len(max_len) &lt; len(dp[i][j]):\n max_len = dp[i][j]\n else:\n max_len = max_len\n</code></pre>\n\n<p>But we can immediately see the <code>else:</code> clause is a no-op, and can be removed:</p>\n\n<pre><code> if len(max_len) &lt; len(dp[i][j]):\n max_len = dp[i][j]\n</code></pre>\n\n<p>Which reads much more clearly than the original.</p>\n\n<h2>From <span class=\"math-container\">\\$O(n m)\\$</span> to <span class=\"math-container\">\\$O(n)\\$</span> space</h2>\n\n<p>During the first iteration of outer loop, you only access rows <code>-1</code> and <code>0</code>. During the second iteration of outer loop, you only access rows <code>0</code> and <code>1</code>. During the third iteration of outer loop, you only access rows <code>1</code> and <code>2</code>. Etc. You only need two rows of the <code>dp</code> matrix!</p>\n\n<p>More over, you create the <code>0</code> row from the <code>-1</code> row, you create the <code>1</code> from the <code>0</code> row, you create the <code>2</code> row from the <code>1</code> row, and so on.</p>\n\n<p>Do you really need to keep the <code>dp</code> matrix? Or could you use a <code>previous_row</code> and a <code>current_row</code>? Only storing two length <code>n</code> rows reduces your space to <span class=\"math-container\">\\$O(2n)\\$</span>, which is simply <span class=\"math-container\">\\$O(n)\\$</span>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-12T05:19:46.803", "Id": "453359", "Score": "0", "body": "thank you for your hint, just update the question with space O(n) solution" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-12T05:27:46.320", "Id": "453362", "Score": "4", "body": "And I've just rolled-back your update. Editing your question after it has been answered invalidates answers. Adding new code creates confusion (are the answers referring to the old code, the new code, both?). If you want to post your updated code for additional review, it must be posted as a new question." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-12T04:33:36.357", "Id": "232226", "ParentId": "232224", "Score": "8" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-12T02:54:20.827", "Id": "232224", "Score": "7", "Tags": [ "python", "python-3.x", "dynamic-programming" ], "Title": "find longest common substring in space O(n)" }
232224
<p>I'm new to python and newer still to pygame. In my attempt to learn, I set to make a basic menu with buttons. Here's my code: (note, ui_plate, is a system that the buttons are based on, it keeps all the ui in the same relative positions and sizes, no matter the size of the window.)</p> <pre><code>#===Setup========================================================================== import pygame from pygame.locals import * pygame.init() global winW, winH winW, winH = (960, 508) window = pygame.display.set_mode((winW, winH), pygame.RESIZABLE) pygame.display.set_caption("SMC") run = True #===UI plate======================================================================= def ui_plate(): global uiW, uiH, uiX, uiY if winH &gt; winW*0.5296: uiW = int(winW) uiH = int(uiW*0.5296) else: uiH = int(winH) uiW = int(uiH/0.5296) uiX = int((winW - uiW)/2) uiY = int((winH - uiH)/2) #===Button class=================================================================== class button: def __init__(self, action, actionParam, buttonPic, x, y, w, h): self.action = action self.actionParam = actionParam self.bx = int(uiX + (x * uiW)) self.by = int(uiY + (y * uiH)) self.bw = int(w * uiW) self.bh = int(h * uiH) self.buttonPic = pygame.transform.scale(buttonPic, (self.bw, self.bh)) self.over = pygame.Surface((self.bw, self.bh)) self.over.fill((0,0,0)) def draw_button(self): if window.blit(self.buttonPic, (self.bx, self.by)).collidepoint(mouse): self.over.set_alpha(50) if click[0]: self.over.set_alpha(100) else: self.over.set_alpha(0) window.blit(self.buttonPic, (self.bx, self.by)) window.blit(self.over, (self.bx, self.by)) def click_button(self): if window.blit(self.buttonPic, (self.bx, self.by)).collidepoint(mouse): self.action(self.actionParam) #===Button actions================================================================= def screen_swap(screen): global current_screen current_screen = screen #------------------------------------------------------------------------ def printT(t): print(t) #------------------------------------------------------------------------ def exit_loop(blank): global run run = False #------------------------------------------------------------------------ #===Menus========================================================================== def main_menu(): global buttonList backGround_image = pygame.image.load('Background.jpg') backGround = pygame.transform.scale(backGround_image, (winW, winH)) ButtonPic = pygame.image.load('Button.jpg') buttonList = [ button(screen_swap, second_menu, ButtonPic, .1, .1, .1, .1), button(printT, 'Hello!', ButtonPic, .1, .3, .1, .1), button(printT, 'Hello my friend', ButtonPic, .1, .5, .1, .1) ] window.blit(backGround, (0, 0)) for b in buttonList: b.draw_button() #------------------------------------------------------------------------ def second_menu(): global buttonList backGround_image = pygame.image.load('Button.jpg') backGround = pygame.transform.scale(backGround_image, (winW, winH)) ButtonPic = pygame.image.load('Background.jpg') buttonList = [ button(screen_swap, main_menu, ButtonPic, .75, .1, .1, .1), button(printT, 'Bye', ButtonPic, .75, .2, .1, .1), button(exit_loop, None, ButtonPic, .75, .3, .1, .1) ] window.blit(backGround, (0, 0)) for b in buttonList: b.draw_button() #===Main Loop====================================================================== def main_loop(): global run, winW, winH, mouse, click ui_plate() backGround = 0 while run: mouse = pygame.mouse.get_pos() click = pygame.mouse.get_pressed() current_screen() events = pygame.event.get() for event in events: if event.type == pygame.QUIT: run = False if event.type == pygame.VIDEORESIZE: window = pygame.display.set_mode ( (event.w, event.h) , pygame.RESIZABLE) winW, winH = event.w, event.h ui_plate() if event.type == pygame.MOUSEBUTTONUP: for b in buttonList: b.click_button() pygame.display.update() #================================================================================== current_screen = main_menu main_loop() pygame.quit() </code></pre> <p>if you want to run it, which I would hope you do, as it will help me show you my issue, just get two images, call one "Background.jpg" and the other "Button.jpg", exact dimensions don't matter. </p> <p>So there are two main issues I have right now, first, when I hover my mouse over a button, it is very slow to update the image showing that the button is being hovered over, and when I click and release a button, it flashes for a single frame before showing the correct hover state. (Note, the issues are more apparent in larger window sizes)</p> <p>So I need help getting that to be responsive and clean, and if it's not too much to ask, I'd also like to know how well written the whole thing is, what could be improved, etc.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-12T08:04:06.127", "Id": "453373", "Score": "1", "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." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-12T07:19:58.680", "Id": "232228", "Score": "1", "Tags": [ "python", "pygame" ], "Title": "Basic pygame menu with buttons" }
232228
<p>I have used below code, code is working fine, also retrieved the data, but there are performance issues. Retrieving the HKLM registry nodes is taking around 6 mins time. Please suggest any solution.</p> <pre><code>Private Function f_AddNodes(ByVal WindowsRegistryKey As RegistryKey, ByVal TreeNode As TreeNodeCollection, ByVal RegParent As Integer) As Integer Dim root As TreeNode If count = 1 Then root = TreeNode(RegParent) Else Dim KeyName = WindowsRegistryKey.Name Dim nLastIndex = KeyName.LastIndexOf("\") KeyName = KeyName.Substring(nLastIndex + 1, (KeyName.Length - 1) - nLastIndex) root = TreeNode.Add(KeyName) 'Node adding End If For Each subkeyName As String In WindowsRegistryKey.GetSubKeyNames Try Form_LoadingBar.Value(WindowsRegistryKey.Name) count = count + 1 Dim vSubKey As RegistryKey = WindowsRegistryKey.OpenSubKey(subkeyName) f_AddNodes(vSubKey, root.Nodes, -1) Catch ex As SecurityException sExceptionHandling.Append(WindowsRegistryKey.Name + "\" + subkeyName + "," + ex.Message + vbNewLine) Catch ex As Exception MsgBox(ex.ToString) Return -1 End Try Next`enter code here` Return 0 End Function </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-12T19:09:08.140", "Id": "453483", "Score": "0", "body": "When submitting code, one thing to remember, you need to explain and/or show code for those variables that are created outside your code. For instance: What is `Form_LoadingBar`? What is `sExceptionHandling`? Where does `count` come from?" } ]
[ { "body": "<p>It looks to me, one of your biggest problems is working directly with the <code>Nodes</code> of the <code>TreeView</code>. This necessitates calling <code>Paint()</code> everytime you add a node. If you start with a new <code>TreeNode</code> as root, and build the tree on that, you can add the whole thing to the <code>TreeView</code> by adding the root to the <code>Nodes</code>. </p>\n\n<p>I also found that running VS as administrator greatly reduced the number of errors, which also sped it up.</p>\n\n<p>By using a custom <code>TreeNode</code> class that inherits from <code>Forms.TreeNode</code>, you can recursively fill the tree inside the class. This also allows you to store the actual <code>RegistryKey</code> object in each node. Here's a relatively simple way of doing it:</p>\n\n<pre><code>Public Class RegistryTreeNode\n Inherits TreeNode\n Private Class SecurityExceptionLogger\n Private Shared Property Exceptions As New List(Of (String, SecurityException))\n Private Shared TempFileName As String = Path.GetTempFileName()\n Private Shared writer As StreamWriter\n Private Shared reader As StreamReader\n Public Shared Async Sub Add(exception As SecurityException)\n Exceptions.Add((Now.ToUniversalTime, exception))\n Using writer = New StreamWriter(TempFileName, True)\n Await writer.WriteLineAsync($\"{Now.ToUniversalTime} - {exception.Message}\")\n End Using\n End Sub\n Public Shared Sub PrintExceptions(stream As StreamWriter)\n Using stream\n Exceptions.ForEach(Async Sub(x)\n Await stream.WriteLineAsync($\"{x.Item1} - {x.Item2.Message}\")\n End Sub)\n End Using\n End Sub\n\n End Class\n Private _RegKey As RegistryKey\n\n Private Property RegKey As RegistryKey\n Get\n Return _RegKey\n End Get\n Set\n _RegKey = Value\n Name = _RegKey.Name\n Text = Name\n For Each key In _RegKey.GetSubKeyNames\n Try\n Nodes.Add(New RegistryTreeNode(_RegKey.OpenSubKey(key)))\n Catch ex As SecurityException\n SecurityExceptionLogger.Add(ex)\n Catch ex As Exception\n MsgBox(ex.Message)\n End Try\n Next\n End Set\n End Property\n\n Public Sub New()\n MyBase.New()\n RegKey = Registry.LocalMachine\n End Sub\n Public Sub New(newRegistryKey As RegistryKey)\n MyBase.New()\n RegKey = newRegistryKey\n End Sub\nEnd Class\n</code></pre>\n\n<p>I hardcoded the default key to <code>Registry.LocalMachine</code> for your uses. Simply <code>Dim root = New RegistryTreeNode()</code> and the whole tree will build itself.</p>\n\n<p>You'll notice I made a simple logger that writes to file as well as keeping a record in memory, instead of just in memory, just as an exercise.</p>\n\n<p>Another way to speed things up, is to only load the first sub level of nodes on start up. You can then use the <code>AfterSelect</code> event handler to load the sub nodes of the key you want to expand. Something like this:</p>\n\n<pre><code>Public Class Form1\n Dim root = New RegistryTreeNode(Registry.LocalMachine)\n Public Sub New()\n\n ' This call is required by the designer.\n InitializeComponent()\n\n ' Add any initialization after the InitializeComponent() call.\n TreeView1.Nodes.Add(root)\n End Sub\n\n\n Private Sub TreeView1_AfterSelect(sender As Object, e As TreeViewEventArgs) Handles TreeView1.AfterSelect\n Dim node = DirectCast(TreeView1.SelectedNode, RegistryTreeNode)\n For Each key In node.GetSubKeyNames\n Try\n Dim regKey = New RegistryTreeNode(node.OpenSubKey(key))\n If Not regKey Is Nothing Then\n node.Nodes.Add(regKey)\n End If\n\n Catch ex As SecurityException\n SecurityExceptionLogger.Add(ex)\n Catch ex As Exception\n MsgBox(ex.Message)\n End Try\n Next\n\n End Sub\n\nEnd Class\nClass SecurityExceptionLogger\n Private Shared Property Exceptions As New List(Of (String, SecurityException))\n Private Shared TempFileName As String = Path.GetTempFileName()\n Private Shared writer As StreamWriter\n Private Shared reader As StreamReader\n Public Shared Async Sub Add(exception As SecurityException)\n Exceptions.Add((Now.ToUniversalTime, exception))\n Using writer = New StreamWriter(TempFileName, True)\n Await writer.WriteLineAsync($\"{Now.ToUniversalTime} - {exception.Message}\")\n End Using\n End Sub\n Public Shared Sub PrintExceptions(stream As StreamWriter)\n Using stream\n Exceptions.ForEach(Async Sub(x)\n Await stream.WriteLineAsync($\"{x.Item1} - {x.Item2.Message}\")\n End Sub)\n End Using\n End Sub\n\nEnd Class\nPublic Class RegistryTreeNode\n Inherits TreeNode\n\n Private _RegKey As RegistryKey\n\n Private Property RegKey As RegistryKey\n Get\n Return _RegKey\n End Get\n Set\n _RegKey = Value\n Name = _RegKey.Name\n Text = Name.Substring(Name.LastIndexOf(\"\\\"c) + 1)\n\n End Set\n End Property\n\n Public Sub New()\n MyBase.New()\n RegKey = Registry.LocalMachine\n End Sub\n Public Sub New(newRegistryKey As RegistryKey)\n MyBase.New()\n RegKey = newRegistryKey\n End Sub\n Public Function GetValueNames() As List(Of String)\n Return _RegKey.GetValueNames().ToList()\n End Function\n Public Function GetValueKind(name As String) As RegistryValueKind\n Return _RegKey.GetValueKind(name)\n End Function\n Public Function GetValue(name As String) As Object\n Return _RegKey.GetValue(name)\n End Function\n Public Function GetSubKeyNames() As String()\n Return _RegKey.GetSubKeyNames()\n End Function\n Public Function OpenSubKey(key As String) As RegistryKey\n Return _RegKey.OpenSubKey(key)\n End Function\nEnd Class\n</code></pre>\n\n<p>I moved the <code>SecurityExceptionLogger</code> outside the <code>RegistryTreeNode</code> class. You can also load the values for the keys, if needed, by looping through them after the sub nodes are added.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-14T04:38:39.587", "Id": "453706", "Score": "0", "body": "Thanks for your reply. I tried with this source code. Still it is slow as retrieving time taking around 4 mins." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-14T20:33:21.460", "Id": "453843", "Score": "0", "body": "@SankarS - I added more code, which shows loading only the first sub level. then any others on demand. Not sure how this will fit your needs but it is really fast." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-15T10:50:05.317", "Id": "453905", "Score": "0", "body": "Thanks, Yes, it its very fast.but my tree has checkboxes, hence, when i checked HKLM alone, automatically all the sub nodes(entire HKLM data) should be retrieved with values. I tried this one , i have extracted all the nodes and saved it to LIST, it takes 4 mins. this time is ok. But when i looping LIST, to take the values , it takes around 10 mins." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-13T04:00:10.593", "Id": "232292", "ParentId": "232234", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-12T09:55:50.487", "Id": "232234", "Score": "2", "Tags": [ "performance", "vb.net", "windows" ], "Title": "Retrieving HKLM nodes of Windows10 Registry" }
232234
<p>I have two different pandas data frames where in the first data frame (price), I have two columns. The first column named value has some values in it and the second column amount has the available amount for each price. The second data frame (bins) has as index some price intervals which are produced from the price data frame. For each row of the price data frame I check each row of the value column to find the interval that it belongs from the bins data frame and if the value is in an interval I assign the available amount in the bins data frame. If another value is again in the same interval I sum up these amounts in the group_bins data frame.</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd bins = pd.DataFrame({ 'value': [1, 2, 5, 7, 8, 16, 20, 3, 9, 11, 35, 12, 54, 33, 3, 22, 23] }) price = pd.DataFrame({ 'value': [2, 5, 7, 8, 16, 20, 3, 9, 11, 2.5, 3.4], 'amount': [50, 112, 130, 157, 146, 148, 300, 124, 151, 100, 32] }) bins['bins'] = pd.qcut(bins['value'], 12) group_bins = bins.groupby(['bins']).sum() group_bins['amount'] = 0 del group_bins['value'] for j in range(price.shape[0]): for i in range(group_bins.shape[0]): if price.loc[j, 'value'] in group_bins.index[i]: group_bins.loc[group_bins.index[i], 'amount'] += price.loc[j, 'amount'] break </code></pre> <p>Expected Result:</p> <pre class="lang-py prettyprint-override"><code> amount bins (0.999, 2.333] 50 (2.333, 3.0] 400 (3.0, 5.0] 144 (5.0, 7.333] 130 (7.333, 8.667] 157 (8.667, 11.0] 275 (11.0, 13.333] 0 (13.333, 18.667] 146 (18.667, 22.0] 148 (22.0, 26.333] 0 (26.333, 34.333] 0 (34.333, 54.0] 0 </code></pre> <p>My problem is that I have 100k data and all this process takes too long to finish. Is there any elegant and much faster way to replace these nested for loops and the if condition?</p> <p>The expected result is the final column in the group_bins amount column. Any help would be much appreciated! Thank you.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-12T13:41:25.513", "Id": "453416", "Score": "1", "body": "Welcome to Code Review! Please edit your question so that the title describes the *purpose* of the code, rather than its *mechanism*. We really need to understand the motivational context to give good reviews. Thanks!" } ]
[ { "body": "<p>This can be solved using <code>groupby</code> directly. First, get the bins you want to use, then just <a href=\"https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.cut.html\" rel=\"nofollow noreferrer\"><code>pandas.cut</code></a> the actual values into those bins.</p>\n\n<pre><code>binning = pd.qcut(bins['value'], 12, retbins=True)[1]\ngroup_bins = price.groupby(pd.cut(price.value, binning)).amount.sum()\n</code></pre>\n\n<p>This produces basically the same output for the given example, except that it is a <code>pandas.Series</code> instead of a <code>pandas.DataFrame</code>:</p>\n\n<pre><code>value\n(1.0, 2.333] 50\n(2.333, 3.0] 400\n(3.0, 5.0] 144\n(5.0, 7.333] 130\n(7.333, 8.667] 157\n(8.667, 11.0] 275\n(11.0, 13.333] 0\n(13.333, 18.667] 146\n(18.667, 22.0] 148\n(22.0, 26.333] 0\n(26.333, 34.333] 0\n(34.333, 54.0] 0\nName: amount, dtype: int64\n</code></pre>\n\n<p>In addition, you should probaly put this into a function and only call it from a <a href=\"http://stackoverflow.com/questions/419163/what-does-if-name-main-do\"><code>if __name__ == \"__main__\":</code> guard</a> to allow importing from the file.</p>\n\n<p>I am not quite sure why you need to determine the binning the way you do, though. From your variable names I would have assumed that <code>bins.value</code> are the bin edges to be used instead.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-12T11:37:22.623", "Id": "453406", "Score": "0", "body": "Hi, implementing your suggestion results in TypeError: float() argument must be a string or a number, not 'pandas._libs.interval.Interval'. This happens because the intervals in the pd.cut function should be determined as a list of [0.999, 2.333, 3, 4, 7.333, 8.667, 11.0, 13.333, 18.667, 26.333, 34.333, 54.0]. Any idea how to fix this problem instead of inserting the intervals manually? Thank you Graipher!!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-12T11:42:33.063", "Id": "453407", "Score": "0", "body": "@NestorasChalkidis: Fixed. It must've been some leftover from your code that made it working. The trick is to return the bins from `pandas.qcut` and use that." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-12T11:09:56.380", "Id": "232240", "ParentId": "232238", "Score": "3" } } ]
{ "AcceptedAnswerId": "232240", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-12T10:54:01.427", "Id": "232238", "Score": "3", "Tags": [ "python", "pandas" ], "Title": "Map price values to bins where bins are of a larger price range" }
232238
<p>About binary heaps: <a href="https://en.wikipedia.org/wiki/Binary_heap" rel="nofollow noreferrer">https://en.wikipedia.org/wiki/Binary_heap</a></p> <p>The purpose of this module is to allow quick and efficient priority queue management, compared to linked list.<br> Efficiency: insert: <span class="math-container">\$O(\log(n))\$</span>, pop: <span class="math-container">\$O(\log(n))\$</span>. </p> <pre><code>export enum BinaryHeapType { min = 1, max = 2, } export default class BinaryHeap { public heap: number[] = []; private check: (parent: number, current: number) =&gt; boolean; private type: BinaryHeapType; constructor(_heap: number[], _type?: BinaryHeapType) { this.heap = _heap; this.type = _type || BinaryHeapType.max; if (this.type == BinaryHeapType.max) { this.check = (parent, current) =&gt; parent &gt;= current; } else if (this.type == BinaryHeapType.min) { this.check = (parent, current) =&gt; parent &lt;= current; } else { throw "Unsupported heap type"; } this.heap = this.heap.sort((a, b)=&gt; { if (a &gt; b) return this.type == BinaryHeapType.max ? -1 : 1; if (a &lt; b) return this.type == BinaryHeapType.max ? 1 : -1; return 0; }); } public insert(val: number) { if (this.type == BinaryHeapType.max) { this.heap.push(val); this.bubbleUp(); } else if (this.type == BinaryHeapType.min) { this.heap.unshift(val); this.sinkDown(0) } } public extractTop() { const max = this.heap[0]; this.heap[0]= this.heap.pop() this.sinkDown(0) return max } public peakTop() { return this.heap[0]; } private bubbleUp() { let index = this.heap.length - 1; while (index &gt; 0) { let element = this.heap[index]; let parentIndex = Math.floor((index - 1) / 2); let parent = this.heap[parentIndex]; if (this.check(parent, element)) break this.heap[index] = parent; this.heap[parentIndex] = element; index = parentIndex; } } private sinkDown(index) { let left = 2 * index + 1, right = 2 * index + 2, largest = index; const length = this.heap.length // if left child is greater than parent if (left &lt;= length &amp;&amp; this.check(this.heap[left], this.heap[largest])) { largest = left } // if right child is greater than parent if (right &lt;= length &amp;&amp; this.check(this.heap[right], this.heap[largest])) { largest = right } // swap if (largest !== index) { [this.heap[largest], this.heap[index]] = [this.heap[index], this.heap[largest]] this.sinkDown(largest) } } } </code></pre> <p>Code: <a href="https://github.com/Livshitz/libx.js/blob/master/compiled/modules/BinaryHeap.ts" rel="nofollow noreferrer">https://github.com/Livshitz/libx.js/blob/master/compiled/modules/BinaryHeap.ts</a></p> <p>Unit tests: <a href="https://github.com/Livshitz/libx.js/blob/master/tests/libx.binaryHeap.test.ts" rel="nofollow noreferrer">https://github.com/Livshitz/libx.js/blob/master/tests/libx.binaryHeap.test.ts</a></p> <p>Extra: How would you suggest implement a generic object support for this heap? So we could insert an object (that implements a interface, lets say <code>IPrioritized</code>, that has a numeric value which will determine its position)?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-12T15:51:43.293", "Id": "453431", "Score": "0", "body": "*implement a generic object support for this heap* - that sounds like you ask for some additional implementation or extension for your approach. That may be out of scope" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-12T13:42:39.237", "Id": "232248", "Score": "1", "Tags": [ "javascript", "performance", "complexity", "typescript", "heap" ], "Title": "Binary Heap module in Typescript/Javascript supporting min-heap and max-heap" }
232248
<p>Is there anything you would suggest to improve this code? In particular, any code to make the snake move more smoothly and make the cursor disappear.</p> <pre><code>#include &lt;iostream.h&gt; #include &lt;conio.h&gt; #include &lt;stdlib.h&gt; #include &lt;dos.h&gt; unsigned long int score, high_score = 0; const int no_rows = 22, no_columns = 77, head_position = 0; char choice, token, token_food, key_press, direction_head, overlay; char board[no_rows][no_columns]; unsigned int i, j, k, snake_length, grow, crash; struct position { int row; int column; } head_map[no_rows * no_columns], food, temp1, temp2; void Initialize() { start: clrscr(); cout &lt;&lt; "\t\t\t\tWELCOME TO SNAKE GAME\n\n\n"; cout &lt;&lt; "Choose the Body of the Snake(Enter a symbol):\n"; cin &gt;&gt; token; cout &lt;&lt; "\nChoose the Food of the Snake(Enter a symbol):\n"; cin &gt;&gt; token_food; if(token_food == token) { clrscr(); cout &lt;&lt; "\nDon't use the same symbols for food and body of the snake!!!\n\n\n"; goto start; } cout &lt;&lt; "\n\nUP\t-\tW\nDOWN\t-\tS\nRIGHT\t-\tD\nLEFT\t-\tA\n\n\nARE YOU READY(Y / N) ?? \n"; cin &gt;&gt; choice; for (i = 0; i &lt; no_rows; i++) { for (j = 0; j &lt; no_columns; j++) board[i][j] = ' '; } head_map[0].row = no_rows / 2; head_map[0].column = no_columns / 2; board[head_map[0].row][head_map[0].column] = token; direction_head = 'R'; snake_length = 1; grow = crash = score = 0; } void Food() { do { food.row = rand() % no_rows; food.column = rand() % no_columns; } while(board[food.row][food.column] == token); board[food.row][food.column] = token_food; } void Display() { clrscr(); for(k = 0; k &lt; (no_columns + 2); k++) cout &lt;&lt; "-"; cout &lt;&lt; endl; for(i = 0; i &lt; no_rows; i++) { cout &lt;&lt; "|"; for(j = 0; j &lt; no_columns; j++) cout &lt;&lt; board[i][j]; cout &lt;&lt; "|" &lt;&lt; endl; } for(k = 0; k &lt; (no_columns + 2); k++) cout &lt;&lt; "-"; cout &lt;&lt; "\t\t\t\t\t SCORE :" &lt;&lt; score; } void Input() { if(kbhit()) { key_press = getch(); if((key_press == 'd' || key_press == 'D') &amp;&amp; (key_press != 'a' || key_press != 'A') &amp;&amp; (direction_head != 'L')) direction_head = 'R'; if((key_press == 's' || key_press == 'S') &amp;&amp; (key_press != 'w' || key_press != 'W') &amp;&amp; (direction_head != 'U')) direction_head = 'D'; if((key_press == 'a' || key_press == 'A') &amp;&amp; (key_press != 'd' || key_press != 'D') &amp;&amp; (direction_head != 'R')) direction_head = 'L'; if((key_press == 'w' || key_press == 'W') &amp;&amp; (key_press != 's' || key_press != 'S') &amp;&amp; (direction_head != 'D')) direction_head = 'U'; if(key_press == 'p' || key_press == 'P') delay(5000); } temp1 = head_map[head_position]; board[head_map[head_position].row][head_map[head_position].column] = ' '; switch(direction_head) { case 'R': { if(head_map[head_position].column == no_columns) crash = 1; overlay = board[head_map[head_position].row][++head_map[head_position].column]; break; } case 'L': { if(head_map[head_position].column == 0) crash = 1; overlay = board[head_map[head_position].row][--head_map[head_position].column]; break; } case 'D': { if(head_map[head_position].row == no_rows) crash = 1; overlay = board[++head_map[head_position].row][head_map[head_position].column]; break; } case 'U': { if(head_map[head_position].row == 0) crash = 1; overlay = board[--head_map[head_position].row][head_map[head_position].column]; break; } default: break; } } void Move() { board[head_map[head_position].row][head_map[head_position].column] = token; for(i = 1; i &lt; snake_length; i++) { temp2 = head_map[i]; head_map[i] = temp1; board[head_map[i].row][head_map[i].column] = token; board[temp2.row][temp2.column] = ' '; temp1 = temp2; } if(grow == 1) { head_map[i] = temp1; board[head_map[i].row][head_map[i].column] = token; ++snake_length; score += 10; Food(); grow = 0; } } void Change() { if(overlay == token) crash = 1; if(overlay == token_food) grow = 1; } void Game_over() { getch(); clrscr(); cout &lt;&lt; "\n\n\n\n\n\n\n\n\n\n\t\t\t\tGAME OVER!!!\n\t\t\t\tFINAL SCORE: " &lt;&lt; score; if(score &gt; high_score) { high_score = score; cout &lt;&lt; "\n\t\t\tYOU BEAT THE HIGH SCORE!!!"; } else { if(score == high_score) cout &lt;&lt; "\n\t\t\tYOU TIED THE HIGH SCORE!!!"; else cout &lt;&lt; "\n\t\t\tHIGH SCORE: " &lt;&lt; high_score; } getch(); clrscr(); cout &lt;&lt; "\n\n\n\n\n\n\n\n\n\n\n\t\t\tDO YOU WANT TO CONTINUE(Y/N)??\n\t\t\t\t\t"; cin &gt;&gt; choice; getch(); } int main() { do { Initialize(); Food(); Display(); do { Input(); Change(); if(crash == 1) break; Move(); delay(200); Display(); } while(crash != 1); Game_over(); } while(choice == 'Y' || choice == 'y'); return 0; } </code></pre>
[]
[ { "body": "<p><strong>Code improvements:</strong></p>\n\n<ol>\n<li>Do not use <code>using namespace std</code> it saves you some time typing the code, but when other namespace get involved later on its a mess to debug this code. Furthermore I personally find it more aesthetic to see from which namespace a functions \"comes from\".</li>\n<li>Consider using a function that checks wether the user-input is valid. \n\n<pre><code>cout &lt;&lt; \"Choose the Body of the Snake(Enter a symbol):\\n\";\ncin &gt;&gt; token;\n</code></pre>\n\nThis, for instance is dangerous. What if I (the user) enter a non ASCII symbol like an emoji. \nOr even worse - a character that isn't even printable.</li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-12T23:26:02.427", "Id": "453528", "Score": "0", "body": "You call a global `unsigned int i` good work? You have a strange sense of quality. Or you may have been in a hurry. I hope for the latter." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-13T02:11:14.317", "Id": "453533", "Score": "0", "body": "Why shouldn't I use a global unsigned variable? I did go with a signed int initially but I figured at least no errors could make it go negative. And I made them global to reduce passing to functions." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-13T05:56:34.147", "Id": "453546", "Score": "1", "body": "@RolandIllig He/She is clearly a beginner and I said something about global variables. If you want to correct any other style ‚mistakes‘, go for it" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-13T06:01:42.423", "Id": "453547", "Score": "1", "body": "@Tarun Roland is right. Although it’s not the worst thing you can do, it‘s not very secure to have a variable is accessible from every part of the program. Consider using a class that contains your game and auxiliary variables." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-13T10:56:24.007", "Id": "453601", "Score": "0", "body": "So should I include the board/map and all associated variables and functions in a class of its own? And create an array of objects for each square on the map?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-13T21:33:15.337", "Id": "453686", "Score": "0", "body": "@Tarun In the first few lessons it's ok to use global variables, since you have not learned the better, but more advanced concepts. I mainly criticized SchnJulian's answer because he said \"Besides that. Good work\", which might make you think your code is fine. In a few weeks you will know yourself that this is not the case. Because answers are assumed to be of high quality here, I am much stricter with them than with questions. Questions may contain bad code, or even horrible code and small mistakes, as long as the purpose of the code is clearly described." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-13T21:37:30.477", "Id": "453687", "Score": "0", "body": "@RolandIllig Removed the line. I still think that it’s not that bad to encourage a beginner even tho he isn’t in fact that good, but yeah- just in case someone uses the code from the question, i removed the compliment." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-14T10:52:20.703", "Id": "453747", "Score": "0", "body": "Thanks a lot, I made this code last year when I hadn't learned OOP or classes. Now I've redone the program and only three variables are global unsigned int." } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-12T20:15:42.990", "Id": "232279", "ParentId": "232249", "Score": "3" } }, { "body": "<p>Your main bottleneck is, of course, using the console for drawing the frame.\nI suggest you to stop using <code>std::endl</code> in your <code>Display()</code> function, and write a new line character instead.</p>\n\n<p>I believe this only helps you, though, if you turn off automatic flushing using<code>std::ios::sync_with_stdio</code>. You have to see yourself if this is an improvement on your machine anyway.</p>\n\n<p><em>Actually there are other problems I see in this code you should care about; quality, and not performance-wise. But I wouldn't address those now, since you didn't ask for it.</em></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-13T02:13:36.147", "Id": "453534", "Score": "0", "body": "Actually I wouldn't mind any suggestions to improve quality either. But is this algorithm efficient enough or am I beating the bush around too much? Also should I implement classes in this program?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-12T21:15:50.230", "Id": "232284", "ParentId": "232249", "Score": "2" } }, { "body": "<h1>Making the code more modern</h1>\n\n<p>Your code looks very old. This is because the <code>&lt;iostream.h&gt;</code> header in line 1 is not used anymore since about the year 1998. Same for the <code>&lt;dos.h&gt;</code> and <code>&lt;conio.h&gt;</code> headers.</p>\n\n<p>To get your program to compile with a modern C++ compiler, I had to replace the first paragraph of your code with this:</p>\n\n<pre class=\"lang-cpp prettyprint-override\"><code>#include &lt;iostream&gt;\n\nusing std::cin;\nusing std::cout;\nusing std::endl;\n\nextern \"C\" {\n void clrscr();\n bool kbhit();\n void delay(int);\n int getch();\n}\n</code></pre>\n\n<p>I only did this change to make your code valid for my compiler. It won't run after these changes. Therefore you should not apply these changes to your code. Just leave your code as it is. Don't be surprised though when you try to run your code in a more modern environment, as this won't work.</p>\n\n<h2>Putting text on the screen</h2>\n\n<p>I noticed that you use long sequences of <code>\\n</code> and <code>\\t</code> to place the text on the screen. Since you are using the <code>clrscr</code> function, I suppose that the function <code>gotoxy</code> is also defined. If so, you can replace this code:</p>\n\n<pre class=\"lang-cpp prettyprint-override\"><code> clrscr();\n\n cout &lt;&lt; \"\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\t\\t\\t\\tGAME OVER!!!\\n\\t\\t\\t\\tFINAL SCORE: \" &lt;&lt; score;\n</code></pre>\n\n<p>with this code:</p>\n\n<pre class=\"lang-cpp prettyprint-override\"><code> clrscr();\n\n gotoxy(32, 10);\n cout &lt;&lt; \"GAME OVER!!!\";\n gotoxy(32, 11);\n cout &lt;&lt; \"FINAL SCORE: \" &lt;&lt; score;\n</code></pre>\n\n<p>This code takes more vertical space than before, but there is no need anymore to count the number of <code>\\n</code> characters in the string.</p>\n\n<h2>Input methods</h2>\n\n<p>You are using two fundamentally different input methods:</p>\n\n<ol>\n<li><p><code>cin &gt;&gt; choice</code>, which reads a character, but the program only sees this character after Enter has been pressed. This is not suitable for a snake game.</p></li>\n<li><p><code>getch()</code>, which reads a single key without requiring the Enter key. This function works closely together with <code>kbhit()</code>.</p></li>\n</ol>\n\n<p>You should not mix these two, at least not in the same phase of the game. There is the dialog phase (\"play again?\"), which should use <code>cin &gt;&gt; choice</code>, and there is the playing phase, which should use <code>kbhit()</code> and <code>getch()</code> (in this order).</p>\n\n<h2>Reducing the scope of variables</h2>\n\n<p>Your code declares (among others) these variables:</p>\n\n<pre class=\"lang-cpp prettyprint-override\"><code>unsigned int i, j, k;\n</code></pre>\n\n<p>These variables are used later by pieces of code that are completely unrelated to each other. Therefore it doesn't make sense that these unrelated code pieces use the same variables. One of these pieces is:</p>\n\n<pre class=\"lang-cpp prettyprint-override\"><code> for (i = 0; i &lt; no_rows; i++)\n {\n for (j = 0; j &lt; no_columns; j++)\n board[i][j] = ' ';\n }\n</code></pre>\n\n<p>After the opening parenthesis of each <code>for</code> loop, you should <em>declare</em> the variable, which is then <em>in scope</em> for the rest of the <code>for</code> loop. The changed code is:</p>\n\n<pre class=\"lang-cpp prettyprint-override\"><code> for (unsigned int i = 0; i &lt; no_rows; i++)\n {\n for (unsigned int j = 0; j &lt; no_columns; j++)\n board[i][j] = ' ';\n }\n</code></pre>\n\n<p>When you do that in the other <code>for</code> loops as well, there will be a compile error:</p>\n\n<pre class=\"lang-cpp prettyprint-override\"><code> head_map[i] = temp1;\n board[head_map[i].row][head_map[i].column] = token;\n</code></pre>\n\n<p>This compile error means that your code is somewhat unusual. You used <code>i</code> in a loop, and usually that variable is not needed after the loop. Not so in this case.</p>\n\n<p>When the <code>for</code> loop is finished, <code>i</code> will be the same as <code>snake_length</code>. Therefore you can replace the code with the very similar:</p>\n\n<pre class=\"lang-cpp prettyprint-override\"><code> head_map[snake_length] = temp1;\n board[head_map[snake_length].row][head_map[snake_length].column] = token;\n</code></pre>\n\n<p>This makes the intention of the code a bit clearer, since for experienced programmers the variable name <code>i</code> means a variable that changes its value often, such as in your loops that fill the board with spaces. That name <code>i</code> would be misleading here, since the code handles the tail of the snake. The expression <code>head_map[snake_length]</code> expresses this more clearly than the expression <code>head_map[i]</code>.</p>\n\n<h2>Redundant conditions</h2>\n\n<p>Further down, you have this code:</p>\n\n<pre class=\"lang-cpp prettyprint-override\"><code> if((key_press == 'w' || key_press == 'W') &amp;&amp; (key_press != 's' || key_press != 'S') &amp;&amp; (direction_head != 'D'))\n</code></pre>\n\n<p>This code is redundant. If the pressed key is <code>'w'</code> or <code>'W'</code>, it cannot be <code>'s'</code> at the same time. Therefore you don't need to check for <code>'s'</code> at all.</p>\n\n<p>Furthermore, the expression <code>key_press != 's' || key_press != 'S'</code> will always be true. There are 3 cases:</p>\n\n<ol>\n<li><code>key_press != 's'</code>: the first condition is true, therefore the whole expression is true.</li>\n<li><code>key_press != 'S'</code>: the second condition is true, therefore the whole expression is true.</li>\n<li>any other key: both conditions are true, therefore the whole expression is true.</li>\n</ol>\n\n<p>Therefore, the simplified code is:</p>\n\n<pre class=\"lang-cpp prettyprint-override\"><code> if((key_press == 'w' || key_press == 'W') &amp;&amp; (true) &amp;&amp; (direction_head != 'D'))\n</code></pre>\n\n<p>This can be further simplified to:</p>\n\n<pre class=\"lang-cpp prettyprint-override\"><code> if((key_press == 'w' || key_press == 'W') &amp;&amp; direction_head != 'D')\n</code></pre>\n\n<h2>Pausing the game</h2>\n\n<pre class=\"lang-cpp prettyprint-override\"><code> if(key_press == 'p' || key_press == 'P')\n delay(5000);\n</code></pre>\n\n<p>This looks wrong. When I press the <code>'p'</code> key, I expect the game to pause until I explicitly continue it by pressing <code>'p'</code> again. Waiting 5 seconds is something entirely different.</p>\n\n<p>To implement the pause correctly, you should define a global variable:</p>\n\n<pre class=\"lang-cpp prettyprint-override\"><code>bool paused = false;\n</code></pre>\n\n<p>After that, adjust the code from above:</p>\n\n<pre class=\"lang-cpp prettyprint-override\"><code> if(kbhit())\n {\n ...\n\n if(key_press == 'p' || key_press == 'P')\n paused = !paused;\n }\n\n if (paused)\n return;\n</code></pre>\n\n<p>Since the second part of the <code>Input</code> function does not deal with the input at all but instead moves the snake, that part is skipped as long as the game is paused.</p>\n\n<h2>Final words</h2>\n\n<p>Your code is structured well, especially since the code of the <code>main</code> function gives a rough overview over the whole game flow, just as it should.</p>\n\n<p>You named the functions well, which makes the <code>main</code> function easy to grasp.</p>\n\n<p>There are many more things that can be said about your code, but they are not urgent. Getting a few ideas and thinking about them is easier than getting a hundred tips at once.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-14T10:58:43.357", "Id": "453748", "Score": "0", "body": "That was really helpful. I've modified the code to include classes and objects. I didn't know if i should reduce the scope of variables as it might decrease efficiency due to repeated definitions. I was intending to use goto(x,y). I didn't know how it worked till now. I know there is redundant code in the Input() function which I realized just after this post. I also apologize for the out of date code but my school uses TurboC++ 3.2 and it's necessary to use it. I am trying to learn newer standards on Visual Studio. That pause function is really great." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-14T11:03:24.157", "Id": "453749", "Score": "0", "body": "I wasn't taught exactly what getch() did but was just told to add it at the end of the program to get the output screen. Also, how would I make the game more smooth or make it fps-based? Also how do I remove the flashing cursor?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-14T19:39:02.157", "Id": "453839", "Score": "1", "body": "TurboC++ is a good language since it lives in a small and understandable environment that is easy to grasp for beginners. I just wanted you to be aware that when you leave that world, it will get a little more complicated." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-14T19:41:25.283", "Id": "453840", "Score": "1", "body": "Regarding the reduced efficiency: with modern compilers there is no efficiency penalty for using variables with a small scope. Most probably the code will get faster by using the smaller scope. Therefore there's no reason to make the scope of these variables global." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-13T22:23:17.383", "Id": "232359", "ParentId": "232249", "Score": "3" } } ]
{ "AcceptedAnswerId": "232359", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-12T14:33:17.063", "Id": "232249", "Score": "5", "Tags": [ "c++", "snake-game" ], "Title": "Snake Game C++ Improvements?" }
232249
<p>I am doing a larger project independently, so I wish to make sure that my prior code is stable and that it will not make any issues along the way. </p> <p>I have several basic uses for this code:<br> - <strong>Display bits</strong><br> - <strong>Allow public access to individual bits</strong><br> - <strong>Allow from <code>integer</code> conversion (truncate larger <code>ints</code>)</strong><br> - <strong>Allow to <code>integer</code> conversion</strong> </p> <h2>Here is the code:</h2> <p><em>Structure definition <code>hpp</code></em></p> <pre class="lang-cpp prettyprint-override"><code>#include &lt;iostream&gt; struct bin_data{ bool b0:1,b1:1,b2:1,b3:1,b4:1,b5:1,b6:1,b7:1; bin_data(int); // initialiser bin_data( const bin_data &amp;bdat ); // copy constructor bin_data( bin_data &amp;&amp; bdat ); // move constructor //bin_data( nabu ); // this part is dependent on different struct // I decided to show that, but omit the code since then dependency will be too long bin_data&amp; operator=( const bin_data &amp;bdat ); // copy asigment bin_data&amp; operator=( bin_data &amp;&amp; bdat ); // move asigment ~bin_data(); // deconstructor operator bool() { return this-&gt;b0 | this-&gt;b1 | this-&gt;b2 | this-&gt;b3 | this-&gt;b4 | this-&gt;b5 | this-&gt;b6 | this-&gt;b7; } operator uint8_t(){ return ( this-&gt;b7 ? 0x80 : 0 ) | ( this-&gt;b6 ? 0x40 : 0 ) | (this-&gt;b5 ? 0x20 : 0) | (this-&gt;b4 ? 0x10 :0) | ( this-&gt;b3 ? 0x08 : 0 ) | ( this-&gt;b2 ? 0x04 : 0 ) | ( this-&gt;b1 ? 0x02 : 0 ) | (this-&gt;b0 ? 0x01 : 0); } operator int(){ return (int)(uint8_t)*this; } }; </code></pre> <p><em>Structure delcaration file</em> </p> <pre class="lang-cpp prettyprint-override"><code>//constants #define bit0 0x1 #define bit1 0x2 #define bit2 0x4 #define bit3 0x8 #define nib 0xf // pre-processor directives #define toNib(val) (val&amp;nib) #define isBit(val,bit) (bool)( (val &amp; bit) == bit ) //binary data display /* bin_data::bin_data( nabu n ) :b0( isBit(n.mask,bit0) ) ,b1( isBit(n.mask,bit1) ) ,b2( isBit(n.mask,bit2) ) ,b3( isBit(n.mask,bit3) ) ,b4( isBit(n.mask,bit0) ) ,b5( isBit(n.mask,bit1) ) ,b6( isBit(n.mask,bit2) ) ,b7( isBit(n.mask,bit3) ){} */ bin_data::bin_data( int val = 0 ) :b0( isBit(val,bit0) ) ,b1( isBit(val,bit1) ) ,b2( isBit(val,bit2) ) ,b3( isBit(val,bit3) ) ,b4( isBit(val, bit0 &lt;&lt; 4 ) ) ,b5( isBit(val, bit1 &lt;&lt; 4 ) ) ,b6( isBit(val, bit2 &lt;&lt; 4 ) ) ,b7( isBit(val, bit3 &lt;&lt; 4 ) ) { } bin_data::bin_data( const bin_data &amp;bdat ) :b0(bdat.b0),b1(bdat.b1),b2(bdat.b2),b3(bdat.b3) ,b4(bdat.b4),b5(bdat.b5),b6(bdat.b6),b7(bdat.b7) { } bin_data::bin_data( bin_data &amp;&amp; bdat ){ this-&gt;b0 = bdat.b0; bdat.b0 = 0; this-&gt;b1 = bdat.b1; bdat.b1 = 0; this-&gt;b2 = bdat.b2; bdat.b2 = 0; this-&gt;b3 = bdat.b3; bdat.b3 = 0; this-&gt;b4 = bdat.b4; bdat.b4 = 0; this-&gt;b5 = bdat.b5; bdat.b5 = 0; this-&gt;b6 = bdat.b6; bdat.b6 = 0; this-&gt;b7 = bdat.b7; bdat.b7 = 0; } bin_data&amp; bin_data::operator=( const bin_data &amp;bdat ){ this-&gt;b0 = bdat.b0; this-&gt;b1 = bdat.b1; this-&gt;b2 = bdat.b2; this-&gt;b3 = bdat.b3; this-&gt;b5 = bdat.b5; this-&gt;b6 = bdat.b6; this-&gt;b7 = bdat.b7; this-&gt;b4 = bdat.b4; return *this; } bin_data&amp; bin_data::operator=( bin_data &amp;&amp; bdat ){ this-&gt;b0 = bdat.b0; bdat.b0 = 0; this-&gt;b1 = bdat.b1; bdat.b1 = 0; this-&gt;b2 = bdat.b2; bdat.b2 = 0; this-&gt;b3 = bdat.b3; bdat.b3 = 0; this-&gt;b4 = bdat.b4; bdat.b4 = 0; this-&gt;b5 = bdat.b5; bdat.b5 = 0; this-&gt;b6 = bdat.b6; bdat.b6 = 0; this-&gt;b7 = bdat.b7; bdat.b7 = 0; return *this; } bin_data::~bin_data(){ } std::ostream&amp; operator&lt;&lt;( std::ostream&amp; os, const bin_data &amp;bdat ){ return os &lt;&lt; bdat.b7 &lt;&lt; bdat.b6 &lt;&lt; bdat.b5 &lt;&lt; bdat.b4 &lt;&lt; '-' &lt;&lt; bdat.b3 &lt;&lt; bdat.b2 &lt;&lt; bdat.b1 &lt;&lt; bdat.b0; } </code></pre> <p><strong>Disclaimer: I need to use <code>bit fields</code> since some part of my program depends on unorthodox <code>bitwise</code> manipulation (outside of traditional logic gates), and it makes it easier to check what happened.</strong> </p> <p>Thank you for your time. </p> <h2>Edit</h2> <p>Since <strong>unorthodox <code>bitwise</code> manipulation (outside of traditional logic gates)</strong> seems so vague as pointed out by comments. Here are some of the functions I am implementing on this structure, and therefore why I need access to individual bits. </p> <p><strong>Unit set - defining presence</strong> </p> <p><code>C = A*B</code> - tipical and gate representation</p> <p><strong>Undefined A set - directional logic</strong> </p> <p><code>C = A - A*B</code> - determines if objects don't generate 1D logic space, which object is present.</p> <p><strong>Undefined B set - directional logic</strong> </p> <p><code>C = B - A*B</code> - same as Undef A , but oposite set </p> <p><strong>Null Set - aka object isnt present</strong> </p> <p><code>C = 1 - (A+B) + (A*B)</code> - determines failure to establish 1D logic space</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-12T15:04:14.330", "Id": "453421", "Score": "0", "body": "Have you unit tested this code and does it work?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-12T15:06:15.383", "Id": "453422", "Score": "0", "body": "Unit tested, no. I don't know how. But I did test each part of it, and it works. And it drives half of my project so far without an glitch. But I did have an experience when code that works great suddenly after 500 lines of code starts bugging out. I credit this to my lack of knowledge." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-12T16:00:06.267", "Id": "453432", "Score": "1", "body": "I have modified the title to make it fit within the rules of Code Review. Questions in the tile like `are there any bugs` could indicate that the question is off-topic due to non-working code. Good reviewers will let you know about the bugs anyway." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-12T16:02:53.053", "Id": "453434", "Score": "0", "body": "@pacmaninbw thank you! I see it is automatically accepted. I was having real trouble with the tittle. Didn't know how to format it as a question." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-12T16:19:46.210", "Id": "453438", "Score": "1", "body": "I think you've just reinvented `std::bitset<8>` - perhaps most of your code isn't necessary?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-12T16:22:10.527", "Id": "453439", "Score": "0", "body": "@TobySpeight , yeah. I did. But as mentioned I am using non traditional logic bitwise manipulations. So I need to acces individual bits, `std::bitset` result is an accidental plus." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-12T16:54:23.727", "Id": "453450", "Score": "3", "body": "@Danilo can you add an explicit example of what you need and cannot do with std::bitset? Nor the disclaimer, nor your comment make it any clearer..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-12T16:59:59.933", "Id": "453451", "Score": "1", "body": "When you get above 2000 reputation your edits should always be accepted." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-12T17:16:50.727", "Id": "453455", "Score": "0", "body": "@slepic I added formulas. Null set is like NOT OR, and Unit Set is like AND, but most of my code relies on undefined states." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-12T17:52:56.790", "Id": "453470", "Score": "2", "body": "`I need access to individual bits`. And bitset has that. https://en.cppreference.com/w/cpp/utility/bitset/operator_at\nAlso If I understand what you mean by `*`,`-` and `+`, then `A*B` is just `A & B` , `A-B` is just `A & ~B`, `A + B` is `A | B`. I still dont see your problem impossible or difficult to implement with bitset. Also i dont understand what relying on undefined states mean." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-12T17:54:59.083", "Id": "453471", "Score": "0", "body": "@slepic , AxB is A&B but the rest isn't. When i said like *such gate* I ment truth table is similar, not operation." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-12T17:58:43.993", "Id": "453473", "Score": "0", "body": "I give up, dude. You should add `reinventing-the-wheel` tag to this question. Anyway, good luck." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-12T18:09:16.757", "Id": "453474", "Score": "0", "body": "Not cool dude. Not cool at all. Tone and public annunciation was unnecessary and rude." } ]
[ { "body": "<h2>Avoid Using the <code>this</code> Pointer</h2>\n<p>It is very rare to see the <code>this</code> pointer used in c++ code, it generally isn't necessary. The code in this question compiles fine without the this pointer. Consider making the structure into a class.</p>\n<h2>Avoid Using Macros in C++</h2>\n<p>In C++ it is better to use constexpr <code>TYPE SYMBOL = constant;</code> because it allows the compiler to do type checking when the values are used.</p>\n<pre><code>constexpr unsigned bit0 = 0x1;\nconstexpr unsigned bit1 = 0x1 &lt;&lt; 1;\nconstexpr unsigned bit2 = 0x1 &lt;&lt; 2;\nconstexpr unsigned bit3 = 0x1 &lt;&lt; 3;\nconstexpr unsigned nib = 0xf;\n</code></pre>\n<p>Instead of macro functions use inline functions.</p>\n<pre><code>bool isBit(unsigned val, unsigned bit) { static_cast&lt;bool&gt; ((val &amp; bit) == bit); }\n</code></pre>\n<p>It might be better to replace bool with unsigned as the underlying storage type, many programmers that program hardware and need to toggle bits will use unsigned.</p>\n<h2>The Default Constructor</h2>\n<p>In the header file there is this constructor <code>bin_data(int);</code> and in the cpp file there is</p>\n<pre><code>bin_data::bin_data( int val = 0 )\n :b0( isBit(val,bit0) ) ,b1( isBit(val,bit1) ) ,b2( isBit(val,bit2) ) ,b3( isBit(val,bit3) )\n ,b4( isBit(val, bit0 &lt;&lt; 4 ) ) ,b5( isBit(val, bit1 &lt;&lt; 4 ) ) ,b6( isBit(val, bit2 &lt;&lt; 4 ) ) \n ,b7( isBit(val, bit3 &lt;&lt; 4 ) )\n{ }\n</code></pre>\n<p>My compiler (Visual Studio 2019) complains about this portion of the constructor in the cpp file:</p>\n<pre><code>bin_data::bin_data( int val = 0 )\n</code></pre>\n<p>It would probably be better if the code in the header file was <code>bin_data(int val = 0);</code> otherwise another constructor needs to be written which does not accept an <code>int</code> as input, remove the <code>int val = 0</code> in the cpp file.</p>\n<pre><code>bin_data::bin_data(int val)\n :b0( isBit(val,bit0) ) ,b1( isBit(val,bit1) ) ,b2( isBit(val,bit2) ) ,b3( isBit(val,bit3) )\n ,b4( isBit(val, bit0 &lt;&lt; 4 ) ) ,b5( isBit(val, bit1 &lt;&lt; 4 ) ) ,b6( isBit(val, bit2 &lt;&lt; 4 ) ) \n ,b7( isBit(val, bit3 &lt;&lt; 4 ) )\n{ }\n</code></pre>\n<p><em>Note, the comma operator should always be followed by a space.</em></p>\n<h2>Use C++ Casts Rather Than Old C Style Casts</h2>\n<p>There are old C style casts in several places, it is better to use either <code>static_cast&lt;type&gt;</code> or <code>dynamic_cast&lt;type&gt;</code> in C++. In this code they would all be static_cast.</p>\n<p>Current code</p>\n<pre><code>#define isBit(val,bit) (bool)( (val &amp; bit) == bit )\n</code></pre>\n<p>more modern code</p>\n<pre><code>bool isBit(unsigned val, unsigned bit) { static_cast&lt;bool&gt; ((val &amp; bit) == bit); }\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-12T17:20:36.510", "Id": "453458", "Score": "0", "body": "What are benefits of class against structure in this example? \n \nI used `bin_data::bin_data(int val = 0)` to replace an empty initialisation - as an shorthand. I could remedy that. \n \nWhat makes new c++ casts better than what I normally use? Is that some sort of code ethics thing or there is added benefit?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-12T17:39:50.997", "Id": "453467", "Score": "2", "body": "If you put the bin_data(int val = 0) into the header the empty initialization still works. static_cast provides additional type checking." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-13T10:31:57.393", "Id": "453587", "Score": "0", "body": "I just need to mention that `isBit` in form you supplied doesn't work for me unless I put an return statement." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-13T12:02:39.187", "Id": "453607", "Score": "1", "body": "@Danilo Sorry, it does need that return." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-12T16:49:17.233", "Id": "232263", "ParentId": "232250", "Score": "2" } }, { "body": "<p>A few observations, additional to the <a href=\"/a/232263\">review by pacmaninbw</a>.</p>\n\n<p>Headers: <code>&lt;iostream&gt;</code> isn't needed for the header, but is needed for the code. We probably want to declare that <code>operator&lt;&lt;()</code> in the header, though - for which we should include <code>&lt;iosfwd&gt;</code>. We also need <code>&lt;cstdint&gt;</code>, to declare <code>std::uint8_t</code>.</p>\n\n<p>The converting constructor from <code>int</code> is a narrowing conversion, so we really ought to make that <code>explicit</code>.</p>\n\n<p>The move constructor and move assignment operators don't add any value, unless there's a demonstrated need to zero the source. I believe they should be omitted.</p>\n\n<p>The destructor adds no value at all, and should be omitted.</p>\n\n<p>Conversion to <code>bool</code> isn't necessary, as there's a conversion to <code>int</code>, and <code>int</code> implicitly converts to <code>bool</code>.</p>\n\n<p>Conversion to <code>std::uint8_t</code> could be simplified:</p>\n\n<pre><code>operator std::uint8_t()\n{\n return 0x80 * b7 + 0x40 * b6 + 0x20 * b5 + 0x10 * b4\n + 0x08 * b3 + 0x04 * b2 + 0x02 * b1 + 0x01 * b0;\n}\n</code></pre>\n\n<p>The streaming operator will produce different results depending on whether the stream has <code>std::boolalpha</code> set or not. Is that desirable?</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-12T17:29:18.937", "Id": "232265", "ParentId": "232250", "Score": "4" } } ]
{ "AcceptedAnswerId": "232263", "CommentCount": "13", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-12T14:56:59.800", "Id": "232250", "Score": "1", "Tags": [ "c++" ], "Title": "Binary digit display structure" }
232250
<p>So I had a similar problem to this:</p> <p><a href="https://stackoverflow.com/questions/39749430/import-huge-dataset-into-access-from-excel-via-vba/57995602#57995602">https://stackoverflow.com/questions/39749430/import-huge-dataset-into-access-from-excel-via-vba/57995602#57995602</a></p> <p>Although it was already answered, I provided a different solution on that thread if anyone else came looking for something similar.</p> <p>If you don't feel like reading through it, the long and short is I have a large data set (850k records) in an Access table that needs to be updated. In my company, we receive new data from a partner in a .xlsx file and need to update said Access database from this file. The unfortunate part is the file sent to us is the entire 850k set with additions and updates (NO DELETIONS). Import tools and macros in Access and Excel take on the order of <strong>10-15 minutes</strong> for the entire comparison and import. My solution was to save previously received .xlsx files as .txt files and then compare them to new files using the <code>std::unordered_map</code> from the C++ STL to produce delta files. Then query the delta files for update and upload instead of using the entire data set. In short, compare last week's .xlsx file to this week's .xlsx file for the delta (about 1k records), then write update and insert queries (queries not written yet) for those 1000 or so updates/inserts instead of comparing all 850k records.</p> <p>The structure of the files are like this:</p> <pre><code>Col1\tCol2\tCol3\tCol4\tCol5\tCol6\n &lt;-----this is a header string1\tstring2\tstring3\tstring4\tstring5\tstring6\n string1\tstring2\tstring3\tstring4\tstring5\tstring6\n string1\tstring2\tstring3\tstring4\tstring5\tstring6\n .... //Through 850k rows// </code></pre> <p>It's important to note that <code>Col1</code> in each row is a unique identifier. It's a string of numbers followed by a terminating "A" character. For example <code>0000001A</code>.</p> <p><strong><em>1. First Attempt</em></strong></p> <p>My first attempt at this used the I/O stream, a single <code>std::unordered_map</code> with string data only, and the first <code>'\t'</code> character and <code>'\n'</code> character as delimiters as can be seen in the thread I linked above. Comparing the input files and writing the outputs took about <strong>5 seconds</strong>.</p> <p><strong><em>2. Second Attempt</em></strong></p> <p>I made my second attempt after seeing a YouTube lecture on Robin Hood hashing, so I researched it a little and stumbled on this. </p> <p><a href="https://probablydance.com/2017/02/26/i-wrote-the-fastest-hashtable/" rel="nofollow noreferrer">https://probablydance.com/2017/02/26/i-wrote-the-fastest-hashtable/</a></p> <p>I'm not even going to attempt to create a faster hash table. This hashtable is implemented the same as the <code>std::unordered_map</code>, so I downloaded it and imported it to see how much faster it was. You can see this in my code below as <code>#include "RobinHood.h"</code> (I renamed the file so I would recognize it but to be 100% clear, I take NO CREDIT for any of that hash). Then its implementation (with integer instead of string): </p> <pre><code>ska::flat_hash_map&lt;int, std::string&gt; hashMap1; ska::flat_hash_map&lt;int, std::string&gt;::iterator it; </code></pre> <p>This cut the comparison time in half. Down to <strong>2.4 seconds</strong>.</p> <p><strong><em>3. Third Attempt</em></strong></p> <p>In my third attempt, I decided I would try to exploit the numbers in <code>Col1</code> as a key because integer searching of a hash table is much faster than string searching. I tried a couple of string conversions using the std library but, it seemed that the most efficient conversion for this application was the <code>atoi()</code> function from <code>&lt;cstdlib&gt;</code>. In my code below, you'll see it in the <code>CreateFileHash()</code> function: <code>int t_key{atoi(key.c_str())};</code></p> <p>This cut my time further down to <strong>1.75 seconds</strong>. </p> <p><strong><em>4. Fourth Attempt</em></strong></p> <p>Now I decided I could probably speed this up, just a bit more. I thought, what would happen if I used a second data structure to store the second file and read the two files into memory in parallel, then compared the data structures instead of comparing the hash table with the I/O stream on the fly? How much time could I save?</p> <pre><code>#include &lt;iostream&gt; #include &lt;fstream&gt; #include &lt;iomanip&gt; #include &lt;string&gt; #include &lt;iterator&gt; #include &lt;cstdlib&gt; //#include &lt;unordered_map&gt; -removed, used the ska::flat_hash_map #include "RobinHood.h" //I renamed the ska robin hood hashing library to "RobinHood.h" so I would remember what it was. #include &lt;thread&gt; void OpenFiles(std::ifstream&amp; f_in1, std::ifstream&amp; f_in2, std::ofstream&amp; f_out1, std::ofstream&amp; f_out2, std::ofstream&amp; f_out3); void Get_Line_Data(std::ifstream&amp; f_in, std::string&amp; key, std::string&amp; s_data); void CreateFileVector(std::ifstream&amp; f_in, std::vector&lt;std::pair&lt;int, std::string&gt;&gt; &amp;f_vec, std::string&amp; key, std::string&amp; s_data); void CreateFileHash(std::ifstream&amp; f_in, ska::flat_hash_map&lt;int, std::string&gt; &amp;hashMap1, ska::flat_hash_map&lt;int, std::string&gt;::iterator &amp;it, std::string &amp;key, std::string&amp; s_data); void printFileDivider(std::ofstream&amp; fout, const int width); int main(int argc, char* argv[]) { const int width{81}; int newRecordIndex{1}; int changedRecordIndex{1}; std::string key1; std::string key2; std::string wholeLine1; std::string wholeLine2; std::vector&lt;std::pair&lt;int, std::string&gt;&gt; vec; //robin hood hash map. interfaces just like std::unordered_map ska::flat_hash_map&lt;int, std::string&gt; hashMap1; ska::flat_hash_map&lt;int, std::string&gt;::iterator it; std::ifstream fin1; //in files std::ifstream fin2; std::ofstream fout1; //out files std::ofstream fout2; std::ofstream fout3; OpenFiles(fin1, fin2, fout1, fout2, fout3); //skip the header fin1.ignore(80, '\n'); // std::thread t1(CreateFileHash, std::ref(fin1), std::ref(hashMap1), std::ref(it), std::ref(key1), std::ref(wholeLine1)); //skip the header fin2.ignore(80, '\n'); std::thread t2(CreateFileVector, std::ref(fin2), std::ref(vec), std::ref(key2), std::ref(wholeLine2)); //closing threads and files t2.join(); fin2.close(); t1.join(); fin1.close(); //put the header in the output files fout2 &lt;&lt; "COL1\t" &lt;&lt; "COL2\t" &lt;&lt; "COL3\t" &lt;&lt; "COL4\t" &lt;&lt; "COL5\t" &lt;&lt; "COL6\n"; fout3 &lt;&lt; "COL1\t" &lt;&lt; "COL2\t" &lt;&lt; "COL3\t" &lt;&lt; "COL4\t" &lt;&lt; "COL5\t" &lt;&lt; "COL6\n"; //loop to compare the data structures for(auto v_it = vec.begin(); v_it != vec.end(); ++v_it) { //look up the key1 data from the vector in the key2 data from hash map it = hashMap1.find(v_it-&gt;first); if(it != hashMap1.end()) //if the key is found compare the data { if(it-&gt;second != v_it-&gt;second) { //print the result to the changed record file. Don't forget to put the 'A' back in the string printFileDivider(fout1, width); fout1 &lt;&lt; changedRecordIndex &lt;&lt; ". CHANGED RECORD\n"; fout1 &lt;&lt; "Old Record" &lt;&lt; "\t" &lt;&lt; it-&gt;first &lt;&lt; "A" &lt;&lt; it-&gt;second &lt;&lt; "\n"; fout1 &lt;&lt; "New Record" &lt;&lt; "\t" &lt;&lt; v_it-&gt;first &lt;&lt; "A" &lt;&lt; v_it-&gt;second &lt;&lt; "\n"; printFileDivider(fout1, width); fout1 &lt;&lt; "\n"; //print the new record to the update file. Don't forget to put the 'A' back in the string fout2 &lt;&lt; v_it-&gt;first &lt;&lt; "A" &lt;&lt; v_it-&gt;second &lt;&lt; "\n"; ++changedRecordIndex; } } else //if the key is not found - print the new record to the upload file { fout3 &lt;&lt; v_it-&gt;first &lt;&lt; "A" &lt;&lt; v_it-&gt;second &lt;&lt; "\n"; ++newRecordIndex; } } fout1.close(); fout2.close(); fout3.close(); return 0; } void OpenFiles(std::ifstream&amp; f_in1, std::ifstream&amp; f_in2, std::ofstream&amp; f_out1, std::ofstream&amp; f_out2, std::ofstream&amp; f_out3) { f_in1.open("OldFile.txt"); //the old input file f_in2.open("NewFile.txt"); //the new input file f_out1.open("Changed Records.txt"); f_out2.open("Update.txt"); f_out3.open("Upload.txt"); } void Get_Line_Data(std::ifstream&amp; f_in, std::string&amp; key, std::string&amp; s_data) { getline(f_in, key, 'A'); getline(f_in, s_data, '\n'); } void CreateFileVector(std::ifstream&amp; f_in, std::vector&lt;std::pair&lt;int, std::string&gt;&gt; &amp;f_vec, std::string&amp; key, std::string&amp; s_data) // { while(f_in) { if(f_in.eof()) break; Get_Line_Data(f_in, key, s_data); int t_key{atoi(key.c_str())}; f_vec.push_back(make_pair(t_key, s_data)); } } //Creates the hash table to store information from the old data file void CreateFileHash(std::ifstream&amp; f_in, ska::flat_hash_map&lt;int, std::string&gt; &amp;hashMap1, ska::flat_hash_map&lt;int, std::string&gt;::iterator &amp;it, std::string &amp;key, std::string&amp; s_data) { while(f_in) { if(f_in.eof()) //check for end of file if so break loop break; Get_Line_Data(f_in, key, s_data); //get the data int t_key{atoi(key.c_str())}; //convert the key string to an int -- this is for faster hashing hashMap1[t_key] = s_data; //add these to the hash table } } </code></pre> <p>Down to <strong>1.4 seconds</strong>.</p> <p><strong><em>10-15 minutes</em></strong> - <strong><em>1.4 seconds</em></strong>. This does not yet include the update and insert queries but we hope that inserting and updating 1k records will be much faster than an entire set of 850k records. I'm still learning. Want to learn more. Harsh criticism welcomed. Tell me what's wrong or what I could do better and please don't be nice about it. Should I use an array of structs instead of a vector as the second data structure? Is there a better more efficient way to do this? I want to make this more readable, more efficient and I want to get better at this. If that code doesn't compile, let me know. It's copied over from a different machine and SHOULD work. Thanks!</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-12T16:11:49.500", "Id": "453435", "Score": "2", "body": "If I understand correctly. 10-15 mins is the time of some general tools to proceed with the entire import? I mean, including the database operations, right? And your algorithm is 1.4s but the database part is not yet implemented, right? Then I'd suggest to move on to the database part and see if you're not optimizing something that is a ridiculously small part of the entire job." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-12T16:17:57.883", "Id": "453437", "Score": "0", "body": "Yes that’s our next step! I will clarify above a little better about the numbers. At the moment we’re updating 800+K records using an 800+K row file. The optimization will come in by having to call queries to about 1000 specific records to change or insert rather than the entire set. I think the speed is largely an MS Access/Excel problem. Thanks!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-12T16:29:44.847", "Id": "453442", "Score": "1", "body": "Don't take me wrong. Your code definitely deserves a review and has space for improvement in many aspects. Although I'm not the right person to give a review on a code of this size, as C++ I only do as hobby. But at this point performance should be the least of your concerns as it seems you've already done good enough job. Implement the database part and see how it does. Then come back to this if it seems that speeding up this part can have significant impact on the entire work." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-12T16:32:39.497", "Id": "453444", "Score": "0", "body": "Maybe I should say it the same way you have. We are currently using Excel and Access tools to import the entire data set (10-15 min). I’ve made it a ridiculously small job in comparison with this code to query to import/update 1000 samples rather than 850k. This should only take seconds, I would think but I will be sure to update the question when we do it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-12T16:34:49.713", "Id": "453445", "Score": "0", "body": "Well...I’m here for the C++ criticism. I’m hoping people will hammer it. ;)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-12T16:35:04.463", "Id": "453446", "Score": "1", "body": "Don't do it. It would be against rules of this site. You should not edit question after you receive at least one review. And I'm sure you will get some :) Post a new review for the database part when you have it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-12T16:38:25.663", "Id": "453447", "Score": "0", "body": "Oh! Ok. The other SE sites tell you to go back and update the original." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-12T19:07:30.010", "Id": "453481", "Score": "0", "body": "Are the data files you are comparing by any chance sorted? That could open the door to faster code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-12T19:15:35.267", "Id": "453488", "Score": "0", "body": "Not really. More pseudo-sorted. It’s the reason I thought of using the hash table. Plus, some entries might get skipped for weeks or months and then show up later, causing all kinds of headaches. Building the hash takes more than half of that 1.4 seconds. Building the vector takes the second most amount of time but in parallel, it’s net effect is 0. It has been suggested to me to look for assembly solutions but I know 0 assembly." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-13T05:54:58.737", "Id": "453544", "Score": "0", "body": "\"Premature optimization is the root of all evil\". I suggest you to build xslx to txt converter, than use diff tool, and 2nd tool to make insertions, deletions and updates according to patch." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-13T12:21:26.380", "Id": "453610", "Score": "0", "body": "I knew that was eventually coming and not really what I asked for but thanks" } ]
[ { "body": "<p><strong>C++ related</strong></p>\n\n<ul>\n<li>Streams close when they go out of scope. No need to call .close() at the end of the function.</li>\n<li>File names can be provided when you create the streams. No need to pass 5 streams to a function (and risk mixing them up) for that.</li>\n<li>You're passing way to many parameters into the functions that read from the file. Why not declare most of them in the body of the function? What is the hashtable iterator doing there as a parameter?</li>\n<li>The result of <code>getline</code> is not checked after the call.</li>\n</ul>\n\n<p><strong>Performance related</strong></p>\n\n<p>As always, profiling helps identify bottlenecks. </p>\n\n<p>Allocating all those strings can get costly. Reading the whole file in memory and using <code>std::string_view</code> might avoid that.</p>\n\n<p>If the key is an <code>int</code>, how big is it? Perhaps a big enough vector is enough instead of the hash table.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-12T21:47:53.343", "Id": "453506", "Score": "0", "body": "Awesome! Thanks!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-12T21:51:26.300", "Id": "453508", "Score": "1", "body": "I did try to use string_view initially and couldn’t figure a way to do it without allocating a string. I actually did have a function to read the whole file at once and it took 4 times as long to do, unless I was doing that wrong. I have since deleted that. I’ll see if I can duplicate that and re-sub in a new thread." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-13T12:35:11.983", "Id": "453616", "Score": "0", "body": "I was unsure about the iterator. I only included it because I was initially using it in the function but then forgot to remove it. Thanks for pointing that out. I've included other things that I needed but by ref because I needed them (or thought I needed them) in the function and in the main. Ill see what I can do to clean it up a little. So maybe return the vector and hash table instead of creating them and passing by ref? Also, I used the hash table because of the comparison. I figured it would be faster to only have to go through one of the structures one by one and use col1 as a key." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-20T14:33:55.043", "Id": "454517", "Score": "0", "body": "So I have tried the suggestions. Loaded both entire files to strings and used string_view to compare them. Searching the first column value through the second string exponentially increases the search time such that the hash function becomes more efficient, with about 3-4 new record entries. I have yet to use the strings in place of only the vector." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-20T18:22:12.883", "Id": "454541", "Score": "0", "body": "Just replaced the vector with a string, using the string_view to navigate. Iterating the entire string with string_view and comparing to the hash table takes almost a minute. comparing a vector to the hash is it. Will work on queries, make them stored procedures and post new with a reference to this thread when I'm done." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-21T14:27:59.867", "Id": "454622", "Score": "0", "body": "Ignore that last comment. I was missing something. Iterating over a string_view of this file loaded completely to a string and compare to the hash table takes approximately 6 times longer than all of the allocations using the vector." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-12T20:50:04.093", "Id": "232282", "ParentId": "232254", "Score": "2" } } ]
{ "AcceptedAnswerId": "232282", "CommentCount": "11", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-12T15:13:49.620", "Id": "232254", "Score": "4", "Tags": [ "c++", "strings" ], "Title": "Two input file string comparison with C++. Large dataset 800+k. Harsh criticism welcomed" }
232254
<p>I made a battleship game for a programming class, where I only had about a week to get it done. Under this time crunch, and the fact that I don't know python very well, I made some of the code in very roundabout ways, and probably far more complicated than it needs to be.</p> <pre class="lang-py prettyprint-override"><code>""" This is my program that lets you play one man battleship. It has a board that displays the info to the player, henceforth know as the player board, and an enemy board which is hidden from the player, know as the enemy board which is used to store ship locations. There is also an info board that has the ship locations for each board on the corosponding line. On the enemy board, a zero is used to represent an empty tile, while an X is a ship section. On the player board, a zero is used to represent a unguessed tile, an M the misses, and an X for hits. """ import random board = [] hits = 0 random.seed() num = random.randrange(1, 5) sunk = [0 , 0, 0, 0] # Loads the enemy board def enemyBoardLoader(): global num file = open("board" + str(num) + ".txt") return file.read() #Loads the line of the info board that corosponds to the board chosen def boardInfoLoader(): file = open("boardInfo.txt") #Reads a line and puts it on a filler varible, as that is the only way to incremeant the readline command for x in range(num - 1): filler = file.readline() return boardInfoInterp(file.readline()) #Turn the line input into a list of lists def boardInfoInterp(boardInfo): boardInfoList = [] #Output shipSet = [] #Varible 1 that is used to chunk the list shotSet = [] #Varible 2 that is used to chunk the list x = 0 #Loop that moves it into a nested list while x &lt; len(boardInfo): #If the letter the program is on is a number, it adds it to the second chunk varible try: shotSet.append(int(boardInfo[x])) #If its not, it runs this code except ValueError: #If it reaches a comma, moves the first chunk varible to the first one, then clears the first chunk varible if boardInfo[x] == ",": shipSet.append(shotSet) shotSet = [] #If it reaches a semi colon, moves the second chunk varible to the ouput, making a nested list, then clears the second chunk varible elif boardInfo[x] == ";": boardInfoList.append(shipSet) shipSet = [] x += 1 return(boardInfoList) #If a shot is on a ship, it removes that shot from the boardInfo list def boardInfoRemover(hit): global boardInfo #Makes the input be in a format that the program needs hit = str(hit) hit = list(hit) #Removes extra charecters from the list while "[" in hit: hit.remove("[") while " " in hit: hit.remove(" ") while "," in hit: hit.remove(",") while "]" in hit: hit.remove("]") x = 0 #Makes the numbers left in the list numbers while x &lt; len(hit): hit[x] = int(hit[x]) x += 1 x = 0 #Checks to see which shot location it was, and removes it from the boardInfo list while x &lt; len(boardInfo): y = 0 while y &lt; len(boardInfo[x]): if boardInfo[x][y] == hit: del boardInfo[x][y] y += 1 x += 1 # General things done to the player board def boardFunc(func, shot): global board if func == "reset": # Checks if command given was reset # Sets default board state of 100 zeros for x in enemyBoard: board.append("0") if func == "print": # Checks if command given was print # Prints 10 rows of 10 characters for x in range(10): print(" ".join(board[(x * 10):((x + 1) * 10)])) if func == "update": # Checks if command given was update if enemyBoard[((shot[0] - 1) + (shot[1] - 1) * 10)] == "X": # If the shot location is an X on the enemy board, mark a hit on the player board if board[((shot[0] - 1) + (shot[1] - 1) * 10)] != "X": board[((shot[0] - 1) + (shot[1] - 1) * 10)] = "X" boardInfoRemover(shot) global hits hits += 1 else: board[((shot[0] - 1) + (shot[1] - 1) * 10)] = "M" # If the shot location is not an X on the enemy board, mark a miss on the player board #Takes and cleans the input to prevent errors def inputCleaner(): global y, x num = [] repeat = True # Secondary variable to handle loops # Checks to make sure input is 2 items instead of one while repeat: try: xy = input("Were do you want to shoot your shot? (num1 num2):") x, y = xy.split() # Gives error if its only one number repeat = False # If there is an error, this does not run, making the loop keep running # If error is given, runs this instead of any code left to run except ValueError: print("Please enter two numbers") true = True # Primary variable to handle loops # Main loop to check if input is right while true: true = False # *Starts chuckling* try: # Sets the variable to numbers instead of characters they came in as. If this fails, it runs the except code below x = int(x) y = int(y) if y &gt; 10 or y &lt; 1: # Makes sure that the first number is on the board, if not asks for another number to replace it true = True y = input( "Please make sure that your first number is at least 1 and no more than 10. Re-enter only your first number:") elif x &gt; 10 or x &lt; 1: # Same as above, but with x true = True x = input( "Please make sure that your second number is at least 1 and no more than 10. Re-enter only your second number:") else: # If neither of the above are true, puts the numbers in the num list num.append(int(x)) num.append(int(y)) except ValueError or TypeError: # If something other than a number is entered, it runs this code repeat = True # This code makes sure at least two numbers were entered while repeat: try: xy = input("Please use only numbers. Enter you shot location again:") x, y = xy.split() repeat = False true = True except ValueError: print("Please enter two numbers") return num #Checks if all locations on a ship have been shot def sunkChecker(): global boardInfo global sunk if len(boardInfo[0]) == 0 and sunk[0] == 0: print("You sunk the aircraft carrier.") sunk[0] = 1 if len(boardInfo[1]) == 0 and sunk[1] == 0: print("You sunk the battleship.") sunk[1] = 1 if len(boardInfo[2]) == 0 and sunk [2] == 0: print("You sunk the cruiser.") sunk[2] = 1 if len(boardInfo[3]) == 0 and sunk[3] == 0: print("You sunk the submarine.") sunk[3] = 1 enemyBoard = enemyBoardLoader() boardInfo = boardInfoLoader() while True: boardFunc("reset", 0) while hits &lt; 15: # Each board has 15 ship spots, when all are hit it breaks out of this loop boardFunc("print", 0) boardFunc("update", inputCleaner()) sunkChecker() boardFunc("print", 0) if input("YOU WON!! Would you like to play again? (y/n):") == "n": quit() </code></pre> <p>What are some parts that could be simplified? Also, <a href="https://github.com/K00lmans/BattleShip/tree/1a88b0f4c4823665a0fb953fed7e8dd5d593c61b/Battleship%20Project" rel="nofollow noreferrer">these</a> are the specific files I have for this program.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-12T22:43:41.373", "Id": "453521", "Score": "7", "body": "Please see [_What to do when someone answers_](https://codereview.stackexchange.com/help/someone-answers). I have rolled back Rev 3 → 2" } ]
[ { "body": "<p>Just a quick comment for now. Unfortunately, <code>except ValueError or TypeError</code> does not do what you think it does. Python tries to be readable English where possible, but here it doesn't quite work. The parser parses this statement as:</p>\n\n<pre><code>except (ValueError or TypeError)\n</code></pre>\n\n<p>where the second part follows the rules of the <code>or</code> operator. If the first argument is truthy, return that truthy value, if not return the truthiness of the second argument.</p>\n\n<p>For integers, which are falsey for <code>0</code> and truthy otherwise, this means:</p>\n\n<pre><code>1 or 2 -&gt; 1\n0 or 2 -&gt; 2\n0 or 0 -&gt; 0\n</code></pre>\n\n<p>In addition, by default all objects are truthy if they exist (unless overwritten by the class itself). Since <code>ValueError</code> exists, it is parsed like this:</p>\n\n<pre><code>except (ValueError or TypeError) -&gt; except ValueError\n</code></pre>\n\n<p>In other words, this cannot actually catch a <code>TypeError</code>:</p>\n\n<pre><code>try:\n raise TypeError\nexcept ValueError or TypeError:\n print(\"caught!\")\n# TypeError: ...\n</code></pre>\n\n<p>Instead, use a tuple for multiple exceptions to be caught by the same <code>except</code> statement:</p>\n\n<pre><code>try:\n raise TypeError\nexcept (ValueError, TypeError):\n print(\"caught!\")\n# caught!\n</code></pre>\n\n<p>Be careful not to use the tuple without parenthesis, which meant something else in Python 2 and is a <code>SyntaxError</code> in Python 3:</p>\n\n<pre><code>try:\n raise TypeError\nexcept ValueError, TypeError:\n print(\"caught!\")\n# Python 2: TypeError: ...\n# Python 3: SyntaxError: ...\n</code></pre>\n\n<p>was the same as</p>\n\n<pre><code>try:\n raise TypeError\nexcept ValueError as TypeError:\n print(\"caught!\")\n# TypeError: ...\n</code></pre>\n\n<p>In other words, it overwrites the variable <code>TypeError</code> with the specific caught <code>ValueError</code>, which is not the exception being raised here.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-12T15:55:48.313", "Id": "232258", "ParentId": "232255", "Score": "10" } }, { "body": "<h1>Style</h1>\n\n<p>Code style is not \"mission critical\" for a beginner, but can become more important when working on larger projects. Python has an \"official\" <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">Style Guide for Python Code</a>, which is widely followed in the larger Python community. It codifies a lot of recommendations on variable naming, whitespace, and the like.</p>\n\n<p>As an example, the official recommendation for variable and function names is to use <code>lower_case_with_underscores</code> instead of <code>camelCase</code>.</p>\n\n<h1>Documentation</h1>\n\n<p>The style guide also has a few rules about <a href=\"https://www.python.org/dev/peps/pep-0008/#documentation-strings\" rel=\"nofollow noreferrer\">how function documentation should be written</a> in order to be usable by Python's built-in <code>help(...)</code>. The convention is to have the docstring after the <code>def</code>-line, <code>\"\"\"quoted in triple quotes\"\"\"</code>.</p>\n\n<pre><code>def enemyBoardLoader():\n \"\"\"Loads the enemy board\"\"\"\n global num\n file = open(\"board\" + str(num) + \".txt\")\n return file.read()\n</code></pre>\n\n<h1>Random number generation</h1>\n\n<p>You only really need to call <a href=\"https://docs.python.org/3/library/random.html\" rel=\"nofollow noreferrer\"><code>random.seed(...)</code></a> if you actually want to get reproducible pseudo-random numbers. Then you would pass a fixed seed value. If you only want some pseudo-random numbers, you don't need to call it, because the random number generator is seeded by default.</p>\n\n<p>Also, there seems to be a small bug in your code. Since what really want are numbers between 1 and 5 (the boards in your repo are numbered 1 to 5), you will have to use <code>random.randrange(1, 6)</code> or even better <a href=\"https://docs.python.org/3/library/random.html#random.randint\" rel=\"nofollow noreferrer\"><code>random.randint(1, 5)</code></a>, since otherwise board 5 will never be selected.</p>\n\n<h1>Global variables</h1>\n\n<p>You are using global variables in a lot of places, which makes it harder to see which functions modify what part of the game state, and as a consequence of that also harder to test functions individually without resetting the global state in the mean time.</p>\n\n<p>Fortunately, quite some instances of global variable usage in your code can be replaced by using (additional) function arguments. E.g. instead of </p>\n\n<blockquote>\n<pre><code>def enemyBoardLoader():\n global num\n file = open(\"board\" + str(num) + \".txt\")\n return file.read()\n</code></pre>\n</blockquote>\n\n<p>simply do</p>\n\n<pre><code>def enemyBoardLoader(num):\n file = open(\"board\" + str(num) + \".txt\")\n return file.read()\n</code></pre>\n\n<p>As you can see we where able to get rid of that pesky <code>global</code> keyword. Sidenote: strictly speaking <code>global</code> is not even necessary to read from variables from a surrounding scope, but only when trying to modify them. For instance, this can be witnessed in <code>boardInfoLoader()</code>, where you are using <code>num</code> without explicitly declaring it <code>global</code>. But as I said, it's best to avoid it whenever possible.</p>\n\n<h1>The truth</h1>\n\n<p>Python has a <code>bool</code> datatype with <code>True</code> and <code>False</code> as possible values, but that should be old news for you since you already use it in some places. Prefer to use <code>True</code> instead of <code>1</code> and <code>False</code> instead of <code>0</code> in <code>sunk</code> and similar situations. Then instead of <code>sunk[0] == 0</code>, you'd write <code>sunk[0] == False</code> or even more \"pythonic\" <code>not sunk[0]</code> (see how this starts to sound like plain English?).</p>\n\n<h1>Closing files</h1>\n\n<p>Whenever you <code>open(...)</code> a file, don't forget to <code>.close()</code> it properly. Otherwise this could get you into trouble in the long run. Since forgetting is so easy, Python has the so called <code>with</code>-statement which automagically ensures that the file gets closed no matter what happens (i.e. not even an <code>Exception</code> or <code>return</code> can stop it from doing so). To get back to the previous example, now rewritten using a <code>with</code>:</p>\n\n<pre><code>def enemyBoardLoader(num):\n with open(\"board\" + str(num) + \".txt\") as file:\n return file.read()\n</code></pre>\n\n<h1>Reading the boards from disk</h1>\n\n<p>Reading and writing data from and to disk (aka (de)serializing) can be a tedious task as you maybe witnessed first-hand when writing <code>boardInfoInterp()</code> and associates. Fortunately, Python can greatly simplify your life here. Maybe you have heard of the so called <a href=\"https://en.wikipedia.org/wiki/JSON\" rel=\"nofollow noreferrer\">JSON format</a>, very often found in web applications. Python has a module called <a href=\"https://docs.python.org/3/library/json.html\" rel=\"nofollow noreferrer\"><code>json</code></a> which allows you to (de)serialize your data from/into a standardized format. As an example, say you have a list of lists (e.g. like your board), <code>my_data = [list(range(4)) for _ in range(3)]</code>. Enter <code>json</code>. <code>json.load/dump</code> allows you two load or write data from and to files with relative ease:</p>\n\n<pre><code>with open(\"mydata.json\", \"w\") as output_file:\n json.dump(mydata, output_file)\n</code></pre>\n\n<p><code>mydata.json</code> now has the following content:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>[[0, 1, 2, 3], [0, 1, 2, 3], [0, 1, 2, 3]]\n</code></pre>\n\n<p>Simply calling</p>\n\n<pre><code>with open(\"mydata.json\", \"r\") as file_:\n mydata = json.load(file_)\n</code></pre>\n\n<p>brings your data back to Python.</p>\n\n<p>Using <code>json</code> might be overkill for simple things like lists of lists, but it can save you a lot of headache once it gets a little more involved.</p>\n\n<hr>\n\n<p>That's it for now. Maybe I have time to look at your code later again. Till then: Happy coding!</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-12T17:15:44.850", "Id": "232264", "ParentId": "232255", "Score": "6" } }, { "body": "<p>I think the place to start is the function <code>boardFunc</code>. Until you get comfortable with \"functional programming\" and dependency inversion, you should probably never write a function that takes an argument telling it what to do. We can rewrite that function as </p>\n\n<pre class=\"lang-py prettyprint-override\"><code># Set up the player board for a new game. (100 \"0\"s)\ndef boardReset():\n global board\n for x in enemyBoard:\n board.append(\"0\")\n\n# Print the player board. (10 rows of 10)\ndef boardPrint():\n global board\n for x in range(10):\n print(\" \".join(board[(x * 10):((x + 1) * 10)]))\n\n# Update the player board based on a shot\ndef boardUpdate(shot):\n global board\n if enemyBoard[((shot[0] - 1) + (shot[1] - 1) * 10)] == \"X\": # If the shot location is an X on the enemy board, mark a hit on the player board\n if board[((shot[0] - 1) + (shot[1] - 1) * 10)] != \"X\":\n board[((shot[0] - 1) + (shot[1] - 1) * 10)] = \"X\"\n boardInfoRemover(shot)\n global hits\n hits += 1\n else:\n board[((shot[0] - 1) + (shot[1] - 1) * 10)] = \"M\" # If the shot location is not an X on the enemy board, mark a miss on the player board\n</code></pre>\n\n<p>I'm testing your code in Jupyter Notebooks, where the <code>while True: ... quit()</code> pattern doesn't work right. We can make it a little more explicit, reliable, and portable by using a mutable variable to break the loop:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>keepPlaying = True\nwhile keepPlaying:\n boardReset()\n while hits &lt; 15: # Each board has 15 ship spots, when all are hit it breaks out of this loop\n boardPrint()\n boardUpdate(inputCleaner())\n sunkChecker()\n boardPrint(\"print\", 0)\n keepPlaying = \"y\" == input(\"YOU WON!! Would you like to play again? (y/n):\")\n</code></pre>\n\n<p>In fact, you seem a bit trigger-happy with the <code>while</code> loops in general. If you can use a <code>for</code> loop, that's preferable. When you want to loop over a range of numbers, you can use <code>range</code>, but when you're working with an existing list you're better off looping over <em>the list itself</em> (or a derivation of the list). Even better is to avoid a loop altogether. While you're at it, try to work <em>with</em> the data structures python provides!<br>\n(I was able to confirm that your <code>boardInfoRemover</code> function was working for hits in the tenth row or column, but I can't explain how.)</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>#If a shot is on a ship, it removes that shot from the boardInfo list\ndef boardInfoRemover(hit):\n #pprint.pprint(hit)\n global boardInfo\n #Checks to see which shot location it was, and removes it from the boardInfo list\n for i, boardRow in enumerate(boardInfo):\n for j, value in enumerate(boardRow):\n if value == hit:\n del boardInfo[i][j]\n</code></pre>\n\n<p>Looking at <code>boardReset</code>, does it actually reset the board, or does it just assume it's already empty, and then append? I was just saying that you should use fewer loops, so now's a good time to introduce list comprehensions. (The other option would be to map with a lambda, build a const function, but comprehension are a good tool.)</p>\n\n<pre class=\"lang-py prettyprint-override\"><code># Set up the player board for a new game. (100 \"0\"s)\ndef boardReset():\n global board\n board = [\"0\" for _ in enemyBoard]\n</code></pre>\n\n<p>The <code>inputCleaner</code> function is large, but without bringing in a new library to do input cleaning for you, there may not be a way to make it <em>shorter</em>. What we can do is make it's flow more clear (linear), not rely on exceptions, and <em>return 0-indexed coordinates</em>. In particular, we can make it recursive, avoiding a lot of the looping behavior. We loose the part where the user only has to re-enter one of the numbers if they're out of range, but that doesn't seem like a big loss.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>#Takes and cleans the input to prevent errors\ndef inputCleaner():\n failures = []\n coordinates = None # be careful about None, but it'll do for now.\n input_list = input(\"Were do you want to shoot your shot? (num1 num2):\")\n if 2 != len(input_list):\n failures.append(\"Please enter exactly two numbers.\")\n if any(not coordinate.isdigit() for coordinate in list_input):\n failures.append(\"Please use only numbers.\")\n else:\n coordinates = map(int, input_list)\n local_names = [\"first\", \"second\"]\n for i, c in enumerate(coordinates):\n if 10 &lt; c or 1 &gt; c:\n failures.append(\"Please make sure that your {} number is at least 1 and no more than 10.\"\n .format(local_names[i]))\n if not failures:\n return [c - 1 for c in coordinates]\n # If we get here, failures will not be empty.\n failures.append(\"Enter you shot location again.\")\n for f in failures:\n print(failure)\n return inputCleaner()\n</code></pre>\n\n<p>Again, use the tools the language gives you to simplify. This time the <code>boardInfoInterp</code> function, because we need to convert it to match the 0-indexing we want to use everywhere. We want to use 0-indexing so that we can do list-lookup.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>#Turn the line input into a list of lists of pairs (which are lists) of 0-indexed ints\ndef boardInfoInterp(boardInfo):\n return [\n [\n [int(coordinate) - 1 for coordinate in pair.split()]\n for pair\n in ship.split(\",\")\n ]\n for ship\n in boardInfo.split(\";\")\n ]\n</code></pre>\n\n<p>Other things we should be doing: </p>\n\n<ul>\n<li>Use bools</li>\n<li>Store the board as a list of lists.</li>\n<li>Use arguments and return values instead of global variables.</li>\n</ul>\n\n<p>But getting this to the point where there's <em>no</em> global state would amount to a complete rewrite. If you want to go that route, you'll need to think about how to best represent the <em>game state</em> as an abstract data structure. You'd then write functions like</p>\n\n<pre><code>newGame: ()-&gt;GameState\nplayerMove: (GameState, PlayerMove)-&gt;GameState\ndisplay: GameState-&gt;print\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-12T22:16:58.237", "Id": "453516", "Score": "0", "body": "Thanks for the in-depth answer. The way the ```boardInfoRemover``` works is by taking the shot input (say, ```[10, 10]```) turns it into a ```str``` (```\"[10, 10]\"```), turns that ```str``` into a ```list``` (```[ \"[\", \"1\", \"0\", \",\", \" \", \"1\", \"0\", \"]\"]```), removes the brackets spaces and commas (```[\"1\", \"0\", \"1\", \"0\"]```), then finally makes all the numbers into ```int``` (```[1, 0, 1, 0]```). Quite ridiculous but the first thing I thought of." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-13T14:05:17.187", "Id": "453627", "Score": "0", "body": "\"you should probably never write a function that takes an argument telling it what to do\" Why not? It can be very useful at times, even if you ignore the existance of functional programming the rest of the time." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-13T22:06:43.513", "Id": "453689", "Score": "0", "body": "@Mast, There's probably a lot of useful discussion about it; higher-level functions are great, and dependency injection/inversion is its own whole thing that can be implemented a lot of different ways. That said, the original `boardFunc` is an excellent example of both _when not to_ and _how not to_ write a function that takes an argument telling it what to do: There's no overlap between the execution paths, the argument in question is a \"data\" Type when it's never used as \"data\", and the arg value is hard-coded in all of the places where it's used." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-12T18:28:08.107", "Id": "232270", "ParentId": "232255", "Score": "6" } } ]
{ "AcceptedAnswerId": "232270", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-12T15:19:19.780", "Id": "232255", "Score": "9", "Tags": [ "python", "beginner", "python-3.x", "game", "battleship" ], "Title": "Single Player Python Battleship Game" }
232255
<p>Below I am giving you my code which I wrote to print even number using even thread and odd number using odd thread sequentially.</p> <p>Could anyone please validate my code whether it is correct way of doing it or not? I am getting correct result, but I just want to make sure whether I am doing it in correct way or not.</p> <pre><code>public class PrintNumberUsingThread { public static void main(String[] args) { PrintNumberUsingThread example = new PrintNumberUsingThread(); PNThread pnThread = example.new PNThread(10); new Thread(pnThread).start(); new Thread(pnThread).start(); } class PNThread implements Runnable { private int number = 0; private int maxNumber; public PNThread(int maxNumber) { this.maxNumber = maxNumber; } @Override public void run() { while (number &lt;= maxNumber) { synchronized (this) { String threadName = Thread.currentThread().getName(); if (number &lt;= maxNumber) { boolean even = threadName.contains("0") &amp;&amp; number % 2 == 0; boolean odd = threadName.contains("1") &amp;&amp; number % 2 != 0; if (even || odd) { System.out.println(threadName + "-" + number++); this.notifyAll(); } else { try { this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } } } } } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-13T07:08:15.010", "Id": "453555", "Score": "2", "body": "Can you post the exact assignment text?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-13T08:00:10.863", "Id": "453563", "Score": "0", "body": "Why do you need synchronized (this) in the thread ? You don't have concurrent access to the run() method." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-13T08:06:19.340", "Id": "453564", "Score": "0", "body": "@rpc1 I need synchronization because I am waiting a thread if that is not satisfying a condition (the else block) also I am notifying all the other waiting threads when condition satisfies." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-13T08:10:50.623", "Id": "453565", "Score": "0", "body": "@TorbenPutkonen What do you mean by exacct assignment text? Do you want me to give what exactly I want to do in this program? If yes, then I want to print odd numbers using odd thread and even numbers using even thread." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-13T13:36:52.413", "Id": "453622", "Score": "0", "body": "It's just that this looks like homework, if so, this works best when you give us the exact homework description." } ]
[ { "body": "<p>If the only requirement is to have two threads, one printing even numbers and other printing odd numbers, then your solution is unnecessarily complicated. The fact that you share the same data model for both threads forces you to synchronize access to the object making the solution unnecessarily complicated. The assignment did not require numbers being printed in sequence, so the coordination between the threads is unnecessary.</p>\n\n<pre><code>public class Counter implements Runnable {\n private final int start;\n private final int end;\n private final int increment;\n ... add boilerplate constructor ...\n public void run() {\n for (int i = start; i &lt;= end; i += increment) {\n System.out.println(i);\n }\n }\n}\n</code></pre>\n\n<p>Start threads:</p>\n\n<pre><code>new Thread(new Counter(1, 10, 2)).start();\nnew Thread(new Counter(2, 10, 2)).start();\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-13T09:04:16.137", "Id": "453576", "Score": "0", "body": "Yes got it, but I am sorry I forgot to mention that I want to print in in a sequence." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-13T08:46:56.313", "Id": "232308", "ParentId": "232262", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-12T16:25:22.063", "Id": "232262", "Score": "3", "Tags": [ "java", "multithreading", "thread-safety", "concurrency", "threadx" ], "Title": "Code to print even and Odd number using two threads" }
232262
<p>I've been writing code for nearly 40 years now and am still not too old to learn and understand new things. Right now, my focus is a bit of OO with functional programming combined and C# with Linq is an excellent way to fool around with this.<br> I'm also practicing deferred execution and aggregating to make it really interesting. So I designed a dice roller. And to start, I begin by specifying various dice types:</p> <pre><code>public enum DiceType { D2 = 2, D3 = 3, D4 = 4, D6 = 6, D8 = 8, D10 = 10, D12 = 12, D20 = 20, D100 = 100 } </code></pre> <p>Very basic, actually. Each enum value just indicates the number of sides a die has. These values are very common, with the D2 (coin flip) and D6 (regular die) being the most well-known.<br> Next is a static class that can basically roll any dice, and will do this until infinity:</p> <pre><code>public static class Dice { public static IEnumerable&lt;int&gt; Roll() { var rnd = new Random(); while (true) { yield return rnd.Next(1, 7); } } public static IEnumerable&lt;int&gt; Roll(this DiceType die) { var rnd = new Random(); while (true) { yield return rnd.Next((int)die) + 1; } } public static IEnumerable&lt;int&gt; RollX(this IEnumerable&lt;int&gt; rolls, int x = 3) { while (true) { yield return rolls.Take(x).Sum(i =&gt; i); } } } </code></pre> <p>The <code>Roll()</code> method will be the stereotype die with six sides. Hardcoded, as someone might change the value for D6 to 8 and cause problems. This method will always roll a six-sided die.<br> But <code>Roll(this DiceType die)</code> is more interesting as it basically extends the DiceTyper enumeration. And it will roll that specific die into infinity so if I use <code>DiceType.D20.Roll()</code> then I will get an endless list of values between 1 and 20...<br> The third method <code>RollX()</code> is an even more interesting one. It will use the previous dice enumerator and take an X amount of values to sum them, before taking the next X amount of dice. By default, it will roll 3 times. And <code>DiceType.D6.Roll().RollX(5)</code> will roll 5 dice, each resulting in a value between 1 and 6, and add them to get values between 5 and 30, and a bell curve.<br> Next, two clock-related aggregators that will limit the amount of time allowed to keep rolling:</p> <pre><code>public static IEnumerable&lt;T&gt; MaxTime&lt;T&gt;(this IEnumerable&lt;T&gt; source, long totalMs) { var sw = new Stopwatch(); foreach (var item in source) { if (!sw.IsRunning) { sw.Restart(); } if (sw.ElapsedMilliseconds &lt; totalMs) { yield return item; } else { yield break; } } } public static IEnumerable&lt;T&gt; MaxTicks&lt;T&gt;(this IEnumerable&lt;T&gt; source, long totalTicks) { var sw = new Stopwatch(); foreach (var item in source) { if (!sw.IsRunning) { sw.Restart(); } if (sw.ElapsedTicks &lt; totalTicks) { yield return item; } else { yield break; } } } </code></pre> <p>The stopwatch class can be found in System.Diagnostics.<br> The principle is simple: it will do a deferred execution until the time is up, which can either be a matter of seconds or a matter of clock ticks.<br> As a final step, I want an aggregator to just add all the results:</p> <pre><code>public static SumTotal Total(this IEnumerable&lt;int&gt; data) { var result = new SumTotal(); foreach (var i in data) { result.Add(i); } return result; } </code></pre> <p>And this introduces this class:</p> <pre><code>public class SumTotal { public long Sum { get; set; } = 0; public long Total { get; set; } = 0; public long Min { get; set; } = long.MaxValue; public long Max { get; set; } = long.MinValue; public SumTotal Add(long value) { Total++; Sum += value; if (Max &lt; value) { Max = value; } if (value &lt; Min) { Min = value; } return this; } public override string ToString() =&gt; $"For {Total:#,##0} items, total of {Sum:#,##0}, average of {Sum * 1.0 / Total:#,##0.00} between {Min:#,##0} and {Max:#,##0}."; } </code></pre> <p>So I get a total containing the number of rolls, the minimum and maximum values rolled and a total of all values and can calculate the average value rolled.<br> Now, to use it, all I have to do is define a rolling queue like this:</p> <pre><code>public static IEnumerable&lt;int&gt; D12Queue = DiceType.D12.Roll(); </code></pre> <p>This generates a static variable from where I can just take an X amount of rolls. Simply using <code>D12Queue.Take(5)</code> will give me 5 random values between 1 and 12. This makes it practical to use in games where you'd need to emulate a dice roll.<br> So, is this a practical solution? I'm just training and learning new skills so I haven't thought about that aspect...</p> <hr> <p>The latter dice queue is what my main focus will be. I can use this:<br> <code>var queue = DiceType.D6.Roll();</code> to generate a queue. And then:<br> <code>var roll = queue.First();</code> which will give a new dice roll with every call.<br> <code>var yahtzee = queue.Take(5);</code> to roll 5 dice and see if I rolled a Yahtzee.<br> <code>var highRoll = queue.RollX(5).Take(20).Max();</code> Which will roll 5 dice repeatedly for 20 times and return the highest value.<br> So basically, I made dice rolling part of Linq queries so I don't need to write loops if I need multiple rolls. I just take the number of required rolls from the queue.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-12T19:12:54.087", "Id": "453485", "Score": "3", "body": "I recently wrote a 41 part blog series on the subject of how to generalize the lessons of LINQ to representing randomness; you might find it interesting. Start here: https://ericlippert.com/2019/01/31/fixing-random-part-1/" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-13T10:55:56.850", "Id": "453600", "Score": "0", "body": "I'm considering if the DiceType enum should be converted into a list of int constants and extend the Roll() method to the int type instead." } ]
[ { "body": "<h1><code>Random</code></h1>\n\n<p>Don't <code>new</code> up a new instance of <code>Random</code> for each and every call of your methods. The reason for this is that the default seed used in the constructor is <strong>not</strong> random. Usually it's based on the current time, or something similar. This means that if you call the method many times at once, the random number generators might provide the same numbers.</p>\n\n<p>Instead, create a single static instance that's used by all calls.</p>\n\n<hr>\n\n<pre><code>public static SumTotal Total(this IEnumerable&lt;int&gt; data)\n{\n var result = new SumTotal();\n foreach (var i in data) { result.Add(i); }\n return result;\n}\n</code></pre>\n\n<p>The <code>linq</code> way of doing this is <code>data.Aggregate(new SumTotal(), (item, aggregate) =&gt; aggregate.Add(item))</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-12T19:14:06.700", "Id": "453487", "Score": "2", "body": "That bug has been fixed in new versions of .NET, after only being in the platform for 19 years. But it is still a bad idea to make a new `Random` every time you need a new number." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-12T19:50:25.697", "Id": "453492", "Score": "1", "body": "The New() is called just once for every dice queue. And the method is used to create one queue for every dice needed and grab values from the queue whenever needed. So, not a problem to me." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-12T20:00:32.457", "Id": "453494", "Score": "0", "body": "The Total method is an aggregator method, similar to Aggregate, ToList and a few other methods. Using aggregators and understanding how they work are different things." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-12T20:04:55.053", "Id": "453496", "Score": "2", "body": "@WimtenBrink the point still stands, and if you are providing this code as a library, you don't have control about how it is called, or how often. Best to think ahead and don't make the mistakes that are easy to prevent." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-12T20:23:03.587", "Id": "453497", "Score": "0", "body": "If I do make a library out of it, it would include a static class with the various dice queues as static variables, depending on what it will be part off. The rest would basically become an internal class. This code by itself isn't meant to be a complete library. It needs more to be more practical." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-12T17:47:51.217", "Id": "232268", "ParentId": "232266", "Score": "8" } }, { "body": "<p>Nice code.</p>\n\n<p>Some comments :)</p>\n\n<h2>Too Defensive</h2>\n\n<p>You wrote:</p>\n\n<blockquote>\n <p>The <code>Roll()</code> method will be the stereotype die with six sides.\n Hardcoded, as someone might change the value for D6 to 8 and cause\n problems. This method will always roll a six-sided die.</p>\n</blockquote>\n\n<p>What if someone changes the underlying value of D2 to 3? Won't that be a major surprise?</p>\n\n<p>My take about this approach is: don't write idiot proof code, otherwise you'd be chasing your tail. Write code that an average programmer could understand.</p>\n\n<p>In your code, there's a convention that the die enum name <em>has to be</em> the same as its underlying <code>int</code> value. That's a design decision you took. It's a valid design decision. Stick to it.</p>\n\n<p>In addition, if, for some reason, you choose to change your implementation of the underlying enum value, you'll have to remember that the logic is also implemented, hard coded, in your <code>Roll()</code> method. In other words, you break DRY.</p>\n\n<h2>O/CP</h2>\n\n<p>When you have an <code>enum</code> in your code, it should be a well defined, closed group of values that usually share something. The \"closed\" part is essential.</p>\n\n<p>Take weekdays, for instance. There won't be any additional weekday. There's no eighth value that can be added. Therefore, we can have them as an <code>enum</code>.</p>\n\n<p>Take card suites. There are only four of them. I think my point is clear.</p>\n\n<p>When we declare an <code>enum</code>, we say something like: \"these are the only values of this group.\"</p>\n\n<p>However, in your code, you declare (only) the following values as possible die/dice:</p>\n\n<p>2, 3, 4, 6, 8, 10, 12, 20, 100</p>\n\n<p>What if someone would want to have your cool engine to be applied on a card suite? It's 13 cards in a suite. And you don't have 13 as a value in your <code>enum</code>.</p>\n\n<p>In programming, there's a very important principle named <a href=\"https://en.wikipedia.org/wiki/Open%E2%80%93closed_principle\" rel=\"noreferrer\">Open/Closed Principle</a>. I think that your <code>enum</code> is not aligned with O/CP, because if you'd want to use your random engine on a \"die\" with 13 values, then you'd have to add <code>D13</code> to your <code>enum</code>, rebuild and redeploy your solution. When you're aligned with O/CP - you provide a way to extend your program (\"open to extensions\") without rebuilding it (\"closed to modifications\").</p>\n\n<p>So maybe there's no need to wrap those values in an <code>enum</code> in the first place? Simply write a class that takes the number of edges the \"die\" has in its constructor, and you're done.</p>\n\n<p>It's not as \"pretty\" as an <code>enum</code>, but it sure is more extensible.</p>\n\n<h2>Deferred Execution</h2>\n\n<p>You write:</p>\n\n<blockquote>\n <p>The principle is simple: it will do a deferred execution until the\n time is up, which can either be a matter of seconds or a matter of\n clock ticks.</p>\n</blockquote>\n\n<p>I'm not sure what you mean by that. It's not that the code runs on a different thread. Maybe I'm missing something because I haven't been coding in C# for a long while, but this code sure seems to be blocking.</p>\n\n<p>I think that the added value of those methods (<code>MaxTime</code> and <code>MaxTicks</code>) is low, and it's pretty much up to the consuming developer to implement them as needed.</p>\n\n<p>In addition to all that, there's sometime a confusion between wall-clock time (which is how things are implemented in your code) and processing time. In a multi-threaded program (or in a multi-processed system), your program, or your executing thread, is sometimes paused so that other processed/threads are executed.<br>\nHaving this point in mind, you might end up executing far less iteration than expected.<br>\nExample: usually you get 10000 iterations in 300 ticks, but in a busy system you get only 500 under the same 300 ticks. The numbers are imaginary, but you get the idea.<br>\nFor doing the actual measurements, you can read <a href=\"https://stackoverflow.com/q/23182781/17772\">this</a>.</p>\n\n<p>Again, I think that adding those measurements to your code somehow increases complexity and have a low value.</p>\n\n<h2>Calculating Min/Max</h2>\n\n<p>It's mostly a matter of style, but I tend to use the SDK's provided functions when possible.<br>\nIn your code:</p>\n\n<pre><code>if (Max &lt; value) { Max = value; }\n</code></pre>\n\n<p>Can be replaced with: </p>\n\n<pre><code>Max = Math.Max(Max, value)\n</code></pre>\n\n<p>To me, this is easier to understand the intention of the code using the built-in <code>Math.Max()</code> method.</p>\n\n<p>Cheers :)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-13T05:55:28.800", "Id": "453545", "Score": "0", "body": "Really? Math.Max instead avoiding unnecesary write? I mean `c=math.max(a,b)` why not. But `a=math.max(a,b)` why yes?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-13T06:02:31.777", "Id": "453548", "Score": "0", "body": "@slepic yes, IMO intention (or semantics), readability and consistency are stronger considerations than performance. There's a famous quote: _Premature optimization is the root of all evil_... If you profile your program and see that there's a performance issue - then (and only then) optimize your code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-13T06:38:04.643", "Id": "453552", "Score": "0", "body": "I know what premature optimization is. But I would object that this isn't it.There is difference between premature optimization and awareness of performance aspects of your code (especialy in a lib it would be bad to ignore performance until some user of the lib reports performance issues, especialy if you could have seen it before you even started implementing it). And I would also object whether a less then + an assignment is less readable than Math.Max.Anyway I wouldn't have brought this up if you didn't bring this up. It was optimal and you suggest suboptimal for a little readability gain." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-13T07:12:50.153", "Id": "453557", "Score": "0", "body": "Fair enough. We both have our opinions. I even like the debate :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-13T10:43:13.673", "Id": "453592", "Score": "0", "body": "The MaxTicks() and MaxTime() methods are useful for performance tests and to see how many rolls I can get within a certain amount of time. But if the dice queue is used for a game then it would add a time limit for the game. After e.g. 60 seconds, the queue would be \"empty\" and thus the game would be over. So the game gets a simple time limit..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-13T10:45:32.127", "Id": "453593", "Score": "0", "body": "As for cards and even a whole deck of cards, you could add them to the enum: `CardValue=13` and `DeckOfCards=52`. But the Roll() method might also just extend any integer... I choose the enum to be more descriptive. (And cards aren't dice!)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-13T10:47:59.647", "Id": "453594", "Score": "0", "body": "The deferred execution relates to the `yield return` which gets called whenever the next method in line asks for the next value. With the MaxTime and MaxTicks method, it will stop yielding values so that ends all rolls. Game over, basically..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-13T12:02:46.057", "Id": "453608", "Score": "0", "body": "@WimtenBrink in a game you will often want to make the timer accessible by the game state view layer. and so it might be better to have it in upper layer and use it to control how long you keep calling Roll(), instead of having to retrieve the timer from inside the roll queue which you actualy didn't make possible. In you implementation the timer is just a local variable of the MaxTick/MaxTime method and thus you cannot possibly hope to be able to retrieve the time left or time lapsed from it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-13T12:50:37.220", "Id": "453618", "Score": "1", "body": "@WimtenBrink You can roll a 13-side dice and get a number from it, which corresponds to the card. In fact, you have D2, which is a **coin flip** (hey, you called it!). As far as I know, a dice and a coin are different. Just allowing to pass a different value (an integer) with the number of sides could be enough. This way, you can use both an enum and a different value. Also, here's a set of odd dice (3 to 15): https://www.amazon.com/Green-Unusual-Odd-Numbered-Dice/dp/B00YLWVOXU (source: https://www.reddit.com/r/rpg/comments/aroymo/uk_is_there_such_a_thing_as_a_21_sided_dice_and/)" } ], "meta_data": { "CommentCount": "9", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-12T21:13:39.607", "Id": "232283", "ParentId": "232266", "Score": "5" } }, { "body": "<p>Let me just repeat what @Ron Klein said, dont put your dices into enum, the real set of all possible dices is much greater than what your enum offers.</p>\n\n<p>Let me show how I think the Dice class would be better implemented:</p>\n\n<pre><code>class Dice : IEnumerable&lt;int&gt;\n{\n private int Sides;\n private int Shift;\n private Random Generator;\n\n public Dice(int sides, int shift, Random generator)\n {\n Sides = sides;\n Shift = shift;\n Generator = generator;\n }\n\n public Dice(int sides, int shift, int seed) : this(sides, shift, new Random(seed)) {}\n public Dice(int sides, int shift) : this(sides, shift, new Random()) {}\n public Dice(int sides, Random generator) : this(sides, 1, generator) {}\n public Dice(int sides) : this(sides, 1) {}\n public Dice(Random generator) : this(6, generator) {}\n public Dice() : this(6) {}\n\n public int Roll()\n {\n return Generator.Next(Sides) + Shift;\n }\n\n public IEnumerator&lt;int&gt; GetEnumerator()\n {\n while (true) yield return Roll();\n }\n\n IEnumerator IEnumerable.GetEnumerator()\n {\n return GetEnumerator();\n }\n}\n</code></pre>\n\n<p>Now you can create whatever dice you want:</p>\n\n<pre><code>var d20 = new Dice(20);\nvar coin = new Dice(2);\nvar cube = new Dice(6);\nvar uncommon = new Dice(7);\nvar d0to5 = new Dice(6, 0);\nvar d15to30 new Dice(16, 15);\n</code></pre>\n\n<p>You can roll once</p>\n\n<pre><code>var roll = d20.Roll(); //1-20\n</code></pre>\n\n<p>Or you can roll N times</p>\n\n<pre><code>var sum = uncommon.Take(3).Sum(i =&gt; i); //3-21\n</code></pre>\n\n<p>Or you can even roll as many as the CPU can do in a certain amount of time/ticks</p>\n\n<pre><code>var rolls = cube.MaxTicks(250);\n</code></pre>\n\n<p>Also as mentioned by others, the Random class needs a seed and the default constructor seeds from current time. My Dice class implementation allow this default Random but also allows to inject Random instance seeded in a way out of scope of the Dice class.</p>\n\n<pre><code>var d20 = new Dice(20, new Random(myseed));\n</code></pre>\n\n<p>I have actualy added more constructors to simplify this and I have also added <code>Shift</code> property to the Dice as it seemd a waste to have +1 as constant, if it might be possible to have dices starting with zero or any other number.</p>\n\n<pre><code>var d20 = new Dice(20, 1, myseed);\n</code></pre>\n\n<p>Anyway I think that the <code>MaxTick</code> and <code>MaxTime</code> methods are quite controversial. One thing is they break SRP.\nGood rule of thumb though is that methods should not instantiate objects and do some work (other that the work needed to instantiate those objects). They should do one or the other, but not both.\nOther thing is I'm not sure they will fulfill their purpose as mentioned in comments under other answer.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-13T10:29:00.220", "Id": "453585", "Score": "0", "body": "Actually, no! I can use First() to get just one roll or Take() to get a number of rolls. By repeating calls to First(), I keep getting new rolls. The principle is that I defined a dice queue from where you can get as many dice rolls as you need. An infinite number of rolls to be used whenever needed." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-13T10:52:56.557", "Id": "453596", "Score": "0", "body": "Creating an infinite enumeration was my purpose here. It would be bad when someone called `DiceType.D20.Roll().Last();` as it would run forever. You're missing the point, though. I implemented it as an enumeration so you can get a list of rolls like `DiceType.D6.Roll().Take(5);` would give 5 values immediately. Not the sum of 5 values. Useful for a Yahtzee game." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-13T10:54:21.303", "Id": "453597", "Score": "0", "body": "Your MaxTicks() method is now limited to rolling dice. Mine can be used for any enumeration and will just break off enumeration when the time is up. You made a method with two functions, mine has just one." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-13T11:45:01.777", "Id": "453603", "Score": "0", "body": "@WimtenBrink ok I guess I missed that purpose. I edited a little to fit your needs. Basicaly keep the `MaxTicks` and `MaxTime` away as you did. but the `Dice` class now implements `IEnumerable<int>` so you can use it with those methods. Also added some convenience constructors." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-13T19:39:02.380", "Id": "453667", "Score": "0", "body": "Now, this is a Dice version I like. Do keep in mind that I want a Dice solution, not a Random replacement. So the shift parameter is not needed as they all start with 1. Even cards start at one. I also wonder if the Random generator should be a static variable in the class, so it is created once and reused for all dice objects. But what I like about the extension method is that you can replace DiceType by Int and thus use 12.Roll() to get a queue for rolling D12's." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-13T19:41:58.343", "Id": "453668", "Score": "0", "body": "And yex, MaxTicks and MaxTime are a bit controversial but I made them to allow time constraints on method chains handling enumerations. Adding MaxTime() to a Dice queue would basically force a game to be over as no more dice can be rolled after the amount of time. When the queue is generated when the game starts, the game would be nicely limited in the amount of game time." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-14T06:51:43.990", "Id": "453712", "Score": "1", "body": "@WimtenBrink I'm not sure that would be a good idea to share one Random object. It is a very simple RNG and it shows some patterns if you for example generate coordinates with it (rolling 2 dice repeatedly one after the other is kinda the same). But Maybe it would be enough for your case." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-14T06:52:11.200", "Id": "453713", "Score": "1", "body": "@WimtenBrink Also one shared static instance may be quite easy to guess what numbers it is going to generate based on the time at which you start the program. I've been thinking maybe you could have one static instance and use this to generate seeds for new Random instances that you will pass to each new Dice. This way it may still be a bit predictable, but the predictions will divert from real values very fast." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-14T06:53:47.533", "Id": "453714", "Score": "1", "body": "@WimtenBrink another option might be to use a mre sofisticated RNG (like https://docs.microsoft.com/en-us/dotnet/api/system.security.cryptography.randomnumbergenerator?redirectedfrom=MSDN&view=netframework-4.8) then i guess it wouldn't be much of a problem to share just one instance of it..." } ], "meta_data": { "CommentCount": "9", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-13T07:29:56.507", "Id": "232303", "ParentId": "232266", "Score": "1" } } ]
{ "AcceptedAnswerId": "232303", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-12T17:31:52.077", "Id": "232266", "Score": "8", "Tags": [ "c#", "functional-programming", "random" ], "Title": "Rolling dice in a method chain" }
232266
<p>I'm working on a web framework in C++ and there's this part that I need to do something like this:</p> <pre class="lang-cpp prettyprint-override"><code>using valves; App app; app.on( (get or head) and "/home"_path , [] (auto &amp;req, auto&amp; res) { // ... }); </code></pre> <p>(The code above is not a semi-code, it'll be like that exactly)</p> <p>In order to implement the <code>(get or head) and "/home"_path)</code> part, I'm doing this: I'm calling those <code>get</code> and <code>head</code> and <code>"/home"_path</code> (which is just <code>path("/home"</code>) <strong>valves</strong>.</p> <p>Here's the code:</p> <pre><code>enum class logical_operators { AND, OR, XOR }; template &lt;typename NextValve&gt; struct basic_valve { using next_valve_type = std::remove_reference_t&lt;std::remove_cv_t&lt;NextValve&gt;&gt;; next_valve_type next; logical_operators op; constexpr basic_valve(next_valve_type&amp;&amp; _next, logical_operators op) noexcept : next(std::move(_next)), op(op) {} constexpr basic_valve(next_valve_type const&amp; _next, logical_operators op) noexcept : next(_next), op(op) {} constexpr basic_valve(basic_valve const&amp; v) noexcept = default; constexpr basic_valve(basic_valve&amp;&amp; v) noexcept = default; constexpr basic_valve&amp; operator=(basic_valve const&amp; v) noexcept = default; constexpr basic_valve&amp; operator=(basic_valve&amp;&amp;) noexcept = default; }; template &lt;&gt; struct basic_valve&lt;void&gt; {}; template &lt;typename ValveType, typename NextValve = void&gt; class valve : public basic_valve&lt;NextValve&gt;, public ValveType { public: using type = ValveType; using next_valve_type = NextValve; using ValveType::ValveType; using basic_valve&lt;NextValve&gt;::basic_valve; constexpr valve() noexcept = default; /** * @tparam NewValveType * @param valve */ template &lt;typename NewValve&gt; [[nodiscard]] constexpr auto set_next(NewValve&amp;&amp; v, logical_operators the_op) const noexcept { if constexpr (std::is_void_v&lt;next_valve_type&gt;) { // this part will only execute when the "next_valve_type" is // void // the first way (A&lt;X, void&gt; and B&lt;Y, void&gt; === A&lt;X, B&lt;Y, void&gt;&gt; return valve&lt;ValveType, NewValve&gt;(std::forward&lt;NewValve&gt;(v), the_op); } else { // this means this function has a "next" valve already, // so it goes to the next's next valve // this way we recursively create a valve type and return it. auto n = basic_valve&lt;NextValve&gt;::next.set_next(v, the_op); return valve&lt;ValveType, decltype(n)&gt;{n, this-&gt;op}; } } template &lt;typename NewValve&gt; [[nodiscard]] constexpr auto operator&amp;&amp;(NewValve&amp;&amp; v) const noexcept { return set_next(std::forward&lt;NewValve&gt;(v), logical_operators::AND); } template &lt;typename NewValve&gt; [[nodiscard]] constexpr auto operator&amp;(NewValve&amp;&amp; v) const noexcept { return set_next(std::forward&lt;NewValve&gt;(v), logical_operators::AND); } template &lt;typename NewValve&gt; [[nodiscard]] constexpr auto operator||(NewValve&amp;&amp; v) const noexcept { return set_next(std::forward&lt;NewValve&gt;(v), logical_operators::OR); } template &lt;typename NewValve&gt; [[nodiscard]] constexpr auto operator|(NewValve&amp;&amp; v) const noexcept { return set_next(std::forward&lt;NewValve&gt;(v), logical_operators::OR); } template &lt;typename NewValve&gt; [[nodiscard]] constexpr auto operator^(NewValve&amp;&amp; v) const noexcept { return set_next(std::forward&lt;NewValve&gt;(v), logical_operators::XOR); } template &lt;typename Interface&gt; [[nodiscard]] bool operator()(request_t&lt;Interface&gt; const&amp; req) const noexcept { if constexpr (std::is_void_v&lt;NextValve&gt;) { return ValveType::operator()(req); } else { switch (basic_valve&lt;NextValve&gt;::op) { case logical_operators::AND: return ValveType::operator()(req) &amp;&amp; basic_valve&lt;NextValve&gt;::next.operator()(req); case logical_operators::OR: return ValveType::operator()(req) || basic_valve&lt;NextValve&gt;::next.operator()(req); case logical_operators::XOR: return ValveType::operator()(req) ^ basic_valve&lt;NextValve&gt;::next.operator()(req); default: return false; } } } }; struct method_condition { private: std::string_view method_string; public: constexpr method_condition(std::string_view str) noexcept : method_string(str) {} constexpr method_condition() noexcept = default; template &lt;typename Interface&gt; [[nodiscard]] bool operator()(request_t&lt;Interface&gt; const&amp; req) const noexcept { return req.request_method() == method_string; } }; struct method : public valve&lt;method_condition&gt; { using valve&lt;method_condition&gt;::valve; }; struct empty_condition { template &lt;typename Interface&gt; [[nodiscard]] constexpr bool operator()(request_t&lt;Interface&gt; const&amp; /* req */) const noexcept { return true; } }; struct empty_t : public valve&lt;empty_condition&gt; {}; constexpr empty_t empty; </code></pre> <p>In the above code I haven't implemented the <code>get</code>, <code>head</code>, <code>path</code> and others yet but you get how they'll be implemented based on the two specializations of <code>empty</code> and <code>method("GET"</code>.</p> <p>The request is something like this:</p> <pre class="lang-cpp prettyprint-override"><code>template &lt;typename Interface&gt; struct request_t { // ... std::string_view request_method() noexcept { // ... } } </code></pre> <p>The required features of valves are:</p> <ul> <li>These (<code>(get &amp;&amp; head) || path("/about")</code>) should be calculated at compile time but the <code>operator()</code> will be run at run-time.</li> <li>Should be as fast as it can be at run-time</li> <li>No vtable (It's too slow isn't it?)</li> </ul> <p>And I know I over-optimize things sometimes but I just can't help it :)</p> <p>So, is there anyway I can make this better?</p> <p>Code on compiler explorer: <a href="https://godbolt.org/z/5EB-GM" rel="nofollow noreferrer">https://godbolt.org/z/5EB-GM</a></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-14T13:07:14.190", "Id": "453773", "Score": "1", "body": "Are you sure you don't have an extra `)` after `_path` in your first example? The parenthesis don't balance out." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-14T13:17:17.170", "Id": "453776", "Score": "0", "body": "yes, good catch, fixed it; thanks" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-14T15:25:09.480", "Id": "453796", "Score": "0", "body": "Do you have any unit tests for this code that you can post?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-15T18:38:37.593", "Id": "453968", "Score": "0", "body": "@pacmaninbw not at this point unfortunately!" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-12T17:51:55.433", "Id": "232269", "Score": "2", "Tags": [ "c++", "template", "template-meta-programming", "meta-programming" ], "Title": "Compile time logical operations for web framework in C++" }
232269
<p>I am learning to write a multi-threaded linked list class implementation with basic functionality such as <code>push</code> to front or back, <code>pop_back</code> and <code>read</code>. I came up with this implementation:</p> <pre><code>#include &lt;iostream&gt; #include &lt;thread&gt; #include &lt;mutex&gt; std::mutex m; template&lt;class T&gt; class Node{ public: T data; Node* next; Node(T data):data(data),next(NULL){} }; template&lt;class T&gt; class List{ Node&lt;T&gt; *head; public: List():head(NULL){} List(const List&lt;T&gt;&amp;)=default; //default copy constructor List&amp; operator =(const List&lt;T&gt;&amp;)=default; //default assignment List(List&lt;T&gt;&amp;&amp;)=default; //default move constructor List&amp; operator =(List&lt;T&gt;&amp;&amp;)=default; //default move assignment void push_front(T val){ //push data to front std::lock_guard&lt;std::mutex&gt; lock(m); Node&lt;T&gt;* temp=new Node&lt;T&gt;(val); if(head==NULL) head=temp; else{ temp-&gt;next=head; head=temp; } } void pop_back(){ //pop from back std::lock_guard&lt;std::mutex&gt; lock(m); Node&lt;T&gt;* cur=head; while(cur-&gt;next-&gt;next) cur = cur-&gt;next; Node&lt;T&gt;* temp=cur-&gt;next; delete(temp); cur-&gt;next=NULL; } T front(){ //return front of Linkedlist if(head!=NULL) return head-&gt;data; return -1; } void push_back(T val){ //push at back std::lock_guard&lt;std::mutex&gt; lock(m); Node&lt;T&gt;* temp=new Node&lt;T&gt;(val); if(head==NULL) head=temp; else{ Node&lt;T&gt;* cur=head; while(cur-&gt;next) cur = cur-&gt;next; cur-&gt;next=temp; } } int size(){ //return size int size=0; Node&lt;T&gt;* cur=head; while(cur){ size++; cur=cur-&gt;next; } return size; } void display(){ //read from linked list std::lock_guard&lt;std::mutex&gt; lock(m); Node&lt;T&gt;* cur=head; while(cur){ std::cout&lt;&lt;cur-&gt;data&lt;&lt;" "; cur = cur-&gt;next; } std::cout&lt;&lt;"\n"; } ~List(){ Node&lt;T&gt;* current = head; Node&lt;T&gt;* next; while (current != NULL) { next = current-&gt;next; delete current; current = next; } } }; </code></pre> <p>But, I am not very sure if I covered it right. Please share some opinions on how to make it perfect. Also, I am targeting C++11, so please throw some pointers/suggestions in that area also.</p> <p>In particular, I am looking for is answers to these questions:</p> <ol> <li>Is this a correct approach for acquiring mutex in <code>push()</code> and <code>display()</code>, in a multi-threaded environment?</li> <li><del>How can I prioritize the read/delete/write operations. For example, suppose 1 thread is displaying the data and another thread comes which wants to pop_back from the data. How do I make the changes so that my 2nd thread gets the priority while 1st thread was using my node. </del></li> <li>I have not much worked with C++11 — I just started it few months ago — so I would like to know what more I should have in my class.</li> <li>In case there are any possible bugs in this code, please let me know that too.</li> </ol>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-12T19:00:43.200", "Id": "453478", "Score": "0", "body": "Whoever so gave me -1, please I would like to understand why? Should I be giving more details, is it not clear enough?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-12T19:08:39.780", "Id": "453482", "Score": "1", "body": "I didn't downvote, but did you test this before posting? Does it appear to work? Are you sure you want your deconstructie written like that?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-12T19:10:12.357", "Id": "453484", "Score": "1", "body": "yes, of course I tested it, It is working. I am not sure what's wrong with the deconstructor, can you explain more please?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-12T19:35:04.870", "Id": "453490", "Score": "1", "body": "The person that downvoted [presumably] also voted to close for \"lacks concrete context\", a very disputable reason in this case. Consider editing your post to add more information about what your code is doing and how it's doing it, but I see nothing wrong with your post." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-13T05:16:43.420", "Id": "453539", "Score": "0", "body": "Thanks! I have edited the post with the specific questions to which I need answer for." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-13T08:23:42.163", "Id": "453572", "Score": "0", "body": "Your second specific question, requesting changes to the functionality, is off-topic for review, so I've deleted it. The rest of the question looks good; I hope you get good answers!" } ]
[ { "body": "<p>About the code:</p>\n\n<ol>\n<li><code>List&amp; operator =(const List&lt;T&gt;&amp;)=default;</code> and <code>List(const List&lt;T&gt;&amp;)=default;</code> provide excellent opportunity to get double delete with 100% chance of success.</li>\n<li>Your linked list required data to be copyable and it copies it on usage. It is bad, since now you cannot store data like <code>std::unique_ptr</code> that are not copyable. Also it is inefficient as it will have to copy large data structures like <code>std::vector</code> instead of moving their internal data around. Utilize <code>std::move</code> in functions like <code>push_back/push_front</code>.</li>\n<li>Functions <code>front()/back()</code> should return data by reference so user can modify them. Also you ought to implement their <code>const</code> versions that return data by const reference (or by value for trivial enough data types).</li>\n<li><code>std::list</code> stores also the size of the list so the function call is lazy unlike your implementation. People generally assume that <code>size()</code> is a fast operation which is not the case in your implementation.</li>\n<li>Normally in a linked-list you store both <code>head</code> and <code>tail</code> as otherwise all operations regarding the other end are ridiculously slow.</li>\n<li><code>std::cout</code> is not exactly thread safe. It doesn't crash or cause malfunctions but it might can mingle the characters you print. In a multi-threaded environment you need a logger.</li>\n<li>Wait... your linked-list doesn't provide any options for iterating over elements. Only adding / deleting / exploring elements at the head/tail and even those are slow. You need iterators or something. One important aspect of a linked list is ability to move elements from one list to another efficiently. This functionality doesn't exist in this implementation.</li>\n<li>Your mutex <code>m</code> is shared across all your linked lists-instances and types. If you want any sensible implementation of multi-threaded linked with mutexes list you ought to privately store a <code>std::unique_ptr&lt;std::mutex&gt;</code> for each instance of the linked-list.</li>\n<li>Honestly, I don't know why you want to use a linked list or implement one - it is one of the slowest and most inefficient data structures.</li>\n</ol>\n\n<p>In general, I don't think that it is a good idea to make a thread-safe linked-list. Make a concurrent linked-list at most I'd say (I not too familiar on this topic as far as I am aware it is still being researched). Just use <code>std::list</code> and have an associated mutex nearby so whenever user wants to do something with the list - they have to lock the mutex. It might be annoying to write and relying on the user to use it right is problematic but frequently user needs to make composite operations (several in a row without interruptions) which will result in program errors if another users locks the list in between these operations and does something with it.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-13T16:47:47.977", "Id": "453642", "Score": "0", "body": "Thanks for the detailed review! I agree with 3-8 points. In 1) and 2) do you mean I should have `List& operator =(const List<T>&)=delete;` and `List(const List<T>&)=delete;` instead of `List& operator =(const List<T>&)=default` and `List(const List<T>&)=default;` since `unique_ptr` can not have the copy constructor" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-13T16:48:58.890", "Id": "453643", "Score": "0", "body": "9. I am just prepping up for interview's and linked list seems to be a very very important topic being asked around." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-13T18:25:38.773", "Id": "453652", "Score": "1", "body": "(1) either delete the copy-ctor/assignment or make a custom implementation that copies the data - a deep copy not a shallow copy. @MFCDev" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-13T18:27:45.643", "Id": "453653", "Score": "1", "body": "(2) In say, `push_back` you write `Node<T>* temp=new Node<T>(std::move(val));` instead of `Node<T>* temp=new Node<T>(val);` @MFCDev" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-15T13:11:40.457", "Id": "453921", "Score": "0", "body": "@MFCDev On the second look, your move ctor/assignment also lead to double delete. You ought to make a custom implementation as well." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-13T11:15:47.823", "Id": "232314", "ParentId": "232272", "Score": "5" } } ]
{ "AcceptedAnswerId": "232314", "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-12T18:57:45.233", "Id": "232272", "Score": "2", "Tags": [ "c++", "c++11", "multithreading", "linked-list" ], "Title": "Multi-threaded LinkedList Implementation" }
232272
<p>I developed a code in python that:</p> <ul> <li>add name, age and Id information for each person,</li> <li>search a person by name, if it exists then display a message "Found" and fill "age" and "Id" with the corresponding information, else display "not found" and fill "age" and "Id" with "---". In case of more that one name is found then a wxchoice lists all these names, after the user can choose one item in the list, then all information (age and id) related to that chosen name appears.</li> </ul> <p>Note that all information are stored in a json file called "data.json".</p> <p>I need to know if that is the correct way (easy to maintain, optimised, respects good practice ...) to implement that requirements:</p> <p>Find below the code:</p> <pre><code>import json import os import wx import wx.xrc class ManageJson: def __init__(self, jsonfile): self.jsonfile = jsonfile self.content = {"Info": []} def read(self): if self.isempty() is False: with open(self.jsonfile, 'r') as infile: self.content = json.load(infile) def write(self): with open(self.jsonfile, 'w') as outfile: json.dump(self.content, outfile, indent=4) def isempty(self): return os.stat(self.jsonfile).st_size == 0 def Presearch(self, pattern): return [data for data in self.content["Info"] if pattern in data['Name'] and pattern != ''] def Postsearch(self, pattern): return [data for data in self.content["Info"] if pattern == data['Name'] and pattern != ''] def add(self, *arg): self.content["Info"].append({"Name": arg[0], "Age": arg[1], "Id": arg[2]}) class ManageGui(ManageJson): def __init__(self, jsonfile): super().__init__(jsonfile) def exporttojson(self, *arg): name = arg[0] age = arg[1] Id = arg[2] statusbar = arg[3] data = super().Presearch(name.GetValue() ) if name.GetValue() != '' and age.GetValue() != '' and Id.GetValue() != '': if len(data) == 0 and name.GetValue() != '': if super().isempty() is False: super().read() super().add(name.GetValue(), age.GetValue(), Id.GetValue()) super().write() statusbar.SetStatusText("Exporting done!") else: statusbar.SetStatusText("Element is already exist!") else: statusbar.SetStatusText("One field is empty!") def importfromjson(self): super().read() def Presearch(self, *arg): super().read() data = super().Presearch(arg[0].GetValue()) print(data) print(len(data)) if len(data) == 1: arg[4].Clear() f = data[0] arg[0].SetValue(f["Name"]) arg[1].SetValue(f["Age"]) arg[2].SetValue(f["Id"]) arg[3].SetStatusText("Found") arg[4].Append(f["Name"]) elif len(data) &gt; 1: arg[4].Clear() for i in range(len(data)): f = data[i] arg[4].Append(f["Name"]) arg[3].SetStatusText("More than one found, choose one?") else: arg[1].SetValue("---") arg[2].SetValue("---") arg[3].SetStatusText("Not Found!") def Postsearch(self, *arg): super().read() id = arg[4].GetSelection() data = super().Postsearch(arg[4].GetString(id)) if len(data) == 1: f = data[0] arg[0].SetValue(f["Name"]) arg[1].SetValue(f["Age"]) arg[2].SetValue(f["Id"]) arg[3].SetStatusText("Found") else: arg[1].SetValue("---") arg[2].SetValue("---") arg[3].SetStatusText("Not Found!") class Frame(wx.Frame): def __init__(self, parent): wx.Frame.__init__(self, parent, id=wx.ID_ANY, title=u"Fist Application", pos=wx.DefaultPosition, size=wx.Size(500, 300), style=wx.DEFAULT_FRAME_STYLE | wx.TAB_TRAVERSAL) self.SetSizeHints(wx.DefaultSize, wx.DefaultSize) self.m_statusBar2 = self.CreateStatusBar(1, wx.STB_SIZEGRIP, wx.ID_ANY) self.m_menubar = wx.MenuBar(0) self.m_file = wx.Menu() self.m_Exit = wx.MenuItem(self.m_file, wx.ID_ANY, u"Exit", wx.EmptyString, wx.ITEM_NORMAL) self.m_file.Append(self.m_Exit) self.m_menubar.Append(self.m_file, u"File") self.SetMenuBar(self.m_menubar) gSizer1 = wx.GridSizer(0, 2, 0, 0) self.m_name = wx.StaticText(self, wx.ID_ANY, u"Name", wx.DefaultPosition, wx.DefaultSize, 0) self.m_name.Wrap(-1) gSizer1.Add(self.m_name, 0, wx.ALL, 5) self.m_textname = wx.TextCtrl(self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.DefaultSize, 0) gSizer1.Add(self.m_textname, 0, wx.ALL, 5) self.m_age = wx.StaticText(self, wx.ID_ANY, u"age", wx.DefaultPosition, wx.DefaultSize, 0) self.m_age.Wrap(-1) gSizer1.Add(self.m_age, 0, wx.ALL, 5) self.m_textage = wx.TextCtrl(self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.DefaultSize, 0) gSizer1.Add(self.m_textage, 0, wx.ALL, 5) self.m_Id = wx.StaticText(self, wx.ID_ANY, u"Id", wx.DefaultPosition, wx.DefaultSize, 0) self.m_Id.Wrap(-1) gSizer1.Add(self.m_Id, 0, wx.ALL, 5) self.m_textId = wx.TextCtrl(self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.DefaultSize, 0) gSizer1.Add(self.m_textId, 0, wx.ALL, 5) gSizer1.Add((0, 0), 1, wx.EXPAND, 5) sbSizer1 = wx.StaticBoxSizer(wx.StaticBox(self, wx.ID_ANY, wx.EmptyString), wx.HORIZONTAL) self.m_search = wx.Button(sbSizer1.GetStaticBox(), wx.ID_ANY, u"Search", wx.Point(-1, -1), wx.DefaultSize, 0) sbSizer1.Add(self.m_search, 0, wx.ALL, 5) m_choice2Choices = [u"empty "] self.m_choice2 = wx.Choice(sbSizer1.GetStaticBox(), wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize, m_choice2Choices, 0) self.m_choice2.SetSelection(0) sbSizer1.Add(self.m_choice2, 0, wx.ALL, 5) self.m_add = wx.Button(sbSizer1.GetStaticBox(), wx.ID_ANY, u"Add", wx.Point(-1, -1), wx.DefaultSize, 0) sbSizer1.Add(self.m_add, 0, wx.ALL, 5) gSizer1.Add(sbSizer1, 1, wx.ALL | wx.ALIGN_BOTTOM | wx.ALIGN_RIGHT, 5) self.SetSizer(gSizer1) self.Layout() self.Centre(wx.BOTH) # Connect Events self.Bind(wx.EVT_MENU, self.Exit, id=self.m_Exit.GetId()) self.m_search.Bind(wx.EVT_BUTTON, self.search) self.m_choice2.Bind(wx.EVT_CHOICE, self.Display) self.m_add.Bind(wx.EVT_BUTTON, self.addnew) def __del__(self): pass # Virtual event handlers, overide them in your derived class def search(self, event): inst.Presearch(self.m_textname, self.m_textage, self.m_textId, self.m_statusBar2, self.m_choice2) def addnew(self, event): inst.exporttojson(self.m_textname, self.m_textage, self.m_textId, self.m_statusBar2) def Display(self, event): inst.Postsearch(self.m_textname, self.m_textage, self.m_textId, self.m_statusBar2,self.m_choice2) def Exit(self, event): self.Close(True) # Close the frame. inst = ManageGui("data.json") app = wx.App(False) frame = Frame(None) frame.Show() app.MainLoop() </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-12T21:33:02.507", "Id": "453501", "Score": "0", "body": "Welcome to Code Review. There is *proof of correctness* (→CS), and there is *methodical testing*. Are you confident your code works as specified?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-13T10:34:02.593", "Id": "453589", "Score": "0", "body": "@greybeard I did not perform any such test. But basing on my tests I can confirm that the functional behaviour is correct. \nwhat do you mean by proof of correctness (→CS) and methodical testing?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-13T10:38:19.760", "Id": "453591", "Score": "2", "body": "Welcome to Coe Review! I have rolled back your last 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": "<p>Ways of improving:</p>\n\n<p><strong><em>Naming issues</em></strong></p>\n\n<p>A lot of Python naming conventions violations. A <em>proper</em> names should be given to identifiers and functions/methods. <br>Some of those are:\n<code>Presearch</code> --> <code>pre_search</code>, <code>Postsearch</code> --> <code>post_search</code>, <code>isempty</code> --> <code>is_empty</code>, <code>exporttojson</code> --> <code>export_tojson</code> etc.<br></p>\n\n<p>As for <code>Id = arg[2]</code>: the intention of preventing shadowing the reserved <code>id</code> function is understood, but <code>Id</code> is not an option. Adding a trailing underscore for such kind of variable would be acceptable - <code>id_ = arg[2]</code>.</p>\n\n<p>Even if you decided to extend a third-party <code>wx.Frame</code> class you should select a consistent way of naming methods in your custom <code>Frame</code> class to <strong>not</strong> mix method naming style as <code>def search ...</code>, <code>def Display</code>, <code>def addnew</code> and so on.</p>\n\n<p><strong><em>Conditions</em></strong></p>\n\n<ul>\n<li><p><code>is_empty</code> function.<br>\nThe condition <code>os.stat(self.jsonfile).st_size == 0</code> is the same as <code>os.stat(self.jsonfile).st_size</code> (file size can not be less than <code>0</code>)</p></li>\n<li><p><code>export_tojson</code> function. The condition:</p>\n\n<pre><code>if name.GetValue() != '' and age.GetValue() != '' and Id.GetValue() != '':\n if len(data) == 0 and name.GetValue() != '':\n</code></pre></li>\n</ul>\n\n<p>contains a redundant check <code>name.GetValue() != ''</code> (inner level) as the outer check already ensures it</p>\n\n<ul>\n<li><code>if super().is_empty() is False:</code> is a \"noisy\" version of <code>if not super().is_empty():</code> , use the 2nd explicit and short version.</li>\n</ul>\n\n<p><strong><em>Prefer Multiple Assignment Unpacking Over Indexing</em></strong><br>\nInstead of:</p>\n\n<pre><code> name = arg[0]\n age = arg[1]\n Id = arg[2]\n</code></pre>\n\n<p>we use </p>\n\n<pre><code> name, age, id_ = arg[:3]\n</code></pre>\n\n<p>Unpacking has less visual noise than accessing the tuple's indexes, and it often requires fewer lines.</p>\n\n<hr>\n\n<p>Setting values for <em>\"found\"</em> person:</p>\n\n<pre><code>arg[0].SetValue(f[\"Name\"])\narg[1].SetValue(f[\"Age\"])\narg[2].SetValue(f[\"Id\"])\n</code></pre>\n\n<p>and for <em>\"not found\"</em> person:</p>\n\n<pre><code>arg[1].SetValue(\"---\")\narg[2].SetValue(\"---\")\narg[3].SetStatusText(\"Not Found!\")\n</code></pre>\n\n<p>are repeated across <code>..._search</code> function and could potentially be extracted to separate functions. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-13T10:30:16.970", "Id": "453586", "Score": "0", "body": "I updated my post according to your valuable remarks." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-12T21:16:43.093", "Id": "232285", "ParentId": "232273", "Score": "2" } } ]
{ "AcceptedAnswerId": "232285", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-12T19:05:55.303", "Id": "232273", "Score": "2", "Tags": [ "python", "json" ], "Title": "Import/Export data from/to json using python" }
232273
<p>How would I go about checking to make sure only valid results are entered/How do I create a loop that will continue to ask one of the questions until answered correctly?</p> <pre><code>def hotel(): rooms = [0, 150, 180, 400] breakfast = [0, 20, 0] type_of_room = input('what type of room would you like?\n1: Queen ($150)\n2: King ($180)\n3: Suite ($400)\n') room = rooms[int(type_of_room)] number_of_nights = input('how many nights will you be staying?') optional_breakfast = input('would you like to include the optional breakfast?\n1: Yes\n2: No') breakfast_answer = breakfast[int(optional_breakfast)] total = 'your total bill will come to: $' result = str((int(room) * int(number_of_nights)) + int(breakfast_answer)) print(total + result) hotel() </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-12T21:40:25.563", "Id": "453503", "Score": "2", "body": "This question asks about code not yet written: [off topic](https://codereview.stackexchange.com/help/on-topic) because not ready for review as defined here." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-12T21:42:45.337", "Id": "453504", "Score": "0", "body": "@greybeard do you mean i should attempt to write the loop and then repost?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-12T21:50:09.747", "Id": "453507", "Score": "2", "body": "You should try to pin down what has to be accomplished, how to test that the code does that. You are welcome to post your code here once confident it does. Heed [How do I ask a good question?](https://codereview.stackexchange.com/help/how-to-ask) and have a look at [How to get the best value out of Code Review - Asking Questions](https://codereview.meta.stackexchange.com/q/2436)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-14T12:40:28.570", "Id": "453770", "Score": "0", "body": "Just a hint: `type_of_room = 666\n valid_inputs = [1, 2, 3]\n while type_of_room not in valid_inputs: \n type_of_room = int(input('what type of room would you like?\\n1: Queen ($150)\\n2: King ($180)\\n3: Suite ($400)\\n'))`. This is the simplest approach, Better answer [here](https://stackoverflow.com/questions/23294658/asking-the-user-for-input-until-they-give-a-valid-response)." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-12T21:30:31.350", "Id": "232288", "Score": "1", "Tags": [ "python", "python-3.x", "design-patterns" ], "Title": "Python - Checking for errors" }
232288
<p>For practice, I decided to write a <a href="https://en.wikipedia.org/wiki/Run-length_encoding" rel="nofollow noreferrer">run-length</a> decoder. For example:</p> <pre><code>basic_run_length_decode("1A2B3C") =&gt; 'ABBCCC' basic_run_length_decode("5A10Z10J") =&gt; 'AAAAAZZZZZZZZZZJJJJJJJJJJ' </code></pre> <p>It ended up getting long, but that's mostly because I wanted try incorporating the <a href="https://clojuredocs.org/clojure.core/partition-by" rel="nofollow noreferrer"><code>partition-by</code></a> function from Clojure. It seemed like it would work nicely here, and it did. It required me to write that function though since Python doesn't seem to have anything equivalent. I also "stole" <code>grouper</code> from the <a href="https://docs.python.org/3.8/library/itertools.html#itertools-recipes" rel="nofollow noreferrer">"recipe"</a> section of the <code>itertools</code> docs. Clojure has both of these functions as part of its standard library, so that's what I thought of while writing this. </p> <p>Basically, it works by cutting the string into groups of digits and non-digits, pairing them into <code>[digits, word]</code> pairs, then parsing the digits and doing some string multiplication.</p> <p>What I'd like commented on mainly:</p> <ul> <li><p><code>partition_by</code>. I tried to see if there was a sane way of using something like <code>takewhile</code> + <code>drop_while</code>, but both of those functions consume an extra element after the predicate flips, which caused problems. I opted to just do manual iteration, but it's quite verbose.</p></li> <li><p>Anything else that I may be doing the hard way.</p></li> </ul> <p>Note, it actually allows for multiple characters per number.</p> <pre><code>basic_run_length_decode("10AB10CD") =&gt; 'ABABABABABABABABABABCDCDCDCDCDCDCDCDCDCD' </code></pre> <p>I thought about raising an error, but decided to just allow it. This is apparently a type of possible encoding, and it cost me nothing to allow it.</p> <pre><code>from itertools import zip_longest from typing import Callable, Any, Iterable, TypeVar, Generator, List T = TypeVar("T") # Emulating https://clojuredocs.org/clojure.core/partition-by def _partition_by(f: Callable[[T], Any], iterable: Iterable[T]) -&gt; Generator[List[T], None, None]: """Splits off a new chunk everytime f returns a new value. list(partition_by(lambda n: n &lt; 5, [1, 2, 3, 6, 3, 2, 1])) =&gt; [[1, 2, 3], [6], [3, 2, 1]] """ last_value = object() # Dummy object that will never be equal to anything else chunk = [] for x in iterable: returned = f(x) if returned == last_value: chunk.append(x) else: if chunk: yield chunk chunk = [x] last_value = returned if chunk: yield chunk # Recipe from https://docs.python.org/3.8/library/itertools.html#itertools.takewhile def _grouper(iterable, n, fillvalue=None): """Collect data into fixed-length chunks or blocks""" args = [iter(iterable)] * n return zip_longest(*args, fillvalue=fillvalue) def _invalid_encoded_error(message: str) -&gt; ValueError: return ValueError(f"Invalid encoded string. {message}") def basic_run_length_decode(encoded_string: str) -&gt; str: """Decodes a string in the form of &lt;number&gt;&lt;chars&gt;&lt;number&gt;&lt;chars&gt;. . . basic_run_length_decode("1A2B3C") =&gt; 'ABBCCC'""" if encoded_string and not encoded_string[0].isdigit(): raise _invalid_encoded_error("First character must be a number.") chunks = _partition_by(lambda c: c.isdigit(), encoded_string) acc = [] for raw_n, raw_word in _grouper(chunks, 2): if not raw_word: raise _invalid_encoded_error("Trailing numbers without character at end of encoded string.") n = int("".join(raw_n)) # Should never throw as long as the very first char is a digit? word = "".join(raw_word) acc.append(n * word) return "".join(acc) </code></pre>
[]
[ { "body": "<p>The code looks good to me, it is well documented and I do not have much to say.</p>\n\n<p><strong>Suggestion for <code>_partition_by</code></strong></p>\n\n<p>In:</p>\n\n<pre><code> if returned == last_value:\n chunk.append(x)\n else:\n if chunk:\n yield chunk\n chunk = [x]\n</code></pre>\n\n<p>I'd tried to write <code>chunk = [x]</code> as <code>chunk = [] ; chunk.append(x)</code>. This allows some rewriting as you can extract the common line out of the <code>if / else</code>.</p>\n\n<pre><code> if returned == last_value:\n pass\n else:\n if chunk:\n yield chunk\n chunk = []\n chunk.append(x)\n</code></pre>\n\n<p>Then revert condition</p>\n\n<pre><code> if returned != last_value:\n if chunk:\n yield chunk\n chunk = []\n chunk.append(x)\n</code></pre>\n\n<p>Then group condition as there is nothing to do when <code>chunk</code> is already empty.</p>\n\n<pre><code> if chunk and returned != last_value:\n yield chunk\n chunk = []\n chunk.append(x)\n</code></pre>\n\n<p>There is nothing wrong with the way things were done, this is a pure personal preference.</p>\n\n<p><strong>Details about docstring</strong></p>\n\n<p>The docstrings are slightly inconsistent as we have two different forms for the verb: with and without the final 's'. If that can be of any help, there are Docstring conventions for Python in <a href=\"https://www.python.org/dev/peps/pep-0257/\" rel=\"noreferrer\">PEP 257</a>.</p>\n\n<p>It suggests:</p>\n\n<blockquote>\n <p>The docstring is a phrase ending in a period. It prescribes the\n function or method's effect as a command (\"Do this\", \"Return that\"),\n not as a description; e.g. don't write \"Returns the pathname ...\".</p>\n</blockquote>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-13T06:08:16.160", "Id": "232296", "ParentId": "232290", "Score": "5" } }, { "body": "<p>Short and flexible substitution for initial <strong><code>_partition_by</code></strong> function by using <a href=\"https://docs.python.org/3/library/itertools.html#itertools.groupby\" rel=\"nofollow noreferrer\"><code>itertools.groupby</code></a> <em>magic</em> (to generate/split a consecutive groups by <em>predicate</em>):</p>\n\n<pre><code>from typing import Callable, Any, Iterable, TypeVar, Generator, List\nfrom itertools import groupby\n\nT = TypeVar(\"T\")\n\ndef _partition_by(f: Callable[[T], Any], iterable: Iterable[T]) -&gt; Generator[List[T], None, None]:\n \"\"\"Splits to consecutive chunks by predicate.\n list(partition_by(lambda n: n &lt; 5, [1, 2, 3, 6, 3, 2, 1])) =&gt; [[1, 2, 3], [6], [3, 2, 1]]\n \"\"\"\n for k, group in groupby(iterable, key=f):\n yield list(group)\n</code></pre>\n\n<p><em>Use case:</em></p>\n\n<pre><code>lst = [1, 2, 3, 6, 3, 2, 1]\nprint(list(_partition_by(lambda n: n &lt; 5, lst)))\n</code></pre>\n\n<p><em>The output:</em></p>\n\n<pre><code>[[1, 2, 3], [6], [3, 2, 1]]\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-13T16:52:47.580", "Id": "453645", "Score": "0", "body": "Thanks. I thought I tried `groupby` and it didn't do what I wanted. I think I misinterpreted it as returning a map instead of a list of pairs. Ya, looking at it now, it's basically `partition_by`." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-13T07:02:21.030", "Id": "232301", "ParentId": "232290", "Score": "2" } }, { "body": "<h2>Type Hint</h2>\n\n<p>The return type <code>-&gt; Generator[List[T], None, None]</code> is correct, but it is a little verbose. The <a href=\"https://docs.python.org/3/library/typing.html?highlight=generator#typing.Generator\" rel=\"nofollow noreferrer\">documentation</a> suggests a simpler way of documenting generators that just yield values, using <code>Iterator[]</code></p>\n\n<pre><code>def _partition_by(...) -&gt; Iterator[List[T]]:\n</code></pre>\n\n<p>The method <code>_grouper()</code> doesn't have a return type hint.</p>\n\n<h2>The Hard Way</h2>\n\n<blockquote>\n <ul>\n <li>Anything else that I may be doing the hard way.</li>\n </ul>\n</blockquote>\n\n<p>Well, you are doing the whole thing The Hard Way™.</p>\n\n<p>You are looking for occurrences of <code>&lt;number&gt;&lt;chars&gt;</code> in a string. This sounds like a job for the <a href=\"https://docs.python.org/3/library/re.html\" rel=\"nofollow noreferrer\"><code>regular expression module</code></a>. The <code>&lt;number&gt;</code> pattern is simply <code>(\\d+)</code>, and the <code>&lt;chars&gt;</code> pattern would be characters which are not numbers, which can be expressed concisely as <code>(\\D+)</code> ... using a capital letter indicates it is matching not-digit characters.</p>\n\n<p>Since you wish to find successive occurrences of these, you would want to use <a href=\"https://docs.python.org/3/library/re.html#re.findall\" rel=\"nofollow noreferrer\"><code>re.findall</code></a>, or perhaps <a href=\"https://docs.python.org/3/library/re.html#re.finditer\" rel=\"nofollow noreferrer\"><code>re.finditer</code></a>:</p>\n\n<pre><code>for m in re.finditer(r\"(\\d+)(\\D+)\", encoded_str)\n</code></pre>\n\n<p>Now, <code>m.group(1)</code> is the string containing <code>&lt;number&gt;</code> characters and <code>m.group(2)</code> is the string containing the <code>&lt;chars&gt;</code> character. At this point, we can turn the digits into an integer, multiply the character string by that value, and join successive values together into one large string:</p>\n\n<pre><code>def basic_run_length_decode(encoded_string: str) -&gt; str:\n \"\"\"\n Decodes a string in the form of &lt;number&gt;&lt;chars&gt;&lt;number&gt;&lt;chars&gt;. . .\n\n &gt;&gt;&gt; basic_run_length_decode(\"1A2B3C\")\n 'ABBCCC'\n &gt;&gt;&gt; basic_run_length_decode(\"10AB10CD\")\n 'ABABABABABABABABABABCDCDCDCDCDCDCDCDCDCD'\n \"\"\"\n\n return \"\".join(m.group(2) * int(m.group(1))\n for m in re.finditer(r\"(\\d+)(\\D+)\", encoded_string))\n</code></pre>\n\n<p>Yup. Your function can be simplified to one line of code, with no helper functions. Re-adding error checking left as exercise. ;-)</p>\n\n<h2>Doctest</h2>\n\n<p>I've changed the format of your <code>\"\"\"docstring\"\"\"</code> slightly.</p>\n\n<p>Instead of writing:</p>\n\n<pre><code> basic_run_length_decode(\"1A2B3C\") =&gt; 'ABBCCC'\n</code></pre>\n\n<p>which implies to the reader that when you execute <code>basic_run_length_decode(\"1A2B3C\")</code>, it will return the value <code>'ABBCCC'</code>, I've replaced this with:</p>\n\n<pre><code> &gt;&gt;&gt; basic_run_length_decode(\"1A2B3C\")\n 'ABBCCC'\n</code></pre>\n\n<p>which implies if you are at Python's REPL, and you type <code>basic_run_length_decode(\"1A2B3C\")</code>, it will return the value <code>'ABBCCC'</code>, the representation of (ie, with quotes) which will be printed by the REPL.</p>\n\n<p>Basically, exactly the same thing.</p>\n\n<p>Except ... </p>\n\n<p>The <a href=\"https://docs.python.org/3.8/library/doctest.html\" rel=\"nofollow noreferrer\"><code>doctest</code></a> module knows how to read docstrings for functions, and extract things that look like Python REPL commands (ie, appear after a <code>&gt;&gt;&gt;</code> prompt), and will execute those commands and compare the actual result with the indicated result, and raise an error if they don't match. Built-in unit testing!</p>\n\n<p>Let's test our code!</p>\n\n<pre><code>aneufeld$ python3 -m doctest run_length_decode.py\naneufeld$\n</code></pre>\n\n<p>Well, that was anticlimactic; nothing got printed. That's a good thing. It means the tests passed. We can add a <code>-v</code> to make the output more verbose:</p>\n\n<pre><code>aneufeld$ python3 -m doctest -v run_length_decode.py \nTrying:\n basic_run_length_decode(\"1A2B3C\")\nExpecting:\n 'ABBCCC'\nok\nTrying:\n basic_run_length_decode(\"10AB10CD\")\nExpecting:\n 'ABABABABABABABABABABCDCDCDCDCDCDCDCDCDCD'\nok\n1 items had no tests:\n run_length_decode\n1 items passed all tests:\n 2 tests in run_length_decode.basic_run_length_decode\n2 tests in 2 items.\n2 passed and 0 failed.\nTest passed.\naneufeld$ \n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-13T16:44:43.750", "Id": "453641", "Score": "0", "body": "Thanks. Honestly, I never learned regex . I've tried several times, and I always just ended up frustrated. I can see how terse they can allow code to be though." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-13T16:49:39.860", "Id": "453644", "Score": "1", "body": "Funny. I often find myself wanting to say the same thing about lambda functions, closures, and functional programming. I can see how they can allow non-string processing code to be be terse. " } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-13T16:35:46.077", "Id": "232336", "ParentId": "232290", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-13T01:01:05.843", "Id": "232290", "Score": "5", "Tags": [ "python", "python-3.x" ], "Title": "Simple run-length encoding decoder" }
232290
<p>When working with geometric objects I like working with the shapely module (<a href="https://pypi.org/project/Shapely/" rel="nofollow noreferrer">Shapely - PyPI</a>). In here it is easy to create polygons and define union, intersection and differences. Like so:</p> <pre><code>from shapely.geometry import Polygon x1 = [3, 3, 6, 6, 3] y1 = [4, 8, 8, 4, 4] x2 = [1, 8, 8, 1, 1] y2 = [1, 1, 6, 6, 1] rectangle_1 = Polygon([*zip(x1, y1)]) rectangle_2 = Polygon([*zip(x2, y2)]) intersection = rectangle_1.intersection(rectangle_2) union = rectangle_1.union(rectangle_2) difference_1_2 = rectangle_1.difference(rectangle_2) difference_2_1 = rectangle_2.difference(rectangle_1) </code></pre> <p>However, when plotting this polygons in Matplotlib I could not find a direct method where I can plot the exterior and interior paths that can exist in shapely Polygons. In particular being able to plot 'holes' in a bigger polygon created by differences of smaller polygons fully embedded in the bigger one.</p> <p><a href="https://i.stack.imgur.com/B8H0j.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/B8H0j.png" alt="enter image description here"></a> </p> <p>I came up with the following solution whereby the exterior and interior paths of the polygon are drawn using the the mpl Path module and convert this to a patch. </p> <pre><code>import matplotlib.pyplot as plt from matplotlib.path import Path from matplotlib.patches import PathPatch from shapely.geometry import Polygon class PatchPolygon: def __init__(self, polygon, **kwargs): polygon_path = self.pathify(polygon) self._patch = PathPatch(polygon_path, **kwargs) @property def patch(self): return self._patch @staticmethod def pathify(polygon): ''' Convert coordinates to path vertices. Objects produced by Shapely's analytic methods have the proper coordinate order, no need to sort. The codes will be all "LINETO" commands, except for "MOVETO"s at the beginning of each subpath ''' vertices = list(polygon.exterior.coords) codes = [Path.MOVETO if i == 0 else Path.LINETO for i in range(len(polygon.exterior.coords))] for interior in polygon.interiors: vertices += list(interior.coords) codes += [Path.MOVETO if i == 0 else Path.LINETO for i in range(len(interior.coords))] return Path(vertices, codes) x1 = [3, 6, 6, 3] y1 = [2, 2, 4, 4] x2 = [1, 1, 2, 2] y2 = [1, 2, 2, 1] x3 = [0, 9, 9, 0] y3 = [0, 0, 6, 6] fig, ax1 = plt.subplots(figsize=(6, 4)) ax1.set_xlim(-1, 10) ax1.set_ylim(-1, 10) rectangle_1 = Polygon([*zip(x1, y1)]) rectangle_2 = Polygon([*zip(x2, y2)]) rectangle_3 = Polygon([*zip(x3, y3)]) difference = rectangle_3.difference(rectangle_2).difference(rectangle_1) ax1.add_patch(PatchPolygon(difference, facecolor='blue', edgecolor='red').patch) plt.show() </code></pre> <p>Credit goes to Sean Gillies (<a href="https://sgillies.net/2010/04/06/painting-punctured-polygons-with-matplotlib.html" rel="nofollow noreferrer">painting-punctured-polygons-with-matplotlib</a>) who inspired me to the solution. However we are now almost 10 years further, so wondered if there is a better way!</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-13T10:55:06.753", "Id": "453599", "Score": "0", "body": "Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*." } ]
[ { "body": "<p>Unfortunately I don't know of a better way (but have also not looked into one, tbh). Here are some comments on your <code>pathify</code> method instead.</p>\n\n<p>You are currently checking <code>if i == 0</code> on every loop iteration, but it is true only once at the beginning. Just special case that one out and do</p>\n\n<pre><code>codes = [Path.MOVETO]\ncodes += [Path.LINETO for _ in range(1, len(polygon.exterior.coords))]\n</code></pre>\n\n<p>Even better, lists can be multiplied. Since <code>Path.LINETO</code> seems to be a constant, you can just do</p>\n\n<pre><code>codes = [Path.MOVETO] + [Path.LINETO] * (len(polygon.exterior.coords) - 1)\n</code></pre>\n\n<p>For the <code>vertices</code> I would use <a href=\"https://docs.python.org/3/library/stdtypes.html#mutable-sequence-types\" rel=\"nofollow noreferrer\"><code>list.extend</code></a> instead of list addition. This way you don't need to cast it to a list yourself but can let <code>extend</code> handle it. It might even be implemented in such a way that it just consumes an iterable. CPython actually does this, but it guesses the size by which the original list needs to be extended by asking the iterable object. If the object does not return a guess, it uses <code>8</code> instead (which might not be the most efficient for e.g. a long generator).</p>\n\n<pre><code>for interior in polygon.interiors:\n vertices.extend(interior.coords)\n codes.extend([Path.MOVETO] + [Path.LINETO] * (len(interior.coords) - 1))\n</code></pre>\n\n<p>At this point it might make sense to put generating the commands into a function, since we already had to use it twice:</p>\n\n<pre><code>@staticmethod\ndef generate_codes(n):\n \"\"\" The first command needs to be a \"MOVETO\" command,\n all following commands are \"LINETO\" commands.\n \"\"\"\n return [Path.MOVETO] + [Path.LINETO] * (n - 1)\n\n@staticmethod\ndef pathify(polygon):\n ''' Convert coordinates to path vertices. Objects produced by Shapely's\n analytic methods have the proper coordinate order, no need to sort.\n\n The codes will be all \"LINETO\" commands, except for \"MOVETO\"s at the\n beginning of each subpath\n '''\n vertices = list(polygon.exterior.coords)\n codes = self.generate_codes(len(polygon.exterior.coords))\n\n for interior in polygon.interiors:\n vertices.extend(interior.coords)\n codes.extend(self.generate_codes(len(interior.coords)))\n\n return Path(vertices, codes)\n</code></pre>\n\n<p>You should also probably put your calling code under a <a href=\"http://stackoverflow.com/questions/419163/what-does-if-name-main-do\"><code>if __name__ == \"__main__\":</code> guard</a> to allow importing from this module without running the example code.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-13T09:43:05.967", "Id": "453580", "Score": "0", "body": "Thanks for the suggestions. I will have a look at extend that I had forgotten about! you are right on the if __name__ == '__main__' guard which I will edit in the text as it is a bit of a distraction from the real issue." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-13T10:01:33.807", "Id": "453583", "Score": "2", "body": "@BrunoVermeulen: Please don't edit your code after having received an answer, it would invalidate it! [Have a look at what you are allowed and not allowed to do after you have received an answer](https://codereview.stackexchange.com/help/someone-answers). I rolled back your edit. In any case, since I mentioned it, any other reviewers might just ignore it, or put it in anyway (in which case you can just ignore it)." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-13T08:47:35.683", "Id": "232309", "ParentId": "232294", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-13T05:14:34.920", "Id": "232294", "Score": "5", "Tags": [ "python", "matplotlib" ], "Title": "Plotting shapely polygon in matplotlib" }
232294
<p>I created this program some time ago. It shows you how to solve <a href="https://en.wikipedia.org/wiki/Tower_of_Hanoi" rel="nofollow noreferrer">tower of hanoi</a> for <code>n</code> disks, step by step.</p> <p>Here's the code:</p> <pre class="lang-py prettyprint-override"><code>from os import system from colorama import Fore, Style clear = lambda: system('cls') class TowerOfHanoi: def __init__(self, n, r1, r2, r3): self.n = n self.r1 = r1 self.r2 = r2 self.r3 = r3 clear() print('Initial: ') self.parser(a, b, c) input('\nEnter To Continue...') self.solve() def parser(self, a1, b1, c1): x, y, z = [], [], [] a1, b1, c1 = [0] * (self.n - len(a1)) + a1, \ [0] * (self.n - len(b1)) + b1, \ [0] * (self.n - len(c1)) + c1 m = self.n for i in a1: s = ' ' * (m - i + 1) h = Fore.RED + s + '██' * i + s + Style.RESET_ALL x.append(h) for i in b1: s = ' ' * (m - i + 1) h = Fore.RED + s + '██' * i + s + Style.RESET_ALL y.append(h) for i in c1: s = ' ' * (m - i + 1) h = Fore.RED + s + '██' * i + s + Style.RESET_ALL z.append(h) print(' ' * self.n + str(self.r1) + ' ' * (self.n * 2 + 1) + str(self.r2) + ' ' * (self.n * 2 + 1) + str(self.r3)) print() print('\n'.join(i + ' ' * (self.n - len(i)) + j + ' ' * (self.n - len(j)) + k for i, j, k in zip(x, y, z))) print() def solve(self, n = None, r1 = None, r2 = None, r3 = None, x = 0, y = 1, z = 2): if n is None: n = self.n if r1 is None: r1 = self.r1 if r2 is None: r2 = self.r2 if r3 is None: r3 = self.r3 if n == 1: clear() print("Move disk 1 from rod", r1, "to rod", r2) print() [a, b, c][y].insert\ (0, [a, b, c][x].pop(0)) self.parser(a, b, c) return self.solve(n - 1, r1, r3, r2, x, z, y) input('\nEnter To Continue...') clear() print("Move disk", n, "From Rod", r1, "To Rod", r2) print() [a, b, c][y].insert\ (0, [a, b, c][x].pop(0)) self.parser(a, b, c) input('\nEnter To Continue...') print() self.solve(n - 1, r3, r2, r1, z, y, x) print('Welcome to Tower of Hanoi!') print('You have some number of rings of increasing length') print('Like this:') print() print(Fore.RED + ' ██ ' + Style.RESET_ALL) print(Fore.RED + ' ████ ' + Style.RESET_ALL) print(Fore.RED + '██████' + Style.RESET_ALL) print() print('The rules are simple: ') print(' * You can move a disk from a rod to another rod') print(' if the current disk is smaller than the topmost disk in the rod you are moving') print() print(' * The goal is to move all disks from rod 1 to rod 2') print() print('This program shows you how to move the disks from rod 1 to rod 2') print() while True: input('Press enter to start!') print() n1 = int(input('Enter number of rings: ')) a = [i for i in range(1, n1 + 1)] b = [] c = [] toh = TowerOfHanoi(n1, 1, 2, 3) print() play_again = input('Do you want to play again? &lt;Y&gt;es or &lt;N&gt;o').lower() while play_again != 'y' or play_again != 'n': play_again = input('Do you want to play again? &lt;Y&gt;es or &lt;N&gt;o').lower() if play_again == 'n': print('Bye!') break </code></pre> <p>This code seems a bit lengthy, as well as ugly. How do I improve it? </p> <p>Any tips are welcome!</p>
[]
[ { "body": "<h2>Bugs</h2>\n\n<h3>Colorama Not Initialized</h3>\n\n<p>Colorama should be initialized, to ensure proper operation:</p>\n\n<pre><code>import colorama\n\ncolorama.init()\n</code></pre>\n\n<h3>Clear Screen</h3>\n\n<blockquote>\n <p>sh: cls: command not found</p>\n</blockquote>\n\n<p>On non-Windows machines, <code>cls</code> is not defined</p>\n\n<p>Instead, simply use colorama to clear the screen.</p>\n\n<pre><code>def clear():\n print(colorama.ansi.clear_screen())\n</code></pre>\n\n<h3>Play again</h3>\n\n<pre><code>Do you want to play again? &lt;Y&gt;es or &lt;N&gt;oY \nDo you want to play again? &lt;Y&gt;es or &lt;N&gt;oN \nDo you want to play again? &lt;Y&gt;es or &lt;N&gt;oy \nDo you want to play again? &lt;Y&gt;es or &lt;N&gt;on \nDo you want to play again? &lt;Y&gt;es or &lt;N&gt;o \n</code></pre>\n\n<p>No answer seems to provide the expected behaviour, due to:</p>\n\n<pre><code>while play_again != 'y' or play_again != 'n':\n</code></pre>\n\n<p>always being <code>True</code>. You need the <code>and</code> conjunction, not <code>or</code>.</p>\n\n<hr>\n\n<h2>Unused variables</h2>\n\n<pre><code>toh = TowerOfHanoi(n1, 1, 2, 3)\n</code></pre>\n\n<p><code>toh</code> is never used after this point. So, why store it in a variable?</p>\n\n<hr>\n\n<h2>Global variables</h2>\n\n<pre><code>a = [i for i in range(1, n1 + 1)]\nb = []\nc = []\n\ntoh = TowerOfHanoi(n1, 1, 2, 3)\n</code></pre>\n\n<p><code>a</code>, <code>b</code>, and <code>c</code> are used inside the <code>TowerOfHanoi</code> class, but are not passed to the class. Instead they are globals variables that must be properly initialized corresponding to the value <code>n1</code> passed to the <code>TowerOfHanoi</code> constructor.</p>\n\n<p>These lists should be created by the class itself, based on the argument passed to the constructor. Moreover, they should be members of the class, not globals.</p>\n\n<hr>\n\n<h2>Code Duplication</h2>\n\n<p>This code:</p>\n\n<pre><code> for i in a1:\n s = ' ' * (m - i + 1)\n h = Fore.RED + s + '██' * i + s + Style.RESET_ALL\n\n x.append(h)\n</code></pre>\n\n<p>is replicated 3 times, with <code>a1</code> changing to <code>b1</code> and <code>c1</code>, and <code>x</code> changing to <code>y</code> and <code>z</code>. Perhaps you could refactor this into its own function, taking the rod list as input, and generating &amp; returning the lists internally?</p>\n\n<pre><code> def rod_images(self, rod):\n # Fill rod with required 0's at top\n rod = [0] * (self.n - len(rod)) + rod\n\n image_rows = []\n for i in rod:\n spaces = ' ' * (self.n - i + 1)\n row = Fore.RED + spaces + '██' * i + spaces + Style.RESET_ALL\n image_rows.append(row)\n\n return image_rows\n</code></pre>\n\n<p>Then you could simply write:</p>\n\n<pre><code> def parser(self, a1, b1, c1):\n\n x = self.rod_images(a1)\n y = self.rod_images(b1)\n z = self.rod_images(c1)\n\n # ... etc ...\n</code></pre>\n\n<hr>\n\n<h2>Zero, One &amp; Many</h2>\n\n<p>In programming, there are 3 important numbers: zero, one, and many. How many rods do you have? More than one, so ... you have many rods. Many items are stored in containers, such as lists, not individual variables. So instead of this:</p>\n\n<pre><code> self.r1 = r1\n self.r2 = r2\n self.r3 = r3\n</code></pre>\n\n<p>write something like:</p>\n\n<pre><code> self.rods = [r1, r2, r3]\n</code></pre>\n\n<p>Then, instead of</p>\n\n<pre><code> print(' ' * self.n + str(self.r1)\n + ' ' * (self.n * 2 + 1) + str(self.r2)\n + ' ' * (self.n * 2 + 1) + str(self.r3))\n</code></pre>\n\n<p>you can take advantage of the fact that you are doing something with each item in the list, in order. In this case, you are converting each item to a string, and then joining them together with a bunch of spaces in-between:</p>\n\n<pre><code> print(' ' * self.n\n + (' ' * (self.n * 2 + 1)).join(str(rod) for rod in self.rods)\n</code></pre>\n\n<p>But ... that still looks ugly. What you are really doing is printing out 3 values, each centred in a <code>n * 2 + 2</code> character wide field:</p>\n\n<pre><code> width = self.n * 2 + 2\n print((f\"{{:^{width}}}\"*3).format(*self.rods))\n</code></pre>\n\n<p>With 3 disks, this creates the format string <code>\"{:^8}{:^8}{:^8}\"</code> which centres the 3 values each in 8 character wide fields.</p>\n\n<p>A similar method could be used to centre the discs when printing, as long as the colour/style codes are removed from the disc \"values\" and moved to the format string itself, so they don't mess up the character counts for automatic centring.</p>\n\n<h2>Unnecessary Default Arguments</h2>\n\n<p>Calling <code>solve()</code>, with no arguments, is only done from <code>__init__()</code>. So the only time the default arguments are used is that one call. So why complicate the method with default arguments which must be set via a number of <code>if _ is None:</code> tests? Simply use:</p>\n\n<pre><code>self.solve(self.n, self.r1, self.r2, self.r3, 0, 1, 2)\n</code></pre>\n\n<p>in the <code>__init__()</code> method, and remove the default arguments and default argument substitution code.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-14T03:23:49.440", "Id": "453704", "Score": "0", "body": "Can you please explain why `colorama.init()` have to be used? I was using them for some time, but then realized it works without `colorama.init()` as well." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-14T18:24:44.377", "Id": "453829", "Score": "0", "body": "From the [documentation](https://pypi.org/project/colorama/), \"_On Windows, calling init() will filter ANSI escape sequences out of any text sent to stdout or stderr, and replace them with equivalent Win32 calls._\" Based on your `system('cls')` function, I expect you are on Windows. Perhaps you're running in a Windows terminal window that supports ANSI escape sequences already. If you share your script with others, and they run it in a different environment, it may stop working if `colorama.init()` is not called. It is never wrong to call the initialization code, even if it becomes a no-op." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-13T19:07:08.890", "Id": "232345", "ParentId": "232295", "Score": "2" } } ]
{ "AcceptedAnswerId": "232345", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-13T05:55:57.030", "Id": "232295", "Score": "2", "Tags": [ "python", "python-3.x", "tower-of-hanoi" ], "Title": "Interactive Tower of Hanoi" }
232295
<p><strong>Summary</strong></p> <p>I made a hangman game using python but I had trouble writing clean pythonic code</p> <p><strong>Questions</strong></p> <ol> <li><p>In the code snippet I provided (Full code in the link below) I used global for: loop and points variables, I know it is bad practice to use the global. What are some ways I can prevent myself from using the global statement</p></li> <li><p>How would you rewrite this code using OOP or functions?</p></li> <li><p>I think I am developing some bad habits because of my game_loop function, a majority of the functions are calling another function but I feel like this code could be so much better. So what would you do differently in the game_loop function</p></li> <li><p>Are you seeing any bad practices in this code?(Not including the global statement)</p></li> </ol> <p><strong>Code</strong> </p> <pre><code>import copy stick_man = [ ''' ________ | | | | | |__________ ''', ''' ________ | | | O | | |__________ ''', ''' ________ | | | O | | | |__________ ''', ''' ________ | | | O | |\\ | |__________ ''', ''' ________ | | | O | /|\\ | |__________ ''', ''' ________ | | | O | /|\\ | / |__________ ''', ''' ________ | | | O | /|\\ | / \\ |__________ '''] word = 'hangman' characters = list(word) wrong_letters = [] loop = True points = 0 def hide_word(): """Loops through the character list and replaces each letter with an * """ copied_word = copy.copy(characters) for index, letter in enumerate(copied_word): copied_word[index] = '*' return copied_word hidden_characters = hide_word() guess_word = [characters, hidden_characters] # [ ['h', 'a', 'n', 'g', 'm', 'a', 'n'], ['*', '*', '*', '*', '*', '*', '*'] ] def get_letter_matches(player_answer): """ Check if player input matches any of letters in the given word and returns the position and duplicates of that letter """ word = guess_word[0] # ['h', 'a', 'n', 'g', 'm', 'a', 'n'] indexes = [index for index in range(len(word)) if word[index] == player_answer] # Don't know exactly what this code does letter_indexes = { player_answer: indexes } return letter_indexes # {'a': [1, 5]} def reveal_letters(dict, player_answer): """ Takes the player input and if the letter matches the word then it will unhide the letter in the guess_word list """ hidden_word = guess_word[1] for index in dict[player_answer]: hidden_word[index] = player_answer return ''.join(hidden_word) # dict[player_answer] -&gt; [1, 5] def print_stick_board(number): """Print the right stick man board""" length = len(number) print(stick_man[length]) def get_incorrect_letters(player_answer): """Tally up all the incorrect words""" word = guess_word[0] if player_answer not in word: wrong_letters.append(player_answer) return wrong_letters def get_point(letter): """Give player 100 points for getting the correct letter""" global points if letter in characters: points += 100 print('Points earned: {}'.format(points)) else: print('Points earned: {}'.format(points)) def is_winner(complete_word, secret_word): """Determine the winner and loser""" global loop if secret_word == complete_word: print('You Won!') loop = False def game_loop(): while loop: print('__________________________________________________') player_letter = input('Choose a letter: ') hidden = reveal_letters( get_letter_matches( player_letter ), player_letter ) incorrect_letters = get_incorrect_letters( player_letter ) print('Your word looks like this:\n{}'.format( hidden )) try: print_stick_board( incorrect_letters ) except IndexError: print('You Lost!') break get_point(player_letter) print('You\'ve entered (wrong): {}'.format( incorrect_letters )) is_winner(''.join(guess_word[0]), hidden) game_loop() </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-15T18:30:02.543", "Id": "453966", "Score": "0", "body": "I updated the code!" } ]
[ { "body": "<p>Here on Code Review, we tend to not look at off-site code. So I'll be reviewing the functions I see, and this'll become a partial answer once you paste all your code.</p>\n\n<h3>Globals</h3>\n\n<p>Generally, the way to avoid them is to simply take more arguments to your function. Any function of the form:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def get_point(letter):\n \"\"\"Give player 100 points for getting the correct letter\"\"\"\n global points\n # Stuff happens...\n</code></pre>\n\n<p>can be refactored as:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def get_point(letter, points):\n \"\"\"Give player 100 points for getting the correct letter\"\"\"\n # Stuff happens...\n</code></pre>\n\n<p>However, that's not the only global you're using. The other one is shown here:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code> if letter in characters:\n</code></pre>\n\n<p>Characters is not found in the local scope, so it's a global. Judging by the name, it's probably a constant, and global constants can be perfectly fine. However, in python we tend to mark them by naming convention with ALL_CAPS_AND_SOMETIMES_UNDERSCORES. So that should be:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code> if letter in CHARACTERS:\n</code></pre>\n\n<p>with of course the global constant renamed appropriately as well.</p>\n\n<p>You'll also need to return the points value, as you want to mutate it. More on this in a sec.</p>\n\n<h3>Code Duplication</h3>\n\n<p>Is generally a bad thing. You're doing:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code> if letter in CHARACTERS:\n points += 100\n print('Points earned: {}'.format(points))\n else:\n print('Points earned: {}'.format(points))\n</code></pre>\n\n<p>Where you probably should be doing:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code> if letter in CHARACTERS:\n points += 100\n print(f'Points total: {points}') # &lt;-- Python 3.6+\n return points\n</code></pre>\n\n<p>I've also included an f-string, usable from python 3.6 onwards. They're awesome. It's basically the same as <code>str.format(stuff)</code>, but it's shorter and more readable.</p>\n\n<p>I've also clarified your message. It's not the amount of points earned, it's total points. You should also return the points value, so you can use it further. So you can now use the function from the outside like this:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>points = get_point(letter, points)\n</code></pre>\n\n<p>And you'll update the point value outside of your function.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-13T16:17:35.890", "Id": "453638", "Score": "0", "body": "If you know the question is off-topic, can you please refrain from answering it till it fits the scope of the site? Thank you." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-13T09:53:30.537", "Id": "232310", "ParentId": "232298", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-13T06:45:13.493", "Id": "232298", "Score": "1", "Tags": [ "python", "python-3.x", "game", "hangman" ], "Title": "Hangman Game using python3" }
232298
<p>I am new to Scala.</p> <p>I have been trying to complete an exercise where the ask was as follows:</p> <p>// Write a function isPerfectNumber which takes integer input and returns String output.</p> <p>// It finds if a number is perfect, and returns true if perfect, else returns false</p> <p>// Write a higher order function myHigherOrderFunction which takes isPerfectNumber and intList as input, and returns a List of Strings which contain the output if the number is perfect or not using map.</p> <p>Perfect Number :</p> <p><a href="https://rosettacode.org/wiki/Perfect_numbers#Scala" rel="nofollow noreferrer">https://rosettacode.org/wiki/Perfect_numbers#Scala</a></p> <p>My Code :</p> <pre><code>object ListMapHigherOrder{ def main(args:Array[String]) { val intRes = args.toList val intList: List[Int] = intRes.map(_.toInt).toList def isPerfectNumber(input: Int) :String = { var check_sum = ( (2 to math.sqrt(input).toInt).collect { case x if input % x == 0 =&gt; x + input / x} ).sum if ( check_sum == input - 1 ) return "true" else return "false" } def myHigherOrderFunction(argFn: Int =&gt; String, argVal:List[Int]): List[String] = { argVal.map(argFn) } println(myHigherOrderFunction(isPerfectNumber, intList)) } } </code></pre> <p>Code execution : scala ScalaExcercise12.scala 1 6 13</p> <p>Expected Output : List(false , true , false)</p> <p>the code gives expected output, am not sure how the backend testing is being done.... it just dosent pass the test.</p> <p>Is there any issue with the code? - i did like to fix it , but cant i see anything wrong/missing</p> <p>any help or direction is greatly appreciated.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-14T13:15:47.887", "Id": "457646", "Score": "0", "body": "Why on Earth does the exercise require the return type to be `String` instead of the obvious `Boolean`?" } ]
[ { "body": "<p>Here is my corrected solution.</p>\n\n<pre><code>object ListMapHigherOrder{\n def main(args:Array[String]) = {\n\n val intList: List[Int] = args.map(_.toInt).toList\n\n def isPerfectNumber(input: Int) :String = {\n val check_sum = ( (2 until input).collect { case x if input % x == 0 =&gt; x } ).sum\n if (input &lt;= 1) \"false\"\n else if ( check_sum == input - 1 ) \"true\"\n else \"false\"\n }\n\n def myHigherOrderFunction(argFn: Int =&gt; String, argVal:List[Int]): List[String] = { argVal.map(argFn) }\n\n println(myHigherOrderFunction(isPerfectNumber, intList))\n }\n}\n</code></pre>\n\n<p>Since this is supposed to be code review, I will not mince words. Some problems I noticed with your code:</p>\n\n<p>1) Your formatting is irregular. For anyone trying to understand your code, this is a needless obstruction.</p>\n\n<p>2) You do not check if the number is negative or equal to 1. In all such cases, the number is not perfect. You need to check for these cases.</p>\n\n<p>3) You are using a var for check_sum. This is an eyesore for anyone who knows the language. Prefer immutable values.</p>\n\n<p>4) You copied and pasted your code for isPerfectNumber from someone else without understanding what it does. In this case, the code you copied and pasted is actually wrong, because it gives the wrong answer for 1. It is probably also a good idea to explicitly check if the number is negative. The original code was also relatively inefficient because of the call to square root. The change to remove square root is only a micro-optimization, but it should be faster.</p>\n\n<p>5) You are trusting that calling toInt on a String won't throw an exception. This depends on the assignment specification. If the exercise assumes you will always get well-formed input, then I suppose this is fine. But if not, you need to use a try-catch block or a Try monad. Since I am not sure if you need this stuff, I won't add it to your solution.</p>\n\n<p>6) The idiom for myHigherOrderFunction is strange. There is almost no point to passing a list and a lambda function to a function just so you can call map on it. If you need to call map, just call map. Creating a wrapper function is unnecessary and an eyesore. I understand that this is what the assignment asks you to do, probably to test your understanding of functions as values. However, it is ugly code, I cannot help but mention that this should be avoided normally.</p>\n\n<p>I think this question is rather manageable, and that if you had spent more time on it, you would have been able to get it yourself. However, I will not lecture you. The biggest mistake you made was trusting someone else's code without checking it yourself. So you should not trust me either.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-14T04:48:08.717", "Id": "453707", "Score": "0", "body": "`intRes` serves no purpose. `args.map(_.toInt).toList` also eliminates the redundant `.toList` invocation." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-14T04:52:03.783", "Id": "453708", "Score": "0", "body": "@jwvh Thank you for the correction. I have edited the answer to include your correction." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-14T13:22:48.273", "Id": "457648", "Score": "0", "body": "Regarding item 6: in this very early phase of learning programming, it is a good exercise to reimplement the basic and proven primitives, just to get an understanding of how they work. Of course, after this exercise you should be told by your teacher that someone else already did that work and tested it comprehensively, and that you therefore should use their implementation instead of your own." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-14T13:26:44.647", "Id": "457649", "Score": "0", "body": "Regarding item 4: How is calling `sqrt` a single time worse than needlessly iterating over the other \\$n-\\sqrt n\\$ numbers, just to sum up a few of them?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-14T19:23:00.557", "Id": "457669", "Score": "0", "body": "@RolandIllig About item 4, point taken. As n gets bigger, it is more likely that calculating the square root is beneficial. I suppose the only way to know for sure is with microbenchmarking, or instruction counting for the two versions of the program. Without such analysis, it is difficult to be certain." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-14T04:29:52.397", "Id": "232364", "ParentId": "232299", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-13T06:59:08.223", "Id": "232299", "Score": "1", "Tags": [ "scala" ], "Title": "Perfect Number usage in higher order function" }
232299
<p>Q1: What are the benefits of using any external library <code>e.g Antlr3.StringTemplate</code>?</p> <p>Q2: What are the potential issues with the below implementation?</p> <pre><code>public class StringTemplate { private string text = string.Empty; public StringTemplate(string template) { this.text = template; } public StringTemplate SetAttribute(string attribute, object value) { text = text.Replace($"${attribute}$", value?.ToString() ?? ""); return this; } public override string ToString() { return text.ToString(); } } </code></pre> <p><strong>And use it like below</strong></p> <pre><code> private void writeMsg() { var email = "Dear $name$...";//Loading from html file place holder used pattern $placeholder$. var template = new StringTemplate(email) .SetAttribute("name", "John"); Console.WriteLine(template.ToString()); } </code></pre>
[]
[ { "body": "<p>One probable issue is performance, suppose there are 30 tokens to be replaced. And email template has a size of 50 kb. strings are immutable in C#/.Net. That means whenever you call <code>StringTemplate.SetAttribute</code> it creates a new string by manipulating existing and return the new string. suppose there are 30 tokens so it will create 50KB * 29 waste string. It will create more pressure on GC and GC will collect more often which will lead to poor performance. Better to use <code>List&lt;char&gt;</code> to do this kind of operation. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-15T17:12:25.787", "Id": "453952", "Score": "0", "body": "Can you paste some code samples? It would be more helpful." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-15T10:41:28.490", "Id": "232436", "ParentId": "232307", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-13T08:44:52.940", "Id": "232307", "Score": "2", "Tags": [ "c#" ], "Title": "String template using concrete implementation instead of external library" }
232307
<p>I've implemented a Caesar cipher in C++ and would like for you to review it. It works as expected, at least with the inputs I've tried.</p> <p>Feel free to suggest improvements, warn about bad practices or mistakes that I might be doing or give general tips.</p> <pre><code>// Caesar Cipher implementation #include &lt;iostream&gt; #include &lt;string&gt; #include &lt;algorithm&gt; #include &lt;fstream&gt; #include &lt;vector&gt; #include &lt;cassert&gt; #include &lt;iterator&gt; std::string encodeStr(const std::string&amp; str, int shift, bool decodeFlag = false) { std::string str_enc; // not sure if this function is doing to much std::transform(str.cbegin(), str.cend(), std::back_inserter(str_enc), [&amp;](char ch) -&gt; char { if (ch == 'z' || ch == 'Z') { return ch - 25; } else if (isspace(ch)) { return ' '; } else { if (islower(ch)) ch ^= 0x20; // XOR 6th bit don't care if it's lower case. if (decodeFlag) { return ((ch - 'A' + 26) - shift) % 26 + 'A'; } else { return ((ch - 'A') + shift) % 26 + 'A'; } } }); return str_enc; } std::vector&lt;std::string&gt; encodeVec(const std::vector&lt;std::string&gt;&amp; strVector, int shift, bool decodeFlag = false) { std::vector&lt;std::string&gt; tempMsg; tempMsg.reserve(strVector.size()); std::transform(strVector.cbegin(), strVector.cend(), std::back_inserter(tempMsg), [&amp;](const std::string&amp; s) { return encodeStr(s, shift, decodeFlag); }); return tempMsg; } int main(int argc, char *argv[]) { int choice; std::cout &lt;&lt; "What do you want to do? 1.Encrypt, 2.Decrypt: "; std::cin &gt;&gt; choice; if (!(choice == 1 || choice == 2)) { return EXIT_FAILURE; } int key; std::cout &lt;&lt; "Enter desired shift: "; std::cin &gt;&gt; key; std::ifstream inFile("test.txt"); // Might ask for the file instead of hard coding it... if (!inFile) { std::cout &lt;&lt; "There was a problem with the file!"; return EXIT_FAILURE; } std::string line; std::vector&lt;std::string&gt; lines; while (std::getline(inFile, line)) { lines.push_back(line); } const std::vector&lt;std::string&gt; finalResult = [&amp;]() { return choice == 1 ? encodeVec(lines, key) : encodeVec(lines, key, true); }(); std::ofstream outFile("test.txt"); std::copy(finalResult.cbegin(), finalResult.cend(), std::ostream_iterator&lt;std::string&gt;(outFile, "\n")); return EXIT_SUCCESS; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-14T12:45:08.813", "Id": "453771", "Score": "2", "body": "I am just going to be a nitpick, but the ceasar cipher is a specifc case of a shiftcipher. What you have here is a shiftcipher, while a ceasarcipher would be a shiftcipher with shift=3. A ceasar cipher would make your implementation a lot easier ;)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-14T13:29:10.173", "Id": "453778", "Score": "1", "body": "@Danagon Really? Even Wikipedia gives examples with a shift of 25" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-14T13:54:34.487", "Id": "453783", "Score": "1", "body": "It was three ..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-14T14:22:55.213", "Id": "453791", "Score": "1", "body": "@Exzlanttt It is commonly misused (to the point that you may even consider it correct today like sometimes happens to language) by people, not into cryptography. The Ceasar cipher is named after Julius Ceasar, who always used a shiftcipher with shift=3 to encode important briefs. That's why the ceaser cipher specifically should use a shift of three and there is a more general name (shiftcipher) for the broader scheme. Which in turn is a specific case of the monoalphabetic substitution cipher, and so on." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-14T14:42:10.480", "Id": "453792", "Score": "1", "body": "@Danagon I'm going to nitpick too...you spelled \"Caesar\" wrong every time. Plus, Caesar's nephew used a shift of ONE. So, I'd say that it doesn't matter." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-14T14:47:49.117", "Id": "453793", "Score": "0", "body": "@Casey sorry for misspelling it :) Also his nephew was octavianus / Augustus. His name wasn't Caesar. Also, it is not a matter of opinion, it is the actual definition of a Caesar cipher." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-14T19:30:53.330", "Id": "453838", "Score": "0", "body": "Intriguing question and historical background." } ]
[ { "body": "<h2>Bug</h2>\n\n<p>Your <code>encodeStr()</code> method takes a <code>shift</code>, and a <code>decodeFlag</code>, but when it encounters a <code>'z'</code> or a <code>'Z'</code>, it ignores both and returns <code>ch - 25</code>. This means any string which contains a Z or encodes to contain a Z will not be decodable. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-13T14:56:24.070", "Id": "453633", "Score": "1", "body": "Yea that is from an earlier version without the flag forgot to delete that part and didn't test for strings with a 'Z'! Thank you for spotting it" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-13T15:01:18.063", "Id": "453634", "Score": "2", "body": "`\"The Quick Brown Fox Jumped Over The Lazy Dog\"` is your friend. :-). Add a test case encoding, and subsequently decoding it, and verifying the original string is returned." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-14T07:33:17.120", "Id": "453716", "Score": "2", "body": "Property-based tests are even more your friend! Just test that `encode(str, a + b) = encode(encode(str, b), a)` whenever 0 <= a,b < 26, and that `encode(str, 26) = str`, and you're 7/8 of the way to knowing that you're correct without even looking at any code." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-13T14:53:33.507", "Id": "232324", "ParentId": "232312", "Score": "4" } }, { "body": "<p>You can accept arguments from the command line.</p>\n\n<p>You don't need to differentiate between decode and encode, you can simply provide negative shift.</p>\n\n<p>You can hide the big lambda into a <code>char -&gt; char</code> function.</p>\n\n<p>You actually don't need the <code>string -&gt; string</code> nor <code>vector -&gt; vector</code> implementations.</p>\n\n<p><code>encodeStr</code> is a terrible name :)</p>\n\n<p>You can leverage the <code>char -&gt; char</code> implementation and copy <code>istream_iterator&lt;char&gt;</code> to <code>ostream_iterator&lt;char&gt;</code> char by char, and doing it over <code>std::cin</code> and <code>std::cout</code> will give you the ability to change the files as needed (through pipes) or use standard input / output by default.</p>\n\n<pre><code>#include &lt;iostream&gt;\n#include &lt;algorithm&gt;\n#include &lt;iterator&gt;\n#include &lt;sstream&gt;\n\nconst unsigned char caesar_range = 'Z' - 'A' + 1;\n\nchar caesar_cipher(char c, int shift)\n{\n char offset;\n if (c &gt;= 'a' &amp;&amp; c &lt;= 'z') offset = 'a';\n else if (c &gt;= 'A' &amp;&amp; c &lt;= 'Z') offset = 'A';\n else return c;\n\n shift = shift % caesar_range;\n auto base = c - offset + shift;\n if (base &lt; 0) {\n base = caesar_range + base;\n }\n return base % caesar_range + offset; \n}\n\nvoid caesar_usage()\n{\n std::cout &lt;&lt; \"Usage caesar &lt;shift&gt;\\n\";\n std::cout &lt;&lt; \"\\tshift must be integer and providing -shift decodes string encoded with shift.\\n\";\n}\n\nint main(int argc, char *argv[])\n{\n if (argc != 2) {\n caesar_usage();\n return EXIT_FAILURE;\n }\n\n int shift;\n std::stringstream ss(argv[1], std::ios_base::in);\n ss &gt;&gt; shift;\n if (ss.fail() || !ss.eof()) {\n caesar_usage();\n return EXIT_FAILURE;\n }\n\n // turn off white space skipping\n std::cin &gt;&gt; std::noskipws;\n\n std::transform(\n std::istream_iterator&lt;char&gt;(std::cin),\n std::istream_iterator&lt;char&gt;(),\n std::ostream_iterator&lt;char&gt;(std::cout), \n [&amp;](char c) -&gt; char {\n return caesar_cipher(c, shift);\n }\n );\n\n return EXIT_SUCCESS;\n}\n</code></pre>\n\n<p>Encode | decode:\n<code>./caesar 5 &lt;in.txt | ./caesar -5</code></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-14T09:13:26.797", "Id": "453725", "Score": "0", "body": "You can use `{}` as the second argument to `transform` to save on characters :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-14T12:05:55.177", "Id": "453758", "Score": "0", "body": "In what way is `encodeStr` a terrible name? Can you elaborate (by [editing your answer](https://codereview.stackexchange.com/posts/232326/edit), not here in comments)?" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-13T15:05:50.343", "Id": "232326", "ParentId": "232312", "Score": "9" } }, { "body": "<ol>\n<li><p>You should really look into the algorithm. If you do, you will see that encoding and decoding are essentially the same operation, though with negated key.</p></li>\n<li><p>Avoid passing a <code>std::string</code> or the like by constant reference. Accepting a <code>std::string_view</code> by value is generally more flexible and efficient.</p></li>\n<li><p><code>.reserve()</code> enough space at the start, and you won't have any wasteful reallocations.</p></li>\n<li><p>Always test with a few trivial examples to weed out brokenness. In your case, <code>z</code> and <code>Z</code> are broken for 25 of the 26 possible keys for each direction.</p></li>\n<li><p>Use <code>auto</code> to avoid repeating types, and potentially getting a costly mismatch.</p></li>\n<li><p>Consider using an in-place transformation instead.</p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-13T15:59:30.563", "Id": "453636", "Score": "2", "body": "I know the Z part is broken that if shouldn't exist. Didn't knew about string_view, thank you!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-14T16:45:40.530", "Id": "453808", "Score": "1", "body": "`std::string_view` is for non-mutating operations and will not work with `std::transform` when the destination is the `string_view`. Since encryption/decryption implies mutation, I would recommend taking the `std::string` by value since a copy is being made regardless if using `std::string_view` or not." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-14T17:27:52.137", "Id": "453815", "Score": "1", "body": "@Casey In-place encryption/decryption would imply mutation, yes. And that's one of my suggestions. But currently the code does not do in-place, and if it doesn't the view is better than the constant reference." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-13T15:24:19.817", "Id": "232328", "ParentId": "232312", "Score": "6" } }, { "body": "<h1>Alternative</h1>\n\n<p>I would use an alternative technique:</p>\n\n<p>Since your application basically reads a file and encodes it, why not simply make the stream do the encoding?</p>\n\n<p>I would do something like this:</p>\n\n<pre><code>#include &lt;locale&gt;\n#include &lt;algorithm&gt;\n#include &lt;iostream&gt;\n#include &lt;fstream&gt;\n\nint shift = 0;\n\nclass CaesarCipher: public std::codecvt&lt;char,char,std::mbstate_t&gt;\n{\n protected:\n virtual std::codecvt_base::result\n do_out(state_type&amp; tabNeeded,\n const char* rStart, const char* rEnd, const char*&amp; rNewStart,\n char* wStart, char* wEnd, char*&amp; wNewStart) const\n {\n for(;rStart &lt; rEnd;++rStart, ++wStart)\n {\n if (!std::isalpha(*rStart)) {\n *wStart = *rStart;\n }\n else {\n char input = *rStart | 0x20;\n *wStart = (input - 'A' - shift) % 26 + 'A';\n }\n }\n\n rNewStart = rStart;\n wNewStart = wStart;\n\n return std::codecvt_base::ok;\n }\n\n // Override so the do_out() virtual function is called.\n virtual bool do_always_noconv() const throw() {return false;}\n};\n\nint main(int argc, char* argv[])\n{\n if (argc != 2) {\n std::cerr &lt;&lt; \"Error Expected a shift value\\n\";\n exit(1);\n }\n shift = std::atoi(argv[1]);\n\n // Open the input file\n std::ifstream inFile(\"input.txt\");\n\n // Create an output file.\n // Imbue it with the encoding facet\n // Open the file.\n std::ofstream outFile;\n outFile.imbue(std::locale(std::locale::classic(), new CaesarCipher()));\n outFile.open(\"output.txt\");\n\n\n // Copy input file to output file\n outFile &lt;&lt; inFile.rdbuf();\n}\n</code></pre>\n\n<hr>\n\n<h1>Code Review</h1>\n\n<p>This is horrible:</p>\n\n<pre><code>const std::vector&lt;std::string&gt; finalResult = [&amp;]()\n{\n return choice == 1 ? encodeVec(lines, key) : encodeVec(lines, key, true);\n}();\n</code></pre>\n\n<p>Simply do:</p>\n\n<pre><code>const std::vector&lt;std::string&gt; finalResult = encodeVec(lines, key, choice != 1);\n</code></pre>\n\n<hr>\n\n<p>Why do you need a encode/decode version? They are doing literally the same thing. In most systems the encode and decode strings are different anyway. In this case the decode number is simply the negative of the encode number (or 26 - &lt;encode number>).</p>\n\n<pre><code> if (decodeFlag)\n {\n return ((ch - 'A' + 26) - shift) % 26 + 'A';\n }\n else\n {\n return ((ch - 'A') + shift) % 26 + 'A';\n }\n</code></pre>\n\n<p>I would simply write:</p>\n\n<pre><code> return ((ch - 'A') + shift) % 26 + 'A';\n</code></pre>\n\n<p>Then have users use different values to encode/decode.</p>\n\n<hr>\n\n<p>This:</p>\n\n<pre><code>if (islower(ch))\n ch ^= 0x20; // XOR 6th bit don't care if it's lower case.\n</code></pre>\n\n<p>Is just a complex way of doing:</p>\n\n<pre><code>ch |= 0x20; // Always add this flag to make everything upper case.\n</code></pre>\n\n<p>Note the encoding stuff is not going to work for any special characters (only uppercase letters) so treat everything as a character.</p>\n\n<hr>\n\n<p>OK, so space is special.</p>\n\n<pre><code> else if (isspace(ch))\n {\n return ' ';\n }\n</code></pre>\n\n<p>As everything that is not an uppercase letter (or converted to uppercase) is not going to decode properly then everything that is not a character should treated as special.</p>\n\n<pre><code> else if (!std::isalpha(ch))\n {\n return c;\n }\n</code></pre>\n\n<hr>\n\n<p>Somebody else mentioned this is a bug:</p>\n\n<pre><code> if (ch == 'z' || ch == 'Z')\n {\n return ch - 25;\n }\n</code></pre>\n\n<hr>\n\n<p>You do a lot of copying of strings to get this working.</p>\n\n<p>Some thought about doing the encoding in-place may save you a lot.</p>\n\n<hr>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-13T15:35:41.720", "Id": "232331", "ParentId": "232312", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-13T10:14:50.860", "Id": "232312", "Score": "8", "Tags": [ "c++", "algorithm", "caesar-cipher" ], "Title": "Caesar cipher implementation in C++" }
232312
<p>Please could you review my code below? </p> <p>The game is similar to "Connect 4", but I haven't implemented diagonal checking for wins.</p> <p>In particular I'm interested in my use of OOP. E.g.</p> <p>My choice of classes</p> <p>Did I need a <code>Game</code> class at all? I've tried to find out whether it's considered a good idea to have a class for game logic etc, but can't get an answer. I can see that here it could be considered overkill...</p> <p><code>self.board</code> used in both classes - probably a bad idea?</p> <p>I'm also interested in feedback on Overall style and anything else which occurs to you.</p> <pre><code>import os import random LINE_LENGTH = 3 NUM_ROWS = 6 NUM_COLS = 7 EMPTY_SPACE = "-" PLAYER_SYMBOL = "+" COMPUTER_SYMBOL = "^" class GameBoard: def __init__(self, rows=NUM_ROWS, cols=NUM_COLS, fill=EMPTY_SPACE): self.rows = rows self.cols = cols self.fill = fill self.board = [[fill] * cols for row in range(rows)] def __str__(self): return ( "\n".join([" ".join(str(c) for c in row) for row in self.board]) + "\n" + "-" * (2 * self.cols - 1) + "\n" + " ".join(str(col) for col in list(range(self.cols))) + "\n" ) def is_free_position(self, col): for row in range(NUM_ROWS): if self.board[row][col] == EMPTY_SPACE: return True return False def insert_piece(self, col, symbol): for row_num in range(len(self.board) - 1, -1, -1): if self.board[row_num][col] == EMPTY_SPACE: self.board[row_num][col] = symbol return def is_win_position(self, board, piece): # board is not instance variable # Horizontal check for row in range(NUM_ROWS): for col in range(NUM_COLS - (LINE_LENGTH - 1)): if all( board[row][col + offset] == (piece) for offset in range(LINE_LENGTH) ): return True # Vertical check for col in range(NUM_COLS): for row in range(NUM_ROWS - (LINE_LENGTH - 1)): if all( board[row + offset][col] == (piece) for offset in range(LINE_LENGTH) ): return True return False class Game: def __init__(self): self.new_game() def print_title(self): print("X IN A LINE") print() def play_again(self): print() answer = input("Would you like to play again? ") print() return answer.lower().startswith("y") def new_game(self): self.board = GameBoard() self.turn = "player" if random.choice([0, 1]) == 0 else "computer" self.current_piece = PLAYER_SYMBOL if self.turn == "player" else COMPUTER_SYMBOL self.winner = None while self.winner is None: self.clear_scr() self.print_title() print(self.board) if self.turn == "player": self.player_plays() else: self.computer_plays() if self.board.is_win_position(self.board.board, self.current_piece): self.clear_scr() self.print_title() print(self.board) self.winner = self.turn print( "Yay you won!" if self.winner == "player" else "Bad luck, the computer won." ) if self.play_again(): self.new_game() else: print("Goodbye.") # Switch player if self.turn == "player": self.turn = "computer" self.current_piece = COMPUTER_SYMBOL else: self.turn = "player" self.current_piece = PLAYER_SYMBOL def clear_scr(self): os.system("cls" if os.name == "nt" else "clear") def validate_input(self, player_choice): try: player_choice = int(player_choice) except ValueError: print("Input should be a number.") return False if 0 &gt; player_choice or player_choice &gt;= NUM_COLS: print("That number is out of range.") return False if not self.board.is_free_position(player_choice): print("That column is not available.") return False return True def player_plays(self): valid_input = False while not valid_input: player_choice = input("Enter a column number to place a piece: ") print() valid_input = self.validate_input(player_choice) self.board.insert_piece(int(player_choice), PLAYER_SYMBOL) def computer_plays(self): free_slot = False while not free_slot: computer_choice = random.randrange(NUM_COLS) if self.board.is_free_position(computer_choice): self.board.insert_piece(computer_choice, COMPUTER_SYMBOL) free_slot = True game = Game() </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-13T11:52:19.147", "Id": "453605", "Score": "1", "body": "A good way to cut down on solution checking in these kinds of problems (Sudoku solvers are similar) is to treat the board as a matrix. Here you could have a method for checking four horizontal counters in a row, then transform the board by rotation (90° for vertical, 45° for diagonal) and perform the same check again. Using numpy, these transformations are trivial." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-13T11:04:56.250", "Id": "232313", "Score": "1", "Tags": [ "python", "object-oriented", "game", "console" ], "Title": "X in a Line Console Game - Python OOP" }
232313
<p>I have the following method, which is called every time the user clicks a checkbox within a <code>Datagrid</code>. Each column within this <code>Datagrid</code> has a box in its header, which checks/unchecks all child checkboxes in the respective column. This header checkbox will be updated according to the child checkboxes by the method. </p> <p>My problem is that there is a lot of repetitive code in it since we do the same operation for each property (column) based on the checkbox that was clicked. </p> <p>Here is the code:</p> <pre><code> /// &lt;summary&gt; /// Sets the Columnsheadercheckbox based on the individual checkbox values of the respective filter /// &lt;/summary&gt; private void SetHeaderCheckbox(string filterProperty = null) { if (GridData.Count == 0) return; var filter = GridData[0]; DataGridDropdownProperty found; if (filterProperty == null) filterProperty = "all"; switch (filterProperty) { case "SuperImpose": found = GridData.FirstOrDefault(f =&gt; f.SplitOver != filter.SplitOver); if (found == null) { SuperimposeHeaderCheckbox = filter.SplitOver; } else { SuperimposeHeaderCheckbox = null; } break; case "Normalize": found = GridData.FirstOrDefault(f =&gt; f.ToNormalize != filter.ToNormalize); if (found == null) { NormalizeByHeaderCheckbox = filter.ToNormalize; } else { NormalizeByHeaderCheckbox = null; } break; case "Legend": found = GridData.FirstOrDefault(f =&gt; f.ToLegend != filter.ToLegend); if (found == null) { LegendHeaderCheckbox = filter.ToLegend; } else { LegendHeaderCheckbox = null; } break; case "all": // Superimpose found = GridData.FirstOrDefault(f =&gt; f.SplitOver != filter.SplitOver); if (found == null) { SuperimposeHeaderCheckbox = filter.SplitOver; } else { SuperimposeHeaderCheckbox = null; } // Normalize found = GridData.FirstOrDefault(f =&gt; f.ToNormalize != filter.ToNormalize); if (found == null) { NormalizeByHeaderCheckbox = filter.ToNormalize; } else { NormalizeByHeaderCheckbox = null; } // Legend found = GridData.FirstOrDefault(f =&gt; f.ToLegend != filter.ToLegend); if (found == null) { LegendHeaderCheckbox = filter.ToLegend; } else { LegendHeaderCheckbox = null; } break; } } </code></pre> <p>My question is, if this kind of code is 'OK' or if it is, this is terrible practice, and there should be a more elegant way around it. (btw. Ignore the hardcoded strings. This is to illustrate the example)</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-15T10:25:22.433", "Id": "453898", "Score": "0", "body": "The current question title, which states your concerns about the code, is too general to be useful here. Please edit to the site standard, which is for the title to simply state the task accomplished by the code. Please see [**How to get the best value out of Code Review: Asking Questions**](https://CodeReview.Meta.StackExchange.com/q/2436) for guidance on writing good question titles." } ]
[ { "body": "<ol>\n<li><p>Replace the <code>if-else</code> statements under each case with inline if statements. You can remove the <code>if-else</code> repetitions. For example..</p>\n\n<pre><code>SuperimposeHeaderCheckbox = found ? null : filter.SplitOver;\n</code></pre></li>\n<li><p>You can use turn <code>filterProperty</code> into an enumeration (instead of a string).</p>\n\n<pre><code>enum flags {SuperImpose=1, Normalize=2, Legend=4, all=7};\n</code></pre></li>\n<li><p>Finally, replace the <code>switch-case</code> statement with simple <code>if</code> statements. You can remove the repetitions for the case <code>all</code>.</p>\n\n<pre><code>if (filterProperty &amp; flags.SuperImpose) {\n // your code here\n}\nif (filterProperty &amp; flags.Normalize) {\n // your code here\n}\nif (filterProperty &amp; flags.Legend) {\n // your code here\n}\n// No need for a fourth if statement.\n</code></pre></li>\n<li><p>If you furthur want to reduce the number of the above <code>if</code> statements, you can map the properties in <code>filter</code> to the values in the enumeration and loop through the map.</p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-13T12:21:32.660", "Id": "453611", "Score": "0", "body": "Thanks, for the tipp, but with this it will still be repeating code for each case statement." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-13T12:23:21.570", "Id": "453612", "Score": "0", "body": "@Roland Deschain, I am adding more to my answer, give me some time." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-13T12:24:51.453", "Id": "453613", "Score": "1", "body": "Inline statements are *not* an improvement over a switch statement." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-13T12:28:11.077", "Id": "453614", "Score": "0", "body": "@shards yes, sorry...all your tips are nice to tidy up the code a bit and make it more readable, but my question was about the repetitiveness of the code itself. But it seems there is no way around doing the same statement for each of the filter properties..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-13T12:33:58.537", "Id": "453615", "Score": "1", "body": "@RolandDeschain of course there is a way. You just have to define all the properties and put them in a dictionary. Let it be the filter holding a dictionary of string to property value directly. Or let it be a dictionary of string to property getter callback, held by the class in question." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-13T12:39:56.920", "Id": "453617", "Score": "0", "body": "@slepic just googled a bit around and, yes, this seems to be what I'm looking for!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-14T16:12:52.510", "Id": "453804", "Score": "0", "body": "`found ? filter.SplitOver : null` It should be inverted. OP's code fills in the value when `found == null`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-15T02:22:48.217", "Id": "453870", "Score": "0", "body": "@Flater, my bad." } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-13T12:14:12.630", "Id": "232317", "ParentId": "232315", "Score": "2" } }, { "body": "<p>You can always avoid repeating code by abstracting the general parts.</p>\n\n<p>For example, your switch statement could be abstracted with the following code (assumed some types that are not declared in your question):</p>\n\n<pre><code>private interface IChecker\n{\n void Apply(GridData gridData);\n bool CanApply(string filterPropertyName);\n}\n\nprivate class Checker&lt;TFilterProperty&gt; : IChecker\n{\n private readonly string name;\n private readonly Func&lt;Filter, TFilterProperty&gt; filterSelector;\n private readonly Func&lt;GridRow, TFilterProperty&gt; gridRowSelector;\n private readonly Action&lt;TFilterProperty&gt; filterSetter;\n\n public Checker(\n string name, \n Func&lt;Filter, TFilterProperty&gt; filterSelector, \n Func&lt;GridRow, TFilterProperty&gt; gridRowSelector,\n Action&lt;TFilterProperty&gt; filterSetter)\n {\n this.name = name;\n this.filterSelector = filterSelector;\n this.gridRowSelector = gridRowSelector;\n this.filterSetter = filterSetter;\n }\n\n public void Apply(GridData gridData)\n {\n var filter = GridData[0];\n var filterValue = filterSelector(filter);\n var found = GridData.FirstOrDefault(f =&gt; gridRowSelector(f) != filterValue);\n var valueToSet = found == null ? filterValue : null;\n this.filterSetter(valueToSet);\n }\n\n public bool CanApply(string filterPropertyName) =&gt; filterPropertyName == \"all\" || filterPropertyName == this.name;\n}\n\nprivate void SetHeaderCheckbox(string filterProperty = null)\n{\n if (GridData.Count == 0) return;\n\n if (filterProperty == null) filterProperty = \"all\";\n\n var checkers = new IChecker[]\n {\n new Checker(\"SuperImpose\", f =&gt; f.SplitOver, f =&gt; f.SplitOver, v =&gt; this.SuperimposeHeaderCheckbox = value),\n new Checker(\"Normalize\", f =&gt; f.ToNormalize, f =&gt; f.ToNormalize, v =&gt; this.NormalizeByHeaderCheckbox = value),\n new Checker(\"Legend\", f =&gt; f.ToLegend, f =&gt; f.ToLegend, v =&gt; this.LegendHeaderCheckbox = value),\n }\n\n foreach (var checker in checkers.Where(c =&gt; c.CanApply(filterProperty))\n {\n checker.Apply(GridData);\n }\n}\n</code></pre>\n\n<p>Whether the abstracted code is more readable / maintainable is another question that depends on the concrete use case :)</p>\n\n<p>Note that the code above is just an untested example that illustrates the abstraction of common parts. There may be better abstractions with less delegates in your case ;)</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-14T12:15:22.587", "Id": "232378", "ParentId": "232315", "Score": "1" } } ]
{ "AcceptedAnswerId": "232317", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-13T11:45:10.643", "Id": "232315", "Score": "4", "Tags": [ "c#" ], "Title": "Is there a way to avoid repetitive code in the following switch statement?" }
232315
<p>I'm a beginner using Python, and I'm trying to implement a functionality of a monitor program already developed by an other programmer.</p> <p>This program is working on a Windows machine (made by Inno Setup), which has to listen to the RabbitMQ server and consume messages. Those messages are supposed to start a background After Effect process (via PowerShell) and monitor it's workflow until it finishes. After that, the monitor consumes another message if it exists. This monitor is never supposed to be down and will have to work indefinitely.</p> <p>So why I'm trying to develop this again? Because the current implementation is buggy at a very particular point : When RabbitMQ closes (reboot, shutdown, or other reason), consumers are disconnected, and no messages are consumed anymore.</p> <p>My implementation below fixes this behavior (for simplicity I develop this entirely apart from the existing software, it was to reproduce the bug and fix it)</p> <p>But I'm new in python, so I'm sure this code is bloated or ugly in some way, and I will gladly take all the advice you can give.</p> <p>My Main.py</p> <pre><code>from src.RabbitMQ.RabbitMQ import RabbitMQ class Main: def __init__(self): RabbitMQ() main = Main() </code></pre> <p>RabbitMQ.py</p> <pre><code>from src.RabbitMQ.Configuration.Liveness import Liveness class RabbitMQ: def __init__(self): self.start_liveness() def start_liveness(self): mainThread = Liveness() mainThread.start() </code></pre> <p>ThreadedConnection.py</p> <pre><code>from src.RabbitMQ.ValueObjects.Connection import Connection from src.RabbitMQ.Service.Consumer import Consumer import threading import time class ThreadedConnection(threading.Thread): def __init__(self, queue_name): threading.Thread.__init__(self) self.queueName = queue_name self.should_reopen = False self.connection = None self.channel = None self.connect() # https://stackoverflow.com/questions/25489292/consuming-rabbitmq-queue-from-inside-python-threads def connect(self): try: result = Connection().connect() if result: [self.connection, self.channel] = result self.channel.queue_declare(queue=self.queueName, durable=True, arguments={"x-queue-type": "quorum"}) self.channel.basic_qos(prefetch_count=1) self.channel.basic_consume(queue=self.queueName, on_message_callback=Consumer.consume, auto_ack=True) else: raise Exception('no connection available') except: print('hang on AMQP is closed') def run(self): try: print('try consuming') self.channel.start_consuming() except: print('something wrong happened... waiting for reopenning') </code></pre> <p>Connection.py</p> <pre><code>import pika from src.RabbitMQ.ValueObjects.ConnectionParams import ConnectionParams class Connection: def __init__(self): self.__get_params() def __get_params(self): self.connectionParams = ConnectionParams() def connect(self): connection = pika.PlainCredentials(self.connectionParams.username, self.connectionParams.password) parameters = pika.ConnectionParameters( self.connectionParams.host, self.connectionParams.port, self.connectionParams.vhost, credentials=connection, heartbeat=3600, blocked_connection_timeout=3600 ) connection = pika.BlockingConnection(parameters) channel = connection.channel() return [connection, channel] </code></pre> <p>Consumer.py</p> <pre><code>class Consumer: def __init__(self, channel): """ :param pika.adapters.blocking_connection.BlockingChannel channel: The channel """ self.channel = channel def consume(self, method, properties, body): """ Cette méthode consomme nos messages :param method: :param properties: :param body: :return: """ print(body) print('[*] Message received') </code></pre> <p>ConnectionParams.py</p> <pre><code>class ConnectionParams: def __init__(self): self.port = 5672 self.host = "127.0.0.1" self.vhost = "/" self.password = "test" self.username = "test" </code></pre> <p>Liveness.py</p> <pre><code>import threading import time from src.RabbitMQ.Configuration.ThreadedConnection import ThreadedConnection class Liveness(threading.Thread): def __init__(self): self.queues = ("preview", "common", "urgent") threading.Thread.__init__(self) self.channels = [] def reopen_channels(self): self.channels = [] for queue in self.queues: from src.RabbitMQ.RabbitMQ import RabbitMQ print("The channel " + queue + " is closed reopen...") self.connect(queue=queue) def run_queues(self): for queue in self.queues: self.connect(queue) def run(self): self.run_queues() self.liveness() def connect(self, queue): thread = ThreadedConnection(queue) thread.start() if thread.channel: channel_tag = '' for key in thread.channel._consumer_infos: channel_tag = key conf_dict = { "channel": thread.channel, "connection": thread.connection, "ctag": channel_tag, "thread": thread, "queue": queue } self.channels.append(conf_dict) def liveness(self): while True: should_reopen = False if not self.channels: self.run_queues() for config in self.channels: if config['thread'].isAlive(): alive = ". The thread is still alive too." else: alive = ". The thread is also closed." if not config['channel'].is_closed: channel_alive = " is alive" else: should_reopen = True channel_alive = " is closed and should be reopened" print("The channel " + config['ctag'] + channel_alive + alive) if should_reopen: print('re-openning...') self.reopen_channels() print('---') time.sleep(20) </code></pre> <p>docker-compose.yml</p> <pre><code>version: '3' services: rabbitmq: image: 'bitnami/rabbitmq:3.8' environment: - RABBITMQ_PASSWORD=test - RABBITMQ_USERNAME=test ports: - '4369:4369' - '5672:5672' - '25672:25672' - '15672:15672' volumes: - 'rabbitmq_data:/bitnami' volumes: rabbitmq_data: driver: local </code></pre> <p>I have some questions. I hope to find an answer :</p> <p>Is it a good practice to start an infinite loop like this in python? Does a better way exist to "hang on"? (don't end the program's execution)</p> <p>Is my code well architectured? With python best practices?</p> <p>Is my test relevant to simulate a rabbitMQ shutdown?</p> <p>Here's a full example of what happens in the terminal</p> <p><a href="https://i.stack.imgur.com/UFgul.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/UFgul.png" alt="sample"></a></p> <p>Before answering: please ask for clarification, if needed, and don't forget to answer my questions during the process.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-13T13:42:08.547", "Id": "453623", "Score": "2", "body": "Pika has some example code for re-connection as well as using multiple hosts if you're using a RabbitMQ cluster: https://github.com/pika/pika/blob/master/examples/blocking_consume_recover_multiple_hosts.py" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-13T14:50:37.727", "Id": "453632", "Score": "0", "body": "thanks for this @LukeBakken the problem I have with the snippet you linked is the connection.close method, I never want to close the connection, maybe I missunderstood this ? not sure." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-13T13:03:21.850", "Id": "232319", "Score": "5", "Tags": [ "python", "python-3.x", "object-oriented", "multithreading", "rabbitmq" ], "Title": "Liveness monitor : python and RabbitMQ together through Pika" }
232319
<p>I need to check if a filename contains a value that I get from 2 excel Columns (ContractNumber &amp; PONumber). My Script is too slow right now. It has been running for 1 hour, and it completed only 2%.</p> <p>The files are in 600+ folders within the main directory(shared drive). There are 19K files(pdf/docx). And 40K numbers to check.</p> <p>How can I improve my script, so it won't take this long to run?</p> <pre><code>#create excel $objExcel = New-Object -ComObject Excel.Application $WorkBook = $objExcel.Workbooks.Open("C:\Users\X\Documents\XYZ.xlsx") # Select the sheet $sheetContractData = $WorkBook.sheets.item("Contracts") $sheetCustomerNames = $WorkBook.sheets.item("Customers") $sheetContractStatus = $WorkBook.sheets.item("Status") # Amount of row -&gt; TOTAL = 19469 $rowMax = ($sheetContracts.UsedRange.Rows).count # declare the starting position for each column $rowContractNumber,$colContractNumber = 2,1 $rowType,$colType = 2,2 $rowCompany,$colCompany = 2,3 $rowStartDate,$colStartDate = 2,4 $rowEndDate,$colEndDate = 2,5 $rowDescription,$colDescription = 2,6 $rowPONumber,$colPONumber = 2,7 $rowContactPerson,$colContactPerson = 2,8 $rowCustomerNumber,$colCustomerNumber = 2,9 $Contracts = New-Object Collections.Generic.List[PSCustomObject] # Contract class class Contract { [string]$ContractNumber [string]$Type [string]$Company [string]$StartDate [string]$EndDate [string]$Description [string]$PONumber [string]$ContactPerson [string]$CustomerNumber } # Adding contracts to list for ($i=1; $i -le $rowMax-1; $i++) { $objContract = [Contract]::new() $objContract.ContractNumber = $sheetContractData.Cells.Item($rowContractNumber+$i,$colContractNumber).text $objContract.Type = $sheetContractData.Cells.Item($rowType+$i,$colType).text $objContract.Company = $sheetContractData.Cells.Item($rowCompany+$i,$colCompany).text $objContract.StartDate = $sheetContractData.Cells.Item($rowStartDate+$i,$colStartDate).text $objContract.EndDate = $sheetContractData.Cells.Item($rowEndDate+$i,$colEndDate).text $objContract.Description = $sheetContractData.Cells.Item($rowDescription+$i,$colDescription).text $objContract.PONumber = $sheetContractData.Cells.Item($rowPONumber+$i,$colPONumber).text $objContract.ContactPerson = $sheetContractData.Cells.Item($rowContactPerson+$i,$colContactPerson).text $objContract.CustomerNumber = $sheetContractData.Cells.Item($rowCustomerNumber+$i,$colCustomerNumber).text $Contracts.Add($objContract) $prcntComplete = [math]::Round(($i / ($rowMax-1)) * 100 ) Write-Progress -Activity "Adding contracts to List" -Status "$prcntComplete% Complete:" -PercentComplete $prcntComplete; } # close Excel $objExcel.quit() # Compare all files -&gt; TOTAL = 23265 $totalFilesInDrive = (Get-ChildItem "C:\Path\X" -Recurse| where { ! $_.PSIsContainer }).count # Compare files with excel data $foundContracts = 0 $filesDone = 0 foreach ($file in Get-ChildItem "C:\Path\X" -Recurse| where { ! $_.PSIsContainer }){ for ($j=0; $j -le $Contracts.Count-1; $j++) { Try { if($Contracts[$j].ContractNumber.Length -gt 5 -and $file.Name -match '^.*' + $Contracts[$j].ContractNumber + '.*\.(([pP][dD][fF])|([dD][oO][cC][xX]?))$'){ $foundContracts += 1 Break } elseif($Contracts[$j].PONumber.Length -gt 5 -and $file.Name -match '^.*' + $Contracts[$j].PONumber + '.*\.(([pP][dD][fF])|([dD][oO][cC][xX]?))$'){ $foundContracts += 1 Break } } Catch { $_ | Out-File C:\Users\X\Desktop\errors.txt -Append } } $progressSearch = [math]::Round(($filesDone / $totalFilesInDrive) * 100, 4) Write-Progress -Activity "Searching for contracts with Contractnumber or PO number FULL" -Status "$progressSearch % Complete:" -PercentComplete $progressSearch; $filesDone += 1 } "Contracts Found: " + $foundContracts # Ratio Write-Host("{0} % of the contracts can be moved" -f [math]::Round(($foundContracts / $totalFilesInDrive) * 100, 4)) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-13T13:24:48.517", "Id": "453621", "Score": "1", "body": "Can you add sample `.pdf` and `.docx` file names so that we could test possible alternatives? Also please add full code (right now `$totalFilesInDrive` seems to be magic)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-13T14:29:24.847", "Id": "453629", "Score": "0", "body": "I have added the full code (There is some sensitive data so I removed specific paths & names but provided the results). Thanks for trying to to help." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-13T16:39:11.060", "Id": "453640", "Score": "1", "body": "Generate a single regexp from all ContractNumber and all PONumber when you read the excel file so it looks like `'(111|222|333)\\.(pdf|docx?)'` where 111, 222, 333 are these numbers. Then instead of the `for` loop over $Contracts you'll simply do a single `-match`, also note it's already case-insensitive so no need for `[dD][oO][cC][xX]`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-14T09:22:50.747", "Id": "453727", "Score": "0", "body": "@wOxxOm Thanks for the info. But a single regex is not possible because al numbers are different (some are 4, 8, 12 numbers and some have chars at random places). And thanks for the case case-insensitive tip. I will update my code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-14T09:39:09.520", "Id": "453732", "Score": "0", "body": "It's possible, the amount of digits doesn't matter, here's an example '(8751a-8|BB6176#21|FF1200-00)\\.(pdf|docx?)$' you will only have to escape the special characters like e.g. $rx += ($ContractNumber -replace `'[.()[\\]{}+]','\\$&'`) + '|' (and then you'll remove the last `|` of course and add `)\\.(pdf|docx?)$`)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-14T09:46:10.017", "Id": "453734", "Score": "0", "body": "Oh ok, now I understand better what you mean, but then I need to write al the 40K numbers in the regexp? I can do that, that's no problem but it will be a very long string." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-13T13:08:28.747", "Id": "232320", "Score": "4", "Tags": [ "regex", "powershell" ], "Title": "Powershell: does a file name contain a value" }
232320
<p>I have implemented my business logic using the repository pattern. I have an Approve method in my controller. I am calling the service method <code>ApproveUserChangeRequest</code>, which in turn invokes <code>GetUserChangeRequest</code> and <code>ApproveUserChangeRequest</code> in the <code>UnitofWork</code> class. I would like to know if this is standard practice or if there are better ways of doing it. Please bear in mind in to test the service methods.</p> <p>UserConroller</p> <pre><code>[HttpPost] [AllowAnonymous] [Route("approve-change-request")] public IActionResult ApproveUserChangeRequest([FromBody] ApproveUserChangeRequests approveUserChangeRequests) { if (!ModelState.IsValid) { return BadRequest(new ResponseModel() { ResponseMessages = new Dictionary&lt;string, string[]&gt; { { "Errors", ModelState.Values.SelectMany(x =&gt; x.Errors).Select(x =&gt; x.ErrorMessage).ToArray() } } }); } var result = _userService.ApproveUserChangeRequest(approveUserChangeRequests); var message = string.Empty; if (result.Succeeded) { return Ok(new ResponseModel() { ResponseMessages = new Dictionary&lt;string, string[]&gt; { { "Info", new string[] { $"True" } } } }); } message = string.Join(";", result.Errors.Select(x =&gt; $"Code: {x.Code}. Description: {x.Description}")); _logger.Error(new IdentityException($"Error approving user change requests. Message: {message}")); return BadRequest(); } </code></pre> <p>UserService class </p> <pre><code>public IdentityResult ApproveUserChangeRequest(ApproveUserChangeRequests approveUserChangeRequests) { var userChangeRequest = _userUow.GetUserChangeRequest(approveUserChangeRequests.UserChangeRequestID); IdentityResult result = _userUow.ApproveUserChangeRequest(userChangeRequest, approveUserChangeRequests.ApprovedByAuthUserId, approveUserChangeRequests.AuthApplicationName); return result; } </code></pre> <p>UnitofWork class (uow)</p> <pre><code>public UserChangeRequest GetUserChangeRequest(int userChangeRequestId) { return UserChangeRequestRepository.GetQueryable(x =&gt; x.Id == userChangeRequestId) .FirstOrDefault(); } public IdentityResult ApproveUserChangeRequest(UserChangeRequest userChangeRequest, int approvedByAuthUserId, string authApplicationName) { var idResult = IdentityResult.Success; // Check if UserChangeRequest is still Pending bool isUserChangeRequestPending = UserChangeRequestRepository.GetQueryable(x =&gt; x.Id == userChangeRequest.Id &amp;&amp; x.ChangeStatus == "Pending").Any(); if (isUserChangeRequestPending &amp;&amp; approvedByAuthUserId &gt; 0) { // Inserting record in the UserChangeRequestApproval table InsertUserChangeRequestApproval(userChangeRequest); SaveContext(); //Updating the user details in IdentityDB, ClientCompanyContact and AuthUser tables UpdateUserDetails(userChangeRequest, authApplicationName); } else { idResult = IdentityResult.Failed(new IdentityError { Description = "No userchange request to approve" }); } return idResult; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-14T08:55:43.630", "Id": "453723", "Score": "3", "body": "Do you have a usage example with this?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-14T13:38:56.360", "Id": "453780", "Score": "1", "body": "To add to what Mast said, could you add all the related classes? For example, `ApproveUserChangeRequests` isn't here, we'd need it to give the best review possible." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-13T13:28:51.507", "Id": "232321", "Score": "2", "Tags": [ "c#", "repository" ], "Title": "Unit testing the code that is written using repository pattern" }
232321
<p>I'm learning how to write WPF custom controls. My example, <code>NameLister</code>, exposes a single DependencyProperty, <code>Names</code>, of type <code>ObservableCollection&lt;string&gt;</code>, and displays all the names concatenated together into a single string in a <code>TextBlock</code>.</p> <p>To test my control, I have a <code>TestApp</code> which binds a collection of three strings: "Larry", "Curly", and "Moe" to the <code>Names</code> property of my control. It then has a repeating timer which adds "Me" strings to its collection.</p> <p>There are a few things I'm puzzled about:</p> <ol> <li>This sure seems like a lot of code just for one <code>DependencyProperty</code> to which someone can bind an <code>ObservableCollection</code>.</li> <li>Should I be using <code>ObservableCollection</code>, <code>IEnumerable</code>, or <code>IList</code> as the type for my <code>Names</code> <code>DependencyProperty</code>?</li> <li>I made my custom control implement INotifyPropertyChanged. I did this because I use a normal property, <code>DisplayString</code>, bound to the <code>TextBlock</code>'s <code>Text</code> property in the XAML. However, I've heard this is a bad idea (because my custom control is a view, not a view-model?)</li> </ol> <h1>TestApp</h1> <h2>MainWindow.xaml</h2> <pre><code>&lt;Window x:Class="TestApp.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:sdwc="clr-namespace:NameListerWpfControl;assembly=NameListerWpfControl" xmlns:local="clr-namespace:TestApp" mc:Ignorable="d" Title="MainWindow" Height="450" Width="800" BorderBrush="#FF0010FF"&gt; &lt;Window.DataContext&gt; &lt;local:ViewModel /&gt; &lt;/Window.DataContext&gt; &lt;Grid&gt; &lt;sdwc:NameLister Background="Red" Names="{Binding Stooges}" /&gt; &lt;/Grid&gt; &lt;/Window&gt; </code></pre> <h2>ViewModel.cs</h2> <pre><code>using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; namespace TestApp { public class ViewModel : INotifyPropertyChanged { public ObservableCollection&lt;string&gt; Stooges { get; set; } = new ObservableCollection&lt;string&gt; {"Larry", "Curly", "Moe"}; public ViewModel() { var dispatcherTimer = new System.Windows.Threading.DispatcherTimer { Interval = new TimeSpan(0, 0, 2) }; dispatcherTimer.Tick += delegate { Stooges.Add("Me"); RaisePropertyChanged(nameof(Stooges)); }; dispatcherTimer.Start(); } /// &lt;summary&gt; /// The property changed event /// &lt;/summary&gt; public event PropertyChangedEventHandler PropertyChanged; /// &lt;summary&gt; /// Raises the property changed event /// &lt;/summary&gt; /// &lt;param name="property"&gt;The property name&lt;/param&gt; public void RaisePropertyChanged(string property) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(property)); } } } </code></pre> <h1>NameListerWpfControl</h1> <h2>Themes/Generic.xaml</h2> <pre><code>&lt;ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:NameListerWpfControl"&gt; &lt;Style TargetType="{x:Type local:NameLister}"&gt; &lt;Setter Property="Template"&gt; &lt;Setter.Value&gt; &lt;ControlTemplate TargetType="{x:Type local:NameLister}"&gt; &lt;TextBlock Text="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type local:NameLister}}, Path=DisplayString}"/&gt; &lt;/ControlTemplate&gt; &lt;/Setter.Value&gt; &lt;/Setter&gt; &lt;/Style&gt; &lt;/ResourceDictionary&gt; </code></pre> <h2>NameLister.cs</h2> <pre><code>using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace NameListerWpfControl { /// &lt;summary&gt; /// Lists names /// &lt;/summary&gt; public class NameLister : Control, INotifyPropertyChanged { static NameLister() { DefaultStyleKeyProperty.OverrideMetadata(typeof(NameLister), new FrameworkPropertyMetadata(typeof(NameLister))); } /// &lt;summary&gt; /// The names displayed as a single string /// &lt;/summary&gt; public string DisplayString =&gt; string.Join(", ", Names); /// &lt;summary&gt; /// Identifies the Names dependency property. /// &lt;/summary&gt; public static readonly DependencyProperty NamesProperty = DependencyProperty.Register( "Names", typeof(ObservableCollection&lt;string&gt;), typeof(NameLister), new FrameworkPropertyMetadata( new ObservableCollection&lt;string&gt; (), OnNamesChanged, CoerceStrings)); /// &lt;summary&gt; /// Gets or sets the value assigned to the control. /// &lt;/summary&gt; public ObservableCollection&lt;string&gt; Names { get =&gt; (ObservableCollection&lt;string&gt;)GetValue(NamesProperty); set =&gt; SetValue(NamesProperty, value); } private static object CoerceStrings(DependencyObject element, object value) { var newValue = (ObservableCollection&lt;string&gt;)value; // TODO: Actually do some coercion. return newValue; } private static void OnNamesChanged(DependencyObject obj, DependencyPropertyChangedEventArgs args) { var control = (NameLister)obj; control.RaisePropertyChanged(nameof(DisplayString)); var action = new NotifyCollectionChangedEventHandler( (o, args2) =&gt; { if (!(obj is NameLister lister)) return; lister.RaisePropertyChanged(nameof(DisplayString)); }); if (args.OldValue != null) { var coll = (INotifyCollectionChanged)args.OldValue; // Unsubscribe from CollectionChanged on the old collection coll.CollectionChanged -= action; } if (args.NewValue != null) { var coll = (INotifyCollectionChanged)args.NewValue; // Subscribe to CollectionChanged on the new collection coll.CollectionChanged += action; } var e = new RoutedPropertyChangedEventArgs&lt;ObservableCollection&lt;string&gt;&gt;( (ObservableCollection&lt;string&gt;)args.OldValue, (ObservableCollection&lt;string&gt;)args.NewValue, NamesChangedEvent); control.OnNamesChanged(e); } /// &lt;summary&gt; /// Identifies the NamesChanged routed event. /// &lt;/summary&gt; public static readonly RoutedEvent NamesChangedEvent = EventManager.RegisterRoutedEvent( "NamesChanged", RoutingStrategy.Bubble, typeof(RoutedPropertyChangedEventHandler&lt;ObservableCollection&lt;string&gt;&gt;), typeof(NameLister)); /// &lt;summary&gt; /// Occurs when the Names property changes. /// &lt;/summary&gt; public event RoutedPropertyChangedEventHandler&lt;ObservableCollection&lt;string&gt;&gt; NamesChanged { add =&gt; AddHandler(NamesChangedEvent, value); remove =&gt; RemoveHandler(NamesChangedEvent, value); } /// &lt;summary&gt; /// Raises the NamesChanged event. /// &lt;/summary&gt; /// &lt;param name="args"&gt;Arguments associated with the NamesChanged event.&lt;/param&gt; protected virtual void OnNamesChanged(RoutedPropertyChangedEventArgs&lt;ObservableCollection&lt;string&gt;&gt; args) { RaiseEvent(args); } /// &lt;summary&gt; /// The property changed event /// &lt;/summary&gt; public event PropertyChangedEventHandler PropertyChanged; /// &lt;summary&gt; /// Raises the property changed event /// &lt;/summary&gt; /// &lt;param name="property"&gt;The property name&lt;/param&gt; public void RaisePropertyChanged(string property) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(property)); } } } </code></pre>
[]
[ { "body": "<p>Without running the code myself, it seems you've done a pretty good job. There are just a couple things I would point out:</p>\n<h1><code>Names</code> Default Value</h1>\n<p>Your dependency property for <code>Names</code> is declared as follows:</p>\n<pre><code> public static readonly DependencyProperty NamesProperty =\n DependencyProperty.Register(\n &quot;Names&quot;,\n typeof(ObservableCollection&lt;string&gt;),\n typeof(NameLister),\n new FrameworkPropertyMetadata(\n new ObservableCollection&lt;string&gt; (),\n OnNamesChanged, \n CoerceStrings));\n</code></pre>\n<p>I'd like to draw your attention to the line <code>new ObservableCollection&lt;string&gt; ()</code> and then show you this quote from Microsoft's documentation on <a href=\"https://docs.microsoft.com/en-us/dotnet/framework/wpf/advanced/collection-type-dependency-properties#initializing-the-collection-beyond-the-default-value\" rel=\"nofollow noreferrer\">Collection-Type Dependency Properties</a>:</p>\n<blockquote>\n<p>If your property is a reference type, the default value specified in dependency property metadata is not a default value per instance; instead it is a default value that applies to all instances of the type. Therefore you must be careful to not use the singular static collection defined by the collection property metadata as the working default value for newly created instances of your type. Instead, you must make sure that you deliberately set the collection value to a unique (instance) collection as part of your class constructor logic. Otherwise you will have created an unintentional singleton class.</p>\n</blockquote>\n<p>That might be a bit to digest, so to simplify: If you set a default value for a collection in the dependency property metadata, that default collection will be shared by <em>all</em> instances of the class (like a static property). Instead, you need to leave the default in the metadata as <code>null</code> and set property in the class's constructor.</p>\n<h1><code>Names</code> Type</h1>\n<p>To answer your question, I don't necessarily see a problem with you using <code>ObservableCollection&lt;string&gt;</code>, except that a popular general rule is <a href=\"https://enterprisecraftsmanship.com/posts/return-the-most-specific-type/\" rel=\"nofollow noreferrer\">&quot;Return the most specific type, accept the most generic type&quot;</a>.</p>\n<p>If we're treating <code>Names</code> as sort of an &quot;input property&quot;, then we would want it to be the most general type possible, which would probably be <code>IEnumerable&lt;string&gt;</code>. You would then check in <code>OnNamesChanged</code> whether the new value of the property implemented <code>INotifyCollectionChanged</code> and if so attach the appropriate event handler. If you take this approach, I would recommend taking inspiration from the <code>ItemsControl</code> class, specifically the <code>ItemsSource</code> property, since it does the same basic action of taking a bound collection and using it. You can find the actual source code for <code>ItemsControl</code> <a href=\"https://referencesource.microsoft.com/#PresentationFramework/src/Framework/System/windows/Controls/ItemsControl.cs\" rel=\"nofollow noreferrer\">here</a> which you can use to see how Microsoft went about implementing it.</p>\n<p>On the other hand, implementing something like that takes considerably more work, and you might very well want to <em>require</em> an <code>ObservableCollection&lt;string&gt;</code> based how your control is intended to be used. In either case, leaving it as is should be fine as far as I'm concerned.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-16T18:11:04.933", "Id": "235740", "ParentId": "232327", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-13T15:06:53.587", "Id": "232327", "Score": "4", "Tags": [ "c#", ".net", "wpf" ], "Title": "WPF Custom Control with a Single ObservableCollection DependencyProperty" }
232327
<p>I made this code to calculate pi using MonteCarlo method.</p> <p>I'm also learning how do Java threadpools and multithreading work.</p> <p>Can you tell me if this method is thread-safe and how can I improve it if there is a deadlock chance.</p> <pre><code>private volatile boolean waiting = false; private int reqsamples = 10000; private int samples = 0; private void job(){ while(samples &lt; reqsamples &amp;&amp; started){ // This lock is used to safely get arraylist data (points). if(lock.tryLock()){ try { // Montecarlo algorithm double x = 500 * random.nextDouble(); double y = 500 * random.nextDouble(); double dist = Math.hypot(x, y); if(dist &lt; 500) innersamples++; else outersamples++; points.add(new Point((int) x, (int) y)); } finally { // Now it is possible to safely get arraylist data. lock.unlock(); } samples++; if(sampledelay &gt; 0){ // here I use a scheduled thread pool to avoid Thread.sleep() // I don't know if it is safe to use Thread.sleep() here // instead of all of this code, because I know that // calling Thread.sleep() in a loop isn't that good timersvc.schedule(() -&gt; { synchronized(waitlock){ // EDIT: Here I wasn't using do-while // It was causing a deadlock :( do //that's another lock waitlock.notifyAll(); while(!waiting); waiting = false; } }, (long)(sampledelay * 1000000), TimeUnit.NANOSECONDS); synchronized(waitlock){ try { waiting = true; waitlock.wait(); } catch (InterruptedException ex) { } } } } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-13T17:31:46.207", "Id": "453648", "Score": "1", "body": "A relatively minor quibble, Monte Carlo doesn't calculate PI it estimates the value of PI." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-14T06:36:00.387", "Id": "453710", "Score": "2", "body": "We can not tell. The function relies on variables (and code) that you left out." } ]
[ { "body": "<p>As has been said in the comments, there are bits missing here for a full answer.... however some general feedback. I'm assuming that the <code>job</code> method will be running on multiple threads.</p>\n\n<p><strong>samples</strong></p>\n\n<p>How important is it that the number of samples collected is exactly <code>reqsamples</code>? If it's important then you need to protect <code>samples</code>. As it stands, it's possible (although fairly unlikely) that a thread would unlock <code>lock</code> just as another thread enters the while loop, having checked the value of <code>samples</code>. This would result in an extra sample being created and added to <code>points</code>. It's also worth mentioning that <code>sample++</code> isn't guaranteed to be threadsafe. If you're not going to protect it, it may be worth considering using <code>AtomicInteger</code>.</p>\n\n<p><strong>trylock</strong></p>\n\n<p>I don't really see the advantage of using <code>trylock</code> here, over just using <code>lock</code>. If you fail to get the lock, you're simply spinning checking if enough samples have been generated / it's been shutdown. This seems like wasted cycles that could be used elsewhere.</p>\n\n<p><strong>minimise locked time</strong></p>\n\n<p>In general, I try to keep the amount of work that's done within locks to a minimum. Sometimes that might mean doing a bit of extra work that's wasted but the net result can be beneficial. So, for example the generation of the <code>x</code>/<code>y</code> values and <code>dist</code> don't really need to be done during protected processing.</p>\n\n<p><strong>schedule vs sleep</strong></p>\n\n<p>I think the aversion to putting sleeps in loops is that it suggests that you're polling / performing an operation that might be handled better in another way. Looking at the code you've written, you're essentially replacing sleep with your own more complicated implementation of it. I don't see a benefit over using sleep here at all.</p>\n\n<p><strong>sampledelay</strong></p>\n\n<p>So, on the face of it, it looks like <code>sampledelay</code> is supposed to be how long to wait before generating the next sample. This would be fine if only one thread is running the <code>job</code> method. However, if you've got multiple threads running it, then the behaviour is going to be somewhat unpredictable since it's really telling each thread how long to wait before it starts trying to create the next sample (which might mean that multiple threads generate a sample close to each other, then they all wait for <code>sampledelay</code> then you get another batch of samples). This may(not) be what you're expecting. For the below, I'll assume that it is...</p>\n\n<p><strong>Tweaked version</strong></p>\n\n<p>Putting it together, you might end up with some code more like this:</p>\n\n<pre><code>private void job() {\n // Keep looping until we're done\n while (samples.get() &lt; reqsamples &amp;&amp; started) {\n // Generate the sample information outside the lock,\n // worst case each thread discards one.\n double x = 500 * random.nextDouble();\n double y = 500 * random.nextDouble();\n\n double dist = Math.hypot(x, y);\n Point newPoint = new Point((int) x, (int) y);\n\n try {\n lock.lock();\n // Now that we have the lock, check if we still need to actually\n // use our sample\n if (samples.get() &lt; reqsamples &amp;&amp; started) {\n points.add(newPoint);\n\n samples.incrementAndGet();\n if (dist &lt; 500) innersamples++;\n else outersamples++;\n }\n } finally {\n lock.unlock();\n }\n\n // Only need to sleep if we're not done already\n if (sampledelay &gt; 0 &amp;&amp; (samples.get() &lt; reqsamples &amp;&amp; started)) {\n try {\n Thread.sleep(sampledelay * 1000);\n } catch (InterruptedException ex) {\n }\n }\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-15T13:42:23.247", "Id": "235663", "ParentId": "232329", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-13T15:29:39.470", "Id": "232329", "Score": "-1", "Tags": [ "java", "multithreading", "thread-safety" ], "Title": "Calculating the value of Pi with Monte Carlo" }
232329
<p>I solved the Advent of Code problems last year in Python, and I wanted to learn a new language this year, so I decided to write up Part 1 of on of the hardest problems from last year - <a href="https://adventofcode.com/2018/day/15" rel="nofollow noreferrer">problem 15</a> - in Rust.</p> <p>While the problem in all its particulars is quite difficult to understand fully, the basic idea is quite simple: each <code>Unit</code> (with two teams: <code>G</code>, the <code>Goblins</code>, and <code>E</code>, the <code>Elves</code>) is present on a <code>CombatGrid</code>. Every single turn, they check if there's an enemy unit adjacent to them (where diagonal doesn't count as adjacent). If so, they attack that unit, reducing their HP. If not, they move using a weird and kind of fussy algorithm that boils down to BFS, and then proceed to attack if they're <em>now</em> in range of an enemy unit after moving. If not, they end their turn. This goes on until every unit of a particular team is dead.</p> <p>As far as I can tell, this program is 100% correct in all its particulars - it produced the correct answer for my input and some others I tested. It uses BFS to calculate the correct moves for each unit, which I think is an appropriate enough algorithm, and it's definitely fast enough for the problem's needs.</p> <p>What I'm really looking for review on is making this code more idiomatic, since I basically just read the Rust book and winged my way through writing this code. I'm not sure about the fact that I have to derive Copy and/or Clone for many of these types, it feels a bit &quot;cheaty&quot;, and the structure of the code is also a little more awkward than it feels like it needs to be, but fighting with the borrow checker means some difficulty in correcting that problem.</p> <pre><code>use std::env; use std::fs; use std::fmt; use std::error::Error; use std::collections::BinaryHeap; use hashbrown::HashMap; use std::cmp::{Ordering, Reverse}; use unit::*; pub fn main() -&gt; Result&lt;(), Box&lt;dyn Error&gt;&gt; { let args = env::args().collect::&lt;Vec&lt;String&gt;&gt;(); let input_filename = match args.len() { 2 =&gt; &amp;args[1], _ =&gt; &quot;input.txt&quot; }; let string_grid = fs::read_to_string(input_filename)?; let mut combat_grid = parse_input(&amp;string_grid)?; let mut full_rounds: usize = 0; println!(&quot;Start&quot;); print!(&quot;{}&quot;, combat_grid); println!(&quot;\n&quot;); while combat_grid.tick() { full_rounds += 1; println!(&quot;\n&quot;); println!(&quot;Round {}&quot;, full_rounds); print!(&quot;{}&quot;, combat_grid); println!(&quot;\n&quot;); } println!(&quot;Final&quot;); print!(&quot;{}&quot;, combat_grid); println!(&quot;\n&quot;); println!(&quot;Outcome: {}&quot;, full_rounds * combat_grid.units.values().map(|u| u.hp).sum::&lt;usize&gt;()); Ok(()) } pub fn parse_input(string_grid: &amp;str) -&gt; Result&lt;CombatGrid, String&gt; { let mut grid = HashMap::new(); let mut units = HashMap::new(); let mut dimensions = (0, 0); for (y, row) in string_grid.lines().enumerate() { dimensions.1 += 1; for (x, character) in row.chars().enumerate() { dimensions.0 += 1; let current_location = Location { x, y }; grid.insert(current_location, match character { '#' =&gt; Environment::Wall, '.' =&gt; Environment::Open, 'G' | 'E' =&gt; { units.insert(current_location, Unit { team: if character == 'G' { UnitTeam::Goblin } else { UnitTeam::Elf }, location: current_location, hp: 200, attack_power: 3 }); Environment::Open }, _ =&gt; { return Err(format!(&quot;Invalid input character: {}&quot;, character)); } }); } } dimensions.0 /= dimensions.1; Ok(CombatGrid { grid, units, dimensions }) } #[derive(Eq, PartialEq, Copy, Clone, Hash)] pub struct Location { x: usize, y: usize } impl Location { fn adjacent(&amp;self) -&gt; [Self; 4] { [ Location { x: self.x, y: self.y - 1 }, Location { x: self.x, y: self.y + 1 }, Location { x: self.x - 1, y: self.y }, Location { x: self.x + 1, y: self.y } ] } } impl fmt::Debug for Location { fn fmt(&amp;self, f: &amp;mut fmt::Formatter&lt;'_&gt;) -&gt; fmt::Result { write!(f, &quot;({}, {})&quot;, self.x, self.y) } } impl Ord for Location { fn cmp(&amp;self, other: &amp;Self) -&gt; Ordering { self.y.cmp(&amp;other.y).then(self.x.cmp(&amp;other.x)) } } impl PartialOrd for Location { fn partial_cmp(&amp;self, other: &amp;Self) -&gt; Option&lt;Ordering&gt; { Some(self.cmp(other)) } } pub struct CombatGrid { pub grid: HashMap&lt;Location, Environment&gt;, pub units: HashMap&lt;Location, Unit&gt;, pub dimensions: (usize, usize), } impl fmt::Display for CombatGrid { fn fmt(&amp;self, f: &amp;mut fmt::Formatter&lt;'_&gt;) -&gt; fmt::Result { for y in 0..self.dimensions.1 { let mut row_units = Vec::new(); for x in 0..self.dimensions.0 { let location = Location { x, y }; if let Some(unit) = self.units.get(&amp;location) { write!(f, &quot;{:?}&quot;, unit.team)?; row_units.push(unit); } else if let Some(env) = self.grid.get(&amp;location) { write!(f, &quot;{:?}&quot;, env)?; } } write!(f, &quot;\t&quot;)?; for unit in row_units { write!(f, &quot; [{:?}] &quot;, unit)?; } writeln!(f)?; } Ok(()) } } impl CombatGrid { pub fn tick(&amp;mut self) -&gt; bool { let mut unit_locations = self.units.keys().cloned().collect::&lt;Vec&lt;_&gt;&gt;(); unit_locations.sort_unstable(); for unit_location in unit_locations.iter() { // This unit may have since died by the hands of another // by the time we have gotten to it, so check if it's still there. let unit = match self.units.get(unit_location) { Some(unit) =&gt; unit.clone(), None =&gt; continue }; let enemy_units = self.units .iter() .filter(|(_, u)| u.is_enemy(&amp;unit)) .map(|(l, u)| (*l, u.clone())) .collect::&lt;HashMap&lt;_, _&gt;&gt;(); if enemy_units.is_empty() { return false; // Combat has ended, one team has won. } if let Some(attacked_unit_location) = unit.maybe_attack(&amp;enemy_units) { self.attack_unit(unit_location, &amp;attacked_unit_location); continue; } if let Some(move_location) = unit.maybe_move(&amp;enemy_units, |l| self.is_open_fn(l)) { // Get the new Unit with the updated location. The old reference is stale // otherwise, leading to attack behaviour based on the old location, which never // actually works out, because the only reason any unit moves is because its // old location is not adjacent to any enemy unit. let unit = self.move_unit(unit_location, &amp;move_location); if let Some(attacked_unit_location) = unit.maybe_attack(&amp;enemy_units) { self.attack_unit(&amp;move_location, &amp;attacked_unit_location); } } } true } fn attack_unit(&amp;mut self, current_unit_location: &amp;Location, attacked_unit_location: &amp;Location) { let current_unit = &amp;self.units[current_unit_location].clone(); let mut attacked_unit = self.units.get_mut(attacked_unit_location).unwrap(); // This protects against overflows in the usize attacked_unit.hp = attacked_unit.hp.saturating_sub(current_unit.attack_power); if attacked_unit.is_dead() { self.units.remove(attacked_unit_location); } } fn move_unit(&amp;mut self, current_unit_location: &amp;Location, new_location: &amp;Location) -&gt; Unit { let new_location = *new_location; let mut current_unit = self.units.remove(current_unit_location).unwrap(); current_unit.location = new_location; self.units.insert(new_location, current_unit.clone()); current_unit } fn is_open_fn(&amp;self, location: &amp;Location) -&gt; bool { if self.units.contains_key(location) { false } else if let Some(env) = self.grid.get(location) { env == &amp;Environment::Open } else { false } } } #[derive(Eq, PartialEq)] pub enum Environment { Wall, Open } impl fmt::Debug for Environment { fn fmt(&amp;self, f: &amp;mut fmt::Formatter&lt;'_&gt;) -&gt; fmt::Result { write!(f, &quot;{}&quot;, if self == &amp;Self::Wall { '#' } else { '.' }) } } mod unit { use super::*; #[derive(Eq, PartialEq, Copy, Clone)] pub enum UnitTeam { Goblin, Elf } impl fmt::Debug for UnitTeam { fn fmt(&amp;self, f: &amp;mut fmt::Formatter&lt;'_&gt;) -&gt; fmt::Result { write!(f, &quot;{}&quot;, if self == &amp;Self::Elf { 'E' } else { 'G' }) } } #[derive(Eq, PartialEq, Clone)] pub struct Unit { pub team: UnitTeam, pub location: Location, pub hp: usize, pub attack_power: usize } impl fmt::Debug for Unit { fn fmt(&amp;self, f: &amp;mut fmt::Formatter&lt;'_&gt;) -&gt; fmt::Result { write!(f, &quot;{:?}({}) @ {:?}&quot;, self.team, self.hp, self.location) } } impl Unit { pub fn is_enemy(&amp;self, other: &amp;Self) -&gt; bool { self.team != other.team } pub fn is_dead(&amp;self) -&gt; bool { self.hp == 0 } pub fn maybe_attack(&amp;self, enemy_units: &amp;HashMap&lt;Location, Unit&gt;) -&gt; Option&lt;Location&gt; { let mut adjacent_enemy_units = enemy_units .values() .filter(|u| self.location.adjacent().contains(&amp;u.location)) .collect::&lt;Vec&lt;_&gt;&gt;(); adjacent_enemy_units.sort_unstable_by(|a, b| { match a.hp.cmp(&amp;b.hp) { Ordering::Equal =&gt; a.location.cmp(&amp;b.location), hp_cmp =&gt; hp_cmp } }); adjacent_enemy_units.reverse(); adjacent_enemy_units.pop().map(|u| u.location) } pub fn maybe_move( &amp;self, enemy_units: &amp;HashMap&lt;Location, Unit&gt;, is_open_fn: impl Fn(&amp;Location) -&gt; bool ) -&gt; Option&lt;Location&gt; { let mut frontier = self.location.adjacent() .iter() .cloned() .filter(|l| is_open_fn(l)) .map(|l| Reverse(SearchNode { distance: 1, current_location: l, starting_location: l, })) .collect::&lt;BinaryHeap&lt;_&gt;&gt;(); let mut explored: Vec&lt;Location&gt; = Vec::new(); while let Some(Reverse(next)) = frontier.pop() { for next_adjacent in next.current_location.adjacent().iter().cloned() { if explored.contains(&amp;next_adjacent) { continue; } if !is_open_fn(&amp;next_adjacent) { if enemy_units.contains_key(&amp;next_adjacent) { return Some(next.starting_location); } continue; } frontier.push(Reverse(SearchNode { distance: next.distance + 1, current_location: next_adjacent, starting_location: next.starting_location })); explored.push(next_adjacent); } } None } } // Private helper to make maybe_move easier to keep track of #[derive(Debug, Eq, PartialEq, Copy, Clone)] struct SearchNode { distance: usize, current_location: Location, starting_location: Location, } impl Ord for SearchNode { fn cmp(&amp;self, other: &amp;Self) -&gt; Ordering { self.distance.cmp(&amp;other.distance).then( self.current_location.cmp(&amp;other.current_location).then( self.starting_location.cmp(&amp;other.starting_location) ) ) } } impl PartialOrd for SearchNode { fn partial_cmp(&amp;self, other: &amp;Self) -&gt; Option&lt;Ordering&gt; { Some(self.cmp(&amp;other)) } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-13T17:12:18.837", "Id": "453646", "Score": "3", "body": "I originally wanted to ask you to add the challenge description to the question, but damn ..., that's a long read ;-)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-14T07:13:17.983", "Id": "453715", "Score": "2", "body": "@AlexV I added a simple problem description to help alleviate the issue, since I'm not asking for improvements to the algorithm or the logic, but simply the idiomaticity of it." } ]
[ { "body": "<p>The code look good. Here's some nitpicks:</p>\n<h1><code>rustfmt</code></h1>\n<p>First of all, I ran <code>cargo fmt</code> on your code. There were some\ndifferences (trailing comma, linebreaks, etc.).</p>\n<h1><code>anyhow</code></h1>\n<p>Consider changing the return type of all functions to use\n<a href=\"https://docs.rs/anyhow/1.0/anyhow/type.Result.html\" rel=\"nofollow noreferrer\"><code>anyhow::Result</code></a>, which provides contexts and backtracks.</p>\n<pre><code>return Err(format!(&quot;Invalid input character: {}&quot;, character));\n</code></pre>\n<p>can be simplified to</p>\n<pre><code>bail!(&quot;Invalid input character: {}&quot;, character);\n</code></pre>\n<h1>Matching on <code>enum</code>s with two variants</h1>\n<p>For <code>enum</code>s with two variants, it is probably clearer to write</p>\n<pre><code>if self == &amp;Self::Wall { '#' } else { '.' }\n</code></pre>\n<p>as</p>\n<pre><code>match self {\n Self::Wall =&gt; '#',\n Self::Open =&gt; '.',\n}\n</code></pre>\n<h1><code>sort_unstable_by_key</code></h1>\n<pre><code>adjacent_enemy_units.sort_unstable_by(|a, b| match a.hp.cmp(&amp;b.hp) {\n Ordering::Equal =&gt; a.location.cmp(&amp;b.location),\n hp_cmp =&gt; hp_cmp,\n});\n</code></pre>\n<p>can be written as</p>\n<pre><code>adjacent_enemy_units.sort_unstable_by_key(|unit| (unit.hp, unit.location));\n</code></pre>\n<h1><code>FnMut</code></h1>\n<p><code>FnMut</code> is more general than <code>Fn</code>, and can be used in the signature of\n<code>maybe_move</code>:</p>\n<pre><code>pub fn maybe_move(\n &amp;self,\n enemy_units: &amp;HashMap&lt;Location, Unit&gt;,\n is_open_fn: impl Fn(&amp;Location) -&gt; bool,\n) -&gt; Option&lt;Location&gt; {\n</code></pre>\n<h1><code>derive</code></h1>\n<pre><code>impl Ord for SearchNode {\n fn cmp(&amp;self, other: &amp;Self) -&gt; Ordering {\n self.distance.cmp(&amp;other.distance).then(\n self.current_location\n .cmp(&amp;other.current_location)\n .then(self.starting_location.cmp(&amp;other.starting_location)),\n )\n }\n}\n\nimpl PartialOrd for SearchNode {\n fn partial_cmp(&amp;self, other: &amp;Self) -&gt; Option&lt;Ordering&gt; {\n Some(self.cmp(&amp;other))\n }\n}\n</code></pre>\n<p>These implementations are equivalent to the automatic versions, so use\n<code>derive</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-09T03:40:02.013", "Id": "247662", "ParentId": "232333", "Score": "4" } } ]
{ "AcceptedAnswerId": "247662", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-13T16:06:00.490", "Id": "232333", "Score": "9", "Tags": [ "beginner", "programming-challenge", "rust" ], "Title": "Advent of Code 2018 day 15 - Naive Rust program" }
232333
<h2>Background</h2> <p>A request (<code>req</code> in the code) is made to my server, and a response (<code>res</code>) returned. By the time the response has filtered through to the code below, most of the heavy lifting - looking up entries in a database, etc - has already been done. This code just puts some final tweaks <strong>on all responses</strong> before it's pushed out to the user's browser.</p> <h2>What This Code Does</h2> <p>More specifically, the code achieves three things:</p> <ul> <li>A time stamp is added to the footer of the page.</li> <li>The crude kind of apostrophes are transmuted into the prettier, curlier kind. (This is more important in some fonts than in others.)</li> <li><code>--</code> and <code>---</code> are transmuted into en and em dashes respectively.</li> </ul> <h2>Entry Point</h2> <p>This code is fired only when code in another file calls <code>finaliser.protoRender(req, res, view, properties);</code>. So the <code>protoRender</code> method is the only entry point; it's also the only exit.</p> <h2>The Code</h2> <pre><code>/* This code contains a class which handles any final, universal touches to the page before it's passed to the browser. */ // The class in question. class Finaliser { constructor() { } // Ronseal. static fixApostrophes(input) { while(input.indexOf("``") &gt;= 0) { input = input.replace("``", "&amp;ldquo;"); } while(input.indexOf("''") &gt;= 0) { input = input.replace("''", "&amp;rdquo;"); } while(input.indexOf("`") &gt;= 0) { input = input.replace("`", "&amp;lsquo;"); } while(input.indexOf("'") &gt;= 0) { input = input.replace("'", "&amp;rsquo;"); } return input; } // Ronseal. static fixDashes(input) { while(input.indexOf("---") &gt;= 0) { input = input.replace("---", "&amp;mdash;"); } while(input.indexOf("--") &gt;= 0) { input = input.replace("--", "&amp;ndash;"); } return input; } // Render, and deliver the page to the browser. protoRender(req, res, view, properties) { var date = new Date(); properties.footstamp = date.toISOString(); res.render(view, properties, function(err, html){ if(html === undefined) { res.render(view, properties); } else { html = Finaliser.fixApostrophes(html); html = Finaliser.fixDashes(html); res.send(html); } }); } } // Exports. module.exports = Finaliser; </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-14T09:54:07.187", "Id": "453735", "Score": "1", "body": "Is there a specific reason you are using HTML entities? Unless you are not delivering UTF-8 (which you should be) you can just use the literal Unicode characters. Why don't your original texts use the proper characters directly?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-14T11:30:14.370", "Id": "453751", "Score": "0", "body": "It's mostly a matter of personal taste. I've heard enough horror stories about programmers getting muddled up between `'` and `’`; `&rsquo;` is unamiguous (at least to me!). Both the HTML templates and the database entries lack the literal characters - and will continue to lack them unless you can point me to a convenient way of touch-typing them using a standard keyboard." } ]
[ { "body": "<p><strong><em>Ways of improving/optimizations:</em></strong></p>\n\n<p>What <code>fixApostrophes</code> and <code>fixDashes</code> functions actually try to do is replacing a specific punctuation chars with respective HTML entities.<br>\nInstead of those numerous horrifying <code>while</code> loops - a more optimized, concise and extendable approach would be to:</p>\n\n<ul>\n<li><p>compose a predefined <em>replacement map</em> (where keys are <em>search patterns</em> and values - respective <em>entities values</em>):</p>\n\n<pre><code>const replaceMap = {\"``\": \"&amp;ldquo;\", \"''\": \"&amp;rdquo;\", \"`\": \"&amp;lsquo;\",\n \"'\": \"&amp;rsquo;\", \"---\": \"&amp;mdash;\", \"--\": \"&amp;ndash;\"};\n</code></pre></li>\n<li><p>perform all the replacements at once\nwith <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace\" rel=\"nofollow noreferrer\"><code>String.replace</code></a> function based on combined regex pattern:</p>\n\n<pre><code>input = input.replace(new RegExp(Object.keys(replaceMap).join('|'), 'g'), function(m){\n return replaceMap[m] || m;\n}); \n</code></pre>\n\n<p>where <code>Object.keys(replaceMap).join('|')</code> is used to compose <em>regex alternation group</em> from <code>replaceMap</code> keys like <code>''|'|---|--</code></p></li>\n<li><p>the former 2 functions can be conceptually combined into a single function called, say <strong><code>punctToEntities</code></strong> (<em>\"punctuations to entities\"</em>)</p></li>\n</ul>\n\n<p>Eventually, the <code>Finaliser</code> class would look as:</p>\n\n<pre><code>const replaceMap = {\"``\": \"&amp;ldquo;\", \"''\": \"&amp;rdquo;\", \"`\": \"&amp;lsquo;\",\n \"'\": \"&amp;rsquo;\", \"---\": \"&amp;mdash;\", \"--\": \"&amp;ndash;\"};\n\nclass Finaliser\n{\n constructor()\n {\n\n }\n\n static punctToEntities(input) {\n /** Converts punctuation chars to respective HTML entities **/\n input = input.replace(new RegExp(Object.keys(replaceMap).join('|'), 'g'), function(m){\n return replaceMap[m] || m;\n }); \n\n return input;\n }\n\n // Render, and deliver the page to the browser.\n protoRender(req, res, view, properties) {\n var date = new Date();\n\n properties.footstamp = date.toISOString();\n res.render(view, properties, function(err, html){\n if (html === undefined) {\n res.render(view, properties);\n } else {\n html = Finaliser.punctToEntities(html);\n res.send(html);\n }\n });\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-14T09:44:06.833", "Id": "453733", "Score": "1", "body": "Why use a template literal? Just use `new RegExp(Object.keys(replaceMap).join('|'), 'g')`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-14T09:56:43.603", "Id": "453738", "Score": "1", "body": "@RoToRa, correct. That's because I was starting reasoning that approach as ``( ${Object.keys(replaceMap).join('|')})`` (enclosed with braces) but forgot to simplify it at the end. Thanks, see my update" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-14T11:33:44.097", "Id": "453752", "Score": "1", "body": "Thank you! I always felt, intuitively, that the `while` loops were somehow unholy, but I couldn't think of a better way of achieving the same result. Now I know. I'll be implementing your suggestions." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-14T11:40:05.130", "Id": "453753", "Score": "1", "body": "@TomHosker, you're welcome!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-19T13:12:08.260", "Id": "454349", "Score": "1", "body": "@TomHosker, it's great that you sense that `while` (or in fact, `for` loops) are very often not the best approach (especially for readability). I think you'll find the following very helpful. The learnings are actually little to do with RxJs, and more to do with learning a more functional, declarative approach: http://reactivex.io/learnrx/" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-13T17:53:44.050", "Id": "232341", "ParentId": "232335", "Score": "4" } }, { "body": "<p><em>(Extension of my comment above)</em></p>\n\n<p>It would be a better idea to use literal Unicode rather than HTML entities. The advantage of Unicode characters is that they are usable universally and not only when outputting HTML. If you don't like the literal characters in the source code, or find them hard them to read, then you can use JavaScript escape sequences with the hex Unicode. For example: <code>\"“\" === \"\\u201C\"</code>. Additionally you can define a constant with a readable name: <code>const LEFT_DOUBLE_QUOTES = \"\\u201C\";</code> or/and do what one always should do if the code is difficult to read and there are no better option: Use comments.</p>\n\n<p>There is nothing to say against using placeholders/markup like this for input, however conversion should happen earlier and not as the last thing. </p>\n\n<p>In case of data stored in the database, if you have a front-end for editing the data in the database, then have that front-end convert the text and store the converted text in the database.</p>\n\n<p>Or this could be done in the HTML templates or even by the template engines themselves by having helper functions, plugins or extensions. That way you can avoid, what I see as the biggest danger when doing globally as the last step: Converting things that shouldn't be converted, such as empty HTML attributes or comments.</p>\n\n<p><code>&lt;input value=''&gt;</code> &rarr; <code>&lt;input value=&amp;rdquo;&gt;</code></p>\n\n<p><code>&lt;!-- comment --&gt;</code> &rarr; <code>&lt;!&amp;ndash; comment &amp;ndash;&gt;</code></p>\n\n<p>BTW, there is another problem with the placeholders you have chosen: ambiguity. <code>'''</code> could mean either <code>&amp;rdquo;&amp;rsquo;</code> or <code>&amp;rsquo;&amp;rdquo;</code>.</p>\n\n<p>Finally: There are keyboard layouts that have typographical quotes. And there are macro programs that, for example, allow you to define abbreviations or key combinations that could output quotes or other characters, and text editors/IDE also often have a such mechanism built in.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-14T17:35:12.997", "Id": "453816", "Score": "0", "body": "You make some fascinating points - particularly regarding the handling of HTML comments. If I could accept two different answers, I would!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-14T13:57:22.057", "Id": "232382", "ParentId": "232335", "Score": "1" } } ]
{ "AcceptedAnswerId": "232341", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-13T16:29:39.200", "Id": "232335", "Score": "4", "Tags": [ "javascript", "node.js", "express.js" ], "Title": "A JavaScript class, which finalises the HTML of each page of my NodeJS (Express) website" }
232335
<p>I'm a hobbist trying to become a professional software developer. I do have a lot interest in Data Science in general and my goal is to master Python before diging deeper into specific data science topics.</p> <p>I created this game when I started studying object oriented programming. Thank you all in advance.</p> <pre><code>import os import getpass class Hangman: winner = False word = '' mask = '' mistakes = [] def __init__(self, word): self.word = word self.mask = '_ ' * len(word) def make_move(self, letter): letter_match = self.word.find(letter) if letter_match &gt;= 0: for i, w in enumerate(self.word): if w == letter: new_mask = list(self.mask) new_mask[i * 2] = letter self.mask = ''.join(new_mask) self.check_winner() else: self.mistakes.append(letter) print('Wrong!') def check_winner(self): if self.mask.find('_') &lt; 0: self.show_board() print('You won!') self.winner = True return self.winner def check_looser(self): if len(self.mistakes) &gt; 4: print('You loose! The word was %s' % self.word) quit() def show_board(self): os.system('cls') print(self.mask) print(self.mistakes) def play(self): while not self.winner: self.show_board() letter_input = input('Choose a letter: ').upper() self.make_move(letter_input) self.check_looser() secret_input = getpass.getpass('Secret Word: ').upper() game = Hangman(secret_input) game.play() </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-13T17:32:28.240", "Id": "453649", "Score": "1", "body": "You should elaborate a bit more about your code, what decisions you made and why, to get better reviews." } ]
[ { "body": "<p>It might be slightly cleaner and more performant to keep <code>self.mask</code> as a list, and just <code>join</code> it before printing:</p>\n\n<pre><code># Basically what you had before, without the space\n# Just \"list multiplication\" instead of \"string multiplication\"\nself.mask = ['_'] * len(word)\n\n. . .\n\nif w == letter:\n mask[i] = letter\n\n. . .\n\nif '_' not in self.mask:\n self.show_board()\n print('You won!')\n\n. . .\n\nprint(' '.join(self.mask))\n</code></pre>\n\n<p>Now there's less converting back and forth between strings and lists. This also saves you from needing to do <code>i * 2</code>. The spaces can just be added in using <code>join</code> before being printed, so you don't need to worry about them.</p>\n\n<hr>\n\n<p><code>print(self.mistakes)</code> currently prints out a normal list representation to the end user without any context. I'd probably prefix a message to that, and format it a bit before printing:</p>\n\n<pre><code>print(f\"Already tried: {', '.join(self.mistakes)}\")\n# Already tried: R, Q\n</code></pre>\n\n<hr>\n\n<p>I'd probably get rid of <code>self.winner</code> and change how you're checking for winning. Notice what you're using it for: you assign it in <code>check_winner</code>, then return that same value that you just assigned, but never use the return value. I'd have <code>check_winner</code> just return the value, move the call to <code>check_winner</code> to after the call to <code>make_move</code>, and use the return value:</p>\n\n<pre><code>def check_winner(self):\n if '_' not in self.mask:\n self.show_board()\n print('You won!')\n return True\n\n return False\n\n. . .\n\ndef play(self):\n won = False # Just track this locally instead\n\n while not won:\n self.show_board()\n\n letter_input = input('Choose a letter: ').upper()\n self.make_move(letter_input)\n\n won = self.check_winner() # And assign it here\n self.check_loser()\n</code></pre>\n\n<p>I'd also probably change <code>check_loser</code> (As a heads up, it's spelled \"loser\". \"Looser\" means that one thing is \"less tight\" than something else). I'd maybe have it return a bool saying whether or not the player lost, and just return from that function instead. As I noted in a <a href=\"https://codereview.stackexchange.com/a/232211/46840\">previous review</a> (at the bottom), <code>quit</code> can cause problems when testing code. Just returning from the main loop to allow control to pass back to the REPL is much cleaner.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-14T16:56:40.080", "Id": "453811", "Score": "0", "body": "Impressive! Thank you so much" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-13T17:51:33.127", "Id": "232340", "ParentId": "232338", "Score": "1" } } ]
{ "AcceptedAnswerId": "232340", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-13T17:13:02.187", "Id": "232338", "Score": "2", "Tags": [ "python", "object-oriented", "hangman" ], "Title": "Object oriented hangman game" }
232338
<p>Consider the following code.</p> <pre><code>$car = (object)[ 'general' =&gt; [ 'interior' =&gt; [ 'seats' =&gt; 'destroyed' ] ] ]; $exteriorProperties = [ 'hood' =&gt; 'shiny', 'windows' =&gt; 'dirty' ]; foreach($exteriorProperties as $key =&gt; $prop){ $car-&gt;{'other'}-&gt;{'exterior'}-&gt;{$key} = $prop; } </code></pre> <p>This is a scenario where I'd like to add properties to an object, a few layers deep at a time, while iterating through some other data. If it doesn't exist, it will just create it, if it does it will override. PERFECT!</p> <p>Unfortunately, this will throw the warning:</p> <blockquote> <p>Creating default object from empty value</p> </blockquote> <p>I could resolve the issue by checking first if the property exists like so:</p> <pre><code>foreach($exteriorProperties as $key =&gt; $prop){ if(!isset($car-&gt;other)) $car-&gt;other = (object)[]; if(!isset($car-&gt;other-&gt;exterior)) $car-&gt;other-&gt;exterior = (object)[]; $car-&gt;other-&gt;exterior-&gt;{$key} = $prop; } </code></pre> <p>This is not my ideal solution. I'm wondering if there's a more elegant solution. Currently, I'm using this:</p> <pre><code>@$car-&gt;{'other'}-&gt;{'exterior'}-&gt;{$key} = $prop; </code></pre> <p>to suppress the warnings but I'm worried about compatibility in the future.</p> <p>Does anyone have a more elegant solution to this scenario?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-09-12T00:02:34.943", "Id": "488478", "Score": "0", "body": "Don't use arrays as the answer below suggest, use object properly. Arrays are only good for local code, shared outside a file or class means you are writing keys manually, having to remember them, miss one or two, typo. Good IDE with auto complete and objects with getter/setter are a happy dev world." } ]
[ { "body": "<p>Yes, use arrays.</p>\n\n<pre><code>$car = [\n 'general' =&gt; [\n 'interior' =&gt; [\n 'seats' =&gt; 'destroyed'\n ]\n ]\n];\n\n$exteriorProperties = [\n 'hood' =&gt; 'shiny',\n 'windows' =&gt; 'dirty'\n];\n\nforeach($exteriorProperties as $key =&gt; $prop){\n $car['other']['exterior'][$key] = $prop;\n}\n$car = (object) $car;\n</code></pre>\n\n<p>Anyway, the object conversion will only convert the outermost array. The nested arrays are still arrays.</p>\n\n<pre><code>\\is_array($car-&gt;general); // true\n</code></pre>\n\n<p>Why you need it to be shapeless objects anyway? Either define classes for those objects or treat them as arrays is the simple answer.</p>\n\n<p>Btw <code>$car-&gt;{'other'}</code> is really weird way of writing <code>$car-&gt;other</code>...</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-13T20:42:32.003", "Id": "453678", "Score": "0", "body": "I suppose you're right, I just hate getting locked into arrays all the time. The `$car->{'other'}` is because most of my property keys are coming from string variables. such as `$car->{$var1}->{$var2}`" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-13T20:30:42.923", "Id": "232350", "ParentId": "232342", "Score": "1" } }, { "body": "<p>Yes, you can avoid the iterated conditional operations by processing all data as arrays.</p>\n\n<p>Code: (<a href=\"https://3v4l.org/oG0t7\" rel=\"nofollow noreferrer\">Demo</a>)</p>\n\n<pre><code>$car = json_decode(\n json_encode(\n array_replace_recursive(\n (array)$car, \n ['other' =&gt; ['exterior' =&gt; $exteriorProperties]]\n )\n )\n);\n</code></pre>\n\n<p>When only coverting the top level from object-type to array-type you can just cast it with <code>(array)</code>. If you need to convert all levels -- json encode the whole object, then decode that string to an array. When you are done processing, use <code>json_</code> functions to revert the data to object-type.</p>\n\n<p>I still find this a little clunky (perhaps just as clunky as your conditional approach). The benefit in the above is in the recursion; if your data depth changes, you won't need to alter the processing script. Ask yourself if you <em>actually</em> need to use an object. If coding is simplified with a different data-type, perhaps have a rethink/refactor.</p>\n\n<p>P.s. DEFINITELY don't write the stfu operator (<code>@</code>) into your code. In nearly all implementations, the technique is avoidable (this is one of those cases) and projects with such syntax are categorized/presumed as low quality by knowledgeable developers.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-13T20:48:30.983", "Id": "453679", "Score": "0", "body": "Thanks, good assessment. I unfortunately could not choose anything but objects since a previous programmer has coded it as such." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-13T20:32:33.503", "Id": "232351", "ParentId": "232342", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-13T18:36:15.220", "Id": "232342", "Score": "1", "Tags": [ "php", "object-oriented", "array" ], "Title": "Creating default object from empty value in PHP?" }
232342
<p>I created snake as my first program with GUI, I didn't learn OOP yet, so my program has no classes. I know that I should use comments, I am sorry. </p> <p>Short instruction:<br> l - increase snake speed<br> k - decrease snake speed<br> space - pause/start/restart game it depends<br> a - turn snake left<br> d - turn snake right </p> <p>What can I improve?</p> <p>edit: Python version 3.6</p> <pre class="lang-py prettyprint-override"><code>from tkinter import * from random import randrange root = Tk() root.geometry('604x604+300+100') root.title('Snake') c = Canvas(root,bg='black', width=604, height=604, highlightthickness=0) c.pack() c.create_text(302, 250, font='Terminal 30 bold', text="Press space to start", fill='white') s = [] directions = [[-30,0],[0,-30],[30,0],[0,30]] which_direction = randrange(0,4) ap = [] run = True score = 0 speed = 50 score_board = '' pause_text = '' sp = '' def create_s_square(x, y): square = c.create_rectangle(x, y, x+30, y+30, fill='', outline='white') s.insert(0,square) def create_s(): for x in range(3): create_s_square(x=300,y=300) def s_move(): iswall() if run: for part in range(len(s)-1): c.coords(s[part],c.coords(s[part+1])) c.move(s[len(s)-1],directions[which_direction][0],directions[which_direction][1]) is_snake() if run: aple() c.after(speed*3+70,s_move) def is_snake(): for part in range(len(s)-1): if c.coords(s[part]) == c.coords(s[len(s)-1]): game_over() def iswall(): if (c.coords(s[len(s)-1])[0]+directions[which_direction][0]&gt;=600 or \ c.coords(s[len(s)-1])[1]+directions[which_direction][1]&gt;=600 or \ c.coords(s[len(s)-1])[0]+directions[which_direction][0]&lt;=-30 or \ c.coords(s[len(s)-1])[1]+directions[which_direction][1]&lt;=-30) and run: game_over() def aple(): global score x, y = randrange(0,600,30), randrange(0,600,30) if not ap: apple = c.create_rectangle(x+7,y+7,x+23,y+23, fill='', outline='white') ap.append(apple) ap_co = [c.coords(ap[0])[0]-7,c.coords(ap[0])[1]-7] if c.coords(s[len(s)-1])[:2] == ap_co: create_s_square(c.coords(s[0])[0],c.coords(s[0])[1]) c.delete(ap[0]) del ap[0] score += 1 score_counter() def score_counter(): global score_board c.delete(score_board) score_board = c.create_text(5, 25, font='Terminal 50 bold', text=str(score), fill='white', anchor=W) def game_over(): global run run = False c.create_text(302, 200, font='Terminal 50 bold', text='GAME OVER', fill='white') c.create_text(302, 260, font ='Terminal 25', text="Press space to restart", fill='white') root.bind('&lt;space&gt;', restart) def restart(_): global s, ap, run, which_direction, score root.bind('&lt;space&gt;', pause) c.delete(ALL) score = 0 score_counter() show_speed() s = [] ap = [] which_direction = randrange(0,4) create_s() run = True s_move() def pause(_): global run, pause_text if run == False: run = True c.delete(pause_text) c.after(speed*3+70,s_move) else: run = False pause_text = c.create_text(302, 250, font='Terminal 30 bold', text="Press space to resume", fill='white') def rotate_left(_): global which_direction if run: which_direction += 1 if which_direction == 4: which_direction = 0 def rotate_right(_): global which_direction if run: which_direction -= 1 if which_direction == -1: which_direction = 3 def show_speed(): global sp c.delete(sp) sp = c.create_text(10, 585, font='TimesNewRoman 10', text=f'speed: {100-speed}', fill='white', anchor=W) def increase_speed(_): global speed if speed &gt; 0: speed -= 1 show_speed() def decrease_speed(_): global speed if speed &lt; 100: speed += 1 show_speed() def start(_): global score_board root.bind('&lt;space&gt;', pause) root.bind('k',decrease_speed) root.bind('l',increase_speed) c.delete(ALL) score_counter() show_speed() root.bind('a',rotate_right) root.bind('d',rotate_left) create_s() s_move() root.bind('&lt;space&gt;',start) root.mainloop() </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-13T19:03:41.540", "Id": "453659", "Score": "3", "body": "Why does `increase_speed` decrease the speed and `decrease_speed` increase the speed? Edit: Ahh.. because `speed` is really a delay... and not a speed." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-13T19:35:48.360", "Id": "453663", "Score": "3", "body": "Oh, wow, this is some violent looking code. I'm glad you came over here." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-13T19:36:32.123", "Id": "453664", "Score": "3", "body": "For whoever is voting to close this for lack of context: care to elaborate? It's a snake game. The game has its own tag. This code looks like it will run out-of-the-box. What more do you want?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-13T19:37:06.177", "Id": "453665", "Score": "1", "body": "Having said that, could you share with us for what Python version you wrote this?" } ]
[ { "body": "<p>Let's start with readability. Without deducing from functionality, I have no idea what variables like <code>s</code> and <code>ap</code>, or what functions like <code>create_s()</code> and <code>s_move()</code> do. Use clear and obvious names; the common saying is that you would read a piece of code way more often than it is written, and it thus needs to be easy to understand---you might be surprised how little even your own code will make sense to you only days after having written it.</p>\n\n<p>You should also take care in how you set up lines, and sometimes more cases are worth it simply since they make it easier to follow what's happening. Your function here:</p>\n\n<pre><code>if (c.coords(s[len(s)-1])[0]+directions[which_direction][0]&gt;=600 or \\\n c.coords(s[len(s)-1])[1]+directions[which_direction][1]&gt;=600 or \\\n c.coords(s[len(s)-1])[0]+directions[which_direction][0]&lt;=-30 or \\\n c.coords(s[len(s)-1])[1]+directions[which_direction][1]&lt;=-30) and run:\n</code></pre>\n\n<p>takes a bit of effort to decipher.</p>\n\n<p>You also shouldn't use the same variable for different things, like this:</p>\n\n<pre><code>def create_s():\n for x in range(3):\n create_s_square(x=300,y=300)\n</code></pre>\n\n<p>where the <code>x</code> in your for loop has nothing to do with the square dimensions. Usually people would write <code>for _ in range(3):</code> here to show that we don't actually care about the index of the iterator.</p>\n\n<p>I think you should start looking at OOP pretty soon, but before that a glaring issue is that your functions all rely entirely on \"side-effects\"; they don't accept any arguments and they return nothing. You should stop using global variables and instead pass whatever variables you need between your functions. Global variables are almost always a bad idea.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-25T11:00:24.823", "Id": "239400", "ParentId": "232343", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-13T18:57:29.260", "Id": "232343", "Score": "6", "Tags": [ "python", "python-3.x", "snake-game" ], "Title": "Snake game in Python with tkinter" }
232343
<p>I am practicing w/ Python and wanted to code a simple Rock, Paper, Scissors game w/o any user input. I used a list to hold the values and randomly pulled them with a function. I used the the return value from the first function to print the response in the second function, along with the printed results. What are some alternative methods to achieve this same functionality and make this more efficient. Thank you. </p> <pre><code># Internal Rock, Paper Scissors Game &gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt; import random # List string values for the game r_p_s = [ 'Rock', 'Paper', 'Scissors' ] # Function to return random values from List def game(): return random.choice(r_p_s) + " vs. " + random.choice(r_p_s) result = game() # Returned Value # Function to print out the results of the returned value with a response def response(): print("Roll: " + "\n" + result) if "Scissors vs. Paper" == result or \ "Paper vs. Scissors" == result: print("\nScissors beats Paper") elif "Scissors vs. Rock" == result or \ "Rock vs. Scissors" == result: print("\nRock beats Scissors!") elif "Rock vs. Paper" == result or \ "Paper vs. Rock" == result: print("\nPaper beats Rock!") else: print("\nDraw! Roll again.") response() </code></pre>
[]
[ { "body": "<p>Despite of very simple and \"verbose\" initial implementation it has a bunch of issues:</p>\n\n<ul>\n<li><p><code>r_p_s = ['Rock', 'Paper', 'Scissors']</code> is better defined as constant of immutable values</p></li>\n<li><p><code>result</code> is accessed within <code>response()</code> function body as a global variable.<br>Instead, it's better called within the function <em>on demand</em>:</p>\n\n<pre><code>def response():\n result = game()\n ...\n</code></pre></li>\n<li><p>instead of arbitrary strings concatenation <code>... + \" vs. \" + ...</code>, <code>\"Roll: \" + \"\\n\" + result</code> <br>- use flexible <code>f-string</code> formatting.<br>\nFor ex.: <code>print(f\"Roll: \\n{result}\")</code></p></li>\n<li><p>the conditions like:</p>\n\n<pre><code>if \"Scissors vs. Paper\" == result or \\\n \"Paper vs. Scissors\" == result:\n print(\"\\nScissors beats Paper\")\n</code></pre>\n\n<p>are too verbose and hard-coded to be manageable and reliable</p></li>\n</ul>\n\n<hr>\n\n<p>Now, when you realize the bad things described above and wonder if there a manageable and advanced approach - take and consider the one below, which is OOP approach representing <strong><code>RPSGame</code></strong> class (as a main class) and powered by <a href=\"https://docs.python.org/3/library/enum.html\" rel=\"noreferrer\"><code>enum</code></a> classes to represent the crucial <em>shapes</em>.<br>\nThe new implementation itself is pretty descriptive (I hope). Enjoy!</p>\n\n<pre><code>import random\nfrom enum import Enum\n\n\nclass RPSGame:\n class Shape(Enum):\n R = 'Rock'\n P = 'Paper'\n S = 'Scissors'\n\n # winning outcome bindings\n WIN_OUTCOMES = {\n (Shape.P, Shape.R), (Shape.R, Shape.S), (Shape.S, Shape.P),\n }\n\n @staticmethod\n def choice():\n shapes = list(RPSGame.Shape)\n return random.choice(shapes), random.choice(shapes)\n\n def play(self):\n shape1, shape2 = self.choice()\n print(f\"Roll: \\n{shape1.value} vs {shape2.value}\\n\")\n\n if shape1 == shape2:\n print(\"Draw! Roll again.\")\n else:\n # check to swap shapes to get winning output order\n if (shape1, shape2) not in RPSGame.WIN_OUTCOMES:\n shape1, shape2 = shape2, shape1\n print(f\"{shape1.value} beats {shape2.value}!\")\n\n\nif __name__ == \"__main__\":\n rps = RPSGame()\n rps.play()\n rps.play()\n rps.play()\n</code></pre>\n\n<p>Sample output (from 3 plays):</p>\n\n<pre><code>Roll: \nPaper vs Scissors\n\nScissors beats Paper!\nRoll: \nScissors vs Scissors\n\nDraw! Roll again.\nRoll: \nRock vs Paper\n\nPaper beats Rock!\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-13T22:27:19.783", "Id": "453692", "Score": "0", "body": "I really appreciate the time you took to answer. Im getting my feet wet with classes currently. Quick question, what does @ staticmethod do?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-13T22:38:21.463", "Id": "453694", "Score": "0", "body": "@Wicked1Kanobi https://docs.python.org/3/library/functions.html#staticmethod" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-14T19:57:24.627", "Id": "453841", "Score": "1", "body": "I'd definitely advocate for including the full name in the Enum, eg `Shape.Rock` if that's the direction you want to go." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-15T11:42:58.230", "Id": "453911", "Score": "0", "body": "You have a single method and no state to persist. Why would you want to write a class?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-15T12:13:08.920", "Id": "453914", "Score": "0", "body": "@409_Conflict, Class is not mandatory as *\"something with persistent state\"*. As well as specific *Factory* class could have NO state, but just generate a specific instances (with *factory* method). Here, I used classes to show how it could be flexibly organized and structured. And since it's a class now, it can be extended and filled with any needed state." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-15T12:40:46.957", "Id": "453917", "Score": "0", "body": "Well, this is not Java, if you need a factory, a simple function or a classmethod can do. For now you're complicating things by introducing the need to instantiate in order to call the one stateless method. Removing the class namespace would allow to call `play` directly. And for the possibility to add state... This is rock paper scissors, YAGNI; or at least it shouldn't be this class' responsibility anyway." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-13T22:10:48.857", "Id": "232358", "ParentId": "232347", "Score": "5" } }, { "body": "<p>Let's start with a list like you did:</p>\n\n<pre><code>rps = ['Rock', 'Paper', 'Scissors']\n</code></pre>\n\n<p>What do we notice with the ordering? Each one always beats the previous one: Paper beats Rock, Scissors beats Paper &amp; Rock beats Scissors (when we wrap around).</p>\n\n<p>We can exploit that logic:</p>\n\n<pre><code>difference = rps.index(first_shape) - rps.index(second_shape)\n</code></pre>\n\n<p>This difference means we now have a very simple way of determining the winner. If it's zero, it's a tie, otherwise the difference tells us who won, and we'll be using the ability to use negative list indexes:</p>\n\n<p>For a length 3 list: <code>lst[-1] == lst[2]</code> and <code>lst[-2] == lst[1]</code>. So a difference of 1 means the first player won, and a difference of 2 means the second player won, and python is gonna handle the negative cases for us automatically. Nice!</p>\n\n<p>So we can just use this directly to figure out who won with the help of a <code>winner_lookup</code> list that makes this </p>\n\n<pre><code>winner_lookup = [\"\\nDraw! Roll again!\", \n f\"\\n{first_shape} beats {second_shape}!\", \n f\"\\n{second_shape} beats {first_shape}!\"]\nprint(winner_lookup[difference])\n</code></pre>\n\n<p>Now we can change the input/output strings without fear of damaging our business logic.</p>\n\n<p>To diverge entirely from using strings for business, let's make our choices as just the index of the choice we want:</p>\n\n<pre><code>first_shape, second_shape = random.randint(0, 2), random.randint(0, 2)\n</code></pre>\n\n<p>To take player input, we'd just use <code>rps.index(player_input)</code> to get the index of their choice. This also means all the prints need to use <code>rps[shape]</code> to get the string instead of the index.</p>\n\n<p>We can pull all of the strings outside of the play function, which all together gives us:</p>\n\n<pre><code>import random\n\nrps = ['Rock', 'Paper', 'Scissors']\nmatch_string = \"Roll:\\n{} vs {}\"\ntie_string = \"\\nDraw! Roll again!\"\nwinner_string = \"\\n{} beats {}!\"\n\ndef autoplay():\n first, second = random.randint(0, 2), random.randint(0, 2)\n difference = first - second\n winner_lookup = [tie_string, \n winner_string.format(rps[first], rps[second]),\n winner_string.format(rps[second], rps[first])]\n print(match_string.format(rps[first], rps[second]))\n print(winner_lookup[difference])\n</code></pre>\n\n<p>Where you may want to use classes and objects instead of this is if you wanted to implement RPSLS (Rock Paper Scissors Lizard Spock), as this implementation relies on the game rules being only <em>each entry is beaten by the next entry</em>. But if we wanted to change any of the strings, we don't affect the code at all.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-14T21:20:48.033", "Id": "232410", "ParentId": "232347", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-13T19:52:22.263", "Id": "232347", "Score": "3", "Tags": [ "python", "beginner", "python-3.x", "rock-paper-scissors" ], "Title": "New to programming. How can I write this Rock, Paper, Scissors code better?" }
232347
<p>This code is scraping the data from IMDB and displays it in JSON or CSV format.</p> <p>I plan to extend it beyond the top rated movies. How can I improve the quality of my code? I am using Python 3.7.3. </p> <pre><code>from bs4 import BeautifulSoup import requests import csv import json import codecs films = [] def getFilms250(): sourceTop250 = requests.get( 'https://www.imdb.com/chart/top?ref_=nv_mv_250').text soup = BeautifulSoup(sourceTop250, 'lxml') counter = 0 for title_container, rating_container in zip(soup.find_all('td', class_='titleColumn'),soup.findAll('td', class_='ratingColumn imdbRating')): title = title_container.a.text counter += 1 year = title_container.span.text rating = rating_container.strong.text film_data = [counter, title, year.strip('()'), rating] films.append(film_data) return films def csvFormat(films, userDelimiter): with open('new_film_base.csv', 'w', newline='') as file: header = ['Position', 'Title', 'Year', 'imdbRanking'] film_writer = csv.writer(file, delimiter=userDelimiter) film_writer.writerow(header) film_writer.writerows(films) file.close def jsonFormat(films): with open('new_film_base.json', 'w', encoding='utf8') as file: arr = [] for i in films: x = { "position": i[0], "title": i[1], "year": i[2], "imbdRanking": i[3] } arr.append(x) movies = { "filmsRequested": arr } json.dump(movies, file, indent=True, ensure_ascii=False) file.close def handleUserFilm(prompt): #While user enters a proper input a function will get list of wanted films while True: try: userMessageFilm = input((prompt)) except ValueError: print('Input unkown') if userMessageFilm == 'films250': getFilms250() break elif userMessageFilm != 'films250': print('No such data') continue return userMessageFilm def handleUserFormat(prompt): while True: try: userMessageFormat = input((prompt)) except ValueError: print('Input unkown') continue if userMessageFormat != 'csv' and userMessageFormat != 'json': print('Format unkown') continue elif userMessageFormat == 'json': jsonFormat(films) break elif userMessageFormat == 'csv': while True: delimiter = input( 'Enter the Delimiter for csv format(";" recommended): ') if len(delimiter) &gt; 4: print("delimiter can't be that long") continue else: csvFormat(films, delimiter) break return userMessageFormat filmsUser = handleUserFilm('To get Top250 type - films250: ') formats = handleUserFormat('To get csv format type - csv\nTo get json format type - json ') </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-13T21:05:09.510", "Id": "453683", "Score": "0", "body": "Hi Philip, I suggest you edit your title to state what your code does in more detail, for example \"Scraping IMDB and exporting to JSON or CSV\", this way your question will have more attention! :)" } ]
[ { "body": "<p>Python uses <a href=\"https://www.python.org/dev/peps/pep-0008/#function-and-variable-names\" rel=\"nofollow noreferrer\">snake_case, not camelCase</a> for variable and function names. <code>csvFormat</code> for example, should be <code>csv_format</code>.</p>\n\n<hr>\n\n<p>In two places you do this weird thing:</p>\n\n<pre><code>with open(. . .) as file:\n . . .\nfile.close\n</code></pre>\n\n<ul>\n<li><p><code>with</code> already closes <code>file</code>, so there's no need to manually close it.</p></li>\n<li><p><code>file.close</code> doesn't do anything, and a good IDE would warn you of that. You need to add <code>()</code> to call <code>close</code>: <code>file.close()</code>.</p></li>\n</ul>\n\n<hr>\n\n<p>Speaking of weird things, you have this in a couple places as well:</p>\n\n<pre><code>try:\n userMessageFormat = input((prompt))\nexcept ValueError:\n print('Input unkown')\n</code></pre>\n\n<p><code>input</code>, as far as I know, will never throw. If you had a call to <code>int</code> in there, or if you were using Python 2 (maybe?), this may make sense. I don't think this <code>try</code> does anything, and I don't think <code>'Input unkown'</code> will <em>ever</em> be printed.</p>\n\n<hr>\n\n<pre><code>if userMessageFormat != 'csv' and userMessageFormat != 'json':\n . . .\nelif userMessageFormat == 'json':\n . . .\nelif userMessageFormat == 'csv':\n</code></pre>\n\n<p>This is written in kind of a \"fragile\" way. If you ever add more formats, you'll need to make two changes: 1. Add a new <code>elif userMessageFormat ==</code> check, and 2. Add to the first condition to validate the format ahead of time. If you forget to update the latter, none of the other cases will be <code>True</code>, and <code>return userMessageFormat</code> will cause a <code>NameError</code> since <code>userMessageFormat</code> will have never been defined.</p>\n\n<p>Just make use of an <code>else</code> case:</p>\n\n<pre><code>if userMessageFormat == 'json':\n . . .\nelif userMessageFormat == 'csv':\n . . .\nelse:\n print('Format unkown')\n</code></pre>\n\n<p>This is what <code>else</code> is for: to handle when none of the other checks were true.</p>\n\n<hr>\n\n<pre><code>for i in films:\n x = {\n \"position\": i[0],\n \"title\": i[1],\n \"year\": i[2],\n \"imbdRanking\": i[3]\n }\n</code></pre>\n\n<p>This could make use of destructuring to avoid needing to index <code>i</code>:</p>\n\n<pre><code>for position, title, year, rank in films:\n x = {\n \"position\": position,\n \"title\": title,\n \"year\": year,\n \"imbdRanking\": rank\n }\n</code></pre>\n\n<p>If the sub-collections in <code>films</code> contain more than 4 elements each, you'll need to change the <code>for</code> line to:</p>\n\n<pre><code>for position, title, year, rank, *_ in films:\n</code></pre>\n\n<p>The <code>*_</code> catches all the remaining elements. Without this, you'll get a <code>ValueError</code>.</p>\n\n<hr>\n\n<pre><code>if userMessageFilm == 'films250':\n . . .\nelif userMessageFilm != 'films250':\n . . .\n</code></pre>\n\n<p>This is redundant. If the first check is false, the second <em>must</em> be true. This can just be:</p>\n\n<pre><code>if userMessageFilm == 'films250':\n . . .\nelse:\n . . .\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-13T23:30:00.540", "Id": "453697", "Score": "0", "body": "Thank you for your answear. Some of those mistakes were really stupid. I'll upadate my code considering your suggestions" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-13T23:34:50.823", "Id": "453698", "Score": "1", "body": "@Philip You're welcome. Note though, don't update the code in the question here (I'm not sure of that's what you meant). Code being reviewed isn't generally allowed to be edited once it's posted, as that invalidates answers." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-13T22:36:10.683", "Id": "232361", "ParentId": "232348", "Score": "5" } } ]
{ "AcceptedAnswerId": "232361", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-13T20:15:40.013", "Id": "232348", "Score": "3", "Tags": [ "python", "beginner", "python-3.x", "web-scraping", "beautifulsoup" ], "Title": "Scraping IMDB and exporting to JSON or/and CSV" }
232348
<p>Is it bad practice to mix async and sync call in same ASP.NET core API call?</p> <p>For example, in following code method <code>CropBlackBroderOfAnImageAsync</code> is an async method.</p> <p>On the other hand <code>SaveImageForProcessing(file, sourceFolderPath);</code> is a sync method.</p> <p>The reason I am calling <code>SaveImageForProcessing</code> synchronously is that I want use the result of it to execute the code in <code>CropBlackBroderOfAnImageAsync</code>.</p> <pre><code>public async Task&lt;(string sourceFolderPath, string destinationFolderPath)&gt; CropBlackBorderOfAnImage(IFormFile file) { var extension = Path.GetExtension(file.FileName); var newFileName = Guid.NewGuid().ToString();//Create a new Name for the file due to security reasons. var fileNameSource = newFileName + extension; var sourceFolderPath = Path.Combine(Directory.GetCurrentDirectory(), "Images\\Source", fileNameSource); var fileNameDestination = newFileName + "Result" + extension; var destinationFolderPath = Path.Combine(Directory.GetCurrentDirectory(), "Images\\Destination", fileNameDestination); SaveImageForProcessing(file, sourceFolderPath); await _imageCropBlackBroderService.CropBlackBroderOfAnImageAsync(sourceFolderPath, destinationFolderPath); return (sourceFolderPath, destinationFolderPath); } private void SaveImageForProcessing(IFormFile file, string path) { using (var bits = new FileStream(path, FileMode.Create)) { file.CopyTo(bits); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-14T09:34:32.503", "Id": "453730", "Score": "2", "body": "Welcome to Code Review! Please edit your question so that the title describes the *purpose* of the code, rather than its *mechanism*. We really need to understand the motivational context to give good reviews. Thanks!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-14T16:07:30.270", "Id": "453802", "Score": "1", "body": "You are using `Path.Combine` which is great, but then you hardcode the path delimiter ``\\\\``. The `Images` and `Source` names should be their own distinct parameters." } ]
[ { "body": "<p>Well, generally it is not a problem to call a sync method within async method.</p>\n\n<p>You are actualy doing this in more then few instances (GetExtension, NewGuild, ToString, etc...)</p>\n\n<p>But if you have an async method available it would be shame to not use it.\nWhich you have - <code>IFormFile.CopyToAsync()</code>.</p>\n\n<pre><code>using (var bits = new FileStream(path, FileMode.Create))\n{\n await file.CopyToAsync(bits);\n}\nawait _imageCropBlackBroderService.CropBlackBroderOfAnImageAsync(sourceFolderPath, destinationFolderPath);\n\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-13T21:12:23.410", "Id": "232354", "ParentId": "232353", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-13T20:57:07.673", "Id": "232353", "Score": "0", "Tags": [ "c#", "asynchronous", "async-await", "asp.net-core" ], "Title": "Mixing Async and Sync in same HTTP request ASP.NET Core C#" }
232353
<pre><code>int main() { int x,numDigits,i,y,a,diff; scanf("%d",&amp;x); a=x; int result = 1; int base=10; numDigits=0; do { ++numDigits; x = x / 10; } while ( x&gt;0 ); for(result=1;numDigits&gt;0;--numDigits){ result *= base; i=result; y=a%i; while(y&gt;10){ y=y/10; } printf(" %d",y); } return 0; } </code></pre> <p>I manage to seperate integer's digits one by one. But I was not able to collect them in an array. Even though with limited numbers without taking input from user it is easier, I also want to process these numbers but I got stuck.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-13T22:03:35.027", "Id": "453688", "Score": "1", "body": "Welcome to Code Review! Since [we require that the code is working as intended to the best of your knowledge](/help/on-topic), your code is unfortunately not yet ready for a review. Once everything is working, feel free to come back to get feedback on best practices and improvements." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-14T00:46:53.393", "Id": "453702", "Score": "2", "body": "There appear to be some magic numbers in the code. Do you mean `base` everywhere you use `10`? Would you please comment your variables so that we know what they are supposed to represent and please comment your code so that we know what you are trying to do? The code makes no attempt \"to collect them in an array\", no array is declared. As it stands, this code is not ready for review." } ]
[ { "body": "<p>You can use the standard <code>C</code> function <a href=\"https://en.cppreference.com/w/c/io/fprintf\" rel=\"nofollow noreferrer\"><code>sprintf(buffer,\"%d\",x)</code></a> to get an array of digits. In this case, the <code>buffer</code> will contain big-endian representation of x, so the conversion to a digit from each char will be something like this</p>\n\n<pre><code>for(int i = 0; buffer[i] != '\\0' &amp;&amp; i &lt; sizeof(buffer);++i)\n digits[i] = buffer[i] - '0';\n</code></pre>\n\n<p>This work if <code>x</code> is positive.</p>\n\n<p>But if you want to make your own implementation of splitting a number into digits, you should analyze the problem:</p>\n\n<ol>\n<li>What is the <code>base</code> - is it always 10?</li>\n<li>How many digits could be - is it always <code>int</code>, i.e. mostly 32-bit?</li>\n</ol>\n\n<p>The answer for first question is to have the <code>base</code> parameter <code>int base = 10</code> or 2 or 3 or 8 or any you want.</p>\n\n<p>The answer for second question is <code>ceil( log(|x| + 1) / log(base) ) + 1</code>. The <code>+1</code> for the minus sign. Or if you didn't want to care about maximum of digits use <code>char digits[128]</code> - more than enough even for 64-bit integer.</p>\n\n<p>So, how to fill <code>digits</code>?</p>\n\n<pre><code>// int x - somewhere\nunsigned base = 10;\n\nchar digits[128];\nchar isNegative = 0;\nint digit = 0;\n\nunsigned tmp = x; // this fix INT_MIN problem thanks chux - Reinstate Monica for note\nif(x &lt; 0) {\n isNegative = 1;\n tmp = -x;\n} \nif(x == 0) {\n digits[0] = 0;\n digit = 1;\n} else {\n for(digit = 0; tmp &gt; 0; ++digit) {\n digits[digit] = tmp % base;\n tmp /= base;\n } \n}\n</code></pre>\n\n<p>At least you got little-endian representation of <code>x</code> on <code>base</code> as digits[i], where <code>0 &lt;= i &lt; digit</code> and <code>isNegative</code> for the minus sign</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-14T09:35:18.063", "Id": "453731", "Score": "0", "body": "Welcome to Code Review! Please refrain from answering low-quality questions that are likely to get closed. Once you've answered, that [limits what can be done to improve the question](/help/someone-answers#help-post-body), making it more likely that your efforts are wasted. It's better to wait until the question is properly ready before you answer!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-18T08:22:13.673", "Id": "454173", "Score": "0", "body": "Yes, @chux-ReinstateMonica! Many thanks. My C is a little rusty. Also, I missed case with `x==INT_MIN`. Fixed now." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-18T13:29:38.297", "Id": "454231", "Score": "0", "body": "Better, yet `-x` is still UB when `x==INT_MIN`. Suggest `bool isNegative = x < 0; unsigned tmp = isNegative ? 0u - x : x;` or the like. The key is that `int` math should not attempt `-INT_MIN`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-18T18:06:44.023", "Id": "454268", "Score": "0", "body": "Did you mean UB if sizeof(tmp)>sizeof(int), when tmp type will changed to unsigned long long?" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-14T08:42:33.140", "Id": "232370", "ParentId": "232355", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-13T21:34:41.357", "Id": "232355", "Score": "0", "Tags": [ "c" ], "Title": "turning the digits of a number into an array" }
232355
<p>So, here's a task. A background thread may or may not call all of it's listeners some time after <code>sendRequest()</code> was called (in other words <code>sendRequest()</code> schedules a possible event). The required function must:</p> <ol> <li>Subscribe to those events</li> <li>Call <code>sendRequest()</code> periodically until the function returns anything</li> <li>Return the first suitable result (filtering is done in the listener and is omitted in this snippet) or <code>null</code> after a timeout</li> <li>Unsubscribe from those events regardless of the result</li> </ol> <pre><code>suspend fun findServer(): Server? { var listener: ((Server) -&gt; Unit)? = null return try { withTimeoutOrNull(10000) { suspendCancellableCoroutine&lt;Server&gt; { continuation -&gt; listener = { server: Server -&gt; continuation.resume(server) }.also { discoveryService.addListener(it) } launch { while (continuation.isActive) { discoveryService.sendRequest() delay(1000) } } } } } finally { listener?.let { discoveryService.removeListener(it) } } } </code></pre> <p>The current implementation seems to work fine, but the nullable <code>listener</code> variable feels kind of clunky and requires using <code>also</code> to keep the listener reference, which in turn breaks type inference and makes me specify listener's parameter type (no big deal, but...). I could use a lateinit var here, but it probably can lead to exceptions when <code>withTimeoutOrNull()</code> stops before the listener was initialized.</p> <p>Any recommendations on improving this snippet? Or am I, in fact, doing everything totally wrong here?</p>
[]
[ { "body": "<p>Think it's pretty good and you can't think of much else. Some tiny bits I can think of:</p>\n\n<ul>\n<li>Make <code>discoveryService</code> parameter.</li>\n<li>Do not use <code>launch</code> without specifying CoroutineScope.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T14:45:55.440", "Id": "457065", "Score": "0", "body": "Well, the application is built on dependency injection and `discoveryService` is an injected component so it shouldn't be a parameter.\n\nI'm not too comfortable with CoroutineScopes yet, but it seems that `withTimeoutOrNull` provides a scope. Should I wrap it somewhere?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T16:33:58.097", "Id": "457097", "Score": "0", "body": "Yeah I get it and I think you are right and `withTimeoutOrNull` indeed provides scope, my bad :)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-09T08:10:26.537", "Id": "233665", "ParentId": "232356", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-13T21:48:26.340", "Id": "232356", "Score": "2", "Tags": [ "kotlin" ], "Title": "Getting a value with timeout using Kotlin coroutines" }
232356
<p>I am modeling a linear process at a number of equally spaced time steps. I have a large list (~70k elements) which corresponds to a location at each time step, <code>timerange = np.linspace(0, time, iterations, False) * speed</code>. For each element in this list, I want to compare its value (location) to two other lists and see if that location falls within a valid region. These two other lists, <code>rot.RegionStarts</code> and <code>rot.RegionEnds</code> (~150 elements) contains the start and end locations, respectively, of each region.<br/><br/> I began tackling this problem with list comprehension, using the following code to achieve the desired result.</p> <pre><code>valid = np.asarray([any((t * dt * speed &gt;= rot.RegionStarts) &amp; (t * dt * speed &lt; rot.RegionEnds) for t in range(iterations)]) </code></pre> <p>Upon using this, I realized that execution was rather slow, about 0.4s each time. As make several hundred calls to this line, this greatly slows down the process. I tried using numpy to achieve a similar effect, which required lots of reshaping and repeating.</p> <pre><code>valid = np.any(np.logical_and( np.greater_equal(np.repeat(np.reshape(timerange, (-1, 1)), rot.RegionStarts.shape[0], axis=1), np.repeat(np.reshape(rot.RegionStarts, (1, -1)), timerange.shape[0], axis=0)), np.less(np.repeat(np.reshape(timerange, (-1, 1)), rot.RegionEnds.shape[0], axis=1), np.repeat(np.reshape(rot.RegionEnds, (1, -1)), timerange.shape[0], axis=0)), axis = 1) </code></pre> <p>Unfortunately, this saw very little performance increase (~0.25s), probably due to the large size of arrays being repeated. Removing lines like <code>np.repeat</code> cause problems aligning shape; element-wise <code>&amp;</code> could not be executed on 2-d arrays. <br/><br/> What optimization techiniques can be used speed up this code?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-13T23:13:20.267", "Id": "453695", "Score": "0", "body": "Are the regions organized in some exploitable fashion/do they overlap? (0-2 in region 1, 2-5 is region 2, etc) Right now you're brute force testing against every region every time. What changes between runs?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-13T23:15:05.957", "Id": "453696", "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." } ]
[ { "body": "<p>Loops over large arrays are not really a good idea in Python. This is why your original list comprehension is not terribly fast.</p>\n\n<p>Your numpy version is loop free, but as far as I know, <code>np.repeat</code> actually makes copies of your data, which again, is really inefficient. An alternative would be to use <code>np.tile</code>, which maybe does not need to copy the data. But we don't really need to bother since numpy has a great feature called <a href=\"https://jakevdp.github.io/PythonDataScienceHandbook/02.05-computation-on-arrays-broadcasting.html\" rel=\"noreferrer\"><em>broadcasting</em></a>, which often makes <code>np.repeat</code>/<code>np.tile</code> completely unneccessary. Broadcasting basically does <code>np.repeat/tile</code> automatically.</p>\n\n<p>To evaluate the performance, I created a more abstract version of your list comprehension:</p>\n\n<pre><code>def get_valid_op(arr, lowers, uppers):\n return np.asarray([any((val &gt;= lowers) &amp; (val &lt; uppers)) for val in arr])\n</code></pre>\n\n<p>and also a broadcasting version</p>\n\n<pre><code>def get_valid_arr(arr, lowers, uppers):\n valid = np.logical_and(arr.reshape(1, -1) &gt;= lowers.reshape(-1, 1), arr.reshape(1, -1) &lt; uppers.reshape(-1, 1))\n return valid.any(axis=0)\n</code></pre>\n\n<p>The second one is virtually the exact same algorithm as your repeat/reshape code.</p>\n\n<p>With some test data modeled after your description above</p>\n\n<pre><code>arr = np.linspace(0, 1000, 70000)\nstarts = np.linspace(0, 150, 151) * 400\nends = starts + np.random.randint(0, 200, region_starts.shape) # I assumed non-overlapping regions here\n</code></pre>\n\n<p>we can first <code>assert all(get_valid_op(arr, starts, ends) == get_valid_arr(arr, starts, ends))</code> and then time:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>%timeit -n 10 get_valid_op(arr, starts, ends)\n511 ms ± 5.42 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)\n\n%timeit -n 10 get_valid_arr(arr, starts, ends)\n37.8 ms ± 3.1 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)\n</code></pre>\n\n<p>An order of magnitude faster. Not bad to begin with ;-)</p>\n\n<p>Since working with large arrays (<code>valid</code> has a shape of <code>(150, 70000)</code> before reduction) also has a cost, I then took a step back and returned to loopy-land (just a little bit). </p>\n\n<pre><code>def get_valid_loop(arr, lowers, uppers):\n valid = np.zeros(arr.shape, dtype=bool)\n for start, end in zip(lowers, uppers):\n valid = np.logical_or(valid, np.logical_and(start &lt;= arr, arr &lt; end))\n return valid\n</code></pre>\n\n<p>In contrast to your list comprehension, this version now only iterates over the shorter region limit vectors, which means about two orders of magnitude fewer iterations.</p>\n\n<p>We can then again <code>assert all(get_valid_op(arr, starts, ends) == get_valid_loop(arr, starts, ends))</code> and time it:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>%timeit -n 10 get_valid_loop(arr, starts, ends)\n18.1 ms ± 865 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)\n</code></pre>\n\n<p>As the results show, this version is even faster on my \"synthetic\" benchmark inputs.</p>\n\n<p>In the end you will have to check the versions in your application and see which one performs best.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-13T23:42:26.330", "Id": "232362", "ParentId": "232360", "Score": "12" } } ]
{ "AcceptedAnswerId": "232362", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-13T22:32:02.300", "Id": "232360", "Score": "8", "Tags": [ "python", "performance", "numpy" ], "Title": "Optimize Performance of Region Checking in List Comprehension" }
232360
<p>This is a pong game I created some time ago, but it doesn't have methods to store scores yet and also might have some bugs. It is also very slow.</p> <p>The code:</p> <pre class="lang-py prettyprint-override"><code>from tkinter import Tk from random import choice import os def clear(): os.system('cls' if os.name == 'nt' else 'clear') class Pong: def __init__(self): self.tk = Tk() self.p1 = [5, 4] self.p2 = [5, 58] self.move = [-1, choice([1, -1])] self.l = 5 self.ball = [7, 31] self.terminal = [ list(' ------------------------------------------------------------- '), list('| |'), list('| |'), list('| |'), list('| |'), list('| | | |'), list('| | | |'), list('| | O | |'), list('| | | |'), list('| | | |'), list('| |'), list('| |'), list('| |'), list('| |'), list(' ------------------------------------------------------------- ') ] def moveUp(self, p): i, j = p l = self.l if i == 1: return self.terminal[i + l - 1][j] = ' ' for x in range(i - 1, i + l - 1): self.terminal[x][j] = '|' p[0] -= 1 def moveDown(self, p): i, j = p l = self.l if i + l == len(self.terminal) - 1: return self.terminal[i][j] = ' ' for x in range(i + 1, i + l + 1): self.terminal[x][j] = '|' p[0] += 1 def moveComputer(self): if self.move[0] == -1: self.moveUp(self.p2) if self.move[0] == 1: self.moveDown(self.p2) def moveBall(self): try: if self.terminal[self.ball[0] + self.move[0]][self.ball[1]] == '-': self.move[0] *= -1 if self.terminal[self.ball[0]][self.ball[1] + self.move[1]] == '|': self.move[1] *= -1 elif self.terminal[self.ball[0] + self.move[0]][self.ball[1] + self.move[1]] == '|': self.move[0] *= -1 self.move[1] *= -1 self.terminal[self.ball[0]][self.ball[1]] = ' ' self.ball[0] += self.move[0] self.ball[1] += self.move[1] self.terminal[self.ball[0]][self.ball[1]] = 'O' if ' ' in self.terminal[0][1:-1]: i = self.terminal[0][1:-1].index(' ') self.terminal[i] = '-' if ' ' in self.terminal[-1][1:-1]: i = self.terminal[-1][1:-1].index(' ') self.terminal[i] = '-' self.print() if self.move[1] == 1: self.moveComputer() except: if (self.terminal[self.ball[0] - 1] == '-') and (self.terminal[self.ball[0] + 1] == '|') or \ (self.terminal[self.ball[0] + 1] == '-') and (self.terminal[self.ball[0] - 1] == '|'): self.move[0] *= -1 else: self.move[0] *= -1 self.move[1] *= -1 self.tk.after(25, self.moveBall) def play(self): self.tk.bind('&lt;Up&gt;', lambda x: self.moveUp(self.p1)) self.tk.bind('&lt;Down&gt;', lambda x: self.moveDown(self.p1)) self.moveBall() self.tk.mainloop() def print(self): clear() print('\n'.join(''.join(i) for i in self.terminal)) pong = Pong() pong.play() </code></pre> <p>How do I make it faster, neater, and shorter?</p> <p>Thanks for your help!</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-14T15:11:51.520", "Id": "453795", "Score": "0", "body": "Why are you using tkinter? The game appears as text in the terminal." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-14T17:35:20.310", "Id": "453817", "Score": "0", "body": "@BryanOakley To use `tk.bind` and `tk.after`" } ]
[ { "body": "<h1>Reserved Name</h1>\n\n<p><code>print</code> is a reserved name in python, so having a method with the same name isn't the best idea. I would use something like <code>print_grid</code> or <code>print_game</code>, something a little more descriptive, and also doesn't conflict with <code>print</code>.</p>\n\n<h1>Naming Conventions</h1>\n\n<p>Method and variable names should be in <code>snake_case</code>, not <code>camelCase</code>.</p>\n\n<h1>Main Guard</h1>\n\n<p>You should use a main guard when you have outside code. Take a look:</p>\n\n<pre><code>if __name__ == '__main__':\n pong = Pong()\n pong.play()\n</code></pre>\n\n<p>This prevents the two lines from being run if you decide to import this game from another module.</p>\n\n<h1>Keystrokes</h1>\n\n<p>It seems a little unnecessary to use <code>tkinter</code> for a console game. Consider using something like <a href=\"https://pypi.org/project/pynput/\" rel=\"nofollow noreferrer\"><code>pynput</code></a> or <a href=\"https://docs.python.org/3/howto/curses.html\" rel=\"nofollow noreferrer\"><code>curses</code></a> to listen to keyboard strokes.</p>\n\n<h1>Unnecessary Code</h1>\n\n<p>This</p>\n\n<pre><code>if (self.terminal[self.ball[0] - 1] == '-') and (self.terminal[self.ball[0] + 1] == '|') or (self.terminal[self.ball[0] + 1] == '-') and (self.terminal[self.ball[0] - 1] == '|'):\n self.move[0] *= -1\nelse:\n self.move[0] *= -1\n self.move[1] *= -1\n</code></pre>\n\n<p>is unnecessarily complicated. Since <code>self.move[0] *= -1</code> is run anyway, you only need to check if this condition is <code>False</code>:</p>\n\n<pre><code>if not ((self.terminal[self.ball[0] - 1] == '-') and (self.terminal[self.ball[0] + 1] == '|') or (self.terminal[self.ball[0] + 1] == '-') and (self.terminal[self.ball[0] - 1] == '|')):\n self.move[1] *= -1\nself.move[0] *= -1\n</code></pre>\n\n<h1>tkinter conventions</h1>\n\n<p>When using <code>tkinter</code>, it's recommended to pass <code>tk</code> into the class's constructor. Take a look:</p>\n\n<pre><code>def __init__(self, master):\n self.tk = master\n</code></pre>\n\n<p>Then your initialization code looks like this:</p>\n\n<pre><code>if __name__ == '__main__':\n root = Tk()\n pong = Pong(root)\n pong.play()\n</code></pre>\n\n<h1>Type Hinting</h1>\n\n<p>You can use type hints to make it clear what types of parameters are passed to functions, and what types are returned by functions. Lets take a look at your <code>moveDown</code> (should be <code>move_down</code>) function header:</p>\n\n<pre><code>def moveDown(self, p):\n</code></pre>\n\n<p>Now consider this</p>\n\n<pre><code>from typing import List\n\ndef moveDown(self, p: List[int]) -&gt; None:\n</code></pre>\n\n<p>This says that <code>moveDown</code> (again, <code>move_down</code>) should take a list of integers and returns None. This becomes more useful as you write functions with more parameters.</p>\n\n<h1>Docstrings</h1>\n\n<p>Lets expand upon your <code>moveDown</code> function. This can be even more descriptive by using a function docstring. This will allow you to put in words what the function is supposed to do. Take a look:</p>\n\n<pre><code>def moveDown(self, p: List[int]) -&gt; None:\n \"\"\"\n Moves the bars down. What player moves depends on the list passed.\n\n :param p -&gt; List[int]: Player to move\n\n :return: None\n \"\"\"\n</code></pre>\n\n<p>Now there is more description to the method, and also allows you to describe the parameters accepted, what values are returned, and what happens in the function. You can also provide when you should use this function.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-18T05:50:43.747", "Id": "232569", "ParentId": "232366", "Score": "1" } } ]
{ "AcceptedAnswerId": "232569", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-14T06:24:41.733", "Id": "232366", "Score": "2", "Tags": [ "python", "python-3.x", "game", "tkinter", "pong" ], "Title": "Pong game in Python with tkinter" }
232366
<p>I am new to python. I have been given a task to verify the data from 2 apis which give similar data but in different format i.e. Json and XML. I have written the code but it is taking too much time to execute. I am unfamiliar with formatting and etc so please help me here. (I am excluding urls and header etc. for security purpose)</p> <pre><code>from openpyxl import load_workbook from xml.etree import ElementTree import json import urllib.request import requests wb = load_workbook("CNIC.xlsx") source = wb["Sheet1"] for cniclist in source['A']: cnic = cniclist.value url = "/%s" % cnic urlobj = urllib.request.urlopen(url) try: string = urlobj.read().decode('utf-8') json_obj = json.loads(string) except: print(urlobj.readlines()) url2 = "url2" payload = "&lt;CUSTNO&gt;{}&lt;/CUSTNO&gt;" headers = {} response = requests.request("POST", url2, data=payload.format(cnic), headers=headers) tree = ElementTree.ElementTree(ElementTree.fromstring(response.text)) json_message = (json_obj.get('Message')) if json_message == "Success": json_record = (json_obj.get('Records')) if json_record == 1: for item in json_obj.get('OutData'): json_acc = item.get('Accounts')['NoAccounts'] print("No Of Accounts in Json Service is ", json_acc) elif json_record &gt; 1: json_acc = 0 for item in json_obj.get('OutData'): json_acc = item.get('Accounts')['NoAccounts'] print("No Of Accounts in Json Service is ", json_acc) else: print("No JSON Records found") root = tree.getroot() count = 0 xml_acc_no = [] for FCDB_BODY in root.findall("./FCDB_BODY/CUSTACCOUNT/ACCOUNT/ACCNO"): temp = FCDB_BODY.text xml_acc_no.append(temp) count += 1 print("No Of Accounts in XML Service is ", str(count)) # Checking Number of Accounts in both services if str(json_acc) == str(count): print("Number of Accounts are same in both services") elif str(json_acc) &gt; str(count): print("Json Service has more accounts ") else: print("XML Service has more accounts ") # Getting all data from Json Service for item1 in json_obj.get('OutData'): json_file_account = item1.get('Accounts')[ 'AccountList'] # Getting Accountlist details from jason service file json_accounts_list = [] for i in json_file_account: json_acc_no = i['ACC#'] # Getting Account Number from Json service file json_accounts_list.append(json_acc_no) json_title_list = [] for i in json_file_account: json_acc_title = i['TITLE'] # Getting Account title from Json service file json_title_list.append(json_acc_title) json_type_list = [] for i in json_file_account: json_account_type = i['STYPE'] # Getting Account type from Json service file json_type_list.append(json_account_type) json_desc_list = [] for i in json_file_account: json_account_desc = i['STPDESC'] # Getting Account description from Json service file if json_account_desc is not "": json_desc_list.append(json_account_desc) else: pass json_bal_list = [] for i in json_file_account: json_account_bal1 = i['ABAL'] # Getting Account balance from Json service file json_account_bal = int(json_account_bal1) / 100 json_account_bal = ('%f' % json_account_bal).rstrip('0').rstrip('.') json_bal_list.append(str(json_account_bal)) # Getting all data from Json Service xml_title_list = [] for j in root.findall("./FCDB_BODY/CUSTACCOUNT/ACCOUNT/ACCOUNTTITLE"): xml_acc_title = j.text xml_title_list.append(xml_acc_title) xml_type_list = [] for k in root.findall("./FCDB_BODY/CUSTACCOUNT/ACCOUNT/ACCOUNTTYPEDETAIL"): xml_acc_type = k.text xml_type_list.append(xml_acc_type) xml_desc_list = [] for l in root.findall("./FCDB_BODY/CUSTACCOUNT/ACCOUNT/ACCPRDDESC"): xml_acc_desc = l.text xml_desc_list.append(xml_acc_desc) xml_bal_list = [] for m in root.findall("./FCDB_BODY/CUSTACCOUNT/ACCOUNT/BAL_AVAIL"): xml_acc_bal = float(m.text) xml_acc_bal = ('%f' % xml_acc_bal).rstrip('0').rstrip('.') xml_bal_list.append(xml_acc_bal) # Checks for Account Number,Title, Type, Description and Balance acc_check = [[x for x in xml_acc_no if x not in json_accounts_list], [x for x in json_accounts_list if x not in xml_acc_no]] if len(acc_check[0]) or len(acc_check[1]): if len(acc_check[0]): print("Accounts which are unmatched in XML are ", acc_check[0]) if len(acc_check[1]): print("Accounts which are unmatched in JSON are ", acc_check[1]) else: print("No Unmatched Accounts found") title_check = [[y for y in xml_title_list if y not in json_title_list], [y for y in json_title_list if y not in xml_title_list]] if len(title_check[0]) or len(title_check[1]): if len(title_check[0]): print("Title which are unmatched in XML are ", title_check[0]) if len(title_check[1]): print("Title which are unmatched in JSON are ", title_check[1]) else: print("No Unmatched Title found") type_check = [[z for z in xml_type_list if z not in json_type_list], [z for z in json_type_list if z not in xml_type_list]] if len(type_check[0]) or len(type_check[1]): if len(type_check[0]): print("Type which are unmatched in XML are ", type_check[0]) if len(type_check[1]): print("Type which are unmatched in JSON are ", type_check[1]) else: print("No Unmatched type found") desc_check = [[q for q in xml_desc_list if q not in json_desc_list], [q for q in json_desc_list if q not in xml_desc_list]] if len(desc_check[0]) or len(title_check[1]): if len(desc_check[0]): print("Description which are unmatched in XML are ", desc_check[0]) if len(desc_check[1]): print("Description which are unmatched in JSON are ", desc_check[1]) else: print("No Unmatched Description found") balance_check = [[w for w in xml_bal_list if w not in json_bal_list], [w for w in json_bal_list if w not in xml_bal_list]] if len(balance_check[0]) or len(balance_check[1]): if len(balance_check[0]): print("Balance which are unmatched in XML are ", balance_check[0]) if len(balance_check[1]): print("Balance which are unmatched in JSON are ", balance_check[1]) else: print("No Unmatched Balance found") print("-----------------------------------") else: print("CNIC NOT FOUND in Json Service ") print("-----------------------------------") </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-14T07:41:41.430", "Id": "453717", "Score": "1", "body": "I would recommend fixing the unclosed string and any other errors that might be present *before* posting." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-14T07:52:30.497", "Id": "453718", "Score": "0", "body": "I have fix the unclosed string." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-14T08:01:46.423", "Id": "453719", "Score": "5", "body": "What is \"too slow\"? Why is it \"too slow\"? What would be an acceptable speed? How did you measure? How can we as reviewers reproduce the slow execution if you don't provide us dummy data?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-14T09:12:07.390", "Id": "453724", "Score": "1", "body": "Hi @Roland Illig, Sorry for not providing these details before. I am reading an excel file which contain user's unique identity numbers. Based on these numbers i am performing two requests which gives almost same data but in different formats. I need to compare the data. The issue is, I have a file of 1 million identity numbers which i have to use. Right now for one identity number, the whole program take around 8 seconds, which in total are many number of days to perform all data. I thought maybe code needed review that's why i posted the question here" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-19T09:58:04.260", "Id": "454320", "Score": "1", "body": "@AliKhan a bit late, but can you provide some example data, anything? I would love to take a more in depth look at your program :)" } ]
[ { "body": "<h1>List Comprehension</h1>\n\n<p>It doesn't look like you're new to list comprehension. So why do you use it some places but not others? When you get the Account Number/Title/Type from the json service file, you use standard loops. These loops can be reduced to three lines:</p>\n\n<pre><code>json_accounts_list = [i['ACC#'] for i in json_file_account]\njson_title_list = [i['TITLE'] for i in json_file_account]\njson_type_list = [i['STYPE'] for i in json_file_account]\n</code></pre>\n\n<p>This reduction can also be applied to when you get all the data from the json service:</p>\n\n<pre><code>xml_title_list = [j.text for j in root.findall(\"./FCDB_BODY/CUSTACCOUNT/ACCOUNT/ACCOUNTTITLE\")]\nxml_type_list = [k.text for k in root.findall(\"./FCDB_BODY/CUSTACCOUNT/ACCOUNT/ACCOUNTTYPEDETAIL\")]\nxml_desc_list = [l.text for l in root.findall(\"./FCDB_BODY/CUSTACCOUNT/ACCOUNT/ACCPRDDESC\")]\n</code></pre>\n\n<h1>String Formatting</h1>\n\n<p>This one is personal preference, but can provide some cleanliness to your code:</p>\n\n<pre><code>('%f' % json_account_bal).rstrip('0').rstrip('.')\n</code></pre>\n\n<p>can be</p>\n\n<pre><code>f\"{json_account_bal}\".rstrip('0').rstrip('.')\n</code></pre>\n\n<p>This removes the use of parentheses and looks just a bit neater. This can be applied to other parts of your program as well.</p>\n\n<h1>Functions</h1>\n\n<p>Your entire program is enveloped in a for loop. I would recommend splitting parts of your code into functions so you can separate and manage what parts do what.</p>\n\n<h1>Printing</h1>\n\n<p>Just a little aside about printing. When you print like <code>print(\"Hi \", name)</code>, there are two spaces between \"Hi\" and whatever the name is. The print function inserts a space whenever you're printing like this, so a little neater output would be <code>print(\"Hi\", name)</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-14T09:16:15.710", "Id": "453726", "Score": "0", "body": "You can use a neat trick to get all the (JSON) lists in one (and a \"half\") go: `json_list = [i['ACC#'], i['TITLE'], i['STYPE'] for i in json_file_account]` and then `accounts, titles, stypes = zip(*json_list)`. Maybe something similar is also possible on the XML-side." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-14T09:59:04.213", "Id": "453739", "Score": "0", "body": "Hi @Linny, Thank you for your help. I have applied all of your suggestions." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-14T10:42:26.377", "Id": "453746", "Score": "0", "body": "@AlexV it gives me syntax error **expected ',' or ']'** before _for loop_" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-14T11:57:34.993", "Id": "453755", "Score": "0", "body": "@AliKhan Sorry, my bad. Please try `json_list = [(i['ACC#'], i['TITLE'], i['STYPE']) for i in json_file_account]` and then `accounts, titles, stypes = zip(*json_list)`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-14T12:21:46.647", "Id": "453762", "Score": "0", "body": "@AlexV Thanks much. It works perfectly :)" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-14T08:14:39.930", "Id": "232369", "ParentId": "232367", "Score": "1" } } ]
{ "AcceptedAnswerId": "232369", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-14T07:37:05.287", "Id": "232367", "Score": "0", "Tags": [ "python", "performance", "python-3.x", "json", "xml" ], "Title": "Reduce the execution time utilizing two apis" }
232367
<p>To compensate for shaky hands when holding a mobile device I'm averaging the rotation of the phone over the last <code>n</code> (in this case 16) frames, and setting the camera's rotation to this average. This works smoothly and allows the user to look around in 360° by moving their phone around without getting sick of vibrations.</p> <pre><code>using System.Collections.Generic; using UnityEngine; using UnityEngine.XR; public class OrientationController : MonoBehaviour { private List&lt;Quaternion&gt; lastQuaternions = new List&lt;Quaternion&gt;(); private readonly int maxRotationCount = 16; void Start() { //Load the cardboard after we've started up to prevent the cardboard overlay from showing XRSettings.LoadDeviceByName("cardboard"); //Disable XR to go into "magic window" mode XRSettings.enabled = false; } void Update() { UpdateCameraRotation(); } /// &lt;summary&gt; /// Update the main camera's rotation based on the data taken from the XRNode.Head /// &lt;/summary&gt; private void UpdateCameraRotation() { lastQuaternions.Add(InputTracking.GetLocalRotation(XRNode.Head)); if (lastQuaternions.Count &gt; maxRotationCount) { lastQuaternions.RemoveAt(0); transform.localRotation = SmoothRotation(); } } /// &lt;summary&gt; /// Get the average rotation over the last 16 frames /// &lt;/summary&gt; /// &lt;returns&gt;The new rotation quaternion&lt;/returns&gt; private Quaternion SmoothRotation() { Quaternion quatA = lastQuaternions[0]; Quaternion quatB = lastQuaternions[1]; Quaternion quatC = lastQuaternions[2]; Quaternion quatD = lastQuaternions[3]; Quaternion quatE = lastQuaternions[4]; Quaternion quatF = lastQuaternions[5]; Quaternion quatG = lastQuaternions[6]; Quaternion quatH = lastQuaternions[7]; Quaternion quatI = lastQuaternions[8]; Quaternion quatJ = lastQuaternions[9]; Quaternion quatK = lastQuaternions[10]; Quaternion quatL = lastQuaternions[11]; Quaternion quatM = lastQuaternions[12]; Quaternion quatN = lastQuaternions[13]; Quaternion quatO = lastQuaternions[14]; Quaternion quatP = lastQuaternions[15]; Quaternion quatAB = Quaternion.Lerp(quatA, quatB, 0.5f); Quaternion quatCD = Quaternion.Lerp(quatC, quatD, 0.5f); Quaternion quatEF = Quaternion.Lerp(quatE, quatF, 0.5f); Quaternion quatGH = Quaternion.Lerp(quatG, quatH, 0.5f); Quaternion quatIJ = Quaternion.Lerp(quatI, quatJ, 0.5f); Quaternion quatKL = Quaternion.Lerp(quatK, quatL, 0.5f); Quaternion quatMN = Quaternion.Lerp(quatM, quatN, 0.5f); Quaternion quatOP = Quaternion.Lerp(quatO, quatP, 0.5f); Quaternion quatABCD = Quaternion.Lerp(quatAB, quatCD, 0.5f); Quaternion quatEFGH = Quaternion.Lerp(quatEF, quatGH, 0.5f); Quaternion quatIJKL = Quaternion.Lerp(quatIJ, quatKL, 0.5f); Quaternion quatMNOP = Quaternion.Lerp(quatMN, quatOP, 0.5f); Quaternion quatABCDEFGH = Quaternion.Lerp(quatABCD, quatEFGH, 0.5f); Quaternion quatIJKLMNOP = Quaternion.Lerp(quatIJKL, quatMNOP, 0.5f); //Quaternion quatABCDEFGHIJKLMNOP = Quaternion.Lerp(quatABCDEFGH, quatIJKLMNOP, 0.5f);//We don't currently want this extreme level of smoothness return quatIJKLMNOP; } } </code></pre> <p>However, despite it working as intended my current approach doesn't feel optimal, as it relies on creating a lot of <code>quaternion</code>s each frame, and <code>lerp</code>ing between them. It is also not scaleable at all, as I'd need to make hardcoded changes every time I want to change the intensity of the smoothing.</p> <p>Using Unity 2019.1.8f1 running C# .Net 4.x scripting runtime, and IL2CPP scripting backend. </p> <p>To recreate in Unity, you also need to set the build target to Android. Enable "Virtual reality supported" under project settings > player > XR Settings. enable the virtual reality SDKs "None" and "Cardboard" (In that order).</p> <p>I'm not experiencing any performance issues with this implementation, but I am curious to know if there are approaches that don't require me to create so many quaternions, or at least make the number of quaternions I can average dynamic.</p>
[]
[ { "body": "<p>Below you can find some of my reflections.</p>\n\n<ol>\n<li>Method InputTracking.GetLocalRotation(XRNode.Head) is obsolete as <a href=\"https://docs.unity3d.com/ScriptReference/XR.InputTracking.GetLocalRotation.html\" rel=\"noreferrer\">DOCS</a> says.</li>\n<li>There is a lot calculations per one frame indeed, but Quaternions are structs and you store only 16 of them on heap. As you mentioned yourself, you don't see performance issues. So it's up to you/manager if it's worth more time spending on this.</li>\n<li>If you want to make it more scalable then you should move it to external class and inject your rate (the last parameter of Lerp method)</li>\n<li>I suggest small refactoring. Please consider refactor of SmoothRotation method to use loop internally, it shouldn't be hard task. Then you'll be able to easily extend frame count that should be considered during calculation.</li>\n<li>Set maxRotationCount as const, as it won't change.</li>\n<li>Initialize list with size new List(maxRotationCount), you'll avoid copying data while list resizing.</li>\n<li><p>Little pseudo code for point 4 below. You can easily change interface to have two parameters, test for edge cases etc.</p>\n\n<pre><code>class SmoothnessCalculator\n{\n private readonly List&lt;Quaternion&gt; quaternions;\n\n public Calculator(int frameCountToStore)\n {\n this.quaternions = new List&lt;Quaternion&gt;(frameCountToStore);\n }\n\n public void Add(Quaternion quaternion)\n {\n if(this.quaternions.Count == this.quaternions.Capacity)\n {\n this.quaternions.RemoveAt(0);\n }\n\n this.quaternions.Add(quaternion);\n }\n\n public Quaternion SmoothRotation(double rate)\n {\n Quaternion result = null;\n\n for(int i = 0; i &lt; this.quaternions.Count - 1; i++)\n {\n var current = this.quaternions[i];\n var next = this.quaternions[i + 1];\n\n result = Quaternion.Larp(current, next, rate);\n }\n\n return result;\n }\n} \n</code></pre></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-14T13:45:47.907", "Id": "453782", "Score": "1", "body": "I think that removing the first quaternion when the list is full is a pretty bad side effect of the `Add` method." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-14T13:56:07.030", "Id": "453785", "Score": "1", "body": "Thanks for your input and example. I will take a look at it. regarding your first point, it only got deprecated in 2019.2, which is a newer version than i'm currently using (2019.1). Good to know that it's going to be deprecated when I do need to upgrade though." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-14T13:57:15.630", "Id": "453786", "Score": "1", "body": "The averaging process in your for loop doesn't give equal weights to all the quaternions in the quaternion buffer - later inputs have more weight this way. This may be acceptable, or can be compensated by tweaking the `rate` parameter." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-14T14:19:27.063", "Id": "453789", "Score": "1", "body": "@IEatBagels yep, definitely, name of method should be more specific, maybe Upsert (insert or update) or something similar :) maybe even change whole class interface just to one method SmoothRotation(Quanternion q, double rate)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-14T14:19:31.983", "Id": "453790", "Score": "0", "body": "@gazoh totally agree with you, with my change there'll be different results, thanks for your comment." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-14T16:53:26.443", "Id": "453809", "Score": "0", "body": "@KarolMiszczyk Actually, looking harder at it, it seems `result` is overwritten on each iteration of the loop, which is not the intended behaviour. Starting with `Quaternion result = quaternions[0]` and repeatedly averaging `result = Qaternion.Lerp(result, quaternions[i], rate)` would be a different behaviour but may actually lead to the desired visual output." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-14T11:17:19.057", "Id": "232375", "ParentId": "232371", "Score": "6" } }, { "body": "<p>To build upon Karol Miszczyk's answer, I'll take on the averaging function of multiple quaternions, and make it scaleable.</p>\n\n<p>The first option is to use a recursive function. It's scaleable, but you need to ensure the <code>quaternions</code> list has a count that is a power of 2.</p>\n\n<pre><code>/// &lt;summary&gt;\n/// Get the average value of a list of quaternion\n/// &lt;/summary&gt;\n/// &lt;param name=\"quaternions\"&gt;The list of quaternions to average. Count must be a power of 2 and at least 2&lt;/param&gt;\n/// &lt;returns&gt;The average quaternion&lt;/returns&gt;\n\npublic static Quaternion QuaternionAverageRecursive(List&lt;Quaternion&gt; quaternions)\n{\n if (quaternions.Count == 2)\n {\n return Quaternion.Lerp(quaternions[0], quaternions[1], 0.5f);\n }\n\n var quats1 = quaternions.GetRange(0, quaternions.Count / 2);\n var quats2 = quaternions.GetRange(quaternions.Count / 2, quaternions.Count / 2);\n\n return Quaternion.Lerp(QuaternionAverageRecursive(quats1), QuaternionAverageRecursive(quats2), 0.5f);\n}\n</code></pre>\n\n<p>It should give the exact same result as your method, but solves none of the potential performance issue.</p>\n\n<p>Another option is to average each quaternion with a partial average in a loop, similar to what Karol Miszczyk proposed, although his version seems to have bugs. Doing so naively would give more weight to the quaternions at the end of the list, which strays away from your original solution, but could be suitable to your case:</p>\n\n<pre><code>/// &lt;summary&gt;\n/// Get the average value of a list of quaternion using a naive accumulating algorithm\n/// &lt;/summary&gt;\n/// &lt;param name=\"quaternions\"&gt;The list of quaternions to average.&lt;/param&gt;\n/// &lt;returns&gt;&lt;/returns&gt;\npublic static Quaternion QuaternionAverageNaive(List&lt;Quaternion&gt; quaternions)\n{\n Quaternion result = quaternions[0];\n\n for (int i = 1; i &lt; quaternions.Count; i++)\n {\n result = Quaternion.Lerp(result, quaternions[i], 0.5f);\n }\n\n return result;\n}\n</code></pre>\n\n<p>It is suitable for any non-empty <code>List&lt;Quaternion&gt;</code> and should improve performance, but the results differ from the ones returned by your current method.</p>\n\n<p>Using the third parameter of <code>Quaternion.Lerp</code> to weight the values differently allows to get results close to your current solution:</p>\n\n<pre><code>/// &lt;summary&gt;\n/// Get the average value of a list of quaternion using a weighted accumulating algorithm\n/// &lt;/summary&gt;\n/// &lt;param name=\"quaternions\"&gt;The list of quaternions to average.&lt;/param&gt;\n/// &lt;returns&gt;&lt;/returns&gt;\npublic static Quaternion QuaternionAverageWeighted(List&lt;Quaternion&gt; quaternions)\n{\n Quaternion result = quaternions[0];\n\n for (int i = 1; i &lt; quaternions.Count; i++)\n {\n result = Quaternion.Lerp(result, quaternions[i], 1f / (i + 1f));\n }\n\n return result;\n}\n</code></pre>\n\n<p>It should have little cost on performance compared to the previous solution, and is still completely scalable. However, while this method would be exact when averaging numbers, the results differ slightly from your method. I suppose this is due to the quirkiness of quaternions, or may be caused by floating point errors, I'm not sure. It is stable, though (averaging a list of identical quaternions outputs the same quaternion), an can be applied to your case.</p>\n\n<p>Finally, answers to <a href=\"https://stackoverflow.com/questions/12374087/average-of-multiple-quaternions\">this question on StackOverflow</a> seem to indicate that getting the exact average implies solving a <code>4n * 4n</code> matrix for eigenvalues (n beein the number of quaternions), which is definitely doable and scalable, but probably sub-optimal performance-wise.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-14T17:43:02.587", "Id": "453819", "Score": "0", "body": "What a great addition! I will try those methods out tomorrow and report back as to which suited the best." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-15T14:10:17.013", "Id": "453925", "Score": "0", "body": "I've tried your suggestions, and stuck with `QuaternionAverageWeighted` due to its ease of reading, while being well within the margin with the results. A bounty will be coming your way once I can open one :)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-14T17:32:07.793", "Id": "232394", "ParentId": "232371", "Score": "4" } }, { "body": "<p>Building on the previous two answers, I like to suggest a different approach to smoothing the series of quaternions.</p>\n\n<p>Right now, you are weighting the past 16 frames equally, which is requiring you to keep all 16 rotations and use a bunch of calls to lerp them all together to get the average.</p>\n\n<p>A different, simpler to implement, approach is to use an exponentially weighted moving average as your smoothing function. That would look like:</p>\n\n<pre><code>public static Quaternion SmoothRotation(Quaternion nextFrame)\n{\n const float alpha = 0.118; // 2/(N+1), N is number of frames in equivalent simple moving average) \n lastFrame = Quaternion.Lerp(lastFrame, nextFrame, alpha);\n return lastFrame;\n}\nprivate static Quaternion lastFrame = Quaternion.Identity;\n</code></pre>\n\n<p>The results won't be exactly like your equally weighted moving average, but it should still smooth acceptably. The higher <code>alpha</code> is, the less smoothing will be done. The lower <code>alpha</code> is, the longer it takes to reach a steady state after a fast transition.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-15T15:09:46.957", "Id": "232448", "ParentId": "232371", "Score": "3" } } ]
{ "AcceptedAnswerId": "232375", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-14T08:53:25.577", "Id": "232371", "Score": "7", "Tags": [ "c#", "object-oriented", "unity3d" ], "Title": "Averaging quaternions" }
232371
<p>Please keep in mind that I am very new to data science and completely new to NLP! I am trying to create a model to classify customer reviews as either negative or positive. However, my main problem is that most of them are in Norwegian, which seems not to be very well supported. I have found this repo <a href="https://github.com/ltgoslo/norsentlex/tree/master/Fullform" rel="noreferrer">https://github.com/ltgoslo/norsentlex/tree/master/Fullform</a> containing both negative and positive lexicons and have decided to use it.</p> <pre><code>with open("Fullform_Positive_lexicon.txt") as f: reader = csv.reader(f) positive_lexicon = [] for row in reader: print(str(row)) positive_lexicon.append(row[0]) with open("Fullform_Negative_lexicon.txt") as f: reader = csv.reader(f) negative_lexicon = [] for row in reader: negative_lexicon.append(row[0]) #adjusted to use it with NaiveBayesClassifier def get_tokens_for_model(cleaned_tokens_list): final_token_list = [] for token in cleaned_tokens_list: token_dict = {} token_dict.update({token : True}) final_token_list.append(token_dict) return final_token_list positive_tokens_for_model = get_tokens_for_model(positive_lexicon) negative_tokens_for_model = get_tokens_for_model(negative_lexicon) positive_dataset = [(token, "Positive") for token in positive_tokens_for_model] negative_dataset = [(token, "Negative") for token in negative_tokens_for_model] dataset = positive_dataset + negative_dataset #shuffle dataset for i in range(len(dataset)-1, 0, -1): j = random.randint(0, i + 1) dataset[i], dataset[j] = dataset[j], dataset[i] train_data = dataset[:20000] test_data = dataset[7742:] classifier = NaiveBayesClassifier.train(train_data) print("Accuracy is:", classify.accuracy(classifier, test_data)) </code></pre> <p>So I am just training my model based on this lexicon and then I am trying to apply it to my comments. I am getting here 87%, which is not so bad. However, it looks worse when used with whole sentences.</p> <pre><code>with open("stopwords.csv") as f: reader = csv.reader(f) norwegian_stopwords = [] for row in reader: norwegian_stopwords.append(row[0]) customer_feedback = pd.read_excel("classification_sample.xlsx") customer_feedback = customer_feedback.dropna() customer_feedback['Kommentar'] = customer_feedback['Kommentar'].apply(remove_punctuation) list_of_comments = list(customer_feedback['Kommentar']) for comment in list_of_comments: custom_tokens = word_tokenize(comment) filtered_tokens = [] for word in custom_tokens: if word not in norwegian_stopwords: filtered_tokens.append(word) classification = classifier.classify(dict([token, True] for token in filtered_tokens)) probdist = classifier.prob_classify(dict([token, True] for token in filtered_tokens)) pred_sentiment = probdist.max() print("Sentence: " + comment) print("Classified as: " + str(classification)) print("Key words: " + str(custom_tokens)) print("Probability: " + str(round(probdist.prob(pred_sentiment), 2))) print("-----------------------------------------------------------") </code></pre> <p>I know my code is not the highest quality right now(although suggestions regarding this are also appreciated). I am looking mostly for some feedback what more can I do to improve my accuracy. What is currently not very clear to me, is how to properly train the model on words and then achieve the very same accuracy on sentences.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-14T11:58:31.887", "Id": "453756", "Score": "0", "body": "Hi, I have forgot to copy this piece of code. Its already there:)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-14T14:09:04.617", "Id": "453788", "Score": "0", "body": "Where is `word_tokenize` from? Is it from `nltk`? Please include your imports." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-14T18:09:48.587", "Id": "453825", "Score": "0", "body": "You would benefit from running your tokens through a lemmatizer or a stemmer. If the word \"glad\" is in your positive tokens list, you'll want to find \"glade\" and \"gladere\" too." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-15T06:26:32.740", "Id": "453881", "Score": "0", "body": "@Łukasz D. Tulikowski: have a word about suggested edit in [CR chat](https://chat.stackexchange.com/rooms/101063/suggested-edit-to-cr-q-232373)?" } ]
[ { "body": "<p>All of this:</p>\n\n<pre><code>def get_tokens_for_model(cleaned_tokens_list):\n final_token_list = [] \n for token in cleaned_tokens_list:\n token_dict = {}\n token_dict.update({token : True})\n final_token_list.append(token_dict)\n return final_token_list\n\npositive_tokens_for_model = get_tokens_for_model(positive_lexicon)\nnegative_tokens_for_model = get_tokens_for_model(negative_lexicon)\n\npositive_dataset = [(token, \"Positive\")\n for token in positive_tokens_for_model]\n\nnegative_dataset = [(token, \"Negative\")\n for token in negative_tokens_for_model]\n\ndataset = positive_dataset + negative_dataset\n#shuffle dataset\nfor i in range(len(dataset)-1, 0, -1): \n j = random.randint(0, i + 1) \n dataset[i], dataset[j] = dataset[j], dataset[i] \n</code></pre>\n\n<p>Is just a very verbose way to write:</p>\n\n<pre><code>dataset = [({token : True}, \"Positive\") for token in positive_lexicon]\ndataset.extend([({token : True}, \"Negative\") for token in negative_lexicon])\nrandom.shuffle(dataset)\n</code></pre>\n\n<p><s>The shuffling probabilities might be a bit different, though. <code>random.shuffle</code> basically has for each element equal probability to end up at any index. I think your method has a bias, but I'm not quite sure.</s></p>\n\n<p>At least your custom shuffling seems to be unbiased:</p>\n\n<p><a href=\"https://i.stack.imgur.com/nLIcz.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/nLIcz.png\" alt=\"enter image description here\"></a></p>\n\n<p>However, I had to fix it to this, because otherwise it raises an <code>IndexError</code>, because <code>random.randint</code> is inclusive of the end (in contrast to <code>range</code>, slices and <code>random.randrange</code>):</p>\n\n<pre><code>#shuffle dataset\nfor i in range(len(dataset)-1, 0, -1): \n j = random.randint(0, i) \n dataset[i], dataset[j] = dataset[j], dataset[i]\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-14T14:06:08.347", "Id": "232383", "ParentId": "232373", "Score": "3" } }, { "body": "<p><strong><em><h3>Ways to significantly improve performance and processing flow:</h3></em></strong></p>\n\n<p><em>Accumulating lexicon dataset</em> phase</p>\n\n<p>The first 2 <strong><code>for</code></strong> loops for accumulating <code>positive_lexicon</code> and <code>negative_lexicon</code> could at least be optimized with a list comprehension:</p>\n\n<pre><code>...\nreader = csv.reader(f)\npositive_lexicon = [row[0] for row in reader]\n</code></pre>\n\n<p>that's better, but not the best when reading large files. (we'll beat that in the <em>final</em> version below)</p>\n\n<p>The next 4 <strong><code>for</code></strong> loops are redundantly traversing the same sequences for just enriching each entry/token with <code>{token : True}</code>, then - with respective keyword flag <code>\"Positive\"/\"Negative\"</code>.</p>\n\n<p>Since all intermediate datasets are not used anywhere further and just intended to compose a combined final dataset <code>dataset = positive_dataset + negative_dataset</code> - all those <strong>6</strong> <code>for</code> loops can be substituted with a <strong>single</strong> efficient <em>generator</em> function which will be consumed just once and return the needed entries.<br>The final version for the 1st processing phase (lexicons/accuracy):</p>\n\n<pre><code>pos_lexicon_fname = \"Fullform_Positive_lexicon.txt\"\nneg_lexicon_fname = \"Fullform_Negative_lexicon.txt\"\n\ndef get_lexicon_dataset(pos_lexicon_fname, neg_lexicon_fname):\n with open(pos_lexicon_fname) as f:\n reader = csv.reader(f)\n for row in reader:\n yield ({row[0]: True}, \"Positive\")\n\n with open(neg_lexicon_fname) as f:\n reader = csv.reader(f)\n for row in reader:\n yield ({row[0]: True}, \"Negative\")\n\ndataset = list(get_lexicon_dataset(pos_lexicon_fname, neg_lexicon_fname))\n#shuffle dataset\n...\n</code></pre>\n\n<hr>\n\n<p><em>Stopwords/tokenizing/probability</em> phase:</p>\n\n<p><strong><code>norwegian_stopwords</code></strong> accumulation approach is better composed with a list comprehension:</p>\n\n<pre><code>with open(\"stopwords.csv\") as f:\n reader = csv.reader(f)\n norwegian_stopwords = [row[0] row in reader]\n</code></pre>\n\n<p>The code fragment which runs on each iteration (of the outer <code>for</code> loop):</p>\n\n<pre><code>...\nfiltered_tokens = []\nfor word in custom_tokens:\n if word not in norwegian_stopwords:\n filtered_tokens.append(word)\n\nclassification = classifier.classify(dict([token, True] for token in filtered_tokens))\nprobdist = classifier.prob_classify(dict([token, True] for token in filtered_tokens))\n</code></pre>\n\n<p>introduces 2 issues:</p>\n\n<ul>\n<li><code>filtered_tokens</code> is better accumulated with a list comprehension</li>\n<li>the same <code>filtered_tokens</code> sequence is then redundantly traversed twice</li>\n</ul>\n\n<p>But, considering that the <em>target</em> data structure for <em>classifying</em> operation is a dictionary of filtered tokens (<code>dict([token, True], ...)</code>) - the more optimized and straightforward way is to compose such a dictionary at once:</p>\n\n<pre><code>for comment in list_of_comments:\n custom_tokens = word_tokenize(comment)\n filtered_tokens_dict = {word: True for word in custom_tokens\n if word not in norwegian_stopwords}\n\n classification = classifier.classify(filtered_tokens_dict)\n probdist = classifier.prob_classify(filtered_tokens_dict)\n pred_sentiment = probdist.max()\n print(\"Sentence: \" + comment)\n ...\n</code></pre>\n\n<hr>\n\n<p><em>Things to remember:</em></p>\n\n<ul>\n<li><em>Generator expressions</em> don’t materialize the whole output sequence when they’re run. Instead, generator expressions evaluate to an iterator that yields one item at a time from the expression</li>\n<li><em>Generators</em> can produce a sequence of outputs for arbitrarily large inputs because their working memory doesn’t include all inputs and outputs</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-14T16:43:41.773", "Id": "232391", "ParentId": "232373", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-14T09:29:46.557", "Id": "232373", "Score": "8", "Tags": [ "python", "natural-language-processing" ], "Title": "NLP sentiment analysis in Norwegian" }
232373
<p>I have a piece of code (below) that checks a data table (45,000 rows) to see if the row matches any entries in a range elsewhere on the workbook (using custom functions). The routine then creates an array of Flags and writes that array back to a field in the table - so a series of Sumifs formulae reference only those records that are relevant to the user's selections.</p> <ul> <li><p>Edited to add Context:</p> <p>The data table is referenced by a Report sheet containing c. 22,000 Sumifs formulae (plus as many dependent formulae again) to create a Profit and Loss report. (and I <strong>know</strong> that it's probably not the best way to do it, but I'm bound by the end user, who wants it in excel and doesn't want to use a Pivot table, no matter how well designed). Maybe this is the reason that writing to the Table is so slow.</p></li> <li><p>Here's one of the sumifs: </p> <blockquote> <p>=$D14*SUMIFS(Table1[Value],Table1[Map Code],$B14,Table1[Service],$A14,Table1[Flag],"TRUE",Table1[Period],Z$5,Table1[Type],$AA$4,Table1[Year],$Z$4)</p> </blockquote> <p>So I can add in some helper cells and make those a bit more efficient, but there's still a lot of them.</p></li> </ul> <p>So here's the code</p> <pre><code>Sub flagselected() Dim datablock As Variant Dim x As Long, i As Integer Dim p As Integer Dim selectedUnits() As String Dim selectKey() As String Dim selectFlag() As Variant Dim startTime As Variant Dim midTime As Variant Dim endTime As Variant Dim postTrans As Variant Dim targetService As String, targetMapCode As Integer, multiplier As Integer Dim cell As Range, gap1 As Integer startTime = Now Application.ScreenUpdating = False Application.Calculation = xlCalculationManual datablock = Sheets("DataBlock").Range("Table1") selectedUnits = RangeToArray(Sheets("Tables").Range("SelectedCC")) ReDim selectKey(1 To UBound(datablock)) ReDim selectFlag(1 To UBound(datablock)) For x = LBound(datablock) To UBound(datablock) ' loops thru the datablock If Contains(selectedUnits, datablock(x, 2)) = True Then 'only considers this row if it's in selected units selectFlag(x) = True End If Next x midTime = Now selectFlag = Application.WorksheetFunction.Transpose(selectFlag) postTrans = Now ' Sheets("datablock").Range("table1[flag]").Value2 = selectFlag ' Commented out to test unload to range Sheets("datablock").Range("P2:p" &amp; UBound(selectFlag)).Value2 = selectFlag ' this range is outside the Table endTime = Now Debug.Print "Started " &amp; startTime Debug.Print "Variable filled " &amp; midTime Debug.Print "Transposed " &amp; postTrans Debug.Print "Unloaded to range " &amp; endTime 'Application.Calculation = xlCalculationAutomatic Application.Calculation = xlCalculationSemiautomatic End Sub </code></pre> <p>The code seems to work fine (although I'm sure can be improved) but it's the last activity that's tripping me up. When I try to populate the Flag field in the table with the array, it takes 18 or 19 seconds. When I comment that row out and populate a range on the same worksheet but outside of the Table, it's near instantaneous.</p> <p>Is there a table property or action that I can switch off for a short time while I write to it so that it's the same as writing to a simple range? There are a lot of formulae on the Workbook that reference the table, so I don't really want to convert it to a range and then recreate the table (unless that would leave formulae untouched?)</p> <p>The results of the debug.print rows are as follows</p> <p>when using <code>Sheets("datablock").Range("table1[flag]").Value2 = selectFlag</code></p> <blockquote> <p>Started 14/11/2019 09:15:01<br> Variable filled 14/11/2019 09:15:01<br> Transposed 14/11/2019 <strong>09:15:01</strong><br> Unloaded to range 14/11/2019 <strong>09:15:19</strong><br></p> </blockquote> <p>When using <code>Sheets("datablock").Range("P2:p" &amp; UBound(selectFlag)).Value2 = selectFlag</code></p> <blockquote> <p>Started 14/11/2019 09:18:30<br> Variable filled 14/11/2019 09:18:30<br> Transposed 14/11/2019 <strong>09:18:30</strong><br> Unloaded to range 14/11/2019 <strong>09:18:30</strong><br></p> </blockquote> <p>Edited to add the custom functions. I'll try Mattieu's suggestions tomorrow and revert.</p> <pre><code>Function Contains(arr, v) As Boolean Dim rv As Boolean, lb As Long, ub As Long, i As Long lb = LBound(arr) ub = UBound(arr) For i = lb To ub If arr(i) = v Then rv = True Exit For End If Next i Contains = rv End Function Function RangeToArray(ByVal my_range As Range) As String() Dim vArray As Variant Dim sArray() As String Dim i As Long vArray = my_range.value ReDim sArray(1 To UBound(vArray)) For i = 1 To UBound(vArray) sArray(i) = vArray(i, 1) Next RangeToArray = sArray() End Function </code></pre> <p>Thanks for help with formatting Question and responses so far.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-14T11:52:16.560", "Id": "453754", "Score": "0", "body": "The write times for a range and a table (listobject) are nearly identical. Are you using `Worksheet_Change` event by chance?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-14T11:59:54.520", "Id": "453757", "Score": "0", "body": "No - this sub runs as part of another routine where the User has selected one or more values from a listbox. The routine then populates the range SelectedCC and calls this sub. It's baffling me as I've tested it multiple times both with the line populating Table1[Flag] and the line populating the range, and the time difference is enormous" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-14T12:22:11.867", "Id": "453763", "Score": "1", "body": "Does `RangeToArray()` or `Contains()` change the calculation mode? I would test the calculation mode the line before writing the data." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-14T12:32:39.240", "Id": "453766", "Score": "0", "body": "Thanks for the tip - I'd not thought to look at those - but sadly, no. I even put in an extra line to set calc to manual again, just before the unload part of the routine, and the time difference between the 2 is still 19 seconds." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-14T16:56:33.860", "Id": "453810", "Score": "2", "body": "Would be nice to include the helper functions `RangeToArray` and `Contains`; that way reviewers could copy and compile your code making fewer assumptions." } ]
[ { "body": "<blockquote>\n<pre><code>Sub flagselected()\n</code></pre>\n</blockquote>\n\n<p>The procedure is implicitly <code>Public</code>. This is potentially confusing, because in most programming languages (including VB.NET) the implicit default would be <code>Private</code>. Consider always making all access modifiers explicit.</p>\n\n<p>Procedure names should be <code>PascalCase</code>, to adhere to both the naming conventions in place (everything in the VBA standard library and Excel object model uses this naming convention) and the modern naming conventions recommended for VB.NET code, which IMO apply perfectly well to VBA code too). Big huge kudos for avoiding Hungarian Notation prefixing though, but <code>alllowercase</code> isn't ideal.</p>\n\n<blockquote>\n<pre><code> Dim datablock As Variant\n Dim x As Long, i As Integer\n Dim p As Integer\n Dim selectedUnits() As String\n Dim selectKey() As String\n Dim selectFlag() As Variant\n Dim startTime As Variant\n Dim midTime As Variant\n Dim endTime As Variant\n Dim postTrans As Variant\n Dim targetService As String, targetMapCode As Integer, multiplier As Integer\n Dim cell As Range, gap1 As Integer\n</code></pre>\n</blockquote>\n\n<p>Don't do this to yourself, <em>especially</em> in procedure scopes that are any longer than just a handful of lines: this <em>Great Wall of Declarations</em> at the top of the procedure is a huge distraction, and only serves to make it harder to see what's used where.</p>\n\n<p>Instead, consider declaring local variables <em>where you're using them</em>. That way it's much harder to declare a variable... and then not use it anywhere.</p>\n\n<p><a href=\"http://rubberduckvba.com\" rel=\"nofollow noreferrer\">Rubberduck</a> (a free, open-source VBIDE add-in project I manage) can't find any uses for the following local variables, which are declared but never assigned or even referred to:</p>\n\n<ul>\n<li><code>i</code></li>\n<li><code>p</code></li>\n<li><code>targetService</code></li>\n<li><code>targetMapCode</code></li>\n<li><code>multiplier</code></li>\n<li><code>cell</code></li>\n<li><code>gap1</code></li>\n</ul>\n\n<p>It also warns about variables declared <code>As Integer</code>, strongly suggesting to use <code>As Long</code> instead.</p>\n\n<p>The 2-spaces indent is non-standard (default is 4 spaces), but it's consistent so it's not too distracting.</p>\n\n<blockquote>\n<pre><code> Application.ScreenUpdating = False\n Application.Calculation = xlCalculationManual\n</code></pre>\n</blockquote>\n\n<p>Whenever this global state is toggled, it should be obligatory to handle runtime errors: that way if anything goes wrong during execution, the global application state is guaranteed to always be reset back to what it was.</p>\n\n<p>But why toggle this <em>at all</em>, if we're only writing to a worksheet <em>once</em>? Disabling <code>ScreenUpdating</code> is useful when you have inefficient code with <code>.Select</code> and <code>.Activate</code> and Excel ends up spending more time repainting itself than running your code, and making <code>Calculation</code> manual is useful when you make so many worksheet writes that Excel is constantly recalculating - but here, none of this is happening: toggling off screen repaints and deferring calculations isn't buying you anything here - I'd just remove these instructions completely.</p>\n\n<blockquote>\n<pre><code>datablock = Sheets(\"DataBlock\").Range(\"Table1\")\n</code></pre>\n</blockquote>\n\n<p>There's quite a bit of implicit code going on here - this would be explicit equivalent:</p>\n\n<pre><code>datablock = ActiveWorkbook.Worksheets(\"DataBlock\").Range(\"Table1\").Value\n</code></pre>\n\n<p>Note that the implicit <code>ActiveWorkbook</code> reference is very much a potential bug: if the \"DataBlock\" sheet exists in <code>ThisWorkbook</code> (the VBA project's host document) at compile-time, then there's no need to dereference it from any <code>Sheets</code> collection - the worksheet has a <code>CodeName</code> that you can use anywhere in your VBA project: this \"code name\" is the sheet module's <code>(Name)</code> property. Set it to a valid VBA identifier name (e.g. <code>DataBlockSheet</code>), and then you can do this:</p>\n\n<pre><code>datablock = DataBlockSheet.Range(\"Table1\").Value\n</code></pre>\n\n<p>Now, this <em>looks</em> like you're getting the named <code>Range</code> for a <code>ListObject</code> table. Why not retrieve the actual <code>ListObject</code> reference and make it explicit that you're looking at a <code>ListObject</code> and not just any other <code>Range</code>?</p>\n\n<pre><code>datablock = DataBlockSheet.ListObjects(\"Table1\").DataBodyRange.Value\n</code></pre>\n\n<p>Out of 6 references to the <code>datablock</code> variable, 5 are passing it as an argument to <code>LBound</code> or <code>UBound</code>; the other is reading a specific value in the table, and is probably indeed more efficient as an in-memory array read - but the <code>LBound</code>/<code>UBound</code> stuff shouldn't need to be re-computed 5 times.</p>\n\n<blockquote>\n<pre><code>ReDim selectKey(1 To UBound(datablock))\nReDim selectFlag(1 To UBound(datablock))\n\nFor x = LBound(datablock) To UBound(datablock) ' loops thru the datablock\n</code></pre>\n</blockquote>\n\n<p>Because the array came from <code>Range.Value</code>, it's <em>necessarily</em> a 1-based, 2D variant array: the <code>LBound</code> will always be <code>1</code>. You've hard-coded that <code>1</code> in 2 places, and computing it for the <code>For x</code> loop - that's inconsistent, but it's good practice to never assume what array bounds are when looping, so kudos for that.</p>\n\n<p>I'd declare a local.</p>\n\n<pre><code>Dim datablockRows As Long\ndatablockRows = UBound(datablock)\n</code></pre>\n\n<p>And then...</p>\n\n<pre><code>ReDim selectKey(1 To datablockRows)\nReDim selectFlag(1 To datablockRows)\n\nFor x = 1 To datablockRows\n</code></pre>\n\n<p>Note that the <code>loops thru the datablock</code> comment isn't saying anything that the code isn't already sayign loud &amp; clear: it's redundant, and potentially distracting &amp; confusing. Imagine you rename <code>datablock</code> to <code>tableData</code>: the comment now needs to be updated, only to keep up with the code. Don't bother writing comments that say <em>what</em> - write comments that say <em>why</em> instead.</p>\n\n<blockquote>\n<pre><code>If Contains(selectedUnits, datablock(x, 2)) = True Then 'only considers this row if it's in selected units\n selectFlag(x) = True\nEnd If\n</code></pre>\n</blockquote>\n\n<p>That's a better comment already (although, the <code>Contains</code> method name is kind of already making that clear enough), but I suspect that results in something like <span class=\"math-container\">\\$O(n^2)\\$</span> complexity: you're iterating <em>up to</em> every single row in <code>selectedUnits</code> (presumably that's very <em>few</em> rows?) for every single row in <code>datablock</code>. We don't know how <code>Contains</code> is implemented, but it looks like it's basically reinventing the wheel of <code>WorksheetFunction.Match</code>, which as a native function <em>should</em> theoretically perform better than a VBA equivalent. I do like the abstraction, but to me <code>Contains</code> all by itself isn't sufficient to tell enough about its usage: <code>StringContains</code> would obviously be an abstraction over <code>InStr</code> / finding a given value within a string, and <code>ArrayContains</code> would obviously be an abstraction over finding a given value within an array.</p>\n\n<p>The Boolean literal value <code>True</code> is redundant in the conditional expression. <code>Contains</code> already returns a <code>Boolean</code>: it <em>is</em> a Boolean expression that <code>If</code> will be happy to work with.</p>\n\n<pre><code>If Contains(selectedUnits, datablock(x, 2)) Then\n</code></pre>\n\n<p>Now, that conditional is assigning to a literal Boolean value, and if there was an <code>Else</code> block it would be assigning the inverse value... but there's no <code>Else</code> block here, and <code>selectFlags</code> is a <code>Variant</code> array. This means the <code>selectFlags</code> array contains <code>Variant/True</code> and <code>Variant/Empty</code> after the loop.</p>\n\n<p>If having explicit <code>FALSE</code> Boolean literal values (rather than empty cells) is ok, then I'd recommend removing the conditional block, and assigning directly to the array subscript:</p>\n\n<pre><code>selectFlag(x) = Contains(selectedUnits, datablock(x, 2))\n</code></pre>\n\n<p>And now we get to the worksheet write operation...</p>\n\n<blockquote>\n<pre><code>Sheets(\"datablock\").Range(\"P2:p\" &amp; UBound(selectFlag)).Value2 = selectFlag\n</code></pre>\n</blockquote>\n\n<p>I like the version that doesn't assume what specific worksheet column the destination column is located in; this one will break if the table's <code>[flag]</code> column is moved anywhere. Actually it won't <em>break</em> - it'll just happily wreck the table by writing to the wrong column. Why assign to <code>Value2</code> though? You're using <code>Value</code> everywhere else. <code>Range.Value2</code> is useful when <em>reading</em> values that are of a <code>Date</code> or <code>Currency</code> data type, under certain specific circumstances (you get a <code>Double</code> instead of a <code>Date</code> or <code>Currency</code> - but most of the time you <em>want</em> to work with <code>Date</code> and <code>Currency</code> and not <code>Double</code>). ...but we're dealing with Boolean values here.</p>\n\n<p>The worksheet doesn't need to be dereferenced again, nor does the target range. It does, but only because you haven't persisted it to a local variable when you dereferenced it before the loop.</p>\n\n<p>I'd have a variable for the table, assigned near the beginning - just before <code>datablock</code> gets assigned:</p>\n\n<pre><code>Dim dataTable As ListObject\nSet dataTable = DataBlockSheet.ListObjects(\"Table1\")\n\nDim dataBlock As Variant\ndatablock = dataTable.DataBodyRange.Value\n</code></pre>\n\n<p>And with that you'd have a reference to your table for writing back the values:</p>\n\n<pre><code>dataTable.ListColumns(\"flag\").DataBodyRange.Value = selectFlag\n</code></pre>\n\n<p>Now, given this:</p>\n\n<blockquote>\n<pre><code>selectedUnits = RangeToArray(Sheets(\"Tables\").Range(\"SelectedCC\"))\n</code></pre>\n</blockquote>\n\n<p>You could probably scrap a lot of that code (if not all of it), and simply have a formula in the <code>flag</code> column, something that might look like this: </p>\n\n<pre><code>=NOT(ISERROR(MATCH([@Column2],SelectedCC[@Column1],0)))\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-14T22:46:20.923", "Id": "453858", "Score": "0", "body": "Excellent post as always +1.but I have couple nits to pick. You know far more about this stuff than I ever will but I think that it is a misnomer to say that `LBound()` and `UBound()`` compute the size of the Arrays. The size of the Arrays are computed at time of declaration or redeclaration. `LBound()` and `UBound()`` are simply referencing the Array's header information." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-14T22:46:34.803", "Id": "453859", "Score": "0", "body": "The difference in speed is roughly 12 MS per million cycles. I would elimiante `LBound()` because it is a given and I can type 1 a lot faster than `LBound(datablock)` . IMO `datablockRows` is just another brick to add to the Great Wall." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-14T22:51:59.527", "Id": "453861", "Score": "0", "body": "@TinMan that is correct - `LBound` and `UBound` are basically language keywords, not *quite* functions, and the array pointer just readily contains this information. Regardless, dereferencing that pointer 3 times in a row strikes me as redundant, hence introducing a local variable to hold it. As for performance, I paid zero attention to it..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-15T09:17:03.470", "Id": "453891", "Score": "0", "body": "@MathieuGuindon Many thanks for your superb critique. As you can see I'm self-taught and pretty new so it's much appreciated. Some went above my head, but I'll learn. I've edited the original post to provide more context (hope I've done it right). My first thought was to use a formula in the Flag field, however, that seemed to slow the whole model down to standstill. Hence my wish to write to the Field from vba. Which brings us back to the point of my original query. Writing to the table field is very much slower than writing to a range outside of the table." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-15T09:18:49.627", "Id": "453892", "Score": "0", "body": "And that's what I was trying to get to understand. I've made your suggested changes to the code, and yet still the very last step, writing to the table, takes 18 seconds - despite calculation being switched to manual. I'd have thought that manual calc would have meant that it didn't matter how many formulae reference the table?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-15T10:27:31.700", "Id": "453899", "Score": "0", "body": "Now I know that it IS because of the number of Sumifs pointing at the data table - I just deleted 98% of them from the Report page, and the write part of the routine runs in under a second. SO - why doesn't manual calc affect this, and is there a property of the Table that I can change to enable fast writing to it?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-15T13:39:22.887", "Id": "453923", "Score": "0", "body": "Interesting, I would expect the recalc to only happen when calculations are toggled back on. In any case, a recalc needs to happen since the cells involved have dependents, so there's no avoiding it either way. Does it recalc if you don't toggle it back to automatic?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-15T15:59:20.223", "Id": "453938", "Score": "0", "body": "Just tried it by commenting out the last 'resetting Calculation back to Auto\" command - it still took 19 seconds to write the array back to the Field, but the Sumifs had not calculated. Once I clicked Calculate it then took several seconds for the expected results to appear at the formulae. So it seems as if I'm getting double hit for time with the routine - once with the load array, and then again with the recalc - It's odd." } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-14T18:31:53.857", "Id": "232401", "ParentId": "232374", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-14T10:27:04.283", "Id": "232374", "Score": "2", "Tags": [ "performance", "vba", "excel" ], "Title": "Excel VBA code that writes to a Table - much slower than writing to a simple range" }
232374