body
stringlengths
25
86.7k
comments
list
answers
list
meta_data
dict
question_id
stringlengths
1
6
<p>I want to read a vector of eight bytes, convert them into hexadecimal, store them in a <code>std::string</code> and finally write them into a binary file.</p> <p>I am looking for suggestions and recommendations to improve the efficiency and readability of the code.</p> <pre><code>#include &lt;vector&gt; #include &lt;string_view&gt; #include &lt;iostream&gt; #include &lt;fstream&gt; #include &lt;cassert&gt; std::string hexify(std::vector&lt;unsigned char&gt; const &amp; v) { std::string str(2 * v.size(), 'x'); auto k = str.begin(); for(auto i{v.begin()}; i &lt; v.end(); ++i) { *k++ = &quot;0123456789ABCDEF&quot;[*i &gt;&gt; 4]; *k++ = &quot;0123456789ABCDEF&quot;[*i &amp; 0x0F]; } return str; } void writeFile(std::string_view str, std::string strToRead) { assert(str.data() != nullptr); std::ofstream f(str.data(), std::ios::binary); if(f.is_open()) { f &lt;&lt; strToRead; } f.close(); } int main() { std::vector&lt;unsigned char&gt; const v{'5', '1', '5', '7', '9'}; writeFile(&quot;text.bin&quot;, hexify(v)); } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-10T22:43:56.840", "Id": "475013", "Score": "0", "body": "And what's your question? Does the code work as intended?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-10T22:47:53.933", "Id": "475014", "Score": "0", "body": "Yes the code is working, but i need suggestions if i can improve anything here for efficiency." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-01T12:14:11.690", "Id": "513661", "Score": "1", "body": "Please do not change the code in the question after an answer has been posted. As mentioned in [this site guideline](https://codereview.stackexchange.com/help/someone-answers) it violates the question answer format of Code Review. Everyone who sees the answers needs to be able to understand what the reviewer saw." } ]
[ { "body": "<p>First off, your formatting is not very good. It makes it difficult to read. I would suggest looking at your IDE's menu options and use the format command.</p>\n\n<p>It seems like you're trying to reinvent the wheel here. The <code>&lt;ios&gt;</code> header contains that option already. To write the vector to a file as base 16 numbers, you can do that directly in the <code>writeFile</code> function:</p>\n\n<pre><code>void writeFile(std::string_view str, std::vector&lt;unsigned char&gt; const &amp; v)\n{\n\n assert(str.data() != nullptr);\n std::ofstream f(str.data(), std::ios::binary);\n for(auto c : v)\n {\n if(f.is_open())\n {\n f &lt;&lt; std::hex &lt;&lt; (int)c;\n }\n }\n f.close();\n}\n</code></pre>\n\n<p>If creating the string is more to the point than writing to the file, you can use a <code>stringstream</code> and do the same thing:</p>\n\n<pre><code>#include &lt;sstream&gt;\n\nstd::string hexify(std::vector&lt;unsigned char&gt; const &amp; v)\n{\n std::stringstream ss;\n for(auto c : v)\n {\n ss &lt;&lt; std::hex &lt;&lt; (int)c;\n }\n return ss.str();\n}\n</code></pre>\n\n<p>If characters with single digit character codes are to be used and the leading 0 is required, it's simply a matter of adding a couple of functions from the <code>&lt;iomanip&gt;</code> header:</p>\n\n<pre><code>&lt;&lt; std::setw(2) &lt;&lt; std::setfill('0') &lt;&lt; std::hex &lt;&lt; (int)c\n</code></pre>\n\n<p>If reinventing the wheel is the point, first there's a tag for that.</p>\n\n<p>When you have a need for literal (magic) use a constant variable. It gives meaning to anonymous values.</p>\n\n<p>Generally speaking when you're using iterators in a loop, since end() is past the last element, it's better to use not equals(<code>!=</code>) instead of less than.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-11T02:30:33.063", "Id": "475019", "Score": "0", "body": "What about leading 0, does `std::hex` handle these?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-11T02:56:30.283", "Id": "475022", "Score": "0", "body": "@RolandIllig - added code for that." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-11T11:14:25.340", "Id": "475049", "Score": "1", "body": "Instead of `const std::string hexDigits = \"0123456789ABCDEF\";`, use `constexpr std::string_view`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-11T13:00:45.167", "Id": "475070", "Score": "0", "body": "“it's much more efficient” — extremely unlikely. In fact, creating a `std::string` instance is marginally *less* efficient, especially if it’s a non-static local variable. If you use the code suggested by L.F., the performance will be on par with using inline literals, but still not “more” efficient, let alone “much more”." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-11T14:47:25.177", "Id": "475081", "Score": "0", "body": "@L.F. - I modified my answer" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-11T14:47:37.423", "Id": "475082", "Score": "0", "body": "@KonradRudolph - I modified my answer" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-11T15:51:28.687", "Id": "475089", "Score": "0", "body": "@tinstaafl is it really necessary to cast to `int`, and if so why are you using a c-style cast?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-11T16:13:59.710", "Id": "475091", "Score": "0", "body": "Yes it is necessary. The `ostream` will treat a char as a char not an int. In this case, since `char` is basically an int already I didn't see any major advantage to using a c++-style cast." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-12T00:37:21.180", "Id": "475112", "Score": "0", "body": "Re *\"your formatting is not very good\"*: Can you be more specific (by [editing your answer](https://codereview.stackexchange.com/posts/242055/edit), not here in comments)? What in particular is wrong with it? There is the missing indentation, but is there anything else? Can you give a concrete example of an IDE that can actually do it (it hasn't been common in IDEs until recently, probably for good reason)?" } ], "meta_data": { "CommentCount": "9", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-10T23:43:03.627", "Id": "242055", "ParentId": "242052", "Score": "7" } }, { "body": "<p><em>Disclaimer: if you want to use <code>std::ostream</code> and its manipulators, see <a href=\"https://codereview.stackexchange.com/a/242055/8999\">@tinstaafl</a>'s answer.</em></p>\n\n<h3>Principle of least capabilities</h3>\n\n<p>Your functions arguments are over-constrained, compared to what is actually necessary:</p>\n\n<ul>\n<li><code>hexify</code> does not need to take a <code>vector</code>, any sequence of <code>unsigned char</code> would work.</li>\n<li><code>writeFile</code> does not need to take a <em>copy</em> of a <code>string</code>.</li>\n</ul>\n\n<h3>Careful about that <code>string_view</code></h3>\n\n<p>Unfortunately, <code>std::ofstream</code> interface is antique: it still expects a C-String as an argument.</p>\n\n<p>This does not mesh well with <code>string_view</code>, because <code>string_view</code> does not guarantee NUL-termination.</p>\n\n<p>Thus the first argument to <code>writeFile</code> should be either <code>char const*</code> or <code>std::string const&amp;</code>. I would advise the former as per the principle of least capabilities.</p>\n\n<h3>No Magic Constant</h3>\n\n<p>You use the literal <code>\"0123456789ABCDEF\"</code> twice:</p>\n\n<ul>\n<li>That's one two many.</li>\n<li>It's better to give a name to constants.</li>\n</ul>\n\n<h3>Range-for loops are awesome</h3>\n\n<p>There is place for iterator-based loops or index-based loops: when you do something tricky.</p>\n\n<p>When you <em>don't</em> do anything special, however, use the range-for loop form: <code>for (auto x : range) { ... }</code>.</p>\n\n<p>It immediately announces loud and clear that you're not doing anything tricky -- freeing brain cells for the reader -- and it guarantees that the loop is done as efficiently as possible -- not calling <code>v.end()</code> at every iteration, notably.</p>\n\n<h3>Implicit is more lightweight</h3>\n\n<p>There are perfectly good reasons to check that a file is open, or not, it allows reacting differently.</p>\n\n<p>Similarly, closing a file manually rather than relying on the destructor to close allows checking for errors.</p>\n\n<p>If you don't do anything special if it's not open, and you don't check whether close succeeded, then there's little point in doing either explicitly: it just clutters the code.</p>\n\n<hr>\n\n<p>With all the above in mind.</p>\n\n<pre><code>// - Principle of least capabilities, short of going template.\n// - No Magic Constant.\n// - Range-for loop.\nstd::string hexify(gsl::span&lt;unsigned char&gt; v) {\n static constexpr char HEXITS[] = \"0123456789ABCDEF\";\n\n std::string str(2 * v.size(), '\\0');\n auto k = str.begin();\n\n for(auto c : v) {\n *k++ = HEXITS[c &gt;&gt; 4];\n *k++ = HEXITS[c &amp; 0x0F];\n }\n\n return str;\n}\n\n// - Principle of least capabilities.\n// - Careful about string_view.\n// - Implicit is more lightweight.\nvoid writeFile(char const* filename, std::string const&amp; content) {\n assert(filename != nullptr);\n std::ofstream f(filename, std::ios::binary);\n\n f &lt;&lt; content;\n}\n\n// Looking good!\nint main() {\n std::vector&lt;unsigned char&gt; const v{'5', '1', '5', '7', '9'};\n writeFile(\"text.bin\", hexify(v));\n}\n</code></pre>\n\n<hr>\n\n<p>There are further potential improvements, notably around <em>memory allocations</em>.</p>\n\n<p>Your code first allocates a string, then writes that string in the buffer of an <code>ofstream</code>: why not cut the middleman?</p>\n\n<p>Instead you could have <code>hexify</code> take a <code>std::ostream&amp;</code> as argument, and stream into it directly: <code>hexify</code> would still know nothing of writing to a file, so would be equally easy to use outside that context, and to test, just without the extraneous memory allocation.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-11T15:08:39.800", "Id": "242082", "ParentId": "242052", "Score": "6" } }, { "body": "<p>A somewhat more advanced alternative could be to use iostream operators. In your example you are writing the hex data to a string, and then writing the string to a file. You could argue that this is inefficient, and the hex data could be directly written to the file in the first place without using the string for temporary storage.</p>\n\n<p>Here is an example of one way you could do this. Note however that although it is marginally more efficient, it is also more verbose and more difficult to read. This is a good lesson that sometimes code that is more efficient to run is not necessarily more efficient for a human to read and maintain.</p>\n\n<p>When optimising your code you need to strike a balance between the fastest leanest code possible, and something that other people can easily understand. Otherwise what is the point of saving a few seconds of execution time over the life of your program when it takes other less experienced people in your team hours to figure out what the code does?</p>\n\n<pre><code>#include &lt;cstdint&gt; // uint8_t etc.\n#include &lt;fstream&gt;\n#include &lt;iomanip&gt;\n#include &lt;iostream&gt;\n#include &lt;vector&gt;\n\n// We'll make a typedef so we don't have to keep typing the whole vector thing\n// everywhere, and we'll use the newer uint8_t type rather than the less obvious\n// 'unsigned char'.\ntypedef std::vector&lt;uint8_t&gt; buffer;\n\n// We need to make a custom type so we can control which function the compiler will call.\nstruct hexbuffer {\n // Taking a const reference is risky, but we know in this case the lifetime of the\n // hexbuffer will match the lifetime of innerbuf, so we will be safe. This is\n // another potentially dangerous optimisation that requires careful understanding\n // of variable scope and lifetime. If we get it wrong the program could crash,\n // and worst case someone could exploit the crash and use it to hack into the\n // computer running this program.\n const buffer&amp; innerbuf;\n};\n\n// This is our iostream function. All it does is wrap the parameter up in the custom\n// type so that the intended operator function below is the one that gets called.\nhexbuffer hexify(const buffer&amp; b)\n{\n return { b };\n}\n\n// This operator overload is what does all the work. Overloads require a unique function\n// signature, which we achieve here by having one of the parameters be our custom type.\nstd::ostream&amp; operator &lt;&lt; (std::ostream&amp; s, const hexbuffer&amp; h)\n{\n // Set up the stream first as it only has to be done once.\n s &lt;&lt; std::setw(2) &lt;&lt; std::setfill('0') &lt;&lt; std::hex;\n\n // Write the hex data.\n for (auto c : h.innerbuf) {\n s &lt;&lt; (int)c &lt;&lt; ' ';\n }\n\n // iostream operators require us to return the same value we were passed. This\n // allows them to &lt;&lt; be &lt;&lt; chained &lt;&lt; together. In other languages you see this\n // same pattern as().chained().functions().\n return s;\n}\n\n// Now all the hard stuff is done, actually using it is pretty easy.\nint main()\n{\n buffer example{'5', '1', '5', '7', '9'};\n\n // We can use our function to write to the console.\n std::cout &lt;&lt; hexify(example) &lt;&lt; std::endl;\n\n // Or we can use it to write to a file.\n std::ofstream f(\"text.bin\");\n f &lt;&lt; hexify(example);\n f.close();\n\n return 0;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-11T15:19:54.693", "Id": "242084", "ParentId": "242052", "Score": "4" } } ]
{ "AcceptedAnswerId": "242055", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-10T22:40:38.677", "Id": "242052", "Score": "6", "Tags": [ "c++", "io", "c++17", "converting" ], "Title": "Conversion into hexadecimal using C++" }
242052
<p>I am brand new to writing my own code. I just started the CS50x intro class and have so far made it to pset 2 readability. It's getting easier to understand what's going on. I just wanted to get some opinions on the code that I wrote to see if there were possible improvements/changes that I could make.</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;cs50.h&gt; #include &lt;string.h&gt; #include &lt;ctype.h&gt; #include &lt;math.h&gt; //initialize lenght function int length(string str, char check); int main(void) { //Get user input string input = get_string("Text: "); //Calculate and set grade level. Take user input and run it thorugh the lenght function. l for letters, w for words and s for sentances. float gradeLevel = (0.0588 * (100 * (float) length(input, 'l') / (float) length(input, 'w')) - 0.296 * (100 * (float) length(input, 's') / (float) length(input, 'w'))) - 15.8; //output grade level if (round(gradeLevel) &gt;= 16) { printf("Grade 16+\n"); } else if (round(gradeLevel) &lt; 1) { printf("Before Grade 1\n"); } else { printf("Grade %i\n", (int) round(gradeLevel)); } //print lengths for testing /* printf("%i letter(s)\n", length(input, 'l')); printf("%i word(s)\n", length(input, 'w')); printf("%i sentance(s)\n", length(input, 's')); */ } //function to get length of letters, words and sentences int length(string str, char check) { int letterCount = 0; int wordCount = 1; int senCount = 0; int n = strlen(str); //check letter count if (check == 'l') { for (int i = 0; i &lt; n; i++) { if (isalpha(str[i])) { letterCount++; } } return letterCount; } //check word count else if (check == 'w') { for (int i = 0; i &lt; n; i++) { if (str[i] == ' ' || str[i] == '\n' || str[i] == '\t') { wordCount++; } } return wordCount; } //check sentance count else if (check == 's') { for (int i = 0; i &lt; n; i++) { if (str[i] == '.' || str[i] == '!' || str[i] == '?') { senCount++; } } return senCount; } return 0; } </code></pre> <p>Thank you for the detailed feedback. Here's the specs of the program</p> <p>Your program should count the number of letters, words, and sentences in the text. You may assume that a letter is any lowercase character from a to z or any uppercase character from A to Z, any sequence of characters separated by spaces should count as a word, and that any occurrence of a period, exclamation point, or question mark indicates the end of a sentence.</p> <p>Your program should print as output "Grade X" where X is the grade level computed by the Coleman-Liau formula, rounded to the nearest integer.</p> <p>If the resulting index number is 16 or higher (equivalent to or greater than a senior undergraduate reading level), your program should output "Grade 16+" instead of giving the exact index number. If the index number is less than 1, your program should output "Before Grade 1".</p> <p>The algorithm used was the Coleman-Liau index</p>
[]
[ { "body": "<p>You're off to a great start! This is reasonably readable, and I'm sure you'll get better with practice.</p>\n\n<hr>\n\n<pre><code>lenght\n</code></pre>\n\n<p>Typo. I make tons of typos myself. I highly recommend getting an IDE with a spell checker.</p>\n\n<hr>\n\n<pre><code>string input = ...\n</code></pre>\n\n<p>This confused me at first. It has to be a typedef, but what kind of typedef makes sense? Turns out in <code>&lt;cs50.h&gt;</code>, they <code>typedef char *string;</code>. This is a little weird to me because <code>char*</code> is a very familiar type -- I instantly know a few things to look for/what operations you can do with that. <code>string</code> is an unknown entity. I think <code>char* input = ...</code> is clearer.</p>\n\n<hr>\n\n<pre><code>float gradeLevel = (0.0588 * (100 * (float) length(input, 'l') / (float) length(input, 'w')) - 0.296 * (100 * (float) length(input, 's') / (float) length(input, 'w'))) - 15.8;\n</code></pre>\n\n<p>This line is so long! Breaking it down and simplifying a bit:</p>\n\n<pre><code>float l_over_w = (float) length(input, 'l') / (float) length(input, 'w');\nfloat s_over_w = (float) length(input, 's') / (float) length(input, 'w');\nfloat gradeLevel = (5.88 * l_over_w - 29.6 * s_over_w) - 15.8;\n</code></pre>\n\n<ol>\n<li>I have no idea where the numbers 5.88, 29.6, and 15.8 came from.</li>\n<li>Maybe the <code>div</code> function would help you instead of casting to float? <code>float</code>s are slow and have a lot of idiosyncrasies... IMO they are best to avoid unless you absolutely MUST use them.</li>\n<li>I find the general idea here non-obvious. How about some comments?</li>\n<li>This could be a function <code>float gradeLevel(char* input);</code></li>\n</ol>\n\n<hr>\n\n<pre><code>int length(string str, char check)\n</code></pre>\n\n<p>You've used <code>check</code> to determine what this function should do. That's generally a bad idea, but if you cannot avoid it, <strong>at least</strong> <code>assert(false)</code> if check is invalid. That way you get a runtime error if <code>check</code> is wrong. As you've written it, you'll silently get the wrong answer if <code>check</code> is wrong.</p>\n\n<p>In this case, it is trivial to do better. You could have several functions: <code>int letterCount(char* str);</code>, <code>int wordCount(char* str);</code>, and <code>int sentenceCount(char* str);</code>. This way you get a compiler error if you write the wrong function name (and you can't get <code>check</code> wrong since <code>check</code> doesn't exist).</p>\n\n<hr>\n\n<pre><code>int letterCount = 0;\nint n = strlen(str);\nfor (int i = 0; i &lt; n; i++) {\n if (isalpha(str[i])) {\n letterCount++;\n }\n}\nreturn letterCount;\n</code></pre>\n\n<p>This is OK, but you go over the string once to compute <code>strlen</code> and once to compute <code>letterCount</code>. You can do them at the same time:</p>\n\n<pre><code>int letterCount = 0;\nfor (int i = 0; str[i]; i++) {\n if (isalpha(str[i])) {\n letterCount++;\n }\n}\nreturn letterCount;\n</code></pre>\n\n<p>I think this is also nicer since you don't have an <code>n</code> to worry about. You could further simplify this to get rid of the index and just have the pointer:</p>\n\n<pre><code>while (str) {\n letterCount += isalpha(*str++);\n}\n</code></pre>\n\n<p>but maybe that's overkill.</p>\n\n<p>N.B. at least you didn't write <code>for (int i = 0; i &lt; strlen(str); i++)</code> which goes over the string once per character!</p>\n\n<hr>\n\n<pre><code>(str[i] == ' ' || str[i] == '\\n' || str[i] == '\\t')\n</code></pre>\n\n<p>How about <code>isspace(str[i])</code>?</p>\n\n<hr>\n\n<pre><code>(str[i] == '.' || str[i] == '!' || str[i] == '?')\n</code></pre>\n\n<p>How about <code>ispunct(str[i])</code>? Not an exact match so be careful.</p>\n\n<p>Here's a list of similar functions available <a href=\"https://linux.die.net/man/3/ispunct\" rel=\"nofollow noreferrer\">https://linux.die.net/man/3/ispunct</a>.</p>\n\n<hr>\n\n<pre><code>//print lengths for testing\n/* ...\n</code></pre>\n\n<p>This is totally fine for a personal project, but there are lots of testing frameworks that will always compile your test code but only run it under certain conditions. Might be worth researching. Here's a list to get you started <a href=\"https://en.wikipedia.org/wiki/List_of_unit_testing_frameworks#C\" rel=\"nofollow noreferrer\">https://en.wikipedia.org/wiki/List_of_unit_testing_frameworks#C</a>.</p>\n\n<hr>\n\n<p>Do you need to deallocate the string returned by <code>get_string</code>?</p>\n\n<hr>\n\n<p>Is the number of words equal to the number of spaces? What about this string <code>with lots of white-spaces....</code>. How many sentences are in that string? I don't know the answer to these questions (maybe the exercise tells you what to compute?), but I think it's interesting to think about.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-16T21:35:33.333", "Id": "475753", "Score": "0", "body": "You are not the only one who is confused by the wrong `typedef` for `string`. See [here](https://github.com/cs50/libcs50/issues/163) and [here](https://github.com/cs50/libcs50/issues/175). Feel free to complain to these irresponsible teachers, they need to be told more often that they are wrong and that they are doing harm to their many students. :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-16T21:51:43.143", "Id": "475759", "Score": "0", "body": "Appreciate the detailed feedback. I noticed a few of the items you pointed out has an * ie. char*. I need to look into what this actually does. In regards to separating the checks into their own functions, I was thinking better to consolidate into one. Is it generally ok to create multiple functions even if for small things? As for the typos thanks for pointing them out. Had no idea I had so many. I've taken your suggestion and setup codeblocks. Seems general consensus is this is a good IDE for beginners, although it's been quite a learning curve compared to the CS50 IDE I've been using." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-16T23:44:11.903", "Id": "475765", "Score": "0", "body": "Any ide you like is good. I recommend trying a few now and again to try new features. Small functions are fine -- do whatever is clearest by default. When you're first starting out there will be things you don't understand/don't even notice (like pointers/typedefs). Do try to learn them but when you're starting it's ok if you don't totally understand everything. Still, learn the correct practices from the start and soon things will fall into place" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-16T12:28:24.570", "Id": "525573", "Score": "0", "body": "*\"letterCount += isalpha(*str++);\"* - Yep, that's overkill" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-11T03:39:06.947", "Id": "242060", "ParentId": "242053", "Score": "3" } }, { "body": "<p><strong>Indentation</strong></p>\n\n<p>Much about indentation is a <em>style issue</em>. Best to follow your group's style guide. That said I would align comment with code.</p>\n\n<pre><code>//check letter count\n if (check == 'l')\n</code></pre>\n\n<p>to</p>\n\n<pre><code> // check letter count\n if (check == 'l')\n</code></pre>\n\n<p><strong>Spell check</strong></p>\n\n<p>Spelling errors are a distraction and a confusion.</p>\n\n<p><strong><code>double</code> vs. <code>float</code></strong></p>\n\n<p>In C, <code>double</code> is the default type for floating point constants like <code>0.0588</code>. Code is going through lots of gyrations converting form <code>int</code> to <code>float</code> to <code>double</code> and back to <code>float</code>. I suggest using <code>double</code> unless required to use <code>float</code> or code has <em>lots</em> of FP. </p>\n\n<pre><code>// float gradeLevel = (0.0588 * (100 * (float) length(input, 'l') / (float) length(input, 'w')) - 0.296 * (100 * (float) length(input, 's') / (float) length(input, 'w'))) - 15.8;\ndouble gradeLevel = 0.0588 * (100.0 * length(input, 'l') / length(input, 'w'))\n - 0.296 * (100.0 * length(input, 's') / length(input, 'w')) - 15.8;\n</code></pre>\n\n<p>If staying with <code>float</code>, use <code>float</code> constants: <code>0.0588</code> --> <code>0.0588f</code></p>\n\n<p><strong>Rounding (advanced)</strong></p>\n\n<p><code>round()</code>returns a <code>double</code>. C provides a nice way to round a <em>floating point</em> to an integer type in one step</p>\n\n<pre><code>long gradeLevel = lround(0.0588 * (100.0 * length(input, 'l') / length(input, 'w'))\n - 0.296 * (100.0 * length(input, 's') / length(input, 'w')) - 15.8);\n...\nprintf(\"Grade %ld\\n\", gradeLevel);\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-16T21:35:37.210", "Id": "475754", "Score": "0", "body": "Appreciate the review! Didn't realize I had so many typos lol. Definitely need to learn more about the different data types available." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-11T23:42:44.390", "Id": "242105", "ParentId": "242053", "Score": "2" } }, { "body": "<p>One of my favorite topics for code review and rants is the <code>&lt;ctype.h&gt;</code> header. It defines functions like <code>isalpha</code> that <em>sound</em> as if they would operate on characters (<code>char</code>), but they don't. They operate on numbers (<code>int</code>) instead, which is obviously confusing, but that's the way it is in C and C++.</p>\n\n<p>The short answer is to never call <code>isalpha</code> with a <code>char</code> as argument. Always use an <code>unsigned char</code>, for example like this:</p>\n\n<pre><code>if (isalpha((unsigned char) str[i])) {\n ...\n}\n</code></pre>\n\n<p>If you want to know more about the background, I've written <a href=\"https://stackoverflow.com/a/60696378\">a lengthy answer to another question</a> that contains many more details.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-16T21:55:40.607", "Id": "475761", "Score": "0", "body": "Thank you! I'll take a look at your previous answer." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-16T21:45:28.693", "Id": "242423", "ParentId": "242053", "Score": "1" } } ]
{ "AcceptedAnswerId": "242060", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-10T22:49:17.050", "Id": "242053", "Score": "4", "Tags": [ "c" ], "Title": "CS50x Readability improvement" }
242053
<p>To practice Object-Oriented Python and learning how to write tests, I found an exercise and solved it as below(all classes are put in one block of code to make the question a little bit more readable):</p> <pre><code>import sys import random from typing import List, Tuple, Dict, Optional from abc import ABC, abstractmethod class Card: SUITS = "♠ ♡ ♢ ♣".split() RANKS = "2 3 4 5 6 7 8 9 10 J Q K A".split() def __init__(self, suit: str, rank: str) -&gt; None : self.suit = suit self.rank = rank @property def suit(self) -&gt; str: return self.__suit @property def rank(self) -&gt; str: return self.__rank @suit.setter def suit(self, suit): if suit not in self.__class__.SUITS: raise ValueError("Invalid Card Suit") self.__suit = suit @rank.setter def rank(self, rank): if rank not in self.__class__.RANKS: raise ValueError("Invalid Card Rank") self.__rank = rank def __repr__(self) -&gt; str : return f"{self.__suit}{self.__rank}" def __hash__(self): return hash((self.__suit, self.__rank)) def __eq__(self, second) -&gt; bool: return self.__suit == second.suit and self.__rank == second.rank def __gt__(self, second) -&gt; bool: """ Specifies whether this card is greater than another card NOTICE: if the suits are different, returns False. """ rankNums = {rank: num for (rank, num) in zip(list("23456789")+["10"]+list("JQKA"), range(2,15))} if second.suit == self.__suit: if rankNums[self.__rank] &gt; rankNums[second.rank]: return True return False class Trick: HEARTS_ALLOWED: bool = False def __init__(self, cards: Optional[Tuple[Card, ...]]=None): self.__cards: Tuple[Card,...] = cards @property def cards(self) -&gt; Tuple[Card,...]: return self.__cards def get_points(self): points = 0 for card in self.__cards: if card.suit == "♡": points += 1 elif card.suit == "♠" and card.rank == "Q": points += 13 return points def add_card(self, card: Card): if self.cards and len(self.cards) &gt;= 4: raise ValueError("More than 4 cards cannot be added to a trick") if self.cards and card in self.cards: raise ValueError("The same card cannot be added to a trick twice") if self.__cards: self.__cards = (*self.__cards, card) else: self.__cards = (card,) def get_winCard_idx(self) -&gt; int: """ returns the turn number in which the winner card of the trick was played """ winIdx = 0 maxCard: Card = self.__cards[0] for idx, card in enumerate(self.__cards): if card &gt; maxCard: winIdx = idx maxCard = card return winIdx class Deck: def __init__(self, **kwargs) -&gt; None : """ possible keyword arguments: cards: Optional[List[Card]]=None shuffle: bool=False """ self.cards_setter(kwargs) def cards_getter(self) -&gt; List[Card]: return self.__cards def cards_setter(self, kwargs): cards = kwargs["cards"] if "cards" in kwargs else None shuffle = kwargs["shuffle"] if "shuffle" in kwargs else False if not cards: cards = [Card(s, r) for r in Card.RANKS for s in Card.SUITS] if shuffle: random.shuffle(cards) self.__cards: List[Card] = cards cards = property(cards_getter, cards_setter) def __iter__(self) -&gt; Card: yield from self.cards def deal(self) -&gt; Tuple["Deck", "Deck", "Deck", "Deck"] : """Deal the cards in the deck into 4 hands""" cls = self.__class__ return tuple(cls(cards=self.__cards[i::4]) for i in range(4)) class Player(ABC): def __init__(self, name: str, hand: Deck) -&gt; None: self.name: str = name self.hand: Deck = hand self.tricksPointsSum: int = 0 self.roundsPointsSum: int = 0 @property def name(self) -&gt; str: return self.__name @name.setter def name(self, name): self.__name = name @property def hand(self) -&gt; Deck: return self._hand @hand.setter def hand(self, cards: Deck): self._hand = cards @property def tricksPointsSum(self) -&gt; int: return self.__tricksPointsSum @tricksPointsSum.setter def tricksPointsSum(self, tricksPointsSum: int): self.__tricksPointsSum = tricksPointsSum @property def roundsPointsSum(self) -&gt; int: return self.__roundsPointsSum @roundsPointsSum.setter def roundsPointsSum(self, roundsPointsSum: int): self.__roundsPointsSum = roundsPointsSum def play_card(self, trick: Trick) -&gt; Trick: if Card("♣","2") in self._hand: yield self.__play_this(Card("♣","2"), trick) while True: playable = self.__get_playable_cards(trick) chosen_card = self._prompt_choice(playable) yield self.__play_this(chosen_card, trick) def __play_this(self, card: Card, trick: Trick) -&gt; Trick: trick.add_card(card) print(f"{self.__name} -&gt; {card}") self._hand.cards.remove(card) return trick def __get_playable_cards(self, trick: Trick) -&gt; List[Card]: if not trick.cards: if Trick.HEARTS_ALLOWED: return self._hand.cards else: lst = list(filter(lambda card: card.suit != "♡" , self._hand)) if lst: return lst else: Trick.HEARTS_ALLOWED = True return self.__get_playable_cards(trick) else: trickSuit = trick.cards[0].suit if self.has_card(trickSuit): return list(filter(lambda card: card.suit == trickSuit, self._hand)) else: Trick.HEARTS_ALLOWED = True return self._hand.cards def has_card(self, suit, rank: Optional[str] = None) -&gt; bool: if rank: if Card(suit, rank) in self._hand: return True else: for card in self._hand: if card.suit == suit: return True return False @abstractmethod def _prompt_choice(self, playable: Deck) -&gt; Card: pass class HumanPlayer(Player): def _prompt_choice(self, playable: Deck) -&gt; Card: rankNums = {rank: num for (rank, num) in zip(list("23456789")+["10"]+list("JQKA"), range(2,15))} sortedPlayable = sorted(playable, key=lambda card: (card.suit, rankNums[card.rank])) [print(f"\t{idx}: {card} ", end="") for idx, card in enumerate(sortedPlayable)] print("(Rest: ", end="") for nonPlayableCard in list(set(self._hand.cards)-set(playable)): print(nonPlayableCard, end="") print(" ", end="") print(")") while True: print(f"\t{self.name}, choose card: ", end="") try: choiceCardIdx: int = int(input()) except ValueError: continue if choiceCardIdx &lt; len(sortedPlayable): break return sortedPlayable[choiceCardIdx] class AutoPlayer(Player): def _prompt_choice(self, playable: Deck) -&gt; Card: rankNums = {rank: num for (rank, num) in zip(list("23456789")+["10"]+list("JQKA"), range(2,15))} sortedPlayable = sorted(playable, key=lambda card: (card.suit, rankNums[card.rank])) return sortedPlayable[0] class Game: def __init__(self, numOfHumans: Optional[int] = 1, *playerNames: Optional[str]) -&gt; None: """Set up the deck and create the 4 players""" self.__roundNumber: int = 1 self.__names: List[str] = (list(playerNames) + "P1 P2 P3 P4".split())[:4] self.__players: List[Player] = [ HumanPlayer(name, hand) for name, hand in zip(self.__names[:numOfHumans], [None]*numOfHumans)] self.__players.extend((AutoPlayer(name, hand) for name, hand in zip(self.__names[numOfHumans:], [None]*(4-numOfHumans)) )) def __set_new_round(self): deck = Deck(shuffle=True) hands = deck.deal() for idx, player in enumerate(self.__players): player.hand = hands[idx] def play(self) -&gt; int: """Play the card game""" while max(player.roundsPointsSum for player in self.__players) &lt; 100: """ while no one has lost the whole game """ self.__set_new_round() # continue the round by playing the rest of the tricks winnerPlayer: Optional[Player] = None while self.__players[0].hand.cards: trick = Trick() turnOrder = next(self.__player_order(winnerPlayer)) for player in turnOrder: trick = next(player.play_card(trick)) winnerIdx = trick.get_winCard_idx() winnerPlayer = turnOrder[winnerIdx] winnerPlayer.tricksPointsSum += trick.get_points() turnOrder = self.__player_order(winnerPlayer) print(f"{winnerPlayer.name} wins the trick\n{'*'*17}") # end of round print(f"{'-'*50}\nEnd Of Round {self.__roundNumber}\n{'-'*50}") # save the round scores for player in self.__players: player.roundsPointsSum += player.tricksPointsSum print(f"{player.name}: {player.roundsPointsSum}") player.tricksPointsSum = 0 # finish the round and reset it Trick.HEARTS_ALLOWED = False self.__roundNumber += 1 print(f"{'-'*50}\n") #end of the whole game self.__announce_winner() return 0 def __announce_winner(self) -&gt; None: winnerName = min(self.__players, key=lambda player: player.roundsPointsSum).name print(f"{'*' * 50}\n{'*'*16} {winnerName} wins the game {'*'*16}\n{'*' * 50}") def __player_order(self, startPlayer: Player) -&gt; List[Player]: """Rotate player order so that start goes first""" if not startPlayer: for player in self.__players: """ find the player that has the ♣2 card """ if player.has_card("♣", "2"): start_idx = self.__players.index(player) yield self.__players[start_idx:] + self.__players[:start_idx] break while True: start_idx = self.__players.index(startPlayer) yield self.__players[start_idx:] + self.__players[:start_idx] if __name__ == "__main__": try: numOfHumans = int(sys.argv[1]) if numOfHumans &gt; 4 or numOfHumans &lt; 0: raise ValueError("Number of human players cannot be less than 0 or more than 4") playerNames = sys.argv[2:2+numOfHumans] except (IndexError, ValueError): print("Number of human players is automatically set to 1") numOfHumans = 1 playerNames = () try: game = Game(numOfHumans, *playerNames) game.play() except EOFError: print("\nGame Aborted") </code></pre> <p>Example usage(the number of humanPlayers can be from 0 to 4):</p> <pre><code>python3 hearts.py 0 </code></pre> <p>I know it's so important to learn how to write tests for any software so I chose Pytest as a start and wrote these tests as well for the public methods of the above classes:</p> <pre><code>import pytest from french_card_game_oo import Card, HumanPlayer, AutoPlayer, Deck, Trick, Game SUITS = {suit_title: suit_symbol for (suit_title, suit_symbol) in zip(["spades", "hearts", "diamonds", "clubs"], "♠ ♡ ♢ ♣".split())} def test_invalid_card_suit(): with pytest.raises(ValueError): Card("*",5) def test_invalid_card_rank(): with pytest.raises(ValueError): Card(SUITS["diamonds"],13) def test_card_5_diamonds_eq_card_5_diamonds(): assert Card(SUITS["diamonds"], "5") == Card(SUITS["diamonds"], "5") def test_card_A_spades_gt_3_spades(): assert Card(SUITS["spades"], "A") &gt; Card(SUITS["spades"], "3") def test_card_A_spades_isnt_gt_10_clubs(): assert not (Card(SUITS["spades"], "A") &gt; Card(SUITS["clubs"], "10")) @pytest.fixture def trick_15_points(): return Trick( ( Card(SUITS['spades'], "Q"), Card(SUITS['hearts'], "2"), Card(SUITS['hearts'], "3") ) ) def test_get_points_of_trick_of_15_points(trick_15_points): assert trick_15_points.get_points() == 15 def test_add_card_to_trick(trick_15_points): trick_15_points.add_card(Card(SUITS['hearts'], "4")) assert len(trick_15_points.cards) == 4 def test_cannot_add_5th_card_to_a_trick(trick_15_points: Trick): with pytest.raises(ValueError): trick_15_points.add_card(Card(SUITS['hearts'], "4")) trick_15_points.add_card(Card(SUITS['hearts'], "5")) def test_cannot_add_repeated_card_to_trick(trick_15_points: Trick): with pytest.raises(ValueError): trick_15_points.add_card(Card(SUITS['hearts'], "3")) def test_get_winner_card_idx1(trick_15_points: Trick): trick_15_points.add_card(Card(SUITS['spades'], "J")) assert trick_15_points.get_winCard_idx() == 0 def test_get_winner_card_idx2(trick_15_points: Trick): trick_15_points.add_card(Card(SUITS['spades'], "A")) assert trick_15_points.get_winCard_idx() == 3 def test_get_winner_card_idx3(trick_15_points: Trick): trick_15_points.add_card(Card(SUITS['clubs'], "A")) assert trick_15_points.get_winCard_idx() == 0 def test_deck_creation(): Deck() Deck(shuffle=True) Deck(cards=[Card(SUITS['clubs'],"A")]) Deck(cards=[Card(SUITS['clubs'],"K")],shuffle=True) @pytest.fixture def deck() -&gt; Deck: return Deck(shuffle=True) def test_can_iterate_in_deck(deck: Deck): for card in deck: pass def test_deal_full_deck(deck: Deck): hands = deck.deal() assert len(hands) == 4 assert isinstance(hands[0], Deck) assert hands[0].cards @pytest.fixture def humanPlayer(deck: Deck): return HumanPlayer("Joe", deck) def test_play_card(humanPlayer: HumanPlayer, monkeypatch): trick = Trick() assert Card(SUITS["clubs"], "2") in next(humanPlayer.play_card(trick)).cards monkeypatch.setattr("builtins.input", lambda: 0) len(next(humanPlayer.play_card(trick)).cards) == 2 def test_game_all_auto_player(): game = Game(0) assert game.play() == 0 </code></pre> <p>The exercise is done (at least gives me a minimum satisfaction), but now I'm riddled with more OO questions. Since I'm self-learning, I'll ask them here, but if it is a TLDR for you, just leave a review of my code independently of my questions.</p> <p>The questions:</p> <ul> <li><p>Isn't this bad practice to create classes that are "plural"s of another class, if they have distinct purposes? I'm referring to Deck and Trick that are both <em>kind of</em> Cards. I have reasons for creating the class Trick, there are points in it, it specifies the winner of the Trick, and more importantly, it is needed to hold the state of the game. It also makes the code much more readable(you give a player the trick when they want to play, and you get a trick back as the output when they've finished playing their card). The class Deck is also basically a wrapper of a list of cards as well. (Probably, I <em>could</em> get rid of them both, but I think then I have to use dictionaries which are not IMO as cool as using objects).</p></li> <li><p>An argument I've seen a lot in object orientation analysis is "How do you know you won't subclass that class one day?", But in real scenario, should we really consider this warning for ALL of the super classes (and start all of them with interfaces/abstract-classes) or just for some of them? I think that sounds reasonable <em>only for some clasess</em>, e.g., Player -> HumanPlayer &amp; AutoPlayer, but in some cases, sounds like an overkill, why would the class "Trick" be abstract ever?</p></li> <li><p>I'm addicted to type hinting. Is that bad? It just gives me so much mental help when I read the code and also the IDE uses these hints and gives miraculous aid!</p></li> <li><p>Is the play() method of the Game class long? Maybe still a functional approach only with a facade of object-orientation? If it is, how can I make it shorter? (I've seen people say long methods are signs of bad/wrong OO designs) I had a hard time thinking of any tests for it so I just added a return value of 0 denoting success and checked if the test received that!</p></li> <li><p>I've defined both "play_card()" and "play_this()", because "play_this()" occured twice in the play_card(). Is this a bad choice to separate it? Because it adds one more layer to the call stack and this is a call that is made quite a lot of times(it doesn't add to the depth of the call stack though).</p></li> <li><p>Also the method "has_card()" does two things, both checking the existence of a card in one's hand, and checking the existence of a card with a certain suit in one's hand. IMO, It's more D-R-Y to write both of these in one method. But still it's a common advice to write methods that do <em>only one thing</em>. Should I break it into two methods? E.g. has_card and has_card_with_suit ?</p></li> <li><p>On the paper, sometimes I thought I had two choices of classes for taking a method. For instance, The "__prompt_choice()" method sounds a bit irrelevant to the class "Player" <em>semantically</em> (it seems much more relevant to the class "Game" probably? Or even a "Screen" class?). But still I thought it was best to be put there in the "Player" class because the method "play_card()" is using it and "play_card()" is in the Player class. Also it's not very unnatural if we think about it this way: "the player is pondering about its own choice".</p></li> <li><p>Sometimes what I did on paper needed modification when I got my hand in code. Now I've seen people explaining TDD saying it's a <em>tests-first</em> approach(I didn't do it, I wrote the tests "after" the code). So what if one writes the tests and then things turn out different from what they initially thought? E.g. you realize you need another public method, or maybe you realize you need a whole new class as well.</p></li> <li><p>I've used class variables like "HEARTS_ALLOWED", but I think <em>somehow</em> they are making a <em>global state</em> in the program... aren't they <em>globalish</em>?</p></li> </ul>
[]
[ { "body": "<p>I think I addressed most of your questions inline with this code review, but let me know if anything is unclear.</p>\n\n<h1>Suit and Rank should be <code>Enum</code>s</h1>\n\n<p>Much of the code can be simplified or removed if you define <code>Suit</code> and <code>Rank</code> as enumerations. Here's an example implementation:</p>\n\n<pre class=\"lang-python prettyprint-override\"><code>from enum import Enum\n\n\nclass Suit(Enum):\n SPADES = \"♠\"\n HEARTS = \"♡\"\n DIAMONDS = \"♢\"\n CLUBS = \"♣\"\n\n def __str__(self) -&gt; str:\n return self.value\n\n\nclass Rank(Enum):\n TWO = 2\n THREE = 3\n FOUR = 4\n FIVE = 5\n SIX = 6\n SEVEN = 7\n EIGHT = 8\n NINE = 9\n TEN = 10\n JACK = 11\n QUEEN = 12\n KING = 13\n ACE = 14\n\n def __str__(self) -&gt; str:\n if self is Rank.JACK:\n return \"J\"\n elif self is Rank.QUEEN:\n return \"Q\"\n elif self is Rank.KING:\n return \"K\"\n elif self is Rank.ACE:\n return \"A\"\n else:\n return str(self.value)\n\n def __gt__(self, other: \"Rank\") -&gt; bool:\n return self.value &gt; other.value\n\n def __lt__(self, other: \"Rank\") -&gt; bool:\n return self.value &lt; other.value\n</code></pre>\n\n<p>How does this help?</p>\n\n<ul>\n<li>Code that checks if a string is one of the suit strings <code>♠ ♡ ♢ ♣</code> or one of the rank strings <code>2 3 4 5 6 7 8 9 10 J Q K A</code> can be removed. For example, instead of passing in a <code>suit: str</code> and performing validations on it, just pass in a <code>suit: Suit</code>. No validations necessary.</li>\n<li><a href=\"https://docs.python.org/3/library/enum.html#allowed-members-and-attributes-of-enumerations\" rel=\"nofollow noreferrer\">Enumerations are Python classes</a>, which means we can define canonical string representations with our own custom <code>__str__</code> methods.</li>\n<li>We can also define comparison methods like <code>__gt__</code> and <code>__lt__</code> which is useful for <code>Rank</code>. This means we no longer need to create ad-hoc mappings from rank strings to their corresponding integer values, e.g.\n\n<pre class=\"lang-python prettyprint-override\"><code>{rank: num for (rank, num) in zip(list(\"23456789\")+[\"10\"]+list(\"JQKA\"), range(2,15))} \n</code></pre>\n\nin order to compare or sort by rank.</li>\n</ul>\n\n<h1><code>Card</code></h1>\n\n<p><code>Card</code> can be simplified a lot if we make it a <a href=\"https://docs.python.org/3/library/typing.html#typing.NamedTuple\" rel=\"nofollow noreferrer\"><code>NamedTuple</code></a>. <code>NamedTuple</code>s, like tuples, are immutable. This is appropriate for modeling <code>Card</code> because we don't need to mutate a card's suit or rank after instantiation.</p>\n\n<pre class=\"lang-python prettyprint-override\"><code>class Card(NamedTuple):\n suit: Suit\n rank: Rank\n\n def __str__(self) -&gt; str:\n return f\"{self.suit}{self.rank}\"\n\n def __gt__(self, other: \"Card\") -&gt; bool:\n return self.suit == other.suit and self.rank &gt; other.rank\n</code></pre>\n\n<h1><code>Deck</code></h1>\n\n<p>I don't think this is needed. It's basically a very specialized <code>List[Card]</code> that only gets used in <code>__set_new_round</code>. Also, using it as a type in contexts when it actually refers to the player's hand (or a subset of the player's hand that is playable) is confusing.</p>\n\n<p>I would consider removing this class. The logic of instantiating the deck as a list of cards, shuffling it, and dealing out the cards to players can be moved to <code>__set_new_round</code>. In places where <code>Deck</code> is currently expected as a parameter or return type, we can safely replace these with <code>List[Card]</code>.</p>\n\n<h1><code>Trick</code></h1>\n\n<p>Unlike <code>Deck</code>, I think <code>Trick</code> is a good abstraction and deserves its own type, even if they both function as \"containers\" of <code>Card</code>s. A few notes:</p>\n\n<ul>\n<li><code>HEARTS_ALLOWED</code> doesn't belong here. It makes more sense as an instance variable of <code>Game</code>.</li>\n<li><code>self.__cards</code> makes more sense as a <code>List[Card]</code> since a trick is \"empty\" by default and we can add cards to it.</li>\n<li>It's a matter of preference, but I think adding the <code>@property</code> decorator to <code>get_points</code> and renaming it to something more appropriate like <code>points</code> would be a nicer interface.</li>\n<li>Your size validation of <code>len(self.cards) &lt;= 4</code> is not applied to the instantiation flow in <code>__init__</code>.</li>\n</ul>\n\n<h1><code>Player</code></h1>\n\n<ul>\n<li>To answer your question about <code>has_card</code>, I am in favor of splitting it up into two methods: <code>has_card(self, suit: Suit, rank: Rank)</code> and <code>has_card_with_suit(self, suit: Suit)</code>. I think having it as two separate methods handling two distinct types of queries makes it much easier to read.</li>\n</ul>\n\n<h1>Type hints</h1>\n\n<p>I also love type hints, and find that they improve code readability. To answer your question, I don't think you need to worry about being addicted to type hinting.</p>\n\n<p>That said, there are issues with many of the type hints in your program. I ran <a href=\"http://mypy-lang.org/\" rel=\"nofollow noreferrer\"><code>mypy</code></a> on your code and it found 40+ errors. I suspect that your IDE isn't running <code>mypy</code> on your code, otherwise it would have flagged these.</p>\n\n<p>One example is the constructor of <code>Trick</code>, where <code>cards</code> is an <code>Optional[Tuple[Card, ...]]</code>, but then you directly assign it to <code>self.__cards</code> and assert that it is now a <code>Tuple[Card, ...]</code>.</p>\n\n<p>Another is in <code>play_card</code>, where the return type should be <code>Iterator[Trick]</code> but it is just <code>Trick</code>.</p>\n\n<p>What you can do is either set up your IDE with <code>mypy</code> integration (usually by installing a plugin) or periodically run <code>mypy</code> via the command line on your code to catch these errors.</p>\n\n<h1>Miscellaneous</h1>\n\n<ul>\n<li>In <code>HumanPlayer</code>'s <code>_prompt_choice</code>, <code>if choiceCardIdx &lt; len(sortedPlayable)</code> should be <code>if 0 &lt;= choiceCardIdx &lt; len(sortedPlayable)</code></li>\n<li>Also in <code>HumanPlayer</code>'s <code>_prompt_choice</code>, there is a list comprehension that is created and thrown away in order to print out the playable cards in hand. Instead, I would generally suggest using a for loop here.</li>\n<li>I'm contradicting myself in the above bullet point because I don't think printing in a loop is the most readable approach here. I see a lot of places where <code>print</code> with <code>end=\"\"</code> is used when it is probably a lot easier to construct intermediate strings first with <a href=\"https://docs.python.org/3/library/stdtypes.html#str.join\" rel=\"nofollow noreferrer\"><code>str.join</code></a>. For example, something like\n\n<pre class=\"lang-python prettyprint-override\"><code>[print(f\"\\t{idx}: {card} \", end=\"\") for idx, card in enumerate(sortedPlayable)]\nprint(\"(Rest: \", end=\"\")\nfor nonPlayableCard in list(set(self._hand.cards)-set(playable)):\n print(nonPlayableCard, end=\"\")\n print(\" \", end=\"\")\nprint(\")\")\n</code></pre>\n\ncan be replaced with\n\n<pre class=\"lang-python prettyprint-override\"><code>playable_cards = \"\\t\".join(\n f\"{idx}: {card}\" for idx, card in enumerate(sortedPlayable)\n)\nnon_playable_cards = \" \".join(\n str(card) for card in set(self._hand.cards) - set(playable)\n)\nprint(f\"{playable_cards} (Rest: {non_playable_cards})\")\n</code></pre></li>\n</ul>\n\n<h1>Case consistency</h1>\n\n<p>There is some inconsistency in the case used for your method, function, and variable names. Some names are in snake case (the recommended choice), but I also saw camel case and some combination of camel case and snake case.</p>\n\n<p>Examples with suggestions on how to rename:</p>\n\n<ul>\n<li><code>get_winCard_idx</code> -> <code>get_win_card_idx</code></li>\n<li><code>choiceCardIdx</code> -> <code>choice_card_idx</code></li>\n<li><code>tricksPointsSum</code> -> <code>trick_points_sum</code></li>\n<li><code>nonPlayableCard</code> -> <code>non_playable_card</code></li>\n<li><code>numOfHumans</code> -> <code>num_humans</code> or <code>number_of_humans</code></li>\n</ul>\n\n<h1>Test-driven development (TDD)</h1>\n\n<p>Writing code via TDD isn't everyone's cup of tea, which I feel is fine because generally people approach problem-solving with many different strategies.</p>\n\n<p>TDD gets you thinking about all the requirements first, and how you would validate those requirements through tests. And while doing that you are also forced to think about the shape of your data, the functions you'll need, the interfaces exposed by your classes, etc.</p>\n\n<p>For example, consider the feature of figuring out which cards in a player's hand are playable. What would a test for this feature look like? To start, we would probably need the following:</p>\n\n<ul>\n<li>a trick with 0-3 cards</li>\n<li>knowledge of whether hearts has been broken yet</li>\n<li>a list of cards (the player's hand)</li>\n</ul>\n\n<p>What do we want as output? Maybe the list of playable cards (<code>List[Card]</code>), or maybe we want both lists, playable <em>and</em> non-playable (<code>Tuple[List[Card], List[Card]]</code>). It depends, but we at least have a start here.</p>\n\n<p>So now we have some idea that we want a method that takes in some parameters as described above, and returns the list of playable cards in some format. Maybe it could look like this:</p>\n\n<pre class=\"lang-python prettyprint-override\"><code>def get_playable_cards(\n trick: Trick, hand: List[Card], hearts_is_broken: bool\n) -&gt; List[Card]:\n pass\n</code></pre>\n\n<p>We don't really care about how <code>get_playable_cards</code> will be implemented, because now we have all the information we need to start sketching out some tests.</p>\n\n<p>One other question is, who has access to all of this information, i.e. who has access to the current trick in play, the current player's hand, and the answer to whether hearts has been broken yet? If I had to guess I'd say <code>Game</code>, but maybe there is a better answer.</p>\n\n<p>The takeaway here is that TDD gets you asking yourself these types of questions which can be very illuminating and helpful before diving into the actual implementation. Yes, there are cases where you write some tests, and then figure out later on that your data model was slightly off, or that you could improve readability of both the code and its tests if you refactored things in a different way. It happens, and in that case you would need to go back and change both the code and the tests. But that's a relatively small price to pay, I think, because what you're getting in return is a maintained suite of tests you can run very quickly against your code at any time while developing it.</p>\n\n<p>Like I said earlier, it's not everyone's preferred style, but you might find it helpful to try it out as an exercise for future coding problems, and then follow up afterwards to see how following TDD influenced your design decisions.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-13T10:23:15.500", "Id": "475286", "Score": "0", "body": "Thank you for all the answers and the delicate points. Specially the TDD part was interesting. Just a few things that are vague to me. 1. Are you suggesting adding the `def get_playable_cards(` you've written towards the end of your answer to the `Game` class? 2. Are the tests I've written good? I've tried to cover all possible ways the classes can be used... 3. do you think I should break the `play` method into more than one methods?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-14T06:49:59.197", "Id": "475387", "Score": "1", "body": "@aderchox 1. Yes, I do think `get_playable_cards` would be appropriate in the `Game` class. This would probable require some refactoring though." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-14T06:50:24.603", "Id": "475388", "Score": "1", "body": "2. The tests for `Trick` are the most useful because they test business logic for the rules of the game. Some other tests are not necessary because they don't really test anything, e.g. `test_can_iterate_in_deck` tests that `__iter__` is implemented, and the implementation is just `yield from self.cards` so this should always work; `test_deck_creation` tests object creation, but unless you're doing something very complex in the constructor, this should again always work." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-14T06:50:28.953", "Id": "475389", "Score": "1", "body": "3. The `play` method contains your main game loop, so it's natural for it to be longer than the other methods. I found it straightforward to read, so I don't think it needs to be split." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-13T04:42:58.393", "Id": "242165", "ParentId": "242054", "Score": "5" } } ]
{ "AcceptedAnswerId": "242165", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-10T22:54:46.230", "Id": "242054", "Score": "6", "Tags": [ "python", "beginner", "object-oriented", "unit-testing" ], "Title": "Multiplayer card game \"Hearts\" with OOP in Python" }
242054
<p>I've been learning Python now for 3 months as I find it really interesting to code. I want to be able to apply for junior dev positions and as I have no formal education I thought I'd make a project to feature what I know.</p> <p>The project is still to be compeltely finsihed but it's got the meat of it done. I created a script to export data from a json file to automatically input to my MYSQL database. I've then used Pygame to create a periodic table GUI that enables you to press on a square (element ids and names yet to be added) and then it animates that atom with complete atom core configuration and electron shells. (Atom info on animation yet to be added) I'll provide the code below and some Images.</p> <p>Do you guys think this is a good project to feature on a resume for my first junior dev position? Do you think this is a good project that shows I know what I'm doing? Do you think this could land me a job or do I need to show I know more?</p> <p>Also, Is there a better way of saving each cell of the periodic table (to color and get data from while pressed) instead of making a list of them?</p> <p>Here is some Images of GUI and Animation and thereafter the code used in the project:</p> <p><a href="https://i.stack.imgur.com/ikzMk.png" rel="nofollow noreferrer">Period Table GUI</a></p> <p><a href="https://i.stack.imgur.com/uVDhD.png" rel="nofollow noreferrer">Still Image of Atom Animation</a></p> <p>JSON to MYSQL code:</p> <pre><code>import mysql.connector import json DB = mysql.connector.connect(host='localhost', database='OlijonDB', user='root', passwd='Testing123') DBCursor = DB.cursor(prepared=True) class Elements: def __init__(self, atomicnumber, symbol, name, atomicmass, type, electronconfig): self.atomicnumber = atomicnumber self.symbol = symbol self.name = name self.atomicmass = atomicmass self.type = type self.electronconfig = electronconfig iteration = 0 with open('periodictable.json') as json_file: data = json.load(json_file) for elements in data: iteration += 1 print(iteration) if elements['atomicNumber'] == iteration: try: atomicmass = elements['atomicMass'].split('.') except: atomicmass = elements['atomicMass'] Element = Elements(elements['atomicNumber'], elements['symbol'], elements['name'], int(atomicmass[0]), elements['groupBlock'], elements['electronicConfiguration']) SQLQuery = """ INSERT INTO elements (atomicnumber, symbol, name, atomicmass, type, electronconfig) VALUES (%s,%s,%s,%s,%s,%s) """ Values = [Element.atomicnumber, Element.symbol, Element.name, Element.atomicmass, Element.type, Element.electronconfig] print(Element.atomicmass) DBCursor.execute(SQLQuery, Values) DB.commit() </code></pre> <p>Periodic Table Code:</p> <pre><code>import pygame from AtomAnimation import * def main(): class Tables: def __init__(self): self.Dimensions = [25, 25, 1] self.Colors = [(255,255,255), (0,100,255), (255, 100, 0)] self.GridSize = 18 self.Grid = [] self.perodictable = [[4, 0], [4, 17], [5, 0], [5, 1], [5, 12], [5, 13], [5, 14], [5, 15], [5, 16], [5, 17], [6, 0], [6, 1], [6, 12], [6, 13], [6, 14], [6, 15], [6, 16], [6, 17], [7, 0], [7, 1], [7, 2], [7, 3], [7, 4], [7, 5], [7, 6], [7, 7], [7, 8], [7, 9], [7, 10], [7, 11], [7, 12], [7, 13], [7, 14], [7, 15], [7, 16], [7, 17], [8, 0], [8, 1], [8, 2], [8, 3], [8, 4], [8, 5], [8, 6], [8, 7], [8, 8], [8, 9], [8, 10], [8, 11], [8, 12], [8, 13], [8, 14], [8, 15], [8, 16], [8, 17], [9, 0], [9, 1], [12, 2], [12, 3], [12, 4], [12, 5], [12, 6], [12, 7], [12, 8], [12, 9], [12, 10], [12, 11], [12, 12], [12, 13], [12, 14], [12, 15], [12, 16], [9, 3], [9, 4], [9, 5], [9, 6], [9, 7], [9, 8], [9, 9], [9, 10], [9, 11], [9, 12], [9, 13], [9, 14], [9, 15], [9, 16], [9, 17], [10, 0], [10, 1], [13, 2], [13, 3], [13, 4], [13, 5], [13, 6], [13, 7], [13, 8], [13, 9], [13, 10], [13, 11], [13, 12], [13, 13], [13, 14], [13, 15], [13, 16], [10, 3], [10, 4], [10, 5], [10, 6], [10, 7], [10, 8], [10, 9], [10, 10], [10, 11], [10, 12], [10, 13], [10, 14], [10, 15], [10, 16], [10, 17]] def GenerateGrid(self): for Row in range(self.GridSize): self.Grid.append([]) for Column in range(self.GridSize): self.Grid[Row].append(0) for i in range(len(self.perodictable)): self.Grid[self.perodictable[i][0]][self.perodictable[i][1]] = 1 def Render(): GameWindow.fill((255,255,255)) for Row in range(Table.GridSize): for Column in range(Table.GridSize): if Table.Grid[Row][Column] == 0: Color = Table.Colors[0] elif Table.Grid[Row][Column] == 1: Color = Table.Colors[1] pygame.draw.rect(GameWindow, Color, [(Table.Dimensions[2] + Table.Dimensions[0]) * Column + Table.Dimensions[2], (Table.Dimensions[2] + Table.Dimensions[1]) * Row + Table.Dimensions[2], Table.Dimensions[0], Table.Dimensions[1]]) pygame.display.update() Table = Tables() Table.GenerateGrid() pygame.init() GameWindow = pygame.display.set_mode((468, 468)) pygame.display.set_caption("Periodic Table") Clock = pygame.time.Clock() Run = True while Run: Clock.tick(30) Events = pygame.event.get() for Event in Events: if Event.type == pygame.QUIT: Run = False elif Event.type == pygame.MOUSEBUTTONDOWN: MousePosition = pygame.mouse.get_pos() Column = MousePosition[0] // (Table.Dimensions[0] + Table.Dimensions[2]) Row = MousePosition[1] // (Table.Dimensions[1] + Table.Dimensions[2]) if Table.Grid[Row][Column] == 1: SimulateAtom(int(Table.perodictable.index([Row, Column]) + 1)) Render() pygame.quit() if __name__ == '__main__': main() </code></pre> <p>Atom Animation Code:</p> <pre><code>import mysql.connector import pygame import random import math import time def SimulateAtom(condition): class Atoms: def __init__(self, Name, Protons, Neutrons, Electrons): self.Name = Name self.Protons = Protons self.Neutrons = Neutrons self.Electrons = Electrons self.CenterPosition = [500, 500] #Create &amp; Render Atom Composition def GenerateAtom(self, AppWindow): #Atom Core for i in range(self.Protons + self.Neutrons): pygame.draw.circle(AppWindow, (random.randrange(100, 255), 0, random.randrange(100, 255)), [self.CenterPosition[0] + Randomize(0, 10), self.CenterPosition[1] + Randomize(0, 10)], 20) #Electron Shells for i in range(len(self.Electrons[0].split(","))): radius = [100, 150, 200, 250, 300, 350, 400] pygame.draw.circle(AppWindow, (211, 211, 211), self.CenterPosition, radius[i], 2) for j in range(int(self.Electrons[0].split(",")[i])): angle = random.randint(0, int((10 - 1) / 0.1)) * 0.1 + 1 pygame.draw.circle(AppWindow, [0,random.randrange(100, 255),random.randrange(100, 255)], [round(radius[i] * math.cos(angle) + self.CenterPosition[0]), round(radius[i] * math.sin(angle) + self.CenterPosition[1])], 8) pygame.draw.circle(AppWindow, (211,211,211), self.CenterPosition, radius[i], 2) #Randomized Position Function def Randomize(start, stop): if random.randrange(0, 2) == 1: return + random.randrange(start, stop) else: return - random.randrange(start, stop) #Rendering Loop def Render(): AppWindow.fill((255, 255, 255)) Atom.GenerateAtom(AppWindow) pygame.display.update() #Connect to Database DB = mysql.connector.connect(host='localhost', database='OlijonDB', user='root', passwd='Testing123') DBCursor = DB.cursor(prepared=True) DBCursor.execute("SELECT * FROM elements WHERE atomicnumber = %s", (condition,)) result = DBCursor.fetchone() Atom = Atoms(result[3], result[1], result[4] - result[1], [result[6]]) #Initiate Pygame pygame.init() pygame.display.set_caption("Element: " + str(Atom.Name)) AppWindow = pygame.display.set_mode((1000, 1000)) Clock = pygame.time.Clock() #Main App Loop Run = True while Run: Clock.tick(30) Events = pygame.event.get() for Event in Events: if Event.type == pygame.QUIT: Run = False time.sleep(0.3) pygame.display.get_surface().get_size() Render() pygame.quit() </code></pre> <p>Periodictable JSON:</p> <pre><code>[ {"atomicNumber":1,"symbol":"H","name":"Hydrogen","atomicMass":"1.00794(4)","cpkHexColor":"FFFFFF","electronicConfiguration":"1","electronegativity":2.2,"atomicRadius":37,"ionRadius":"","vanDerWaalsRadius":120,"ionizationEnergy":1312,"electronAffinity":-73,"oxidationStates":"-1, 1","standardState":"gas","bondingType":"diatomic","meltingPoint":14,"boilingPoint":20,"density":0.0000899,"groupBlock":"nonmetal","yearDiscovered":1766}, {"atomicNumber":2,"symbol":"He","name":"Helium","atomicMass":"4.002602(2)","cpkHexColor":"D9FFFF","electronicConfiguration":"2","electronegativity":"","atomicRadius":32,"ionRadius":"","vanDerWaalsRadius":140,"ionizationEnergy":2372,"electronAffinity":0,"oxidationStates":"","standardState":"gas","bondingType":"atomic","meltingPoint":"","boilingPoint":4,"density":0.0001785,"groupBlock":"noble gas","yearDiscovered":1868}, {"atomicNumber":3,"symbol":"Li","name":"Lithium","atomicMass":"6.941(2)","cpkHexColor":"CC80FF","electronicConfiguration":"2, 1","electronegativity":0.98,"atomicRadius":134,"ionRadius":"76 (+1)","vanDerWaalsRadius":182,"ionizationEnergy":520,"electronAffinity":-60,"oxidationStates":1,"standardState":"solid","bondingType":"metallic","meltingPoint":454,"boilingPoint":1615,"density":0.535,"groupBlock":"alkali metal","yearDiscovered":1817}, {"atomicNumber":4,"symbol":"Be","name":"Beryllium","atomicMass":"9.012182(3)","cpkHexColor":"C2FF00","electronicConfiguration":"2, 2","electronegativity":1.57,"atomicRadius":90,"ionRadius":"45 (+2)","vanDerWaalsRadius":"","ionizationEnergy":900,"electronAffinity":0,"oxidationStates":2,"standardState":"solid","bondingType":"metallic","meltingPoint":1560,"boilingPoint":2743,"density":1.848,"groupBlock":"alkaline earth metal","yearDiscovered":1798}, {"atomicNumber":5,"symbol":"B","name":"Boron","atomicMass":"10.811(7)","cpkHexColor":"FFB5B5","electronicConfiguration":"2, 3","electronegativity":2.04,"atomicRadius":82,"ionRadius":"27 (+3)","vanDerWaalsRadius":"","ionizationEnergy":801,"electronAffinity":-27,"oxidationStates":"1, 2, 3","standardState":"solid","bondingType":"covalent network","meltingPoint":2348,"boilingPoint":4273,"density":2.46,"groupBlock":"metalloid","yearDiscovered":1807}, {"atomicNumber":6,"symbol":"C","name":"Carbon","atomicMass":"12.0107(8)","cpkHexColor":909090,"electronicConfiguration":"2, 4","electronegativity":2.55,"atomicRadius":77,"ionRadius":"16 (+4)","vanDerWaalsRadius":170,"ionizationEnergy":1087,"electronAffinity":-154,"oxidationStates":"-4, -3, -2, -1, 1, 2, 3, 4","standardState":"solid","bondingType":"covalent network","meltingPoint":3823,"boilingPoint":4300,"density":2.26,"groupBlock":"nonmetal","yearDiscovered":"Ancient"}, {"atomicNumber":7,"symbol":"N","name":"Nitrogen","atomicMass":"14.0067(2)","cpkHexColor":"3050F8","electronicConfiguration":"2, 5","electronegativity":3.04,"atomicRadius":75,"ionRadius":"146 (-3)","vanDerWaalsRadius":155,"ionizationEnergy":1402,"electronAffinity":-7,"oxidationStates":"-3, -2, -1, 1, 2, 3, 4, 5","standardState":"gas","bondingType":"diatomic","meltingPoint":63,"boilingPoint":77,"density":0.001251,"groupBlock":"nonmetal","yearDiscovered":1772}, {"atomicNumber":8,"symbol":"O","name":"Oxygen","atomicMass":"15.9994(3)","cpkHexColor":"FF0D0D","electronicConfiguration":"2, 6","electronegativity":3.44,"atomicRadius":73,"ionRadius":"140 (-2)","vanDerWaalsRadius":152,"ionizationEnergy":1314,"electronAffinity":-141,"oxidationStates":"-2, -1, 1, 2","standardState":"gas","bondingType":"diatomic","meltingPoint":55,"boilingPoint":90,"density":0.001429,"groupBlock":"nonmetal","yearDiscovered":1774}, {"atomicNumber":9,"symbol":"F","name":"Fluorine","atomicMass":"18.9984032(5)","cpkHexColor":9e+51,"electronicConfiguration":"2, 7","electronegativity":3.98,"atomicRadius":71,"ionRadius":"133 (-1)","vanDerWaalsRadius":147,"ionizationEnergy":1681,"electronAffinity":-328,"oxidationStates":-1,"standardState":"gas","bondingType":"atomic","meltingPoint":54,"boilingPoint":85,"density":0.001696,"groupBlock":"halogen","yearDiscovered":1670}, {"atomicNumber":10,"symbol":"Ne","name":"Neon","atomicMass":"20.1797(6)","cpkHexColor":"B3E3F5","electronicConfiguration":"2, 8","electronegativity":"","atomicRadius":69,"ionRadius":"","vanDerWaalsRadius":154,"ionizationEnergy":2081,"electronAffinity":0,"oxidationStates":"","standardState":"gas","bondingType":"atomic","meltingPoint":25,"boilingPoint":27,"density":0.0009,"groupBlock":"noble gas","yearDiscovered":1898}, {"atomicNumber":11,"symbol":"Na","name":"Sodium","atomicMass":"22.98976928(2)","cpkHexColor":"AB5CF2","electronicConfiguration":"2, 8, 1","electronegativity":0.93,"atomicRadius":154,"ionRadius":"102 (+1)","vanDerWaalsRadius":227,"ionizationEnergy":496,"electronAffinity":-53,"oxidationStates":"-1, 1","standardState":"solid","bondingType":"metallic","meltingPoint":371,"boilingPoint":1156,"density":0.968,"groupBlock":"alkali metal","yearDiscovered":1807}, {"atomicNumber":12,"symbol":"Mg","name":"Magnesium","atomicMass":"24.3050(6)","cpkHexColor":"8AFF00","electronicConfiguration":"2, 8, 2","electronegativity":1.31,"atomicRadius":130,"ionRadius":"72 (+2)","vanDerWaalsRadius":173,"ionizationEnergy":738,"electronAffinity":0,"oxidationStates":"1, 2","standardState":"solid","bondingType":"metallic","meltingPoint":923,"boilingPoint":1363,"density":1.738,"groupBlock":"alkaline earth metal","yearDiscovered":1808}, {"atomicNumber":13,"symbol":"Al","name":"Aluminum","atomicMass":"26.9815386(8)","cpkHexColor":"BFA6A6","electronicConfiguration":"2, 8, 3","electronegativity":1.61,"atomicRadius":118,"ionRadius":"53.5 (+3)","vanDerWaalsRadius":"","ionizationEnergy":578,"electronAffinity":-43,"oxidationStates":"1, 3","standardState":"solid","bondingType":"metallic","meltingPoint":933,"boilingPoint":2792,"density":2.7,"groupBlock":"metal","yearDiscovered":"Ancient"}, {"atomicNumber":14,"symbol":"Si","name":"Silicon","atomicMass":"28.0855(3)","cpkHexColor":"F0C8A0","electronicConfiguration":"2, 8, 4","electronegativity":1.9,"atomicRadius":111,"ionRadius":"40 (+4)","vanDerWaalsRadius":210,"ionizationEnergy":787,"electronAffinity":-134,"oxidationStates":"-4, -3, -2, -1, 1, 2, 3, 4","standardState":"solid","bondingType":"metallic","meltingPoint":1687,"boilingPoint":3173,"density":2.33,"groupBlock":"metalloid","yearDiscovered":1854}, {"atomicNumber":15,"symbol":"P","name":"Phosphorus","atomicMass":"30.973762(2)","cpkHexColor":"FF8000","electronicConfiguration":"2, 8, 5","electronegativity":2.19,"atomicRadius":106,"ionRadius":"44 (+3)","vanDerWaalsRadius":180,"ionizationEnergy":1012,"electronAffinity":-72,"oxidationStates":"-3, -2, -1, 1, 2, 3, 4, 5","standardState":"solid","bondingType":"covalent network","meltingPoint":317,"boilingPoint":554,"density":1.823,"groupBlock":"nonmetal","yearDiscovered":1669}, {"atomicNumber":16,"symbol":"S","name":"Sulfur","atomicMass":"32.065(5)","cpkHexColor":"FFFF30","electronicConfiguration":"2, 8, 6","electronegativity":2.58,"atomicRadius":102,"ionRadius":"184 (-2)","vanDerWaalsRadius":180,"ionizationEnergy":1000,"electronAffinity":-200,"oxidationStates":"-2, -1, 1, 2, 3, 4, 5, 6","standardState":"solid","bondingType":"covalent network","meltingPoint":388,"boilingPoint":718,"density":1.96,"groupBlock":"nonmetal","yearDiscovered":"Ancient"}, {"atomicNumber":17,"symbol":"Cl","name":"Chlorine","atomicMass":"35.453(2)","cpkHexColor":"1FF01F","electronicConfiguration":"2, 8, 7","electronegativity":3.16,"atomicRadius":99,"ionRadius":"181 (-1)","vanDerWaalsRadius":175,"ionizationEnergy":1251,"electronAffinity":-349,"oxidationStates":"-1, 1, 2, 3, 4, 5, 6, 7","standardState":"gas","bondingType":"covalent network","meltingPoint":172,"boilingPoint":239,"density":0.003214,"groupBlock":"halogen","yearDiscovered":1774}, {"atomicNumber":18,"symbol":"Ar","name":"Argon","atomicMass":"39.948(1)","cpkHexColor":"80D1E3","electronicConfiguration":"2, 8, 8","electronegativity":"","atomicRadius":97,"ionRadius":"","vanDerWaalsRadius":188,"ionizationEnergy":1521,"electronAffinity":0,"oxidationStates":"","standardState":"gas","bondingType":"atomic","meltingPoint":84,"boilingPoint":87,"density":0.001784,"groupBlock":"noble gas","yearDiscovered":1894}, {"atomicNumber":19,"symbol":"K","name":"Potassium","atomicMass":"39.0983(1)","cpkHexColor":"8F40D4","electronicConfiguration":"2, 8, 8, 1","electronegativity":0.82,"atomicRadius":196,"ionRadius":"138 (+1)","vanDerWaalsRadius":275,"ionizationEnergy":419,"electronAffinity":-48,"oxidationStates":1,"standardState":"solid","bondingType":"metallic","meltingPoint":337,"boilingPoint":1032,"density":0.856,"groupBlock":"alkali metal","yearDiscovered":1807}, {"atomicNumber":20,"symbol":"Ca","name":"Calcium","atomicMass":"40.078(4)","cpkHexColor":"3DFF00","electronicConfiguration":"2, 8, 8, 2","electronegativity":1,"atomicRadius":174,"ionRadius":"100 (+2)","vanDerWaalsRadius":"","ionizationEnergy":590,"electronAffinity":-2,"oxidationStates":2,"standardState":"solid","bondingType":"metallic","meltingPoint":1115,"boilingPoint":1757,"density":1.55,"groupBlock":"alkaline earth metal","yearDiscovered":"Ancient"}, {"atomicNumber":21,"symbol":"Sc","name":"Scandium","atomicMass":"44.955912(6)","cpkHexColor":"E6E6E6","electronicConfiguration":"2, 8, 9, 2","electronegativity":1.36,"atomicRadius":144,"ionRadius":"74.5 (+3)","vanDerWaalsRadius":"","ionizationEnergy":633,"electronAffinity":-18,"oxidationStates":"1, 2, 3","standardState":"solid","bondingType":"metallic","meltingPoint":1814,"boilingPoint":3103,"density":2.985,"groupBlock":"transition metal","yearDiscovered":1876}, {"atomicNumber":22,"symbol":"Ti","name":"Titanium","atomicMass":"47.867(1)","cpkHexColor":"BFC2C7","electronicConfiguration":"2, 8, 10, 2","electronegativity":1.54,"atomicRadius":136,"ionRadius":"86 (+2)","vanDerWaalsRadius":"","ionizationEnergy":659,"electronAffinity":-8,"oxidationStates":"-1, 2, 3, 4","standardState":"solid","bondingType":"metallic","meltingPoint":1941,"boilingPoint":3560,"density":4.507,"groupBlock":"transition metal","yearDiscovered":1791}, {"atomicNumber":23,"symbol":"V","name":"Vanadium","atomicMass":"50.9415(1)","cpkHexColor":"A6A6AB","electronicConfiguration":"2, 8, 11, 2","electronegativity":1.63,"atomicRadius":125,"ionRadius":"79 (+2)","vanDerWaalsRadius":"","ionizationEnergy":651,"electronAffinity":-51,"oxidationStates":"-1, 2, 3, 4","standardState":"solid","bondingType":"metallic","meltingPoint":2183,"boilingPoint":3680,"density":6.11,"groupBlock":"transition metal","yearDiscovered":1803}, {"atomicNumber":24,"symbol":"Cr","name":"Chromium","atomicMass":"51.9961(6)","cpkHexColor":"8A99C7","electronicConfiguration":"2, 8, 13, 1","electronegativity":1.66,"atomicRadius":127,"ionRadius":"80 (+2*)","vanDerWaalsRadius":"","ionizationEnergy":653,"electronAffinity":-64,"oxidationStates":"-2, -1, 1, 2, 3, 4, 5, 6","standardState":"solid","bondingType":"metallic","meltingPoint":2180,"boilingPoint":2944,"density":7.14,"groupBlock":"transition metal","yearDiscovered":"Ancient"}, {"atomicNumber":25,"symbol":"Mn","name":"Manganese","atomicMass":"54.938045(5)","cpkHexColor":"9C7AC7","electronicConfiguration":"2, 8, 13, 2","electronegativity":1.55,"atomicRadius":139,"ionRadius":"67 (+2)","vanDerWaalsRadius":"","ionizationEnergy":717,"electronAffinity":0,"oxidationStates":"-3, -2, -1, 1, 2, 3, 4, 5, 6, 7","standardState":"solid","bondingType":"metallic","meltingPoint":1519,"boilingPoint":2334,"density":7.47,"groupBlock":"transition metal","yearDiscovered":1774}, {"atomicNumber":26,"symbol":"Fe","name":"Iron","atomicMass":"55.845(2)","cpkHexColor":"E06633","electronicConfiguration":"2, 8, 14, 2","electronegativity":1.83,"atomicRadius":125,"ionRadius":"78 (+2*)","vanDerWaalsRadius":"","ionizationEnergy":763,"electronAffinity":-16,"oxidationStates":"-2, -1, 1, 2, 3, 4, 5, 6","standardState":"solid","bondingType":"metallic","meltingPoint":1811,"boilingPoint":3134,"density":7.874,"groupBlock":"transition metal","yearDiscovered":"Ancient"}, {"atomicNumber":27,"symbol":"Co","name":"Cobalt","atomicMass":"58.933195(5)","cpkHexColor":"F090A0","electronicConfiguration":"2, 8, 15, 2","electronegativity":1.88,"atomicRadius":126,"ionRadius":"74.5 (+2*)","vanDerWaalsRadius":"","ionizationEnergy":760,"electronAffinity":-64,"oxidationStates":"-1, 1, 2, 3, 4, 5","standardState":"solid","bondingType":"metallic","meltingPoint":1768,"boilingPoint":3200,"density":8.9,"groupBlock":"transition metal","yearDiscovered":"Ancient"}, {"atomicNumber":28,"symbol":"Ni","name":"Nickel","atomicMass":"58.6934(4)","cpkHexColor":"50D050","electronicConfiguration":"2, 8, 16, 2","electronegativity":1.91,"atomicRadius":121,"ionRadius":"69 (+2)","vanDerWaalsRadius":163,"ionizationEnergy":737,"electronAffinity":-112,"oxidationStates":"-1, 1, 2, 3, 4","standardState":"solid","bondingType":"metallic","meltingPoint":1728,"boilingPoint":3186,"density":8.908,"groupBlock":"transition metal","yearDiscovered":1751}, {"atomicNumber":29,"symbol":"Cu","name":"Copper","atomicMass":"63.546(3)","cpkHexColor":"C88033","electronicConfiguration":"2, 8, 18, 1","electronegativity":1.9,"atomicRadius":138,"ionRadius":"77 (+1)","vanDerWaalsRadius":140,"ionizationEnergy":746,"electronAffinity":-118,"oxidationStates":"1, 2, 3, 4","standardState":"solid","bondingType":"metallic","meltingPoint":1358,"boilingPoint":3200,"density":8.92,"groupBlock":"transition metal","yearDiscovered":"Ancient"}, {"atomicNumber":30,"symbol":"Zn","name":"Zinc","atomicMass":"65.38(2)","cpkHexColor":"7D80B0","electronicConfiguration":"2, 8, 18, 2","electronegativity":1.65,"atomicRadius":131,"ionRadius":"74 (+2)","vanDerWaalsRadius":139,"ionizationEnergy":906,"electronAffinity":0,"oxidationStates":2,"standardState":"solid","bondingType":"metallic","meltingPoint":693,"boilingPoint":1180,"density":7.14,"groupBlock":"transition metal","yearDiscovered":1746}, {"atomicNumber":31,"symbol":"Ga","name":"Gallium","atomicMass":"69.723(1)","cpkHexColor":"C28F8F","electronicConfiguration":"2, 8, 18, 3","electronegativity":1.81,"atomicRadius":126,"ionRadius":"62 (+3)","vanDerWaalsRadius":187,"ionizationEnergy":579,"electronAffinity":-29,"oxidationStates":"1, 2, 3","standardState":"solid","bondingType":"metallic","meltingPoint":303,"boilingPoint":2477,"density":5.904,"groupBlock":"metal","yearDiscovered":1875}, {"atomicNumber":32,"symbol":"Ge","name":"Germanium","atomicMass":"72.64(1)","cpkHexColor":"668F8F","electronicConfiguration":"2, 8, 18, 4","electronegativity":2.01,"atomicRadius":122,"ionRadius":"73 (+2)","vanDerWaalsRadius":"","ionizationEnergy":762,"electronAffinity":-119,"oxidationStates":"-4, 1, 2, 3, 4","standardState":"solid","bondingType":"metallic","meltingPoint":1211,"boilingPoint":3093,"density":5.323,"groupBlock":"metalloid","yearDiscovered":1886}, {"atomicNumber":33,"symbol":"As","name":"Arsenic","atomicMass":"74.92160(2)","cpkHexColor":"BD80E3","electronicConfiguration":"2, 8, 18, 5","electronegativity":2.18,"atomicRadius":119,"ionRadius":"58 (+3)","vanDerWaalsRadius":185,"ionizationEnergy":947,"electronAffinity":-78,"oxidationStates":"-3, 2, 3, 5","standardState":"solid","bondingType":"metallic","meltingPoint":1090,"boilingPoint":887,"density":5.727,"groupBlock":"metalloid","yearDiscovered":"Ancient"}, {"atomicNumber":34,"symbol":"Se","name":"Selenium","atomicMass":"78.96(3)","cpkHexColor":"FFA100","electronicConfiguration":"2, 8, 18, 6","electronegativity":2.55,"atomicRadius":116,"ionRadius":"198 (-2)","vanDerWaalsRadius":190,"ionizationEnergy":941,"electronAffinity":-195,"oxidationStates":"-2, 2, 4, 6","standardState":"solid","bondingType":"metallic","meltingPoint":494,"boilingPoint":958,"density":4.819,"groupBlock":"nonmetal","yearDiscovered":1817}, {"atomicNumber":35,"symbol":"Br","name":"Bromine","atomicMass":"79.904(1)","cpkHexColor":"A62929","electronicConfiguration":"2, 8, 18, 7","electronegativity":2.96,"atomicRadius":114,"ionRadius":"196 (-1)","vanDerWaalsRadius":185,"ionizationEnergy":1140,"electronAffinity":-325,"oxidationStates":"-1, 1, 3, 4, 5, 7","standardState":"liquid","bondingType":"covalent network","meltingPoint":266,"boilingPoint":332,"density":3.12,"groupBlock":"halogen","yearDiscovered":1826}, {"atomicNumber":36,"symbol":"Kr","name":"Krypton","atomicMass":"83.798(2)","cpkHexColor":"5CB8D1","electronicConfiguration":"2, 8, 18, 8","electronegativity":"","atomicRadius":110,"ionRadius":"","vanDerWaalsRadius":202,"ionizationEnergy":1351,"electronAffinity":0,"oxidationStates":2,"standardState":"gas","bondingType":"atomic","meltingPoint":116,"boilingPoint":120,"density":0.00375,"groupBlock":"noble gas","yearDiscovered":1898}, {"atomicNumber":37,"symbol":"Rb","name":"Rubidium","atomicMass":"85.4678(3)","cpkHexColor":"702EB0","electronicConfiguration":"2, 8, 18, 8, 1","electronegativity":0.82,"atomicRadius":211,"ionRadius":"152 (+1)","vanDerWaalsRadius":"","ionizationEnergy":403,"electronAffinity":-47,"oxidationStates":1,"standardState":"solid","bondingType":"metallic","meltingPoint":312,"boilingPoint":961,"density":1.532,"groupBlock":"alkali metal","yearDiscovered":1861}, {"atomicNumber":38,"symbol":"Sr","name":"Strontium","atomicMass":"87.62(1)","cpkHexColor":"00FF00","electronicConfiguration":"2, 8, 18, 8, 2","electronegativity":0.95,"atomicRadius":192,"ionRadius":"118 (+2)","vanDerWaalsRadius":"","ionizationEnergy":550,"electronAffinity":-5,"oxidationStates":2,"standardState":"solid","bondingType":"metallic","meltingPoint":1050,"boilingPoint":1655,"density":2.63,"groupBlock":"alkaline earth metal","yearDiscovered":1790}, {"atomicNumber":39,"symbol":"Y","name":"Yttrium","atomicMass":"88.90585(2)","cpkHexColor":"94FFFF","electronicConfiguration":"2, 8, 18, 9, 2","electronegativity":1.22,"atomicRadius":162,"ionRadius":"90 (+3)","vanDerWaalsRadius":"","ionizationEnergy":600,"electronAffinity":-30,"oxidationStates":"1, 2, 3","standardState":"solid","bondingType":"metallic","meltingPoint":1799,"boilingPoint":3618,"density":4.472,"groupBlock":"transition metal","yearDiscovered":1794}, {"atomicNumber":40,"symbol":"Zr","name":"Zirconium","atomicMass":"91.224(2)","cpkHexColor":"94E0E0","electronicConfiguration":"2, 8, 18, 10, 2","electronegativity":1.33,"atomicRadius":148,"ionRadius":"72 (+4)","vanDerWaalsRadius":"","ionizationEnergy":640,"electronAffinity":-41,"oxidationStates":"1, 2, 3, 4","standardState":"solid","bondingType":"metallic","meltingPoint":2128,"boilingPoint":4682,"density":6.511,"groupBlock":"transition metal","yearDiscovered":1789}, {"atomicNumber":41,"symbol":"Nb","name":"Niobium","atomicMass":"92.90638(2)","cpkHexColor":"73C2C9","electronicConfiguration":"2, 8, 18, 12, 1","electronegativity":1.6,"atomicRadius":137,"ionRadius":"72 (+3)","vanDerWaalsRadius":"","ionizationEnergy":652,"electronAffinity":-86,"oxidationStates":"-1, 2, 3, 4, 5","standardState":"solid","bondingType":"metallic","meltingPoint":2750,"boilingPoint":5017,"density":8.57,"groupBlock":"transition metal","yearDiscovered":1801}, {"atomicNumber":42,"symbol":"Mo","name":"Molybdenum","atomicMass":"95.96(2)","cpkHexColor":"54B5B5","electronicConfiguration":"2, 8, 18, 13, 1","electronegativity":2.16,"atomicRadius":145,"ionRadius":"69 (+3)","vanDerWaalsRadius":"","ionizationEnergy":684,"electronAffinity":-72,"oxidationStates":"-2, -1, 1, 2, 3, 4, 5, 6","standardState":"solid","bondingType":"metallic","meltingPoint":2896,"boilingPoint":4912,"density":10.28,"groupBlock":"transition metal","yearDiscovered":1778}, {"atomicNumber":43,"symbol":"Tc","name":"Technetium","atomicMass":[98],"cpkHexColor":"3B9E9E","electronicConfiguration":"2, 8, 18, 13, 2","electronegativity":1.9,"atomicRadius":156,"ionRadius":"64.5 (+4)","vanDerWaalsRadius":"","ionizationEnergy":702,"electronAffinity":-53,"oxidationStates":"-3, -1, 1, 2, 3, 4, 5, 6, 7","standardState":"solid","bondingType":"metallic","meltingPoint":2430,"boilingPoint":4538,"density":11.5,"groupBlock":"transition metal","yearDiscovered":1937}, {"atomicNumber":44,"symbol":"Ru","name":"Ruthenium","atomicMass":"101.07(2)","cpkHexColor":"248F8F","electronicConfiguration":"2, 8, 18, 15, 1","electronegativity":2.2,"atomicRadius":126,"ionRadius":"68 (+3)","vanDerWaalsRadius":"","ionizationEnergy":710,"electronAffinity":-101,"oxidationStates":"-2, 1, 2, 3, 4, 5, 6, 7, 8","standardState":"solid","bondingType":"metallic","meltingPoint":2607,"boilingPoint":4423,"density":12.37,"groupBlock":"transition metal","yearDiscovered":1827}, {"atomicNumber":45,"symbol":"Rh","name":"Rhodium","atomicMass":"102.90550(2)","cpkHexColor":"0A7D8C","electronicConfiguration":"2, 8, 18, 16, 1","electronegativity":2.28,"atomicRadius":135,"ionRadius":"66.5 (+3)","vanDerWaalsRadius":"","ionizationEnergy":720,"electronAffinity":-110,"oxidationStates":"-1, 1, 2, 3, 4, 5, 6","standardState":"solid","bondingType":"metallic","meltingPoint":2237,"boilingPoint":3968,"density":12.45,"groupBlock":"transition metal","yearDiscovered":1803}, {"atomicNumber":46,"symbol":"Pd","name":"Palladium","atomicMass":"106.42(1)","cpkHexColor":6985,"electronicConfiguration":"2, 8, 18, 18","electronegativity":2.2,"atomicRadius":131,"ionRadius":"59 (+1)","vanDerWaalsRadius":163,"ionizationEnergy":804,"electronAffinity":-54,"oxidationStates":"2, 4","standardState":"solid","bondingType":"metallic","meltingPoint":1828,"boilingPoint":3236,"density":12.023,"groupBlock":"transition metal","yearDiscovered":1803}, {"atomicNumber":47,"symbol":"Ag","name":"Silver","atomicMass":"107.8682(2)","cpkHexColor":"C0C0C0","electronicConfiguration":"2, 8, 18, 18, 1","electronegativity":1.93,"atomicRadius":153,"ionRadius":"115 (+1)","vanDerWaalsRadius":172,"ionizationEnergy":731,"electronAffinity":-126,"oxidationStates":"1, 2, 3","standardState":"solid","bondingType":"metallic","meltingPoint":1235,"boilingPoint":2435,"density":10.49,"groupBlock":"transition metal","yearDiscovered":"Ancient"}, {"atomicNumber":48,"symbol":"Cd","name":"Cadmium","atomicMass":"112.411(8)","cpkHexColor":"FFD98F","electronicConfiguration":"2, 8, 18, 18, 2","electronegativity":1.69,"atomicRadius":148,"ionRadius":"95 (+2)","vanDerWaalsRadius":158,"ionizationEnergy":868,"electronAffinity":0,"oxidationStates":2,"standardState":"solid","bondingType":"metallic","meltingPoint":594,"boilingPoint":1040,"density":8.65,"groupBlock":"transition metal","yearDiscovered":1817}, {"atomicNumber":49,"symbol":"In","name":"Indium","atomicMass":"114.818(3)","cpkHexColor":"A67573","electronicConfiguration":"2, 8, 18, 18, 3","electronegativity":1.78,"atomicRadius":144,"ionRadius":"80 (+3)","vanDerWaalsRadius":193,"ionizationEnergy":558,"electronAffinity":-29,"oxidationStates":"1, 2, 3","standardState":"solid","bondingType":"metallic","meltingPoint":430,"boilingPoint":2345,"density":7.31,"groupBlock":"metal","yearDiscovered":1863}, {"atomicNumber":50,"symbol":"Sn","name":"Tin","atomicMass":"118.710(7)","cpkHexColor":668080,"electronicConfiguration":"2, 8, 18, 18, 4","electronegativity":1.96,"atomicRadius":141,"ionRadius":"112 (+2)","vanDerWaalsRadius":217,"ionizationEnergy":709,"electronAffinity":-107,"oxidationStates":"-4, 2, 4","standardState":"solid","bondingType":"metallic","meltingPoint":505,"boilingPoint":2875,"density":7.31,"groupBlock":"metal","yearDiscovered":"Ancient"}, {"atomicNumber":51,"symbol":"Sb","name":"Antimony","atomicMass":"121.760(1)","cpkHexColor":"9E63B5","electronicConfiguration":"2, 8, 18, 18, 5","electronegativity":2.05,"atomicRadius":138,"ionRadius":"76 (+3)","vanDerWaalsRadius":"","ionizationEnergy":834,"electronAffinity":-103,"oxidationStates":"-3, 3, 5","standardState":"solid","bondingType":"metallic","meltingPoint":904,"boilingPoint":1860,"density":6.697,"groupBlock":"metalloid","yearDiscovered":"Ancient"}, {"atomicNumber":52,"symbol":"Te","name":"Tellurium","atomicMass":"127.60(3)","cpkHexColor":"D47A00","electronicConfiguration":"2, 8, 18, 18, 6","electronegativity":2.1,"atomicRadius":135,"ionRadius":"221 (-2)","vanDerWaalsRadius":206,"ionizationEnergy":869,"electronAffinity":-190,"oxidationStates":"-2, 2, 4, 5, 6","standardState":"solid","bondingType":"metallic","meltingPoint":723,"boilingPoint":1261,"density":6.24,"groupBlock":"metalloid","yearDiscovered":1782}, {"atomicNumber":53,"symbol":"I","name":"Iodine","atomicMass":"126.90447(3)","cpkHexColor":940094,"electronicConfiguration":"2, 8, 18, 18, 7","electronegativity":2.66,"atomicRadius":133,"ionRadius":"220 (-1)","vanDerWaalsRadius":198,"ionizationEnergy":1008,"electronAffinity":-295,"oxidationStates":"-1, 1, 3, 5, 7","standardState":"solid","bondingType":"covalent network","meltingPoint":387,"boilingPoint":457,"density":4.94,"groupBlock":"halogen","yearDiscovered":1811}, {"atomicNumber":54,"symbol":"Xe","name":"Xenon","atomicMass":"131.293(6)","cpkHexColor":"429EB0","electronicConfiguration":"2, 8, 18, 18, 8","electronegativity":"","atomicRadius":130,"ionRadius":"48 (+8)","vanDerWaalsRadius":216,"ionizationEnergy":1170,"electronAffinity":0,"oxidationStates":"2, 4, 6, 8","standardState":"gas","bondingType":"atomic","meltingPoint":161,"boilingPoint":165,"density":0.0059,"groupBlock":"noble gas","yearDiscovered":1898}, {"atomicNumber":55,"symbol":"Cs","name":"Cesium","atomicMass":"132.9054519(2)","cpkHexColor":"57178F","electronicConfiguration":"2, 8, 18, 18, 8, 1","electronegativity":0.79,"atomicRadius":225,"ionRadius":"167 (+1)","vanDerWaalsRadius":"","ionizationEnergy":376,"electronAffinity":-46,"oxidationStates":1,"standardState":"solid","bondingType":"metallic","meltingPoint":302,"boilingPoint":944,"density":1.879,"groupBlock":"alkali metal","yearDiscovered":1860}, {"atomicNumber":56,"symbol":"Ba","name":"Barium","atomicMass":"137.327(7)","cpkHexColor":"00C900","electronicConfiguration":"2, 8, 18, 18, 8, 2","electronegativity":0.89,"atomicRadius":198,"ionRadius":"135 (+2)","vanDerWaalsRadius":"","ionizationEnergy":503,"electronAffinity":-14,"oxidationStates":2,"standardState":"solid","bondingType":"metallic","meltingPoint":1000,"boilingPoint":2143,"density":3.51,"groupBlock":"alkaline earth metal","yearDiscovered":1808}, {"atomicNumber":57,"symbol":"La","name":"Lanthanum","atomicMass":"138.90547(7)","cpkHexColor":"70D4FF","electronicConfiguration":"2, 8, 18, 18, 9, 2","electronegativity":1.1,"atomicRadius":169,"ionRadius":"103.2 (+3)","vanDerWaalsRadius":"","ionizationEnergy":538,"electronAffinity":-48,"oxidationStates":"2, 3","standardState":"solid","bondingType":"metallic","meltingPoint":1193,"boilingPoint":3737,"density":6.146,"groupBlock":"lanthanoid","yearDiscovered":1839}, {"atomicNumber":58,"symbol":"Ce","name":"Cerium","atomicMass":"140.116(1)","cpkHexColor":"FFFFC7","electronicConfiguration":"2, 8, 18, 19, 9, 2","electronegativity":1.12,"atomicRadius":"","ionRadius":"102 (+3)","vanDerWaalsRadius":"","ionizationEnergy":534,"electronAffinity":-50,"oxidationStates":"2, 3, 4","standardState":"solid","bondingType":"metallic","meltingPoint":1071,"boilingPoint":3633,"density":6.689,"groupBlock":"lanthanoid","yearDiscovered":1803}, {"atomicNumber":59,"symbol":"Pr","name":"Praseodymium","atomicMass":"140.90765(2)","cpkHexColor":"D9FFC7","electronicConfiguration":"2, 8, 18, 21, 8, 2","electronegativity":1.13,"atomicRadius":"","ionRadius":"99 (+3)","vanDerWaalsRadius":"","ionizationEnergy":527,"electronAffinity":-50,"oxidationStates":"2, 3, 4","standardState":"solid","bondingType":"metallic","meltingPoint":1204,"boilingPoint":3563,"density":6.64,"groupBlock":"lanthanoid","yearDiscovered":1885}, {"atomicNumber":60,"symbol":"Nd","name":"Neodymium","atomicMass":"144.242(3)","cpkHexColor":"C7FFC7","electronicConfiguration":"2, 8, 18, 22, 8, 2","electronegativity":1.14,"atomicRadius":"","ionRadius":"129 (+2)","vanDerWaalsRadius":"","ionizationEnergy":533,"electronAffinity":-50,"oxidationStates":"2, 3","standardState":"solid","bondingType":"metallic","meltingPoint":1294,"boilingPoint":3373,"density":7.01,"groupBlock":"lanthanoid","yearDiscovered":1885}, {"atomicNumber":61,"symbol":"Pm","name":"Promethium","atomicMass":[145],"cpkHexColor":"A3FFC7","electronicConfiguration":"2, 8, 18, 23, 8, 2","electronegativity":1.13,"atomicRadius":"","ionRadius":"97 (+3)","vanDerWaalsRadius":"","ionizationEnergy":540,"electronAffinity":-50,"oxidationStates":3,"standardState":"solid","bondingType":"metallic","meltingPoint":1373,"boilingPoint":3273,"density":7.264,"groupBlock":"lanthanoid","yearDiscovered":1947}, {"atomicNumber":62,"symbol":"Sm","name":"Samarium","atomicMass":"150.36(2)","cpkHexColor":"8FFFC7","electronicConfiguration":"2, 8, 18, 24, 8, 2","electronegativity":1.17,"atomicRadius":"","ionRadius":"122 (+2)","vanDerWaalsRadius":"","ionizationEnergy":545,"electronAffinity":-50,"oxidationStates":"2, 3","standardState":"solid","bondingType":"metallic","meltingPoint":1345,"boilingPoint":2076,"density":7.353,"groupBlock":"lanthanoid","yearDiscovered":1853}, {"atomicNumber":63,"symbol":"Eu","name":"Europium","atomicMass":"151.964(1)","cpkHexColor":"61FFC7","electronicConfiguration":"2, 8, 18, 25, 8, 2","electronegativity":1.2,"atomicRadius":"","ionRadius":"117 (+2)","vanDerWaalsRadius":"","ionizationEnergy":547,"electronAffinity":-50,"oxidationStates":"2, 3","standardState":"solid","bondingType":"metallic","meltingPoint ":1095,"boilingPoint":1800,"density":5.244,"groupBlock":"lanthanoid","yearDiscovered":1901}, {"atomicNumber":64,"symbol":"Gd","name":"Gadolinium","atomicMass":"157.25(3)","cpkHexColor":"45FFC7","electronicConfiguration":"2, 8, 18, 25, 9, 2","electronegativity":1.2,"atomicRadius":"","ionRadius":"93.8 (+3)","vanDerWaalsRadius":"","ionizationEnergy":593,"electronAffinity":-50,"oxidationStates":"1, 2, 3","standardState":"solid","bondingType":"metallic","meltingPoint":1586,"boilingPoint":3523,"density":7.901,"groupBlock":"lanthanoid","yearDiscovered":1880}, {"atomicNumber":65,"symbol":"Tb","name":"Terbium","atomicMass":"158.92535(2)","cpkHexColor":"30FFC7","electronicConfiguration":"2, 8, 18, 27, 8, 2","electronegativity":1.2,"atomicRadius":"","ionRadius":"92.3 (+3)","vanDerWaalsRadius":"","ionizationEnergy":566,"electronAffinity":-50,"oxidationStates":"1, 3, 4","standardState":"solid","bondingType":"metallic","meltingPoint":1629,"boilingPoint":3503,"density":8.219,"groupBlock":"lanthanoid","yearDiscovered":1843}, {"atomicNumber":66,"symbol":"Dy","name":"Dysprosium","atomicMass":"162.500(1)","cpkHexColor":"1FFFC7","electronicConfiguration":"2, 8, 18, 28, 8, 2","electronegativity":1.22,"atomicRadius":"","ionRadius":"107 (+2)","vanDerWaalsRadius":"","ionizationEnergy":573,"electronAffinity":-50,"oxidationStates":"2, 3","standardState":"solid","bondingType":"metallic","meltingPoint":1685,"boilingPoint":2840,"density":8.551,"groupBlock":"lanthanoid","yearDiscovered":1886}, {"atomicNumber":67,"symbol":"Ho","name":"Holmium","atomicMass":"164.93032(2)","cpkHexColor":"00FF9C","electronicConfiguration":"2, 8, 18, 29, 8, 2","electronegativity":1.23,"atomicRadius":"","ionRadius":"90.1 (+3)","vanDerWaalsRadius":"","ionizationEnergy":581,"electronAffinity":-50,"oxidationStates":3,"standardState":"solid","bondingType":"metallic","meltingPoint":1747,"boilingPoint":2973,"density":8.795,"groupBlock":"lanthanoid","yearDiscovered":1878}, {"atomicNumber":68,"symbol":"Er","name":"Erbium","atomicMass":"167.259(3)","cpkHexColor":0,"electronicConfiguration":"2, 8, 18, 30, 8, 2","electronegativity":1.24,"atomicRadius":"","ionRadius":"89 (+3)","vanDerWaalsRadius":"","ionizationEnergy":589,"electronAffinity":-50,"oxidationStates":3,"standardState":"solid","bondingType":"metallic","meltingPoint":1770,"boilingPoint":3141,"density":9.066,"groupBlock":"lanthanoid","yearDiscovered":1842}, {"atomicNumber":69,"symbol":"Tm","name":"Thulium","atomicMass":"168.93421(2)","cpkHexColor":"00D452","electronicConfiguration":"2, 8, 18, 31, 8, 2","electronegativity":1.25,"atomicRadius":"","ionRadius":"103 (+2)","vanDerWaalsRadius":"","ionizationEnergy":597,"electronAffinity":-50,"oxidationStates":"2, 3","standardState":"solid","bondingType":"metallic","meltingPoint":1818,"boilingPoint":2223,"density":9.321,"groupBlock":"lanthanoid","yearDiscovered":1879}, {"atomicNumber":70,"symbol":"Yb","name":"Ytterbium","atomicMass":"173.054(5)","cpkHexColor":"00BF38","electronicConfiguration":"2, 8, 18, 32, 8, 2","electronegativity":1.1,"atomicRadius":"","ionRadius":"102 (+2)","vanDerWaalsRadius":"","ionizationEnergy":603,"electronAffinity":-50,"oxidationStates":"2, 3","standardState":"solid","bondingType":"metallic","meltingPoint":1092,"boilingPoint":1469,"density":6.57,"groupBlock":"lanthanoid","yearDiscovered":1878}, {"atomicNumber":71,"symbol":"Lu","name":"Lutetium","atomicMass":"174.9668(1)","cpkHexColor":"00AB24","electronicConfiguration":"2, 8, 18, 32, 9, 2","electronegativity":1.27,"atomicRadius":160,"ionRadius":"86.1 (+3)","vanDerWaalsRadius":"","ionizationEnergy":524,"electronAffinity":-50,"oxidationStates":3,"standardState":"solid","bondingType":"metallic","meltingPoint":1936,"boilingPoint":3675,"density":9.841,"groupBlock":"lanthanoid","yearDiscovered":1907}, {"atomicNumber":72,"symbol":"Hf","name":"Hafnium","atomicMass":"178.49(2)","cpkHexColor":"4DC2FF","electronicConfiguration":"2, 8, 18, 32, 10, 2","electronegativity":1.3,"atomicRadius":150,"ionRadius":"71 (+4)","vanDerWaalsRadius":"","ionizationEnergy":659,"electronAffinity":0,"oxidationStates":"2, 3, 4","standardState":"solid","bondingType":"metallic","meltingPoint":2506,"boilingPoint":4876,"density":13.31,"groupBlock":"transition metal","yearDiscovered":1923}, {"atomicNumber":73,"symbol":"Ta","name":"Tantalum","atomicMass":"180.94788(2)","cpkHexColor":"4DA6FF","electronicConfiguration":"2, 8, 18, 32, 11, 2","electronegativity":1.5,"atomicRadius":138,"ionRadius":"72 (+3)","vanDerWaalsRadius":"","ionizationEnergy":761,"electronAffinity":-31,"oxidationStates":"-1, 2, 3, 4, 5","standardState":"solid","bondingType":"metallic","meltingPoint":3290,"boilingPoint":5731,"density":16.65,"groupBlock":"transition metal","yearDiscovered":1802}, {"atomicNumber":74,"symbol":"W","name":"Tungsten","atomicMass":"183.84(1)","cpkHexColor":"2194D6","electronicConfiguration":"2, 8, 18, 32, 12, 2","electronegativity":2.36,"atomicRadius":146,"ionRadius":"66 (+4)","vanDerWaalsRadius":"","ionizationEnergy":770,"electronAffinity":-79,"oxidationStates":"-2, -1, 1, 2, 3, 4, 5, 6","standardState":"solid","bondingType":"metallic","meltingPoint":3695,"boilingPoint":5828,"density":19.25,"groupBlock":"transition metal","yearDiscovered":1783}, {"atomicNumber":75,"symbol":"Re","name":"Rhenium","atomicMass":"186.207(1)","cpkHexColor":"267DAB","electronicConfiguration":"2, 8, 18, 32, 13, 2","electronegativity":1.9,"atomicRadius":159,"ionRadius":"63 (+4)","vanDerWaalsRadius":"","ionizationEnergy":760,"electronAffinity":-15,"oxidationStates":"-3, -1, 1, 2, 3, 4, 5, 6, 7","standardState":"solid","bondingType":"metallic","meltingPoint":3459,"boilingPoint":5869,"density":21.02,"groupBlock":"transition metal","yearDiscovered":1925}, {"atomicNumber":76,"symbol":"Os","name":"Osmium","atomicMass":"190.23(3)","cpkHexColor":266696,"electronicConfiguration":"2, 8, 18, 32, 14, 2","electronegativity":2.2,"atomicRadius":128,"ionRadius":"63 (+4)","vanDerWaalsRadius":"","ionizationEnergy":840,"electronAffinity":-106,"oxidationStates":"-2, -1, 1, 2, 3, 4, 5, 6, 7, 8","standardState":"solid","bondingType":"metallic","meltingPoint":3306,"boilingPoint":5285,"density":22.61,"groupBlock":"transition metal","yearDiscovered":1803}, {"atomicNumber":77,"symbol":"Ir","name":"Iridium","atomicMass":"192.217(3)","cpkHexColor":175487,"electronicConfiguration":"2, 8, 18, 32, 15, 2","electronegativity":2.2,"atomicRadius":137,"ionRadius":"68 (+3)","vanDerWaalsRadius":"","ionizationEnergy":880,"electronAffinity":-151,"oxidationStates":"-3, -1, 1, 2, 3, 4, 5, 6","standardState":"solid","bondingType":"metallic","meltingPoint":2739,"boilingPoint":4701,"density":22.65,"groupBlock":"transition metal","yearDiscovered":1803}, {"atomicNumber":78,"symbol":"Pt","name":"Platinum","atomicMass":"195.084(9)","cpkHexColor":"D0D0E0","electronicConfiguration":"2, 8, 18, 32, 17, 1","electronegativity":2.28,"atomicRadius":128,"ionRadius":"86 (+2)","vanDerWaalsRadius":175,"ionizationEnergy":870,"electronAffinity":-205,"oxidationStates":"2, 4, 5, 6","standardState":"solid","bondingType":"metallic","meltingPoint":2041,"boilingPoint":4098,"density":21.09,"groupBlock":"transition metal","yearDiscovered":"Ancient"}, {"atomicNumber":79,"symbol":"Au","name":"Gold","atomicMass":"196.966569(4)","cpkHexColor":"FFD123","electronicConfiguration":"2, 8, 18, 32, 18, 1","electronegativity":2.54,"atomicRadius":144,"ionRadius":"137 (+1)","vanDerWaalsRadius":166,"ionizationEnergy":890,"electronAffinity":-223,"oxidationStates":"-1, 1, 2, 3, 5","standardState":"solid","bondingType":"metallic","meltingPoint":1337,"boilingPoint":3129,"density":19.3,"groupBlock":"transition metal","yearDiscovered":"Ancient"}, {"atomicNumber":80,"symbol":"Hg","name":"Mercury","atomicMass":"200.59(2)","cpkHexColor":"B8B8D0","electronicConfiguration":"2, 8, 18, 32, 18, 2","electronegativity":2,"atomicRadius":149,"ionRadius":"119 (+1)","vanDerWaalsRadius":155,"ionizationEnergy":1007,"electronAffinity":0,"oxidationStates":"1, 2, 4","standardState":"liquid","bondingType":"metallic","meltingPoint":234,"boilingPoint":630,"density":13.534,"groupBlock":"transition metal","yearDiscovered":"Ancient"}, {"atomicNumber":81,"symbol":"Tl","name":"Thallium","atomicMass":"204.3833(2)","cpkHexColor":"A6544D","electronicConfiguration":"2, 8, 18, 32, 18, 3","electronegativity":2.04,"atomicRadius":148,"ionRadius":"150 (+1)","vanDerWaalsRadius":196,"ionizationEnergy":589,"electronAffinity":-19,"oxidationStates":"1, 3","standardState":"solid","bondingType":"metallic","meltingPoint":577,"boilingPoint":1746,"density":11.85,"groupBlock":"metal","yearDiscovered":1861}, {"atomicNumber":82,"symbol":"Pb","name":"Lead","atomicMass":"207.2(1)","cpkHexColor":575961,"electronicConfiguration":"2, 8, 18, 32, 18, 4","electronegativity":2.33,"atomicRadius":147,"ionRadius":"119 (+2)","vanDerWaalsRadius":202,"ionizationEnergy":716,"electronAffinity":-35,"oxidationStates":"-4, 2, 4","standardState":"solid","bondingType":"metallic","meltingPoint":601,"boilingPoint":2022,"density":11.34,"groupBlock":"metal","yearDiscovered":"Ancient"}, {"atomicNumber":83,"symbol":"Bi","name":"Bismuth","atomicMass":"208.98040(1)","cpkHexColor":"9E4FB5","electronicConfiguration":"2, 8, 18, 32, 18, 5","electronegativity":2.02,"atomicRadius":146,"ionRadius":"103 (+3)","vanDerWaalsRadius":"","ionizationEnergy":703,"electronAffinity":-91,"oxidationStates":"-3, 3, 5","standardState":"solid","bondingType":"metallic","meltingPoint":544,"boilingPoint":1837,"density":9.78,"groupBlock":"metal","yearDiscovered":"Ancient"}, {"atomicNumber":84,"symbol":"Po","name":"Polonium","atomicMass":[209],"cpkHexColor":"AB5C00","electronicConfiguration":"2, 8, 18, 32, 18, 6","electronegativity":2,"atomicRadius":"","ionRadius":"94 (+4)","vanDerWaalsRadius":"","ionizationEnergy":812,"electronAffinity":-183,"oxidationStates":"-2, 2, 4, 6","standardState":"solid","bondingType":"metallic","meltingPoint":527,"boilingPoint":1235,"density":9.196,"groupBlock":"metalloid","yearDiscovered":1898}, {"atomicNumber":85,"symbol":"At","name":"Astatine","atomicMass":[210],"cpkHexColor":"754F45","electronicConfiguration":"2, 8, 18, 32, 18, 7","electronegativity":2.2,"atomicRadius":"","ionRadius":"62 (+7)","vanDerWaalsRadius":"","ionizationEnergy":920,"electronAffinity":-270,"oxidationStates":"-1, 1, 3, 5","standardState":"solid","bondingType":"covalent network","meltingPoint":575,"boilingPoint":"","density":"","groupBlock":"halogen","yearDiscovered":1940}, {"atomicNumber":86,"symbol":"Rn","name":"Radon","atomicMass":[222],"cpkHexColor":428296,"electronicConfiguration":"2, 8, 18, 32, 18, 8","electronegativity":"","atomicRadius":145,"ionRadius":"","vanDerWaalsRadius":"","ionizationEnergy":1037,"electronAffinity":"","oxidationStates":2,"standardState":"gas","bondingType":"atomic","meltingPoint":202,"boilingPoint":211,"density":0.00973,"groupBlock":"noble gas","yearDiscovered":1900}, {"atomicNumber":87,"symbol":"Fr","name":"Francium","atomicMass":[223],"cpkHexColor":420066,"electronicConfiguration":"2, 8, 18, 32, 18, 8, 1","electronegativity":0.7,"atomicRadius":"","ionRadius":"180 (+1)","vanDerWaalsRadius":"","ionizationEnergy":380,"electronAffinity":"","oxidationStates":1,"standardState":"solid","bondingType":"metallic","meltingPoint":"","boilingPoint":"","density":"","groupBlock":"alkali metal","yearDiscovered":1939}, {"atomicNumber":88,"symbol":"Ra","name":"Radium","atomicMass":[226],"cpkHexColor":"007D00","electronicConfiguration":"2, 8, 18, 32, 18, 8, 2","electronegativity":0.9,"atomicRadius":"","ionRadius":"148 (+2)","vanDerWaalsRadius":"","ionizationEnergy":509,"electronAffinity":"","oxidationStates":2,"standardState":"solid","bondingType":"metallic","meltingPoint":973,"boilingPoint":2010,"density":5,"groupBlock":"alkaline earth metal","yearDiscovered":1898}, {"atomicNumber":89,"symbol":"Ac","name":"Actinium","atomicMass":[227],"cpkHexColor":"70ABFA","electronicConfiguration":"2, 8, 18, 32, 18, 9, 2","electronegativity":1.1,"atomicRadius":"","ionRadius":"112 (+3)","vanDerWaalsRadius":"","ionizationEnergy":499,"electronAffinity":"","oxidationStates":3,"standardState":"solid","bondingType":"metallic","meltingPoint":1323,"boilingPoint":3473,"density":10.07,"groupBlock":"actinoid","yearDiscovered":1899}, {"atomicNumber":90,"symbol":"Th","name":"Thorium","atomicMass":"232.03806(2)","cpkHexColor":"00BAFF","electronicConfiguration":"2, 8, 18, 32, 18, 10, 2","electronegativity":1.3,"atomicRadius":"","ionRadius":"94 (+4)","vanDerWaalsRadius":"","ionizationEnergy":587,"electronAffinity":"","oxidationStates":"2, 3, 4","standardState":"solid","bondingType":"metallic","meltingPoint":2023,"boilingPoint":5093,"density":11.724,"groupBlock":"actinoid","yearDiscovered":1828}, {"atomicNumber":91,"symbol":"Pa","name":"Protactinium","atomicMass":"231.03588(2)","cpkHexColor":"00A1FF","electronicConfiguration":"2, 8, 18, 32, 20, 9, 2","electronegativity":1.5,"atomicRadius":"","ionRadius":"104 (+3)","vanDerWaalsRadius":"","ionizationEnergy":568,"electronAffinity":"","oxidationStates":"3, 4, 5","standardState":"solid","bondingType":"metallic","meltingPoint":1845,"boilingPoint":4273,"density":15.37,"groupBlock":"actinoid","yearDiscovered":1913}, {"atomicNumber":92,"symbol":"U","name":"Uranium","atomicMass":"238.02891(3)","cpkHexColor":"008FFF","electronicConfiguration":"2, 8, 18, 32, 21, 9, 2","electronegativity":1.38,"atomicRadius":"","ionRadius":"102.5 (+3)","vanDerWaalsRadius":186,"ionizationEnergy":598,"electronAffinity":"","oxidationStates":"3, 4, 5, 6","standardState":"solid","bondingType":"metallic","meltingPoint":1408,"boilingPoint":4200,"density":19.05,"groupBlock":"actinoid","yearDiscovered":1789}, {"atomicNumber":93,"symbol":"Np","name":"Neptunium","atomicMass":[237],"cpkHexColor":"0080FF","electronicConfiguration":"2, 8, 18, 32, 22, 9, 2","electronegativity":1.36,"atomicRadius":"","ionRadius":"110 (+2)","vanDerWaalsRadius":"","ionizationEnergy":605,"electronAffinity":"","oxidationStates":"3, 4, 5, 6, 7","standardState":"solid","bondingType":"metallic","meltingPoint":917,"boilingPoint":4273,"density":20.45,"groupBlock":"actinoid","yearDiscovered":1940}, {"atomicNumber":94,"symbol":"Pu","name":"Plutonium","atomicMass":[244],"cpkHexColor":"006BFF","electronicConfiguration":"2, 8, 18, 32, 24, 8, 2","electronegativity":1.28,"atomicRadius":"","ionRadius":"100 (+3)","vanDerWaalsRadius":"","ionizationEnergy":585,"electronAffinity":"","oxidationStates":"3, 4, 5, 6, 7","standardState":"solid","bondingType":"metallic","meltingPoint":913,"boilingPoint":3503,"density":19.816,"groupBlock":"actinoid","yearDiscovered":1940}, {"atomicNumber":95,"symbol":"Am","name":"Americium","atomicMass":[243],"cpkHexColor":"545CF2","electronicConfiguration":"2, 8, 18, 32, 25, 8, 2","electronegativity":1.3,"atomicRadius":"","ionRadius":"126 (+2)","vanDerWaalsRadius":"","ionizationEnergy":578,"electronAffinity":"","oxidationStates":"2, 3, 4, 5, 6","standardState":"solid","bondingType":"metallic","meltingPoint":1449,"boilingPoint":2284,"density":"","groupBlock":"actinoid","yearDiscovered":1944}, {"atomicNumber":96,"symbol":"Cm","name":"Curium","atomicMass":[247],"cpkHexColor":"785CE3","electronicConfiguration":"2, 8, 18, 32, 25, 9, 2","electronegativity":1.3,"atomicRadius":"","ionRadius":"97 (+3)","vanDerWaalsRadius":"","ionizationEnergy":581,"electronAffinity":"","oxidationStates":"3, 4","standardState":"solid","bondingType":"metallic","meltingPoint":1618,"boilingPoint":3383,"density":13.51,"groupBlock":"actinoid","yearDiscovered":1944}, {"atomicNumber":97,"symbol":"Bk","name":"Berkelium","atomicMass":[247],"cpkHexColor":"8A4FE3","electronicConfiguration":"2, 8, 18, 32, 27, 8, 2","electronegativity":1.3,"atomicRadius":"","ionRadius":"96 (+3)","vanDerWaalsRadius":"","ionizationEnergy":601,"electronAffinity":"","oxidationStates":"3, 4","standardState":"solid","bondingType":"metallic","meltingPoint":1323,"boilingPoint":"","density":14.78,"groupBlock":"actinoid","yearDiscovered":1949}, {"atomicNumber":98,"symbol":"Cf","name":"Californium","atomicMass":[251],"cpkHexColor":"A136D4","electronicConfiguration":"2, 8, 18, 32, 28, 8, 2","electronegativity":1.3,"atomicRadius":"","ionRadius":"95 (+3)","vanDerWaalsRadius":"","ionizationEnergy":608,"electronAffinity":"","oxidationStates":"2, 3, 4","standardState":"solid","bondingType":"metallic","meltingPoint":1173,"boilingPoint":"","density":15.1,"groupBlock":"actinoid","yearDiscovered":1950}, {"atomicNumber":99,"symbol":"Es","name":"Einsteinium","atomicMass":[252],"cpkHexColor":"B31FD4","electronicConfiguration":"2, 8, 18, 32, 29, 8, 2","electronegativity":1.3,"atomicRadius":"","ionRadius":"","vanDerWaalsRadius":"","ionizationEnergy":619,"electronAffinity":"","oxidationStates":"2, 3","standardState":"solid","bondingType":"","meltingPoint":1133,"boilingPoint":"","density":"","groupBlock":"actinoid","yearDiscovered":1952}, {"atomicNumber":100,"symbol":"Fm","name":"Fermium","atomicMass":[257],"cpkHexColor":"B31FBA","electronicConfiguration":"2, 8, 18, 32, 30, 8, 2","electronegativity":1.3,"atomicRadius":"","ionRadius":"","vanDerWaalsRadius":"","ionizationEnergy":627,"electronAffinity":"","oxidationStates":"2, 3","standardState":"","bondingType":"","meltingPoint":1800,"boilingPoint":"","density":"","groupBlock":"actinoid","yearDiscovered":1952}, {"atomicNumber":101,"symbol":"Md","name":"Mendelevium","atomicMass":[258],"cpkHexColor":"B30DA6","electronicConfiguration":"2, 8, 18, 32, 31, 8, 2","electronegativity":1.3,"atomicRadius":"","ionRadius":"","vanDerWaalsRadius":"","ionizationEnergy":635,"electronAffinity":"","oxidationStates":"2, 3","standardState":"","bondingType":"","meltingPoint":1100,"boilingPoint":"","density":"","groupBlock":"actinoid","yearDiscovered":1955}, {"atomicNumber":102,"symbol":"No","name":"Nobelium","atomicMass":[259],"cpkHexColor":"BD0D87","electronicConfiguration":"2, 8, 18, 32, 32, 8, 2","electronegativity":1.3,"atomicRadius":"","ionRadius":"","vanDerWaalsRadius":"","ionizationEnergy":642,"electronAffinity":"","oxidationStates":"2, 3","standardState":"","bondingType":"","meltingPoint":1100,"boilingPoint":"","density":"","groupBlock":"actinoid","yearDiscovered":1957}, {"atomicNumber":103,"symbol":"Lr","name":"Lawrencium","atomicMass":[262],"cpkHexColor":"C70066","electronicConfiguration":"2, 8, 18, 32, 32, 8, 3","electronegativity":1.3,"atomicRadius":"","ionRadius":"","vanDerWaalsRadius":"","ionizationEnergy":"","electronAffinity":"","oxidationStates":3,"standardState":"","bondingType":"","meltingPoint":1900,"boilingPoint":"","density":"","groupBlock":"transition metal","yearDiscovered":1961}, {"atomicNumber":104,"symbol":"Rf","name":"Rutherfordium","atomicMass":[267],"cpkHexColor":"CC0059","electronicConfiguration":"2, 8, 18, 32, 32, 10, 2","electronegativity":"","atomicRadius":"","ionRadius":"","vanDerWaalsRadius":"","ionizationEnergy":"","electronAffinity":"","oxidationStates":4,"standardState":"","bondingType":"","meltingPoint":"","boilingPoint":"","density":"","groupBlock":"transition metal","yearDiscovered":1969}, {"atomicNumber":105,"symbol":"Db","name":"Dubnium","atomicMass":[268],"cpkHexColor":"D1004F","electronicConfiguration":"2, 8, 18, 32, 32, 11, 2","electronegativity":"","atomicRadius":"","ionRadius":"","vanDerWaalsRadius":"","ionizationEnergy":"","electronAffinity":"","oxidationStates":"","standardState":"","bondingType":"","meltingPoint":"","boilingPoint":"","density":"","groupBlock":"transition metal","yearDiscovered":1967}, {"atomicNumber":106,"symbol":"Sg","name":"Seaborgium","atomicMass":[271],"cpkHexColor":"D90045","electronicConfiguration":"2, 8, 18, 32, 32, 12, 2","electronegativity":"","atomicRadius":"","ionRadius":"","vanDerWaalsRadius":"","ionizationEnergy":"","electronAffinity":"","oxidationStates":"","standardState":"","bondingType":"","meltingPoint":"","boilingPoint":"","density":"","groupBlock":"transition metal","yearDiscovered":1974}, {"atomicNumber":107,"symbol":"Bh","name":"Bohrium","atomicMass":[272],"cpkHexColor":"E00038","electronicConfiguration":"2, 8, 18, 32, 32, 13, 2","electronegativity":"","atomicRadius":"","ionRadius":"","vanDerWaalsRadius":"","ionizationEnergy":"","electronAffinity":"","oxidationStates":"","standardState":"","bondingType":"","meltingPoint":"","boilingPoint":"","density":"","groupBlock":"transition metal","yearDiscovered":1976}, {"atomicNumber":108,"symbol":"Hs","name":"Hassium","atomicMass":[270],"cpkHexColor":"E6002E","electronicConfiguration":"2, 8, 18, 32, 32, 14, 2","electronegativity":"","atomicRadius":"","ionRadius":"","vanDerWaalsRadius":"","ionizationEnergy":"","electronAffinity":"","oxidationStates":"","standardState":"","bondingType":"","meltingPoint":"","boilingPoint":"","density":"","groupBlock":"transition metal","yearDiscovered":1984}, {"atomicNumber":109,"symbol":"Mt","name":"Meitnerium","atomicMass":[276],"cpkHexColor":"EB0026","electronicConfiguration":"2, 8, 18, 32, 32, 15, 2","electronegativity":"","atomicRadius":"","ionRadius":"","vanDerWaalsRadius":"","ionizationEnergy":"","electronAffinity":"","oxidationStates":"","standardState":"","bondingType":"","meltingPoint":"","boilingPoint":"","density":"","groupBlock":"transition metal","yearDiscovered":1982}, {"atomicNumber":110,"symbol":"Ds","name":"Darmstadtium","atomicMass":[281],"cpkHexColor":"","electronicConfiguration":"2, 8, 18, 32, 32, 16, 2","electronegativity":"","atomicRadius":"","ionRadius":"","vanDerWaalsRadius":"","ionizationEnergy":"","electronAffinity":"","oxidationStates":"","standardState":"","bondingType":"","meltingPoint":"","boilingPoint":"","density":"","groupBlock":"transition metal","yearDiscovered":1994}, {"atomicNumber":111,"symbol":"Rg","name":"Roentgenium","atomicMass":[280],"cpkHexColor":"","electronicConfiguration":"2, 8, 18, 32, 32, 17, 2","electronegativity":"","atomicRadius":"","ionRadius":"","vanDerWaalsRadius":"","ionizationEnergy":"","electronAffinity":"","oxidationStates":"","standardState":"","bondingType":"","meltingPoint":"","boilingPoint":"","density":"","groupBlock":"transition metal","yearDiscovered":1994}, {"atomicNumber":112,"symbol":"Cn","name":"Copernicium","atomicMass":[285],"cpkHexColor":"","electronicConfiguration":"2, 8, 18, 32, 32, 18, 2","electronegativity":"","atomicRadius":"","ionRadius":"","vanDerWaalsRadius":"","ionizationEnergy":"","electronAffinity":"","oxidationStates":"","standardState":"","bondingType":"","meltingPoint":"","boilingPoint":"","density":"","groupBlock":"transition metal","yearDiscovered":1996}, {"atomicNumber":113,"symbol":"Nh","name":"Nihonium","atomicMass":[284],"cpkHexColor":"","electronicConfiguration":"2, 8, 18, 32, 32, 18, 3","electronegativity":"","atomicRadius":"","ionRadius":"","vanDerWaalsRadius":"","ionizationEnergy":"","electronAffinity":"","oxidationStates":"","standardState":"","bondingType":"","meltingPoint":"","boilingPoint":"","density":"","groupBlock":"post-transition metal","yearDiscovered":2003}, {"atomicNumber":114,"symbol":"Fl","name":"Flerovium","atomicMass":[289],"cpkHexColor":"","electronicConfiguration":"2, 8, 18, 32, 32, 18, 4","electronegativity":"","atomicRadius":"","ionRadius":"","vanDerWaalsRadius":"","ionizationEnergy":"","electronAffinity":"","oxidationStates":"","standardState":"","bondingType":"","meltingPoint":"","boilingPoint":"","density":"","groupBlock":"post-transition metal","yearDiscovered":1998}, {"atomicNumber":115,"symbol":"Mc","name":"Moscovium","atomicMass":[288],"cpkHexColor":"","electronicConfiguration":"2, 8, 18, 32, 32, 18, 5","electronegativity":"","atomicRadius":"","ionRadius":"","vanDerWaalsRadius":"","ionizationEnergy":"","electronAffinity":"","oxidationStates":"","standardState":"","bondingType":"","meltingPoint":"","boilingPoint":"","density":"","groupBlock":"post-transition metal","yearDiscovered":2003}, {"atomicNumber":116,"symbol":"Lv","name":"Livermorium","atomicMass":[293],"cpkHexColor":"","electronicConfiguration":"2, 8, 18, 32, 32, 18, 6","electronegativity":"","atomicRadius":"","ionRadius":"","vanDerWaalsRadius":"","ionizationEnergy":"","electronAffinity":"","oxidationStates":"","standardState":"","bondingType":"","meltingPoint":"","boilingPoint":"","density":"","groupBlock":"post-transition metal","yearDiscovered":2000}, {"atomicNumber":117,"symbol":"Ts","name":"Tennessine","atomicMass":[294],"cpkHexColor":"","electronicConfiguration":"2, 8, 18, 32, 32, 18, 7","electronegativity":"","atomicRadius":"","ionRadius":"","vanDerWaalsRadius":"","ionizationEnergy":"","electronAffinity":"","oxidationStates":"","standardState":"","bondingType":"","meltingPoint":"","boilingPoint":"","density":"","groupBlock":"post-transition metal","yearDiscovered":2010}, {"atomicNumber":118,"symbol":"Og","name":"Oganesson","atomicMass":[294],"cpkHexColor":"","electronicConfiguration":"2, 8, 18, 32, 32, 18, 8","electronegativity":"","atomicRadius":"","ionRadius":"","vanDerWaalsRadius":"","ionizationEnergy":"","electronAffinity":"","oxidationStates":"","standardState":"","bondingType":"","meltingPoint":"","boilingPoint":"","density":"","groupBlock":"noble gas","yearDiscovered":2002} ] </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-11T07:03:49.560", "Id": "475028", "Score": "1", "body": "Welcome! Good to see you are learning python programming :) But threse questions: \"Do you guys think this is a good project to feature on a resume for my first junior dev position? Do you think this is a good project that shows I know what I'm doing? Do you think this could land me a job or do I need to show I know more?\" --> are off topic for Code Review :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-11T07:05:20.993", "Id": "475029", "Score": "0", "body": "@RobAu I asked it over att Stackoverflow first and they told me to post it here instead. Do you have any idea where I should post it?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-11T07:41:02.197", "Id": "475031", "Score": "4", "body": "We can review your code, no problem. But whether or not this project will land you a job is such a complicated question (depending on a lot of variables *and* outside of our scope) I wouldn't know where you'd get a decent answer on it. Please see our [help/on-topic] to see what we do and don't do here." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-11T07:42:15.030", "Id": "475032", "Score": "0", "body": "What does your `periodictable.json` look like? Why do you need `self.perodictable` on top of that?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-11T07:45:19.207", "Id": "475033", "Score": "0", "body": "At first glance, I think you could use some more practice before applying for a junior dev position. But if you provide us with more context about the code, we can probably review it in such a way to get you a decent start on your journey. You'll get there, but I wouldn't want this code-quality in my code base at work." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-11T09:13:57.203", "Id": "475036", "Score": "2", "body": "(Depending on mood, I might be put off by typos as in `compeltely finsihed`, `perodictable`, even lower-case acronyms.)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-11T09:15:22.020", "Id": "475037", "Score": "2", "body": "[Let the title state the goal of the code presented](https://codereview.stackexchange.com/help/how-to-ask)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-11T17:09:42.070", "Id": "475093", "Score": "0", "body": "@Mast Do you think you could help me out on how to improve my code-quality? What do I need to think about while writing?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-11T18:21:20.717", "Id": "475094", "Score": "0", "body": "If you put in the effort, I'm sure we can help you. I'm a bit short on time though, so if nobody else writes an answer it might take a while till I've finished mine. But your question does look interesting so I'll keep commenting till it's reviewable or answered. Please heed all comments that have been posted so far." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "9", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-11T06:50:48.853", "Id": "242063", "Score": "2", "Tags": [ "python", "mysql" ], "Title": "Junior Dev Self-taught Resume Project" }
242063
<p>I find myself often encountering a use case where I need to fetch paginated data, where I need <em>all</em> of the data. Currently I use something similar to below to handle these cases:</p> <pre class="lang-py prettyprint-override"><code>def fetch_paginated_data(api_base, query, good_citizen_rate): encoded = urllib.parse.quote(query.encode('utf-8')) initial = f'{api_base}?q={encoded}' payload = { 'has_more': True, 'next_page': initial } storage = [] while payload['has_more']: response = requests.get(payload['next_page']) if response.status_code != 200: raise ValueError('Status not 200') payload['has_more'] = False return data = response.json() if (data and data['data']): storage.extend(data['data']) payload['has_more'] = data['has_more'] if 'next_page' in data: payload['next_page'] = data['next_page'] time.sleep(good_citizen_rate) return storage </code></pre> <p>My question is how could I better make this convention more reusable? Should I use <code>async</code> / <code>await</code>? <code>yield</code> pages? Add a callback to transform the data prior to adding it to the collection variable?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-11T12:38:54.453", "Id": "475059", "Score": "0", "body": "What would be the response of `requests.get(payload['next_page'])` if there is no next page? And why do you need `time.sleep(good_citizen_rate)`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-11T13:03:10.597", "Id": "475072", "Score": "0", "body": "@ades that is why there is a `has_more` from the apis I often use. `time.sleep(good_citizen_rate)` is to follow the providers of these apis guidelines" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-19T13:10:08.223", "Id": "475997", "Score": "0", "body": "It seems that the statement `payload['has_more'] = False` has no effect, because it is written **after** `raise` (also the `return`). And it seems not only related to 3.6+ (except for the f-string feature you're using, so this is only a side comment)." } ]
[ { "body": "<p>Without the other code that calls that function is difficutl to say if you need async operations or not, on the other hand here are some suggestions to make your code more pythonic.</p>\n\n<pre><code>payload = {\n 'has_more': True,\n 'next_page': initial\n}\n</code></pre>\n\n<p>Change to</p>\n\n<pre><code>has_more = True\nnext_page = initial\n</code></pre>\n\n<p>Your code</p>\n\n<pre><code>while payload['has_more']:\n response = requests.get(payload['next_page'])\n if response.status_code != 200:\n raise ValueError('Status not 200')\n payload['has_more'] = False\n return\n</code></pre>\n\n<p>Change to</p>\n\n<pre><code>while has_more:\n response = requests.get(payload['next_page'])\n if response.status_code != 200:\n raise ValueError('Status not 200')\n</code></pre>\n\n<p>Your code</p>\n\n<pre><code> payload['has_more'] = data['has_more']\n</code></pre>\n\n<p>Change to</p>\n\n<pre><code> has_more = data['has_more']\n</code></pre>\n\n<p>Sorry if I forget more changes.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-11T07:55:31.367", "Id": "242069", "ParentId": "242064", "Score": "0" } }, { "body": "<p>You should let the <code>requests</code> module do the urlencoding for you. It can take a <a href=\"https://requests.readthedocs.io/en/master/user/quickstart/#passing-parameters-in-urls\" rel=\"nofollow noreferrer\">dictionary of parameters</a> and do it right.</p>\n\n<p>Instead of having a variable around which you check in your <code>while</code> condition, I would prefer a <code>while True</code> and an explicit <code>break</code> here. The loop is small enough that this makes it more readable IMO.</p>\n\n<p>I would indeed use <code>yield</code>, or rather <code>yield from</code> here, in order to flatten the response. This means that the next page is only fetched when you have consumed the previous data. If you need to, you could also make it asynchronously using <a href=\"https://docs.aiohttp.org/en/stable/\" rel=\"nofollow noreferrer\"><code>aiohttp</code></a>, have a look at <a href=\"https://codereview.stackexchange.com/q/237253/98493\">this question of mine</a> which used it or the documentation I linked.</p>\n\n<p>You can also use <a href=\"https://2.python-requests.org/en/master/api/#requests.Response.raise_for_status\" rel=\"nofollow noreferrer\"><code>response.raise_for_status</code></a> to raise an exception if the status code is not 2XX. Note that any code after a <code>raise</code> is not accessible, so your <code>payload['has_more'] = False</code> and <code>return</code> will never run (unless you run it in a debugger or something).</p>\n\n<p>Python has an official style-guide, <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP8</a>, which you are following (nice!). One thing it does not recommend but I would nevertheless encourage you to do is not using unnecessary parenthesis in <code>if</code> statements. Python is not C.</p>\n\n<pre><code>def fetch_paginated_data(url, query, timeout=0): \n params = {\"q\": query}\n while True:\n response = requests.get(url, params=params)\n response.raise_for_status()\n data = response.json()\n if data and data['data']:\n yield from data['data']\n if not data['has_more']:\n break\n url = data['next_page']\n time.sleep(timeout)\n</code></pre>\n\n<p>Here I left the interface as is. If you are free to change it, I would consider taking <code>params</code> directly as an argument or even collect all keyword arguments (except for the timeout, which I also gave a defualt value) directly into a dictionary with <code>**params</code>. The latter would give you the very nice interface:</p>\n\n<pre><code>data = fetch_paginated_data(\"example.com\", q=\"FooBar\", timeout=3)\n</code></pre>\n\n<p>Instead of <code>if data and data['data']:</code> you could also just use a <code>try..except</code> block. This will be slightly more performant if the response usually has this key:</p>\n\n<pre><code>try:\n yield from data['data']\nexcept (KeyError, TypeError): # for dict, list\n pass\n</code></pre>\n\n<p>You should definitely add a <a href=\"https://www.python.org/dev/peps/pep-0257/\" rel=\"nofollow noreferrer\"><code>docstring</code></a> describing what this function does. Especially your naming the timeout a rate can be confusing for other people reading your code, or yourself in half a year.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-19T12:50:45.313", "Id": "242560", "ParentId": "242064", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-11T07:04:37.453", "Id": "242064", "Score": "2", "Tags": [ "python", "python-3.x", "asynchronous" ], "Title": "Python 3.6+ Conventions for fetching paginated data" }
242064
<p><strong>Goal:</strong></p> <p>Goal of this application is to sign in using MySQL database and across the forms access the username and access id.</p> <p>Reason I am sharing the username is for only reason at the moment, is to display a welcome message for the user.</p> <p>For the access id, depending on what number id, different dashboard buttons will restricted.</p> <p>I'd like to hear some of your thoughts on my coding - and whether the structure is good. </p> <p><strong>Login Screen.xaml.cs</strong></p> <pre><code>public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } //Send object from MySQL results to the User class User u = new User(); private void Button_Click(object sender, RoutedEventArgs e) { try { //Connection string string connString = ConfigurationManager.ConnectionStrings["Technical_Application.Properties.Settings.MySQL"].ConnectionString; using (var conn = new MySqlConnection(connString)) { conn.Open(); //MySQL command using (var cmd = new MySqlCommand("SELECT count(*), id, access, username from users where username = '"+ txtUsername.Text + "' and password = MD5('" + txtPassword.Password + "');", conn)) { cmd.ExecuteNonQuery(); //Place results into dataTable DataTable dt = new DataTable(); MySqlDataAdapter da = new MySqlDataAdapter(cmd); da.Fill(dt); conn.Close(); if (dt.Rows[0][0].ToString() == "1") { //Send results to class u.id = Int32.Parse(dt.Rows[0][1].ToString()); u.access = Int32.Parse(dt.Rows[0][2].ToString()); u.username = dt.Rows[0][3].ToString(); Dashboard dashboard = new Dashboard(); dashboard.Show(); this.Close(); } else { MessageBox.Show("Login Failed", "Technical Login Error", MessageBoxButton.OK, MessageBoxImage.Warning); } } } } catch (Exception ex) { MessageBox.Show(ex.ToString()); } } private void Window_Loaded(object sender, RoutedEventArgs e) { txtUsername.Focus(); } private void CloseButton_Click(object sender, RoutedEventArgs e) { Close(); } } </code></pre> <p><strong>Login Screen.xaml</strong></p> <pre><code>&lt;Grid&gt; &lt;Grid&gt; &lt;Grid.RowDefinitions&gt; &lt;RowDefinition/&gt; &lt;RowDefinition/&gt; &lt;/Grid.RowDefinitions&gt; &lt;Border CornerRadius="10" Grid.RowSpan="2"&gt; &lt;Border.Background&gt; &lt;LinearGradientBrush&gt; &lt;GradientStop Color="White"/&gt; &lt;/LinearGradientBrush&gt; &lt;/Border.Background&gt; &lt;/Border&gt; &lt;Button Name="CloseButton" Content="x" Margin="0,10,0,164" Foreground="Black" FontSize="30" VerticalAlignment="Center" HorizontalAlignment="Right" Height="51" BorderBrush="Transparent" Background="Transparent" Click="CloseButton_Click"&gt;&lt;/Button&gt; &lt;StackPanel VerticalAlignment="Center"&gt; &lt;Image Source="Resources/Logo.jpg" Width="80"/&gt; &lt;/StackPanel&gt; &lt;StackPanel Grid.Row="1"&gt; &lt;StackPanel Orientation="Horizontal"&gt; &lt;TextBox FontFamily="Helvetica" x:Name="txtUsername" FontWeight="Light" HorizontalContentAlignment="Left" HorizontalAlignment="Center" Width="235" Foreground="Black" FontSize="18" Height="30" Margin="63,0,0,0" /&gt; &lt;iconPacks:PackIconControl Kind="{x:Static iconPacks:PackIconMaterialKind.Account}" Width="24" Height="24" HorizontalAlignment="Center" VerticalAlignment="Center" Margin="10,0,0,0"/&gt; &lt;/StackPanel&gt; &lt;StackPanel Orientation="Horizontal" Margin="0,30,0,0"&gt; &lt;PasswordBox FontFamily="Helvetica" x:Name="txtPassword" FontWeight="Light" HorizontalContentAlignment="Left" HorizontalAlignment="Center" Width="235" Foreground="Black" FontSize="18" Height="30" Margin="63,0,0,0" /&gt; &lt;iconPacks:PackIconControl Kind="{x:Static iconPacks:PackIconMaterialKind.FormTextboxPassword}" Width="24" Height="24" HorizontalAlignment="Center" VerticalAlignment="Center" Margin="10,0,0,0"/&gt; &lt;/StackPanel&gt; &lt;Button Margin="0,50,0,0" Width="200" Click="Button_Click" Foreground="White"&gt;Login&lt;/Button&gt; &lt;/StackPanel&gt; &lt;/Grid&gt; &lt;/Grid&gt; </code></pre> <p><strong>User.cs</strong> - This is where I store the info and shared later for other forms to access the information required.</p> <pre><code>namespace Technical_Application { class User { public int id; public int access; public string username; public int ID { get { return id; } set { id = value; } } public int Access { get { return access; } set { access = value; } } public string Username { get { return username; } set { username = value; } } } } </code></pre> <p><strong>More detail:</strong></p> <p>This application will not be cloud or web based. It's fully only for a desktop application and to be used internally.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-11T14:57:08.233", "Id": "475083", "Score": "0", "body": "This code doesn't do what you describe. The `User` information isn't shown to be used on the other forms." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-11T15:10:14.580", "Id": "475085", "Score": "0", "body": "@tinstaafl oh wow.. you're correct. Think I need to look into MVVM to share the user info," } ]
[ { "body": "<p>Some quick remarks:</p>\n\n<ul>\n<li><p>If you're doing WPF, you should be <a href=\"https://docs.microsoft.com/en-us/archive/msdn-magazine/2009/february/patterns-wpf-apps-with-the-model-view-viewmodel-design-pattern\" rel=\"noreferrer\">using MVVM</a>. There is a learning curve, but your code will be vastly easier to maintain once you add more and more features.</p></li>\n<li><p>Much of the code inside <code>Button_Click</code> should be in separate classes (and arguably even separate layers).</p></li>\n<li><p>Your code is vulnerable to SQL injection. Also, avoid writing ADO.NET and instead <a href=\"https://dapper-tutorial.net/\" rel=\"noreferrer\">use Dapper</a>.</p></li>\n<li><p>Do not mix the UI and the back-end logic. Have your login logic return a custom class and display an error message depending on the contents of that class.</p></li>\n<li><p>Why are the fields of <code>User</code> set to <code>public</code>? Why even have such fields, when <a href=\"https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/auto-implemented-properties\" rel=\"noreferrer\">auto-implemented properties</a> have been a thing for more than a decade?</p></li>\n<li><p>To me, <code>Access</code> feels like it should be an <code>enum</code> and not a meaningless <code>int</code>.</p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-11T15:16:12.803", "Id": "475086", "Score": "0", "body": "Appreciate your remarks. I have tried MVVM but struggle to understand it. I'll need to find a proper lesson or tutorial for it, if you have any beginner links, feel free to fire them at me. Regarding `Button_Click` - can you expand on that please? That's how I've learned it and seen others do it, i'd like to know why you suggested to separate it? `Dapper` great link! cheers." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-11T15:33:43.187", "Id": "475087", "Score": "0", "body": "(Once you do MVVM, you won't even have a Button_Click method, you're working with Commands (e.g. https://stackoverflow.com/a/39601781/648075 ).) The separation is necessary, because otherwise you'll end up with an overlong code behind file that is impossible to maintain. If you move all that DB code to a class of its own and call that, your method will decrease in length and become easier to read. See also https://en.wikipedia.org/wiki/SOLID ." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-12T07:09:27.147", "Id": "475124", "Score": "0", "body": "Moment you mentioned I won't need `Button_Click` method - that just opened up my mind how much flexible coding really is! Also found a great MVVM tutorial here if anybody needs it https://www.wintellect.com/model-view-viewmodel-mvvm-explained/" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-11T14:59:10.373", "Id": "242081", "ParentId": "242068", "Score": "6" } }, { "body": "<h1>DB query</h1>\n<p>Check how you can use LINQ with mySQL. The query code will be shorter and readable with LINQ. Also, syntax errors are caught at compile time.</p>\n<p>Regardless of my suggestion to use LINQ, here my review of your current implementation :</p>\n<ul>\n<li><p>Don't ever concatenate strings to create a query. This way is vulnerable to SQL Injection. Use query parameters instead.</p>\n</li>\n<li><p>No need for count(*), just check the number of rows in the DataTable.</p>\n</li>\n</ul>\n<h1>Error handling</h1>\n<p>You show a message box with the exception. It means nothing to the user. Also, it is considered not safe to show internal errors.</p>\n<p>I suggest at least to add a human-friendly error like &quot;an error occurred, please send this to XXX Exception message &quot;</p>\n<p>I guess you did this so the user will pass you the error.<br />\nThese are the approaches I am familiar with:</p>\n<ol>\n<li>Write the errors in log and add a way for the user to send it to you.</li>\n<li>Use a library that reports errors to an external service.</li>\n</ol>\n<p>When the user doesn't succeed to connect aka <code>connection.Open</code> fails. The user gets an error message of the exception.</p>\n<h1>Store User</h1>\n<p>I assume <code>Dashboard</code> needs the user.</p>\n<p>I don't understand why user is a member of the form; it is not used anywhere.</p>\n<p>Create user after the query and pass it to <code>Dashboard</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-13T00:25:46.067", "Id": "242159", "ParentId": "242068", "Score": "2" } } ]
{ "AcceptedAnswerId": "242081", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-11T07:38:50.143", "Id": "242068", "Score": "2", "Tags": [ "c#", "wpf" ], "Title": "WPF login screen and share username and access id across other forms" }
242068
<p>My code: <a href="https://ideone.com/DZeIZv" rel="nofollow noreferrer">https://ideone.com/DZeIZv</a></p> <pre class="lang-cpp prettyprint-override"><code>#include &lt;atomic&gt; template &lt;class T&gt; class Seqlock { std::atomic&lt;int&gt; seq_; T val_; public: Seqlock(T value = T()) : val_(value) { } // concurrent calls are NOT allowed void store(T value) { const int seq0 = seq_.load(std::memory_order_relaxed); seq_.store(seq0 + 1, std::memory_order_relaxed); std::atomic_thread_fence(std::memory_order_release); val_ = value; std::atomic_thread_fence(std::memory_order_release); seq_.store(seq0 + 2, std::memory_order_relaxed); } // concurrent calls are allowed T load() const { for (;;) { const int seq0 = seq_.load(std::memory_order_relaxed); if (seq0 &amp; 1) { // cpu_relax() continue; } std::atomic_thread_fence(std::memory_order_acquire); T ret = val_; std::atomic_thread_fence(std::memory_order_acquire); const int seq1 = seq_.load(std::memory_order_relaxed); if (seq0 == seq1) { return ret; } } } }; </code></pre> <p>Is this <a href="https://en.wikipedia.org/wiki/Seqlock" rel="nofollow noreferrer">seqlock</a> implementation correct across all architectures, at least when T is an integral type? Can it be improved?</p> <p>References I was following:</p> <ul> <li><a href="https://elixir.bootlin.com/linux/latest/source/include/linux/seqlock.h" rel="nofollow noreferrer">https://elixir.bootlin.com/linux/latest/source/include/linux/seqlock.h</a></li> <li><a href="https://www.hpl.hp.com/techreports/2012/HPL-2012-68.pdf" rel="nofollow noreferrer">https://www.hpl.hp.com/techreports/2012/HPL-2012-68.pdf</a></li> <li><a href="https://github.com/rigtorp/Seqlock/" rel="nofollow noreferrer">https://github.com/rigtorp/Seqlock/</a></li> </ul>
[]
[ { "body": "<p>My guideline on memory orders is \"Just say no\"; I guarantee that if you're using them, you're using them wrong. :) So I won't attempt to find the exact bug, I'll just assume they all say <code>seq_cst</code>. The only thing I'll say about your memory orders is, when you write</p>\n\n<pre><code> seq_.store(seq0 + 1, std::memory_order_relaxed);\n std::atomic_thread_fence(std::memory_order_release);\n</code></pre>\n\n<p>can you explain how that's different from</p>\n\n<pre><code> seq_.store(seq0 + 1, std::memory_order_release);\n</code></pre>\n\n<p>?</p>\n\n<hr>\n\n<pre><code>Seqlock(T value = T())\n</code></pre>\n\n<p>This constructor should be <code>explicit</code>; otherwise you're accidentally permitting</p>\n\n<pre><code>Seqlock&lt;int&gt; s = 42;\n</code></pre>\n\n<p>and in fact because of C++17 CTAD you're also permitting</p>\n\n<pre><code>Seqlock s = 42;\n</code></pre>\n\n<p>Rule of thumb: make all constructors <code>explicit</code> except for those you want the compiler to be able to call implicitly (i.e., copy and move constructors).</p>\n\n<hr>\n\n<p>In <code>T load() const</code>, you load <code>seq1</code> at the bottom of the loop, and then go around again and immediately load <code>seq0</code> from the same location. You could just have set <code>seq0 = seq1</code>; i.e.</p>\n\n<pre><code>T load() const {\n int seq1 = seq_.load(std::memory_order_relaxed);\n while (true) {\n int seq0 = seq1;\n if (seq0 &amp; 1) {\n // cpu_relax();\n } else {\n std::atomic_thread_fence(std::memory_order_acquire);\n T ret = val_;\n std::atomic_thread_fence(std::memory_order_acquire);\n seq1 = seq_.load(std::memory_order_relaxed);\n if (seq0 == seq1) {\n return ret;\n }\n }\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-25T07:32:39.247", "Id": "476695", "Score": "0", "body": "Thanks for your reply. \"Just say no\" to barriers is a good approach, but sometimes we can't. In may case, I need to implement an alternative to 64-bit atomics on 32-bit platforms, and using seqlocks is a commonly used solution for this." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-25T07:33:13.333", "Id": "476696", "Score": "0", "body": "atomic_thread_fence() is different from passing MO to store() in the scope to which the MO applies: in the first case it applies to all stores and loads of all variables, and in the second case it's applied only to specific variable. This is what the spec says, but unfortunately I don't know the exact difference it the instructions produced by compiler." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-25T14:31:51.503", "Id": "476725", "Score": "0", "body": "FWIW, I didn't \"just say no\" to barriers (inter-thread synchronization) in general; just to using _memory orders_ to get there. Reasoning about `seq_cst` atomics is difficult but possible. It's when you start throwing in orders like `acquire` and `release` that it gets inhumanly confusing." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-25T14:36:04.763", "Id": "476729", "Score": "0", "body": "Re the difference between \"applies to all stores and loads of all variables\" and \"applied only to specific variable\" — yeah, that's what I meant. Can you explain the difference between these two in this situation? It seems like the only non-atomic variable involved is `val_`, which is overwritten right after the fence. Hm, since you don't want the hardware to hoist the store to `val_` _before_ the increment of `seq_`, it feels like maybe you want an `acquire` there, not a `release`. ...This is the confusing part that I recommend saying \"no\" to. Just `seq_cst`! It's the default for a reason." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-31T17:53:47.507", "Id": "477293", "Score": "0", "body": "`FWIW, I didn't \"just say no\" to barriers (inter-thread synchronization) in general; just to using memory orders to get there.` Thanks, this is indeed a good advice which I will follow in higher level code. However, using 2 or 3 full fences in such a low-level thing as seqlock (i.e. small in one hand and widely used on the other hand) clearly would be an overkill." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-31T17:58:38.783", "Id": "477294", "Score": "0", "body": "`Can you explain the difference between these two in this situation?` According to spec, specifying MO for seq would prevent reordering for that specific variable, but is not guaranteed to prevent reordering with other stores/loads. The difference is actually real (though I don't fully understand details), for example see https://gcc.gnu.org/bugzilla/show_bug.cgi?id=65697 (a long read...). In this particular case, we need to ensure that the last store to `seq_` wont be executed before store to `val_` is complete. Thus release barrier after store to val_ and before last store to seq_." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-31T18:02:31.577", "Id": "477295", "Score": "0", "body": "In my understanding, just using, for example, `seq_.store(seq0 + 2, std::memory_order_release)` here will say \"don't reorder this store with proceeding stores/loads to seq\", but we need \"don't reorder this store with ANY proceeding stores/loads\". Though my understanding may be incorrect. I'm quite new to this topic. Also, I guess that on some architectures these two will be equivalent. But not on all. E.g. on AArch64, if I understand correctly, just `STLR` is weaker than `DMB ISH` - https://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-31T18:10:53.303", "Id": "477296", "Score": "0", "body": "BTW, in my project I decided to provide sequential consistency in Seqlock, by converting *one* of the barriers in store and one in load to seq-cst. This way the code that builds things on top of seqlocks and other primitives becomes simpler, as you suggested." } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-11T15:34:05.770", "Id": "242085", "ParentId": "242070", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-11T07:59:48.747", "Id": "242070", "Score": "2", "Tags": [ "c++", "c++11", "locking", "lock-free", "atomic" ], "Title": "Is this C++11 seqlock implementation correct?" }
242070
<p>Find a bitwise XOR for a range for.e.g (5,8) --> 5 bitXOR 6 | 7 bitXOR 8 3 bitXOR 15 12</p> <p>Expected worst time Complexity - O(log(n))</p> <p>Expected worst space Complexity - O(1)</p> <p>I have written the below code, could you please help me to improve it?</p> <pre><code>static List&lt;Integer&gt; list; public static void main(String[] args) { int bitXORProduct = solution(5,8); System.out.println(bitXORProduct); } public static int solution(int M, int N) { if (isValidatedInput(M, N)) { int lastXOR = M; int currentXOR = 0; try { for (int i = M; i &lt; N; i++) { currentXOR = computeXOR(lastXOR, i + 1); lastXOR = currentXOR; } } catch (Exception e) { System.out.println("Error Found : -" + e); } return lastXOR; } System.out.println("Input is not in the range or valid"); return -1; } private static boolean isValidatedInput(int M, int N) { if (0 &lt;= M &amp;&amp; 0 &lt;= N &amp;&amp; M &lt;= Math.pow(10, 9) &amp;&amp; N &lt;= Math.pow(10, 9) &amp;&amp; M &lt;= N) { return true; } else return false; } private static Integer computeXOR(Integer m, Integer n) { return m ^ n; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-11T09:26:11.627", "Id": "475041", "Score": "0", "body": "[Cross-posted on Stack Overflow](https://stackoverflow.com/q/61724713/1014587)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-11T09:31:27.050", "Id": "475043", "Score": "0", "body": "I do not understand the example. How do I interpret the vertical bar (`|`)? How do `15 12` turn up? I *might* understand `5 ^ 6 ^ 7 ^ 8 = 3 ^ 15 = 12` - or the verbose *bitXOR*. How does the `Expected worst time Complexity - O(log(n))` come up?" } ]
[ { "body": "<p>First of all the solution you have given is complexity <code>O(n)</code>, not <code>O(log(n))</code>. It is possible to do it in <code>O(log(n))</code> by calculating the result bit by bit. For example, suppose I have a range of four consecutive integers. Then I know that two of those numbers are odd and two of those numbers are even. Since only odd numbers have the first bit set I already know that XOR-ing the four numbers will leave the first bit at <code>0</code>. For the second bit, I notice that for each set of four consecutive numbers there is always one number <code>2 mod 4</code> and one number <code>3 mod 4</code>. Since all integers which have the second bit set ar either <code>2</code> or <code>3</code> <code>mod 4</code>, I know that XOR-ing the set of four integers will leave the second bit at <code>0</code>. In this way I can determine for each bit if it should be set or not by looking at the properties of the numbers in the range. Usually this can be done in <code>O(1)</code> by only using the boundries of the range. Since there are log<sub>2</sub>(n) rounded up bits in n, this solution will have complexity <code>O(log(n))</code>.</p>\n\n<p>On to the code.</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>static List&lt;Integer&gt; list;\n</code></pre>\n\n<p>This list is not needed, it can be removed.</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>public static int solution(int M, int N)\n</code></pre>\n\n<p>The name of the method is <code>solution</code> but it doesn't describe what it is doing. Try to give it a name in accordance with it's function, something like <code>computeXorForRange</code> perhaps. Also, all other variables and methods in your code are camelCase so for consistency you should make <code>M</code> and <code>N</code> lower case. Or you can rename them to <code>lowerBound</code> and <code>upperBoundInclusive</code> if you like to tell the reader what they represent.</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>int lastXOR = M;\ncurrentXOR = 0;\ntry {\n for (int i = M; i &lt; N; i++) {\n currentXOR = computeXOR(lastXOR, i + 1);\n lastXOR = currentXOR;\n }\n} catch (Exception e) {\n System.out.println(\"Error Found : -\" + e);\n}\n</code></pre>\n\n<p>In this part it is not needed to have to different variables, <code>currentXOR</code> and <code>lastXOR</code>. One should be enough. Having the two variables here makes it more complex than it should be. Also, why are you catching exceptions here? What exceptions do you expect to happen? Since the code used in the try does not throw any exception except for the possible standard java runtime exceptions like for example <code>OutOfMemoryException</code>, it is not needed to have a try catch.</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>System.out.println(\"Input is not in the range or valid\");\nreturn -1;\n</code></pre>\n\n<p>This part is at the end of the method. Instead you can negate the if statement at the beginning of the method and put this piece in the if. Then it becomes more clear what happens if the conditions are not met. There is also a <code>return -1</code> which is more of a C style thing. In this case it is perfectly fine to use an Exception, the <code>IllegalArgumentException</code> will fit since the arguments passed are not valid (they are too small or too large).</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>private static boolean isValidatedInput(int M, int N) {\n if (0 &lt;= M &amp;&amp; 0 &lt;= N &amp;&amp; M &lt;= Math.pow(10, 9) &amp;&amp; N &lt;= Math.pow(10, 9) &amp;&amp; M &lt;= N) {\n return true;\n } else\n return false;\n}\n</code></pre>\n\n<p>The name of the method can be changed to <code>isValidInput</code>. The name <code>isValidatedInput</code> suggests that there will be a check if the input is already validated while it seems you are validating the input. There us also no reason to have the <code>return true</code> and <code>return false</code>, you can immediatly return the condition used in the if. Because if that condition is true the method will then return true and if the condition is false the method will then return false. Lastly, the upper bound of 10^9 seems arbitrary. If you want to prevent overflows and underflows you can use <code>Integer.MAX_VALUE</code> as upper bound.</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>private static Integer computeXOR(Integer m, Integer n) {\n return m ^ n;\n}\n</code></pre>\n\n<p>In the rest of the code you use <code>int</code> yet here you use <code>Integers</code>. Using <code>Integer</code> is not necessary in this case since you don't have to deal with null values so using <code>int</code> would be consistent with the rest of the code. You can also ask if this method is really needed. IMO something like <code>x ^ y</code> is perfectly fine and clear and you don't need a separate method for that, but if it helps you, you can leave it in.</p>\n\n<p>All in all with the above suggestions the code will become</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>public static void main(String[] args) {\n int bitXORProduct = solution(5,8);\n System.out.println(bitXORProduct);\n}\n\npublic static int solution(int lowerBound, int upperBoundInclusive) {\n if (!isValidInput(lowerBound, upperBoundInclusive)) {\n throw new IllegalArgumentException(\"Input is not in the range or valid\");\n }\n\n int currentXOR = lowerBound;\n for (int i = lowerBound; i &lt; upperBoundInclusive; i++) {\n currentXOR = currentXOR ^ (i + 1); // this can also be written as currentXOR ^= i + 1;\n }\n\n return currentXOR;\n}\n\nprivate static boolean isValidInput(int M, int N) {\n return 0 &lt;= M\n &amp;&amp; 0 &lt;= N\n &amp;&amp; M &lt;= Math.pow(10, 9)\n &amp;&amp; N &lt;= Math.pow(10, 9)\n &amp;&amp; M &lt;= N;\n}\n<span class=\"math-container\">```</span>\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-11T10:35:23.370", "Id": "242076", "ParentId": "242072", "Score": "0" } } ]
{ "AcceptedAnswerId": "242076", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-11T09:18:06.250", "Id": "242072", "Score": "0", "Tags": [ "java" ], "Title": "Coding - Find a bitwise XOR for a range of numbers in java" }
242072
<p><strong>Introduction</strong></p> <p>I've created a typed Promise implementation in Java for Android, borrowing ideas from <a href="https://www.promisejs.org/implementing/" rel="nofollow noreferrer">this article</a> for a JavaScript implementation, by Forbes Lindesay.</p> <p>To allow for "asynchronicity", my implementation posts callbacks (<code>Promise.Callback</code>) to the message queue of main thread (<code>Looper.getMainLooper()</code>). I don't know the appropriate terminology, but in this case by asynchronicity I mean the following:</p> <pre class="lang-java prettyprint-override"><code>new Promise&lt;&gt;(new Promise.Executor&lt;Integer&gt;() { @Override public void execute(Promise.Action&lt;Integer&gt; action) { // just simple synchronous code: System.out.println("This is executed first."); action.resolve(1); } }) .andThen(new Promise.Callback&lt;Integer, Void&gt;() { @Override public Promise.Result&lt;Void&gt; execute(Integer value) { System.out.println("This is executed third. Got: " + value); return null; } }); System.out.println("This is executed second."); </code></pre> <p>In other words: the executor (constructor argument) is executed first, but the callback passed to the <code>Promise&lt;T&gt;.andThen()</code> method is only executed <em>after</em> the main code block (with <code>System.out.println("This is executed second.");</code>) has finished, even though the code in the executor is synchronous. I believe this to be in line with how JavaScript promises behave.</p> <p>To provide for this asynchronicity, callbacks are posted on the message queue of main thread (simply with a delay of <code>0 milliseconds</code> and utilizing <code>Looper.getMainLooper()</code>), hence it currently only runs on Android. </p> <p>I also thought about posting callbacks to any possibly other currently executing thread, but those are not guaranteed to have a <code>Looper</code> nor guaranteed to still be alive and I didn't want to make it too complicated, nor did I want to have to create <code>Thread</code>s myself, since I understand those to be expensive. I wanted to keep it snappy.</p> <p><strong>Here are the concerns I'd like to see addressed:</strong></p> <ol> <li>I claim my implementation is thread-safe, but I'm not entirely sure whether I should be using the <code>volatile</code> keyword for certain properties. In particular the private <code>Promise.state</code>. Do you see any other thread-safety issues?</li> <li>Do you see any issues that could arise from posting the callbacks on the main thread? I believe the actual bodies of callbacks posted on another thread will still be executed in that other thread's context, even though I post them to the main thread, but I'm not entirely sure (of possible edge cases).</li> </ol> <p><strong>Code</strong></p> <p><a href="https://github.com/Codifier/Android.Promise/blob/master/promise/src/main/java/nl/codifier/android/promise/Promise.java" rel="nofollow noreferrer">On Github</a></p> <pre class="lang-java prettyprint-override"><code>package nl.codifier.android.promise; import android.os.Handler; import android.os.Looper; import androidx.annotation.NonNull; import java.util.ArrayList; import java.util.List; /** * This is the {@code Promise} class. * * @param &lt;T&gt; The type with which the {@code Promise} will be fulfilled */ @SuppressWarnings({"WeakerAccess", "UnusedReturnValue", "unused"}) public class Promise&lt;T&gt; { /** * The object that is passed to the {@link Promise.Executor} function. This object provides the * methods to resolve its associated {@code Promise} with. * * &lt;p&gt;Since a {@code Promise} must be allowed to resolve to either a value of type {@code R} * or a new {@code Promise} of type {@code R}, this object contains three overloaded * implementations of {@code Promise.Action.resolve()}:&lt;/p&gt; * * &lt;ul&gt; * &lt;li&gt;{@link Promise.Action#resolve(Object)}&lt;/li&gt; * &lt;li&gt;{@link Promise.Action#resolve(Promise)}&lt;/li&gt; * &lt;li&gt;{@link Promise.Action#resolve(Promise.Result)}&lt;/li&gt; * &lt;/ul&gt; * * &lt;p&gt;The last one is a convenience method to allow for {@link Promise.Result} as well&lt;/p&gt; * * @param &lt;T&gt; The type with which the associated {@code Promise} will be fulfilled * @see Promise#Promise(Executor) * @see Promise.Result */ public final static class Action&lt;T&gt; { private final Promise&lt;T&gt; promise; /** * Constructs a {@code Promise.Action} with a {@code Promise} of type {@code T}. * * @param promise the {@code Promise} of type {@code T} that this {@code Promise.Action} is associated with */ private Action(final Promise&lt;T&gt; promise) { this.promise = promise; } /** * Resolves the associated {@code Promise} with {@code T value}. * * @param value a value of type {@code T} */ public void resolve(final T value) { promise.resolveInternal(new Result&lt;&gt;(value)); } /** * Resolves the associated {@code Promise} with another {@code Promise&lt;T&gt;}. * * @param value a {@code Promise} of type {@code T} */ @SuppressWarnings("ConstantConditions") public void resolve(@NonNull final Promise&lt;T&gt; value) { if(value == null) { throw new NullPointerException("Argument 'Promise&lt;T&gt; value' must not be null."); } promise.resolveInternal(new Result&lt;&gt;(value)); } /** * Resolves the associated {@code Promise} with the value wrapped inside {@link Promise.Result} * * @param value a {@code Promise.Result} of type {@code T} * @see Promise.Result */ public void resolve(final Result&lt;T&gt; value) { promise.resolveInternal(value); } /** * Rejects the associated {@code Promise} with a {@code Throwable} * * @param value a {@code Throwable} */ public void reject(final Throwable value) { promise.rejectInternal(value); } } /** * A wrapper object that {@link Promise.Callback} can optionally return to allow returning * either a value of type {@code R} or a {@code Promise} of type {@code R}. * * &lt;p&gt;A {@code Promise.Callback} must be allowed to return either a value of type {@code R} * or a new {@code Promise} of type {@code R}. However, since Java does not allow * return types to be this ambiguous (without the need for casting), {@code Promise.Callback} * must wrap the return value in this {@code Promise.Result} (unless it does not want to return * anything, in which case {@code null} must be returned).&lt;/p&gt; * * @param &lt;R&gt; The type with which the earlier returned {@code Promise} will be fulfilled * @see Promise.Callback */ public final static class Result&lt;R&gt; { /** * The possible wrapped result types of {@code Promise.Result}. */ private enum Type { VALUE, PROMISE } /** * The wrapped result type of this {@code Promise.Result}. */ private final Type type; /** * The value of type {@code R} with which this {@code Promise.Result} might be constructed. */ private R value; /** * The {@code Promise} of type {@code R} with which this {@code Promise.Result} might be constructed. */ private Promise&lt;R&gt; promise; /** * Constructs a {@code Promise.Result} with a value of type {@code R}. * * @param value the value of type {@code R} this {@code Promise.Result} wraps */ public Result(final R value) { this.value = value; this.type = Type.VALUE; } /** * Constructs a {@code Promise.Result} with a {@code Promise} of type {@code R}. * * @param promise the {@code Promise} of type {@code R} this {@code Promise.Result} wraps */ @SuppressWarnings("ConstantConditions") public Result(@NonNull final Promise&lt;R&gt; promise) { if(promise == null) { throw new NullPointerException("Constructor argument 'Promise&lt;R&gt; promise' must not be null."); } this.promise = promise; this.type = Type.PROMISE; } /** * Getter to determine the type of the wrapped object. * * @return the {@code Promise.Result.Type} */ private Type getType() { return type; } /** * Getter to retrieve the wrapped value. * * @return the value of type {@code R} */ private R getValue() { return value; } /** * Getter to retrieve the wrapped {@code Promise}. * * @return the {@code Promise} of type {@code R} */ private Promise&lt;R&gt; getPromise() { return promise; } } /** * The executor function that is passed to the {@link Promise#Promise(Executor)} constructor. * * @param &lt;T&gt; The type with which the {@code Promise} will be fulfilled * @see Promise#Promise(Executor) * @see Promise.Action */ public interface Executor&lt;T&gt; { void execute(Action&lt;T&gt; action); } /** * The callback function that is passed to callback methods of {@code Promise}. * * &lt;p&gt;A {@code Promise.Callback} must be allowed to return either a value of type {@code R} * or a new {@code Promise} of type {@code R}. However, since Java does not allow * return types to be this ambiguous (without the need for casting), {@code Promise.Callback} * must wrap the return value in a {@code Promise.Result} (unless it does not want to return * anything, in which case {@code null} must be returned).&lt;/p&gt; * * @param &lt;T&gt; The type with which the current {@code Promise} will be fulfilled * @param &lt;R&gt; The return type with which the earlier returned {@code Promise} will be fulfilled * @see Promise#andThen(Callback, Callback) * @see Promise#andThen(Callback) * @see Promise#andCatch(Callback) * @see Promise#andFinally(Callback) */ public interface Callback&lt;T, R&gt; { Result&lt;R&gt; execute(T value); } /** * A container object that holds the {@link Promise.Callback} functions for asynchronous * processing, after the {@code Promise} has been fulfilled. * * @param &lt;T&gt; The type with which the current {@code Promise} will be fulfilled * @param &lt;R&gt; The return type with which the returned {@code Promise} will be fulfilled * @see Promise#addCallbacks(Callback, Callback) * @see Promise#andThen(Callback, Callback) * @see Promise#andThen(Callback) * @see Promise#andCatch(Callback) * @see Promise#andFinally(Callback) */ private final static class CallbackContainer&lt;T, R&gt; { private final Callback&lt;T, R&gt; onFulfilled; private final Callback&lt;Throwable, R&gt; onRejected; public CallbackContainer(final Callback&lt;T, R&gt; onFulfilled, final Callback&lt;Throwable, R&gt; onRejected) { this.onFulfilled = onFulfilled; this.onRejected = onRejected; } } /** * The possible states of a {@code Promise}. */ private enum State { PENDING, FULFILLED, REJECTED } /** * The list of {@link Promise.CallbackContainer} objects that are held while the {@code Promise} * is still in a {@link Promise.State#PENDING} state. */ private final List&lt;CallbackContainer&lt;T, ?&gt;&gt; callbackContainers = new ArrayList&lt;&gt;(); /** * The {@link Promise.Action} that is associated with this {@code Promise}. */ private final Action&lt;T&gt; action = new Action&lt;&gt;(this); /** * The {@link Promise.Executor} that was passed to this {@code Promise}. */ private final Executor&lt;T&gt; executor; /** * Holds the current {@link State} of this {@code Promise}. */ private State state = State.PENDING; /** * The {@link Handler} uses to add callbacks asynchronously. * * @see Promise#getHandler() * @see Promise#addCallbacks(Callback, Callback) */ private Handler handler; /** * The value of type {@code T} with which this Promise might be fulfilled. */ private T value; /** * The {@code Throwable} with which this Promise might be rejected. */ private Throwable error; /** * Returns a {@code Promise&lt;T&gt;} that is fulfilled with {@code T value}. * * @param value the value of type {@code T} with which the returned {@code Promise} will be fulfilled * @param &lt;T&gt; the type of the returned {@code Promise} * @return the {@code Promise&lt;T&gt;} */ public static &lt;T&gt; Promise&lt;T&gt; resolve(final T value) { return new Promise&lt;&gt;(new Executor&lt;T&gt;() { @Override public void execute(final Action&lt;T&gt; action) { action.resolve(value); } }); } /** * Identity function that returns the {@code Promise&lt;T&gt;} argument. * * @param value the {@code Promise} of type {@code T} which will be returned * @param &lt;T&gt; the type of the returned {@code Promise} * @return the {@code Promise&lt;T&gt;} */ public static &lt;T&gt; Promise&lt;T&gt; resolve(final Promise&lt;T&gt; value) { return value; } /** * Returns a {@code Promise&lt;T&gt;} that is rejected with {@code Throwable value}. * * @param value the {@code Throwable} with which the returned {@code Promise} will be rejected * @param &lt;T&gt; the type of the returned {@code Promise} * @return the {@code Promise&lt;T&gt;} */ public static &lt;T&gt; Promise&lt;T&gt; reject(final Throwable value) { return new Promise&lt;&gt;(new Executor&lt;T&gt;() { @Override public void execute(final Action&lt;T&gt; action) { action.reject(value); } }); } /** * Constructs a {@code Promise} with the {@link Promise.Executor} function it should execute. * * @param executor the {@link Promise.Executor} function this {@code Promise} should execute */ @SuppressWarnings("ConstantConditions") public Promise(@NonNull Executor&lt;T&gt; executor) { if(executor == null) { throw new NullPointerException("Constructor argument 'Executor&lt;T&gt; executor' must not be null."); } this.executor = executor; execute(); } /** * The callback method for adding {@link Promise.Callback}s that will be called when this * {@code Promise} is resolved. * * @param onFulfilled the {@link Promise.Callback} to execute when this {@code Promise} is fulfilled * @param onRejected the {@link Promise.Callback} to execute when this {@code Promise} is rejected * @param &lt;R&gt; the return type of the {@link Promise.Callback} arguments and the type of the {@code Promise} that is returned by this method * @return a new {@code Promise} that will eventually be resolved */ public &lt;R&gt; Promise&lt;R&gt; andThen(final Callback&lt;T, R&gt; onFulfilled, final Callback&lt;Throwable, R&gt; onRejected) { return new Promise&lt;&gt;(new Executor&lt;R&gt;() { @Override public void execute(final Action&lt;R&gt; action) { addCallbacks( new Callback&lt;T, R&gt;() { @Override public Result&lt;R&gt; execute(final T value) { if(onFulfilled != null) { try { action.resolve(onFulfilled.execute(value)); } catch(Throwable e) { action.reject(e); } } else { action.resolve((R) null); } return null; } }, new Callback&lt;Throwable, R&gt;() { @Override public Result&lt;R&gt; execute(final Throwable value) { if(onRejected != null) { try { action.resolve(onRejected.execute(value)); } catch(Throwable e) { action.reject(e); } } else { action.reject(value); } return null; } } ); } }); } /** * The callback method for adding a {@link Promise.Callback} that will be called when this * {@code Promise} is fulfilled. * * @param onFulfilled the {@link Promise.Callback} to execute when this {@code Promise} is fulfilled * @param &lt;R&gt; the return type of the {@link Promise.Callback} argument and the type of the {@code Promise} that is returned by this method * @return a new {@code Promise} that will eventually be resolved */ public &lt;R&gt; Promise&lt;R&gt; andThen(final Callback&lt;T, R&gt; onFulfilled) { return andThen(onFulfilled, null); } /** * The callback method for adding a {@link Promise.Callback} that will be called when this * {@code Promise} is rejected. * * @param onRejected the {@link Promise.Callback} to execute when this {@code Promise} is rejected * @param &lt;R&gt; the return type of the {@link Promise.Callback} argument and the type of the {@code Promise} that is returned by this method * @return a new {@code Promise} that will eventually be resolved */ public &lt;R&gt; Promise&lt;R&gt; andCatch(final Callback&lt;Throwable, R&gt; onRejected) { return andThen(null, onRejected); } /** * The callback method for adding a {@link Promise.Callback} that will &lt;em&gt;always&lt;/em&gt; be called when this * {@code Promise} is resolved (as either fulfilled or rejected). * * @param onFinally the {@link Promise.Callback} to execute when this {@code Promise} is resolved * @param &lt;R&gt; the return type of the {@link Promise.Callback} argument and the type of the {@code Promise} that is returned by this method * @return a new {@code Promise} that will eventually be resolved */ public &lt;R&gt; Promise&lt;R&gt; andFinally(final Callback&lt;Void, R&gt; onFinally) { Callback&lt;T, R&gt; onResolvedFinallyWrapper = new Callback&lt;T, R&gt;() { @Override public Result&lt;R&gt; execute(final Object value) { return onFinally.execute(null); } }; Callback&lt;Throwable, R&gt; onRejectedFinallyWrapper = new Callback&lt;Throwable, R&gt;() { @Override public Result&lt;R&gt; execute(final Throwable value) { return onFinally.execute(null); } }; return andThen(onResolvedFinallyWrapper, onRejectedFinallyWrapper); } /** * Execute the {@link Promise#executor} function, by passing it {@link Promise#action} and * possibly rejecting this {@code Promise} with any {@code Throwable} it throws. */ private void execute() { try { executor.execute(action); } catch(Throwable e) { rejectInternal(e); } } /** * Fulfills this {@code Promise} with the value of type {@code T}, &lt;em&gt;unless&lt;/em&gt; this {@code Promise} * was already previously resolved. * * @param fulfillValue the final value with which this {@code Promise} should be fulfilled */ private void fulfillInternal(final T fulfillValue) { synchronized(callbackContainers) { if(state == State.PENDING) { state = State.FULFILLED; value = fulfillValue; handleCallbacks(); callbackContainers.clear(); } } } /** * Rejects this {@code Promise} with a {@code Throwable}, &lt;em&gt;unless&lt;/em&gt; this {@code Promise} * was already previously resolved. * * @param rejectValue the {@code Throwable} with which this {@code Promise} should be rejected * @see Promise.Action#reject(Throwable) */ private void rejectInternal(final Throwable rejectValue) { synchronized(callbackContainers) { if(state == State.PENDING) { state = State.REJECTED; error = rejectValue; handleCallbacks(); callbackContainers.clear(); } } } /** * Resolves this {@code Promise} with a {@link Promise.Result}, &lt;em&gt;unless&lt;/em&gt; this {@code Promise} * was already previously resolved. * * @param result the {@code Promise.Result} with which this {@code Promise} should be resolved * @see Promise.Action#resolve(T) * @see Promise.Action#resolve(Result) * @see Promise.Action#resolve(Promise) * @see Promise#fulfillInternal(T) */ private void resolveInternal(final Result&lt;T&gt; result) { if(result == null) { fulfillInternal(null); } else if(result.getType() == Result.Type.VALUE) { fulfillInternal(result.getValue()); } else { result.getPromise().andThen( new Callback&lt;T, T&gt;() { @Override public Result&lt;T&gt; execute(final T value) { action.resolve(new Result&lt;&gt;(value)); return null; } }, new Callback&lt;Throwable, T&gt;() { @Override public Result&lt;T&gt; execute(final Throwable value) { action.reject(value); return null; } } ); } } /** * The {@link Handler} used by {@link Promise#addCallbacks} to add them at the * back of the message queue of {@link Looper#getMainLooper}, so they will be * processed asynchronously. * * @return Handler * @see Promise#addCallbacks(Callback, Callback) */ private Handler getHandler() { if(handler == null) { handler = new Handler(Looper.getMainLooper()); } return handler; } /** * Process a single {@link Promise.CallbackContainer}, either by adding them * to the {@link Promise#callbackContainers} list if this {@code Promise} is still * {@link Promise.State#PENDING} or executing one of its {@link Promise.Callback}s * immediately, depending on the resolved {@link Promise#state}. * * @param callbackContainer the {@link Promise.CallbackContainer} that needs processing * @param &lt;R&gt; the return type with which the earlier returned {@code Promise} will be fulfilled */ private &lt;R&gt; void handleCallbacks(final CallbackContainer&lt;T, R&gt; callbackContainer) { synchronized(callbackContainers) { if(state == State.PENDING) { callbackContainers.add(callbackContainer); } else if(state == State.FULFILLED &amp;&amp; callbackContainer.onFulfilled != null) { callbackContainer.onFulfilled.execute(value); } else if(state == State.REJECTED &amp;&amp; callbackContainer.onRejected != null) { callbackContainer.onRejected.execute(error); } } } /** * Process all pending {@link Promise.CallbackContainer}s. * * @see Promise#fulfillInternal(T) * @see Promise#rejectInternal(Throwable) * @see Promise#handleCallbacks(CallbackContainer) */ private void handleCallbacks() { synchronized(callbackContainers) { for(CallbackContainer&lt;T, ?&gt; callbackContainer : callbackContainers) { handleCallbacks(callbackContainer); } } } /** * Adds a {@link Promise.CallbackContainer} to {@link Promise#callbackContainers} asynchronously, * by posting it to back of the message queue of {@link Handler}. * * @param onFulfilled the {@link Promise.Callback} to execute when this {@code Promise} is fulfilled * @param onRejected the {@link Promise.Callback} to execute when this {@code Promise} is rejected * @param &lt;R&gt; the return types of the {@link Promise.Callback} arguments and the earlier returned {@code Promise} * @see Promise#andThen(Callback, Callback) * @see Promise#andThen(Callback) * @see Promise#andCatch(Callback) * @see Promise#andFinally(Callback) */ private &lt;R&gt; void addCallbacks(final Callback&lt;T, R&gt; onFulfilled, final Callback&lt;Throwable, R&gt; onRejected) { final CallbackContainer&lt;T, R&gt; callbackContainer = new CallbackContainer&lt;&gt;(onFulfilled, onRejected); // force async execution getHandler().postDelayed(new Runnable() { @Override public void run() { handleCallbacks(callbackContainer); } }, 0); } } </code></pre> <p><strong>Example usage</strong></p> <pre class="lang-java prettyprint-override"><code>new Promise&lt;&gt;(new Promise.Executor&lt;Integer&gt;() { @Override // make action final for accessibility inside Runnable public void execute(final Promise.Action&lt;Integer&gt; action) { // simulate some fictional asynchronous routine new Thread(new Runnable() { @Override public void run() { try { // sleep for 5 seconds Thread.sleep(5000); // resolve with integer 1 action.resolve(1); } catch(Throwable e) { // or reject with some caught Throwable action.reject(e); } } }).start(); } }) // accepts the Integer result and returns a new Promise&lt;Boolean&gt; .andThen(new Promise.Callback&lt;Integer, Boolean&gt;() { @Override public Promise.Result&lt;Boolean&gt; execute(Integer value) { System.out.println("This is executed when the previous promise is fulfilled. Got: " + value); // Boolean must be wrapped in a Promise.Result&lt;Boolean&gt;, because Promise.Callback&lt;..., Boolean&gt; // must be allowed to return another Promise&lt;Boolean&gt; as well return new Promise.Result&lt;&gt;(false); } }) // accepts the Boolean result and returns a new Promise&lt;Void&gt; .andThen(new Promise.Callback&lt;Boolean, Void&gt;() { @Override public Promise.Result&lt;Void&gt; execute(Boolean value) { System.out.println("This is executed when the previous promise is fulfilled. Got: " + value); return null; } }) // catches any uncaught Throwable up the chain and returns a new Promise&lt;Void&gt; .andCatch(new Promise.Callback&lt;Throwable, Void&gt;() { @Override public Promise.Result&lt;Void&gt; execute(Throwable value) { System.out.println("This is executed when a promise up the chain is rejected."); return null; } }) // will always be called, regardless of the settled state of promises up the chain // and returns a new Promise&lt;Void&gt; .andFinally(new Promise.Callback&lt;Void, Void&gt;() { @Override public Promise.Result&lt;Void&gt; execute(Void value) { System.out.println("This will always be executed."); return null; } }); </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-12T12:05:48.063", "Id": "475146", "Score": "1", "body": "Not an answer to your question, but have you looked at the class `java.util.concurrent.CompletableFuture`? What you do there looks very much like `CompletableFuture.supplyAsync(...).thenAcceptAsync(...)` to me. (Thus re-inventing the wheel.)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-12T15:31:47.670", "Id": "475176", "Score": "0", "body": "Hi @mtj. Yes, I was aware of that class. However, I find it too bloated for my current needs. And, more importantly, it is only available from Android API 24 onward, while I'm still coding for Android API 19. Cheers, though." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-12T15:52:06.853", "Id": "475184", "Score": "0", "body": "This question is of course fine for CodeReview, but generally I'd rather copy a \"bloated\" but well tested implementation than reinventing my own, especially when it comes to thread-safety. Note to other readers: relies on Android specific classes and annotations!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-12T16:29:58.317", "Id": "475195", "Score": "0", "body": "@MaartenBodewes Fair enough, perhaps I should have explicitly stated in the question that it's meant for Android API 19 onward, so `CompletableFuture` is not available. About your note though: I mean, it's clearly stated in the title, the introduction *and* implied in the tags already that this implementation is meant for Android." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-12T17:02:55.003", "Id": "475200", "Score": "0", "body": "Yeah, I know, but just to get started quickly I tried compiling in my Java environment, which of course did not work. Usually I can get it to work pretty easily - since it is a rather generic component - but without the `Handler` code it's just not that easy." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-12T18:49:15.083", "Id": "475217", "Score": "0", "body": "@MaartenBodewes Ah, I see. Yes, unfortunately, you need `Handler` and `Looper`, indeed. I haven't found a plain Java alternative for this (but haven't searched extensively, to be honest) and didn't want to open the can of worms of having to implement my own `Looper` mechanism, nor did I want my `Promise` to have to create its own `Thread`s, as long as I could prevent it. Ultimately though, the conclusion may very well be that this *will* actually be needed. For now though, it appears to do the job as I intended, but I'm curious what the community has to say." } ]
[ { "body": "<p>I'm not familiar with <code>Promise</code> from <em>JavaScript</em> and this is quite a complex flow, so hopefully I didn't miss much.</p>\n\n<h3>Let's just review the flow a bit</h3>\n\n<pre><code>new Promise&lt;&gt;(new Promise.Executor&lt;Integer&gt;() {\n @Override\n public void execute(Promise.Action&lt;Integer&gt; action) {\n // Perhaps do something asynchronous and then:\n action.resolve(1);\n }\n})\n</code></pre>\n\n<p>In this case, the entire execution is done within you constructor, under <code>execute()</code>. There is access to some properties in the class, however it is done in a single thread. So no problems so far.</p>\n\n<pre><code>.andThen(new Promise.Callback&lt;Integer, Boolean&gt;() {\n @Override\n public Promise.Result&lt;Boolean&gt; execute(Integer value) {\n return new Promise.Result&lt;&gt;(false);\n }\n})\n</code></pre>\n\n<p>Now things start to complicate a bit. <code>andThen</code> creates a new <code>Promise</code> which adds this callback to the <em>original</em> <code>Promise</code>. The callback it self, is transferred to an <code>Handler</code>, and executed using <code>postDelayed</code>.</p>\n\n<p>We know for certain that the first execution of the original <code>Promise</code> was done, since it is in the constructor. So there is no race with it. We also know that the callback doesn't access any of the properties in our <code>Promise</code>. So far it looks safe. Let's take a look at the execution of the callbacks:</p>\n\n<pre><code> private &lt;R&gt; void handleCallbacks(final CallbackContainer&lt;T, R&gt; callbackContainer) {\n synchronized(callbackContainers) {\n if(state == State.PENDING) {\n callbackContainers.add(callbackContainer);\n }\n else if(state == State.FULFILLED &amp;&amp; callbackContainer.onFulfilled != null) {\n callbackContainer.onFulfilled.execute(value);\n }\n else if(state == State.REJECTED &amp;&amp; callbackContainer.onRejected != null) {\n callbackContainer.onRejected.execute(error);\n }\n }\n }\n</code></pre>\n\n<p>The first thing done in this method is entering a <code>synchronized</code> block, so any modifications to our states are going to be safe. This includes modifications to <code>state</code> and <code>callbackContainers</code>.</p>\n\n<p>Let's say we have 2 callbacks. One by one, the call is done to <code>Handler.postDelayed</code>, with execution of those callbacks. We know they are added to <code>postDelayed</code> in order, so they should be executed in order (I'm not sure 100% that <code>postDelayed</code> guarantees that`. </p>\n\n<p>Let's dive in a little. Say <code>callbackContainer.onFulfilled.execute(value);</code> is called, This will invoke this code section:</p>\n\n<pre><code>new Promise.Callback&lt;T, R&gt;() {\n @Override\n public Promise.Result&lt;R&gt; execute(final T value) {\n if(onFulfilled != null) {\n try {\n action.resolve(onFulfilled.execute(value));\n }\n catch(Throwable e) {\n action.reject(e);\n }\n }\n else {\n action.resolve((R) null);\n }\n\n return null;\n }\n }\n</code></pre>\n\n<p>Let's say a value is returned from <code>onFulfilled</code>, and <code>action.resolve(onFulfilled.execute(value));</code> is called. This calls <code>resolveInternal</code>, and called lead to a call to <code>fulfillInternal</code>.</p>\n\n<pre><code> private void fulfillInternal(final T fulfillValue) {\n synchronized(callbackContainers) {\n if(state == State.PENDING) {\n state = State.FULFILLED;\n value = fulfillValue;\n handleCallbacks();\n callbackContainers.clear();\n }\n }\n }\n</code></pre>\n\n<p>Luckily <code>state</code> is fulfilled already, so this won't be executed. What if it isn't? The modification of values is done in a <code>synchronized</code> block, so it is safe. How about <code>handleCallbacks</code>? Well it will run all callbacks inside <code>callbackContainer</code>, and because the callback use the same lock, and are only added to the container from <code>postDelayed</code> under that lock, it shouldn't be a problem.</p>\n\n<p>Although the code is complex, and I have talked here a lot, it is actually quite solid. The limitations on <code>state</code> are well placed, the use of the lock is done where needed, and the callbacks are executed well. I could try to dig further, but I have to go.</p>\n\n<p>So well done!</p>\n\n<p>A couple of other things: </p>\n\n<ul>\n<li>Wayyy to much code in one file. All the inner types and the javadoc make it difficult to navigate. You should extract the inner classes.</li>\n<li>I can't really find much way that it after <code>execute</code> in the constructor, the value won't be <code>PENDING</code>. To do this, I have to run an async operation from inside the <code>Executor</code>, and modify the action there. Which is weird. Maybe I'm missing something?</li>\n<li>Exposing <code>Action</code> to users is quite dangerous, since it is a state of the class, and they can really abuse it.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-15T13:49:50.217", "Id": "475579", "Score": "0", "body": "Thank you very much for your review! It appears your conclusions about the `synchronized` parts coincide with my own, so that's reassuring. I'll address your three end remarks in separate comments. About your first: I definitely see where you are coming from, but for some reason, because all classes are so closely linked to the `Promise` and without much use outside of it, I actually like them as inner classes. But perhaps that's a bit silly and I should reevaluate this." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-15T13:51:16.780", "Id": "475582", "Score": "0", "body": "About your second: Indeed, the whole point of a `Promise` is to do something asynchronous in the `Executor`, during which the `Promise` remains `PENDING`, and after which you either `resolve()` or `reject()`. For brevity I haven't given a concrete example of this, but could surely add an asynchronous example, if necessary. Furthermore, another thing about `Promise`s is, is that even after a `Promise` is settled (as either fulfilled or rejected) and thus not `PENDING` anymore, one must still be able to add callbacks to them, that will then still be executed, depending on the settled state." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-15T13:53:34.473", "Id": "475583", "Score": "0", "body": "Finally, about your third: In JavaScript `Promise`s the `resolve()` and `reject()` functions are passed as arguments to the executor, but I didn't see a neat way to do this for a typed `Promise` in Java, particularly because I need overloaded versions of `resolve()`, to allow for either a concrete value of the projected type, or another `Promise` that resolves to that type, so I pass an `Action` object. Furthermore, the `Action` class is final and has a private constructor, so I don't see any immediate vectors of abuse. Or am I missing something?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-15T22:12:11.620", "Id": "475618", "Score": "0", "body": "I took a look at the flow of using `Action` in a delay, and again it seems the `synchronized` blocks are keeping the flows proper. My comment about exposing `Action` is more of a general safety tip. In your case exposing `Action` doesn't seem to be a danger. I will say that abusing is always possible, through reflection for instance, but stopping that is a different story." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-15T23:00:58.163", "Id": "475620", "Score": "0", "body": "Yeah, exactly: with reflection all bets are off. :-) Anyway, thanks again for looking into this." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-15T12:58:16.557", "Id": "242338", "ParentId": "242073", "Score": "3" } } ]
{ "AcceptedAnswerId": "242338", "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-11T09:49:22.053", "Id": "242073", "Score": "3", "Tags": [ "java", "android", "asynchronous", "thread-safety", "promise" ], "Title": "A thread-safe typed Promise implementation in Java for Android" }
242073
<p>Here's a dynamic loopable string array that doesn't require a count to be maintained at the caller level.</p> <p><strong>Definition</strong></p> <pre><code>char **getList() { char **items = (char *[]) {"John", "Jane", NULL}; // dynamic/variable hard coded list int size = 0; for (char **ptr = items; *ptr; ptr++) { // count items size++; } char **data = malloc(sizeof(char *) * (size + 1)); if (data == NULL) goto err; for (int i = 0; *items; items++, i++) { // copy data[i] = malloc(sizeof(char) * strlen(*items) + 1); if (data[i] == NULL) goto err; strcpy(data[i], *items); } data[size] = NULL; // last item return data; err: fprintf(stderr, "Allocation failed.\n"); return NULL; } </code></pre> <p><strong>Caller</strong></p> <pre><code>char **data = getList(); for (char **ptr = data; *ptr; ptr++) { puts(*ptr); } free(data); </code></pre> <p>Please review if this code can be improved upon for any redundancy or optimizations.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-11T15:02:10.950", "Id": "475084", "Score": "0", "body": "Have you tried running some static analyzers/valgrind? Those should find a few little mistakes and hopefully in the process you'll learn how to catch that type of problem yourself." } ]
[ { "body": "<blockquote>\n <p>review if this code can be improved upon for any redundancy or optimizations.</p>\n</blockquote>\n\n<p><strong>Micro optimization</strong></p>\n\n<p>String duplication does not take advantage of the pre-calculation of the length.</p>\n\n<pre><code> data[i] = malloc(sizeof(char) * strlen(*items) + 1);\n if (data[i] == NULL) goto err;\n strcpy(data[i], *items);\n</code></pre>\n\n<p>For longer strings, code may (or may not) improve with the below. This <em>tended</em> to improve things. Less so today (usually a tie) unless in embedded platforms.</p>\n\n<pre><code> size_t sz = strlen(*items) + 1;\n data[i] = malloc(sz); // dealing with `char` strings, no need for sizeof(char)\n if (data[i] == NULL) goto err;\n memcpy(data[i], *items, sz);\n</code></pre>\n\n<p>Note: <code>sizeof(char) * strlen(*items) + 1</code> is logically wrong. Should have been <code>sizeof(char) * (strlen(*items) + 1)</code>, yet since <code>sizeof(char)</code> is 1, makes no arithmetic difference.</p>\n\n<p><strong>Redundancy</strong></p>\n\n<p>No need to start at 0 and add 1: Start at 1. Better to use <code>size_t</code> for sizing. Better to size to the referenced type, than explicitly code the type.</p>\n\n<pre><code>// int size = 0; \nsize_t size = 1; \nfor (char **ptr = items; *ptr; ptr++) {\n size++;\n}\n// char **data = malloc(sizeof(char *) * (size + 1));\nchar **data = malloc(sizeof *data * size);\n</code></pre>\n\n<p>Even better, just subtract:</p>\n\n<pre><code>for (char **ptr = items; *ptr; ptr++) {\n ;\n}\nsize_t size = ptr - items; \nchar **data = malloc(sizeof *data * size);\n</code></pre>\n\n<hr>\n\n<p><strong>Design flaw</strong></p>\n\n<p><code>if (data[i] == NULL) goto err;</code> fails to free prior allocations.</p>\n\n<p><strong>Design</strong></p>\n\n<p>The <code>for (int i = 0; *items; items++, i++)</code> increments one pointer with a ++ and indexes the other. I'd expect the same for both.</p>\n\n<p><strong>Caller flaw</strong></p>\n\n<p><code>free(data);</code> leaks the individual strings. Recommend coding a <code>freeList(char **)</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-11T22:06:21.287", "Id": "242100", "ParentId": "242075", "Score": "4" } }, { "body": "<p>Unfortunately, this is not very good code, for several reasons.</p>\n<p>First, I'm not certain what need you have for this kind of list to begin with. It is almost always more convenient to know the size of the data in advance, rather than relying on a NULL sentinel value. You could combine the two though, having both a &quot;count&quot; and the sentinel.</p>\n<p>Though lets suppose you come up with a need for this list as-is; then question if it has to be heap allocated with read/write access. Because if you can drop that part, the code could be massively simplified into a plain read-only look-up table:</p>\n<pre><code>const char** get_list (void)\n{\n static const char* items[] = {&quot;John&quot;, &quot;Jane&quot;, NULL };\n return &amp;items[0];\n}\n</code></pre>\n<p>Notably, it would have been more convenient if we knew the table size and don't have to rely on the NULL sentinel value, because that would enable the caller to write faster code with random access to any item. (That is, <code>if(i &lt; size) access(array[i])</code> directly rather than to slowly loop and count until item <code>i</code> is found, if it exists.)</p>\n<p>So maybe consider <code>const char** get_list (size_t* size)</code> instead, where the size 2 can be optionally returned through parameter.</p>\n<hr />\n<p>Dissecting the code that you have, here are some remarks:</p>\n<ul>\n<li><p>Never write functions with empty parenthesis <code>char **getList()</code>. This is obsolete style in C and might not work in future revisions of the language. Write an explicit <code>(void)</code> instead. (C and C++ are different here.)</p>\n</li>\n<li><p><code>char **items</code> should be <code>const</code> qualified. Whenever you have a pointer to a string literal, always const-qualify it, no exceptions.</p>\n</li>\n<li><p>There isn't a need to run-time calculate the array size inside the function, since it is known there. The array size is <code>size_t size = sizeof items / sizeof *items</code>, which can be computed at compile-time. <code>-1</code> to not count the sentinel value. Again, it is much more convenient to know the size instead of iterating for a terminating sentinel value.</p>\n</li>\n<li><p>The &quot;on error goto&quot; design pattern is only meaningful here if you do actual clean-up upon error. Otherwise you could just <code>return NULL</code>. Instead you should have <code>err: free(data);</code> at the end of the function and you won't have any leaks, because <code>free(NULL)</code> is well-defined to be a no-op. If you don't write the code like that, then <code>if (data[i] == NULL) goto err;</code> leaks memory.</p>\n<p>(Which is a nit-pick, because if any malloc fails, your program is toast and needs to terminate anyway. But this way you keep tools like Valgrind happy.)</p>\n</li>\n<li><p>As a design rule of thumb, whoever did the <code>malloc</code> is responsible for doing the <code>free</code>. You shouldn't outsource the <code>free</code> to the caller, that's bad API and is exactly how millions of defective C programs throughout history have created memory leaks before you. Instead create a function inside the same file as <code>get_list</code> for this purpose: <code>void free_list (char** list)</code> that does the clean-up.</p>\n</li>\n<li><p>Don't mix user I/O with algorithms. That is, leave the printing of error messages to the caller.</p>\n</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-12T08:49:33.227", "Id": "242125", "ParentId": "242075", "Score": "2" } } ]
{ "AcceptedAnswerId": "242100", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-11T10:29:56.270", "Id": "242075", "Score": "1", "Tags": [ "c" ], "Title": "A dynamic string array that's loopable without requiring a count" }
242075
<p>I would like to convert a string like <code>"1 2 3-5"</code> to an array of numbers <code>[1, 2, 3, 4, 5]</code>.</p> <p>Following <a href="https://en.wikipedia.org/wiki/Robustness_principle" rel="noreferrer">the robustness principle</a>, the list doesn't need to be separated by spaces, comma on any other separator is accepted. The only mandatory syntax is <code>A-B</code> to represent range from <code>A</code> to <code>B</code> (inclusive). Also, it's ok to ignore malformed input (like <code>1-3-5</code>), it can be considered "undefined behavior" as long as it doesn't raise an exception.</p> <p>My current code is a follow:</p> <pre><code>function parse(string) { let numbers = []; for (let match of string.match(/[0-9]+(?:\-[0-9]+)?/g)) { if (match.includes("-")) { let [begin, end] = match.split("-"); for (let num = parseInt(begin); num &lt;= parseInt(end); num++) { numbers.push(num); } } else { numbers.push(parseInt(match)); } } return numbers; } </code></pre> <p>This seems quite convoluted for such a simple task. Is there any alternative more straightforward using "modern" Javascript (I'm targeting ES6)?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-11T10:56:48.013", "Id": "475046", "Score": "1", "body": "I would take in account `5-3` too, that provides `[ 5, 4, 3 ]`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-11T11:11:13.453", "Id": "475047", "Score": "0", "body": "@Cid Yes, that's a good idea, thank you. I improved my code by calling `.split(\"-\").map(Number)` and then using `Math.min()` / `Math.max()` for iteration." } ]
[ { "body": "<p>On modern environments that support it (which is pretty much all of them except Safari), you can make it a bit nicer by using <code>matchAll</code> instead of <code>match</code>, and use capture groups to capture the digits immediately, rather than having to use an <code>.includes</code> check and <code>split</code> afterwards:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function parse(string) {\n const numbers = [];\n for (const [, beginStr, endStr] of string.matchAll(/(\\d+)(?:-(\\d+))?/g)) {\n const [begin, end] = [beginStr, endStr].map(Number);\n numbers.push(begin);\n if (endStr !== undefined) {\n for (let num = begin + 1; num &lt;= end; num++) {\n numbers.push(num);\n }\n }\n }\n return numbers;\n}\n\nconsole.log(parse('11 14-16 18-20'));</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>(For older environments, you'll need a <a href=\"https://github.com/ljharb/String.prototype.matchAll\" rel=\"noreferrer\">polyfill</a>)</p>\n\n<p>Also note that you should always use <code>const</code> to declare variables whenever possible - only use <code>let</code> when you need to warn readers of the code that you may have to reassign the variable in the future.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-11T11:12:22.403", "Id": "475048", "Score": "0", "body": "Thanks, unfortunately I'm developing for Qt / QML and the JavaScript engine over there does not support `matchAll()`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-11T11:16:36.493", "Id": "475051", "Score": "0", "body": "That's what polyfills are for - they add functionality to older non-standards-compliant environments that don't support modern methods. (In a reasonably professional project, I'd expect to see polyfills regardless). Without support *and* without the polyfill, you can do the same sort of thing with `let match; while (match = pattern.exec(str)) { const [, beginStr, endStr] = match;`, but that's kind of ugly." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-11T10:52:31.363", "Id": "242078", "ParentId": "242077", "Score": "7" } }, { "body": "<p>While your approach is working, it is also convoluted, which means that is hard to work with, for others, and for you in the future.</p>\n\n<p>You should break it down in smaller functions, that are <strong>easier to understand, develop, test and debug</strong>.</p>\n\n<pre><code>// converts \"1 2 3, 5-7\" into [\"1\", \"2\", \"3\" \"5-7\"]\nconst sanitizeInput = input =&gt; ...\n\n// converst \"5-7\" into [5, 6, 7]\nconst handleRange = input =&gt; ...\n\n// return true if the string contains a dash\nconst isRange = input =&gt; ...\n\n// turns [1, 2, 3, [5, 6, 7]] into [1, 2, 3, 5, 6, 7]\nconst flatten = input =&gt; ...\n\nconst mapValue = input =&gt; isRange(input) ? handleRange(input) : input\n\nconst processSanitizedInput = input =&gt; \n flatten(sanitizeInput(input).map(mapValue))\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-11T20:33:59.580", "Id": "242095", "ParentId": "242077", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-11T10:47:58.013", "Id": "242077", "Score": "5", "Tags": [ "javascript" ], "Title": "Parsing numbers and ranges from a string in Javascript" }
242077
<p>I have written a series of functions to solve <a href="https://en.wikipedia.org/wiki/KenKen" rel="nofollow noreferrer">kenkens</a>. The general strategy is to eliminate possibilities until only one remains for each cell. This first function eliminates all possibilities that can't be used to satisfy the operation and target constraints. </p> <p>I'm interested in any feedback concerning style and efficiency.</p> <pre class="lang-py prettyprint-override"><code> from itertools import product from itertools import combinations #set size of square board side = 9 #each cell of the grid is identified by an index indices = [i for i in range(side*side)] #each cell is located in a row and in a column addresses = [] index2row = [] index2column = [] for x in range(side): for y in range(side): addresses.append([x,y]) index2row.append(x) index2column.append(y) #each row and column is a list of indices rows = [] a = 0 b = side for r in range(side): row = [] for i in indices[a:b]: row.append(i) rows.append(row) a = b b = b+side columns = [] for c in range(side): column = [] a = c for i in range(side): column.append(a) a = a + side columns.append(column) #initially each cell can be any number from 1 to the number side possibilities = [] for i in range(side*side): lp = [] for n in range(1, side+1): lp.append(n) possibilities.append(lp) #initially the solution for each cell is set at 0 values = [0 for i in range(side * side)] ##define Cage class class Cage: def __init__(self, indexes, operation, target): self.indexes = indexes #cells in cage self.operation = operation #arithmetic operation self.target = target #result of operation e.g. 2 by division ##operation functions def multiplication(combination): result = 1 for n in combination: result = result*n return(result) def subtraction(pair): return(abs(pair[0] - pair[1])) def division(pair): return(max([pair[0]/pair[1], pair[1]/pair[0]])) def addition(combination): return(sum(combination)) def equals(combination): return(combination[0]) #sample puzzle, indices, operations and targets for each cage indexes = [[0,1,9,10],[2,3],[4,12,13],[5,14],[6,7],[8,17,26],[11,20],[15,24],[16,25],[18,27,36,45], [19,28,37],[21,22,31],[23,32,41,50,59],[29,38],[30,39],[33,42],[34,43,52],[35,44],[40,49], [46,54,55],[47,48],[51,60],[53,62],[56,57],[58,67,68,77],[61],[63,72],[64,73,74],[65], [66,75,76],[69,70,71],[78,79,80]] operations = [multiplication,subtraction,addition,division,addition,multiplication, multiplication,division,subtraction, multiplication,addition,multiplication,addition, multiplication,division,subtraction,multiplication,subtraction, addition,addition,division,addition,addition, subtraction,addition,equals, subtraction,addition,equals,multiplication,addition,multiplication] targets = [1344,5,20,2,15,15,24,2,2,648,14,120,35,56,4,5,18,5,6,12,3,11,13,1,16,8,3,19,1,48,18,210] #assemble indexes, operations and targets for all cages into list 'cages' cages = [] for i in range(len(targets)): cage = Cage(indexes[i], operations[i], targets[i]) cages.append(cage) ##1 remove numbers that can't be used to produce target ##e.g. 2 by division eliminates 5,7,9 ## 8 by subtraction leaves only 1 and 9, 2-8 are eliminated def cullPossibilities(possibilities): for cage in cages: if all([possibilities[i] == [] for i in cage.indexes]): continue #test if all cells in cage have been solved, if so move to #next cage listsPossibilities = [] #assemble list of possibilities from cage cells for index in cage.indexes: if possibilities[index] != []: listsPossibilities.append(possibilities[index]) else: listsPossibilities.append([values[index]]) combinations = list(product(*listsPossibilities)) #generate combinations of possibilities from cells in cage combinations = [list(combination) for combination in combinations] #test which satisfy target targetCombinations = [] for combination in combinations: if cage.operation(combination) == cage.target: #check for duplicates using set and length of list if len(combination) == len(set(combination)): targetCombinations.append(combination) else: rowAddresses = [index2row[index] for index in cage.indexes] testRow = list(zip(combination, rowAddresses)) columnAddresses = [index2column[index] for index in cage.indexes] testColumn = list(zip(combination, columnAddresses)) if len(testColumn) == len(set(testColumn)) and len(testRow) == len(set(testRow)): targetCombinations.append(combination) # if target is satisfied and there are no duplicates add to new list of #possibilities which replaces original list of possibilities i = 0 for index in cage.indexes: newPossibilities = [targetCombination[i] for targetCombination in targetCombinations] if possibilities[index] != []: possibilities[index] = list(set(newPossibilities)) i = i + 1 return(possibilities) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-11T16:09:54.677", "Id": "475090", "Score": "0", "body": "Welcome to CR! Could you post how this function is to be called and show a sample input/output? I'm not sure what `possibilities` is supposed to look like. Thanks." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-12T16:03:34.850", "Id": "475187", "Score": "0", "body": "possibilities is a list of the numbers being considered as a solution for a given cell." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-12T16:05:18.323", "Id": "475188", "Score": "0", "body": "where do I post the additional code to demonstrate how the function is called?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-12T16:05:31.370", "Id": "475189", "Score": "0", "body": "OK. What might that look like? Just random numbers from -infinity..infinity and the list can be any length? You can edit the post to show what a KenKen board looks like being solved by your algorithm. See the [edit link](https://codereview.stackexchange.com/posts/242079/edit) above this comment section and slightly to the left." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-12T16:22:42.163", "Id": "475192", "Score": "0", "body": "Thanks for the additional code, however, I still feel very in the dark about how the code works--it feels a bit like a wall of text. I recommend looking at [this upvoted KenKen post](https://codereview.stackexchange.com/questions/162933/a-kenken-puzzle-solver-in-python) which guides readers through the code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-12T16:25:31.100", "Id": "475193", "Score": "0", "body": "kenken is a number puzzle played on a square grid. I've added the setup for a 9x9 puzzle. The cells must be filled with the numbers 1-9 such that there are no duplicates in any row or column. An additional set of constraints involves a set of cages: groups of cells that must satisfy some arithmetical rule. For example: the values of the cells must equal 2 by division." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-12T16:33:11.673", "Id": "475198", "Score": "1", "body": "Please make this part of your question, comments are just for discussion. See the above link to get a sense of what a solid, answerable post looks like. Without a bit more context, the post might remain unanswered, or answers that do arrive will be cursory and unsatisfying for you." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-12T21:57:20.073", "Id": "475234", "Score": "1", "body": "I've added annotation to try to convey my thought process." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-13T13:49:28.097", "Id": "475328", "Score": "1", "body": "the referenced KenKen post was very helpful. Thank you." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "9", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-11T12:56:33.380", "Id": "242079", "Score": "4", "Tags": [ "python", "beginner" ], "Title": "kenken solver, python" }
242079
<p>So, I've tried to make a simple math library in Rust. What do you think about it?</p> <pre><code>const PRECISION: f64=512.; //Balance between speed and precision here. fn ln(x:f64) -&gt; f64 { let mut sum=0.; let epsilon=(x-1.)/(5.*PRECISION); let mut i=1.; while (epsilon&gt;0. &amp;&amp; i&lt;x) || (epsilon&lt;0. &amp;&amp; i&gt;x) { sum+=epsilon/i; i+=epsilon; } sum } fn exp(x:f64) -&gt; f64 { let mut i=0.; let mut y=1.; let epsilon=x/PRECISION; while (epsilon&gt;0. &amp;&amp; i&lt;x) || (epsilon&lt;0. &amp;&amp; i&gt;x) { y+=epsilon*y; i+=epsilon; } y } fn arctan(x:f64) -&gt; f64 { let mut sum=0.; let epsilon=x/PRECISION; let mut i=0.; while i&lt;x { sum+=epsilon/(1.+i*i); i+=epsilon; } sum*(180./pi()) } fn tan(degrees:f64) -&gt; f64 { sin(degrees)/cos(degrees) } fn sin(degrees:f64) -&gt; f64 { if degrees&lt;0. { return -sin(-degrees); } if degrees&gt;90. { return cos(degrees-90.); } let radians=degrees/(180./pi()); let mut tmpsin=0.; let mut tmpcos=1.; let epsilon=radians/PRECISION; let mut i=0.; while (epsilon&gt;0. &amp;&amp; i&lt;radians) || (epsilon&lt;0. &amp;&amp; i&gt;radians) { tmpsin+=epsilon*tmpcos; tmpcos-=epsilon*tmpsin; i+=epsilon; } tmpsin } fn arcsin(x:f64) -&gt; f64 { arctan(x/sqrt(1.-x*x)) } fn arccos(x:f64) -&gt; f64 { 90.-arcsin(x) } fn cos(degrees:f64) -&gt; f64 { sin(90.-degrees) } fn sqrt(x:f64) -&gt; f64 { let mut max=1000.; let mut min=0.; let mut i=(min+max)/2.; while (max-min)&gt;1./PRECISION { if i*i&gt;x { max=i; } else { min=i; } i=(max+min)/2.; } i } fn pi() -&gt; f64 { let mut sum=0.; let mut i=-1.; let epsilon=1./PRECISION; while i&lt;1. { sum+=epsilon/(1.+i*i); i+=epsilon; } 2.*sum } fn main() { println!("x\tsin(x)\tcos(x)\ttan(x)\tln(x)\tsqrt(x)\tasin\tacos\tatan"); for i in 0..101 { print!("{:.4}\t",i); print!("{:.4}\t",sin(i as f64)); print!("{:.4}\t",cos(i as f64)); if tan(i as f64)&lt;100. &amp;&amp; tan(i as f64)&gt; -10. { print!("{:.4}\t",tan(i as f64)); } else if tan(i as f64)&lt; -10. { print!("{:.3}\t",tan(i as f64)); } else { print!("inf\t"); } if ln(i as f64)&gt; -100. { print!("{:.4}\t",ln(i as f64)); } else { print!("-inf\t"); } print!("{:.4}\t",sqrt(i as f64)); if arcsin((i as f64)/100.)&lt;90. { print!("{:.4}\t",arcsin((i as f64)/100.)); } else { print!("90\t"); } if arccos((i as f64)/100.)&lt;90. &amp;&amp; arccos((i as f64)/100.)&gt;0. { print!("{:.4}\t",arccos((i as f64)/100.)); } else if arccos((i as f64)/100.)&gt;0. { print!("90\t"); } else { print!("0\t"); } print!("{:.4}\n",arctan((i as f64)/100.)); } println!("pi={:.4}",pi()); println!("rad={:.4}",180./pi()); println!("ln(1/pi)={:.4}",ln(1./pi())); println!("e={:.4}",exp(1 as f64)); println!("1/e={:.4}",exp(-1 as f64)); } </code></pre>
[]
[ { "body": "<p>I'm not too familiar with the math side of this, so I'll just focus on the Rust part.</p>\n\n<h1>Run <a href=\"https://github.com/rust-lang/rustfmt\" rel=\"nofollow noreferrer\">rustfmt</a></h1>\n\n<p>Running <code>cargo fmt</code> will autoformat your code to the Rust best practices. For example, it will convert</p>\n\n<pre class=\"lang-rust prettyprint-override\"><code>fn arctan(x:f64) -&gt; f64 {\n let mut sum=0.;\n let epsilon=x/PRECISION;\n let mut i=0.;\n while i&lt;x {\n sum+=epsilon/(1.+i*i);\n i+=epsilon;\n }\n sum*(180./pi())\n}\n</code></pre>\n\n<p>to</p>\n\n<pre class=\"lang-rust prettyprint-override\"><code>fn arctan(x: f64) -&gt; f64 {\n let mut sum = 0.;\n let epsilon = x / PRECISION;\n let mut i = 0.;\n while i &lt; x {\n sum += epsilon / (1. + i * i);\n i += epsilon;\n }\n sum * (180. / pi())\n}\n</code></pre>\n\n<p>Notice the spacing added.</p>\n\n<h1>Run <a href=\"https://github.com/rust-lang/rust-clippy\" rel=\"nofollow noreferrer\">clippy</a></h1>\n\n<p>Running <code>cargo clippy</code> will point out a few common mistakes. Let's take a look at them here.</p>\n\n<pre class=\"lang-rust prettyprint-override\"><code>warning: using `print!()` with a format string that ends in a single newline\n --&gt; src/main.rs:136:9\n |\n136 | print!(\"{:.4}\\n\",arctan((i as f64)/100.));\n | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n |\n = note: `#[warn(clippy::print_with_newline)]` on by default\n = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#print_with_newline\nhelp: use `println!` instead\n |\n136 | println!(\"{:.4}\",arctan((i as f64)/100.));\n | ^^^^^^^\n</code></pre>\n\n<p>As it suggests, you should replace that line with <code>println!</code>.</p>\n\n<pre class=\"lang-rust prettyprint-override\"><code>warning: casting integer literal to `f64` is unnecessary\n --&gt; src/main.rs:141:28\n |\n141 | println!(\"e={:.4}\",exp(1 as f64));\n | ^^^^^^^^ help: try: `1_f64`\n |\n = note: `#[warn(clippy::unnecessary_cast)]` on by default\n = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#unnecessary_cast\n</code></pre>\n\n<p>That, and the line that follows it, can be used as a float like you do everywhere else in your code. You can do <code>1_f64</code>, <code>1f64</code>, <code>1.0</code>, or like elsewhere in your code, <code>1.</code>.</p>\n\n<h1>Extract repeated operations</h1>\n\n<p>When you print things out, you repeat the calculation a lot, and <a href=\"https://godbolt.org/z/Wz8r17\" rel=\"nofollow noreferrer\">it actually appears to have a difference in assembly</a> (although not when <code>#[inline(never)]</code> is used on <code>ln</code>?). So instead of</p>\n\n<pre class=\"lang-rust prettyprint-override\"><code>if arccos((i as f64) / 100.) &lt; 90. &amp;&amp; arccos((i as f64) / 100.) &gt; 0. {\n print!(\"{:.4}\\t\", arccos((i as f64) / 100.));\n} else if arccos((i as f64) / 100.) &gt; 0. {\n print!(\"90\\t\");\n} else {\n print!(\"0\\t\");\n}\n</code></pre>\n\n<p>Prefer</p>\n\n<pre class=\"lang-rust prettyprint-override\"><code>let inv_cos = arccos((i as f64) / 100.);\nif inv_cos &lt; 90. &amp;&amp; inv_cos &gt; 0. {\n print!(\"{:.4}\\t\", inv_cos);\n} else if inv_cos &gt; 0. {\n print!(\"90\\t\");\n} else {\n print!(\"0\\t\");\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-11T21:59:15.150", "Id": "242099", "ParentId": "242080", "Score": "1" } } ]
{ "AcceptedAnswerId": "242099", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-11T14:14:48.963", "Id": "242080", "Score": "0", "Tags": [ "mathematics", "rust" ], "Title": "Simple math library in Rust" }
242080
<p>I am busy on a protected page with login and I want know if there is more protection needed. It is a very simple system without database etc...</p> <p>authentication.php</p> <pre><code>&lt;?php session_start(); if($_SERVER['REQUEST_METHOD'] == 'POST'){ $account = array ( 'sebas' =&gt; '$2y$10$96Yi1ezzoS6xZYjPhbvYTeCha.YypKF.7MSYwfruXtKaFyeGRLeMK', 'bert' =&gt; '$3g$10$96Yi1ezzoS6xZYjPhbvYTeCha.YypKF.7MSYwfruXtKaFyeGRLeMK', ); if(array_key_exists($_POST['user'], $account)){ if(password_verify($_POST['password'], $account[$_POST['user']])){ session_regenerate_id(); $_SESSION['username'] = $_POST["user"]; $_SESSION["loggedin"]) = true; header("location: protected_page.php"); }else{ echo 'Something wrong'; } }else{ echo 'Something wrong'; } } ?&gt; </code></pre> <p>protected.php</p> <pre><code>&lt;?php session_start(); if (isset($_SESSION['loggedin']) &amp;&amp; $_SESSION['loggedin'] == true) { echo 'welcome'; }else{ header("location: login.php"); exit; } ?&gt; </code></pre> <p>Please let me know and give me any feedback for a better secure system without database.</p>
[]
[ { "body": "<p>One major concern is that you define the array of account names and their associated hashed passwords in the file that, presumably, is publicly accessible through a web server. </p>\n\n<p>You might be tempted to think this is not a concern, because users will not be able to see the source code, right? Generally speaking, that's correct. However, if the web server somehow becomes misconfigured at some point, where .php files are not executed by the PHP engine, but in stead are served as plain text, you have a big security issue: any visitor will now be able to view the account info.</p>\n\n<p>To deal with this, you should keep this sensitive information outside of the server's public directory.</p>\n\n<p>So, let's imagine this is your web server's directory structure:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code> - etc/\n - private/ &lt;-- A hidden private directory, outside of the public directory\n - public/ &lt;-- The public root directory from which your .php pages are served\n - img/\n - js/\n - authentication.php\n - protected.php\n</code></pre>\n\n<p>...then you should, for instance, put your account info in <code>private</code>:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code> - etc/\n - private/\n - accounts.php\n - public/\n - img/\n - js/\n - authentication.php\n - protected.php\n</code></pre>\n\n<p><code>accounts.php</code> would then look like this:</p>\n\n<pre><code>&lt;?php\nreturn array (\n 'sebas' =&gt; '$2y$10$96Yi1ezzoS6xZYjPhbvYTeCha.YypKF.7MSYwfruXtKaFyeGRLeMK',\n 'bert' =&gt; '$3g$10$96Yi1ezzoS6xZYjPhbvYTeCha.YypKF.7MSYwfruXtKaFyeGRLeMK',\n);\n</code></pre>\n\n<p><code>authentication.php</code> would then do something like this:</p>\n\n<pre><code>&lt;?php\nsession_start();\n\nif($_SERVER['REQUEST_METHOD'] == 'POST'){\n // I personally prefer to name this variable as plural\n $accounts = include '../private/accounts.php';\n\n // if include has failed, it will return false\n if(is_array($accounts)) {\n // continue your authentication procedure\n }\n\n... etc.\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-11T16:18:26.080", "Id": "242086", "ParentId": "242083", "Score": "3" } } ]
{ "AcceptedAnswerId": "242086", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-11T15:17:05.240", "Id": "242083", "Score": "3", "Tags": [ "php" ], "Title": "More protection needed? PHP secure" }
242083
<p>I wanted to use an external global state to a React.js application with a redux-like sort of pattern (with reducers, actions, etc). However, I don't want to use redux itself, as it's just a small project and redux might be too much boilerplate.</p> <p>Below is a sort of imitation of Redux with React.js Hooks and State. It's a variation of a design found in <a href="https://medium.com/simply/state-management-with-react-hooks-and-context-api-at-10-lines-of-code-baf6be8302c" rel="nofollow noreferrer">this article</a></p> <pre><code>// src/store/index.js import React, { createContext, useContext, useReducer} from "react"; import { initialAppState } from "./types"; import { reducer } from "./reducers"; // Redux Mini :) let dispatchOuter; const StateContext = createContext(initialAppState); export const StateProvider = ({ children }) =&gt; { const [state, dispatch] = useReducer(reducer, initialAppState); dispatchOuter = dispatch; return ( &lt;StateContext.Provider value={state}&gt;{children}&lt;/StateContext.Provider&gt; ); }; export const useStore = () =&gt; [ useContext(StateContext), dispatchOuter, ]; </code></pre> <p>Usage:</p> <pre><code>// src/index.js ReactDOM.render( &lt;StateProvider&gt; &lt;ExampleComponent/&gt; &lt;/StateProvider&gt;, document.getElementByID("root") ); </code></pre> <pre><code>// src/components/ExampleComponent.js export function ExampleComponent() { const [state, dispatch] = useStore(); return ( &lt;div&gt; &lt;Button onClick={() =&gt; {dispatch({type: "INCREMENT_CLICKS"})}}/&gt; &lt;span&gt;{state.clicks}&lt;/span&gt; &lt;/div&gt; ); } </code></pre> <p>The <code>StateProvider</code> component is actually a <code>StateContext.Provider</code>, which provides context accessed by the <code>useStore()</code>. With some initial tests it seems to work pretty well.</p> <p>Are there any major flaws with this design? Any changes you would suggest? Will I be shooting myself in the foot down the road using this pattern?</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-11T16:49:24.480", "Id": "242087", "Score": "1", "Tags": [ "javascript", "react.js", "redux", "state" ], "Title": "Custom Global Store using React.js context and hooks" }
242087
<p>I wanted to write a simple implementation for a high card game. Basically two cards are drawn and the higher one wins. Additional rules: support for multiple decks, if same suits drawn then the higher colour wins, if same colour and suit (possible as there's multiple decks) then resolve a tie by dealing a further card to each player until a max number of tries reached. Also there exists a wild card that beats all others.</p> <p>It's trivial but really I'd like to get some feedback on how it's tested. I tried to come up with a way to test the logic that depends on what rand() returns, not sure if that's the correct approach, so any feedback appreciated.</p> <pre><code>#include &lt;stdlib.h&gt; #include &lt;iostream&gt; #include &lt;sstream&gt; #define NUM_OF_CARDS 52 #define NUM_OF_RETRIES 2 class HighCard { public: HighCard() = default; ~HighCard() = default; bool Play( int (*f) (void) = rand, std::ostream&amp; os = std::cout ); }; bool HighCard::Play( int (*f) (void), std::ostream&amp; os ) { for (int k = 0; k &lt; NUM_OF_RETRIES; k++) { int rank1 = -1, rank2 = -1, suit1 = -1, suit2 = -1; rank1 = f() % NUM_OF_CARDS + 1; rank2 = f() % NUM_OF_CARDS + 1; suit1 = f() % 4 + 1; suit2 = f() % 4 + 1; os &lt;&lt; "rank1 is " &lt;&lt; rank1 &lt;&lt; " rank2 is " &lt;&lt; rank2 &lt;&lt; "\n"; os &lt;&lt; "suit1 is " &lt;&lt; suit1 &lt;&lt; " suit2 is " &lt;&lt; suit2 &lt;&lt; "\n"; if (rank1 == rank2 &amp;&amp; suit1 == suit2) { os &lt;&lt; "a tie so need to draw again" &lt;&lt; "\n"; continue; } if (rank1 == 2 &amp;&amp; suit1 == 2) { os &lt;&lt; "a wild card drawn " &lt;&lt; "\n"; return false; } else if (rank2 == 2 &amp;&amp; suit2 == 2) { os &lt;&lt; "a wild card drawn " &lt;&lt; "\n"; return true; } if (rank1 != rank2) return ( rank1 &lt; rank2 ); else return ( suit1 &lt; suit2 ); } os &lt;&lt; "a tie repeated too many times..." &lt;&lt; "\n"; return true; } // function used for testing instead of rand() // ints passed in instantiation will be returned in subsequent calls template&lt;int n1, int n2, int n3, int n4, int n5 = -1, int n6 = -1, int n7 = -1, int n8 = -1&gt; int drawNums() { static int i = -1; i++; if (i % 8 == 0) return n1; else if (i % 8 == 1) return n2; else if (i % 8 == 2) return n3; else if (i % 8 == 3) return n4; else if (i % 8 == 4) return n5; else if (i % 8 == 5) return n6; else if (i % 8 == 6) return n7; else return n8; } void test_win () { HighCard card; std::ostringstream oss; oss.str(""); // rank1 &gt; rank2, suit1 &lt; suit2 assert(card.Play( drawNums&lt;22,3,0,1&gt;, oss ) == false); assert(oss &amp;&amp; oss.str() == "rank1 is 23 rank2 is 4\n" "suit1 is 1 suit2 is 2\n"); oss.str(""); // rank1 &gt; rank2, suit1 &gt; suit2 assert(card.Play( drawNums&lt;22,3,1,0&gt;, oss ) == false); assert(oss &amp;&amp; oss.str() == "rank1 is 23 rank2 is 4\n" "suit1 is 2 suit2 is 1\n"); oss.str(""); // rank1 &gt; rank2, suit1 = suit2 assert(card.Play( drawNums&lt;22,3,0,0&gt;, oss ) == false); assert(oss &amp;&amp; oss.str() == "rank1 is 23 rank2 is 4\n" "suit1 is 1 suit2 is 1\n"); oss.str(""); // rank1 &lt; rank2, suit1 &lt; suit2 assert(card.Play( drawNums&lt;3,22,0,1&gt;, oss ) == true); assert(oss &amp;&amp; oss.str() == "rank1 is 4 rank2 is 23\n" "suit1 is 1 suit2 is 2\n"); oss.str(""); // rank1 &lt; rank2, suit1 &gt; suit2 assert(card.Play( drawNums&lt;3,22,1,0&gt;, oss ) == true); assert(oss &amp;&amp; oss.str() == "rank1 is 4 rank2 is 23\n" "suit1 is 2 suit2 is 1\n"); oss.str(""); // rank1 &lt; rank2, suit1 = suit2 assert(card.Play( drawNums&lt;3,22,0,0&gt;, oss ) == true); assert(oss &amp;&amp; oss.str() == "rank1 is 4 rank2 is 23\n" "suit1 is 1 suit2 is 1\n"); oss.str(""); // rank1 = rank2, suit1 &lt; suit2 assert(card.Play( drawNums&lt;22,22,0,1&gt;, oss ) == true); assert(oss &amp;&amp; oss.str() == "rank1 is 23 rank2 is 23\n" "suit1 is 1 suit2 is 2\n"); oss.str(""); // rank1 = rank2, suit1 &gt; suit2 assert(card.Play( drawNums&lt;22,22,1,0&gt;, oss ) == false); assert(oss &amp;&amp; oss.str() == "rank1 is 23 rank2 is 23\n" "suit1 is 2 suit2 is 1\n"); } void test_wildcard() { HighCard card; std::ostringstream oss; oss.str(""); // rank1 &lt; rank2, suit1 &lt; suit2 assert(card.Play( drawNums&lt;1,3,1,3&gt;, oss ) == false); assert(oss &amp;&amp; oss.str() == "rank1 is 2 rank2 is 4\n" "suit1 is 2 suit2 is 4\n" "a wild card drawn \n"); oss.str(""); // rank1 &gt; rank2, suit1 &gt; suit2 assert(card.Play( drawNums&lt;1,0,1,0&gt;, oss ) == false); assert(oss &amp;&amp; oss.str() == "rank1 is 2 rank2 is 1\n" "suit1 is 2 suit2 is 1\n" "a wild card drawn \n"); oss.str(""); // rank1 &gt; rank2, suit1 &gt; suit2 assert(card.Play( drawNums&lt;3,1,3,1&gt;, oss ) == true); assert(oss &amp;&amp; oss.str() == "rank1 is 4 rank2 is 2\n" "suit1 is 4 suit2 is 2\n" "a wild card drawn \n"); oss.str(""); // rank1 &lt; rank2, suit1 &lt; suit2 assert(card.Play( drawNums&lt;0,1,0,1&gt;, oss ) == true); assert(oss &amp;&amp; oss.str() == "rank1 is 1 rank2 is 2\n" "suit1 is 1 suit2 is 2\n" "a wild card drawn \n"); } void test_retries_limit() { HighCard card; std::ostringstream oss; oss.str(""); assert(card.Play( drawNums&lt;2,2,2,2, 2,2,2,2&gt;, oss ) == true); assert(oss &amp;&amp; oss.str() == "rank1 is 3 rank2 is 3\n" "suit1 is 3 suit2 is 3\n" "a tie so need to draw again\n" "rank1 is 3 rank2 is 3\n" "suit1 is 3 suit2 is 3\n" "a tie so need to draw again\n" "a tie repeated too many times...\n"); // wild card oss.str(""); assert(card.Play( drawNums&lt;1,1,1,1, 1,1,1,1&gt;, oss ) == true); assert(oss &amp;&amp; oss.str() == "rank1 is 2 rank2 is 2\n" "suit1 is 2 suit2 is 2\n" "a tie so need to draw again\n" "rank1 is 2 rank2 is 2\n" "suit1 is 2 suit2 is 2\n" "a tie so need to draw again\n" "a tie repeated too many times...\n"); } void test_retries() { HighCard card; std::ostringstream oss; oss.str(""); assert(card.Play( drawNums&lt;2,2,2,2 ,23,2,2,2&gt;, oss ) == false); assert(oss &amp;&amp; oss.str() == "rank1 is 3 rank2 is 3\n" "suit1 is 3 suit2 is 3\n" "a tie so need to draw again\n" "rank1 is 24 rank2 is 3\n" "suit1 is 3 suit2 is 3\n"); // wild card oss.str(""); assert(card.Play( drawNums&lt;1,1,1,1, 1,2,1,3&gt;, oss ) == false); assert(oss &amp;&amp; oss.str() == "rank1 is 2 rank2 is 2\n" "suit1 is 2 suit2 is 2\n" "a tie so need to draw again\n" "rank1 is 2 rank2 is 3\n" "suit1 is 2 suit2 is 4\n" "a wild card drawn \n"); } int main (int argc, char **argv) { srand (time(NULL)); test_win(); test_wildcard(); test_retries(); test_retries_limit(); return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-11T19:29:08.557", "Id": "475096", "Score": "0", "body": "What HighCard.Play returns?" } ]
[ { "body": "<p>Ok, let's start with basics.</p>\n\n<p><code>class HighCard</code> doesn't make much sense. Make it a namespace.</p>\n\n<p>The method \n <code>bool HighCard::Play( int (*f) (void) = rand, std::ostream&amp; os = std::cout );</code> isn't convenient by any means. Supplementing a function pointer is very old fashioned (C style not a C++ way) and a poor practice in general.</p>\n\n<p>You'd better use <code>std::function&lt;int(void)&gt;</code> make <code>HighCard::Play</code> into a template that accepts a callable as the first parameter.</p>\n\n<p>The reason why function pointer is not good is because it isn't general enough - <code>rand</code> is a very poor random function and it is preferable to use <code>std::default_random_device</code> which is a class with data and one cannot use it via function pointers. <code>std::function&lt;int(void)&gt;</code> can wrap it but calling it is generally slow, so for the code to be efficient it is best to use template callable and wrap whatever needed into a lambda/closure.</p>\n\n<p>This would also solve the problem with the ridiculous template <code>template&lt;...&gt; int drawNums()</code>. Once your method accepts a callable just make a simple structure that holds a vector of prefixed results and passes them.</p>\n\n<pre><code>rank1 = f() % NUM_OF_CARDS + 1;\nrank2 = f() % NUM_OF_CARDS + 1;\nsuit1 = f() % 4 + 1;\nsuit2 = f() % 4 + 1;\n</code></pre>\n\n<p>This is not a good way to generate random numbers. Use <code>std::uniform_int_distribution</code> to properly randomize values instead of <code>%</code> operation. It requires a random engine to work, so it best be used inside the function. So make the function/callable in format <code>std::function&lt;int(int)&gt;</code> and use it as</p>\n\n<pre><code>rank1 = f(NUM_OF_CARDS);\nrank2 = f(NUM_OF_CARDS);\nsuit1 = f(4);\nsuit2 = f(4);\n</code></pre>\n\n<p>so <code>f(val)</code> generates number between 1 and <code>val</code> including.</p>\n\n<p>Do not use MACROS. Use <code>constexpr</code> or <code>enum</code> instead for <code>NUM_OF_CARDS</code> and <code>NUM_OF_RETRIES</code>.</p>\n\n<p>I think you can potentially make <code>HighCard::Play</code> into a constexpr conditionally on the input (by also removing the logs...). In which case you can perform <code>static_assert</code> for the tests instead of <code>assert</code>. This means that you can compile-time run the test instead of relying on run-time verification.</p>\n\n<p>Also, about logs, <code>HighCard::Play</code> shouldn't quite print anything. Instead it should send results (an enum of current state) to some other class which should perform printing or whatever. This way <code>HighCard::Play</code> will be cleaner and printing is delegated to some other code.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-11T19:39:09.733", "Id": "242093", "ParentId": "242088", "Score": "1" } }, { "body": "<p>My main issue with the game is that you randomly generate cards:</p>\n\n<pre><code> rank1 = f() % NUM_OF_CARDS + 1;\n rank2 = f() % NUM_OF_CARDS + 1;\n suit1 = f() % 4 + 1;\n suit2 = f() % 4 + 1;\n</code></pre>\n\n<p>This is not like real life where the probability of two people getting the same card is zero (here the chances are small but they exist).</p>\n\n<p>A better technique would be to generate a pack of cards and then randomly shuffle the cards. Then select cards from the top of the pack (selected cards can not be re-selected you can just keep track of the current top). When you want to reset simply re-shuffle and reset the top to zero. This way you guarantee that you get a fair chance of any card but you can not have two cards the same.</p>\n\n<hr>\n\n<p>Talking about random numbers.</p>\n\n<p>The old C style random number generator:</p>\n\n<pre><code>srand()\nrand()\n</code></pre>\n\n<p>They are easy to use (also easy to use incorrectly).</p>\n\n<p>Assuming <code>f()</code> maps to <code>rand()</code> then:</p>\n\n<pre><code> f() % NUM_OF_CARDS + 1;\n</code></pre>\n\n<p>Is <strong>not</strong> correct (just check stack-overflow for answers about this (there are some violent debates)). Suffice to say not all the numbers in <code>[0..NUM_OF_CARDS]</code> are equally as likely (the lower numbers have a slightly higher probability than the higher numbers).</p>\n\n<p>Also it has been shown that <code>rand()</code> is not that random. There are papers on the subject.</p>\n\n<p>Rather than work out how to do all the correctly you can simply switch to the C++ functionality:</p>\n\n<pre><code> // Only create this once in main.\n // Then pass it to where it needs to go.\n std::default_random_engine generator;\n\n std::uniform_int_distribution&lt;int&gt; suit(1,4);\n std::uniform_int_distribution&lt;int&gt; rank(1,13);\n\n rank1 = rank(generator);\n suit1 = suit(generator);\n //etc\n</code></pre>\n\n<p>Or probably better:</p>\n\n<pre><code> std::default_random_engine generator;\n\n std::uniform_int_distribution&lt;int&gt; card(0,51);\n\n card1 = card(generator);\n rank1 = (card % 13) + 1; // you use 1-13 hence the +1\n suit1 = (card / 13) + 1; // you use 1-4. hence the +1\n</code></pre>\n\n<hr>\n\n<p>This is an interesting comment:</p>\n\n<pre><code>// function used for testing instead of rand() \n// ints passed in instantiation will be returned in subsequent calls\n</code></pre>\n\n<p>yes testing becomes hard when you use random numbers. But the rand functionality is designed with that in mind. You can make sure you get the same set of random numbers by seeding the generator with a specific start point.</p>\n\n<pre><code>srand(10); // The random number will start from the seed of 10.\n // starting here will always generate the same set of random\n // numbers. So if you want your unit tests to always run the\n // same way simply seed the rand number generator before\n // running the test with a specific value (you will get the\n // same sequence of randoms).\n</code></pre>\n\n<p>Same happens for the C++ version:</p>\n\n<pre><code>std::default_random_engine generator(10);\n</code></pre>\n\n<p>But saying all that I do like your number generator idea.</p>\n\n<hr>\n\n<p>In C++ we frown upon <code>#define</code></p>\n\n<pre><code>#define NUM_OF_CARDS 52\n#define NUM_OF_RETRIES 2\n</code></pre>\n\n<p>Nearly all use cases for <code>#define</code> have been replaced by language (rather than pre-processor) features. Prefer to use language features where they exist.</p>\n\n<pre><code>static constexpr int NumOfCards = 52; // Note all uppercase is still macro names so avoid them.\nstatic constexpr int NumOfRetries = 2;\n</code></pre>\n\n<p>Here these values are correctly typed.</p>\n\n<hr>\n\n<p>Better implementation:</p>\n\n<p>if you have a lot <code>if () else if else if else if</code>.</p>\n\n<pre><code>template&lt;int n1, int n2, int n3, int n4,\n int n5 = -1, int n6 = -1, int n7 = -1, int n8 = -1&gt;\nint drawNums()\n{\n static int i = -1;\n i++;\n if (i % 8 == 0)\n return n1;\n else if (i % 8 == 1)\n return n2;\n else if (i % 8 == 2)\n return n3;\n else if (i % 8 == 3)\n return n4;\n else if (i % 8 == 4)\n return n5;\n else if (i % 8 == 5)\n return n6;\n else if (i % 8 == 6)\n return n7;\n else \n return n8;\n}\n</code></pre>\n\n<p>You may want to look at using a <code>switch</code> statement.</p>\n\n<pre><code>template&lt;int n1, int n2, int n3, int n4,\n int n5 = -1, int n6 = -1, int n7 = -1, int n8 = -1&gt;\nint drawNums()\n{\n static int i = -1;\n i++;\n\n switch(i % 8) {\n case 0: return n1; // Though i would have numbered from n0 - n7\n case 1: return n2; // To make this more logical.\n case 2: return n3;\n case 3: return n4;\n case 4: return n5;\n case 5: return n6;\n case 6: return n7;\n case 7: return n8;\n }\n}\n</code></pre>\n\n<p>But we can go one better than that.<br>\nWhy do we need a switch when we simply use an array and look up the value.</p>\n\n<pre><code>template&lt;int n1, int n2, int n3, int n4,\n int n5 = -1, int n6 = -1, int n7 = -1, int n8 = -1&gt;\nint drawNums()\n{\n static int result[] = {n1, n2, n3, n4, n5, n6, n7, n8};\n static int i = -1;\n i++;\n return result[i % 8];\n}\n</code></pre>\n\n<p>But let's take this a step further. We don't need to limit ourselves to 8 values we can simply allow as many values as we like by using var arg template arguments:</p>\n\n<pre><code>template&lt;int... Vals&gt;\nint drawNums()\n{\n static int result[] = {Vals...};\n static int i = -1;\n i++;\n return result[i % sizeof...(Vals)];\n}\n</code></pre>\n\n<hr>\n\n<p>Remember C is not the same language as C++. So pefer not to use C header files where eqivelent <strong>BUT</strong> correctly namespaced for C++ versions exist in C++</p>\n\n<pre><code>#include &lt;stdlib.h&gt;\n----\n#include &lt;cstdlib&gt; // Functions are placed in the `std` namespace.\n // Helps avoid collisions.\n</code></pre>\n\n<hr>\n\n<p>One of the obscure corner cases where C and C++ actually differ is the use of a void parameter.</p>\n\n<pre><code> func();\n func(void);\n</code></pre>\n\n<p>In C these have different meanings.<br>\nIn C++ they mean exactly the same thing. As a result in C++ we don't bother with the extra <code>void</code> parameter as it does not convey any extra meaning and is just fluff.</p>\n\n<p>Thus you're declarations for function pointers:</p>\n\n<pre><code> int (*f) (void)\n</code></pre>\n\n<p>That <code>void</code> has no menaing in this context. This is simpler to write (and more commonly written as):</p>\n\n<pre><code> int (*f)()\n</code></pre>\n\n<p>Though to be honest even this is rare. We would normally wrap this in a <code>std::function</code> object that allows us to pass other types (not just functions)</p>\n\n<pre><code> bool HighCard::Play( int (*f) (void), std::ostream&amp; os )\n</code></pre>\n\n<p>I would write like this:</p>\n\n<pre><code> bool HighCard::Play(std::function&lt;int()&gt; const&amp; action, std::ostream&amp; os)\n</code></pre>\n\n<p>Now I can pass a function pointer a functor or even a lambda.</p>\n\n<pre><code> highCard.Play([](){return 5;}, std::cout);\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-11T22:35:53.927", "Id": "242102", "ParentId": "242088", "Score": "1" } }, { "body": "<p>First, I suggest using a unit test framework. </p>\n\n<h1>Test Cases</h1>\n\n<p>You test multiple test cases in one function. Write a test in the format of \"Arrange Act Assert\". You should have a single act - a single call to <code>HighCard::Play</code> in each test. </p>\n\n<h1>Assert</h1>\n\n<p>You are asserting the output of the game. This makes the tests fragile because a change in the presentation will break tests.</p>\n\n<p>Separate logic from the presentation and test the logic. The tests will become shorter and clear.</p>\n\n<h1>Random</h1>\n\n<ul>\n<li><p>You should not have a test code on your production code.</p></li>\n<li><p>A way to handle random logic in tests is to replace it with mocks.</p></li>\n</ul>\n\n<h2><code>test_win</code> and <code>test_wildcard</code></h2>\n\n<p>Separate the logic of who is the winning card to another function like this <code>WinStatus whoWin(rank1,suit1,rank2,suit2,card2)</code>.</p>\n\n<p>Now, you can test <code>whoWin</code> and there are no calls to <code>rand</code>.Also, it creates documentation for the rules.</p>\n\n<h2>Retries tests</h2>\n\n<p>I see a few options here:</p>\n\n<ol>\n<li>Mock <code>rand</code> calls. Wrap the calls to <code>rand</code> with a class and use mock to return different values for each call. This is what you did but with mocks.</li>\n<li><p>Mock <code>takeCard</code>.\nThe following lines are the logic of taking a card from the deck:</p>\n\n<p><code>rank1 = f() % NUM_OF_CARDS + 1;<br>\nsuit1 = f() % 4 + 1;</code></p>\n\n<p>Use mock to return different values for each call. Having a Card class will help here.</p></li>\n<li><p>Mock the result of <code>whoWin</code>. You still call <code>rand</code> in tests but it doesn't affect anything.</p></li>\n</ol>\n\n<p>I prefer the second option because it tests more logic in a single test.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-12T05:15:05.250", "Id": "242117", "ParentId": "242088", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-11T17:26:38.210", "Id": "242088", "Score": "1", "Tags": [ "c++", "unit-testing", "random" ], "Title": "high card game implementation" }
242088
<h2>The Problem</h2> <p>I have a module with several sibling classes that share a method with a similar name. These methods receive the same basic arguments, however, for a number of the sibling classes the method in question can take different arguments that are irrelevant to the methods defined in its siblings. For example:</p> <pre class="lang-py prettyprint-override"><code>class ElectricKeyboard(Instrument): def __init__ (self): Instrument.__init__(self) def play (sheet_music: list, foot_pedal: bool = True): # play some music class ElectricGuitar(Instrument): def __init__ (self): Instrument.__init__(self) def play (sheet_music: list, foot_pedal: bool = True, guitar_pick: bool = True): # play some music class Kazoo(Instrument): def __init__ (self): Instrument.__init__(self) def play (sheet_music: list): # play some music </code></pre> <p>Above, we have three children of the <code>Instrument</code> class that are siblings. They all have a method, <code>play</code>, that takes a similar argument, however, <code>ElectricKeyboard.play</code> and <code>ElectricGuitar.play</code> take different additional keyword arguments relative to <code>Kazoo.play</code>, which takes none. </p> <p>Now imagine there exists a separate module where we have some calling context where the <code>guitar_pick</code> keyword argument happens to be defined. Something like this:</p> <pre class="lang-py prettyprint-override"><code># Import the Instrument parent class from instruments import ElectricGuitar, ElectricKeyboard, Kazoo # We have some external config file that encapsulates a concert object import concert_config # We have some local variables that could be useful guitar_pick, foot_pedal = True, False # We initialize all the instruments for the concert and store them in a list instruments = [Instrument.get_child(instrument)() for instrument in concert_config["instruments"]] # We then play the music (ignoring that this would play the same bar for each instrument sequentially rather than all at once) for bar in concert_config["sheet_music"]: for instrument in instruments: # Either of these three scenarios could occur in the body of the for loop instrument.play(bar) # We'd like to do this for the Kazoo instrument.play(bar, foot_pedal = foot_pedal) # Or this for the ElectricKeyboard instrument.play(bar, foot_pedal = foot_pedal, guitar_pick = guitar_pick) # Or this for the ElectricGuitar </code></pre> <p>The key here is that in the calling context, the instrument is considered generic; it could be an electric guitar, a keyboard, or a kazoo. We don't care what instrument we're playing, we just want to play it. However, to play it correctly, we want to give as much detail as possible – we would like to provide the values for <code>foot_pedal</code> and <code>guitar_pick</code>, when appropriate. In contrast, if we were to instead have the <code>Kazoo</code> class as our <code>instrument</code> we would not want to pass any additional arguments because they would not be useful or make sense for that instrument.</p> <h2>A Possible Solution</h2> <p>In thinking about how to manage this and preserve the existing architecture (this example is highly contrived relative to the actual application) I thought it might be useful to create a decorator that 'absorbs' the variable scope of the method's calling context (this could be the scope just outside of the method or the global scope). </p> <p>This is how it would work: Prior to executing the decorated function (i.e. the <code>play</code> method for the instrument), the decorator would <strong>1.</strong> retrieve a specified context (e.g. <code>locals()</code>), <strong>2.</strong> inspect the function signature to identify its parameters and <strong>3.</strong> search the specified context for variables that have the same name as the function parameters and, if found, pass them to the decorated function if they exist. Here's a decorator that does this:</p> <pre class="lang-py prettyprint-override"><code>import inspect from typing import Callable, Any class AbsorbContext (): """ A decorator that searches a specified context (e.g. locals() or globals()) for undefined arguments and passes them to the decorated function from the local contest if they are defined there (i.e. 'absorbs' them). """ def __init__ (self, context: dict = globals(), positional_only: bool = True, positional_or_keyword: bool = True, keyword_only: bool = True ): self.positional_only = positional_only self.positional_or_keyword = positional_or_keyword self.keyword_only = keyword_only self.context = context def __call__ (self, func: Callable[..., Any]): def absorb (*args, **kwargs): params = inspect.signature(func).parameters.values() if self.positional_only: absorbed_pos_args = () pos_only = [param.name for param in params if param.kind is inspect.Parameter.POSITIONAL_ONLY] args = tuple(self.context[arg] for arg in pos_only if arg in self.context) if self.positional_or_keyword: absorbed_pos_or_kwd_args = {} pos_or_kwd = [param.name for param in params if param.kind is inspect.Parameter.POSITIONAL_OR_KEYWORD] kwargs = dict(kwargs, **{arg: self.context[arg] for arg in pos_or_kwd if arg in self.context}) if self.keyword_only: absorbed_kwd_args = {} kwd_only = [param.name for param in params if param.kind is inspect.Parameter.KEYWORD_ONLY] kwargs = dict(kwargs, **{arg: self.context[arg] for arg in kwd_only if arg in self.context}) return func(*args, **kwargs) return absorb </code></pre> <p>This works and seems to achieved the desired behavior. Below is an example usage (if you're unfamiliar with the <code>/</code> and <code>*</code> syntax seen in function signature below, see this <a href="https://stackoverflow.com/questions/57848612/python-inspect-signature-shows-all-defined-positional-arguments-as-parameterk/61719220#61719220">answer</a>).</p> <h2>Example Usage</h2> <pre><code># Some Arguments a = 2 b = 3 c = 4 d = 5 @AbsorbContext(context = locals()) def func (a: int, b: int, /, c: int = 0, *, d: int = 1): return (a * b + c) * d func(a) # Returns 50 func(a, b) # Returns 50 func() # We can pass nothing and it will still evaluate correctly; returns 50 # ... </code></pre> <p>As long as we maintain the correct ordering for args <code>a</code> and <code>b</code> (the positional only arguments), the method will always return the correct value, <code>50</code>, given the parameters that are available for input in the calling context. This can also be thought of as defining the default argument values for a function in the calling context rather than in the function signature.</p> <pre class="lang-py prettyprint-override"><code>func(1, 2, 3, 4) # All new arguments, returns 20 func(1) # Modify a POSITION_ONLY argument, returns 35 func(d = 10) # Modify a KEYWORD_ONLY argument, returns 100 func(2, 3, c = 14) # Modify a POSITION_OR_KEYWORD argument, returns 100 func(2, 3, 14) # Modify a POSITION_OR_KEYWORD argument, returns 100 </code></pre> <p>Note that unlike in the example shown here, in general the definition of the function (e.g. <code>func</code>) will exist in a separate module from the one where the arguments are defined and the function is called. </p> <h2>The Question</h2> <p>This feels like a hack. While this seems to work I have some questions:</p> <ol> <li><p>Is there a way to get a similar behavior that does not require a decorator of this sort? It seems like this could be a weakness with the architecture I have chosen – are there any architectures that have been designed to solve this problem?</p></li> <li><p>Is there any obvious way this behavior could be exploited by a bad actor? Note that this software is not designed to run or be called over a network; it is reasonable to assume that all arguments will be defined by the user at runtime.</p></li> <li><p>In its current form, the context should be called in the same module that the decorated function is defined. Is there a way to make this more flexible? I think we might be able to solve this problem by calling <code>globals()</code>, but that seems inelegant.</p></li> </ol>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-11T22:23:32.330", "Id": "475107", "Score": "0", "body": "Please see [_What to do when someone answers_](https://codereview.stackexchange.com/help/someone-answers). I have rolled back Rev 4 → 3" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-11T22:24:02.833", "Id": "475108", "Score": "0", "body": "@SᴀᴍOnᴇᴌᴀ Gotcha, thanks!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-11T22:26:12.140", "Id": "475109", "Score": "0", "body": "feel free to re-add the words added to question two (i.e. _it is reasonable to assume that_) if you so desire" } ]
[ { "body": "<p>It definitely seems like a hack.</p>\n\n<ul>\n<li><p>A first smell is that changing the function signature by just renaming variables will break it.\nIf <code>a</code> is available in <code>locals()</code>, it has to match <code>a</code> in the function signature.\nEven just a capital <code>A</code> in either spot will break the behaviour.</p>\n\n<p>This requires you to change names in multiple locations if you only wanted to change it in one.</p></li>\n<li><p>Next, it is hard to follow and debug.\nIt is certainly very surprising behaviour to anyone just getting to know your code.</p>\n\n<p>Your functions return surprising results that no longer correspond to the <em>very arguments the caller provided</em>.\nInstead, they are influenced by global state and cannot be overridden:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code> # Some Arguments\n a = 2\n b = 3\n c = 4\n d = 5\n\n @AbsorbContext(context = locals())\n def func (a: int, b: int, /, c: int = 0, *, d: int = 1):\n return (a * b + c) * d\n\n print(func(1, 2, 1, 1)) # Expected to return 3, returns 50\n</code></pre></li>\n<li><p>Variable names like <code>a</code>, <code>b</code>, <code>c</code>, ... make sense now, but in a larger context, more elaborate variable names are needed.\nThese are then blocked for usage, and a person declaring new variables has to check <em>every decorated function</em> for collisions.</p>\n\n<p>Not only that, also <code>def</code> and <code>class</code> definitions have to be regarded, since these also bind to names.\nBuilt-ins can also collide, though function parameters shadowing built-ins is a terrible idea and rare.\nSame is true for <code>import *</code>: terrible idea in the first place, but <code>@AbsorbContext</code> turns it into proper chaos.</p>\n\n<p>Situations like this can arise (fails because <code>check_array</code> is a function):</p>\n\n<pre class=\"lang-py prettyprint-override\"><code> def check_array():\n pass\n\n # check_array = True # uncommenting works\n\n @AbsorbContext(context = locals())\n def func (a: int, check_array: bool, /, c: int = 0, *, d: int = 1):\n return (a * int(check_array) + c) * d\n</code></pre>\n\n<p><code>check_array</code> is a generic name which is easily imagined to be that of a function, or a function parameter.</p></li>\n<li>Providing <code>context=globals()</code> as a default argument to <code>__init__</code> will use <code>globals()</code> of the module where <code>AbsorbContext</code> is defined.\nThis will break behaviour if that class is imported, which you will probably be doing.\n<code>context</code> should not have a default argument.</li>\n<li><code>AbsorbContent</code> could have been a function and therefore shorter.\nDid you leverage <code>self</code> to access state?\nDecorator functions can do this through closure.</li>\n<li><p>Situations in which run-time should <em>definitely</em> error out are silently overridden:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code> # Some Arguments\n a = 2\n b = 3\n c = 4\n d = 5\n\n @AbsorbContext(context = locals())\n def func (a: int, b: int, /, c: int = 0, *, d: int = 1):\n return (a * b + c) * d\n\n print(func(1, 2, 1, 1, 1, 1, 1, 1, 1, 1)) # Expected to error out\n</code></pre>\n\n<p>Here, a <code>TypeError</code> for mismatched function arguments and parameters is expected, but it works and returns <code>50</code>.\nThis bug might not be found immediately, even though it should definitely fail-fast.</p></li>\n</ul>\n\n<hr>\n\n<p>In the spirit of your \"absorption\" approach, you could use <code>**kwargs</code> in <code>play</code> to collect (absorb) all unused keyword arguments which the function has no use for.\n<code>sheet_music</code> then remains as a mandatory positional argument in all cases:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>class Instrument:\n pass\n\n\nclass ElectricKeyboard(Instrument):\n def __init__ (self):\n Instrument.__init__(self)\n def play (self, sheet_music: list, foot_pedal: bool = True, **kwargs):\n print(\"Playing Keyboard\")\n # play some music\n\n\nclass ElectricGuitar(Instrument):\n def __init__ (self):\n Instrument.__init__(self)\n def play (self, sheet_music: list, foot_pedal: bool = True, guitar_pick: bool = True, **kwargs):\n print(\"Playing Guitar\")\n # play some music\n\n\nclass Kazoo(Instrument):\n def __init__ (self):\n Instrument.__init__(self)\n def play (self, sheet_music: list, **kwargs):\n print(\"Playing Kazoo\")\n # play some music\n\n\ninstruments = [ElectricGuitar(), ElectricKeyboard(), Kazoo()]\n\nfor instrument in instruments:\n instrument.play(\"sheet_music\", foot_pedal=True)\n instrument.play(\"sheet_music\")\n instrument.play(\"sheet_music\", guitar_pick=True)\n</code></pre>\n\n<p>Now, all those <a href=\"https://en.wikipedia.org/wiki/Duck_typing\" rel=\"nofollow noreferrer\">ducks</a> quack properly.</p>\n\n<hr>\n\n<p>Collecting <code>instruments</code> and then iterating over them calls for identical interfaces.\nThis is because lists are homogeneous.\nThey should contain items of identical type (think of a list of text files; you can safely call <code>.read()</code> on all of these).\nThis is another hint that the <em>sibling</em> approach might be off.</p>\n\n<p>Instead, you could look into <em>composition</em> and implement a <code>MusicGroup</code> class with <em>has-a</em> relations towards the instruments played by the musical group.\n<code>MusicGroup</code> then has methods like <code>play_guitars</code> to play all available guitars.\n<code>play_guitars</code> can have a specialized signature, which only makes sense for guitars.\nThen, you can give <code>MusicGroup</code> a <code>play</code> or maybe <code>play_all</code> method to call all <code>play_&lt;instrument&gt;</code> methods.\nThe <code>play_all</code> method would forward all required <code>**kwargs</code>, or better still, manually forward them to each specific function.</p>\n\n<p>Your inheritances and attempt to treat all siblings equally might be a case of <a href=\"https://en.wikipedia.org/wiki/Circle%E2%80%93ellipse_problem\" rel=\"nofollow noreferrer\">the Circle-Ellipse problem</a>.\nYour instruments certainly all fulfill the <em>is-a</em> relationship towards <code>Instrument</code>, but that does not necessarily warrant inheritance if their behaviours differ too much.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-11T22:11:19.610", "Id": "475106", "Score": "0", "body": "Thanks this is a very nice overview of some problems with the concept. I'll continue to think on the structure of the sibling classes – this was a fun experiment but it definitely won't make it into the library!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-11T20:37:57.987", "Id": "242096", "ParentId": "242089", "Score": "3" } } ]
{ "AcceptedAnswerId": "242096", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-11T18:00:44.037", "Id": "242089", "Score": "2", "Tags": [ "python", "design-patterns", "scope" ], "Title": "Retrieving unspecified function arguments from external context (scope)" }
242089
<p>I'm in the process of creating my first web app using node with mongodb on the backend. I could use some opinions on the schemas/models I've set up.</p> <p>I have three schemas: User, Pet, Food. Here's the general relationship of them:</p> <p>Users have pets -> Pets have a list of ingredients and list of favorite foods -> Food has list of ingredients.</p> <p>Here's my userSchema:</p> <pre><code>const userSchema = new mongoose.Schema({ name: { type: String, required: true, trim: true, }, password: { type: String, required: true, trim: true, minlength: 8, validate(value) { if (value.toLowerCase().includes('password')) { throw new Error('password contains password'); } }, }, email: { type: String, unique: true, required: true, trim: true, lowercase: true, validate(value) { if (!validator.isEmail(value)) { throw new Error('Email is invalid'); } }, }, tokens: [ { token: { type: String, required: true, }, }, ], }); userSchema.virtual('pets', { ref: 'Pet', localField: '_id', // associated with the _id of the user foreignField: 'owner', // the name of the field on the other object that creates the relationship, which we set to the owner }); const User = mongoose.model('User', userSchema); </code></pre> <p>Here's my pet model:</p> <pre><code>const Pet = mongoose.model('Pet', { name: { type: String, required: true, trim: true, }, badIngredients: [ [ { Ingredient: { type: String, }, }, ], ], favoriteFoods: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Food' }], owner: { type: mongoose.Schema.Types.ObjectId, required: true, ref: 'User', // reference to the User model }, }); </code></pre> <p>and finally the food model:</p> <pre><code>const Food = mongoose.model('Food', { name: { type: String, required: true, trim: true, }, brand: { type: String, required: true, trim: true, }, flavor: { type: String, required: true, trim: true, }, ingredients: [ { type: String, required: true, trim: true, }, ], imagePath: { type: String, required: true, trim: true, }, }); </code></pre> <p>I'm unsure if it would be a good idea to have some kind of relationship between the pet's list of ingredients and the list of ingredients with the food. The general idea is a user can select ingredients that their pet is allergic to, and it will filter out the list of foods for them that DON'T contain those ingredients. They can then assign favorite foods to their pet.</p> <p>I could also use some advice if using the <code>userSchema.virtual</code> property for pets is better than simply having a property on my user that is a list of pets.</p> <p>The food itself will be static data stored somewhere.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-11T19:24:07.237", "Id": "242091", "Score": "1", "Tags": [ "javascript", "node.js", "mongodb", "mongoose" ], "Title": "Modeling mongoose schemas" }
242091
<p>I have a class <code>Main</code> that uses <code>fn(cls, ...)</code> methods from several modules; they're used exclusively by <code>Main</code>. Each module is 500-1000 lines long (without docstrings); the idea is to "break up" various <code>Main</code> methods to ease debugging and readability, instead of packing them all into one class and make a 9000+ lines file. </p> <p>Everything functions properly. However, a core asset is sacrificed: <em>introspection</em>; <code>help(Main.method)</code>, or even <code>Main.method()</code> are no longer an option. The goal is thus as follows: keep methods in separate files, but have them behave just like regular class methods. </p> <hr> <p><strong>My approach</strong>: 'pack' module methods into classes, then module classes into a 'unifier' class, then inherit the unifier in <code>Main</code>. Code below. Points to note:</p> <ul> <li>No overriding issues; <code>Module</code> classes only hold methods, their <code>__init__</code> is as minimal as shown</li> <li>No attributes, per above, and thus same for <code>Unifier</code></li> <li>No duplicate attributes / methods; all methods are uniquely named (and no attrs to duplicate)</li> </ul> <hr> <p><strong>Question</strong>: any caveats to note? What can be done better? Some particular concerns are:</p> <ol> <li>Is <code>pickle.dump</code>, <code>.load</code> affected? I pickle only non-method <code>Main</code> attributes.</li> <li>Is a dynamic <code>to_unify</code> reliable? I suppose 'it depends' on how all involved classes change along.</li> <li>Any metaclass intricacies from the inheritance scheme?</li> </ol> <hr> <p><strong>Code</strong>: <a href="https://repl.it/repls/StrongLeafyWireframe" rel="nofollow noreferrer">live demo</a></p> <pre class="lang-py prettyprint-override"><code># module_a.py class ModuleA(): def __init__(self): super(ModuleA, self).__init__() def woof(self): """I'm a dog""" self.do_woofing() # dependency on ModuleB def do_dooting(self): print("DOOT") </code></pre> <pre class="lang-py prettyprint-override"><code># module_b.py class ModuleB(): def __init__(self): super(ModuleB, self).__init__() def doot(self): """I'm a skeleton""" self.do_dooting() # dependency on ModuleA def do_woofing(self): print("WOOF") </code></pre> <pre class="lang-py prettyprint-override"><code># main_module.py from module_a import ModuleA from module_b import ModuleB to_unify = ModuleA, ModuleB # can add modules later class Unifier(*to_unify): def __init__(self): super(Unifier, self).__init__() class Main(Unifier): def __init__(self, *args, **kwargs): super().__init__() # ... </code></pre> <pre class="lang-py prettyprint-override"><code># main.py from main_module import Main m = Main() m.woof() m.doot() help(m.doot) </code></pre> <pre><code>WOOF DOOT Help on method doot in module module_b: doot() method of main_module.Main instance I'm a skeleton </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-11T21:45:40.877", "Id": "475104", "Score": "4", "body": "I think this is symptom of other design problem (\"god class\"). If you have 9000+ lines worth of methods on one class definition then probably that class has too many responsibilities." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-11T21:47:31.110", "Id": "475105", "Score": "0", "body": "@wim Agreed this is typically true, but it's the main class within a deep learning framework, where official implementations have similar lengths (unavoidably). Also a large fraction of these lines would be documentation - actual code's 5-6k." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-12T06:33:26.410", "Id": "475119", "Score": "0", "body": "(`actual code's 5-6k [of] 9000+ lines` That is not what I would consider a *large fraction* with \"javadoc-style documentation\" - with docstrings (introspectable) and the odd comment, it's a start.)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-12T06:36:16.847", "Id": "475120", "Score": "4", "body": "If you want a review here, please a) be sure you are willing and in a position to put code from your project [under Creative Commons](https://codereview.stackexchange.com/help/licensing) and b) present actual code from your project." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-14T19:20:42.520", "Id": "475473", "Score": "0", "body": "Correction, ~2500 lines of code in the class." } ]
[ { "body": "<p>Hi OverLordGoldDragon,</p>\n\n<p>Why don't you define your methods as functions in your submodules and attach them to your main class afterwards?</p>\n\n<pre class=\"lang-py prettyprint-override\"><code># module_a.py\n\ndef woof(self):\n \"\"\"I'm a dog\"\"\"\n self.do_woofing() \n\ndef do_dooting(self):\n print(\"DOOT\")\n</code></pre>\n\n<pre class=\"lang-py prettyprint-override\"><code># module_b.py\n\ndef doot(self):\n \"\"\"I'm a skeleton\"\"\"\n self.do_dooting()\n\ndef do_woofing(self):\n print(\"WOOF\")\n</code></pre>\n\n<pre class=\"lang-py prettyprint-override\"><code>import module_a, module_b # I know some people won't like this form of import\n\nclass Main:\n def __init__(self, *args, **kwargs):\n # do whatever you need to do to initialize your instance\n pass\n\n woof = module_a.woof\n do_dooting = module_a.do_dooting\n doot = module_b.doot\n do_woofing = module_b.do_woofing\n</code></pre>\n\n<pre class=\"lang-py prettyprint-override\"><code># main.py\nfrom main_module import Main\n\nm = Main()\nm.woof()\nm.doot()\nhelp(m.doot)\n</code></pre>\n\n<p>I want to highlight the fact that <code>help()</code> is supposed to be used at the interactive prompt not in a script.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-12T19:25:05.873", "Id": "475222", "Score": "0", "body": "This indeed works, though I had a more complete answer planned before you posted, just couldn't post earlier" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-12T06:00:47.690", "Id": "242119", "ParentId": "242092", "Score": "0" } }, { "body": "<p>This is accomplished more elegantly and minimally by:</p>\n\n<ol>\n<li>Fetching methods from relevant modules</li>\n<li>Assigning these methods to the class, programmatically</li>\n</ol>\n\n<p>We can further ensure that methods are intended for the class by checking whether <code>self</code> is in the input signature, and can omit specific methods by name. Below accomplishes this:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>from inspect impport getfullargspec\nfrom package_a import module_1a, module_2a\nimport package_b.module_1b\n\nclass Unifier():\n def __init__(self):\n pass\n\nargs = lambda x: getfullargspec(x).args\nmodules = (module_1a, module_2a, module_1b) # extendable\nto_exclude = ['_method_to_omit']\n\nfor module in modules:\n mm = get_module_methods(module)\n for name, method in mm.items():\n if name in to_exclude or 'self' not in args(method):\n continue\n setattr(Unifier, name, method)\n</code></pre>\n\n<p>Now <code>Main</code>, after inheriting <code>Unifier</code>, will have all <code>fn(self, ...)</code> methods from <code>module_1a, module_2a, module_1b</code> (except <code>def _method_to_omit</code>).</p>\n\n<ul>\n<li><code>get_module_methods</code> <a href=\"https://codereview.stackexchange.com/questions/242109/get-methods-in-module-python/#answer-242148\">source</a></li>\n<li>Method class assignment ideas derived from <a href=\"https://stackoverflow.com/questions/61739682/bound-method-class-fn-vs-bound-method-fn\">this Q&amp;A</a></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-12T19:25:02.587", "Id": "242152", "ParentId": "242092", "Score": "0" } } ]
{ "AcceptedAnswerId": "242152", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-11T19:25:39.153", "Id": "242092", "Score": "-1", "Tags": [ "python", "object-oriented", "design-patterns", "inheritance" ], "Title": "Multiple inheritance of class broken up into modules" }
242092
<p>i try to make an app for a mobile store</p> <pre><code>class Mobile(models.Model): model= models.CharField(max_length=30,unique=True) created_at = models.DateTimeField(auto_now_add=True) edited_at = models.DateTimeField(auto_now=True) def __str__(self): return self.name class Storage(models.Model): model = models.ForeignKey(Mobile,on_delete=models.CASCADE,related_name='models') IMEI = models.CharField(max_length=60) company_name = models.CharField(max_length=50) quantity = models.IntegerField(default=0) buying_price = models.IntegerField(default=1) cost_price = models.IntegerField(default=1) odd_price = models.IntegerField(default=0) mul_price = models.IntegerField(default=0) second_hand = models.BooleanField(default=True) created_at = models.DateTimeField(auto_now_add=True) edited_at = models.DateTimeField(auto_now=True) def __str__(self): return self.IMEI </code></pre> <p>should i change it to create a new table(model) from <code>Storage</code> named <code>Prices</code> to normalizing and performance or its fine ?thanks </p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-11T22:34:12.400", "Id": "242101", "Score": "1", "Tags": [ "python", "python-3.x", "django" ], "Title": "normalizing django models" }
242101
<p>When keeping track of various pieces of information in a variable when using a dispatch group, I've fallen into a pattern of protecting the variable using a serial queue, and then ultimately notifying on that queue to do something with the final value. Is there a more idiomatic way to protect things?</p> <p>Here's an example of what I mean that can be run in a Playground:</p> <pre><code>import Foundation func uploadAll() { func mockUpload(_ delay: TimeInterval, _ queue: DispatchQueue = DispatchQueue(label: "mockUpload", attributes: .concurrent), block: @escaping () -&gt; Void) { let deadline = DispatchTime.now() + delay queue.asyncAfter(deadline: deadline, execute: block) } let resultQueue = DispatchQueue(label: "resultQueue") var results: [Int] = [] let group = DispatchGroup() for i in 0..&lt;5 { group.enter() mockUpload(TimeInterval(Int.random(in: 1...3))) { resultQueue.async { results.append(i) group.leave() } } } group.notify(queue: resultQueue) { print("results: \(results)") DispatchQueue.main.async { // And maybe do something on the main queue... } } } uploadAll() import PlaygroundSupport PlaygroundPage.current.needsIndefiniteExecution = true </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-11T23:26:17.897", "Id": "242104", "Score": "2", "Tags": [ "swift", "grand-central-dispatch" ], "Title": "Idiomatic way to mutate array while using Swift dispatch groups" }
242104
<p>This is a simple command line interface program that just keeps track of duration spent on multiple tasks.</p> <p>Any areas of improvements are welcomed to be pointed out.</p> <pre><code>import json import datetime dt = datetime.datetime td = datetime.timedelta def encode_time(t): if isinstance(t, dt): return { '_type': 'datetime', 'year': t.year, 'month': t.month, 'day': t.day, 'hour': t.hour, 'minute': t.minute, 'second': t.second } elif isinstance(t, td): return { '_type': 'timedelta', 'days': t.days, 'seconds': t.seconds, 'microseconds': t.microseconds } return t def decode_time(t): if '_type' in t: data_type = t['_type'] del t['_type'] if data_type == 'datetime': return dt(**t) elif data_type == 'timedelta': return td(**t) return t def display_pending(): &quot;&quot;&quot; pretty prints the pending dictionary. :return: None &quot;&quot;&quot; print('\n') if pending: max_len = max([len(key) for key in pending.keys()]) print('Pending Activities:') print('-'*40) else: max_len = 0 print('No pending data.') counter = 0 for key, value in pending.items(): duration_so_far = (dt.now() - value) seconds = duration_so_far.seconds days = duration_so_far.days hours = seconds // 3600 minutes = (seconds // 60) % 60 s = 's' if days &gt; 1 else '' days = f'{days} Day{s} ' if days &gt; 0 else '' s = 's' if hours &gt; 1 else '' hours = f'{hours} Hour{s} ' if hours &gt; 0 else '' s = 's' if minutes &gt; 1 else '' minutes = f'{minutes} Min{s} ' if minutes &gt; 0 else '' seconds = f'{seconds} Seconds' if seconds &lt; 60 else '' print(f'[{counter}] {key.capitalize():{max_len}} | {value}') # Key and start time. max_len += 4 # Adding 4 to max_len to make sure this line is aligned with the one above it. print(f'{&quot;.&quot; * max_len:{max_len}} | {days}{hours}{minutes}{seconds}\n') # Duration so far. print('-' * 40) max_len -= 4 # Avoiding mutating max_len. counter += 1 def display_durations(): &quot;&quot;&quot; Pretty prints the durations dictionary. :return: None &quot;&quot;&quot; print('\n') counter = 0 if durations: max_len = max([len(key) for key in durations.keys()]) print('Durations: ') print('_' * 40) else: max_len = 0 print('No durations data') for key, value in durations.items(): print(f'[{counter}] {key.capitalize():{max_len}} | {value}') print('-' * 40) counter += 1 pending = {} durations = {} # Reading data from pending.json try: with open('pending.json', 'r') as pending_json: pending = json.load(pending_json, object_hook=decode_time) s = 's' if len(pending) &gt; 1 else '' print(f'{len(pending)} pending item{s} loaded from disk') except FileNotFoundError: print(' &quot;pending.json&quot; was not found, creating.') open('pending.json', 'x').close() except json.decoder.JSONDecodeError: print('pending.json is empty...') # Reading data from durations.json try: with open('durations.json', 'r') as durations_json: durations = json.load(durations_json, object_hook=decode_time) s = 's' if len(durations) &gt; 1 else '' print(f'{len(durations)} duration item{s} loaded from disk') except FileNotFoundError: print(' &quot;durations.json&quot; was not found, creating.') open('durations.json', 'x').close() except json.decoder.JSONDecodeError: print('durations.json is empty...') if pending: display_pending() if durations: display_durations() # Acquiring user input. while True: activity = input('\n&gt;&gt;&gt; ').lower() now = dt.now() start_time = pending.get(activity, None) if activity == 'quit': print('Exiting.') break elif activity == '': continue if activity in pending: duration = now - start_time print(f'&quot;{activity}&quot; ended. Duration: {duration}') durations[activity] = durations.get(activity, td(0)) + duration # Record duration of activity. del pending[activity] # Delete activity from pending list to confirm that it's completed. continue elif activity == 'man': activity = input('Activity Name: ') activity_duration = {} # Get num of days, hours, etc.. of manually eneterd activity. for parameter in ['days', 'hours', 'minutes', 'seconds', 'microseconds']: while True: i = input(f'{parameter.capitalize()}: ') if i.isnumeric(): activity_duration[parameter] = int(i) break elif i == '': activity_duration[parameter] = 0 break add_minus = input('Add / Minus: ').lower() if add_minus == 'add': durations[activity] = durations.get(activity, td(0)) + td(**activity_duration) elif add_minus == 'minus': durations[activity] = durations.get(activity, td(0)) - td(**activity_duration) display_durations() continue elif activity == 'del': activity = input('Delete: ') if activity == 'all': confirmed = input('Delete Everything? y/n ') if confirmed == 'y': pending.clear() durations.clear() print('Data Cleared.') continue key_index = [[None, None]] # A list of index, key pairs for each key in pending or durations dictionaries. # If the activity the user wants to delete is a number, treat it as an index, # Unless the activity is an entry in either pending/durations lists: if activity.isnumeric() and activity not in set(list(pending.keys()) + list(durations.keys())): is_numeric = True activity = int(activity) wanted_list = input('Delete From Pending/Durations? p/d: ') if wanted_list == 'd': key_index = [(index, key) for index, key in enumerate(durations.keys())] elif wanted_list == 'p': key_index = [(index, key) for index, key in enumerate(pending.keys())] # If no list specified then delete from durations or pending according to index given. else: if activity &lt;= len(durations) - 1: key_index = [(index, key) for index, key in enumerate(durations.keys())] elif activity &lt;= len(pending) - 1: key_index = [(index, key) for index, key in enumerate(pending.keys())] for index, key in key_index: if index == activity: break activity = key else: is_numeric = False if activity in pending: not_in_pending = False del pending[activity] print(f'&quot;{activity.capitalize()}&quot; deleted from pending') else: not_in_pending = True if activity in durations: not_in_durations = False del durations[activity] print(f'{activity.capitalize()} deleted from durations') else: not_in_durations = True if not_in_pending and not_in_durations: if is_numeric: print('No data') else: print('Key Not Found') continue elif activity == 'data': display_pending() display_durations() continue elif activity == 'help': print(''' Enter activity name for it to be started. Enter the same name again for it to be ended and record it's duration. Commands: man: manually edit a duration del: delete an entry from pending activities and/or duration data: show currently pending activities and duration records quit: exit program and save edits. ''') continue pending[activity] = now print(f'&quot;{activity.capitalize()}&quot; started on: {now}') print(' Writing updated data to disk.') if len(pending) &gt; 0: with open('pending.json', 'w') as pending_json: json.dump(pending, pending_json, default=encode_time, indent=2) else: # So that json doesn't dump an empty dictionary symbol: {} to the file. open('pending.json', 'w').close() if len(durations) &gt; 0: with open('durations.json', 'w') as durations_json: json.dump(durations, durations_json, default=encode_time, indent=2) else: open('durations.json', 'w').close() print(' Data updated.') exit_confirm = input('Press Enter To Exit...') <span class="math-container">```</span> </code></pre>
[]
[ { "body": "<ul>\n<li><p>Not a fan of all your single or double letter variable names. Please write out variables like <code>time</code>, <code>datetime</code> and <code>timedelta</code>.</p>\n\n<p>However I do think <code>s</code> is more readable than a written out variable name.</p></li>\n<li><p>I would prefer it if <code>decode_time</code> copied <code>t</code> before mutating it. This makes your code easier to use as there are no side effects.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>t = t.copy()\ndata_type = t.pop('_type')\n</code></pre></li>\n<li><p>You can change the <code>if</code>s in <code>decode_time</code> to use a dictionary to make the code easier to extend.</p>\n\n<p>If you have more than two data types then the dictionary will allow you to reduce duplicate code.</p>\n\n<p>You can use either of the following based on your preference.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>DECODES = {\n 'datetime': datetime.datetime,\n 'timedelta': datetime.timedelta,\n}\n</code></pre>\n\n<pre class=\"lang-py prettyprint-override\"><code>try:\n fn = DECODES[data_type]\nexcept KeyError:\n pass\nelse:\n return fn(**t)\n</code></pre>\n\n<pre class=\"lang-py prettyprint-override\"><code>return DECODES.get(data_type, lambda **kwargs: kwargs)(**t)\n</code></pre></li>\n<li><p>You kinda just gave up on seconds in <code>display_pending</code>. You've not calculated how many seconds it would need nor have you adjusted for when it's 1.</p>\n\n<p>To reduce the amount of duplication you can use a fairly simple for loop and a dictionary. We can build the dictionary with the existing code to build the variables. If we assign the values to the name to print, we can iterate over the dictionary getting all the information needed to display each unit.</p>\n\n<p>With some carefully placed assignments we can exploit the fact that dictionaries are sorted and have the same output you currently have.</p>\n\n<p>Additionally we can use a comprehension for some sugar to filter missing units.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>duration = {'Day': duration_so_far.days}\nremainder, seconds = divmod(duration_so_far.seconds, 60)\nduration['Hour'], duration['Minute'] = divmod(remainder, 60)\nduration['Second'] = seconds\n\ntime = ' '.join(\n f'{v} {k}{\"s\" if v != 1 else \"\"}'\n for k, v in duration.items()\n if v\n)\n\n...\n\nprint(f'{\".\" * max_len:{max_len}} | {time}\\n')\n</code></pre></li>\n<li><p>I would recommend toning down the amount of <code>print</code>s you have. These have side effects like deleting the type in <code>decode_time</code>. This makes your code harder to:</p>\n\n<ul>\n<li>Test - now you need to wrap <code>sys.std.out</code> for basic functions.</li>\n<li>Understand - others now have to second guess each and every one of your functions. This is because you've done it once and not been explicit about it, what's to stop you from doing it twice?</li>\n<li>Maintain - refactoring your code to keep the same output is more challenging without a complete rewrite.</li>\n</ul></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-12T07:03:53.983", "Id": "475123", "Score": "0", "body": "The problem with `datetime` is its alternatives. `from datetime import datetime` will be confusing, since now the `datetime` class takes the place of what is usually the `datetime` module. This leaves two sensible, as in unambiguous/clear, ways. Either `import datetime` and call `datetime.datetime` everywhere, or the somewhat [widespread short verion `from datetime import datetime as dt`](https://github.com/search?q=%22from+datetime+import+datetime+as+dt%22&type=Code). Subjective, but the latter is useful (like `np` to `numpy`)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-12T09:47:36.643", "Id": "475140", "Score": "1", "body": "@AlexPovel Yeah no, consistent code fixes that problem." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-12T03:09:31.693", "Id": "242112", "ParentId": "242107", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-12T01:38:21.740", "Id": "242107", "Score": "4", "Tags": [ "python", "json" ], "Title": "Time Tracker using JSON" }
242107
<p>A common use for Keras LSTM layers is to generate text. There are <a href="https://machinelearningmastery.com/text-generation-lstm-recurrent-neural-networks-python-keras/" rel="nofollow noreferrer">many examples</a> showing you how to do it.</p> <p>The usual method is to convert the text into a sequence of tokens and then slice up the sequence into overlapping windows which is used as inputs and the windows following tokens are the outputs.</p> <p>So if your token sequence is of length <code>i</code> and the length of each window is <code>j</code>, the input data would have the dimensions <code>(i, j)</code>. The output data would have the dimensions <code>(i)</code>. But then you also have to one hot encode the data. So if the number of unique tokens is <code>k</code>, the input gets the dimensions <code>(i, j, k)</code> and the output <code>(i, k)</code>.</p> <p>This is way to much data to fit in memory. So you have to load it iteratively, using a generator. Here is my generator that does that:</p> <pre><code>class OneHotGenerator(Sequence): def __init__(self, seq, batch_size, win_size, vocab_size): self.seq = seq self.batch_size = batch_size self.win_size = win_size self.vocab_size = vocab_size def __len__(self): n_windows = len(self.seq) - self.win_size return int(np.ceil(n_windows / self.batch_size)) def __getitem__(self, i): base = i * self.batch_size # Fix running over the dge. n_windows = len(self.seq) - self.win_size batch_size = min(n_windows - base, self.batch_size) X = np.zeros((batch_size, self.win_size, self.vocab_size), dtype = np.bool) Y = np.zeros((batch_size, self.vocab_size), dtype = np.bool) for i in range(batch_size): for j in range(self.win_size): X[i, j, self.seq[base + i + j]] = 1 Y[i, self.seq[base + i + self.win_size]] = 1 return X, Y </code></pre> <p>Meant to be used like this:</p> <pre><code>gen = OneHotGenerator(seq, batch_size, win_size, vocab_size) model.fit_generator(generator = gen, steps_per_epoch = len(seq) // batch_size, ...) </code></pre> <p>where <code>seq</code> is the sequence of tokens. The code works (I think), but I'm not happy with it for a few reasons:</p> <ul> <li>Windowing a sequence and converting it to one hot vectors seem like a very common use case. There should be something in Keras that can do what I want so I don't have to write the code myself.</li> <li>I haven't double-checked all indexing operations. There may be some unhandled edge cases.</li> <li>My <code>__getitem__</code> code doesn't seem to be very efficient. It seem to slow down training quite a bit.</li> <li>The code doesn't handle different step sizes (the amount of overlap between windows) or any edge cases.</li> </ul> <p>So what I want to know is if there is a better way to do what I want? If it isn't can my code be improved?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-12T02:14:25.997", "Id": "475114", "Score": "0", "body": "Your example doesn't actually show usage, all it shows is that variables can be passed to functions. Usage would be using `len(gen) # ???` and `gen[1] # ???`, or `for foo in gen:`." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-12T01:46:12.013", "Id": "242108", "Score": "1", "Tags": [ "python", "neural-network", "keras", "lstm" ], "Title": "Lazy loading generator for training a Keras network" }
242108
<p>Goal: extract methods/functions <em>defined in module</em>. This excludes:</p> <ol> <li>Imports</li> <li>Lambda methods</li> <li>Magic methods</li> <li>Builtin methods</li> <li>Class methods</li> <li>Classes</li> <li>Non-original definitions (i.e. function assignments, <code>alt_name = orig_fn</code>)</li> </ol> <p>My approach + test below. Any room for improvement, or false positives/negatives? (In particular I wonder if we can get away without typechecks, e.g. <code>isinstance(method, types.LambdaType)</code>)</p> <hr> <p><strong>Code</strong>: <a href="https://repl.it/repls/LittleFantasticAssemblylanguage" rel="nofollow noreferrer">live demo</a></p> <pre class="lang-py prettyprint-override"><code>import utils def get_module_methods(module): def is_module_function(obj): return ('&lt;function' in str(obj) and module.__name__ in getattr(obj, '__module__', '')) def not_lambda(obj): return not ('&lt;lambda&gt;' in getattr(obj, '__qualname__', '')) def not_magic(obj): s = getattr(obj, '__name__', '').split('__') return (len(s) &lt; 2) or not (s[0] == s[-1] == '') def not_duplicate(name, obj): return name == getattr(obj, '__name__', '') def cond(name, obj): return (is_module_function(obj) and not_lambda(obj) and not_magic(obj) and not_duplicate(name, obj)) objects = {name: getattr(module, name) for name in dir(module)} m_methods = {} for name, obj in objects.items(): if cond(name, obj): m_methods[name] = obj return m_methods mm = get_module_methods(utils) _ = [print(k, '--', v) for k, v in mm.items()] </code></pre> <hr> <p><strong>Test</strong>:</p> <pre class="lang-py prettyprint-override"><code># utils.py import random import numpy as np from inspect import getsource def fn1(a, b=5): print("wrong animal", a, b) class Dog(): meow = fn1 def __init__(self): pass def bark(self): print("WOOF") d = Dog() barker = d.bark mewoer = d.meow A = 5 arr = np.random.randn(100, 100) def __getattr__(name): return getattr(random, name, None) magic = __getattr__ duplicate = fn1 _builtin = str lambd = lambda: 1 </code></pre> <pre class="lang-py prettyprint-override"><code># main.py import utils # def get_module_methods(): ... mm = get_module_methods(utils) _ = [print(k, '--', v) for k, v in mm.items()] </code></pre> <pre class="lang-py prettyprint-override"><code>fn1 -- &lt;function fn1 at 0x7f00a7eb2820&gt; </code></pre> <hr> <p><strong>Edit</strong>: additional test case for a lambda surrogate:</p> <pre class="lang-py prettyprint-override"><code>import functools def not_lambda(): return 1 functools.wraps(lambda i: i)(not_lambda).__name__ </code></pre> <p>Code in question and answer catch <code>not_lambda</code> as a <code>lambda</code> - false positive.</p>
[]
[ { "body": "<ul>\n<li>Not a fan of all these redundant functions.</li>\n<li><p>Use equality for equality and <code>in</code> for in.</p>\n\n<ul>\n<li><code>'&lt;function' in str(obj)</code> -> <code>str(obj).startswith('&lt;function')</code></li>\n<li><code>module.__name__ in ...</code> -> <code>module.__name__ == ...</code></li>\n<li><code>not ('&lt;lambda&gt;' in ...)</code> -> <code>'&lt;lambda&gt;' not in ...</code> -> <code>'&lt;lambda&gt;' != ...</code></li>\n</ul>\n\n<p><br>\nLets play a game of what if:</p>\n\n<ul>\n<li>What if <code>foo.fn</code> is copied to <code>foo.bar.fn</code>.</li>\n<li>What if someone built a function from a lambda so they changed the name to <code>fn_from_&lt;lambda&gt;</code>.</li>\n</ul>\n\n<p><br>\nYeah, let's stick to using <code>==</code> for equals.</p></li>\n<li><p>Why is there a dictionary comprehension when the for after it consumes it?</p>\n\n<p>This is just a waste of memory.</p></li>\n<li><p>like with the dictionary compression this is a waste of memory. Additionally it's normally easier to work from a plain for as you can use assignments. </p>\n\n<pre class=\"lang-py prettyprint-override\"><code>_ = [print(k, '--', v) for k, v in mm.items()]\n</code></pre></li>\n</ul>\n\n<pre class=\"lang-py prettyprint-override\"><code>import utils\n\n\ndef get_module_methods(module):\n output = {}\n for name in dir(module):\n obj = getattr(module, name)\n obj_name = getattr(obj, '__name__', '')\n if (str(obj).startswith('&lt;function') # Is function\n and '&lt;lambda&gt;' != obj_name # Not a lambda\n and module.__name__ == getattr(obj, '__module__', '') # Same module\n and name == obj_name\n and not ( # Dunder\n obj_name.startswith('__')\n and obj_name.endswith('__')\n and len(obj_name) &gt;= 5\n )\n ):\n output[name] = obj\n return output\n\n\nmm = get_module_methods(utils)\nfor k, v in mm.items():\n print(k, '--', v)\n</code></pre>\n\n<p>Lets play another game of what if:</p>\n\n<ul>\n<li>What if I have a class that's <code>__str__</code> returns <code>'&lt;function...'</code>?</li>\n<li><p>What if someone built a function from a lambda so changed the <code>__name__</code>?</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>import functools\nfunctools.wraps(lambda i: i)(...).__name__\n</code></pre></li>\n</ul>\n\n<blockquote>\n <p>In particular I wonder if we can get away without typechecks</p>\n</blockquote>\n\n<p>No.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-12T14:27:26.990", "Id": "475162", "Score": "1", "body": "Thanks for the analysis. Valid loopholes in last two bullets, but the answer doesn't address them; I suppose a typecheck addresses the first, but how would one reliably identify a lambda?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-12T14:33:45.670", "Id": "475163", "Score": "1", "body": "To address some points: (1) I don't see the problem with \"`foo.fn` is copied to `foo.bar.fn`\"; (2) `'<lambda>' != ...` can't tell how this is better than `'<lambda>' not in`; (3) \"waste of memory\" - it's for readability, and their memory use is negligible (and garbage-collected); (4) `# Same module` not necessarily; if in PYTHONPATH, a package level can be bypassed, e.g. `from a import b` -> `import b`, but this has its own problems, and I agree with your preference for `==` here; still worth a mention." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-12T14:42:00.987", "Id": "475164", "Score": "0", "body": "The answer to your first question is in _your question_. (1) It's a bug (2) Please read the bullet point again. `fn_from_<lambda>` is _not_ a lambda. (3) Yeah, that's not more readable." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-12T16:00:16.970", "Id": "475186", "Score": "0", "body": "(2) I know, so _how do we tell_ if it isn't? Your code thinks it is, just like mine." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-12T16:09:44.097", "Id": "475191", "Score": "0", "body": "@OverLordGoldDragon I have already answered that off-topic question." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-12T16:30:33.190", "Id": "475197", "Score": "2", "body": "No, you haven't - and your answer stands as incomplete by your own assessment. Maybe I'll still 'accept' it as a net-positive, but the shortcomings should be supposedly easy to correct." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-12T17:23:30.100", "Id": "475203", "Score": "1", "body": "To clarify, I see how `'<lambda> != ` works - my question concerns not the running point \"(2)\", but \"how to not filter a trojan horse\" (e.g. functools's). Dedicated a question [here](https://stackoverflow.com/questions/61758005/how-to-detect-a-lambda-in-python)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-12T17:33:21.077", "Id": "475207", "Score": "0", "body": "@OverLordGoldDragon Please stop harassing me." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-12T18:13:38.663", "Id": "475211", "Score": "2", "body": "I've done nothing to harass you." } ], "meta_data": { "CommentCount": "9", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-12T04:01:17.457", "Id": "242114", "ParentId": "242109", "Score": "2" } }, { "body": "<h3>pyclbr</h3>\n\n<p>The standard library includes the <code>pyclbr</code> module, which provides functions for building a module browser. <code>pyclbr.readmodule_ex()</code> returns a tree of nested dicts with the functions (<code>def</code>statements) and classes (<code>class</code> statements) in a module. So you just need to check the top level dict for items of class <code>pyclbr.Function</code>.</p>\n\n<p>Note that <code>readmodule_ex</code> takes the name of the module (a str), not the actual module.</p>\n\n<p>Just tested this, and it prints out imported functions and dunder functions as well, so those need to be filtered out.</p>\n\n<pre><code>import pyclbr\n\nmodule = 'tutils'\n\nfor k,v in pyclbr.readmodule_ex(module).items():\n if ( isinstance(v, pyclbr.Function) \n and v.module==module\n and not v.name.startswith('__')):\n print(f\"{v.name} -- {v.file} at {v.lineno}\")\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-12T15:58:24.310", "Id": "475185", "Score": "0", "body": "Looks plausible, but the code given as-is fails the test case in the question (nothing is printed)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-12T19:04:11.280", "Id": "475220", "Score": "0", "body": "@OverLordGoldDragon, it printed out too much when I ran it, so I had to add tests for imported functions and dunder functions. Note, the source file for the module has to be on the search path so `pyclbr` can find it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-13T00:18:38.113", "Id": "475239", "Score": "0", "body": "This does work, but it's more of an 'alternative' than 'code review' - also worth mentioning this [docs'](https://docs.python.org/3.7/library/pyclbr.html) note: _\"information is extracted from the Python source code rather than by importing the module, so this module is safe to use with untrusted code\"_ - which is an advantage over existing answers." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-12T15:56:33.850", "Id": "242140", "ParentId": "242109", "Score": "3" } }, { "body": "<p>Thanks to @Peilonrayz for the original answer, but I figure it's worth including a more complete version of the working function:</p>\n<pre class=\"lang-py prettyprint-override\"><code>from types import LambdaType\n\ndef get_module_methods(module):\n output = {}\n for name in dir(module):\n obj = getattr(module, name)\n obj_name = getattr(obj, '__name__', '')\n if ((str(obj).startswith('&lt;function')\n and isinstance(obj, LambdaType)) # is a function\n and module.__name__ == getattr(obj, '__module__', '') # same module\n and name in str(getattr(obj, '__code__', '')) # not a duplicate\n and &quot;__%s__&quot; % obj_name.strip('__') != obj_name # not a magic method\n and '&lt;lambda&gt;' not in str(getattr(obj, '__code__')) # not a lambda\n ):\n output[name] = obj\n return output\n</code></pre>\n<p>Lambda detection taken from <a href=\"https://stackoverflow.com/questions/56451020/is-there-any-way-to-tell-if-a-function-object-was-a-lambda-or-a-def\">this Q&amp;A</a>. Note that we can omit the <code>isinstance(obj, LambdaType)</code> typecheck, but with caveats:</p>\n<ul>\n<li><code>str(obj).startswith('&lt;function')</code> is insufficient to tell whether <code>obj</code> is a function, since we can define a class whose <code>__str__</code> returns <code>'&lt;function'</code> (as pointed by Peilonrayz). However, <code>__str__</code> is effective on a class <em>instance</em>, which fails the <code># not a duplicate</code> check - so we can &quot;luck out&quot;. This is unlikely in practice, but here's where a typecheck may be necessary:</li>\n</ul>\n<pre class=\"lang-py prettyprint-override\"><code>class Dog():\n def __init__(self):\n self.__name__ = 'd'\nd = Dog()\n</code></pre>\n<hr>\n<p><strong>Edit</strong>: changed <code># not a duplicate</code> check, which would falsely exclude <code>not_lambda</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-12T18:13:03.747", "Id": "242148", "ParentId": "242109", "Score": "-1" } } ]
{ "AcceptedAnswerId": "242148", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-12T01:54:20.063", "Id": "242109", "Score": "0", "Tags": [ "python", "python-3.x" ], "Title": "Get methods in module, Python" }
242109
<p><strong>Hello, I'm a C++ beginner, learning the language while trying to code Project Euler problems. I'm having trouble coding problem 14, which I'll copy here:</strong></p> <blockquote> <p>The following iterative sequence is defined for the set of positive integers:</p> <p>n → n/2 (n is even) n → 3n + 1 (n is odd)</p> <p>Using the rule above and starting with 13, we generate the following sequence: 13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1</p> <p>It can be seen that this sequence (starting at 13 and finishing at 1) contains 10 terms. Although it has not been proved yet (Collatz Problem), it is thought that all starting numbers finish at 1.</p> <p>Which starting number, under one million, produces the longest chain?</p> <p>NOTE: Once the chain starts the terms are allowed to go above one million.</p> </blockquote> <p><strong>My program runs fast, and works for smaller values of n, but for some reason I don't understand, it doesn't give the right solution for n = 1 million. I think the mod function % might be the issue in some way for large numbers, or the way i defined the variables, but I can't get it right. Would appreciate some help, and thank you for your patience in advance.</strong></p> <p><strong>I wrote this piece of code for it:</strong></p> <pre><code>#include &lt;iostream&gt; #include &lt;cmath&gt; using namespace std; double maxvec(int *v,int n){ //gets the max value of a vector double elmax; elmax=v[0]; for(int i=1;i&lt;n;i++){ if(v[i]&gt;elmax) elmax=v[i]; } return elmax; } double indice(int *v,int n){ //gets the index corresponding to the max value of a vector double elmax=v[0]; double indice; indice=0; for(int i=1;i&lt;n;i++){ if(v[i]&gt;elmax){ elmax=v[i];indice=i; } } return indice; } int main(){ const int n = 1000000; long x0; int ind; int k[n-2]; //vector that contains how many elements are there in the sequence for each initial number for ( int i=2; i&lt;n; i++){ //the numbers we are gonna run through the Collatz sequence (in this case the problem asks for n=1000000) k[i-2]=0; x0=i; while (x0!=1){ //using the property that all Collatz sequences end in 1 x0=x0%2 + x0/2*((x0+1)%2)+ 3*x0*(x0%2); //the algorithm for the collatz sequence k[i-2] = k[i-2]+1; //for the final iteration of the while loop, the (i-2)th component contains the information of the number of elements that corresponds to the initial value i } } cout&lt;&lt;maxvec(k,n-2)&lt;&lt;endl; //shows the maximum value of array k cout&lt;&lt;indice(k,n-2)+2&lt;&lt;endl; //shows the initial value for the max value of k, which is the solution to the problem } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-12T07:23:43.147", "Id": "475126", "Score": "2", "body": "Welcome to Code Review! I'm afraid this question does not match what this site is about. Code Review is about improving existing, working code. Code Review is not the site to ask for help in fixing or changing *what* your code does. Once the code works for n = 1000000, we would love to help you do the same thing in a cleaner way! Please see our [help center](/help/on-topic) for more information." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-12T07:24:39.330", "Id": "475127", "Score": "0", "body": "Also, this cannot be all of your code, it's missing the `#include`, at least one `using` and several other parts to be complete on its own." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-12T07:27:47.287", "Id": "475128", "Score": "0", "body": "Furthermore, both `maxvec` and `indice` are missing in your code. As-is, this question is unfortunately non-reviewable, but you can fix that :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-12T08:15:44.710", "Id": "475131", "Score": "1", "body": "Okay, I added the includes, using, and the two functions. I thought adding the includes and stuff was trivial and not necessary, the functions are pretty basic too. Sorry for that, I'm new here, thanks for baring with me :D You can check that the code works, it just has some bug for large n that I can't figure out!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-13T08:20:34.287", "Id": "475263", "Score": "0", "body": "As long as you state you'd *appreciate some help* with a correctness problem taken for granted, instead of [looking for open-ended feedback in concrete application of best practices and design pattern use, potential security issues or performance](https://codereview.stackexchange.com/help/on-topic), I take this question to be off-topic. (After all, you knew about the million right from the outset.)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-13T21:31:40.273", "Id": "475364", "Score": "0", "body": "Even if your edit does take the code presented from `doesn't give the right solution for n = 1 million` to *works correctly up to a million and who knows what beyond*, [the edit should *not* have happened](https://codereview.stackexchange.com/help/someone-answers) (and is bound to be rolled back - do it yourself). The question will stay off topic, one answer given as helpfully as misguidedly notwithstanding." } ]
[ { "body": "<p>I will try and tackle correctness, style and performance in that order</p>\n\n<p><strong>Corectness</strong></p>\n\n<p>My initial guess, for wrong results would be you are overflowing an int for long sequences. making x0 an unsigned long I get the longest sequence as 524, for 837799, which matches the results at <a href=\"https://www.dcode.fr/collatz-conjecture\" rel=\"nofollow noreferrer\">https://www.dcode.fr/collatz-conjecture</a> . Indeed that sequence contains 2974984576 which will overflow a signed int.</p>\n\n<p><strong>Style</strong></p>\n\n<p>Your code is very c-like and has not really used any c++ features other than cout. Some things I would change:</p>\n\n<ul>\n<li><p>avoid using namespace std, see <a href=\"https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice\">https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice</a> This is generally considered bad practise as it you can get unexpected name collisions. It probably won't cause any real issues on a small project like this, but is a bad habit to get into.</p></li>\n<li><p>Prefer stl containers to raw arrays. Stl containers have many advantages over raw arrays. In your case I would make k a std::array, i.e. <code>std::array&lt; std::size_t, n-2 &gt; k;</code> std::arrays are fixed size containers very similar to raw arrays, but don't decay to pointers, provide iterators and to allow easily looping over the elements ( and interacting with the rest of the stl ), among other features.</p></li>\n<li><p>Your update of x0 is not very clear/easy to read. I would break this into the two cases with and if/else, and probably make it a separate function. i.e.</p></li>\n</ul>\n\n<pre><code>if( x0%2 )\n{\n x0 = 3*x0 + 1;\n}\nelse\n{\n x0 = x0/2;\n}\n</code></pre>\n\n<ul>\n<li>Use stl functions rather than writing your own. Another advantage of using stl containers is there are many standard functions that use the containers, which can save you having to write your own. e.g. std::max_element this could simplify your calculation of max value and index.</li>\n</ul>\n\n<pre><code>auto maxIt = std::max_element(k.begin(), k.end());\nint maxSeq = std::distance(k.begin(), maxIt) + 2;\nunsigned long maxValue = k[maxSeq - 2];\n</code></pre>\n\n<ul>\n<li>Make values unsigned if they cannot be &lt; 0. None of your values should be &lt;0, for clarity it is good practise to make them in this case. The normal way to do this for ints is to use <code>std::size_t</code>. This helps clarify the intent of your code.</li>\n</ul>\n\n<p><strong>Performance</strong></p>\n\n<p>Your code seems to have pretty good performance and has no trivial performance improvements that I can see. Possibly the updating of x0 can be written more efficiently, but I would change it for clarity reasons, as mentioned above, and profile any possible performance changes from there. </p>\n\n<p>I will note that the sequence does not depend on previous values, so if you reach a value already calculated k for you do not need to calculate the rest of the sequence, but can just add that value. Again you would need to profile whether the cost of doing the extra checks gives an actual improvement.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-12T09:51:07.560", "Id": "242128", "ParentId": "242111", "Score": "2" } } ]
{ "AcceptedAnswerId": "242128", "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-12T02:27:00.573", "Id": "242111", "Score": "1", "Tags": [ "c++", "beginner", "programming-challenge" ], "Title": "C++ Beginner. Project Euler 14: Longest Collatz sequence under one million" }
242111
<p>I am making a 2d graphics engine. I am somewhat new to JavaScript and have been winging this project. So far it creates a background (a tilemap made of smaller images in a grid) and sprites ( a small image with a higher z index). I ommited my test code, as I didn't care for that to be reviewed, but if it needs to be included I can add it.</p> <p>I am looking for best practice advice for javascript or in general. One specific question is: Are the OLNs (sprites and tilemap) used correctly or should something else be used?</p> <p>js:</p> <pre><code>'use strict'; const TILEMAPSIZE = 160; // Total number of tiles displayed. Must be a multiple of TILECOLUMNS. const TILECOLUMNS = 16; // Number of columns let tileSet = []; // Set of all tiles to be used let tilemapList = []; // The order in which the tiles are used via references to elements in tileSet let spriteSet = []; // Set of all sprites to be used loadResources(); let sprites = (function (){ function createSprites(spritesList) { let spriteCount = 0; spritesList.forEach(x =&gt; { let sprite = document.createElement('img'); sprite.src = x; sprite.className = "sprites"; sprite.id = "sprite" + spriteCount; sprite.style.visibility = "hidden"; ++spriteCount; document.getElementById("window").appendChild(sprite); }); } function show(index) { const spriteStyle = document.getElementById("sprite" + index).style spriteStyle.visibility = "visible"; } function hide(index) { spriteStyle = document.getElementById("sprite" + index).style spriteStyle.visibility = "hidden"; } function reflectY(spriteIndex) { const sprite = "sprite" + spriteIndex; const transform = document.getElementById(sprite).style.transform; if (transform === "scale(-1, 1)"){ document.getElementById(sprite).style.transform = "scale(1)"; } else if (transform === "scale(1, -1)"){ document.getElementById(sprite).style.transform = "scale(-1)"; } else if (transform === "scale(-1)"){ document.getElementById(sprite).style.transform = "scale(1, -1)"; } else { document.getElementById(sprite).style.transform = "scale(-1, 1)"; } } function reflectX(spriteIndex) { const sprite = "sprite" + spriteIndex; const transform = document.getElementById(sprite).style.transform; if (transform === "scale(-1, 1)"){ document.getElementById(sprite).style.transform = "scale(-1)"; } else if (transform === "scale(1, -1)"){ document.getElementById(sprite).style.transform = "scale(1)"; } else if (transform === "scale(-1)"){ document.getElementById(sprite).style.transform = "scale(-1, 1)"; } else { document.getElementById(sprite).style.transform = "scale(1, -1)"; } } function reflect(spriteIndex, dX, dY) { const sprite = "sprite" + spriteIndex; if (dX === true &amp;&amp; dY === true){ document.getElementById(sprite).style.transform = "scale(1)"; } else if (dX === true &amp;&amp; dY === false){ document.getElementById(sprite).style.transform = "scale(1, -1)"; } else if (dX === false &amp;&amp; dY === true){ document.getElementById(sprite).style.transform = "scale(-1, 1)"; } else if (dX === false &amp;&amp; dY === false){ document.getElementById(sprite).style.transform = "scale(-1)"; } } function translate(spriteIndex, dX, dY) { const sprite = "sprite" + spriteIndex; const posLeft = parseInt(document.getElementById(sprite).style.left.slice(0, -2)) + dX; const posTop = parseInt(document.getElementById(sprite).style.top.slice(0, -2)) + dY; document.getElementById(sprite).style.left = posLeft + "px"; document.getElementById(sprite).style.top = posTop + "px"; } function setPosition(spriteIndex, dX, dY) { const sprite = "sprite" + spriteIndex; document.getElementById(sprite).style.left = dX +"px"; document.getElementById(sprite).style.top = dY + "px"; } function getPosition(spriteIndex) { const sprite = "sprite" + spriteIndex; return { x: parseInt(document.getElementById(sprite).style.left.slice(0, -2)), y: parseInt(document.getElementById(sprite).style.top.slice(0, -2)) }; } function getOrientation(spriteIndex) { const sprite = "sprite" + spriteIndex; const transform = document.getElementById(sprite).style.transform; let pair = {}; if (transform === "scale(1)"){ pair = {x: 1, y: 1}; } else if (transform === "scale(-1)"){ pair = {x: -1, y: -1}; } else if (transform === "scale(1, -1)"){ pair = {x: 1, y: -1}; } else if (transform === "scale(-1, 1)"){ pair = {x: -1, y: 1}; } else { pair = {x: 0, y: 0}; } return pair; } return{ setPosition: setPosition, getPosition: getPosition, getOrientation: getOrientation, translate: translate, reflect: reflect, reflectX: reflectX, reflectY: reflectY, createSprites: createSprites, show: show, hide: hide }; }()) let tilemap = (function (){ function create(){ // create the tile map for (let i = 0; i &lt; TILEMAPSIZE; ++i){ let tile = document.createElement('div'); tile.className = "tile"; tile.id = "tile" + i; document.getElementById("tilemap").appendChild(tile); }; // set the number of columns let value = ""; for (let i = 0; i &lt; TILECOLUMNS; ++i){ value += "auto "; } document.getElementById("tilemap").style.gridTemplateColumns = value; // insert images let index = 0; tilemapList.forEach(x =&gt; { let img = document.createElement('img'); img.src = x; img.className = "tileImage"; document.getElementById("tile" + index).appendChild(img); ++index; }) } function show() { spriteStyle = document.getElementById("tilemap").style spriteStyle.visibility = "visible"; } function hide() { spriteStyle = document.getElementById("tilemap").style spriteStyle.visibility = "hidden"; } function translate(dX, dY) { const posLeft = parseInt(document.getElementById("viewport").style.left.slice(0, -2)) + dX; const posTop = parseInt(document.getElementById("viewport").style.top.slice(0, -2)) + dY; document.getElementById("viewport").style.left = posLeft + "px"; document.getElementById("viewport").style.top = posTop + "px"; } function setPosition(dX, dY) { document.getElementById("viewport").style.top = dY + "px"; document.getElementById("viewport").style.left = dX + "px"; } function getPosition() { return { x: parseInt(document.getElementById("viewport").style.left.slice(0, -2)), y: parseInt(document.getElementById("viewport").style.top.slice(0, -2)) }; } return{ setPosition: setPosition, getPosition: getPosition, translate: translate, show: show, hide: hide, create: create}; }()) tilemap.setPosition(0, 0); tilemap.create(); sprites.createSprites(spriteSet); sprites.setPosition(0, 235, 240); sprites.show(0); function loadResources(){ const img1 = 'https://georgec0stanza.github.io/2DgraphicsEngine/images/ferns.jpg'; const img2 = 'https://georgec0stanza.github.io/2DgraphicsEngine/images/tulips.jpg'; const img3 = 'https://georgec0stanza.github.io/2DgraphicsEngine/images/water.jpg'; const sprite0 = 'https://georgec0stanza.github.io/2DgraphicsEngine/images/daffodil.jpg'; const sprite1 = 'https://georgec0stanza.github.io/2DgraphicsEngine/images/eagle.jpg'; spriteSet = [sprite0, sprite1]; tileSet = [img1, img2, img3]; tilemapList = [tileSet[2], tileSet[1] , tileSet[1] , tileSet[0] ,tileSet[2], tileSet[1] , tileSet[1] , tileSet[0] ,tileSet[2], tileSet[1] , tileSet[1] , tileSet[0] ,tileSet[2], tileSet[1] , tileSet[1] , tileSet[0] ,tileSet[2], tileSet[1] , tileSet[1] , tileSet[0] ,tileSet[2], tileSet[1] , tileSet[1] , tileSet[0] ,tileSet[2], tileSet[1] , tileSet[1] , tileSet[0] ,tileSet[2], tileSet[1] , tileSet[1] , tileSet[0] ,tileSet[2], tileSet[1] , tileSet[1] , tileSet[0] ,tileSet[2], tileSet[1] , tileSet[1] , tileSet[0] ,tileSet[2], tileSet[1] , tileSet[1] , tileSet[0] ,tileSet[2], tileSet[1] , tileSet[1] , tileSet[0] ,tileSet[2], tileSet[1] , tileSet[1] , tileSet[0], tileSet[0] , tileSet[2], tileSet[2], tileSet[1] , tileSet[1] , tileSet[0] ,tileSet[2], tileSet[1] , tileSet[1] , tileSet[0] ,tileSet[2], tileSet[1] , tileSet[1] , tileSet[0] ,tileSet[2], tileSet[1] , tileSet[1] , tileSet[0] ,tileSet[2], tileSet[1] , tileSet[1] , tileSet[0] ,tileSet[2], tileSet[1] , tileSet[1] , tileSet[0] ,tileSet[2], tileSet[1] , tileSet[1] , tileSet[0] ,tileSet[2], tileSet[1] , tileSet[1] , tileSet[0] ,tileSet[2], tileSet[1] , tileSet[1] , tileSet[0] ,tileSet[2], tileSet[1] , tileSet[1] , tileSet[0] ,tileSet[2], tileSet[1] , tileSet[1] , tileSet[0] ,tileSet[2], tileSet[1] , tileSet[1] , tileSet[0] ,tileSet[2], tileSet[1] , tileSet[1] , tileSet[0] , tileSet[2], tileSet[2], tileSet[1] , tileSet[1] , tileSet[0] ,tileSet[2], tileSet[1] , tileSet[1] , tileSet[0] ,tileSet[2], tileSet[1] , tileSet[1] , tileSet[0] ,tileSet[2], tileSet[1] , tileSet[1] , tileSet[0] ,tileSet[2], tileSet[1] , tileSet[1] , tileSet[0] ,tileSet[2], tileSet[1] , tileSet[1] , tileSet[0] ,tileSet[2], tileSet[1] , tileSet[1] , tileSet[0] ,tileSet[2], tileSet[1] , tileSet[1] , tileSet[0] ,tileSet[2], tileSet[1] , tileSet[1] , tileSet[0] ,tileSet[2], tileSet[1] , tileSet[1] , tileSet[0] ,tileSet[2], tileSet[1] , tileSet[1] , tileSet[0] ,tileSet[2], tileSet[1] , tileSet[1] , tileSet[0] ,tileSet[2], tileSet[1] , tileSet[1] , tileSet[0] , tileSet[2]]; } </code></pre> <p>html:</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;meta charset="utf-8" /&gt; &lt;meta http-equiv="X-UA-Compatible" content="IE=edge"&gt; &lt;title&gt;Page Title&lt;/title&gt; &lt;meta name="viewport" content="width=device-width, initial-scale=1"&gt; &lt;link rel="stylesheet" type="text/css" media="screen" href="main.css" /&gt; &lt;script src="main.js" defer&gt;&lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;div id="window"&gt; &lt;div id="viewport"&gt; &lt;div id ="tilemap"&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>css:</p> <pre><code>:root { --TILESIZE: 50px; /* Size of tiles */ --SPRITESIZE: 50px; /* Size of sprites */ --WINDOWIDTH: 650px; --WINDOWHEIGHT: 500px; --WINDOWBACKGROUND: white; } body { background-color: black; } img { display: block; } #window { overflow: hidden; margin: 0 auto; position: relative; width: var(--WINDOWIDTH); height: var(--WINDOWHEIGHT); background: var(--WINDOWBACKGROUND); } #viewport { position: absolute; } #tilemap { display: grid; z-index: -1; } .tile { text-align: center; } .tileImage { height: var(--TILESIZE); width: var(--TILESIZE); } .sprites { position: absolute; height: var(--SPRITESIZE); width: var(--SPRITESIZE); z-index: 1; transform: scale(1); } <span class="math-container">```</span> </code></pre>
[]
[ { "body": "<p>There are a number of improvements you can make.</p>\n\n<p>Reassigning global variables so that a particular function can proceed to use them (<code>spriteSet</code>, <code>tileSet</code>, <code>tilemapList</code>) is pretty strange. It would make a lot more sense if these were only passed as arguments to the functions that need them instead. In fact, since the <code>tileSet</code> isn't being used anywhere except inside <code>loadResources</code>, that can be made completely local:</p>\n\n<pre><code>const { spriteSet, tilemapList } = loadResources();\ntilemap.setPosition(0, 0);\ntilemap.create(tilemapList);\n\nsprites.createSprites(spriteSet);\n</code></pre>\n\n<p>Always declare variables <a href=\"https://softwareengineering.stackexchange.com/questions/278652/how-much-should-i-be-using-let-vs-const-in-es6\">with <code>const</code> when possible</a> - you don't intend to reassign the <code>sprites</code> or the <code>tilemap</code> object, right? There are a few variables like this - consider using a linter to prompt you to fix these sorts of potential mistakes automatically.</p>\n\n<p>The <code>tilemapList</code> definition is repetitive and difficult to read:</p>\n\n<pre><code>const tilemapList = [tileSet[2], tileSet[1] , tileSet[1] , tileSet[0] ,tileSet[2], tileSet[1] , tileSet[1] , tileSet[0] ,tileSet[2], tileSet[1] , tileSet[1] , tileSet[0] ,tileSet[2], tileSet[1] , tileSet[1] , tileSet[0] ,tileSet[2], tileSet[1] , tileSet[1] , tileSet[0] ,tileSet[2], tileSet[1] , tileSet[1] , tileSet[0] ,tileSet[2], tileSet[1]\n</code></pre>\n\n<p>Consider defining the layout with a single string instead, where each cell (numeric, indicating the index of the tile in the <code>tileSet</code>) is separated by a space (or few) or newlines, which gets parsed into the array above afterwards - this way, it'll be far more readable and less prone to copy/paste bugs or the like:</p>\n\n<pre><code>const tiles = `\n2 1 1 0 2 1 1 0 2 1 1 0 2 1 1 0 2 1 1 0\n2 2 2 0 0 0 2 2 2 0 0 0 2 2 2 0 0 0 1 1\n`\n.trim()\n.split(/\\s+/)\n.map(index =&gt; tileSet[index]);\n</code></pre>\n\n<p>Numeric-indexed IDs are never a good idea - IDs are for elements that are <em>absolutely unique</em> in a document, and they create global variables, unfortunately. If you want a way to select the <code>n</code>th sprite in the tilemap, just select the <code>n</code>th child of the tilemap:</p>\n\n<pre><code>tilemap.children[i]\n</code></pre>\n\n<p>You might put the children into an array, and have the array in a closure or on an instance so it's easily accessible by all methods. (See snippet below for an example)</p>\n\n<p>Having <code>sprites</code> for the main sprite maker object isn't as precise as it could be. I'd expect a variable named <code>sprites</code> to be an array-like collection of <code>sprite</code> objects. Maybe call the main sprite maker <code>SpritesMaker</code> instead? You can also use a class instead of an IIFE in order to have the children as a property of the instance, as mentioned above.</p>\n\n<p>You frequently select elements over and over again:</p>\n\n<pre><code>spritesList.forEach(x =&gt; {\n // do stuff\n document.getElementById(\"window\").appendChild(sprite);\n</code></pre>\n\n<p>Consider selecting the element <em>once</em> instead, rather than having to go through the DOM to find the element again each time:</p>\n\n<pre><code>const win = document.getElementById(\"window\");\nspritesList.forEach(x =&gt; {\n // do stuff\n win.appendChild(sprite);\n</code></pre>\n\n<p>You have a lot of places where the above pattern can make the code a lot cleaner - instead of repeating <code>document.getElementById(x)</code> multiple times, do <code>const someElement = document.getElementById(x)</code> and then repeat <code>someElement</code> instead. Nearly all of the functions in both the big <code>sprites</code> object and the <code>tilemap</code> object can be significantly improved with this technique.</p>\n\n<p>But <code>window</code> is a <em>very</em> weird ID - it's very easily confused with <code>window</code>, the global object. Consider using something else, like <code>main</code>. You might even avoid IDs altogether, since every element with an ID creates an additional global variable of that name, which can occasionally result in confusing weird bugs.</p>\n\n<p>You have</p>\n\n<pre><code>spritesList.forEach(x =&gt; {\n</code></pre>\n\n<p><code>x</code> isn't very descriptive at all. Best to call a variable what it represents, maybe <code>srcStr</code>.</p>\n\n<p>Since you're appending each sprite to the <code>.main</code>, you may avoid having to set a class name on each sprite element by using the <code>.main &gt; img</code> in your CSS instead.</p>\n\n<p>You have</p>\n\n<pre><code>if (dX === true &amp;&amp; dY === true){\n style.transform = \"scale(1)\";\n} else if (dX === true &amp;&amp; dY === false){\n</code></pre>\n\n<p>You may use simple truthy/falsey tests instead if you wish:</p>\n\n<pre><code>if (dX &amp;&amp; dY){\n style.transform = \"scale(1)\";\n}\nelse if (dX &amp;&amp; !dY){\n style.transform = \"scale(1, -1)\";\n}\n</code></pre>\n\n<p>Rather than frequently checking and reassigning with</p>\n\n<pre><code>let pair = {};\n\nif (transform === \"scale(1)\"){\n pair = {x: 1, y: 1};\n}\nelse if (transform === \"scale(-1)\"){\n pair = {x: -1, y: -1};\n}\n// etc\nreturn pair;\n</code></pre>\n\n<p>You might consider just returning the object instead:</p>\n\n<pre><code>if (transform === \"scale(1)\"){\n return {x: 1, y: 1};\n}\nelse if (transform === \"scale(-1)\"){\n return {x: -1, y: -1};\n}\n</code></pre>\n\n<p>If you <em>do</em> want to keep using the IIFE, note that you may use shorthand properties in ES2015, and you're using ES2015 syntax already. The below:</p>\n\n<pre><code>return{\n setPosition: setPosition,\n getPosition: getPosition,\n getOrientation: getOrientation,\n // ...\n</code></pre>\n\n<p>simplifies to</p>\n\n<pre><code>return {\n setPosition,\n getPosition,\n getOrientation,\n // ...\n</code></pre>\n\n<p>All together:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>'use strict';\n\nconst TILEMAPSIZE = 160; // Total number of tiles displayed. Must be a multiple of TILECOLUMNS.\nconst TILECOLUMNS = 16; // Number of columns\n\nclass SpritesMaker {\n constructor(spritesList) {\n const main = document.querySelector('.main');\n this.sprites = spritesList.map(srcStr =&gt; {\n const sprite = document.createElement('img');\n sprite.src = srcStr;\n main.appendChild(sprite);\n return sprite;\n });\n }\n\n show(index) {\n this.sprites[index].style.visibility = 'visible';\n }\n\n hide(index) {\n this.sprites[index].style.visibility = 'hidden';\n }\n\n reflectY(index) {\n const { style } = this.sprites[index];\n const transform = style.transform;\n if (transform === \"scale(-1, 1)\"){ \n style.transform = \"scale(1)\";\n }\n else if (transform === \"scale(1, -1)\"){\n style.transform = \"scale(-1)\";\n }\n else if (transform === \"scale(-1)\"){\n style.transform = \"scale(1, -1)\";\n }\n else {\n style.transform = \"scale(-1, 1)\";\n }\n }\n\n reflectY(index) {\n const { style } = this.sprites[index];\n const transform = style.transform;\n if (transform === \"scale(-1, 1)\"){\n style.transform = \"scale(-1)\";\n }\n else if (transform === \"scale(1, -1)\"){\n style.transform = \"scale(1)\";\n }\n else if (transform === \"scale(-1)\"){\n style.transform = \"scale(-1, 1)\";\n }\n else {\n style.transform = \"scale(1, -1)\";\n }\n }\n\n reflect(index, dX, dY) {\n const { style } = this.sprites[index];\n if (dX &amp;&amp; dY){\n style.transform = \"scale(1)\";\n }\n else if (dX &amp;&amp; !dY){\n style.transform = \"scale(1, -1)\";\n }\n else if (!dX &amp;&amp; dY){\n style.transform = \"scale(-1, 1)\";\n }\n else if (!dX &amp;&amp; !dY){\n style.transform = \"scale(-1)\";\n }\n }\n\n translate(index, dX, dY) {\n const { style } = this.sprites[index];\n const posLeft = Number(style.left.slice(0, -2)) + dX;\n const posTop = Number(style.top.slice(0, -2)) + dY;\n style.left = posLeft + \"px\";\n style.top = posTop + \"px\";\n }\n\n setPosition(index, dX, dY) {\n const { style } = this.sprites[index];\n style.left = dX +\"px\";\n style.top = dY + \"px\";\n }\n\n getPosition(spriteIndex) {\n const { style } = this.sprites[index];\n return {\n x: Number(style.left.slice(0, -2)),\n y: Number(style.top.slice(0, -2))\n };\n }\n\n getOrientation(index) {\n const { transform } = this.sprites[index].transform;\n if (transform === \"scale(1)\"){\n return {x: 1, y: 1};\n }\n else if (transform === \"scale(-1)\"){\n return {x: -1, y: -1};\n }\n else if (transform === \"scale(1, -1)\"){\n return {x: 1, y: -1};\n }\n else if (transform === \"scale(-1, 1)\"){\n return {x: -1, y: 1};\n }\n else {\n return {x: 0, y: 0};\n }\n }\n}\n\nclass TileMap {\n constructor(tilemapList){\n this.viewport = document.querySelector('.viewport');\n this.tilemapDiv = document.querySelector('.tilemap');\n // set the number of columns\n let value = \"\";\n for (let i = 0; i &lt; TILECOLUMNS; ++i){\n value += \"auto \";\n }\n this.tilemapDiv.style.gridTemplateColumns = value;\n \n // create the tile map\n this.tiles = [];\n for (let i = 0; i &lt; TILEMAPSIZE; ++i){\n this.tiles.push(this.tilemapDiv.appendChild(document.createElement('div')));\n }; \n \n // insert images\n tilemapList.forEach((src, i) =&gt; {\n const img = document.createElement('img');\n img.src = src;\n this.tiles[i].appendChild(img);\n })\n }\n\n show() {\n this.tilemapDiv.style.visibility = \"visible\";\n }\n\n hide() {\n this.tilemapDiv.style.visibility = \"hidden\";\n }\n\n translate(dX, dY) {\n const { style } = this.viewport;\n const posLeft = Number(style.left.slice(0, -2)) + dX;\n const posTop = Number(style.top.slice(0, -2)) + dY;\n style.left = posLeft + \"px\";\n style.top = posTop + \"px\";\n }\n\n setPosition(dX, dY) {\n const { style } = this.viewport;\n style.top = dY + \"px\";\n style.left = dX + \"px\";\n }\n\n getPosition() {\n const { left, top } = this.viewport.style;\n return {\n x: style.left.slice(0, -2),\n y: style.top.slice(0, -2)\n };\n }\n}\n\nconst { spriteSet, tilemapList } = loadResources();\nconst tileMap = new TileMap(tilemapList);\ntileMap.setPosition(0, 0);\n\nconst fernsTulipsSprites = new SpritesMaker(spriteSet);\nfernsTulipsSprites.setPosition(0, 235, 240);\nfernsTulipsSprites.show(0); \n\nfunction loadResources(){\n const img1 = 'https://georgec0stanza.github.io/2DgraphicsEngine/images/ferns.jpg';\n const img2 = 'https://georgec0stanza.github.io/2DgraphicsEngine/images/tulips.jpg';\n const img3 = 'https://georgec0stanza.github.io/2DgraphicsEngine/images/water.jpg';\n\n const sprite0 = 'https://georgec0stanza.github.io/2DgraphicsEngine/images/daffodil.jpg'; \n const sprite1 = 'https://georgec0stanza.github.io/2DgraphicsEngine/images/eagle.jpg'; \n\n const spriteSet = [sprite0, sprite1];\n const tileSet = [img1, img2, img3];\n const tilemapList = `\n 2 1 1 0 2 1 1 0 2 1 1 0 2 1 1 0 \n 2 1 1 0 2 1 1 0 2 1 1 0 2 1 1 0 \n 2 1 1 0 2 1 1 0 2 1 1 0 2 1 1 0 \n 2 1 1 0 0 2 2 1 1 0 2 1 1 0 2 1 \n 1 0 2 1 1 0 2 1 1 0 2 1 1 0 2 1 \n 1 0 2 1 1 0 2 1 1 0 2 1 1 0 2 1 \n 1 0 2 1 1 0 2 1 1 0 2 2 1 1 0 2 \n 1 1 0 2 1 1 0 2 1 1 0 2 1 1 0 2 \n 1 1 0 2 1 1 0 2 1 1 0 2 1 1 0 2 \n 1 1 0 2 1 1 0 2 1 1 0 2 1 1 0 2\n `\n .trim()\n .split(/\\s+/)\n .map(index =&gt; tileSet[index]);\n return { spriteSet, tilemapList };\n}</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>:root {\n --TILESIZE: 50px;\n /* Size of tiles */\n --SPRITESIZE: 50px;\n /* Size of sprites */\n --WINDOWIDTH: 650px;\n --WINDOWHEIGHT: 500px;\n --WINDOWBACKGROUND: white;\n}\n\nbody {\n background-color: black;\n}\n\nimg {\n display: block;\n}\n\n.window {\n overflow: hidden;\n margin: 0 auto;\n position: relative;\n width: var(--WINDOWIDTH);\n height: var(--WINDOWHEIGHT);\n background: var(--WINDOWBACKGROUND);\n}\n\n.viewport {\n position: absolute;\n}\n\n.tilemap {\n display: grid;\n z-index: -1;\n}\n\n.tilemap &gt; div {\n text-align: center;\n}\n\n.tilemap &gt; div &gt; img {\n height: var(--TILESIZE);\n width: var(--TILESIZE);\n}\n\n.main &gt; img {\n position: absolute;\n height: var(--SPRITESIZE);\n width: var(--SPRITESIZE);\n z-index: 1;\n transform: scale(1);\n visibility: hidden;\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;div class=\"main\"&gt;\n &lt;div class=\"viewport\"&gt;\n &lt;div class=\"tilemap\"&gt;\n &lt;/div&gt;\n &lt;/div&gt;\n&lt;/div&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-12T15:16:34.787", "Id": "475169", "Score": "0", "body": "So I'm still chewing through this, but you made some classes so we can use ` tilemap.children[i] ` but that returns `TypeError: \"tileMap.children is undefined\"`. (If `i` is set and `tilemap` is `tileMap`)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-12T15:21:58.153", "Id": "475170", "Score": "0", "body": "Also, are classes" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-12T15:22:07.967", "Id": "475171", "Score": "0", "body": "If you do `const tileMap = new TileMap(tilemapList);`, you have an instance of the object as `tileMap`, not the `tilemap` *element* - better to decrease these sorts of name collisions when possible. In the code in the snippet, I assigned the element to the `tilemapDiv` property of the instance, so if you want to get to the element, you have to access that property of the instance. The instance doesn't have a `children` property." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-12T15:24:00.570", "Id": "475173", "Score": "0", "body": "Classes are generally for when you want to tie together persistent *data* (here, HTML elements) with methods that do stuff with that data (here, modify the elements). Classes are very suited for the job here." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-12T15:31:14.903", "Id": "475175", "Score": "0", "body": "Sorry my comment got submitted early by accident, I thought that classes wasn't very JavaScripty, So I was avoiding them. Plus they didn't need to keep track of state, so I thought the IIFE(i thought it was called OLN?) was more appropriate." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-12T15:32:41.637", "Id": "475177", "Score": "0", "body": "Additionally, the reason we switched to classes ended up not even existing if the tilemapDiv doesn't have children." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-12T15:32:46.433", "Id": "475178", "Score": "0", "body": "Never heard of OLN. If you mean object literal, that'd be *just* the declaration of an object literal, `const obj = { prop: 'val' }`. An immediately-invoked function expression which returns an object is different. `const obj = (() => { /* do lots of stuff */ return { prop: 'val' }; })();`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-12T15:35:48.030", "Id": "475179", "Score": "0", "body": "Sure, classes are often overused in Javascript, IMO. At least in my experience, they're rarely the right tool for the job - but sometimes, they are, and this is a decent example: if you have instance variables, no need for (smelly) globals. (it also allows you to easily extend the script to create *multiple* grids/sprites/etc, if you ever wanted to)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-12T15:36:18.653", "Id": "475180", "Score": "0", "body": "Oh I was just trying to do classes the \"JavaScript way\" and ended up with the IIF,E but somewhere someone called it OLN - object literal notation." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-12T15:37:46.797", "Id": "475181", "Score": "0", "body": "*they didn't need to keep track of state* The elements tied to the methods *are* state, pretty much - you have to keep persistent track of them while calling the different functions that do stuff with them." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-12T16:57:53.847", "Id": "475199", "Score": "0", "body": "Thanks for your help, I just have one last question, is `tileMap.tiles[0].innerHTML = \"<img src=\\\"https://georgec0stanza.github.io/2DgraphicsEngine/images/eagle.jpg\\\">\"` an elegant way of changing a tile in the tilemap? I tried the `tilemapDiv.children` but that doesn't change anything in the document." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-12T17:18:53.977", "Id": "475202", "Score": "1", "body": "I'd prefer to change the `src` of the image. `this.tiles[0].children[0].src = 'newSrc'`. `this.tilemapDiv.children` will give you the same sort of collection as `tileMap.tiles`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-12T17:28:57.653", "Id": "475204", "Score": "0", "body": "yeah but that gives me `TypeError: 0 is read-only` and I tried changing all the `const`s to `let`s to no avail." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-12T17:31:02.173", "Id": "475206", "Score": "0", "body": "Works just fine here https://jsfiddle.net/9ah7rdw0/" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-12T17:35:08.763", "Id": "475208", "Score": "0", "body": "I missed the `.src`... lol I feel dumb!" } ], "meta_data": { "CommentCount": "15", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-12T09:46:53.453", "Id": "242127", "ParentId": "242113", "Score": "3" } } ]
{ "AcceptedAnswerId": "242127", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-12T03:32:26.147", "Id": "242113", "Score": "3", "Tags": [ "javascript", "html" ], "Title": "Does my graphics engine code follow good conventions?" }
242113
<p>I have created a bash script to generate a HTML file, which will have the duration of the audio/video files in the current folder. The script uses <code>ffprobe</code> to fetch the duration in the quiet mode and <code>file</code> to get the mime-type. Although, the script works as intended, <strong>it feels a bit slow. I was wondering if it is possible to speed it up</strong>. However, I don't have any experience in scripting and don't know about any time profiling tools. I did come across a stackoverflow answer on that topic, but time profiling can't suggest new libs or methods.</p> <p>I did come across a suggestion on the SO from the python world using opencv and the benchmarks looked promising, but I am wary of installing such a huge library, and its big or small dependencies, just for this.</p> <pre><code>#!/bin/bash today=$(date +"%Y-%m-%d-%H-%M-%S") file=$(printf "duration-${today}.html") tot_dur=0 echo "&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;style&gt; table { border: 1px solid black; border-collapse: collapse; } th, td { border: 1px solid black; text-align: left; padding: 8px; } tr:nth-child(even) {background-color: #f5f5f5;} &lt;/style&gt; &lt;/head&gt; &lt;body&gt;" &gt;&gt; "${file}" echo "&lt;table&gt;" &gt;&gt; "${file}" echo "&lt;tr&gt; &lt;th&gt;File&lt;/th&gt; &lt;th&gt;Duration&lt;/th&gt; &lt;/tr&gt;" &gt;&gt; "${file}" while read filename do mime=$(file -b --mime-type "${filename}") IFS='/' read -r -a mime &lt;&lt;&lt; "$mime" if [[ $mime == "video" || $mime == "audio" ]]; then duration=$(ffprobe -v quiet -of default=noprint_wrappers=1:nokey=1 -show_entries format=duration "${filename}") tot_dur=$(echo $tot_dur + $duration | bc -l) duration=$(printf '%02d:%02d:%02f\n' $(echo -e "$duration/3600\n$duration%3600/60\n$duration%60"| bc | xargs echo)) echo "&lt;tr&gt;&lt;td&gt;"${filename}"&lt;/td&gt;&lt;td&gt;"${duration}"&lt;/td&gt;&lt;/tr&gt;" &gt;&gt; "${file}" fi done &lt; &lt;(ls) # (find . -type f) tot_dur=$(printf '%02d:%02d:%02f\n' $(echo -e "$tot_dur/3600\n$tot_dur%3600/60\n$tot_dur%60"| bc | xargs echo)) echo "&lt;tr&gt; &lt;td&gt;&lt;b&gt;Total&lt;/td&gt; &lt;td&gt;&lt;b&gt;${tot_dur}&lt;/td&gt; &lt;/tr&gt;" &gt;&gt; "${file}" echo "&lt;/table&gt;" &gt;&gt; "${file}" echo "&lt;/body&gt; &lt;/html&gt;" &gt;&gt; "${file}" </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-12T04:07:48.053", "Id": "242115", "Score": "1", "Tags": [ "performance", "bash" ], "Title": "Slow bash script for getting audio/video duration" }
242115
<p>I have the following code which works fine but the execution time is more which I want to reduce. I guess this happens since each file is opened and then the operation is performed. Is there a way to open the file once, perform all operations, and then close it, which may improve the processing speed?</p> <p>At a high level, the code is using Beautiful soup and finding tags and changing href, id attributes content to lowercase, change referenced file extension from xml to dita. Last piece of code changes the filenames to lowercase and file extension from xml to dita. I have added comments before each block to indicate the operation that the code is performing. </p> <p>All the functions work as expected, but, the problem is with the processing time since every time file is opened and written for each function. I want to improve it by combining all the functions together so that the file is opened once, all changes are made at the same time, which may improve the performance. I tried to bring in all the functions together, but, the code did not work. I am new to Python, so do not have the expertise needed to achieve this.</p> <pre><code>import os import glob from bs4 import BeautifulSoup as bs #Following code is to find fig, concept, table tags in all xml files and change id attribute to lowercase. def lower_figcontab_id(file_path): with open(path, encoding="utf-8") as f: s = f.read() s = bs(s, "xml") fct = s.find_all(["fig", "concept", "table"]) for i in fct: if "id" in i.attrs: i.attrs["id"] = i.attrs["id"].lower() s = str(s) with open(path, "w", encoding="utf-8") as f: f.write(s) upper_directory = "C:/Users/sh001/Desktop/onemore/content" #add your directory path here for dirpath, directories, files in os.walk(upper_directory): for files in glob.iglob('C:/Users/sh001/Desktop/onemore/content/**/*.xml', recursive=True): #finds all .xml files and updates references for fname in files: path = os.path.join(dirpath, files) lower_figcontab_id(path) #Following code is to find image, xref, topicref tags and change href attribute to lowercase, and change .xml to dita file reference extension in href attribute. def lower_topic_references(file_path): with open(path, encoding="utf-8") as f: s = f.read() s = bs(s, "xml") refs = s.find_all("topicref") for i in refs: if "href" in i.attrs: i.attrs["href"] = i.attrs["href"].replace("xml", "dita").lower() s = str(s) with open(path, "w", encoding="utf-8") as f: f.write(s) upper_directory = "C:/Users/sh001/Desktop/onemore/content" #add your directory path here for dirpath, directories, files in os.walk(upper_directory): #for files in glob.iglob('C:/Users/sh001/Desktop/newtest/**/*.xml', recursive=True): #finds all .xml files and updates references for files in glob.iglob('C:/Users/sh001/Desktop/onemore/content/**/*.ditamap', recursive=True): #finds all .dita files and updates references for fname in files: path = os.path.join(dirpath, files) lower_topic_references(path) #Following code finds the image, xref, topicref tags and changes the case of href to lowercase. def lower_file_references(file_path): with open(path, encoding="utf-8") as f: s = f.read() s = bs(s, "xml") imgs = s.find_all(["image", "xref", "topicref"]) for i in imgs: if "href" in i.attrs: i.attrs["href"] = i.attrs["href"].lower() s = str(s) with open(path, "w", encoding="utf-8") as f: f.write(s) upper_directory = "C:/Users/sh001/Desktop/onemore/content" #add your directory path here for dirpath, directories, files in os.walk(upper_directory): for files in glob.iglob('C:/Users/sh001/Desktop/onemore/content/**/*.xml', recursive=True): #finds all .xml files and updates references #for files in glob.iglob('C:/Users/sh001/Desktop/newtest/**/*.dita', recursive=True): #finds all .dita files and updates references #if files.endswith(".xml") or files.endswith(".dita"): for fname in files: path = os.path.join(dirpath, files) lower_file_references(path) #Following code finds xref tag and replaces .xml to .dita for href attribute. def change_file_extension_in_references(file_path): with open(path, encoding="utf-8") as f: s = f.read() s = bs(s, "xml") ext = s.find_all(["xref"]) for i in ext: if "href" in i.attrs: i.attrs["href"] = i.attrs["href"].replace(".xml",".dita") s = str(s) with open(path, "w", encoding="utf-8") as f: f.write(s) upper_directory = "C:/Users/sh001/Desktop/onemore/content" #add your directory path here for dirpath, directories, files in os.walk(upper_directory): for files in glob.iglob('C:/Users/sh001/Desktop/onemore/content/**/*.xml', recursive=True): #finds all .xml files and updates references for fname in files: path = os.path.join(dirpath, files) change_file_extension_in_references(path) #Following code changes file extension from .xml to .dita and changes the case to lowercase. path = "C:/Users/sh001/Desktop/onemore/content" for dir,subdir,listfilename in os.walk(path): for filename in listfilename: new_filename = filename.replace(".xml",".dita").lower() src = os.path.join(dir, filename) dst = os.path.join(dir, new_filename) os.rename(src,dst) <span class="math-container">```</span> </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-12T09:19:56.460", "Id": "475139", "Score": "0", "body": "Please tell us more about what the code is supposed to do. The current question title, which states your concerns about the code, applies to too many questions on this site to be useful. The site standard is for the title to simply state the task accomplished by the code. Please see [ask] for examples, and revise the title accordingly." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-12T10:49:53.030", "Id": "475143", "Score": "0", "body": "A data sample would help as well, please show an example of input file and what result you want." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-12T11:46:25.587", "Id": "475145", "Score": "0", "body": "I will prepare a sample and share it soon." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-12T12:36:45.913", "Id": "475149", "Score": "0", "body": "From the documentation of glob: \"Note: Using the “**” pattern in large directory trees may consume an inordinate amount of time. \"" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-12T12:40:34.103", "Id": "475150", "Score": "0", "body": "What's going on with `def lower_figcontab_id(file_path)` when you don't use `file_path` anywhere else in the definition of the function?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-12T12:40:53.577", "Id": "475151", "Score": "0", "body": "`for fname in files` followed by code that never mentions `fname` again?" } ]
[ { "body": "<p>I'm not surprised you had trouble modifying the code and making it work. It takes some careful thought to understand how it is working at all.</p>\n\n<pre><code>upper_directory = \"C:/Users/sh001/Desktop/onemore/content\" #add your directory path here\nfor dirpath, directories, files in os.walk(upper_directory):\n</code></pre>\n\n<p>Here, <code>os.walk</code> creates a generator that \"visits\" C:/Users/sh001/Desktop/onemore/content and every subdirectory of C:/Users/sh001/Desktop/onemore/content, recursively. The <code>for</code> ensures that the code following this line will execute once for each directory visited by the generator.</p>\n\n<pre><code> for files in glob.iglob('C:/Users/sh001/Desktop/onemore/content/**/*.xml', recursive=True): #finds all .xml files and updates references\n</code></pre>\n\n<p>Here, <code>glob.iglob</code> returns a list containing the full paths of all *.xml files in C:/Users/sh001/Desktop/onemore/content and in all subdirectories of C:/Users/sh001/Desktop/onemore/content, recursively. The <code>for</code> ensures that the lines after it will be executed once for each filepath in the list.</p>\n\n<p>Already I can see a reason why the script is so slow. The line starting <code>for files in glob.iglob</code> all by itself ensures that you will process every file in C:/Users/sh001/Desktop/onemore/content and all its subdirectories (recursively searched). The line <em>before</em> that line ensures that you won't just process the files once. You'll process all the files, and then you'll process them all <em>again</em> N more times, where N is the number of subdirectories of C:/Users/sh001/Desktop/onemore/content (recursively searched).</p>\n\n<p>But didn't you need <code>dirpath</code> from <code>os.walk</code> in order to make the following work?</p>\n\n<pre><code> path = os.path.join(dirpath, files)\n</code></pre>\n\n<p>Actually, you didn't. Since <code>files</code> is an absolute path to a file, <code>join</code> ignores <code>dirpath</code> and just returns <code>files</code>.</p>\n\n<p>But back to your nested loops:</p>\n\n<pre><code> for fname in files:\n</code></pre>\n\n<p>Here, <code>files</code> is a single string that is defined in one iteration of the previous <code>for files</code>. Since <code>files</code> is a string, <code>for fname in files:</code> iterates once for each letter in the string, setting <code>fname</code> to each letter in turn.</p>\n\n<p>OK, so not only are you processing every file multiple times due to iterating over <code>os.walk</code>, you are also multiplying the multiple times by the number of characters in the full file path to each file.\nThat is, if C:/Users/sh001/Desktop/onemore/content has just 2 subdirectories that have 2 subdirectories each (and no more), that's 7 directories total; and if the average length of the full path to each file (including the initial part of the path, C:/Users/sh001/Desktop/onemore/content) is 50 characters, you are processing every single file 350 times. No wonder it's slow.</p>\n\n<p>(It's possible I've made a mistake somewhere in this analysis. Honestly, I didn't check very carefully, because code of such poor quality is not worth the trouble. You should know that nesting three different kinds of <code>for</code> loops like this is a terrible code smell. Just don't do it.)</p>\n\n<p>When you're learning how to process a lot of files using iterators like these, it's helpful to insert some debug printout in the early versions of your script, printing out the name of the file just before you process that file. In this case, with multiple loops, I would just debug the first loop to start with (because I would only <em>write</em> the first loop to start with and would wait until I was sure it worked right before writing any other processing). For example, instead of just calling <code>lower_figcontab_id(path)</code>, you could have</p>\n\n<pre><code> print(path)\n lower_figcontab_id(path)\n</code></pre>\n\n<p>You might want to take out the <code>print</code> once everything is working OK. Or maybe not--it can be helpful to have confirmation in the console output that your script is working.</p>\n\n<hr>\n\n<p>I think you should start over, though you can salvage some bits and pieces from this script (such as the operations you perform on the BeautifulSoup objects).\nA good basic structure would be to write a loop of some kind--using os.walk is fine, or glob.iglob, <em>but not both</em>--that will list the full path to each *.xml file exactly once. Once you have such a full path in a variable named <code>path</code>, this part of your code makes a BeautifulSoup object <code>s</code> from it:</p>\n\n<pre><code> with open(path, encoding=\"utf-8\") as f:\n s = f.read()\n s = bs(s, \"xml\")\n</code></pre>\n\n<p>Do all the operations you want on <code>s</code>. It's helpful to have a function for each transformation, as you do, but rather than take a path as the argument to the function it's better to take <code>s</code> as the argument to the function and return the modified copy of <code>s</code> back to the caller when you're done.\nAfter all that you can use the code you've already written to write the contents of <code>s</code> to the file.</p>\n\n<hr>\n\n<p>To avoid making such a mess in the future, write your scripts incrementally. Get a few lines that do some part of the job and test that they actually do what you think (and not a lot more than you think or a lot less). Temporary <code>print</code> statements can help you keep track of your failures and successes.\nWhen you have pieces that work you can put subroutines in them or use them as subroutines for other pieces.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-15T05:05:59.107", "Id": "475522", "Score": "0", "body": "Thanks David. The analysis you have made is right about the code. Since the files are being opened multiple times, the execution time is getting impacted. Initially, there was only os.walk but that started manipulating the graphic files too which became unusable, hence I had to include glob function to select the file type to parse. This may have slowed down the execution time. Any suggestion to select file type without using glob function? I am very new to scripting, hence don't know much about what would be the best method to use." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-15T05:23:46.557", "Id": "475523", "Score": "0", "body": "I tried using if files.endswith('.xml'): and got the error -> AttributeError: 'list' object has no attribute 'endswith'" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-15T05:43:03.740", "Id": "475526", "Score": "0", "body": "I tried using if fname.endswith('.xml'): and got the error -> join() argument must be str or bytes, not 'list'" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-15T05:58:10.360", "Id": "475527", "Score": "0", "body": "I was able to fix all errors and also improve the execution time. Before the script would take 7 minutes for 2 folders to execute all the functions, now, it takes less than a minute to parse through 2 folders and make all the changes. Thanks for the tip on not including os.walk and glob functions together." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-15T05:58:56.207", "Id": "475528", "Score": "0", "body": "Improved piece of code (added this to all functions) -> for fname in files:\n if fname.endswith(\".xml\"):\n path = os.path.join(dirpath, fname)\n lower_figcontab_id(path)" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-13T03:27:25.953", "Id": "242163", "ParentId": "242123", "Score": "1" } } ]
{ "AcceptedAnswerId": "242163", "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-12T08:22:43.187", "Id": "242123", "Score": "3", "Tags": [ "python", "python-3.x" ], "Title": "Finding tags and changing id attributes" }
242123
<p>Below program find a minimum positive number that is greater than 0, it doesn't occur in the array. My solution actually works fulfil performance-wise. However, Codelity has given 55% only, I m trying to understand what is the potential issues with below code?</p> <hr> <p>For example, given A = [1, 3, 6, 4, 1, 2], the function should return 5.</p> <hr> <pre><code>#include &lt;stdio.h&gt; #define ARRAY_SIZE(a) sizeof(a) / sizeof(a[0]) int solution(int A[], int N) { // write your code in C99 (gcc 6.2.0) int i=0, j=0, k=0; int result = 1, tmp = 0; for(i=0; i &lt; N; i++) { for(j=i+1; j &lt; N; j++) { if(A[j] &lt; A[i]) { tmp = A[i]; A[i] = A[j]; A[j] = tmp; } } } for (i = 0; i &lt; N; i++) { printf("%d\n", A[i]); } for ( k = 0; k &lt; N; k++) { if (A[k] == result) result += 1; if (A[k] &gt; result) break; } return result; } int main(void) { int a[] = {1,3,6,4,1,2}; int ret = solution(a, ARRAY_SIZE(a)); printf("Smallest positive integer: %d\n", ret); return 0; } </code></pre>
[]
[ { "body": "<p>At first glance, your code looks quite verbose. Seeing as it was an assignment for some type of class, I'm also assuming that points would've been deducted for you doing something that is considered bad practice. With this in mind, let's go through the code:</p>\n\n<pre><code> int i=0, j=0, k=0;\n int result = 1, tmp = 0;\n\n for(i=0; i &lt; N; i++) {\n for(j=i+1; j &lt; N; j++) {\n if(A[j] &lt; A[i]) {\n tmp = A[i];\n A[i] = A[j];\n A[j] = tmp;\n }\n }\n }\n\n for (i = 0; i &lt; N; i++) {\n printf(\"%d\\n\", A[i]);\n }\n</code></pre>\n\n<p>In C99, declaring all variables at the start of the function isn't required. Variables like <code>i</code>, <code>j</code>, and <code>k</code> should be block scoped.</p>\n\n<p>You're also sorting your array in a function that is called <code>solution</code>. The name isn't very descriptive, and given how that function returns an integer, I wouldn't expect it to actually <em>change</em> the array I'm passing.</p>\n\n<p>Your solution function has a single point of return. That's fine, if that's what you were asked to do. However, generally speaking, most people prefer to return early. It simplifies the code, and reduces the total number of <code>else</code>'s quite a lot.</p>\n\n<p>You're missing some checks. An array, once passed to a function, decays into a pointer. I'd write the function as <code>int solution(int *in, int size)</code>, and if I wanted to be paranoid about safety, I'd check for <code>in == NULL</code> and make sure <code>size</code> is non-negative. Then again, the size of the array is obtained through the <code>sizeof</code> operator, which actually yields a value of type <code>size_t</code>. Perhaps it makes sense to change your function argument to accept a <code>size_t</code> instead of an int? <code>size_t</code> is unsigned, so no need to check for negative values there...</p>\n\n<p>You're sorting the array in ascending order. Understandable, of course, but why aren't you using <code>qsort</code>? It's better practice to write functions that only do 1 thing. Your <code>solution</code> function handles sorting, prints some debug output, and then sets about searching the lowest missing positive integer. Let's assume, for now, that changing the array that's being passed is not an issue, I'd break things up into 2 functions and write this:</p>\n\n<pre><code>static\nint sort_ascending(const void *a, const void *b) {\n int av = *(int *)a, bv = *(int *)b;\n\n if (av == bv)\n return 0;\n if (av &gt; bv)\n return 1;\n return -1;\n}\n\nstatic\nint get_missing(int *in, size_t size) {\n // let's make sure the pointer can be dereferenced:\n if (in == NULL)\n return -1; // -1 is a common error value to return\n // first, sort the array\n qsort(in, size, sizeof *in, sort_ascending);\n\n // now let's just iterate over the array and find the answer\n // note, we're iterating until the NEXT TO LAST element, because we access in[i+1] in the body\n for (int i = 0; i &lt; size-1; i++) {\n int v = in[i]+1; // the lowest possible value based on in[i]\n // if v is positive, and smaller than the next value in the array\n // we're done, and we can return\n if (v &gt; 0 &amp;&amp; v &lt; in[i+1])\n return v;\n }\n // we didn't return from the loop. The lowest value is in[size-1]+1, if it's positive:\n int last = in[size-1]+1;\n if (last &gt; 0)\n return last;\n // the highest value in the array was still negative, so the lowest positive missing value is 1\n return 1;\n}\n</code></pre>\n\n<p>The last bit (getting the last value from the input, adding 1 and returning) is something that I'd probably leave at the end, but some might choose to perform this check before iterating the array. If the last (highest) value in the array is still negative, the loop is just a waste of time. The function then would look like this:</p>\n\n<pre><code>static\nint get_missing(int *int, size_t size) {\n if (in == NULL || size == 0)\n return -1;\n qsort(in, size, sizeof *in, sort_ascending);\n\n if (in[size-1] &lt;= 0) // highest value is 0 or less\n return 1;\n\n for (int i = 0; i &lt; size -1; i++) {\n int v = in[i]+1;\n if (v &gt; 0 &amp;&amp; v &lt; in[i+1])\n return v;\n }\n}\n</code></pre>\n\n<p>As you can see, the function is a lot smaller, and fairly easy to read. The thing I don't like about checking the last element in the array before iterating is that it means the last return in the function is kind of <em>\"hidden\"</em> in a loop body. That may be personal preference, and if the input array is potentially huge, it's likely to be more efficient to preform that check. Then again, using <code>qsort_r</code> and passing in a pointer to an <code>int</code> allows you to count the number of negative values in the array, and that way you can start the iteration at the correct offset right away, but that's premature optimization. Let's get back to the matter at hand.</p>\n\n<hr>\n\n<h2>What was changed:</h2>\n\n<p>So far, we've changed:</p>\n\n<ul>\n<li>Sorting separated out in a separate function, and using <code>qsort</code> rather than a nested loop</li>\n<li>Checking for zero and NULL array</li>\n<li>Returning early</li>\n<li>Have error values returned in case the input is invalid (a <code>-1</code>)</li>\n</ul>\n\n<p>What we still haven't addressed is the side-effect your function has. The input array is altered. This is considered bad practice (unless it's well documented, and is done for a clear reason). The way I'd solve it is by creating a <em>copy</em>:</p>\n\n<pre><code>static\nint get_missing(const int *in, size_t size) {\n if (in == NULL || size == 0)\n return -1;\n // allocate memory for copy of input array\n int *temp = malloc(size * sizeof *in);\n if (temp == NULL)\n return -1;\n // copy the array\n memcpy(temp, in, size * sizeof *temp);\n\n // from here on, we use the copy\n qsort(temp, size, sizeof *temp, sort_ascending);\n if (temp[size-1] &lt;= 0) {\n free(temp); // free memory\n return 1;\n }\n\n for (int i = 0; i &lt; size -1; i++) {\n int v = temp[i]+1;\n if (v &gt; 0 &amp;&amp; v &lt; temp[i+1]) {\n free(temp);\n return v;\n }\n }\n}\n</code></pre>\n\n<p>Now if we do something like:</p>\n\n<pre><code>int main( void ) {\n int arr[] = int a[] = {1,3,6,4,1,2};\n int ret = get_missing(arr, ARRAY_SIZE(arr));\n for (int i=0; i &lt; ARRAY_SIZE(arr); i++)\n printf(\"arr[%d] = %d\\n\", i, arr[i]);\n printf(\"Lowest positive int not in arr is %d\\n\", ret);\n return 0;\n}\n</code></pre>\n\n<p>You'll see that the original array was not altered. The <code>get_missing</code> function now also communicates that clearly to:</p>\n\n<pre><code>int get_missing(const int *in, size_t size);\n</code></pre>\n\n<p>Looking at this, I know right away this function will return an int, accepts a pointer (decayed array), and will not change the argument (as it's <code>const</code>). I am expected to pass in a size value, which cannot be negative.</p>\n\n<p>Putting it all together:</p>\n\n<pre><code>#include &lt;stdio.h&gt;\n#include &lt;stdlib.h&gt;\n#include &lt;string.h&gt;\n\n#define ARRAY_SIZE(a) (sizeof(a) / sizeof(a[0]))\n\nstatic\nint sort_callback(const void* a, const void* b) {\n int av = *((int *)a), bv = *(int *)b;\n\n if (av == bv)\n return 0;\n if (av &lt; bv)\n return -1;\n return 1;\n}\n\nstatic\nint get_missing_sideeffect(int *arr, int size) {\n qsort(arr, size, sizeof *arr, sort_callback);\n\n for (int i = 0; i &lt; size-1; i++) {\n int next = arr[i] +1;\n if (next &gt; 0 &amp;&amp; arr[i+1] &gt; next)\n return next;\n }\n\n int last = arr[size-1];\n if (last &lt;= 0)\n last = 0;\n\n return last+1;\n}\n\nstatic\nint get_missing(const int *in, size_t size) {\n if (in == NULL || size == 0)\n return -1;\n\n int *temp = malloc(size * sizeof *in);\n if (temp == NULL)\n return -1;\n\n memcpy(temp, in, size * sizeof *in);\n\n qsort(temp, size, sizeof *temp, sort_callback);\n if (temp[size-1] &lt;= 0) {\n free(temp);\n return 1;\n }\n\n for (int i = 0; i &lt; size -1; i++) {\n int v = temp[i]+1;\n if (v &gt; 0 &amp;&amp; v &lt; temp[i+1]) {\n free(temp);\n return v;\n }\n }\n}\n\nint main(void) {\n int a[] = {1,3,6,4,1,2};\n int ret1 = get_missing(a, ARRAY_SIZE(a));\n // prints out a unchanged\n for (int i = 0; i &lt; ARRAY_SIZE(a); i++)\n printf(\"a[%d] = %d\\n\", i, a[i]);\n int ret2 = get_missing_sideeffect(a, ARRAY_SIZE(a));\n\n printf(\"Smallest positive integer: %d -&gt; %d\\n\", ret1, ret2);\n\n // shows a was changed due to side-effect\n for (int i = 0; i &lt; ARRAY_SIZE(a); i++)\n printf(\"a[%d] = %d\\n\", i, a[i]);\n\n return 0;\n}\n</code></pre>\n\n<hr>\n\n<p>As chux correctly pointed out: the version I posted here could've resulted in integer overflow. To fix this problem, it's a simple matter of returning <code>0</code> to indicate an error, and an <code>unsigned int</code> in all other cases (if the input has all ints up to (and including) <code>INT_MAX</code>).</p>\n\n<p>Another issue I've realised is that the code wouldn't return a value like <code>1</code>, if the input looked something like <code>{2, 3, 4, 5}</code>, whereas clearly, the smallest positive int missing from the array is <code>1</code>. For these reasons, I'll write a final version of <code>get_missing</code> here:</p>\n\n<pre><code>static\nunsigned int get_missing(const int *in, size_t size) {\n if (in == NULL || size == 0)\n return 0;\n\n int *temp = malloc(size * sizeof *in);\n if (temp == NULL)\n return 0;\n\n memcpy(temp, in, size * sizeof *in);\n\n qsort(temp, size, sizeof *temp, sort_callback);\n\n // lowest value in temp &gt; 1, or highest value is zero or less\n if (temp[0] &gt; 1 || temp[size-1] &lt;= 0) {\n free(temp);\n return 1;\n }\n\n unsigned int v = 0;\n for (int i = 0; i &lt; size -1; i++) {\n v = temp[i]+1u;\n if (v &gt; 0 &amp;&amp; v &lt; temp[i+1]) {\n free(temp);\n return v;\n }\n }\n return v;\n}\n</code></pre>\n\n<p>So I've added the check to make sure we return 1 if the input starts with 2 or more. I've changed the function to return an <code>unsigned int</code> (which means you have to print the output using <code>printf(\"Return value %ud\\n\", ret);</code>). Lastly, I'm also declaring <code>v</code> outside of the for loop. The last return statement won't ever be reached, but when I compiled the code in its original form (<code>gcc -std=c99 main.c -o missing -Wall</code>), the compiler spits out a warning.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-12T22:09:37.637", "Id": "475236", "Score": "2", "body": "Nice review. UV. For fun on a pedantic note `arr[i] +1` may overflow with array [1,2,3...INT_MAX]. Instead of returning `int`, code could return `unsigned` (to form `INT_MAX+1u` and return 0 for `size==0` case." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-13T14:07:23.417", "Id": "475329", "Score": "1", "body": "@chux-ReinstateMonica Thank you, and yes, you're right. I've added an updated version where I return an `unsigned int`. I also realised the function wouldn't have returned the correct value if the input started above 1, and I've changed it to have a (albeit redundant) return statement at the end, so squelch a compiler warning" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-12T14:52:12.750", "Id": "242138", "ParentId": "242126", "Score": "4" } } ]
{ "AcceptedAnswerId": "242138", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-12T09:20:35.047", "Id": "242126", "Score": "4", "Tags": [ "c", "array" ], "Title": "Want to know vulnerabilities in below program finding minimum positive number greater than 0 that doesn't occur in array" }
242126
<p>I recently played around with a script that got some data from the Google API. As I didn't want to spam requests at the service (and potentially get blocked), I made this decorator, which caches the result of a function for a specified amount of time. Any call after the time-to-live (TTL) will call the function again.</p> <p>This is the first decorator I wrote that takes an optional argument (the time to keep the cache). That code was taken from this <a href="https://stackoverflow.com/a/3931903/4042267">StackOverflow answer</a> by <a href="https://stackoverflow.com/users/243483/eric">@Eric</a>. I also couldn't abstain from using the new walrus operator (Python 3.8+), since I'm always looking for opportunities to use it in order to get a better feel for it.</p> <p>Any and all advice on how to make this better or more readable are welcome.</p> <pre><code>from datetime import datetime from functools import wraps DEBUG = True def temporary_cache(*args, ttl=60): """A decorator that ensures that the result of the function call is cached for `ttl` seconds (default: 60). Warning: The returned object is stored directly, mutating it also mutates the cached object. Make a copy if you want to avoid that. """ def decorator(func): func.cache = None func.cache_time = datetime.fromordinal(1) @wraps(func) def inner(*args, **kwargs): if ((now := datetime.now()) - func.cache_time).total_seconds() &gt; ttl: func.cache = func(*args, **kwargs) func.cache_time = now elif DEBUG: # for debugging, disable in production print("Cached", func.__name__) return func.cache return inner if len(args) == 1 and callable(args[0]): return decorator(args[0]) elif args: raise ValueError("Must supply the decorator arguments as keywords.") return decorator </code></pre> <p>Example usages:</p> <pre><code>import time @temporary_cache def f(): return datetime.now() @temporary_cache(ttl=1) def g(): return datetime.now() if __name__ == "__main__": print(f()) # 2020-05-12 10:41:18.633386 time.sleep(2) print(f()) # Cached f # 2020-05-12 10:41:18.633386 print(g()) # 2020-05-12 10:41:20.635594 time.sleep(2) print(g()) # 2020-05-12 10:41:22.636782 </code></pre> <p>Note that <code>f</code> was still cached, while <code>g</code> was not, because the TTL is shorter than the time between calls.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-12T18:53:41.053", "Id": "475218", "Score": "0", "body": "What do you want to happen if the cached function has different arguments? Or do you only cache functions that don't take arguments?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-12T21:31:49.623", "Id": "475233", "Score": "0", "body": "@RootTwo: Good question! The decorator allows arguments, but ignores them. This is fine for the usecase I had (a function with no arguments), but in order to generalize it I would have to make `cache` and `cache_time` dictionaries of the arguments." } ]
[ { "body": "<ul>\n<li><p>Rather than using <code>*args</code> you can supply a default positional only argument.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def temporary_cache(fn=None, *, ttl=60):\n ...\n if fn is not None:\n return decorator(fn)\n return decorator\n</code></pre></li>\n<li><p>If you feel following \"flat is better than nested\" is best, we can use <code>functools.partial</code> to remove the need to define <code>decorator</code>.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def temporary_cache(fn=None, *, ttl=60):\n if fn is None:\n return functools.partial(temporary_cache, ttl=ttl)\n\n @functools.wraps(fn)\n def inner(*args, **kwargs):\n ...\n</code></pre></li>\n<li><blockquote>\n <p>for debugging, disable in production</p>\n</blockquote>\n\n<p>You can use <code>logging</code> for this. I will leave actually implementing this as an exercise.</p></li>\n<li><blockquote>\n <p>I also couldn't abstain from using the new walrus operator (Python 3.8+), since I'm always looking for opportunities to use it in order to get a better feel for it.</p>\n</blockquote>\n\n<p>A very reasonable thing to do. Abuse the new feature until you know what <em>not</em> to do. +1</p>\n\n<p>However, I don't think this is a good place for it.\nGiven all the brackets in such a small space I'm getting bracket blindness.\nI can't tell where one bracket ends and the others starts.</p></li>\n<li><p>I am not a fan of <code>func.cache = ...</code> and <code>func.cache_time</code>. You can stop assigning to a function by using <code>nonlocal</code>.</p></li>\n</ul>\n\n<p>Bringing this all together, and following some of my personal style guide, gets the following. I'm not really sure which is <em>better</em>, but it's food for thought.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>from datetime import datetime\nimport functools\n\n\ndef temporary_cache(fn=None, *, ttl=60):\n if fn is None:\n return functools.partial(temporary_cache, ttl=ttl)\n\n cache = None\n cache_time = datetime.fromordinal(1)\n\n @functools.wraps(fn)\n def inner(*args, **kwargs):\n nonlocal cache, cache_time\n now = datetime.now()\n if ttl &lt; (now - cache_time).total_seconds():\n cache = fn(*args, **kwargs)\n cache_time = now\n elif DEBUG:\n # for debugging, disable in production\n print(\"Cached\", fn.__name__)\n return cache\n return inner\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-12T13:36:03.577", "Id": "475157", "Score": "0", "body": "I was playing around with making `ttl` keyword only, but when preceeded by `*args` it insisted on `args` having to be empty(?). This is a nice way around it. I also previously had `nonlocal`, but liked `func.cache` more because then it is possible to get the value from outside. Didn't know you could assign multiple variables `nonlocal` at once, though!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-12T13:43:41.003", "Id": "475158", "Score": "1", "body": "@Graipher That sounds strange, I really don't know what was going on there :O I'm not entirely sure why you want to get `func.cache` from the outside, but me understanding isn't really important :) However since you do, might I suggest `inner.cache` over `func.cache`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-12T14:16:54.253", "Id": "475160", "Score": "0", "body": "Well, whenever I was using caching decorators in the past, there came the time (during development) where I needed to have a look what was actually in the cache, so it's just convenience, I guess :D" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-12T13:23:51.083", "Id": "242135", "ParentId": "242129", "Score": "5" } } ]
{ "AcceptedAnswerId": "242135", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-12T10:45:47.200", "Id": "242129", "Score": "7", "Tags": [ "python", "python-3.x", "functional-programming", "cache" ], "Title": "Decorator to cache a function result for some time" }
242129
<p>I'm learning C++ and did some reading here and elsewhere on trie structures. I've written a simple class that performs insert and match using a sorted vector as the underlying container. </p> <p>I used unique_ptr, but I get nervous using the .get() method to access the raw pointer. Is there a better way? </p> <p>Also, I had to overload the operator&lt;, but I'm wondering if there is a better approach than the 3 methods shown.</p> <p>It would be great to get any other feedback too. Don't be nice. I need conditioning to face <strong><em>The Tech Lead</em></strong>.</p> <p>Thanks for reading. George</p> <pre><code>#include &lt;iostream&gt; #include &lt;memory&gt; #include &lt;sstream&gt; #include &lt;string&gt; #include &lt;vector&gt; using namespace std; template&lt;class T&gt; class trie { struct node_t { T val; vector&lt;trie&lt;T&gt;&gt; children; explicit node_t(const T&amp; _val) : val(_val){}; }; unique_ptr&lt;node_t&gt; root; public: using iterator_type = typename vector&lt;trie&lt;T&gt;&gt;::iterator; using const_iterator_type = typename vector&lt;trie&lt;T&gt;&gt;::const_iterator; trie() = default; explicit trie(const T&amp; val): root(make_unique&lt;node_t&gt;(val)) {}; T&amp; val() const { return root-&gt;val; } vector&lt;basic_string&lt;T&gt;&gt; match(const basic_string&lt;T&gt; &amp; s) { basic_string&lt;T&gt; prefix; node_t const* n = root.get(); for (typename basic_string&lt;T&gt;::const_iterator s_it = s.cbegin(); s_it &lt; s.cend() ; ++s_it) { const_iterator_type h_it = lower_bound(n-&gt;children.cbegin(), n-&gt;children.cend(), *s_it); if (h_it != n-&gt;children.cend() &amp;&amp; !(*s_it &lt; *h_it)) // value exists { prefix.push_back(*s_it); n = h_it-&gt;root.get(); } else break; } vector&lt;basic_string&lt;T&gt;&gt; matches; for (const_iterator_type it = n-&gt;children.cbegin(); it != n-&gt;children.cend(); ++it) { vector&lt;basic_string&lt;T&gt;&gt; suffixes = get_suffixes(it); transform(suffixes.cbegin(), suffixes.cend(), back_inserter(matches), [&amp;prefix](const basic_string&lt;T&gt;&amp; suffix) { return prefix + suffix; }); } return matches; } pair&lt;const_iterator_type,bool&gt; insert(basic_string&lt;T&gt; const &amp; s) { if (s.empty()) return(make_pair(vector&lt;trie&lt;T&gt;&gt;().cend(),false)); if (!root) root = make_unique&lt;node_t&gt;(s[0]); node_t * n = root.get(); typename basic_string&lt;T&gt;::const_iterator s_it ; typename vector&lt;trie&lt;T&gt;&gt;::const_iterator it; for (s_it = s.begin(); s_it &lt; s.end(); ++s_it) { it = lower_bound(n-&gt;children.cbegin(), n-&gt;children.cend(), *s_it); if (it != n-&gt;children.cend() &amp;&amp; !(*s_it &lt; *it)) n = it-&gt;root.get(); else break; } if (s_it == s.end()) return make_pair(it,false); for (;s_it &lt; s.end(); ++s_it) { n-&gt;children.emplace_back(*s_it); sort(n-&gt;children.begin(), n-&gt;children.end()); it = lower_bound(n-&gt;children.cbegin(), n-&gt;children.cend(), *s_it); n = it-&gt;root.get(); } return make_pair(it, true); } private: vector&lt;basic_string&lt;T&gt;&gt; get_suffixes(const_iterator_type it) { node_t const* n = it-&gt;root.get(); vector&lt;basic_string&lt;T&gt;&gt; suffixes; if (n-&gt;children.empty()) { suffixes.emplace_back(1,n-&gt;val); return suffixes; } basic_string&lt;T&gt; s; vector&lt;basic_string&lt;T&gt;&gt; temp; for (const_iterator_type it = n-&gt;children.cbegin(); it != n-&gt;children.cend(); ++it) { temp = get_suffixes(it); } for (basic_string&lt;T&gt;&amp; s: temp) s = n-&gt;val + s; copy(temp.cbegin(), temp.cend(), back_inserter(suffixes)); return suffixes; } }; template &lt;typename T&gt; bool operator&lt; (const trie&lt;T&gt;&amp; l, const trie&lt;T&gt;&amp; r) { return l.val() &lt; r.val(); }; template &lt;typename T&gt; bool operator&lt; (const T&amp; l, const trie&lt;T&gt;&amp; r) { return l &lt; r.val(); }; template &lt;typename T&gt; bool operator&lt; (const trie&lt;T&gt;&amp; l, const T&amp; r) { return l.val() &lt; r; }; int main() { string s("bard barstool barraster barn barndoor brindille breezy broach"); stringstream sm(s); vector&lt;string&gt; words; copy(istream_iterator&lt;string&gt;(sm), istream_iterator&lt;string&gt;(), back_inserter(words)); cout &lt;&lt; words.back() &lt;&lt; endl; trie&lt;char&gt; t; for (string const&amp; w: words) t.insert(w); for (string const&amp; w: t.match("bar")) cout &lt;&lt; w &lt;&lt; endl; for (string const&amp; w: t.match("br")) cout &lt;&lt; w &lt;&lt; endl; return 0; } </code></pre>
[]
[ { "body": "<p><em>bug:</em></p>\n\n<p>Trie implementations need to mark word endings somehow. e.g. If you add the word \"bar\" to end of the input string, it won't be inserted in the trie (because the trie already contains the whole word as a prefix of other words, e.g. \"barndoor\"). We can't tell that the word \"bar\" is there as a separate word because the last letter isn't a leaf node.</p>\n\n<p>To mark the end of a word we need to either insert a special character that will always end up in a leaf node (e.g. '\\0' or '~'), or add a boolean variable to <code>node_t</code>. (Using a special character may be more efficient, but obviously means we can't store strings containing that character).</p>\n\n<hr>\n\n<p><em>fun(?) fact:</em></p>\n\n<p>If you reduce the input to just \"bard\", it will be printed by both of your <code>match</code> loops:</p>\n\n<pre><code>for (string const&amp; w: t.match(\"bar\")) cout &lt;&lt; w &lt;&lt; endl;\nfor (string const&amp; w: t.match(\"br\")) cout &lt;&lt; w &lt;&lt; endl;\n</code></pre>\n\n<p>That seems incorrect.</p>\n\n<hr>\n\n<p>I'm not sure if it's causing the above issue, but this looks suspicious:</p>\n\n<pre><code> basic_string&lt;T&gt; s;\n vector&lt;basic_string&lt;T&gt;&gt; temp;\n\n for (const_iterator_type it = n-&gt;children.cbegin(); \n it != n-&gt;children.cend();\n ++it)\n {\n temp = get_suffixes(it);\n }\n for (basic_string&lt;T&gt;&amp; s: temp) s = n-&gt;val + s;\n</code></pre>\n\n<p>We overwrite <code>temp</code> for each child, then only use the last value of <code>temp</code> after the loop.</p>\n\n<hr>\n\n<pre><code>trie() = default;\n...\n\nvector&lt;basic_string&lt;T&gt;&gt; match(const basic_string&lt;T&gt; &amp; s)\n{\n basic_string&lt;T&gt; prefix;\n node_t const* n = root.get();\n...\n</code></pre>\n\n<p><code>root.get()</code> will return <code>nullptr</code> for a default constructed trie (and then our <code>match</code> function will dereference it and crash). We could just return an empty vector (no matches) if the root isn't present.</p>\n\n<hr>\n\n<p>missing includes:</p>\n\n<ul>\n<li><code>#include &lt;algorithm&gt;</code> for <code>transform</code>.</li>\n<li><code>#include &lt;iterator&gt;</code> for <code>istream_iterator</code>.</li>\n</ul>\n\n<hr>\n\n<p><code>using namespace std;</code></p>\n\n<p><a href=\"https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice?answertab=votes#tab-top\">don't do that</a>.</p>\n\n<hr>\n\n<pre><code>struct node_t\n{\n T val;\n vector&lt;trie&lt;T&gt;&gt; children;\n explicit node_t(const T&amp; _val) : val(_val){};\n};\n</code></pre>\n\n<p>I'd definitely expect <code>children</code> to be a vector of <code>node_t</code>, not a vector of <code>trie</code>s.</p>\n\n<hr>\n\n<p>There are several places we can use range-based for loops (and <code>auto</code>) to simplify the code, e.g.:</p>\n\n<p><code>for (typename basic_string&lt;T&gt;::const_iterator s_it = s.cbegin(); s_it &lt; s.cend() ; ++s_it)</code></p>\n\n<p><code>for (auto const&amp; s_it : s)</code></p>\n\n<hr>\n\n<pre><code> typename vector&lt;trie&lt;T&gt;&gt;::const_iterator it;\n for (s_it = s.begin(); s_it &lt; s.end(); ++s_it)\n {\n\n it = lower_bound(n-&gt;children.cbegin(), n-&gt;children.cend(), *s_it);\n if (it != n-&gt;children.cend() &amp;&amp; !(*s_it &lt; *it))\n n = it-&gt;root.get();\n else break;\n }\n</code></pre>\n\n<p>Avoid reusing variables (unless they're expensive resources). In other words, declare <code>it</code> inside the loop.</p>\n\n<p>(In this case <code>it</code>'s actually used in a return statement outside the loop, but if you fix the bug pointed out above, that should never happen. Also, since we return <code>false</code> as the second member of the pair, the user should never access that iterator, so there's no point in returning it.)</p>\n\n<hr>\n\n<pre><code>if (!root) root = std::make_unique&lt;node_t&gt;(s[0]);\n</code></pre>\n\n<p>It looks like the root node's <code>val</code> is ignored. This could perhaps be clearer in the code (e.g. add a comment and give it a <code>val</code> of <code>0</code> or some other placeholder, instead of <code>s[0]</code>).</p>\n\n<hr>\n\n<pre><code> for (;s_it &lt; s.end(); ++s_it)\n {\n n-&gt;children.emplace_back(*s_it);\n sort(n-&gt;children.begin(), n-&gt;children.end()); \n it = lower_bound(n-&gt;children.cbegin(), n-&gt;children.cend(), *s_it);\n n = it-&gt;root.get();\n }\n</code></pre>\n\n<p>It would be better to find the insertion point for the new child, and insert it there directly. Then we don't have to sort the entire vector <em>and</em> then search it anyway to find our lost child.</p>\n\n<hr>\n\n<pre><code> if (s.empty()) return(make_pair(vector&lt;trie&lt;T&gt;&gt;().cend(),false));\n</code></pre>\n\n<p>We can default-construct an iterator, rather than creating an empty vector to get the end iterator.</p>\n\n<p>With modern C++, we can use list initialization:</p>\n\n<pre><code> return { {}, false };\n</code></pre>\n\n<hr>\n\n<p>Rather than overloading <code>operator&lt;</code>, we could create a functor, e.g.:</p>\n\n<pre><code>struct node_t_less\n{\n bool operator()(T a, node_t const&amp; b) const\n {\n return a &lt; b.val;\n }\n\n bool operator()(node_t const&amp; a, T b) const\n {\n return a.val &lt; b;\n }\n\n bool operator()(node_t const&amp; a, node_t const&amp; b) const\n {\n return a.val &lt; b.val;\n }\n};\n</code></pre>\n\n<p>and pass it to the algorithms where necessary</p>\n\n<pre><code> auto h_it = lower_bound(n-&gt;children.cbegin(), n-&gt;children.cend(), *s_it, node_t_less());\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-13T20:27:48.377", "Id": "475359", "Score": "0", "body": "That is all awesome thank you much for taking the time, I'll be applying all these, that's my homework." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-13T09:40:40.847", "Id": "242185", "ParentId": "242133", "Score": "2" } } ]
{ "AcceptedAnswerId": "242185", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-12T12:57:55.587", "Id": "242133", "Score": "5", "Tags": [ "c++", "trie", "overloading" ], "Title": "C++ simple dictionary match and insert, unique_ptr, operator<" }
242133
<p>I'm writing an app with NativeScript 6.4.1 and Angular version 8.</p> <p>There are a series of UI events in iOS that you can watch to see what the keyboard is doing: <a href="https://developer.apple.com/documentation/uikit/uikeyboarddidhidenotification?language=objc" rel="nofollow noreferrer">https://developer.apple.com/documentation/uikit/uikeyboarddidhidenotification?language=objc</a></p> <p>I wrote a service to watch and subscribe to these changes.</p> <p>Do you see any issues in the code with having too many Observables and listeners?</p> <p>Here is my service:</p> <pre><code>import { Injectable } from '@angular/core'; import { Observable } from 'rxjs'; import * as application from 'tns-core-modules/application'; @Injectable({ providedIn: 'root' }) export class iOSKeyboardObserverService { public didShow$(): Observable&lt;any&gt; { return new Observable((observer) =&gt; { const iosObserver = application.ios.addNotificationObserver(UIKeyboardDidShowNotification, (notification) =&gt; { observer.next(true); }); return () =&gt; { application.ios.removeNotificationObserver(iosObserver, UIKeyboardDidShowNotification); } }); } public didHide$(): Observable&lt;any&gt; { return new Observable((observer) =&gt; { const iosObserver = application.ios.addNotificationObserver(UIKeyboardDidHideNotification, (notification) =&gt; { observer.next(false); }); return () =&gt; { application.ios.removeNotificationObserver(iosObserver, UIKeyboardDidHideNotification); } }); } } </code></pre> <p>Example usage:</p> <pre><code>public isKeyboardShowing: boolean; constructor(private page: Page, private ngZone: NgZone, private keyboardObserver: iOSKeyboardObserverService) { this.page.on(Page.layoutChangedEvent, (args: EventData) =&gt; this.onLayoutChanged(args)); this.isKeyboardShowing = false; if (utils.ios) { this.keyboardObserver.didHide$().subscribe((result) =&gt; { this.setIsKeyboardShowing(result); }); this.keyboardObserver.didShow$().subscribe((result) =&gt; { this.setIsKeyboardShowing(result); }); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-29T14:00:34.940", "Id": "477118", "Score": "0", "body": "Why not create single observable as `this.keyboardObserver.visibility$().subscribe` which will emit `{show: true/false}`" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-12T13:17:08.710", "Id": "242134", "Score": "2", "Tags": [ "angular-2+", "observer-pattern", "native-code" ], "Title": "NativeScript - Angular Service to watch iOS keyboard event listeners" }
242134
<p>I have a function written in Groovy which needs to save a record and also return response from the server. Function is working fine, but I am not happy with the design because I have a problem with multiple nesting.</p> <p><strong>This is the function:</strong></p> <pre><code>Map scanAccessRecord(GrailsParameterMap params){ Map response Date currentTime = new Date() String readerEthernetAddress = params.readerMac Reader reader = Reader.findByDeletedAndEthernetAddress(false, readerEthernetAddress) Boolean isAccessIn = (params.isAccessIn == "True") if(reader) { UserSettings userSettings = UserSettings.findByRfidCode(params.rfid.toString()) if(userSettings) { if(userSettings.user.company.id == reader.companyId) { AccessRecord accessRecord = new AccessRecord(reader:reader, userId:userSettings.userId, specificDate:currentTime, isAccessIn: isAccessIn) if(accessRecord.save(flush: true)) { response = [ status: '00', message: 'OK', recordId: accessRecord.id, ] } else { response = [ status: '60', message: 'error' ] } } else { response = [status: '40', message: 'USER AND READER ARE NOT FROM SAME COMPANY'] } } else { response = [status: '10', message: 'UNKNOWN USER'] } } else { response = [status: '50', message: 'READER NOT FOUND'] } return response } </code></pre> <p>What can I do to make this function "cleaner"?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-13T00:38:24.490", "Id": "475240", "Score": "0", "body": "Not familiar with groovy. Is `if(reader)` is a null check?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-13T09:31:15.230", "Id": "475276", "Score": "0", "body": "Yes, it is checking whether there is a reader or not" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-13T09:42:47.903", "Id": "475278", "Score": "0", "body": "In what case reader is null?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-13T09:48:29.803", "Id": "475280", "Score": "0", "body": "`Reader reader = Reader.findByDeletedAndEthernetAddress(false, readerEthernetAddress)`\n\nReader is NULL in the case there is no reader found in DB with `readerEthernetAddress`(mac address) given in params or if it is found but has a flag `deleted`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-13T10:07:11.130", "Id": "475281", "Score": "0", "body": "Is AccessRecord your code or some framework? I Want to understand why `save` returns boolean." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-13T10:12:57.930", "Id": "475283", "Score": "0", "body": "`AccessRecord` is domainClass which I created, but `.save()` method is method which is automatically given to domainClasses in Grails framework.\n\nAbout you question, here is an answer from official documentaion:\n\n\"The save method returns null if validation failed and the instance was not persisted, or the instance itself if successful. This lets you use \"Groovy truth\" (null is considered false) to write code like the following:\"" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-13T11:17:34.963", "Id": "475304", "Score": "0", "body": "Why `params.isAccessIn` is a string and not boolean?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-13T11:33:15.423", "Id": "475307", "Score": "0", "body": "Because request is sent from a Python(Python script is in a reader) and it was easiest to send a string value which I just needed to convert to Boolean in Groovy." } ]
[ { "body": "<ul>\n<li>Use optional instead of null. I wrote an <a href=\"https://link.medium.com/2dU1PEeqk6\" rel=\"nofollow noreferrer\">article</a> about avoiding nulls if you are interested. </li>\n<li>Use early returns to avoid nesting</li>\n</ul>\n\n<pre><code>If !reader return [status: '50', message: 'READER NOT FOUND']\n\nIf !userSettings return...\nRest of the logic\n</code></pre>\n\n<ul>\n<li><p>I prefer to avoid nulls,so I would choose to call save with <code>failOnError=true</code> and it will throw exception instead of returning null when save fails. </p></li>\n<li><p>I assume you want any exception to return [ status: '60', message: 'error'], if you use <code>save</code> with <code>failOnError=true</code> then the error is handled in one place only. </p></li>\n<li><p>add validation for <code>params.isAccessIn</code>. If by mistake it is nor true or false, it is better to throw error than do something the client didn't intend to. </p></li>\n<li><p>Maybe you should be more flexible with <code>params.isAccessIn</code> and compare strings without case sensitivity.</p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-13T09:43:27.163", "Id": "475279", "Score": "0", "body": "Although I am not preferring using early returns in my code, I need to admin that they are very good solution in this case :)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-13T00:50:20.953", "Id": "242160", "ParentId": "242136", "Score": "2" } } ]
{ "AcceptedAnswerId": "242160", "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-12T13:44:19.057", "Id": "242136", "Score": "5", "Tags": [ "design-patterns", "groovy" ], "Title": "Design - prevent multiple nesting in function" }
242136
<p>all.<br> This component is meant to take in an array of available options and provide the user an easy way to choose multiple options. Each time the selected options are changed/updated, those options are console logged.<br></p> <p>I'm hoping that someone could provide any criticism on my current code. I want to make sure that the code is as simple and clean as it could be, while keeping all logic outside of the JSX. Photo of component at bottom of post.</p> <p>Thanks in advance!</p> <pre><code>const label = 'Select options'; const availableOptionsLabel = 'Available Types'; const selectedOptionsLabel = 'Selected Types'; export default function MultiSelection({options=['A', 'B', 'C']}) { const [availableOptions, setAvailableOptions] = useState([]); const [selectedOptions, setSelectedOptions] = useState([]); useEffect(() =&gt; { setAvailableOptions(options); }, []); useEffect(() =&gt; { console.log('Updated selection is: ', JSON.stringify(selectedOptions)); }, [selectedOptions]); const row = (text, key, whichColumn, action) =&gt; { return( &lt;div key={`${whichColumn}-button-row-${key}`} className='button-row-container' onClick={() =&gt; action(text)}&gt; &lt;IconButtonRow&gt; &lt;IconButton id='add' iconClass='icon-add'/&gt; &lt;p&gt;{text}&lt;/p&gt; &lt;/IconButtonRow&gt; &lt;/div&gt; ) } const moveToAvailableOptions = clickedOption =&gt; { setAvailableOptions([...availableOptions, clickedOption]); let tempSelectedOptions = [...selectedOptions.filter(option =&gt; option !== clickedOption)]; setSelectedOptions(tempSelectedOptions); } const moveToSelectedOptions = clickedOption =&gt; { setSelectedOptions([...selectedOptions, clickedOption]); let tempAvailableOptions = [...availableOptions.filter(option =&gt; option !== clickedOption)]; setAvailableOptions(tempAvailableOptions); } return( &lt;div className='multi-selection'&gt; &lt;h5&gt;{label}&lt;/h5&gt; &lt;div className='label-containter'&gt; &lt;h6 className='available-options-label'&gt;{availableOptionsLabel}&lt;/h6&gt; &lt;h6 className='selected-options-label'&gt;{selectedOptionsLabel}&lt;/h6&gt; &lt;/div&gt; &lt;div className='options-containter'&gt; &lt;div className='available-options'&gt; {availableOptions.map((option, key) =&gt; row(option, key, 'available', moveToSelectedOptions))} &lt;/div&gt; &lt;div className='selected-options'&gt; {selectedOptions.map((option, key) =&gt; row(option, key, 'selected', moveToAvailableOptions))} &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; ) } </code></pre> <p><a href="https://i.stack.imgur.com/Tm8Sd.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Tm8Sd.png" alt="enter image description here"></a></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-12T14:22:09.770", "Id": "475161", "Score": "1", "body": "Looks fine, except for the `let`s (prefer `const`) and a few missing semicolons (for both, consider a linter)" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-12T13:53:44.970", "Id": "242137", "Score": "1", "Tags": [ "javascript", "react.js", "jsx" ], "Title": "Multi Selection Component (React + Hooks)" }
242137
<p>Ahoy friends. Right now i'm selling a huge amount of HDDs and usually i used DBAN or nwipe to perform this actions. Unfortunately the PRNG Mersenne Twister is quite slow, so i get a throughput of around 100MB/s for 16 HDDs, which takes a really long time. I'm majoring electric engineering, but i had some C programming lessons as well for 1 year, so i love to code. Currently i have implemented Xoroshiro 128 in nwipe, to speed it up a little, but it's still not perfect. About 200MB/s. So i'd like to give a try, because usually i get everything to work, but that's a thing where i'm struggeling, and i'd like to learn.</p> <p>That's the code i'm talking about, it seems to be quite short, but the math is extremely heavy in my opinion.</p> <pre><code> /* This code is modified for use in nwipe. A C-program for MT19937, with initialization improved 2002/2/10. Coded by Takuji Nishimura and Makoto Matsumoto. This is a faster version by taking Shawn Cokus's optimization, Matthe Bellew's simplification, Isaku Wada's real version. Before using, initialize the state by using init_genrand(seed) or init_by_array(init_key, key_length). Copyright (C) 1997 - 2002, Makoto Matsumoto and Takuji Nishimura, All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. The names of its contributors may not be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. Any feedback is very welcome. http://www.math.keio.ac.jp/matumoto/emt.html email: matumoto@math.keio.ac.jp */ #include &lt;stdio.h&gt; #include "mt19937ar-cok.h" /* initializes state[N] with a seed */ void init_genrand( twister_state_t* state, unsigned long s) { int j; state-&gt;array[0]= s &amp; 0xffffffffUL; for( j = 1; j &lt; N; j++ ) { state-&gt;array[j] = (1812433253UL * (state-&gt;array[j-1] ^ (state-&gt;array[j-1] &gt;&gt; 30)) + j); state-&gt;array[j] &amp;= 0xffffffffUL; /* for &gt;32 bit machines */ } state-&gt;left = 1; state-&gt;initf = 1; } void twister_init( twister_state_t* state, unsigned long init_key[], unsigned long key_length ) { int i = 1; int j = 0; int k = ( N &gt; key_length ? N : key_length ); init_genrand( state, 19650218UL ); for( ; k; k-- ) { state-&gt;array[i] = (state-&gt;array[i] ^ ((state-&gt;array[i-1] ^ (state-&gt;array[i-1] &gt;&gt; 30)) * 1664525UL)) + init_key[j] + j; state-&gt;array[i] &amp;= 0xffffffffUL; /* for WORDSIZE &gt; 32 machines */ ++i; ++j; if ( i &gt;= N ) { state-&gt;array[0] = state-&gt;array[N-1]; i = 1; } if ( j &gt;= key_length ) { j = 0; } } for( k = N -1; k; k-- ) { state-&gt;array[i] = (state-&gt;array[i] ^ ((state-&gt;array[i-1] ^ (state-&gt;array[i-1] &gt;&gt; 30)) * 1566083941UL)) - i; state-&gt;array[i] &amp;= 0xffffffffUL; ++i; if ( i &gt;= N ) { state-&gt;array[0] = state-&gt;array[N-1]; i = 1; } } state-&gt;array[0] = 0x80000000UL; /* MSB is 1; assuring non-zero initial array */ state-&gt;left = 1; state-&gt;initf = 1; } static void next_state( twister_state_t* state ) { unsigned long *p = state-&gt;array; int j; if( state-&gt;initf == 0) { init_genrand( state, 5489UL ); } state-&gt;left = N; state-&gt;next = state-&gt;array; for( j = N - M + 1; --j; p++ ) { *p = p[M] ^ TWIST(p[0], p[1]); } for( j = M; --j; p++ ) { *p = p[M-N] ^ TWIST(p[0], p[1]); } *p = p[M-N] ^ TWIST(p[0], state-&gt;array[0]); } /* generates a random number on [0,0xffffffff]-interval */ unsigned long twister_genrand_int32( twister_state_t* state ) { unsigned long y; if ( --state-&gt;left == 0 ) { next_state( state ); } y = *state-&gt;next++; /* Tempering */ y ^= (y &gt;&gt; 11); y ^= (y &lt;&lt; 7) &amp; 0x9d2c5680UL; y ^= (y &lt;&lt; 15) &amp; 0xefc60000UL; y ^= (y &gt;&gt; 18); return y; } </code></pre> <p>So what i understood is: We have to initiliaze the generator using a seed, and then we perform a lot of XOR and vector operations. When i think on vectors, is it possible to optimize this code, using SSE instructions? But what's the most time consuming part of this code, and where may i apply the changes to improve the performance, maybe just a little bit?</p> <p>Currently i'm walking through the <a href="https://software.intel.com/sites/landingpage/IntrinsicsGuide/#techs=SSE" rel="nofollow noreferrer">Intel Instrinsics</a> guide, and i'd just check which vector operation i have in this code, to simply replace them by the appropriate instruction from the instrinsics guide. Unfortunately it didn't work so well, so i hope someone can give me some hints, maybe also about the maths regarding the vector parts in this code, so i can get through it. So i love to learn about it, and look for difficult projects, but this one is to heavy for me, so i'm looking for some help this time.</p> <p>Thanks in advance!</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-12T16:29:41.560", "Id": "475194", "Score": "0", "body": "Welcome to Code Review. Did you profile this code? What's in `mt19937ar-cok.h`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-12T16:30:08.583", "Id": "475196", "Score": "1", "body": "Not going to put this in a review because it's not a review, but just fetch your random data into a file first, write the data to the disk, and then zero the disk." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-13T07:43:11.490", "Id": "475260", "Score": "0", "body": "(I'd worry about not overwriting sectors/blocks once written with sensitive data, but replaced *before the end of the overwrite process* much more than about data patterns to overwrite with. Add to that contents of non-volatile cache (in the device). (Due to dynamic block mapping, the NV cache is a real headache targeting alphabet soup agency level erasure. Given physical access, shatter the platters, melt down all remains.))" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-13T08:07:47.280", "Id": "475262", "Score": "2", "body": "(`throughput of around 100MB/s for 16 HDDs` Why would the number of HDDs matter? Are you writing different data to each drive? Same question as with using \"high quality pseudo-random data\" in the first place: To what advantage?)" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-12T16:24:00.817", "Id": "242141", "Score": "1", "Tags": [ "performance", "c", "array", "mathematics", "vectorization" ], "Title": "Vectorization of Mersenne Twister?" }
242141
<p>When writing image processing/computer vision algorithms, I usually use <code>double</code> in computations and then I have to remap the values back into <code>std::uint8_t</code> range, because that is what PNG supports. The main problem is that the image is represented as multi channel entries in a matrix, and remapping should be done for each channel individually. Here is the formula I used for the remapping:</p> <p><span class="math-container">\$srcrange=srcmax-srcmin+1 \\ dstrange=dstmax-dstmin+1 \\ mapped=dstmin + \frac{value - srcmin}{srcrange}*dstrange \$</span></p> <p><span class="math-container">\$srcmax,srcmin\$</span> are computed for each channel individually.</p> <p>The code will work when remapping to wider range, but then <code>dst_min</code> and <code>dst_max</code> values should be manually specified, otherwise overflow is guaranteed. It is a use case I am supporting.</p> <h2>code</h2> <pre><code>// remap larger range into smaller one template &lt;typename U, typename MT, bool SO&gt; auto remap_to_channeled(const blaze::DenseMatrix&lt;MT, SO&gt;&amp; source, U dst_min = std::numeric_limits&lt;U&gt;::min(), U dst_max = std::numeric_limits&lt;U&gt;::max()) { using source_vector_type = blaze::UnderlyingElement_t&lt;MT&gt;; constexpr auto vector_size = source_vector_type::size(); using element_type = blaze::UnderlyingElement_t&lt;source_vector_type&gt;; static_assert(blaze::IsStatic_v&lt;source_vector_type&gt; &amp;&amp; blaze::IsDenseVector_v&lt;source_vector_type&gt;); auto min_reducer = [](source_vector_type prev, const source_vector_type&amp; current) { for (std::size_t i = 0; i &lt; prev.size(); ++i) { if (prev[i] &gt; current[i]) { prev[i] = current[i]; } } return prev; }; auto src_min_elems = blaze::reduce(source, min_reducer); auto max_reducer = [](source_vector_type prev, const source_vector_type&amp; current) { for (std::size_t i = 0; i &lt; prev.size(); ++i) { if (prev[i] &lt; current[i]) { prev[i] = current[i]; } } return prev; }; auto src_max_elems = blaze::reduce(source, max_reducer); using result_vector_type = blaze::StaticVector&lt;U, source_vector_type::size()&gt;; // pick according to std::common_type rules to make // more resistant to overflow/underflow and accuracy loss using proxy_type = std::common_type_t&lt;element_type, U&gt;; using proxy_vector = blaze::StaticVector&lt;proxy_type, source_vector_type::size()&gt;; result_vector_type dst_min_elems; std::fill(dst_min_elems.begin(), dst_min_elems.end(), dst_min); result_vector_type dst_max_elems; std::fill(dst_max_elems.begin(), dst_max_elems.end(), dst_max); proxy_vector src_range_length = src_max_elems - src_min_elems + 1; proxy_vector dst_range_length = dst_max_elems - dst_min_elems + 1; return blaze::evaluate(blaze::map( (~source), [src_min_elems, dst_min_elems, src_range_length, dst_range_length, vector_size]( const source_vector_type&amp; elem) { result_vector_type result{}; for (std::size_t i = 0; i &lt; vector_size; ++i) { result[i] = dst_min_elems[i] + (static_cast&lt;double&gt;(elem[i] - src_min_elems[i]) / // cast to double to make more // resistant to accuracy loss src_range_length[i] * dst_range_length[i]); } return result; })); } </code></pre> <h2>Tests</h2> <pre><code>TEST_CASE("test remap_to_channeled - simple case") { blaze::StaticVector&lt;int, 3&gt; default_vector({0, 1, 2}); blaze::DynamicMatrix&lt;blaze::StaticVector&lt;int, 3&gt;&gt; matrix(2, 3, default_vector); blaze::DynamicMatrix&lt;blaze::StaticVector&lt;std::uint8_t, 3&gt;&gt; expected(2, 3, {0, 0, 0}); auto result = flash::remap_to_channeled&lt;std::uint8_t&gt;(matrix); REQUIRE(expected == result); } TEST_CASE("test remap_to_channeled - slightly harder case") { blaze::StaticVector&lt;int, 3&gt; default_vector({0, 1, 2}); blaze::DynamicMatrix&lt;blaze::StaticVector&lt;int, 3&gt;&gt; matrix(2, 3, default_vector); blaze::DynamicMatrix&lt;blaze::StaticVector&lt;std::uint8_t, 3&gt;&gt; expected(2, 3, {10, 10, 10}); auto result = flash::remap_to_channeled&lt;std::uint8_t&gt;(matrix, 10, 12); REQUIRE(expected == result); } TEST_CASE("test remap_to_channeled - linear case") { // input range is from 0 to 15, so the length of the range is 16 // the output range is from 0 to 255, so the length is 256 // for every value in input, remapped value should be value * 16 blaze::DynamicMatrix&lt;blaze::StaticVector&lt;int, 3&gt;&gt; matrix(2, 8, {0, 0, 0}); int multiplier = 16; int counter = 0; blaze::DynamicMatrix&lt;blaze::StaticVector&lt;std::uint8_t, 3&gt;&gt; expected(2, 8, {0, 0, 0}); for (unsigned int counter = 0; counter &lt; 16; ++counter) { auto i = counter / 8; auto j = counter % 8; matrix(i, j)[0] = counter; expected(i, j)[0] = counter * multiplier; } auto result = flash::remap_to_channeled&lt;std::uint8_t&gt;(matrix); REQUIRE(result == expected); } </code></pre> <p>The full source code can be found <a href="https://github.com/simmplecoder/blazing-gil" rel="nofollow noreferrer">here</a>.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-12T16:54:44.880", "Id": "242142", "Score": "2", "Tags": [ "c++", "c++17" ], "Title": "Remap input matrix into matrix with narrower range" }
242142
<p>The question is as follows: Given a collection of distinct integers, return all possible permutations. Example:</p> <pre><code>Input: [1,2,3] Output: [ [1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], [3,2,1] ] </code></pre> <p>Here is my backtracking solution for the problem, where I added the <code>num_calls</code> variable to keep track of the number of times that the <code>backtrack</code> function is called recursively.</p> <pre><code>class Solution: def permute(self, nums): answer = [] num_calls = [] def backtrack(combo, rem): if len(rem) == 0: answer.append(combo) for i in range(len(rem)): num_calls.append(1) backtrack(combo + [rem[i]], rem[:i] + rem[i + 1:]) if len(nums) == 0: return None backtrack([], nums) print(len(num_calls)) return answer </code></pre> <p>I can't make sense of any of the answers that I have seen thus far for the time and space complexity of this solution.</p> <p>Some people say its worst case O(n * n!), but looking at the len of <code>num_calls</code> doesn't verify this claim.</p> <p>For example, for:</p> <pre><code>test = Solution() print(test.permute([1, 2, 3])) </code></pre> <p>length of num_calls = 15, which != n * n! = 3 * (3*2*1) = 18</p> <p>, for:</p> <pre><code>test = Solution() print(test.permute([1, 2, 3, 4])) </code></pre> <p>length of num_calls = 64, which != n * n! = 4 * (4*3*2*1) = 96.</p> <p>, and for:</p> <pre><code>test = Solution() print(test.permute([1, 2, 3, 4, 5])) </code></pre> <p>length of num_calls = 325, which != n * n! = 5 * (5*4*3*2*1) = 600</p> <p>Can someone please explain this in a simplified and easily understandable manner?</p>
[]
[ { "body": "<p>The number of calls indeed grows slower than <span class=\"math-container\">\\$n*n!\\$</span>. Its growth is only <span class=\"math-container\">\\$O(n!)\\$</span>. However, number of calls is not the only source of complexity. </p>\n\n<p>Constructing arguments for the recursive call also takes time, and <code>rem[:i] + rem[i + 1:]</code> is on average linear in terms of <code>n</code>. The total complexity therefore is <span class=\"math-container\">\\$O(n*n!)\\$</span>, just as some people say.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-12T20:22:01.950", "Id": "475229", "Score": "0", "body": "How is the growth of the number of calls only O(n!)? For each of the examples I showed above, the number of calls is greater than n!. In addition, could you explain a bit more as to why `rem[:i] + rem[i + 1:]` is on average linear?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-12T17:40:53.623", "Id": "242145", "ParentId": "242144", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-12T17:00:03.427", "Id": "242144", "Score": "2", "Tags": [ "algorithm", "recursion", "combinatorics", "complexity", "backtracking" ], "Title": "Time and Space Complexity of Leetcode Problem #31. Next Permutation" }
242144
<p>I wrote a simple prime sieve in Python. But it ended up looking... ugly. I included a few of the most basic optimizations. When posting this question SE suggested a bunch of questions on the same topic, which lead me to some improvements. But few were in generator form.</p> <p>It's the optimizations' fault.<br> Unfortunately I can't <code>continue</code> an outer loop from an inner loop, like I can in JavaScript. I very much disagree with Guido <a href="https://stackoverflow.com/a/1859147/802363">here</a>, as it makes the inner loop clunky.</p> <pre class="lang-py prettyprint-override"><code>from itertools import count def sieve(): primes = [2] for candidate in count(start=3, step=2): cont = False n = 0 while primes[n]**2 &lt;= candidate: # You only need to check up to the square root of a number. if candidate % primes[n] == 0: cont = True # outer break n = n + 1 if cont: cont = False continue yield primes[-1] primes.append(candidate) </code></pre> <p>Can we make this more concise without changing the basic logic? For example <a href="https://codereview.stackexchange.com/a/6698/203088">this</a> is extremely concise, but it doesn't have some of the optimizations my code does.</p> <p>For fun, I wrote the same logic in Javascript. This looks cleaner due to being able to continue an outer loop. But the lack of negative indices is a step backwards.</p> <blockquote> <pre class="lang-javascript prettyprint-override"><code>function* sieve() { let primes = [2] counter: for (let candidate = 3;; candidate+=2) { for (let n = 1; primes[n]**2 &lt;= candidate; n++) if (candidate % primes[n] == 0) continue counter yield primes[primes.length - 1] primes.push(candidate) } } </code></pre> </blockquote>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-12T18:30:26.463", "Id": "475212", "Score": "0", "body": "Please pick one language per question. Do you want the Python or the JavaScript reviewed?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-12T18:31:38.523", "Id": "475213", "Score": "0", "body": "Hm, if I have to choose, I guess I'll go with python." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-13T13:17:16.893", "Id": "475321", "Score": "3", "body": "Note that what you are implementing here is *not* the Sieve of Eratosthenes, but rather the oft-mistaken and much slower Trial Division algorithm. The Sieve has no divisions nor modulo operations in it and accomplishes everything through additions or, at worst, some multiplications." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-13T13:28:02.177", "Id": "475325", "Score": "0", "body": "You can compare Trial Division (https://en.wikipedia.org/wiki/Trial_division) to the Sieve of Eratosthenes here: https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes." } ]
[ { "body": "<p>This outputs the same as your function:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>import array\nfrom itertools import count\n\n\ndef sieve():\n primes = array.array(\"L\", [2]) # L: unsigned long int\n for candidate in count(start=3, step=2):\n n = 0\n while primes[n] ** 2 &lt;= candidate:\n if candidate % primes[n] == 0:\n break\n n += 1\n else: # nobreak\n yield primes[-1]\n primes.append(candidate)\n\n\nn = 0\nprimes = sieve()\n\nwhile True:\n prime = next(primes)\n print(prime)\n n += 1\n</code></pre>\n\n<p>I did not touch the algorithm itself because I am unfamiliar, but Python (tested on 3.8.2, but also runs on 2.7.18, as you seem to need given your tag <a href=\"/questions/tagged/python-2.x\" class=\"post-tag\" title=\"show questions tagged &#39;python-2.x&#39;\" rel=\"tag\">python-2.x</a>) has the <code>while</code>/<code>else</code> construct that can help you with your control flow here.</p>\n\n<p>A <code>break break</code>, <code>break &lt;label&gt;</code> or similar thinkable constructs have been <a href=\"https://www.python.org/dev/peps/pep-3136/\" rel=\"noreferrer\">proposed</a>, as you linked as well, but rejected.\nA possible remedy is to extract sub-routines into functions and to use their <code>return</code> statements for control flow/multi-level breaking.\nIn your case, that is not needed.</p>\n\n<p>The <code>while</code>/<code>else</code> construct is unfamiliar to many. In fact, it is so alien that Guido <a href=\"https://mail.python.org/pipermail/python-ideas/2009-October/006157.html\" rel=\"noreferrer\">would not implement it again</a> nowadays.\nFor now, it is best to think of the <code>else</code> as <code>nobreak</code>: the <code>while</code> loop finished normally (its condition evaluated to <code>False</code>) and exited.\nSince <em>no</em> <code>break</code> occurred, the <code>else</code> block is executed.</p>\n\n<p>In the above case, if <code>break</code> is hit in the <code>if</code> block, the <code>else</code> is <em>skipped</em>: no <code>yield</code> occurs, and since after the <code>else</code> block, there is no code left, a <code>continue</code> for the outer <code>for</code> loop is implied and not explicitly necessary, since there is nothing else to do anyway.</p>\n\n<hr>\n\n<p>A frequent example is in the form of <code>for</code>/<code>else</code> (which works like the <code>while</code>/<code>else</code>) when looking for a hit, like in your case:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>for file in files:\n if file == file_looked_for:\n file.do_something()\n break\nelse: # nobreak\n # code to handle file not found\n</code></pre>\n\n<p>So while, like you, I have been tripped up by the lack of advanced <code>break</code> functionalities, I agree with Guido.\nApart from the unfortunate naming of <code>else</code> in the <code>while</code> construct (more discussion <a href=\"https://news.ycombinator.com/item?id=17169331\" rel=\"noreferrer\">here</a>), it can do the job just fine.\nTrying to break through multiple levels is an occasion to rethink the implementation.</p>\n\n<hr>\n\n<p>Other observations:</p>\n\n<ul>\n<li><p><code>primes[n]</code> has to call <code>__getitem__</code>, which happens twice. This is constant-time, but the following will probably provide a speed-up (but requires the \"walrus\" operator from Python 3.8):</p>\n\n<pre class=\"lang-py prettyprint-override\"><code> while (\n (prime := primes[n]) ** 2 &lt;= candidate\n ): # You only need to check up to the square root of a number.\n if candidate % prime == 0:\n</code></pre>\n\n<p><code>primes</code> no longer has to be looked up, the simple, local <code>prime</code> suffices for the second call.</p></li>\n<li><code>n = n + 1</code> can be <code>n += 1</code>. However, this is possibly slower.</li>\n<li><p>Finally, the built-in <code>array.array</code> can be much faster than a <code>list</code>. This is because <code>list</code>s can hold arbitrary objects, whereas an <code>array</code> has to be initiliazed for a specific one (here: <code>L</code> for <code>long int</code>, which will <a href=\"https://en.wikibooks.org/wiki/C_Programming/limits.h\" rel=\"noreferrer\">last a while</a>). As a positive consequence, the <code>array</code> can then be optimized accordingly.</p>\n\n<p>Note how <code>array.array</code>, in this case, is a 1:1 drop-in for the previous <code>list</code>. As such, the code did not have to change. As such, it is also easy for you to revert the change if unwanted.</p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-12T19:46:29.633", "Id": "475226", "Score": "1", "body": "You can change the calling code in your first code block to just `for prime in sieve(): print(prime)`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-12T19:50:14.497", "Id": "475227", "Score": "0", "body": "Yes you are right. There was a guard clause to `break` at `n == 20` that felt more natural in a `while True`, but I removed it before posting." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-12T19:51:28.900", "Id": "475228", "Score": "2", "body": "In the future you may wish to do `for i, prime in enumerate(sieve()): if i == 20: break` it's more 'Pythonic' ;)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-13T03:54:29.167", "Id": "475243", "Score": "1", "body": "`alien` > You can say that again. I initially thought you'd messed up your indentation before reading the explanation. While the construct looks odd (and `else` is a questionable choice of words), it does make it pretty neat - and faster. For the other observations: Walrus operator - this is just a straight up a _holy crap, wtf python?_ moment - why is the same thing that works for a million other languages not enough for python? Why does there have to be a special operator? Also provides at best a marginal improvement (12.9s > 12.6s over n=200K). Continued..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-13T04:03:10.587", "Id": "475244", "Score": "1", "body": "And I am sad to report that `array.array` actually results in a slowdown. For `n += 1` - I know python doesn't have `++` and I was under the mistaken impression shorthand assignment is also not in there. Regardless, if `n += 1` is slower, it is not observable over n=200K. Thank you for the review. It's a good explanation of a language construct I've never encountered before. The other observations also fit in the spirit of the question, even if they end up being hit or miss. Python is just like that special child(walrus - _seriously? I can't even..._)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-13T07:06:10.407", "Id": "475258", "Score": "0", "body": "Thanks for you feedback, interesting to see. Well, some just call it \"walrus\", but its official fancy name is [Assignment Operator](https://www.python.org/dev/peps/pep-0572/). `array.array` being a slowdown is surprising! I can confirm that observation. Even `\"I\"` instead of `\"L\"` is slower. At this point, `numpy` could be the next thing to try out, if you want more optimization." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-12T19:33:41.983", "Id": "242153", "ParentId": "242147", "Score": "5" } }, { "body": "<ol>\n<li><p>We can move the while loop into another function.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def is_prime(candidate, primes):\n n = 0\n while primes[n]**2 &lt;= candidate:\n if candidate % primes[n] == 0:\n return False\n n += 1\n return True\n\ndef sieve():\n primes = [2]\n for candidate in count(start=3, step=2):\n if not is_prime(candidate, primes):\n continue\n yield primes[-1]\n primes.append(candidate)\n</code></pre></li>\n<li><p>We can use <code>itertools.takewhile</code> to expose the while loop as an iterable.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def is_prime(candidate, primes):\n for prime in itertools.takewhile(lambda p: p**2 &lt;= candidate, primes):\n if candidate % prime == 0:\n return False\n return True\n</code></pre></li>\n<li><p>We can use <code>any</code> to make <code>is_prime</code> easier to read.</p>\n\n<p>If for any of the values, <code>candidate % prime == 0</code>, are true the result is true.\nIf none of them are then it is false.\nSince we want it to be the other way around we can just use <code>not</code>.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def is_prime(candidate, primes):\n return not any(\n candidate % prime == 0\n for prime in itertools.takewhile(lambda p: p**2 &lt;= candidate, primes)\n )\n</code></pre></li>\n<li><p>We can move <code>is_prime</code> back into the first function.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def sieve():\n primes = [2]\n for candidate in count(start=3, step=2):\n if not not any(\n candidate % prime == 0\n for prime in itertools.takewhile(lambda p: p**2 &lt;= candidate, primes)\n ):\n continue\n yield primes[-1]\n primes.append(candidate)\n</code></pre></li>\n<li><p>We can swap the <code>if</code> to cancel the <code>continue</code> and a <code>not</code>.</p></li>\n<li>We can swap the <code>any</code> and <code>== 0</code>, with <code>not all</code>.</li>\n<li>We can cancel the double <code>not</code>.</li>\n</ol>\n\n<pre class=\"lang-py prettyprint-override\"><code>def sieve():\n primes = [2]\n for candidate in count(start=3, step=2):\n if all(\n candidate % prime\n for prime in itertools.takewhile(lambda p: p**2 &lt;= candidate, primes)\n ):\n yield primes[-1]\n primes.append(candidate)\n</code></pre>\n\n<p>At the expense of readability you can get the following trade offs.</p>\n\n<ol>\n<li>There is a chance that using <code>int(candidate ** 0.5).__ge__</code> is faster than the <code>lambda</code>.</li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-13T04:35:27.423", "Id": "475247", "Score": "0", "body": "While this is a good explanation of the approach, I am sad to report that it is also wrong - the logic is broken. It thinks 9 is a prime. More generally, it considers all odd squares prime." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-13T04:40:02.307", "Id": "475248", "Score": "0", "body": "Though the fix is simple - the lambda condition must be `<=`, not `<`. I do like how mathematically / logically this is more expressive than the other answer. It is also slower(15.1s vs 12.9s over n=200K). TBH I can't decide which answer is better..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-13T04:48:51.380", "Id": "475249", "Score": "0", "body": "@martixy Ah yes I dropped the equals there, but somehow kept it in the 'extra' part - `__ge__`. Thank you. You didn't highlight that you wanted this super optimized, however if you do then [another one of my answers](https://codereview.stackexchange.com/a/213422/42401) likely performs better than either of these answers." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-13T04:55:05.283", "Id": "475250", "Score": "0", "body": "Not specifically \"super optimized\", I was just listing pros and cons." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-13T09:09:59.467", "Id": "475266", "Score": "1", "body": "I like everything in this answer except the implicit conversion of a remainder to a truthy value: to me, `candidate % prime != 0` is vastly more readable, despite being a minimal change." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-13T10:25:30.493", "Id": "475287", "Score": "0", "body": "@KonradRudolph I'm guessing you disagree with 2.1 too :P I had originally put it as 2.2 for that reason but then 1.6 wouldn't make as much sense :(" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-13T10:33:19.830", "Id": "475289", "Score": "0", "body": "@Peilonrayz You’ve lost me." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-13T10:36:26.333", "Id": "475291", "Score": "0", "body": "Maybe my x.y notation is unclear? x is the referring to one of the ordered lists, 1 -> first ordered list. y is the number of the item in the list. E.g. 1.6 -> \"We can swap the `any` and `== 0`, with `not all`.\" I think I should start the second list from the end of the first list in the future." } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-12T19:42:16.550", "Id": "242154", "ParentId": "242147", "Score": "6" } }, { "body": "<p>Three main things vex me about your code:</p>\n\n<ul>\n<li>the just generated prime isn't returned,</li>\n<li>the boolean test a the end of the <code>while</code> loop</li>\n<li>repeated prime \"square and test\" for candidacy.</li>\n</ul>\n\n<h1>Not returning generated prime</h1>\n\n<p>Your code generates <code>3</code>, and yields <code>2</code>, then it generates <code>5</code> and yields <code>3</code>, then it generates <code>7</code> and yields <code>5</code>, then generates <code>11</code> and yields <code>7</code>, and so on.</p>\n\n<p>This happens because you half treat <code>2</code> as a special case. You initialize the <code>primes</code> array with it. But to return it, you use <code>yield primes[-1]</code> just like every other prime.</p>\n\n<p>If you treated it completely as a special case, and yield it right off the hop, you could <code>yield candidate</code> at the end of the loop, thus returning the prime you just computed.</p>\n\n<pre><code>def sieve():\n primes = [2]\n yield 2\n\n for candidate in count(start=3, step=2):\n ...\n yield candidate\n primes.append(candidate)\n</code></pre>\n\n<h1>Unnecessary boolean test at end of while</h1>\n\n<p>A <code>while</code> loop is often used for searching. If the value is found, the <code>while</code> loop is escaped via a <code>break</code> statement. If the while loop completes without ever breaking, the condition searched for was never found, and something different needs to happen. In Python, this is the <code>while ... else</code> statement:</p>\n\n<pre><code>def sieve():\n primes = [2]\n yield 2\n for candidate in count(start=3, step=2):\n n = 0\n while primes[n]**2 &lt;= candidate: # Only check up to the square root of number.\n if candidate % primes[n] == 0:\n break\n n = n + 1\n else:\n yield candidate\n primes.append(candidate)\n</code></pre>\n\n<h1>Repeated prime \"square and test\" for candidacy.</h1>\n\n<p>How often is the <code>primes[n]**2 &lt;= candidate</code> done?</p>\n\n<p>If <code>candidate</code> is just over 10,000, and is prime, then we will be squaring all primes less than 100, and testing that they are less than <code>candidate</code>. Then, we do the same thing for <code>candidate + 2</code>, and the results will be the same. No prime number less than 100, squared, will ever be greater than <code>candidate</code> once <code>candidate</code> exceeds 10,000 ... so this is all busy work, repeating the same test over and over.</p>\n\n<p>What you need is to partition your <code>primes</code> list into two parts: primes less or equal to the square-root of candidate, and primes greater the square-root of candidate.</p>\n\n<p>You can do this in several ways. The smallest change would be to keep track of a count of \"small\" primes. As <code>candidate</code> gets larger by 2, you would only need add at most one more prime into the \"small\" primes bucket:</p>\n\n<pre><code>def sieve():\n primes = [2]\n yield 2\n\n small_primes = 0\n for candidate in count(start=3, step=2):\n\n if primes[small_primes] ** 2 &lt;= candidate:\n small_primes += 1\n\n for n in range(small_primes):\n if candidate % primes[n] == 0:\n break\n else:\n yield candidate\n primes.append(candidate)\n</code></pre>\n\n<p>Now how often is <code>primes[small_primes] ** 2 &lt;= candidate</code> being done? Once per candidate! This has got to be an improvement. Also, all <code>n = 0</code> and <code>n = n + 1</code> code has been absorbed into <code>for n in range(small_primes)</code>, and having Python do this work is faster than coding it ourselves.</p>\n\n<h1>Other improvements</h1>\n\n<h2>Odd numbers</h2>\n\n<p>Why are we test-dividing all of our candidates by <code>primes[0] == 2</code>? By design, they are all odd, and can never be evenly divided by 2. </p>\n\n<pre><code> for n in range(1, small_primes): # Skip divide-by-2 tests\n</code></pre>\n\n<h2>All</h2>\n\n<p>As mentioned by Peilonrayz, Python has an <code>any()</code> function, though I think <code>all()</code> is more appropriate here.</p>\n\n<pre><code>def sieve():\n primes = [2]\n yield 2\n\n small_primes = 0\n for candidate in count(start=3, step=2):\n\n if primes[small_primes] ** 2 &lt;= candidate:\n small_primes += 1\n\n if all(candidate % primes[n] != 0 for n in range(1, small_primes)):\n yield candidate\n primes.append(candidate)\n</code></pre>\n\n<h2>Maintain separate lists</h2>\n\n<p>Instead of <code>small_primes</code> being a count of the number of primes less than the square-root of the <code>candidate</code>, what if it actually was a list of the small prime numbers? And instead of adding prime candidates to that list, we add to a <code>large_primes</code> list? Then we could move primes from the <code>large_primes</code> to the <code>small_primes</code> as the square-root of the candidate increases.</p>\n\n<p>Optimizations:</p>\n\n<ul>\n<li><code>deque</code> for <code>large_primes</code></li>\n<li>Omit <code>2</code> from the <code>small_primes</code> list,</li>\n<li>Cache the <code>large_prime[0] ** 2</code> value, to avoid repeatedly squaring the same quantity.</li>\n</ul>\n\n<p>Resulting code:</p>\n\n<pre><code>from itertools import count\nfrom collections import deque\n\ndef sieve():\n yield 2\n yield 3\n\n small_primes = []\n large_primes = deque((3,))\n next_prime_squared = large_primes[0] ** 2\n\n for candidate in count(start=5, step=2):\n\n if candidate &gt;= next_prime_squared:\n small_primes.append(large_primes.popleft())\n next_prime_squared = large_primes[0] ** 2\n\n if all(candidate % prime != 0 for prime in small_primes):\n yield candidate\n large_primes.append(candidate)\n</code></pre>\n\n<h1>Time Comparisons</h1>\n\n<p>Time (in seconds) for generating 100 to 100,000 primes:\n<a href=\"https://i.stack.imgur.com/g4RGA.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/g4RGA.png\" alt=\"enter image description here\"></a></p>\n\n<p>Timing code:</p>\n\n<pre><code>import array\nfrom timeit import timeit\nfrom itertools import count, takewhile\nfrom collections import deque\nimport matplotlib.pyplot as plt\n\ndef martixy():\n primes = [2]\n for candidate in count(start=3, step=2):\n cont = False\n n = 0\n while primes[n]**2 &lt;= candidate: # You only need to check up to the square root of a number.\n if candidate % primes[n] == 0:\n cont = True # outer\n break\n n = n + 1\n if cont:\n cont = False\n continue\n yield primes[-1]\n primes.append(candidate)\n\ndef alex_povel():\n primes = array.array(\"L\", [2]) # L: unsigned long int\n for candidate in count(start=3, step=2):\n n = 0\n while primes[n] ** 2 &lt;= candidate:\n if candidate % primes[n] == 0:\n break\n n += 1\n else: # nobreak\n yield primes[-1]\n primes.append(candidate)\n\ndef peilonrayz():\n primes = [2]\n for candidate in count(start=3, step=2):\n if all(\n candidate % prime\n for prime in takewhile(lambda p: p**2 &lt;= candidate, primes)\n ):\n yield primes[-1]\n primes.append(candidate)\n\ndef ajneufeld():\n yield 2\n yield 3\n\n small_primes = []\n large_primes = deque((3,))\n next_prime_squared = large_primes[0] ** 2\n\n for candidate in count(start=5, step=2):\n\n if candidate &gt;= next_prime_squared:\n small_primes.append(large_primes.popleft())\n next_prime_squared = large_primes[0] ** 2\n\n if all(candidate % prime != 0 for prime in small_primes):\n yield candidate\n large_primes.append(candidate)\n\ndef test(candidate, limit):\n sieve = candidate()\n for _ in range(limit):\n next(sieve)\n\nif __name__ == '__main__':\n candidates = (martixy, alex_povel, peilonrayz, ajneufeld)\n limits = [int(10 ** (power * 0.25)) for power in range(8, 21)]\n\n fig, ax = plt.subplots()\n\n for candidate in candidates:\n print(\"Testing\", candidate.__name__)\n times = [ timeit(lambda: test(candidate, limit), number=1) for limit in limits ]\n ax.plot(limits, times, '-+', label=candidate.__name__)\n\n ax.legend()\n plt.show()\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-13T15:25:19.240", "Id": "242208", "ParentId": "242147", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-12T18:10:16.913", "Id": "242147", "Score": "6", "Tags": [ "python", "python-2.x", "sieve-of-eratosthenes", "generator" ], "Title": "Prime sieve generator" }
242147
<p><strong><em>Straight</em> insertion sort</strong></p> <p>When inserting an element into its proper location to the left, one can achieve that by <span class="math-container">\$n\$</span> adjacent swaps which totals to <span class="math-container">\$3n\$</span> assignments. Straight insertion sort, instead, stores the element and than performs <span class="math-container">\$n\$</span> chain shifts to the right.</p> <p><strong><em>Binary</em> insertion sort</strong></p> <p>Just like conventional insertion sort, but the search for the insertion point is done via binary search, reducing the worst-case running time for pivot search from <span class="math-container">\$\Theta(n)\$</span> to <span class="math-container">\$\Theta(\log n)\$</span>.</p> <p><strong>Code</strong></p> <p><strong><code>com.github.coderodde.util.BinaryInsertionSort.java:</code></strong></p> <pre><code>package com.github.coderodde.util; import java.util.Comparator; /** * This class implements binary insertion sort, which, unlike conventional * insertion sort, relies on binary search when searching the position to insert * the pivot element into. * * @author Rodion "rodde" Efremov * @version 1.6 (May 12, 2020) ~ initial version. * @since 1.6 (May 12, 20202) */ public final class BinaryInsertionSort { private BinaryInsertionSort() {} /** * Sorts the input range {@code array[fromIndex], ..., array[toIndex - 1]} * into ascending order. * * @param &lt;E&gt; the array component type. * @param array the array holding the target range. * @param fromIndex the first inclusive range index. * @param toIndex the last exclusive range index. * @param comparaotr the comparator object. */ public static &lt;E&gt; void sort(E[] array, int fromIndex, int toIndex, Comparator&lt;? super E&gt; comparaotr) { for (int currentIndex = fromIndex + 1; currentIndex &lt; toIndex; currentIndex++) { final E pivot = array[currentIndex]; int left = fromIndex; int right = currentIndex; while (left &lt; right) { final int middle = (left + right) &gt;&gt;&gt; 1; if (comparaotr.compare(pivot, array[middle]) &lt; 0) { right = middle; } else { left = middle + 1; } } assert left == right; final int n = currentIndex - left; switch (n) { case 2: array[left + 2] = array[left + 1]; case 1: array[left + 1] = array[left]; break; default: System.arraycopy(array, left, array, left + 1, n); } } } /** * Sorts the input array range into ascending order using a natural * comparator. * * @param &lt;E&gt; the array component type. * @param array the array holding the target range. * @param fromIndex the first inclusive range index. * @param toIndex the last exclusive range index. */ public static &lt;E&gt; void sort(E[] array, int fromIndex, int toIndex) { sort(array, fromIndex, toIndex, new Comparator&lt;E&gt;() { @Override public int compare(final E elementLeft, final E elementRight) { return ((Comparable&lt;E&gt;) elementLeft).compareTo(elementRight); } }); } /** * Sorts the entire input array into ascending order. * * @param &lt;E&gt; the array component type. * @param array the target array to sort. */ public static &lt;E&gt; void sort(E[] array) { sort(array, 0, array.length); } /** * Sorts the entire input array using the specifying comparator. * * @param &lt;E&gt; the array component type. * @param array the target array to sort. * @param comparator the comparator object. */ public static &lt;E&gt; void sort(E[] array, Comparator&lt;? super E&gt; comparator) { sort(array, 0, array.length, comparator); } } </code></pre> <p><strong><code>com.github.coderodde.util.StraightInsertionSort.java:</code></strong></p> <pre><code>package com.github.coderodde.util; import java.util.Comparator; /** * This class implements straight insertion sort, which differs from ordinary * insertion sort by the fact that it does not shift the subranges to shift by * swapping the element, but instead by saving the rightmost element, shifting * everything in the shift range one position to the right and inserting the * saved element into its correct position. * * @author Rodion "rodde" Efremov * @version 1.6 (May 11, 2020) ~ initial version. * @see 1.6 (May 11, 2020) */ public final class StaightInsertionSort { private StaightInsertionSort() {} /** * Sorts the input array range into ascending order using an explicit * comparator. * * @param &lt;E&gt; the array component type. * @param array the array holding the target range. * @param fromIndex the first inclusive range index. * @param toIndex the last exclusive range index. * @param comparator the comparator. */ public static &lt;E&gt; void sort(E[] array, int fromIndex, int toIndex, Comparator&lt;? super E&gt; comparator) { for (int i = fromIndex + 1; i &lt; toIndex; i++) { final E targetElement = array[i]; int j = i - 1; while (j &gt;= fromIndex &amp;&amp; comparator.compare(array[j], targetElement) &gt; 0) { array[j + 1] = array[j]; j--; } array[j + 1] = targetElement; } } /** * Sorts the input array range into ascending order using a natural * comparator. * * @param &lt;E&gt; the array component type. * @param array the array holding the target range. * @param fromIndex the first inclusive range index. * @param toIndex the last exclusive range index. */ public static &lt;E&gt; void sort(E[] array, int fromIndex, int toIndex) { sort(array, fromIndex, toIndex, new Comparator&lt;E&gt;() { @Override public int compare(final E elementLeft, final E elementRight) { return ((Comparable&lt;E&gt;) elementLeft).compareTo(elementRight); } }); } public static &lt;E&gt; void sort(E[] array) { sort(array, 0, array.length); } public static &lt;E&gt; void sort(E[] array, Comparator&lt;? super E&gt; comparator) { sort(array, 0, array.length, comparator); } } </code></pre> <p><strong><code>com.github.coderodde.util.BinaryInsertionSortTest.java:</code></strong></p> <pre><code>package com.github.coderodde.util; import static com.github.coderodde.util.SharedSortingTestUtils.getRandomIntegerArray; import java.util.Arrays; import java.util.Random; import org.junit.Test; import static org.junit.Assert.*; /** * This unit test class tests the binary insertion sort algorithm * ({@link com.github.coderodde.util.BinaryInsertionSort}). * * @author Rodion "rodde" Efremov * @version 1.6 (May 12, 2020) ~ initial version. * @since 1.6 (May 12, 2020) */ public class BinaryInsertionSortTest { public static final int REPETITIONS = 10_000; public static final int LENGTH = 100; @Test public void bruteForceTest() { long seed = System.currentTimeMillis(); System.out.println("Seed = " + seed); Random random = new Random(); for (int repetition = 0; repetition &lt; REPETITIONS; repetition++) { Integer[] array1 = getRandomIntegerArray(random, LENGTH); Integer[] array2 = array1.clone(); int index1 = random.nextInt(LENGTH), index2 = random.nextInt(LENGTH); int fromIndex = Math.min(index1, index2); int toIndex = Math.max(index1, index2); Arrays.sort(array1, fromIndex, toIndex); StaightInsertionSort.sort(array2, fromIndex, toIndex); assertTrue(Arrays.equals(array1, array2)); } } } </code></pre> <p><strong><code>com.github.coderodde.util.StraightInsertionSortTest.java:</code></strong></p> <pre><code>package com.github.coderodde.util; import static com.github.coderodde.util.SharedSortingTestUtils.getRandomIntegerArray; import java.util.Arrays; import java.util.Random; import static org.junit.Assert.assertTrue; import org.junit.Test; /** * This unit test class tests the binary insertion sort algorithm * ({@link com.github.coderodde.util.StaightInsertionSort}). * * @author Rodion "rodde" Efremov * @version 1.6 (May 12, 2020) ~ initial version. * @since 1.6 (May 12, 2020) */ public class StaightInsertionSortTest { public static final int REPETITIONS = 10_000; public static final int LENGTH = 100; @Test public void bruteForceTest() { long seed = System.currentTimeMillis(); System.out.println("Seed = " + seed); Random random = new Random(); for (int repetition = 0; repetition &lt; REPETITIONS; repetition++) { Integer[] array1 = getRandomIntegerArray(random, LENGTH); Integer[] array2 = array1.clone(); int index1 = random.nextInt(LENGTH), index2 = random.nextInt(LENGTH); int fromIndex = Math.min(index1, index2); int toIndex = Math.max(index1, index2); Arrays.sort(array1, fromIndex, toIndex); StaightInsertionSort.sort(array2, fromIndex, toIndex); assertTrue(Arrays.equals(array1, array2)); } } } </code></pre> <p><strong><code>com.github.coderodde.util.SharedSortingTestUtils.java:</code></strong></p> <pre><code>package com.github.coderodde.util; import java.util.Random; /** * This class provides shared facilities for unit testing. * * @author Rodion "rodde" Efremov * @version 1.6 (May 12, 2020) ~ initial version. * @since 1.6 (May 12, 2020) */ class SharedSortingTestUtils { static Integer[] getRandomIntegerArray(Random random, int length) { Integer[] array = new Integer[length]; for (int i = 0; i &lt; length; i++) { array[i] = random.nextInt(); } return array; } } </code></pre> <p><strong><code>com.github.coderodde.util.Demo.java</code></strong></p> <pre><code>package com.github.coderodde.util; import java.util.Random; /** * This class implements a demonstration comparing performance of straight * and binary insertion sort algorithms. * * @author Rodion "rodde" Efremov * @version 1.6 (May 12, 2020) ~ initial version. * @since 1.6 (May 12, 2020) */ public class Demo { public static final int REPETITIONS = 100_000; public static final int MAX_LENGTH_NORMAL = 2048; public static final int MAX_LENGTH_SMALL = 64; interface SortingAlgorithm&lt;E&gt; { public void sort(E[] array, int fromIndex, int toIndex); } public static void main(String[] args) { long seed = System.currentTimeMillis(); System.out.println("seed = " + seed); Random random = new Random(seed); /////////////////////////////////////////// System.out.println("--- Small arrays ---"); warmupSmall(random, seed); benchmarkSmall(random, seed); //////////////////////////////////////////// System.out.println("--- Normal arrays ---"); warmupNormal(random, seed); benchmarkNormal(random, seed); } static void warmupSmall(Random random, long seed) { random.setSeed(seed); System.out.print("Warmed up "); System.out.print(StaightInsertionSort.class.getSimpleName()); warmup(MAX_LENGTH_SMALL, REPETITIONS, random, StaightInsertionSort::sort); random.setSeed(seed); System.out.print("Warmed up "); System.out.print(BinaryInsertionSort.class.getSimpleName()); warmup(MAX_LENGTH_SMALL, REPETITIONS, random, BinaryInsertionSort::sort); } static void benchmarkSmall(Random random, long seed) { random.setSeed(seed); System.out.print("Benchmarked "); System.out.print(StaightInsertionSort.class.getSimpleName()); benchmark(MAX_LENGTH_SMALL, REPETITIONS, random, StaightInsertionSort::sort); random.setSeed(seed); System.out.print("Benchmarked "); System.out.print(BinaryInsertionSort.class.getSimpleName()); benchmark(MAX_LENGTH_SMALL, REPETITIONS, random, BinaryInsertionSort::sort); } static void warmupNormal(Random random, long seed) { random.setSeed(seed); System.out.print("Warmed up "); System.out.print(StaightInsertionSort.class.getSimpleName()); warmup(MAX_LENGTH_NORMAL, REPETITIONS, random, StaightInsertionSort::sort); random.setSeed(seed); System.out.print("Warmed up "); System.out.print(BinaryInsertionSort.class.getSimpleName()); warmup(MAX_LENGTH_NORMAL, REPETITIONS, random, BinaryInsertionSort::sort); } static void benchmarkNormal(Random random, long seed) { random.setSeed(seed); System.out.print("Benchmarked "); System.out.print(StaightInsertionSort.class.getSimpleName()); benchmark(MAX_LENGTH_NORMAL, REPETITIONS, random, StaightInsertionSort::sort); random.setSeed(seed); System.out.print("Benchmarked "); System.out.print(BinaryInsertionSort.class.getSimpleName()); benchmark(MAX_LENGTH_NORMAL, REPETITIONS, random, BinaryInsertionSort::sort); } static void perform(boolean isBenchmark, int maxLength, int repetitions, Random random, SortingAlgorithm&lt;Integer&gt; sortingAlgorithm) { long startTime = System.currentTimeMillis(); for (int repetition = 0; repetition &lt; repetitions; repetition++) { Integer[] array = getRandomIntegerArray(random, maxLength); int index1 = random.nextInt(maxLength); int index2 = random.nextInt(maxLength); int fromIndex = Math.min(index1, index2); int toIndex = Math.max(index1, index2); sortingAlgorithm.sort(array, fromIndex, toIndex); } System.out.println(" in " + (System.currentTimeMillis() - startTime) + " milliseconds."); } static void benchmark(int length, int repetitions, Random random, SortingAlgorithm sortingAlgorithm) { perform(true, length, repetitions, random, sortingAlgorithm); } static void warmup(int length, int repetitions, Random random, SortingAlgorithm sortingAlgorithm) { perform(false, length, repetitions, random, sortingAlgorithm); } static Integer[] getRandomIntegerArray(Random random, int length) { Integer[] array = new Integer[length]; for (int i = 0; i &lt; length; i++) { array[i] = random.nextInt(); } return array; } } </code></pre> <p>(The GitHub repository for this project is <a href="https://github.com/coderodde/BinaryInsertionSort" rel="nofollow noreferrer">here</a>.)</p> <p><strong>Sample output</strong></p> <pre><code>seed = 1589305635492 --- Small arrays --- Warmed up StaightInsertionSort in 160 milliseconds. Warmed up BinaryInsertionSort in 133 milliseconds. Benchmarked StaightInsertionSort in 125 milliseconds. Benchmarked BinaryInsertionSort in 129 milliseconds. --- Normal arrays --- Warmed up StaightInsertionSort in 30890 milliseconds. Warmed up BinaryInsertionSort in 6897 milliseconds. Benchmarked StaightInsertionSort in 32279 milliseconds. Benchmarked BinaryInsertionSort in 7022 milliseconds. </code></pre> <p><strong>Critique request</strong></p> <p>First and foremost, I would like to hear your opinions on unit testing. Does generating a bunch of input instances and comparing the sort output to <code>Arrays.sort</code> output a good idea? I tried also to deal with warming up the JVM, yet I did not use any funky third-party libraries for that.</p>
[]
[ { "body": "<p>The only reason <code>BinaryInsertionSort</code> outperforms <code>StraightInsertionSort</code> is that it is in the position to call <code>System.arraycopy</code>, which I expect to be highly optimized (possibly all the way down to <code>memcpy</code>), and much faster than the element-by-element copying loop <code>StraightInsertionSort</code> does. It tastes like cheating. You compare apples to oranges.</p>\n\n<p>From the purely algorithmic point of view, both versions copy elements the same number of times. Binary version may do less comparisons. However, it may do way more. Consider the case of sorting a sorted array. Both versions do zero copies. Straight sort does 1 comparison per element; <span class=\"math-container\">\\$O(n)\\$</span> total. Binary sort does <span class=\"math-container\">\\$\\log k\\$</span> comparisons per element; <span class=\"math-container\">\\$O(n\\log n)\\$</span> total.</p>\n\n<p>Also, the straight sort implementation is suboptimal. It does two comparisons per inner loop iteration: <code>j &gt;= fromIndex</code> and <code>comparator.compare(array[j], targetElement) &gt; 0</code>. It is possible to get away with one:</p>\n\n<pre><code> if (comparator.compare(array[fromIndex], targetElement &gt; 0) {\n // The target element is less than all other elements. We\n // don't need to compare values anymore.\n // NB: May as well call System.arraycopy here.\n while (j &gt;= fromIndex) {\n array[j+1] = array[j];\n j--;\n } else {\n // The leftmost element is now a natural sentinel. We don't\n // need to compare indices anymore.\n while (comparator.compare(array[j], targetElement) &gt; 0) {\n array[j+1] = array[j];\n j--;\n }\n }\n</code></pre>\n\n<hr>\n\n<p>The only practical application of the insertion sort I am aware of is sorting almost sorted arrays, that is those in which every element is within fixed small distance <code>k</code> from its final position (e.g. quicksort with the recursion cutoff). Benchmarking such arrays will be most instructive. Try a 100 million-strong array with <code>k = 16</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-12T20:26:27.707", "Id": "242155", "ParentId": "242149", "Score": "3" } }, { "body": "<blockquote>\n<pre><code> while (j &gt;= fromIndex \n &amp;&amp; comparator.compare(array[j], targetElement) &gt; 0) {\n array[j + 1] = array[j];\n j--;\n }\n</code></pre>\n</blockquote>\n\n<p>This code does two things. It finds the insertion point and it moves the existing elements. It could do just one thing. </p>\n\n<pre><code> while (j &gt;= fromIndex \n &amp;&amp; comparator.compare(array[j], targetElement) &gt; 0) {\n j--;\n }\n</code></pre>\n\n<p>Now it only finds the insertion point. </p>\n\n<p>Then you can insert with something like </p>\n\n<pre><code> final int n = i - j;\n\n switch (n) {\n case 2: array[j + 2] = array[j + 1];\n case 1: array[j + 1] = array[j];\n case 0:\n break;\n\n default:\n System.arraycopy(array, j, array, j + 1, n);\n }\n array[j] = targetElement;\n</code></pre>\n\n<p>Not tested for fencepost errors, etc. You may have to increment <code>j</code> before this. But this should show the essential concept. </p>\n\n<p>Now both algorithms use essentially the same insertion code and you can compare the time to find the insertion point more directly. So if your goal is to compare the two methods of finding the insertion point, this would be a better test. It more clearly isolates that difference. </p>\n\n<p>Another alternative would be to stop using <code>System.arraycopy</code> and write a manual move routine in your binary insertion sort. That would also fix the problem of comparability. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-13T05:26:57.903", "Id": "242166", "ParentId": "242149", "Score": "1" } }, { "body": "<blockquote>\n<p>I would like to hear your opinions on unit testing</p>\n</blockquote>\n<p>Way to go. When I saw <code>BinaryInsertionSort.sort(E[] array, int fromIndex, int toIndex, Comparator&lt;? super E&gt; comparaotr)</code>, I was dubious it worked - after all, my spelling checker flagged the last parameter. Gave it a backhanded try:</p>\n<pre><code> public static void main(String[] args) {\n Integer[]a = { 1, 3, 2, 0 };\n sort(a);\n System.out.println(java.util.Arrays.toString(a));\n }\n</code></pre>\n<blockquote>\n<p>[1, 1, 3, 3]</p>\n</blockquote>\n<p>When I scrolled through the question, I rolled my eyes for the code duplicated among <em>StraightInsertionSortTest.java</em> and <em>BinaryInsertionSortTest.java</em>.<br />\nFurther down, <code>BinaryInsertionSortTest.bruteForceTest()</code> reads</p>\n<pre><code> StaightInsertionSort.sort(array2, fromIndex, toIndex);\n</code></pre>\n<p>Lesson: I need a better spelling checker. Marking all of <code>StaightInsertionSort</code> had me miss the typo in the first word.<br />\n(How on earth <em>did</em> you get that accepted in a <em>StraightInsertionSortTest.java</em>?!)</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-20T15:55:48.440", "Id": "253705", "ParentId": "242149", "Score": "0" } } ]
{ "AcceptedAnswerId": "242155", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-12T18:22:13.420", "Id": "242149", "Score": "2", "Tags": [ "java", "algorithm", "sorting", "binary-search", "insertion-sort" ], "Title": "Comparing binary insertion sort with straight insertion sort in Java" }
242149
<p>I have written a C program to sort files (on Windows) into dynamically created subfolders based on information found in their data headers. I am a newb at C, especially memory management. <strong>The code works</strong>. I have <strong>tested it on a small sample</strong> of 6 files. The next step is to put it into "production" and have it sort a giant, 1,000+ files (18+ GB) folder of files (if it would help, please note that the files I am sorting start at 1MB and have no upper limit, but the average is between 50MB and 100MB). I have not done this yet because I do not have confidence in my C. I do not want to brick my computer or my drives. Any responses on memory/storage safety (and to a lesser extent, speed) would be greatly appreciated.</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;errno.h&gt; #include &lt;limits.h&gt; #include &lt;string.h&gt; #include &lt;dirent.h&gt; #include &lt;errno.h&gt; #include &lt;sys/stat.h&gt; #include &lt;sys/types.h&gt; //demo header info struct, written by me //specifications here: https://developer.valvesoftware.com/wiki/DEM_Format typedef struct dhead { char header[8]; int demp; int netp; unsigned char servername[260]; unsigned char clientname[260]; unsigned char map[260]; unsigned char gamedir[260]; float playback; int ticks; int frames; int signon; } dhead; struct dhead alldemos[1000*sizeof(dhead)]; unsigned char buffer[1000]; FILE *ptr; /* Everything above here I wrote */ /* BEGIN STUFF I STOLE */ char* replace_char(char* str, char find, char replace) { char *current_pos = strchr(str, find); for (char* p = current_pos; (current_pos = strchr(str, find)) != NULL; *current_pos = replace); } const char *get_filename_ext(const char *filename) { const char *dot = strrchr(filename, '.'); if (!dot || dot == filename) return ""; return dot+1; } // I found this online and made a few tweaks to make it a function int move(char *in_, char *out_) { size_t len = 0; char a[256]; strcpy(a, in_); char b[256]; strcpy(b, out_); strcat(b, "\\"); strcat(b, a); char buffer[BUFSIZ] = {'\0'}; printf("Moving %s -&gt; %s\n", a, b); FILE* in = fopen(a, "rb"); FILE* out = fopen(b, "wb"); if (in == NULL || out == NULL) { printf("mve: %s, %s %s\n", in, out, out_); perror("Error while opening files in mv"); in = out = 0; } else { while((len = fread(buffer, BUFSIZ, 1, in)) &gt; 0) { fwrite(buffer, BUFSIZ, 1, out); } fclose(in); fclose(out); if (remove(a) == 0){printf("File moved\n");}else{ printf("Error while removing file: \n"); perror(NULL); } } return 0; } // https://gist.github.com/JonathonReinhart/8c0d90191c38af2dcadb102c4e202950 int mkdir_p(char *path) { printf("Mkdir called: %s\n", path); /* Adapted from http://stackoverflow.com/a/2336245/119527 */ const size_t len = strlen(path); char _path[PATH_MAX]; char *p; errno = 0; /* Copy string so its mutable */ if (len &gt; sizeof(_path)-1) { errno = ENAMETOOLONG; printf("ENAMETOOLONG\n"); return -1; } strcpy(_path, path); /* Iterate the string */ for (p = _path + 1; *p; p++) { if (*p == '\\') { /* Temporarily truncate */ *p = '\0'; if (mkdir(_path) != 0) { if (errno != 17){ printf("Err: %s\n", strerror(errno)); return -1; } } *p = '\\'; } } if (mkdir(_path) != 0) { if (errno != 17){ printf("Err: %s\n", strerror(errno)); return -1; } } return 0; } /* END STUFF I STOLE */ /* Everything below here I wrote */ int list_len = 0; /* I wrote this function to search a directory and compile a list of demo files and put demo information into a struct*/ int find_demos(char* directory_location, char** list) { struct dirent *de; DIR *directory = opendir(directory_location); list_len = 0; while ((de = readdir(directory)) != NULL) { if (strcmp(get_filename_ext(de-&gt;d_name),"dem")) //if file not dem { continue; } list[list_len] = strdup(de-&gt;d_name); ptr = fopen(de-&gt;d_name, "rb"); fread(&amp;alldemos[list_len], sizeof(dhead), 1, ptr); list_len++; fclose(ptr); } closedir(directory); perror(NULL); printf("Closed dir\n"); return 0; } /* I wrote this function to call mkdir_p to create directories for each demo then move them there. */ int create_dirs(char** list) { for (int iter = 0; iter &lt; list_len; iter++) //for file { printf("\n\n"); //establish path and demo char pth[256]; dhead dem = alldemos[iter]; //can't have folders with : in windows replace_char(dem.servername, ':', '@'); //establish truncated date char date[8]; strncpy(date, list[iter], 7); date[7] = '\0'; //create path snprintf(pth, 256, "%s\\%s\\%s", dem.map, date, dem.servername); printf("File: %s | Path: %s\n", list[iter], pth); //create path if (mkdir_p(pth) != 0) { printf("Makedir error %s\n", strerror(errno)); } //move demo move(list[iter], pth); } return 0; } /* I also wrote this. I initialize an array of arrays to hold all relevant file names */ int main(int argc, char *argv[]) { char **list; //the two * means this is a pointer to a pointer //const int datacount = 2100; //I have like 2100 files to search through, although only near 1,000 +- 50 will be entered into the array. list = malloc(260*210); //A quick google search shows that max filename length is 259 so this should work. if (!list) { //if can't allocate space perror("Error allocating memory"); abort(); } for (int i = 0; i &lt; 2000; ++i) { list[i] = (char *)malloc(261); //each string is (probably) no longer than 260 bytes + a null terminator (in practice, a majority of those bytes will be termintors but I'm being safe) } find_demos(".", list); create_dirs(list); return 0; } <span class="math-container">```</span> </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-12T22:23:03.513", "Id": "475237", "Score": "0", "body": "Please add comments before and after the parts you wrote, so we know what to review." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-12T22:50:20.200", "Id": "475238", "Score": "0", "body": "Alright, I added a few more comments that I hope will clarify." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-13T06:12:50.610", "Id": "475253", "Score": "1", "body": "Is there any specific reason why you chose C as the programming language? If you had chosen Python instead, the code would have been much shorter, and you wouldn't have to care about memory management. String processing is a lot easier in Python than in C." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-13T07:08:26.450", "Id": "475259", "Score": "0", "body": "@RolandIllig Well I thought learning C would be fun (I was wrong), but also I was attracted to the ease of compiling binaries with no need to install C or dependencies for end users. I originally wanted to write this in Lua, which I am fluent in, but I struggled to find a program that could link a LuaJIT compiler with dependencies for use on another computer with little work. Python did not cross my mind, I do not know the process of creating bins for it. Having bins has since moved to the back of my mind, but I'd revisit, were I to bulk up the program with more useful features." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-13T14:09:55.450", "Id": "475330", "Score": "0", "body": "`struct dhead alldemos[1000*sizeof(dhead)];` <-- erm... do you even know how big the array will be on different platforms? If you want an array to hold 1000 `dhead` structs, just use `dhead alldemos[1000]`. Also: your use of `strcpy` and `strcat` into a buffer of `char[256]` is a bit worrying. Just use `strncat` and `strncpy`. You can do that here" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-13T14:13:24.253", "Id": "475331", "Score": "0", "body": "@EliasVanOotegem This would be better in an answer." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-13T14:14:52.187", "Id": "475332", "Score": "1", "body": "@pacmaninbw Yeah, might actually take some time to properly review this. There's a lot more to be said, though, and I only tend to commit to writing up a review if I'm going to cover the full code" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-13T17:08:33.147", "Id": "475349", "Score": "0", "body": "@EliasVanOotegem Can you please explain what is worrying about using `char[256]`? Even if I were to replace all the `str` functions with `strn` equivalents wouldn't I still need to have a chararray with enough space to store the result?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-13T23:59:08.367", "Id": "475372", "Score": "0", "body": "@EliasVanOotegem: Please don't suggest to use `strncpy` and `strncat` with strings, they are not meant for that, despite their names. Both these functions are badly named since they do not guarantee to null-terminate the memory blocks they are working with." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-14T16:08:23.687", "Id": "475446", "Score": "0", "body": "@RolandIllig You could use `snprintf` I suppose, but I can't think of an alternative for `strncat` off the top of my head. Checking where the nil-char should go and manually setting it a rather trivial task. What are `strncpy` and `strncat` meant for if not strings, especially considering `memcpy` is its own function" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-14T16:10:38.493", "Id": "475448", "Score": "0", "body": "@Zidgel you have an array of 256 chars, so each time you concatenate strings, or copy them, you know how much space is left in your buffer. I'd use `strn*` functions so I can ensure that the buffer will never overflow" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-14T17:40:11.600", "Id": "475463", "Score": "0", "body": "@EliasVanOotegem but I don't intrinsically know how much space is left in the buffer. The strings are programmatically found from files. They vary in length. I would have to call a function to determine the size of a string before every `strn*` call." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "12", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-12T19:12:47.460", "Id": "242150", "Score": "4", "Tags": [ "beginner", "c", "file-system", "windows" ], "Title": "C program to sort files based on information within" }
242150
<p>A program that generates questions to train your number base conversion skills. This program is made to ask questions about octet, binary and hexadecimal. No other bases. It first asks a series of questions to the user such as "amount of questions", "question type" and "base". Then, it starts generating questions based on the user's input. The user can give an answer and it will tell them if they're correct. Code is perfectly functional.</p> <p>I'm asking for a review because I sense a bad smell in my code. It feels overly long, repetitive, and kind of confusing. There surely must be a better way. Maybe an OOP approach? Something to cut down on the complexity and "if-else" repetition. Though, I feel it is this way partly because I have limited it to <em>only</em> 3 bases. I'm a late beginner but I wouldn't say that I am intermediate just yet.</p> <p>My code uses only one external library, that is <code>baseconvert</code>. Can be installed with pip using <code>pip install baseconvert</code></p> <pre><code>import random import baseconvert # The Start # --------- # Step 1: Ask whether the user wants 'Decimal &gt; Base X' or 'Base X &gt; Decimal' or 'Random' # Step 2: Ask how many questions the user wants. Type the answer. Type -1 for infinite. # Step 3: If infinite, prompt to type 'f' to stop. # Step 4: Ask what base you want based on index. 1. Octet // 2. Hexadecimal // 3. Binary // 4. Random def question_type_ask(): print('Which question would you like to be asked?') print('1. Decimal &gt; Base X\n2. Base X &gt; Decimal\n3. Random') ans = input('Input: ') if ans != '1' and ans != '2' and ans != '3': print('Invalid input') question_type_ask() return ans def amount_ask(): print('How many questions do you want to be asked? Type -1 for infinite.') print('Type \'f\' as answer to stop') try: ans = int(input('Input: ')) except ValueError: print('Input numbers only, please.') return amount_ask() if ans &gt;= -1: return ans else: return amount_ask() def base_ask(): print('Which base do you want to be asked?') print('1. Octet\n2. Hexadecimal\n3. Binary\n4. Random') ans = input('Input: ') if ans != '1' and ans != '2' and ans != '3' and ans != '4': print('Invalid input') base_ask() return ans question_type = question_type_ask() amount = amount_ask() base = base_ask() is_random_question = False is_random_base = False if question_type == '3': is_random_question = True if base == '4': is_random_base = True def question_generator(): global question_type global amount global base base_list = ['1', '2', '3'] type_list = ['1', '2'] while True: if is_random_base: base = random.choice(base_list) if is_random_question: question_type = random.choice(type_list) if question_type == '1': # Decimal &gt; Base X base1 = 'Base 10' num = random.randrange(100, 100000) if base == '1': # Octet base2 = 'Base 8' correct_ans = baseconvert.base(num, 10, 8, string=True) break elif base == '2': # Hexa base2 = 'Base 16' correct_ans = baseconvert.base(num, 10, 16, string=True) break elif base == '3': # Binary base2 = 'Base 2' correct_ans = baseconvert.base(num, 10, 2, string=True) break elif base == '4': # Random base2 = random.choice(base_list) if base2 == base_list[0]: base = '1' elif base2 == base_list[1]: base = '2' elif base2 == base_list[2]: base = '3' elif question_type == '2': # Base X &gt; Decimal base2 = 'Base 10' correct_ans = str(random.randrange(100, 100000)) if base == '1': # Octet base1 = 'Base 8' num = baseconvert.base(correct_ans, 10, 8, string=True) break elif base == '2': # Hexa base1 = 'Base 16' num = baseconvert.base(correct_ans, 10, 16, string=True) break elif base == '3': # Binary base1 = 'Base 2' num = baseconvert.base(correct_ans, 10, 2, string=True) break elif base == '4': # Random base1 = random.choice(base_list) if base1 == base_list[0]: base = '1' elif base1 == base_list[1]: base = '2' elif base1 == base_list[2]: base = '3' print(f'[{base1}] {num} to [{base2}]') ans = input('Answer: ') if ans == correct_ans: print('You are correct!') elif ans.lower() == 'f': question_generator() else: print(f'Wrong! The answer is {correct_ans}') counter = 0 if amount == -1: amount = float('inf') while counter &lt; amount: counter += 1 question_generator() </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-14T11:53:15.920", "Id": "475421", "Score": "0", "body": "New code scored 9.05/10 in pylint so that's awesome. Just one question, is the `while True:` loop inside `question_generator` function really necessary ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-14T14:45:55.037", "Id": "475434", "Score": "0", "body": "I have rolled back your latest post. Once an answer has been provided, you may not change your question. See the [help], specifically the [What should I do when someone answers my question?](https://codereview.stackexchange.com/help/someone-answers), and especially \"What should I _not_ do\". If you want your updated code to be reviewed, you must post a new question." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-14T15:49:42.703", "Id": "475443", "Score": "0", "body": "You can post a new question or simply discuss more in chat" } ]
[ { "body": "<ul>\n<li>Firstly I would recommend not to use recursive methods for handling wrong inputs. A simple <code>while</code> loop is enough.</li>\n<li>Use <code>.strip()</code> while taking inputs since <code>'a'=='a '</code> is <code>False</code> in python.</li>\n<li>If you are playing with numbers, keep them as numbers, not as strings. Usually numbers are easier to handle.</li>\n<li>Avoid use of <code>global</code> if simple passing as arguments is an available option.</li>\n<li>In the <code>if-elif</code> ladder, the condition <code>base=='4'</code> is unnecessary since you are already handling random case using the flags <code>is_random_question</code> and <code>is_random_base</code>.</li>\n<li>I have added a dictionary <code>base_dict</code> which eliminates the need of <code>if-else</code> repetitions.</li>\n<li>Why would you do <code>elif ans.lower()=='f': question_generator()</code> when you want <code>'Type \\'f\\' as answer to stop'</code>? I have modified the while loop inside <code>generate_question</code> method to work as counter for number of questions.</li>\n</ul>\n\n<pre class=\"lang-py prettyprint-override\"><code>import random\nimport baseconvert\n\ndef question_type_ask():\n print('Which question would you like to be asked?')\n print('1. Decimal &gt; Base X\\n2. Base X &gt; Decimal\\n3. Random')\n ans = input('Input: ').strip()\n # print(ans)\n while ans&lt;'1' or ans&gt;'3':\n ans = input('Invalid input. Enter again: ')\n return int(ans)\n\ndef amount_ask():\n print('How many questions do you want to be asked? Type -1 for infinite.')\n print('Type \\'f\\' as answer to stop')\n while True:\n ans = input('Input: ').strip()\n if not ans.lstrip('-+').isnumeric():\n print('Input numbers only, please.')\n elif int(ans)&lt;-1 or int(ans)==0:\n print('Input -1 or positive numbers only, please.') \n else:\n break\n return int(ans)\n\ndef base_ask():\n print('Which base do you want to be asked?')\n print('1. Octet\\n2. Hexadecimal\\n3. Binary\\n4. Random')\n ans = input('Input: ').strip()\n # print(ans)\n while ans&lt;'1' or ans&gt;'4':\n ans = input('Invalid input. Enter again: ')\n return int(ans)\n\nquestion_type = question_type_ask()\namount = amount_ask()\nbase = base_ask()\n# print(question_type, amount, base)\nis_random_question = False\nis_random_base = False\nif question_type == 3:\n is_random_question = True\nif base == 4:\n is_random_base = True\n\ndef question_generator(question_type, amount, base):\n base_list = [1, 2, 3]\n type_list = [1, 2]\n base_dict = {1:8, 2:16, 3:2}\n\n counter = 0\n if amount == -1:\n amount = float('inf')\n while counter &lt; amount:\n counter += 1\n\n if is_random_base:\n base = random.choice(base_list)\n if is_random_question:\n question_type = random.choice(type_list)\n if question_type == 1: # Decimal &gt; Base X\n num = random.randrange(10, 100)\n base1 = 10\n base2 = base_dict[base]\n correct_ans = baseconvert.base(num, base1, base2, string=True)\n elif question_type == 2: # Base X &gt; Decimal\n base1 = base_dict[base]\n base2 = 10\n correct_ans = str(random.randrange(10, 100))\n num = baseconvert.base(correct_ans, base2, base1, string=True)\n\n print(f'\\n[Base {base1}] {num} to [Base {base2}] ?')\n ans = input('Answer: ').strip()\n if ans.lower() == 'f':\n break\n if ans == correct_ans.lower():\n print('You are correct!')\n else:\n print(f'Wrong! The answer is {correct_ans}')\n\nquestion_generator(question_type, amount, base)\n<span class=\"math-container\">```</span>\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-13T07:04:20.033", "Id": "475256", "Score": "1", "body": "Thank you! Excellent answer. The idea of using dictionaries had never crossed my mind." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-14T04:31:42.863", "Id": "475377", "Score": "0", "body": "I've completely rewritten my code based on your suggestions. Can you take a look and tell me what you think?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-14T14:54:50.853", "Id": "475439", "Score": "0", "body": "You use `.strip()` when getting the first input (`ans = input('Input: ').strip()`) but not when you ask the user to re-enter (`ans = input('Invalid input. Enter again: ')`). The test `ans<'1' or ans>'3'` is broken, since `\"2048\"` will pass, the first character being greater than `\"1\"` and less than `\"3\"`. Also, `not ans.lstrip('-+').isnumeric()` is not sufficient validation as `\"-+-+23\"` will pass. Also, `\"¼⁸\".isnumeric()` returns `True`; the method you want is `.isdecimal()`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-14T15:48:54.500", "Id": "475441", "Score": "0", "body": "@AJNeufeld Thanks for pointing out such details that i somehow missed. If i remember correctly, the new code (not there anymore) did solve some of the points you mentioned." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-13T05:32:39.960", "Id": "242167", "ParentId": "242156", "Score": "2" } }, { "body": "<p><strong>When you ask the user to input</strong>: (It applys in <code>question_type_ask()</code>, <code>ask_amount()</code> and <code>ask_base()</code>)</p>\n\n<p>It's better to add <code>.strip()</code> after taking the input; otherwise, the input with leading whitespace will be invalid.</p>\n\n<p>You may use <code>try...except</code> to check the input's validity:</p>\n\n<pre><code>while True:\n try:\n ans = int(ans)\n if ans &lt; 1 or ans &gt; 3:\n ans = input('Invalid input. Try again: ').strip()\n else: \n return ans\n except ValueError: \n ans = input('Invalid input. Try again: ').strip()\n</code></pre>\n\n<p><strong><code>question_generator(question_type, amount, base)</code>:</strong></p>\n\n<p><code>base_dict = {1: 8, 2: 16, 3: 2, 4: 'Random'}</code> ('Random' or None) is better; because in Python, all non-zero integers are True.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-14T09:05:46.977", "Id": "475405", "Score": "1", "body": "Ah, yes! I forgot about `.strip()`. That last fact about non-zero integers is very helpful. It explains why I had to use `stored_base is True:` instead of just `stored_base:`. Thanks!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-14T08:26:07.713", "Id": "242251", "ParentId": "242156", "Score": "2" } } ]
{ "AcceptedAnswerId": "242167", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-12T20:51:25.970", "Id": "242156", "Score": "5", "Tags": [ "python", "beginner", "python-3.x" ], "Title": "Number Base Conversion Problem Generator" }
242156
<p>Any improvements? </p> <pre><code>import datetime import json class CustomEncoder(json.JSONEncoder): def default(self, obj): """ This method will only be called if an object is passed to the parent JSON encoder in the case it doesn't know how to deal with. In case the object passed to the encode method of JSON that is by default json serializable [eg.: list] this method will not be called """ if isinstance(obj, datetime.datetime): # Return a JSON object where each parameter of the datetime object is a key in a dictionary. return { '_type': 'datetime', 'year': obj.year, 'month': obj.month, 'day': obj.day, 'hour': obj.hour, 'minute': obj.minute, 'second': obj.second } elif isinstance(obj, datetime.timedelta): return { '_type': 'timedelta', 'days': obj.days, 'seconds': obj.seconds, 'microseconds': obj.microseconds } # In case the object passed is not serializable by default and, # is not implemented above; the default method will fall through here. In which case: # Pass the object back to the default JSON handler and: return super().default(obj) # Let the default JSON handler output the error: not serializable. class CustomDecoder(json.JSONDecoder): def __init__(self, *args, **kwargs): json.JSONDecoder.__init__(self, object_hook=self.object_hook, *args, **kwargs) @staticmethod def object_hook(obj): decodes = {'datetime': datetime.datetime, 'timedelta': datetime.timedelta} if '_type' in obj: data_type = obj.pop('_type') # This line will return either: # a decoded object of a type specified in the "decodes" dictionary # or obj without any modification to it's type in case the type is not implemented yet. return decodes.get(data_type, lambda **kwargs: kwargs)(**obj) # Testing: now = datetime.datetime.now() encoded_datetime_data = json.dumps(now, cls=CustomEncoder, indent=2) decoded_datetime_data = json.loads(encoded_datetime_data, cls=CustomDecoder) encoded_timedelta_data = json.dumps(datetime.timedelta(0), cls=CustomEncoder, indent=2) decoded_timedelta_data = json.loads(encoded_timedelta_data, cls=CustomDecoder) encoded_array = json.dumps([1, 2, 3, 4], cls=CustomEncoder, indent=2) decoded_array = json.loads(encoded_array, cls=CustomDecoder) print(encoded_datetime_data) print(decoded_datetime_data) print(type(decoded_datetime_data)) print(encoded_timedelta_data) print(decoded_timedelta_data) print(type(decoded_timedelta_data)) print(encoded_array) print(decoded_array) print(type(decoded_array)) class Nothing: pass # This will fail: (TypeError: Object of type Nothing is not JSON serializable) encoded_nothing_data = json.dumps(Nothing(), cls=CustomEncoder) decoded_nothing_data = json.loads(encoded_nothing_data, cls=CustomDecoder) <span class="math-container">```</span> </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-13T00:01:30.067", "Id": "242158", "Score": "2", "Tags": [ "python" ], "Title": "JSON Class Extension" }
242158
<p><a href="https://en.wikipedia.org/wiki/Kosaraju%27s_algorithm" rel="nofollow noreferrer">Kosaraju algorithm</a> is mainly phrased as two <em>recursive</em> subroutines running <em>postorder</em> <a href="https://en.wikipedia.org/wiki/Depth-first_search" rel="nofollow noreferrer">DFS</a> twice to mark <a href="https://en.wikipedia.org/wiki/Strongly_connected_component" rel="nofollow noreferrer">SCCs</a> with linear time complexity <em>O(V+E)</em> below,</p> <blockquote> <ol> <li><p>For each vertex u of the graph, mark u as unvisited. Let L be empty.</p></li> <li><p>For each vertex u of the graph do Visit(u), where Visit(u) is the recursive subroutine: </p></li> </ol> <p>&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; If u is unvisited then: </p> <p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 1. Mark u as visited. </p> <p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 2. For each out-neighbour v of u, do Visit(v). </p> <p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 3. Prepend u to L. </p> <p>&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Otherwise do nothing. </p> <ol start="3"> <li>For each element u of L in order, do Assign(u,u) where Assign(u,root) is the recursive subroutine: </li> </ol> <p>&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; If u has not been assigned to a component then: </p> <p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 1. Assign u as belonging to the component whose root is root. </p> <p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 2. For each in-neighbour v of u, do Assign(v,root). </p> <p>&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Otherwise do nothing.</p> </blockquote> <p>Here is the <em>recursive</em> implementation in <em>Python</em> according to the above recipe,</p> <pre><code>def kosaraju(G): # postorder DFS on G to transpose the graph and push root vertices to L N = len(G) T, L, U = [[] for _ in range(N)], [], [False] * N def visit(u): if not U[u]: U[u] = True for v in G[u]: visit(v) T[v].append(u) L.append(u) for u in range(N): visit(u) # postorder DFS on T to pop root vertices from L and mark SCCs C = [None] * N def assign(u, r): if U[u]: U[u] = False C[u] = r for v in T[u]: assign(v, r) while L: u = L.pop() assign(u, u) return C </code></pre> <p>The following <em>iterative</em> implementation scales well against the stack overflow due to excessively deep recursion, however it deserves to be shared for further improvement. I'll be glad about all your opinions or alternative implementations.</p> <p><strong>@EDIT</strong></p> <p>The inner loop of the first <em>iterative</em> DFS has been corrected below, so the linear time complexity <em>O(V+E)</em> is guaranteed now.</p> <pre><code>def kosaraju(G): # postorder DFS on G to transpose the graph and push root vertices to L N = len(G) T, L, U = [[] for _ in range(N)], [], [False] * N for u in range(N): if not U[u]: U[u], S = True, [u] while S: u, done = S[-1], True for v in G[u]: T[v].append(u) if not U[v]: U[v], done = True, False S.append(v) break if done: S.pop() L.append(u) # postorder DFS on T to pop root vertices from L and mark SCCs C = [None] * N while L: r = L.pop() S = [r] if U[r]: U[r], C[r] = False, r while S: u, done = S[-1], True for v in T[u]: if U[v]: U[v] = done = False S.append(v) C[v] = r break if done: S.pop() return C </code></pre> <p>Test example:</p> <pre><code>G = [[1], [0, 2], [0, 3, 4], [4], [5], [6], [4], [6]] print(kosaraju(G)) # =&gt; [0, 0, 0, 3, 4, 4, 4, 7] </code></pre> <p><a href="https://i.stack.imgur.com/IPswe.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/IPswe.png" alt="enter image description here"></a></p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-13T00:58:05.520", "Id": "242161", "Score": "6", "Tags": [ "python", "algorithm", "graph", "depth-first-search" ], "Title": "Recursive and iterative implementation on Kosaraju algorithm" }
242161
<p>I am trying to implement the Jagged Diagonal Storage code in Cuda for Sparse Matrix - Vector multiplication. The code I wrote is as follows but I'm not sure about it:</p> <pre><code>__global__ jds_kernel(JDSMatrix jds, float * invector, float * outvector){ int i = blockIdx.x * blockDime.x + threadIdx.x; int row = jds.rows[i]; if (row &lt; jds.numRows){ float sum = 0.0f; for (nnz=0; nnz &lt; jds.nnzperrow[row]; ++nnz){ int idx = i + jds.iterPtr[nnz]; int col = jds.colIdxs[idx]; int val = jds.values[idx]; sum += invector[col] * val; } output[row] = sum; } } </code></pre> <p>Assuming that:</p> <ul> <li><code>jds</code> is the jds matrix</li> <li><code>invector</code> is the input vector</li> <li><code>outvector</code> is the output vector</li> <li><code>jds.numRows</code> is the number of rows in the jds matrix</li> <li><code>jds.nnzperrow</code> is the number of non-zero entries in per row</li> <li><code>jds.rows</code> are the rows </li> <li><code>jds.iterPtr</code> is the iteration pointer</li> <li><code>jds.colIdxs</code> is the column indexes</li> <li><code>jds.values</code> are the values </li> </ul>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-13T02:46:22.400", "Id": "242162", "Score": "2", "Tags": [ "c++", "matrix", "vectors", "cuda" ], "Title": "JDS - Cuda implementation" }
242162
<p>I have some code that boots up a minecraft server, more complicated then most. I'm looking for some positive criticism on how to improve my code (and coding practice!).</p> <p><strong>File:</strong></p> <pre><code>::Copyright notice ::RandomWords.py ::By Dylan Prins :: ::This work is licensed under CC BY 4.0. ::To view a copy of this license, visit ::https://creativecommons.org/licenses/by/4.0 ::bootstrap :bootstrap @echo off title %sver% %sname% SETLOCAL EnableDelayedExpansion if exist "runfig.conf" set "fig=True" if NOT exist "runfig.conf" set "fig=False" echo MConsole Beta echo. echo Config loaded? if %fig% == True goto confLoad echo %fig% ping 0 &gt;nul goto question ::Load the stuffs :confLoad echo %fig% &lt; runfig.conf ( set /p fname= set /p name= set /p mem= set /p sname= set /p sver= ) echo. echo %fname% echo %name% echo %mem% echo %sname% echo %sver% echo. title %sver% %sname% ping 0 &gt;nul ::main menu :question cls echo %sver% %sname% Main Menu echo Type 'help' for help and type 'settings' for the settings menu echo. set /p "option=&gt;" if %option% == boot goto boot if %option% == bootnorm goto quesbootnorm if %option% == help set "menu=main" &amp;&amp; goto help if %option% == settings goto settings if %option% == vars goto vars if %option% == refresh cls &amp;&amp; goto bootstrap if %option% == exit exit goto question ::boot modded :boot cls echo. echo Booting... echo. java -Xmx%mem%G -Xms%mem%G -jar %fname%.jar nogui ping 0 &gt;nul pause goto question ::Ask if booting the vanilla server is what they want :quesbootnorm cls echo. echo WARNING: Booting a modded server in vanilla mode can corrupt the world! echo. set /p "option=Continue? (y/n)" if %option% == y goto bootnorm if %option% == Y goto bootnorm if %option% == N goto question if %option% == n goto question echo. echo Invalid choice (y/n) echo. pause goto quesbootnorm :: Boot vanilla server :bootnorm cls echo. echo You have been warned! echo Booting... echo. java -Xmx%mem%G -Xms500M -jar %name%.jar nogui ping 0 &gt;nul pause goto question ::set the name of the forge file :fnameset cls echo What do you want to set the name of the forge file to (without the .jar) echo It is currently "%fname%" echo. set /p "fname=&gt;" echo. echo Name set to "%fname%" echo Don't forget to run saveconf if you wish to save these changes! echo. pause goto settings ::set the name of the vanilla boot file :nameset cls echo What do you want to set the name of the regular file to (without the .jar) echo It is currently "%name%" echo. set /p "name=&gt;" echo. echo Name set to "%name%" echo Don't forget to run saveconf if you wish to save these changes! echo. pause goto settings ::save current name(s) to file :saveconf cls echo Do you wish to save these files into config file for later? echo. echo (Forge server name) - %fname% echo (Vanilla server name) - %name% echo (Memory) - %mem%GB echo (Server name) - %sname% echo (Server version) - %sver% echo. set /p "option=Continue? (y/n)" if %option% == y goto dosaveconf if %option% == Y goto dosaveconf if %option% == N goto settings if %option% == n goto settings echo. echo Invalid choice (y/n) echo. pause goto saveconf ::actually save the config :dosaveconf echo. echo %fname%&gt;runfig.conf &amp;&amp; echo Saving "%fname%" to file... echo %name%&gt;&gt;runfig.conf &amp;&amp; echo Saving "%name%" to file... echo %mem%&gt;&gt;runfig.conf &amp;&amp; echo Saving "%mem%" to file... echo %sname%&gt;&gt;runfig.conf &amp;&amp; echo Saving "%sname%" to file... echo %sver%&gt;&gt;runfig.conf &amp;&amp; echo Saving "%sver%" to file... echo. echo Save complete! pause goto settings ::set the memory cap :memory cls echo The current memory cap is "%mem%GB" echo What would you like to change it to? (without the 'GB' just the number) set /p "mem=&gt;" echo. echo Memory cap changed to "%mem%GB" echo Don't forget to run saveconf if you wish to save these changes! echo. pause goto settings ::Variables list :vars echo. echo %mem%GB echo %fname%.jar echo %name%.jar echo %sname% echo %sver% echo. pause goto question ::self explanitory :help cls echo. echo Help menu echo. echo Main echo. echo boot - Reboot modded server echo bootnorm - Reboot normal server echo help - Show this list echo exit - Exit echo. echo Settings echo. echo memory - Set the max memory cap echo setforgename - Set the name of the forge server file echo setname - Set the name of the normal server file echo saveconf - Save the current name(s) to a conf file echo sname - Set the server name echo sver - Set the server version echo. echo Debug (main) echo. echo vars - List all current loaded variables echo refresh - Start the console again from bootstrap echo. pause if %menu% == main goto question if %menu% == set goto settings echo. echo Error code 1; value "menu" is "%menu%" echo. pause goto question ::Set server name :sname cls echo The current server name is "%sname%" echo What would you like to change it to? set /p "sname=&gt;" echo. echo Server name changed to "%sname%" echo Don't forget to run saveconf if you wish to save these changes! echo. pause goto settings ::Set server version :sver cls echo The current server version is "%sver%" echo What would you like to change it to? set /p "sver=&gt;" echo. echo Server version changed to "%sver%" echo Don't forget to run saveconf if you wish to save these changes! echo. pause goto settings :settings cls echo %sver% %sname% Settings Menu echo Type 'help' for help echo. set /p "option=&gt;" if %option% == setforgename goto fnameset if %option% == setname goto nameset if %option% == saveconf goto saveconf if %option% == memory goto memory if %option% == help set goto help if %option% == sname goto sname if %option% == sver goto sver if %option% == help set "menu=set" &amp;&amp; goto help if %option% == exit goto question goto settings <span class="math-container">```</span> </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-15T22:48:29.167", "Id": "475619", "Score": "0", "body": "i am working on the script, can you make a flowchart (just a simple one)? `GOTO` is a mess..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-16T00:43:53.710", "Id": "475628", "Score": "0", "body": "Alright, working on a flowchart now" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-16T00:47:13.817", "Id": "475629", "Score": "0", "body": "in my answer i'm currently working on, i mostly use `CALL`, but sometimes `GOTO` is necessary." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-16T01:22:23.037", "Id": "475631", "Score": "0", "body": "Hey, while scrolling through my code i just released in the :settings menu 'help' is listed twice. That's a mistake, and you can probably delete the one that's listed which does not change the 'menu' variable." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-16T01:38:03.913", "Id": "475632", "Score": "0", "body": "https://app.lucidchart.com/invitations/accept/f065b40b-5cae-4e59-8a18-5269f2f0f55a\nThis looks like it covers everything, PNG link: https://i.imgur.com/a/akZOhpD.png incase you dont want to make a lucidchart account" } ]
[ { "body": "<p>I completely omitted the <code>:HELP</code> section by adding description to labels</p>\n\n<pre><code>:label - Description here\n</code></pre>\n\n<p>and <a href=\"https://ss64.com/nt/findstr.html\" rel=\"nofollow noreferrer\"><code>FINDSTR</code></a> to search the script for descriptions.</p>\n\n<pre><code>@echo off\nSETLOCAL EnableDelayedExpansion EnableExtensions\n\n\nREM Define variables\n=:: User-defined\nset \"conf=runfig.conf\"\nset \"#MAIN=boot bootnorm settings\" MAIN section\nset \"#SETTINGS=memory setforgename setname saveconf sname sver\" SETTINGS section\nset \"#DEBUG=vars refresh help exit\" DEBUG section\n=:: Initalized\n(set LF=^\n%=-----DO NOT REMOVE THIS LINE. Expands to nothing.-----=%\n)\nset ^\"NL=^^^%LF%%LF%^%LF%%LF%^^\" Escaped LF gets ignored, next LF always escaped\n\n\n====:BOOTSTRAP\ncls\ntitle %sver% %sname%\n\nif EXIST \"%conf%\" (set \"fig=True\") ELSE set \"fig=false\"\necho MConsole Beta\necho Config loaded? %fig%\n\nif \"%fig%\" == \"True\" goto :confLoad\n&gt;nul ping 127.1\ngoto :MENU\n\n\n====:CONFLOAD - Load the stuffs\necho %fig%\n&lt;\"%conf%\" (FOR %%V in (fname name mem sname sver) do (\n set/p\"%%V=\"\n echo(!%%V!\n))\ntitle %sver% %sname%\n&gt;nul ping 127.1\n\n\n====:MENU - main menu\ncls\necho %sver% %sname% Main Menu\necho Type 'help' for help and type 'settings' for the settings menu\n\nset \"option=\"\nset/p\"option=&gt;\"\n\ncls\n=:: EXIT, a special case all by itself\nif \"!option!\" == \"exit\" exit /b\nFOR %%O in (%#MAIN% %#DEBUG%) do if \"!option!\" == \"%%O\" call :%%O\n\ngoto :MENU\n\n\n:::::::::::::::::::::::::::::::::::::::::::::::::\n::::MAIN\n:boot - boot modded\necho Booting...\n\njava -Xmx%mem%G -Xms%mem%G -jar %fname%.jar nogui\n&gt;nul ping 127.1\n\npause &gt;nul&amp;exit /b\n\n\n:bootnorm - Boot vanilla server\necho WARNING: Booting a modded server in vanilla mode can corrupt the world!\n\nCHOICE /C yn /M \"Continue?\"\nif ERRORLEVEL 2 goto :MENU\n\necho You have been warned!\necho Booting...\n\njava -Xmx%mem%G -Xms500M -jar %name%.jar nogui\n&gt;nul ping 127.1\n\npause &gt;nul&amp;exit /b\n\n\n:settings\ncls\necho %sver% %sname% Settings Menu\necho Type 'help' for help\n\nset \"option=\"\nset/p\"option=&gt;\"\n\ncls\nif \"!option!\" == \"exit\" goto :MENU\nFOR %%O in (%#SETTINGS% %#DEBUG%) do if \"!option!\" == \"%%O\" call :%%O\n\ngoto :settings\n\n\n:\n::::SETTINGS\n:memory - set the memory cap\necho The current memory cap is \"%mem%GB\"\necho What would you like to change it to? (without the 'GB' just the number)\nset/p\"mem=&gt;\"\necho Memory cap changed to \"%mem%GB\"\necho Don't forget to run saveconf if you wish to save these changes!\npause &gt;nul\ngoto :settings\n\n\n:setforgename - set the name of the forge file\necho What do you want to set the name of the forge file to (without the .jar)\necho It is currently \"%fname%\"\n\nset/p\"fname=&gt;\"\necho Name set to \"%fname%\"\necho Don't forget to run saveconf if you wish to save these changes!\n\npause &gt;nul&amp;exit /b\n\n\n:setname - set the name of the vanilla boot file\necho What do you want to set the name of the regular file to (without the .jar)\necho It is currently \"%name%\"\n\nset/p\"name=&gt;\"\necho Name set to \"%name%\"\necho Don't forget to run saveconf if you wish to save these changes!\n\npause &gt;nul&amp;exit /b\n\n\n:saveconf - save current name(s) to file\n=:: Prompt for user\necho Do you wish to save these files into config file for later?%NL%\n\n(Forge server name) - %fname%%NL%\n(Vanilla server name) - %name%%NL%\n(Memory) - %mem%GB%NL%\n(Server name) - %sname%%NL%\n(Server version) - %sver%\n\nCHOICE /C yn /M \"Continue?\"\nif %ERRORLEVEL% NEQ 1 goto :settings\n\n=:: Really save the config\n&gt;\"%conf%\" (FOR %%V in (fname name mem sname sver) do (\necho(!%%V!\n&gt;&amp;3 echo Saving \"%fname%\" to file...\n))\necho Save complete!\n\npause &gt;nul&amp;exit /b\n\n\n:sname - Set server name\n:sver - Set server version\nset \"var=%0\"\nset \"var=!var:~1!\"\n\necho The current server name is \"!%var%!\"\necho What would you like to change it to?\nset/p\"%var%=&gt;\"\necho Server name changed to \"!%var%!\"\necho Don't forget to run saveconf if you wish to save these changes!\n\npause &gt;nul&amp;exit /b\n\n\n\n:\n::::DEBUG\n:vars - Variables list\necho %mem%GB%NL%\n %fname%.jar%NL%\n %name%.jar%NL%\n %sname%%NL%\n %sver%\n\npause &gt;nul&amp;exit /b\n\n\n:refresh - Start the console again from bootstrap\ngoto :BOOTSTRAP\n\n\n:help - Show this list\necho Help menu\nfindstr /R \"^:\" \"%~f0\"\n\npause &gt;nul&amp;cls&amp;exit /b\n\n\n:exit - Exit\nexit /b\n</code></pre>\n\n<hr>\n\n<p>Rules:</p>\n\n<h1>1. <strong><a href=\"https://www.youtube.com/watch?v=WWJTsKaJT_g\" rel=\"nofollow noreferrer\">NEVER</a> trust user input.</strong> Use <code>!DELAYED EXPANSION!</code></h1>\n\n<ol start=\"2\">\n<li>Use <code>CALL</code> instead of <code>GOTO</code></li>\n<li>Use <code>FOR</code> loops to shorten repetitive commands</li>\n<li>Use <code>CHOICE</code> instead of <code>SET /P</code></li>\n<li><p>When you want to <code>ECHO</code> a multi-line string, the <em>\"normal\"</em> way to do it is:</p>\n\n<pre><code>echo foo\necho bar\necho foobar\n</code></pre>\n\n<p>but it can be very slow, depending on how many <code>ECHO</code>s there are.<br>\nA faster and more readable way is to create a <a href=\"https://stackoverflow.com/a/4455750/12861751\">line continuation character</a> yourself (<code>\\n</code> + <code>^</code>):</p>\n\n<pre><code>(set LF=^\n%=-----DO NOT REMOVE THIS LINE. Expands to nothing.-----=%\n)\nset ^\"NL=^^^%LF%%LF%^%LF%%LF%^^\"\necho foo%NL%\nbar%NL%\nfoobar\n</code></pre></li>\n<li><p><strong>Always</strong> use full paths (use <a href=\"https://www.dostips.com/forum/viewtopic.php?t=6137\" rel=\"nofollow noreferrer\">variables</a> like <code>%__CD__%</code>/<code>%__APPDIR__%</code>), <em>not</em> relative paths for external commands, but i didn't do it here</p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-16T16:06:18.643", "Id": "475707", "Score": "0", "body": "I don't really know the proper etiquette on what to do once you've gotten a code review, but tysm!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-16T06:21:13.500", "Id": "242381", "ParentId": "242168", "Score": "2" } } ]
{ "AcceptedAnswerId": "242381", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-13T06:04:17.550", "Id": "242168", "Score": "2", "Tags": [ "batch" ], "Title": "Batch code that boots up minecraft servers" }
242168
<p>I'm currently in a programming competition where time is key, therefore I'm trying to optimize my solution as much as possible. I am trying to implement a BFS Flood Fill solution on a map size of 30x30 (900 operations) where the time limit is 1 second. I'm falling a bit short on time (a little bit above 1 second). I changed all my lists into a deque (for speed) and I changed my 1D list into a 2D list for faster indexing. I'm trying to calculate the distance for each node to every other node so that I can just look it up later on.</p> <p>What else can I try to get a bit of speed?</p> <p>Here is my BFS Function:</p> <pre><code>def BFS5(grid, start): visited = deque([]) for _ in range(height): visited.append(deque([-1]*width)) queue = deque([start]) _x, _y = start.x, start.y visited[_y][_x] = 0 distance = 1 while queue: current_point = queue.popleft() if grid[current_point.y][current_point.x] == -1: continue adjacent_points = current_point.get_adjacents(grid) for point in adjacent_points: if grid[point.y][point.x] == -1: continue if visited[point.y][point.x] &gt;= 0: continue _x, _y = point.x, point.y visited[_y][_x] = distance queue.append(point) distance += 1 return visited </code></pre> <p>Grid example:</p> <pre><code>[ [-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, 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, -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, 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, 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, -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, 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, 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, -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, -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, 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, 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, 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, -1, -1] ] </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-13T06:51:28.820", "Id": "475255", "Score": "0", "body": "can you include an example grid?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-13T07:04:46.307", "Id": "475257", "Score": "0", "body": "@MaartenFabré added to original question" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-13T06:16:06.587", "Id": "242169", "Score": "1", "Tags": [ "python", "python-3.x", "pathfinding" ], "Title": "Python3 BFS Flood Fill with Deque and 2D Indexing" }
242169
<p>I have been learning about refactoring and I have this method that I'm wondering if I should split into two for code cleanness. First, the method as one, next the method split in two:</p> <p>Method not split:</p> <pre><code>public static ArrayList&lt;String&gt; getFilePathOrName(String pathOrName) { ArrayList&lt;String&gt; files = new ArrayList&lt;&gt;(); File folder = new File("C:\\Users\\damar\\OneDrive\\Documenten\\FolderTest\\Folderretouren\\Niet verdeeld"); File[] listOfFiles = folder.listFiles(); if(pathOrName.equalsIgnoreCase("path")) { for (File file : listOfFiles) { if (file.isFile()) { files.add(file.toString()); } } } else if(pathOrName.equalsIgnoreCase("name")) { for (File file : listOfFiles) { if (file.isFile()) { files.add(file.getName()); } } } return files; } </code></pre> <p>Method split:</p> <pre><code>public static ArrayList&lt;String&gt; getAllUndistributedFilesNames() { ArrayList&lt;String&gt; files = new ArrayList&lt;&gt;(); File folder = new File("C:\\Users\\damar\\OneDrive\\Documenten\\FolderTest\\Folderretouren\\Niet verdeeld"); File[] listOfFiles = folder.listFiles(); for (File file : listOfFiles) { if (file.isFile()) { files.add(file.getName()); } } return files; } public static ArrayList&lt;String&gt; getAllUndistributedFilesPaths() { ArrayList&lt;String&gt; files = new ArrayList&lt;&gt;(); File folder = new File("C:\\Users\\damar\\OneDrive\\Documenten\\FolderTest\\Folderretouren\\Niet verdeeld"); File[] listOfFiles = folder.listFiles(); for (File file : listOfFiles) { if (file.isFile()) { files.add(file.toString()); } } return files; } </code></pre> <p>I feel like the method names when they are split is more intuitive. However, I'm not sure if that is enough justification to have this much duplicate code.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-13T09:17:59.017", "Id": "475268", "Score": "1", "body": "The current question title of your question is too generic to be helpful. Please edit to the site standard, which is for the title to simply **state the task accomplished by the code**. Please see [**How do I ask a good question?**](https://CodeReview.StackExchange.com/help/how-to-ask)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-13T10:56:58.397", "Id": "475294", "Score": "0", "body": "There is another alternative: create methods to use with [`java.nio.file.Files.walk()/walkTree()`](https://docs.oracle.com/en/java/javase/13/docs/api/java.base/java/nio/file/Files.html#walk(java.nio.file.Path,int,java.nio.file.FileVisitOption...))." } ]
[ { "body": "<p>When we refactor the aim is to reduce code duplication. but you introduced even more duplication.</p>\n\n<p>The way to go is to look out for code that is <em>similar</em> and make it <em>the same</em>.</p>\n\n<p>When looking at your original method the duplication is in the <code>if/else</code> cascade. This means you should deal with that. The obvious differences are: </p>\n\n<ul>\n<li>the string literal used</li>\n<li>the <code>else</code> before the second <code>if</code></li>\n<li>the method called at the object <code>file</code></li>\n</ul>\n\n<p>Lets convert that in thee steps:</p>\n\n<ol>\n<li><p>the <code>else</code> is not needed for business reasons. It is introduced for <em>performance optimization</em>. You can safely remove this else and <em>verify by measurement</em> it that has really an impact. My guess is it does not. so lets let rid of it:</p>\n\n<pre><code>if(pathOrName.equalsIgnoreCase(\"path\")) {\n for (File file : listOfFiles) {\n if (file.isFile()) {\n files.add(file.toString());\n }\n }\n}\nif(pathOrName.equalsIgnoreCase(\"name\")) {\n for (File file : listOfFiles) {\n if (file.isFile()) {\n files.add(file.getName());\n }\n }\n}\n</code></pre></li>\n<li><p>now you can extract the first literal string into a variable:</p>\n\n<pre><code>String requestedPathName = \"path\";\nif(pathOrName.equalsIgnoreCase(requestedPathName)) {\n for (File file : listOfFiles) {\n if (file.isFile()) {\n files.add(file.toString());\n }\n }\n}\nif(pathOrName.equalsIgnoreCase(\"name\")) {\n // ...\n</code></pre>\n\n<p>Then, after the first <code>if</code> block we can resuse this variable:</p>\n\n<pre><code>String requestedPathName = \"path\";\nif(pathOrName.equalsIgnoreCase(requestedPathName)) {\n for (File file : listOfFiles) {\n if (file.isFile()) {\n files.add(file.toString());\n }\n }\n}\nrequestedPathName = \"name\";\nif(pathOrName.equalsIgnoreCase(requestedPathName)) {\n // ...\n</code></pre></li>\n<li><p>The last change requires to use an <em>interface</em>. This interface should declare a method that takes a file object as a parameter and returns a <code>String</code> object. One option is to define such interface yourself:</p>\n\n<pre><code>@FunctionalInterface\ninterface FileToStringConverter{\n String convert(File file);\n}\n</code></pre>\n\n<p>Or we use the <code>Function</code> interface provides by the <a href=\"https://docs.oracle.com/javase/8/docs/api/java/util/function/Function.html\" rel=\"nofollow noreferrer\">Java standard Lib</a>. I choose the latter.</p>\n\n<p>The principle is the same as with the string literal before:</p>\n\n<p>replace the original code with the interface usage:</p>\n\n<pre><code>if(pathOrName.equalsIgnoreCase(requestedPathName)) {\n for (File file : listOfFiles) {\n if (file.isFile()) {\n files.add(new Function&lt;File,String&gt;(){ \n @Override public String apply(File t){\n t.toString();\n }\n }.apply(file));\n }\n }\n}\n</code></pre>\n\n<p>extract the interface implementation to a local variable:</p>\n\n<pre><code>// interface implemented as Lambda and method reference.\nFunction&lt;File,String&gt; converter = File::toString; // interface implemented as Lambda and method reference.\n if(pathOrName.equalsIgnoreCase(requestedPathName)) {\n for (File file : listOfFiles) {\n if (file.isFile()) {\n files.add(converter.apply(file)); \n }\n }\n}\n</code></pre>\n\n<p>repeat this in the other `if block:</p>\n\n<pre><code>String requestedPathName = \"path\";\nFunction&lt;File,String&gt; converter = File::toString;\n if(pathOrName.equalsIgnoreCase(requestedPathName)) {\n for (File file : listOfFiles) {\n if (file.isFile()) {\n files.add(converter.apply(file));\n }\n }\n}\nrequestedPathName = \"name\";\nconverter = File::getName;\nif(pathOrName.equalsIgnoreCase(requestedPathName)) {\n for (File file : listOfFiles) {\n if (file.isFile()) {\n files.add(converter.apply(file));\n }\n }\n}\n</code></pre></li>\n</ol>\n\n<p>Now both <code>if</code> blocks look exactly the same. You can select one of them and apply your IDEs <em>extract method</em> automated refactoring feature:</p>\n\n<pre><code>public static ArrayList&lt;String&gt; getFilePathOrName(String pathOrName) {\n ArrayList&lt;String&gt; files = new ArrayList&lt;&gt;();\n File folder = new File(\"C:\\\\Users\\\\damar\\\\OneDrive\\\\Documenten\\\\FolderTest\\\\Folderretouren\\\\Niet verdeeld\");\n File[] listOfFiles = folder.listFiles();\n\n String requestedPathName = \"path\";\n Function&lt;File,String&gt; converter = File::getName;\n // of cause you should choose a better name for the method!\n extracted(requestedPathName, pathOrName, converter, listOfFiles, files); \n requestedPathName = \"name\";\n converter = File::getName;\n extracted(requestedPathName, pathOrName, converter, listOfFiles, files);\n\n return files;\n}\n\nprivate void extracted(\n String requestedPathName, \n String pathOrName, \n Function&lt;File,String&gt; converter,\n File[] listOfFiles, \n List&lt;File&gt; files) { \n if(pathOrName.equalsIgnoreCase(requestedPathName)) {\n for (File file : listOfFiles) {\n if (file.isFile()) {\n files.add(converter.apply(file));\n }\n }\n }\n}\n</code></pre>\n\n<p>last step is inlineing the variables:</p>\n\n<pre><code> extracted(\"path\", pathOrName, File::toString, listOfFiles, files);\n extracted(\"name\", pathOrName, File::getName, listOfFiles, files);\n</code></pre>\n\n<p>The complete result (with a better name for the extracted method) is:</p>\n\n<pre><code>public static ArrayList&lt;String&gt; getFilePathOrName(String pathOrName) {\n ArrayList&lt;String&gt; files = new ArrayList&lt;&gt;();\n File folder = new File(\"C:\\\\Users\\\\damar\\\\OneDrive\\\\Documenten\\\\FolderTest\\\\Folderretouren\\\\Niet verdeeld\");\n File[] listOfFiles = folder.listFiles();\n\n addPathOrNameToList(\"path\", pathOrName, File::toString, listOfFiles, files);\n addPathOrNameToList(\"name\", pathOrName, File::getName, listOfFiles, files); \n\n return files;\n}\n\nprivate void addPathOrNameToList(\n String requestedPathName, \n String pathOrName, \n Function&lt;File,String&gt; fileToStringConversion,\n File[] listOfFiles, \n List&lt;File&gt; files) { \n if(pathOrName.equalsIgnoreCase(requestedPathName)) {\n for (File file : listOfFiles) {\n if (file.isFile()) {\n files.add(fileToStringConversion.apply(file));\n }\n }\n }\n}\n</code></pre>\n\n<hr>\n\n<p>We could turn the repeated method call into a loop if we would introduce another <em>interface</em> or an <em>enum</em> to encapsulate the differing data. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-13T20:14:51.930", "Id": "475358", "Score": "0", "body": "Thank you for your elaborate response! If I understand correctly, you are first creating a new method to get rid of the duplicate if-statement, and then creating a new method to get rid of the double for-statement. What I am wondering - and please bear in mind I am very much a beginner programmer - is how this refactoring makes the code more readable and efficient, which I thought are main functions of refactoring, since to me this seems a lot more complex to understand than my initials code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-14T09:42:30.127", "Id": "475411", "Score": "0", "body": "@Dmrenger *\"since to me this seems a lot more complex to understand than my initials code.\"* **---** Well, Then come back in 3 month... Your (original) solution does look more \"readable\" **to you right now** because it is *your baby*. You have thought about it a lot and it was the best solution you came up with. Any other solution is harder to understand because you need to make an effort to understand it while you already understood our own. In three month you will have forgotten about the details of your solution and so lost the context making it \"easier\" to understand..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-14T11:48:47.623", "Id": "475419", "Score": "0", "body": "Good point, I suppose that is true. Your code definitely makes it look a lot cleaner, so I will try to apply to those steps to more part of my code! Thanks again." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-13T07:07:33.617", "Id": "242172", "ParentId": "242170", "Score": "3" } }, { "body": "<p>The only difference is the line that converts File objects to Strings. You should refactor the two methods into one method that accepts a Function and just pass it a lambda that performs the desired operation.</p>\n\n<p>Also, <code>File.toString()</code> is definitely not what you want to call here. <code>File.getPath()</code> is probably the correct method.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-13T07:51:23.767", "Id": "242175", "ParentId": "242170", "Score": "1" } }, { "body": "<p>Some remarks from my end:</p>\n\n<ul>\n<li>Folderpath should be a constant, because its easy to change if you use it multiple and it makes it more readable</li>\n<li>FunctionArguments should be removed and instead create two methods with meaningful name, which do only one thing, like you did in your first refactoring :)</li>\n<li>declare Interface instead of Classes especially by List, because then the caller can also use different implementations from List</li>\n<li>if you use at least java 8 then you could use streams to handle simple straight forward things like filtering Lists or arrays </li>\n</ul>\n\n<p>I would change it to this without any adding more complexicity to the main concern of your code.</p>\n\n<pre><code>private static final String FOLDER_PATH = \"C:\\\\Users\\\\damar\\\\OneDrive\\\\Documenten\\\\FolderTest\\\\Folderretouren\\\\Niet verdeeld\";\n\npublic static List&lt;String&gt; getFilePaths(String path) {\n\n File folder = new File(FOLDER_PATH);\n File[] listOfFiles = folder.listFiles();\n\n return Arrays.stream(listOfFiles)\n .filter(file -&gt; file != null &amp;&amp; file.isFile())\n .map(file -&gt; file.toString())\n .collect(Collectors.toList());\n}\n\npublic static List&lt;String&gt; getFileNames(String fileName) {\n\n File folder = new File(FOLDER_PATH);\n File[] listOfFiles = folder.listFiles();\n\n return Arrays.stream(listOfFiles)\n .filter(file -&gt; file != null &amp;&amp; file.isFile())\n .map(file -&gt; file.getName())\n .collect(Collectors.toList());\n\n}\n</code></pre>\n\n<p>I hope this will help you :)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-14T11:58:40.877", "Id": "475422", "Score": "0", "body": "Thanks for your feedback! Good point about making the folder path a constant and using List instead of ArrayList. And thanks for confirming I was at least headed in the right direction. Question: your code looks functionally the same as mine. In what way exactly is it better? Could you elaborate for example why using streams are better than what I did? I use Java 8 :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-15T05:38:23.880", "Id": "475525", "Score": "0", "body": "I just gave remarks regarding Code quality and not about functionality :) So on my end i think its more readable and maintainable. Regarding streams, i think if you just iterate through list with filtering and edititng value, then streams are more expressive and readable, but if you make complex things on elements that needs more then one operation for e.g. map() or filter(), i wouldn't use streams, because i dont like to debug them" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-14T06:27:19.033", "Id": "242242", "ParentId": "242170", "Score": "2" } }, { "body": "<p>I'm agree with @TorbenPutkonen's <a href=\"https://codereview.stackexchange.com/a/242175/203649\">answer</a> that you can refactor your code using <a href=\"https://docs.oracle.com/javase/8/docs/api/java/util/function/Function.html\" rel=\"nofollow noreferrer\">Function</a>.</p>\n\n<p>From your code:</p>\n\n<pre><code>ArrayList&lt;String&gt; files = new ArrayList&lt;&gt;();\nif(pathOrName.equalsIgnoreCase(\"path\")) { //adding strings to your list calling method toString }\nelse if(pathOrName.equalsIgnoreCase(\"name\")) { //adding strings to your list calling method getName } }\nreturn files;\n</code></pre>\n\n<p>Basically in your code you will return an empty list or if your String <code>pathOrName</code> is case insensitive equals to <code>\"path\"</code> or <code>\"name\"</code> you will return a new list of Strings using method <code>toString</code> or method <code>getName</code>.</p>\n\n<p>You can create a <code>Map&lt;String, Function&lt;File, String&gt;&gt;</code> in this way:</p>\n\n<pre><code>Map&lt;String, Function&lt;File, String&gt;&gt; map = new HashMap&lt;&gt;();\nmap.put(\"path\", (file) -&gt; file.toString());\nmap.put(\"name\", (file) -&gt; file.getName());\n</code></pre>\n\n<p>Then you can return the new List created like below:</p>\n\n<pre><code>String lowercase = pathOrName.toLowerCase();\nif (!map.containsKey(lowercase)) { return Collections.emptyList(); }\nreturn Arrays.stream(listOfFiles)\n .filter(File::isFile)\n .map(file -&gt; map.get(lowercase).apply(file))\n .collect(Collectors.toList());\n</code></pre>\n\n<p>The full code of the method is below:</p>\n\n<pre><code>public static List&lt;String&gt; getFilePathOrName(String pathOrName) {\n File folder = new File(\"C:\\\\Users\\\\damar\\\\OneDrive\\\\Documenten\\\\FolderTest\\\\Folderretouren\\\\Niet verdeeld\");\n File[] listOfFiles = folder.listFiles(); \n Map&lt;String, Function&lt;File, String&gt;&gt; map = new HashMap&lt;&gt;();\n map.put(\"path\", (file) -&gt; file.toString());\n map.put(\"name\", (file) -&gt; file.getName());\n\n String lowercase = pathOrName.toLowerCase();\n if (!map.containsKey(lowercase)) { return Collections.emptyList(); }\n return Arrays.stream(listOfFiles)\n .filter(File::isFile)\n .map(file -&gt; map.get(lowercase).apply(file))\n .collect(Collectors.toList());\n }\n</code></pre>\n\n<p>You could add a new parameter in your method passing the path of your file folder instead of instantiating it inside your method.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-14T10:13:43.870", "Id": "242260", "ParentId": "242170", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-13T06:35:38.130", "Id": "242170", "Score": "0", "Tags": [ "java", "comparative-review" ], "Title": "Java method refactoring: getting the file name or path" }
242170
<p>I did the <a href="https://www.hackerrank.com/challenges/divisible-sum-pairs/problem" rel="nofollow noreferrer">Divisible Sum Pairs problem on HackerRank</a> </p> <blockquote> <p>input: <em>n</em> is length of array <em>ar</em>, <em>k</em> is an integer value.<br> a pair is define only if <em>ar</em>[<em>i</em>]+<em>ar</em>[<em>j</em>] is dividable by <em>k</em> where <em>i</em> &lt; <em>j</em>.<br> Problem: find and return pairs in array. </p> </blockquote> <pre><code>def divisibleSumPairs(n, k, ar): i=0 #pointer 1 j=1 #pointer 2 is faster than p1 count =0 #pointer 3 will only increment 1 once j = n-1 (second last element) pairs=0 while count &lt; n-1: if (ar[i]+ar[j])%k==0: pairs+=1 j+=1 count+=1 if count==n-1: i+=1 j=i+1 count =i print(pairs) </code></pre> <p>Code visualized</p> <pre><code>step 1: i j [a][b][c][e][f] compare (i,j) i j [a][b][c][e][f] compare (i,j) i j [a][b][c][e][f] compare (i,j) i j [a][b][c][e][f] compare (i,j) i+=1 j=i+1 step2 i j [a][b][c][e][f] compare (i,j) . . . . step n i j [a][b][c][e][f] compare (i,j) finish </code></pre> <p>I have a couple of questions:</p> <ol> <li>Does this algorithm have a name?</li> <li>Is there other way (maybe better, faster)?</li> <li>Is there some code I could have done better/ differently?</li> </ol> <p><code>#some test data n=6 , k=3 ar =[1, 3, 2, 6, 1, 2]</code> </p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-13T10:13:32.933", "Id": "475284", "Score": "0", "body": "Welcome to CodeReview. Did you check the discussions on HackerRank for this challenge? There is a decent solution posted there with explanation. You can find it [here](https://www.hackerrank.com/challenges/divisible-sum-pairs/forum/comments/152302)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-13T10:43:35.317", "Id": "475292", "Score": "0", "body": "Thanks @impopularGuy. I did. However, the top voted code, written by usinha02, is stated to be O(n) time complexity. I don't understand how this can be when the code is using nested for loops? Shouldn't it then be O(n^2) time complexity? I guess it has something to do with the way the array is split into buckets of k i%k where i= 0,1,..k divide and conquer -ish?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-13T10:52:01.147", "Id": "475293", "Score": "0", "body": "I agree that the one I linked is not O(n) but is rather O(nk). However have a look at an [explanation](https://www.hackerrank.com/challenges/divisible-sum-pairs/forum/comments/153278) and the [python implementation](https://www.hackerrank.com/challenges/divisible-sum-pairs/forum/comments/242851)" } ]
[ { "body": "<p>Your code is not Pythonic as it does not adhere to the standard Python style guide.</p>\n\n<ol>\n<li><code>divisibleSumPairs</code> should be snake case <code>divisible_sum_pairs</code>.</li>\n<li>You should have one space both sides of most operators. <code>i=0</code> <code>i+=1</code>, <code>ar[i]+ar[j]</code> are all harder to read than they need to be.</li>\n<li>Most of your variable names don't describe what they contain.</li>\n<li>You <code>print</code> inside a function that should <code>return</code>.</li>\n</ol>\n\n<pre class=\"lang-py prettyprint-override\"><code>def divisible_sum_pairs(length, divisor, items):\n i = 0 #pointer 1\n j = 1 #pointer 2 is faster than p1\n count = 0 #pointer 3 will only increment 1 once j = n-1 (second last element)\n pairs = 0\n while count &lt; length - 1:\n if (items[i] + items[j]) % divisor == 0: \n pairs += 1\n j += 1\n count += 1\n if count == length - 1:\n i += 1\n j = i + 1\n count = i\n return pairs\n</code></pre>\n\n<ol start=\"5\">\n<li><p>You don't need pointer 3 as <code>count = j + 1</code>:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>j += 1\ncount += 1\n</code></pre>\n\n<pre class=\"lang-py prettyprint-override\"><code>j = i + 1\ncount = i\n</code></pre>\n\n<p>We can just replace <code>count</code> with <code>j - 1</code>.</p></li>\n<li><p>We can simplify all of the places where <code>count</code> was being used.\nThis is as you have <code>- 1</code>s on both sides of the operators.</p></li>\n<li><p>Rather than <code>while j &lt; length</code> it would be clearer if you instead used <code>while i &lt; length - 1</code>.\nThis comes in two parts:</p>\n\n<ul>\n<li>It is confusing to see <code>while j &lt; length</code> with <code>if j == length</code> in the body.</li>\n<li>You're not actually bound by <code>j</code> you're bound by <code>i</code>.</li>\n</ul></li>\n<li><p>Rather than using a <code>while</code> loop we can see that there's an opportunity to use two for loops to make things easier to read.</p>\n\n<p><strong>Note</strong>: These for loops have the exact same time complexity as your <code>while</code>.</p></li>\n</ol>\n\n<pre class=\"lang-py prettyprint-override\"><code>def divisible_sum_pairs(length, divisor, items):\n pairs = 0\n for i in range(length - 1):\n for j in range(i + 1, length):\n if (items[i] + items[j]) % divisor == 0: \n pairs += 1\n return pairs\n</code></pre>\n\n<ol start=\"9\">\n<li><p>We can simplify the code by using using a comprehension.</p>\n\n<p>For example we can extract getting the combinations of items.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>combinations = (\n (items[i], items[j])\n for i in range(length - 1)\n for j in range(i + 1, length)\n)\nfor a, b in combinations:\n if (a + b) % divisor == 0:\n</code></pre></li>\n<li><p>We can instead <code>sum</code> with a comprehension that generates numbers.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>pairs = sum(\n 1\n for a, b in combinations\n if (a + b) % divisor == 0\n)\n</code></pre></li>\n<li><p>We can exploit the fact that bools are integers and move the if's expression as the comprehension's expression.</p></li>\n<li>We can use <a href=\"https://docs.python.org/3/library/itertools.html#itertools.combinations\" rel=\"nofollow noreferrer\"><code>itertools.combinations</code></a> to remove the need to manually get the combinations.</li>\n</ol>\n\n<pre class=\"lang-py prettyprint-override\"><code>import itertools\n\n\ndef divisible_sum_pairs(_, divisor, items):\n return sum(\n (a + b) % divisor == 0\n for a, b in itertools.combinations(items, 2)\n )\n</code></pre>\n\n<p>Every change has been a 1 to 1 replacement. The time complexity is still <span class=\"math-container\">\\$O(\\binom{n}{2})\\$</span> (<span class=\"math-container\">\\$O(n^2)\\$</span>) and memory complexity is still <span class=\"math-container\">\\$O(1)\\$</span>.</p>\n\n<p>However now readability is much better.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-13T14:55:52.397", "Id": "475334", "Score": "0", "body": "nice answer. Only remark I have is that instead of the `for i in range(length - 1)` in the intermediate solution, I would introduce `enumerate` here." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-13T15:06:09.540", "Id": "475336", "Score": "0", "body": "@MaartenFabré I had thought of using `enumerate` but getting all bar the last value with it is not really that clean." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-13T11:40:41.867", "Id": "242191", "ParentId": "242176", "Score": "1" } } ]
{ "AcceptedAnswerId": "242191", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-13T08:00:10.667", "Id": "242176", "Score": "0", "Tags": [ "python", "algorithm", "python-3.x" ], "Title": "Algorithm Divisible Sum Pairs" }
242176
<p>I'm writing a small game and I use Kotlin for that. I want to model my buildings with the following class:</p> <pre class="lang-java prettyprint-override"><code>class Building ( val name: String, val inputs: Array&lt;Resource&gt;, val outputs: Array&lt;Resource&gt; ) {} </code></pre> <p>I want to create multiple instances of this class for the map but I don't want to fill the constructor parameters every time with the same data for the same building. So my idea was to make the constructor private and write creator functions in the companion object. </p> <pre class="lang-java prettyprint-override"><code>class Building private constructor( val name: String, val inputs: Array&lt;Resource&gt;, val outputs: Array&lt;Resource&gt; ) { companion object { fun createWoodcutter(): Building = Building( "Woodcutter", arrayOf( Resource(ResourceType.WOOD, 1), Resource(ResourceType.WORKFORCE, 3), Resource(ResourceType.MONEY, 10) ), arrayOf(Resource(ResourceType.PLANKS, 1)) ) } } </code></pre> <p>But I don't know if this strategy counts as clean code or is there a better way or design pattern for this?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-13T09:07:49.133", "Id": "475265", "Score": "0", "body": "For the record, when/if this game is available to play, I would love to try it out." } ]
[ { "body": "<p>First of all, I would recommend using a <code>data class</code>. In order to do this, it's better to use <code>List</code> rather than <code>Array</code> (because Array does not support hashCode/equals)</p>\n\n<pre><code>data class Building (\n val name: String,\n val inputs: List&lt;Resource&gt;,\n val outputs: List&lt;Resource&gt;\n)\n</code></pre>\n\n<p>Actually, considering that the order of elements doesn't matter you could use <code>Set</code> or any iterable data structure as well, but my experience is that <code>List</code> is usually the fastest to iterate through.</p>\n\n<p>As for using the companion object, that's entirely possible and will be similar to static factory methods, but I like to go beyond that and have a completely separate factory class for this. The reasoning being that I don't want to tightly couple my <code>Building</code> with the actual data, what if I would like to have two entirely different games in the future that both use the <code>Building</code> ? What if I would like to let the user design their own buildings? Either way, I see many reasons to use a separate factory class/object than use the companion object.</p>\n\n<p>In Kotlin it is as easy as defining an <code>object BuildingFactory</code>.</p>\n\n<pre><code>object BuildingFactory {\n fun woodcutter(): Building = Building(\n \"Woodcutter\",\n listOf(\n Resource(ResourceType.WOOD, 1),\n Resource(ResourceType.WORKFORCE, 3),\n Resource(ResourceType.MONEY, 10)\n ),\n listOf(Resource(ResourceType.PLANKS, 1))\n )\n}\n</code></pre>\n\n<p>Then you can create instances as easy as <code>BuildingFactory.woodcutter()</code></p>\n\n<p>Another approach could be to have a configuration data file specifying the buildings available and reading from that file. Then construct a building based on a name.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-13T09:06:33.567", "Id": "242182", "ParentId": "242177", "Score": "1" } }, { "body": "<p>As addition to @Simon Frosbergs answer, I would create an interface for the factory:</p>\n\n<pre><code>interface BuildingFactory{\n fun build(...) : Building\n}\n</code></pre>\n\n<p>For the param you can choose for enums or Strings:</p>\n\n<pre><code>enum class BuildingType{\n Woodcutter\n}\n</code></pre>\n\n<p>The enums are typesafe and the Strings are not.<br>\nThe drawback for enums is that every time you add a BuildingType, you change the enum.<br>\nTherefor every module depending on that enum has to change as well.<br>\n(If you're not using multiple modules, this problem can be ignored)</p>\n\n<p>Also, note that your companion object can implement an interface.<br>\nTherefor you can bind the static functions to one factory implementation:</p>\n\n<pre><code>object DefaultBuildingFactory : BuildingFactory{\n override fun build(type : BuildingType): Building = when(type){\n BuildingType.WoodCutter -&gt; Building(\n \"Woodcutter\",\n listOf(\n Resource(ResourceType.WOOD, 1),\n Resource(ResourceType.WORKFORCE, 3),\n Resource(ResourceType.MONEY, 10)\n ),\n listOf(Resource(ResourceType.PLANKS, 1))\n )\n }\n}\n\nclass Building private constructor(\n val name: String,\n val inputs: Array&lt;Resource&gt;,\n val outputs: Array&lt;Resource&gt;\n) {\n companion object : BuildingFactory{\n override fun build(type : BuildingType) = DefaultBuildingFactory.build(type)\n }\n}\n</code></pre>\n\n<p>Here you delegate the interface to DefaultBuildingFactory.<br>\nin kotlin <a href=\"https://kotlinlang.org/docs/reference/delegation.html#overriding-a-member-of-an-interface-implemented-by-delegation\" rel=\"nofollow noreferrer\">interface delegation</a> is build in:</p>\n\n<pre><code>class Building private constructor(\n val name: String,\n val inputs: Array&lt;Resource&gt;,\n val outputs: Array&lt;Resource&gt;\n) {\n companion object : BuildingFactory by DefaultBuildingFactory\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-14T09:57:04.600", "Id": "242257", "ParentId": "242177", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-13T08:01:31.413", "Id": "242177", "Score": "1", "Tags": [ "game", "design-patterns", "kotlin", "file-structure" ], "Title": "Building a Building - Is the building clean?" }
242177
<p>I'm simply using <strong>Slim PHP MVC framework</strong> in my <strong>API</strong> project. <strong>PDO::FETCH_ASSOC</strong> is used in the database calls. So no data objects. The router handles requests and pass to the controller. controller calls the necessary model to do database operations and response is delivered.</p> <p>This is the scenario that I want to handle different user types. Each user_type has user_type based specific db transaction to be done. I want to make this more reusable and remove code duplication.</p> <p>Sorry if there's any wrong thing here, and for my English.</p> <p><strong>My Route</strong></p> <pre><code>$this-&gt;post('/users/preferences', \UserPreferenceController::class . ':store') </code></pre> <p><strong>UserPreferenceController => Controller</strong></p> <pre><code>public function store($request, $response, $args){ $parsedBody = $request-&gt;getParsedBody(); $user_id = $parsedBody['user_id']; $preferences = $parsedBody['preferences']; $user = $this-&gt;User-&gt;getUserInfo($user_id); if ($user["type_id"] == 'Admin') { $preferenceAdded = $this-&gt;User-&gt;AddAdminUserPreferences($user_id, $preferences); // DB transaction operation } else if ($user["type_id"] == 'Customer') { $preferenceAdded = $this-&gt;User-&gt;AddCustomerUserPreferences($user_id, $preferences); // DB transaction Operation } else if ($user["type_id"] == 'Sales') { $preferenceAdded = $this-&gt;User-&gt;AddSalesUserPreferences($user_id, $preferences); // DB transaction Operation } // return if the transaction is rollbacked if(!$preferenceAdded){ return $response-&gt;withJSON([ "error" =&gt; true, "message" =&gt; "cannot add preferences for user" "data" =&gt; $user_id ]); } if ($user["type_id"] == 'Admin') { $staisticsAdded = $this-&gt;User-&gt;AddAdminUserPreferencesStatistics($user_id, $preferences); // DB transaction operation } else { $staisticsAdded = $this-&gt;User-&gt;AddOtherUserPreferencesStatistics($user_id, $preferences); // DB transaction operation } // return if the transaction is rollbacked if(!$staisticsAdded ){ return $response-&gt;withJSON([ "error" =&gt; true, "message" =&gt; "cannot add statistics for user" "data" =&gt; $user_id ]); } return $response-&gt;withJSON([ "error" =&gt; false, "message" =&gt; "operation completed successfully" "data" =&gt; null ]); } </code></pre> <p><strong>User.php => User model</strong></p> <pre><code>public function getUserInfo($user_id) { $sql = "SELECT id, name, email, type_id FROM users WHERE id= :id"; $stmt = $this-&gt;db-&gt;prepare($sql); $result = $stmt-&gt;execute(['id' =&gt; $user_id]); return $stmt-&gt;fetch()[0]; } public function AddAdminUserPreferences($user_id, $preferences) { $this-&gt;db-&gt;beginTransaction(); try { // $sql1 execute (common function for every user_type) // rollback if $sql1 fails // $sql2 execute (a user_type specific function) // rollback if $sql2 fails $this-&gt;db-&gt;commit(); return true; } catch(\PDOException $e){ $this-&gt;db-&gt;rollBack(); return false; } } </code></pre> <p><strong>My Container</strong></p> <pre><code>$container = $app-&gt;getContainer(); $container['UserPreferenceController'] = function ($c) { return new App\Controllers\UserPreferenceController($c); }; $container['User'] = function ($c) { return new App\Models\User($c); }; </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-13T09:17:35.817", "Id": "475267", "Score": "0", "body": "The current question title of your question is too generic to be helpful. Please edit to the site standard, which is for the title to simply **state the task accomplished by the code**. Please see [**How do I ask a good question?**](https://CodeReview.StackExchange.com/help/how-to-ask)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-13T09:19:03.540", "Id": "475269", "Score": "0", "body": "How different Add Preferences functions' code differ? Can't you just have a single function AddUserPreferences?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-13T09:25:56.327", "Id": "475274", "Score": "0", "body": "@YourCommonSense.. the Add Preferences function have a common function which insert data into the same table and also a user specific function which inserts to a user specific table" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-13T10:58:11.110", "Id": "475295", "Score": "0", "body": "A question. Shouldn't setting preferences and statistics be wrapped in a *common* transaction? Would it make sense to have preferences set but statistics not?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-13T11:05:59.193", "Id": "475296", "Score": "0", "body": "@YourCommonSense I didn't fully get your question. If you ask whether the setting preferences and statistics can be wrapped in same function, yes it can be. I wrote 2 functions to separate the logic" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-13T11:13:09.317", "Id": "475302", "Score": "0", "body": "I am asking whether setting preferences and statistics can be wrapped in same *transaction*? These two operations seem to be related and I am wondering why they arent in the same transaction" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-13T11:19:17.363", "Id": "475305", "Score": "1", "body": "@YourCommonSense it can be. But some future user types (future requirement) may not want set statistics function." } ]
[ { "body": "<p>I'll start by listing some notes on the code itself and then I'll suggest a new architecture that I think will help improve the 'maintainability' of the code.</p>\n\n<ol>\n<li><p>As <a href=\"https://codereview.stackexchange.com/questions/242179/php-how-can-i-refactor-this-store-function-which-handles-different-database-o/242188#comment475269_242179\">@YourCommonSense said</a>, the AddPreferences methods should be only one method that will take the user_id and preference_id and add it to the database, and this will be it's sole purpose. Also what if you got new roles? What if you got new preferences? You will have to add new functions for each one of these, the best way is to go abstract and generalize the thing, later on when you add new preferences, the method doesn't care, it just takes the user_id and the preference_id.</p></li>\n<li><p>Throw Exceptions, and let the controller handle them, and then return exceptions with error codes. Don't return that <code>error</code> flag, <code>message</code>. So for example let's say you wanted to add a a preference to a user that already exists, this should throw an exception from the AddPreferences method, the Controller will handle the exception and then return a response with <code>status_code = 400 // for example, maybe you want another code to represent that</code> and the exception message that was thrown, this way you can handle things better in the front end and debug with ease.</p></li>\n<li><p>Why not move the database logic to a separate generic class and use it, maybe you can create a class that you can extend and give it the table_name, and this way it can control all database operations specific to that table, just like ORM models, you can search for ActiveRecord or Eloquent to learn more.</p></li>\n<li><p>Don't catch Exceptions in low layers unless you have another option to use of their fail, otherwise just throw them and let them bubble. For example, int the <code>AddAdminUserPreferences</code>, you caught the exception and returned false, okay, but how should I know what has gone wrong? How should the user know? What will happen next?</p></li>\n</ol>\n\n<p>So for the Architecture, Please search MVC, there is plenty of resources out there, and after that, there is there repository pattern which will do a really good job in separating the concerns, leaving the database layer away from business logic.</p>\n\n<p>As a side note, I'd suggest you look at 'lumen', it a pretty REST framework, very easy to use and has a wide range of things, including a smart Service Container and Discovery, so you wont need to bind (almost)anything, it also has a really good ORM and Query builder.</p>\n\n<p>EDIT: Example on the 2nd Point.</p>\n\n<p>instead of</p>\n\n<pre><code>// return if the transaction is rollbacked\n if(!$preferenceAdded){\n return $response-&gt;withJSON([\n \"error\" =&gt; true, \n \"message\" =&gt; \"cannot add preferences for user\"\n \"data\" =&gt; $user_id\n ]);\n }\n</code></pre>\n\n<p>You can do this</p>\n\n<pre><code>// return if the transaction is rollbacked\n if(!$preferenceAdded){\n return $response-&gt;withJSON([\n \"message\" =&gt; \"cannot add preferences for user\"\n ])-&gt;statusCode(400); // BAD_REQUEST, and I'm not sure if this is how to set a statusCode, sorry.\n }\n</code></pre>\n\n<p>Now you are in the browser and sent your request, the old way is you will check whether the <code>error</code> flag is true or false, and act based on that, and you will repeat that check in every call to the api, and the method of sending an error flag itself is not a reliable(and i don't like it, not beautiful :) ).</p>\n\n<p>but if you return a <code>status_code = 400 // or anything other than success codes</code>, this will throw exception in the request you made from the browser, say you're using fetch.</p>\n\n<pre><code>fetch('www.example.com').then(response =&gt; response.json()).catch(e =&gt; {\n // Do something with the exception\n})\n</code></pre>\n\n<p>Instead of</p>\n\n<pre><code>fetch('www.example.com').then(response =&gt; {\n response = response.json()\n if(response.error) {\n // Do something with the error\n } else {\n // Do something with the response\n }\n}).catch(e =&gt; {\n // Do something with the exception\n})\n</code></pre>\n\n<p>See How you separated the response logic from the code logic?.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-13T12:12:36.500", "Id": "475311", "Score": "0", "body": "hi @mahmoud, Thanks for the great answer. I didn't actually get the 2nd point. Could you be able to give me an example for that." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-13T12:21:58.810", "Id": "475312", "Score": "0", "body": "Hi @camille I've updted my answer with an example, please see if you have any questions." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-13T12:29:53.657", "Id": "475315", "Score": "0", "body": "When a database fails, it's rather a server error (500), not a request error (400)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-13T12:31:56.033", "Id": "475316", "Score": "0", "body": "Well, there might be any Kind of errors, notice `// or anything other than success codes`, you can return what ever you want, just not a success code such as 200 or 201" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-13T10:40:53.073", "Id": "242188", "ParentId": "242179", "Score": "1" } }, { "body": "<p>I think it's a very good case to employ OOP, namely polymorphism and inheritance.</p>\n\n<p>First, we've got to create a dedicated class to handle the user preferences.</p>\n\n<p>A common ancestor to hold all the common code</p>\n\n<pre><code>abstract class UserPreferences\n{\n protected $userId;\n protected $db;\n\n public function __construct($userId, $db) {\n $this-&gt;userId = $userId;\n $this-&gt;db = $db;\n }\n protected function addGeneric($preferences) {\n $sql = \"INSERT INTO preferences (...) VALUES (?,?,?)\";\n $this-&gt;db-&gt;prepare($sql)-&gt;execute($preferences);\n } \n\n abstract protected function addSpecific($preferences);\n\n public function add($preferences)\n {\n $this-&gt;db-&gt;beginTransaction();\n\n try {\n $this-&gt;addGeneric($preferences);\n $this-&gt;addSpecific($preferences);\n $this-&gt;db-&gt;commit();\n } catch(Throwable $e){\n $this-&gt;db-&gt;rollBack();\n throw $e;\n }\n }\n}\n</code></pre>\n\n<p>and then implementations for different types</p>\n\n<pre><code>class AdminPreferences extends UserPreferences \n{\n protected function addSpecific($preferences) {\n $sql = \"INSERT INTO admin_preferences (...) VALUES (?,?,?)\";\n $this-&gt;db-&gt;prepare($sql)-&gt;execute($preferences);\n }\n} \n\nclass SalesPreferences extends UserPreferences \n{\n protected function addSpecific($preferences) {\n $sql = \"INSERT INTO sales_preferences (...) VALUES (?,?,?)\";\n $this-&gt;db-&gt;prepare($sql)-&gt;execute($preferences);\n }\n} \n</code></pre>\n\n<p>...and so on.</p>\n\n<p>Then in the User class create an instance of the Preferences class</p>\n\n<pre><code>class User \n{\n public $preferences;\n public function __construct($db, $type) {\n $this-&gt;userId = $userId;\n $this-&gt;db = $db;\n $this-&gt;preferences = $this-&gt;setPreferences($db, $type);\n }\n protected function setPreferences($db, $type) {\n switch($type) {\n case 'Admin':\n $this-&gt;preferences = new AdminPreferences($db);\n break;\n case 'Sales':\n $this-&gt;preferences = new SalesPreferences($db);\n break;\n }\n }\n}\n</code></pre>\n\n<p>the same goes for the statistics</p>\n\n<p>and finally in your controller simply </p>\n\n<pre><code>$preferences = $parsedBody['preferences'];\n$this-&gt;User-&gt;preferences-&gt;add($preferences);\n$this-&gt;User-&gt;preferencesStatistics-&gt;add($preferences);\n\nreturn $response-&gt;withJSON([\n \"error\" =&gt; false, \n \"message\" =&gt; \"operation completed successfully\"\n \"data\" =&gt; null\n]);\n</code></pre>\n\n<p>Note that checking $preferenceAdded manually is <strong>not the way to go</strong>. There should be a <a href=\"https://phpdelusions.net/articles/error_reporting\" rel=\"nofollow noreferrer\">dedicated error handler</a> to do the job. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-13T12:11:05.710", "Id": "475309", "Score": "0", "body": "hi @your-common-sense thanks for the answer. Seems like I have lot of refactoring to do. My User model class consists only with database functions and not any attributes. Also I have several controllers functions (in other controllers) which needs to handle those specific user types. Do you have any tip for handling those user types in App Level?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-13T12:26:22.300", "Id": "475314", "Score": "1", "body": "You asked for it :) The main idea of this refactoring is to reduce the reprtitions. The \"common function for every user_type\" is written only once and then reused. Also the final calling code in the controller is also greatly reduced. As ot the other controllers, it's just the same way as in this controller. Add new public methods to Preferences classes and call these methods." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-13T12:35:33.750", "Id": "475317", "Score": "0", "body": "One final question, Is it okay to write functions with MySQL queries inside User class?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-13T13:00:21.270", "Id": "475318", "Score": "1", "body": "It's entirely up to you. There are two competing approaches, ActiveRecord(AR) where it's OK to have the database interaction in the User class, and DataMapper(DM) where a satellite class is used, UserMapper to hold all the database operations for the User class." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-13T10:43:56.127", "Id": "242189", "ParentId": "242179", "Score": "2" } } ]
{ "AcceptedAnswerId": "242189", "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-13T08:42:14.880", "Id": "242179", "Score": "1", "Tags": [ "beginner", "php", "mvc", "slim" ], "Title": "PHP - How can I refactor this store function (which handles different database operation for user types) in order to reduce duplication?" }
242179
<p>LeetCode Problems <strong>3. Longest substring without repeating characters</strong></p> <blockquote> <p>Given a string, find the length of the <strong>longest substring</strong> without repeating characters.</p> <p>Examples:</p> <blockquote> <p>Given "abcabcbb", the answer is "abc", length 3. </p> <p>Given "bbbbb", the answer is "b", length 1.</p> <p>Given "pwwkew", the answer is "wke", length 3. Note that the answer must be a substring, "pwke" is a subsequence and not a substring.</p> </blockquote> </blockquote> <p>I did the question in ReasonML. However, I use a lot of <code>if</code> statement, it is an inappropriate coding style in function programming. Please feel free to comment, how to modify the source as functional programming oriented e.g. type-driven development, pattern matching, etc.</p> <pre><code> let explode = s =&gt; List.init(String.length(s), String.get(s)); module LongestSubstringWithoutRepeatingCharacters: { let longestSubstringWithoutRepeatingCharacters: string =&gt; int; let run: unit =&gt; unit; } = { let longestSubstringWithoutRepeatingCharacters = l1 =&gt; { let ll = explode(l1); let myQueue = Queue.create(); let rec aux = (queue, x: char, xs: list(char), ceil: int, counter: int) =&gt; { switch (xs) { | [] =&gt; ceil | [h, ...t] =&gt; if (Queue.is_empty(queue) === false) { if (h != x) { if (h != Queue.top(queue)) { Queue.push(h, queue); aux( queue, h, t, ceil &gt; counter ? ceil : ceil + 1, counter + 1, ); } else { let _c = Queue.pop(queue); aux(queue, h, t, ceil, counter - 1); }; } else { Queue.clear(queue); aux(queue, '@', [h, ...t], ceil, 0); }; } else { Queue.push(h, queue); aux(queue, h, t, ceil &gt; counter ? ceil : ceil + 1, counter + 1); } }; }; aux(myQueue, '@', ll, 0, 0); }; let run = () =&gt; { Printf.printf( "longestSubstringWithoutRepeatingCharacters : %d\n", longestSubstringWithoutRepeatingCharacters("abcabcbb"), ); }; }; </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-13T08:43:18.413", "Id": "242180", "Score": "2", "Tags": [ "haskell", "functional-programming", "ocaml" ], "Title": "Longest Substring Without Repeating Characters in ReasonML/Ocaml" }
242180
<p>I have following code but wonder if I can loop it instead of copy-pasting.</p> <p><strong>calculator.ts</strong></p> <pre><code>data: function() { return { calcInput: 'user types some value in input with v-model' } }, template: ` &lt;span class="calc-button-control" @click="evaluate()" @keyup.enter="evaluate()" &gt;calc&lt;/span&gt; &lt;span class="calc-button-control" @click="calcInput = calcInput.substring(0, calcInput.length - 1) " @keyup.del="calcInput = calcInput.substring(0, calcInput.length - 1) " &gt;del&lt;/span&gt; &lt;span class="calc-button-control" @click="calcInput = ''" @keyup.esc="calcInput = ''" &gt;clr&lt;/span&gt; ` </code></pre> <p>Pass modifier to v-on:keyup is the hardest part here.<br> <code>@[loopedItem.key]={loopedItem.method}</code> - doesn't work.<br> In this case I can see in event listeners for example <code>keyup.enter</code> but it doesn't work.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-13T10:11:49.987", "Id": "475282", "Score": "0", "body": "Please state (maybe upfront) whether the code works, and just the coding alternatives listed close to the bottom didn't." } ]
[ { "body": "<p>No.</p>\n\n<p>Or well, maybe you <em>could</em> but I absolutely do not see any reason to do so.</p>\n\n<p>What each <code>&lt;span&gt;</code> has in common:</p>\n\n<ul>\n<li>The same class</li>\n<li>They all have <em>a</em> click event and <em>a</em> keyup event</li>\n</ul>\n\n<p>What each <code>&lt;span&gt;</code> has different:</p>\n\n<ul>\n<li>They all have different handlers for what to do on the click/keyup event</li>\n<li>They all have listen for different keyup events.</li>\n</ul>\n\n<p>I don't see any benefit in creating a loop from this.</p>\n\n<p>Some things you <em>might</em> want to consider though is:</p>\n\n<ul>\n<li>Have a method that is performed for both click and the keyup event, to not copy-paste code between the different handlers.</li>\n<li>Create a component for <code>&lt;span class=\"calc-button-control\"&gt;</code></li>\n</ul>\n\n<p>If you have plenty of more of these <code>&lt;span&gt;</code> elements, creating a component would be the way to go. Then you could have a component to handle the following:</p>\n\n<ul>\n<li>It is a <code>&lt;span&gt;</code> element and applies the <code>calc-button-control</code> class.</li>\n<li>It has a method for what to do when clicked or keyup event triggers.</li>\n</ul>\n\n<p>I am not sure how flexible you can make the <code>keyup</code> listener, I don't think you can for example pass <code>:keypress=\"enter\"</code> or similar to have it listen to <code>@keyup.enter</code> so I am not sure if creating a component for all of this does more harm than good.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-13T11:15:00.300", "Id": "475303", "Score": "0", "body": "Okay, thanks. Image the application, where you type a text from the screen (blind keyboard writing) and there will be a keyboard with all letters like on keyboard. When user types a letter, js have to listen for key press and set some animation class to that key. So I have to hard code it?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-13T10:10:10.943", "Id": "242186", "ParentId": "242181", "Score": "1" } } ]
{ "AcceptedAnswerId": "242186", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-13T09:02:42.000", "Id": "242181", "Score": "1", "Tags": [ "typescript", "vue.js" ], "Title": "Loop Vue2 tag with keyup + modifier and click" }
242181
<p>I am a C++ beginner and am working on a bit of code which calculates the pairwise cosine similarities between vectors. The vectors are TF-IDF vectors and the similarities are used to determine similarity between texts (documents).</p> <p>My code and approach outlined below work as expected, but runs into performance issues when datasets get larger. The number of vectors often runs into the thousands and the vectors can be quite large themselves (thousands of elements).</p> <p>I have done the following to try and optimize the code:</p> <ul> <li>In the nested loop, set <code>j</code> equal to <code>i</code> to only calculate similarities one way, i.e. only return results for one side of the diagonal of the similarity matrix;</li> <li>Passing the vectors as <code>const</code> references to <code>cosine_similarity</code> to avoid the overhead of copying the vectors;</li> <li>Defined <code>v1i</code> and <code>v2i</code> outside of the loop in <code>cosine_similarity</code> to only look them up once inside the loop (as opposed to using <code>v1[i]</code> and <code>v2[i]</code> in the dot product and sum of squares calculations);</li> <li>Check for <code>dot_product == 0</code> in <code>cosine_similarity</code> to avoid <code>magnitude</code> calculation when it is not necessary.</li> </ul> <p>Here's what I have:</p> <pre><code>// Vector containing all the vectors to compare (populated somewhere else) std::vector&lt; std::vector&lt;double&gt; &gt; vector_of_vectors; // Get the number of vectors int number_of_vectors = vector_of_vectors.size(); // Get the size of a vector (all vectors have the same size) int vector_size = vector_of_vectors[0].size(); // Vector to store the results std::vector&lt;double&gt; similarities; // Nested loop for similarity calculation for (int i=0; i&lt;number_of_vectors; ++i) { for (int j=i; j&lt;number_of_vectors; ++j) { if (i == j) { similarities.push_back(1); } else { similarities.push_back(cosine_similarity(vector_of_vectors[i], vector_of_vectors[j], vector_size)); } } } double cosine_similarity(const std::vector&lt;double&gt;&amp; v1, const std::vector&lt;double&gt;&amp; v2, const int&amp; vector_size) { // Cross-vector dot product double dot_product = 0; // Sum of squares of first vector double ss1 = 0; // Sum of squares of second vector double ss2 = 0; double v1i; double v2i; for (int i=0; i&lt;vector_size; ++i) { v1i = v1[i]; v2i = v2[i]; dot_product += (v1i * v2i); ss1 += (v1i * v1i); ss2 += (v2i * v2i); } if (dot_product == 0) { return 0; } else { double magnitude = sqrt(ss1 * ss2); return dot_product / magnitude; } } </code></pre> <p>I'm quite happy about how it works, but have the feeling there are some things I could do to make this much faster. Any ideas?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-13T10:31:43.100", "Id": "475288", "Score": "0", "body": "Welcome to CodeReview@SE. Is there more to say as to what the code presented is to accomplish or how it is used?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-13T10:34:13.420", "Id": "475290", "Score": "0", "body": "Thank you. That's a good addition indeed - the vectors are TF-IDF vectors and are used for determining similarity between texts. Will add this to the question." } ]
[ { "body": "<ul>\n<li><p>Not so much about performance. The cosine similarity can be expressed in a more concise (and maybe even more performant) way with STL:</p>\n\n<pre><code>dot_product = std::inner_product(v1.begin(), v1.end(), v2.begin());\nss1 = std::inner_product(v1.begin(), v1.end(), v1.begin());\nss2 = std::inner_product(v2.begin(), v2.end(), v2.begin());\n</code></pre>\n\n<p>This of course assumes that the vectors are of the same size.</p></li>\n<li><p>Since you want it for every pair of vectors, nothing can be done to speed thins up algorithmically. There are <span class=\"math-container\">\\$O(n^2)\\$</span> pairs, so the performance is bound to be quadratic.</p></li>\n<li><p><code>cosine_similarity</code> works with each vector many times, and recomputes its length (<code>ss1</code>/<code>ss2</code>) many times. Compute them all in advance. It is probably the biggest performance gain you can achieve.</p></li>\n<li><p>There is no need to pass <code>vector_size</code> by reference.</p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-13T20:51:09.760", "Id": "475361", "Score": "0", "body": "Thank you! Tried using `std::inner_product`, but that seems significantly less performant for some reason. Excellent suggestion to precompute all sums of squares - this seems to give me a boost of about 20%!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-13T16:02:34.397", "Id": "242210", "ParentId": "242187", "Score": "0" } } ]
{ "AcceptedAnswerId": "242210", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-13T10:23:03.103", "Id": "242187", "Score": "2", "Tags": [ "c++", "performance", "beginner", "vectors" ], "Title": "Large-scale pairwise similarity calculations of vectors" }
242187
<p>I needed a way to get URL parameters and put them and their values into a query set's <code>.filter()</code> if they exist. After a day of piecing together information from the Interwebs, I have a working solution to my problem. However, is it the best way to do this? I feel it can be improved or streamlined, but my tiny brain is failing me:</p> <p>In <code>utilities.py</code>:</p> <pre><code>def get_filters(url, allowed): query = parse.urlsplit(url).query pack = dict(parse.parse_qsl(query)) translated = {} for pk, pv in pack.items(): for ak, av in allowed.items(): if pk == ak: translated[av] = pv return translated </code></pre> <p>In <code>views.py</code>:</p> <pre><code>from utilities import get_filters people = Person.objects.all() url = request.get_full_path() allowed_filters = { 'location': 'person_location', 'role': 'person_role', } filters = get_filters(url, allowed_filters) if filters: filtered_query = people.filter(**filters) else: filtered_query = people if ('search' in request.GET) and request.GET['search'].strip(): query_string = request.GET['search'] query_search = get_query(query_string, ['person_first_name', 'person_last_name']) query_results = filtered_query.filter(query_search) else: query_results = filtered_query </code></pre> <p>It does everything I need it to: if a URL parameter is in the allowed list, it takes that parameter and value, packs it into a dictionary, and shoves it into <code>filter()</code> to be unpacked by the interpreter.</p> <p>This way whenever I want to add a new filter, I just add it in the allowed list and I don't have to touch anything else. I did it this way so I could use an alias like <code>special_id=3</code> in the URL to target a relationship like <code>person__special__special_id=3</code> without the URL getting cluttered like the Django admin side does.</p> <p>Any suggestions for improving this?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-13T11:09:59.450", "Id": "475299", "Score": "0", "body": "`my tiny brain is failing me` switch to [one of the others](https://en.wikipedia.org/wiki/ARM_big.LITTLE)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-13T19:07:38.200", "Id": "475355", "Score": "0", "body": "Heterogeneous multi-processing (global task scheduling) would be huge benefit, for sure!" } ]
[ { "body": "<p>You can change the first method to</p>\n\n<pre><code>def get_filters(url, allowed):\n query = parse.urlsplit(url).query\n pack = dict(parse.parse_qsl(query))\n translated = {}\n\n for pk, pv in pack.items():\n if pk in allowed:\n translated[allowed[pk]] = pv\n\n return translated\n</code></pre>\n\n<p>Remove this condition, it's useless.</p>\n\n<pre><code>if filters:\n filtered_query = people.filter(**filters)\nelse:\n filtered_query = people\n</code></pre>\n\n<p>and just use </p>\n\n<pre><code>filtered_query = people.filter(**filters)\n</code></pre>\n\n<p>Maybe add <code>search</code> to the allowed filters? and improve the method to handle multiple values for a specific key.</p>\n\n<pre><code>allowed_filters = {\n 'location': 'person_location',\n 'role': 'person_role',\n 'search': ['person_first_name', 'person_last_name']\n}\n\n<span class=\"math-container\">```</span>\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-13T11:51:54.657", "Id": "242193", "ParentId": "242190", "Score": "0" } } ]
{ "AcceptedAnswerId": "242193", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-13T10:58:57.230", "Id": "242190", "Score": "1", "Tags": [ "python", "django" ], "Title": "Am I dynamic filtering correctly in Django?" }
242190
<p>This is pretty straightforward, it takes requests from the frontend, checking if it is present on the request, if it does, an action is taken for that if statement.</p> <p>I wonder if there is a way to remove some if statements or make it less complicated.</p> <pre><code>private function applyFiltering($query, $request) { if ($request-&gt;has('active_group')) { $query-&gt;whereNotIn('status_id', [1, 6, 4]); $query-&gt;whereHas('userStatus', function ($query) use ($request) { $query-&gt;where('user_id', $request-&gt;user()-&gt;id)-&gt;whereNotIn('status_id', [1, 6, 4]); }); } if ($request-&gt;has('waiting_group')) { $query-&gt;whereNotIn('status_id', [1, 6]); $query-&gt;whereHas('userStatus', function ($query) use ($request) { $query-&gt;where('user_id', $request-&gt;user()-&gt;id)-&gt;whereNotIn('status_id', [1, 6])-&gt;where('status_id',4); }); } if ($request-&gt;has('meeting_group')) { $query-&gt;where('type_id', 2); } if ($request-&gt;has('comp_meeting_group')) { $query-&gt;where('type_id', 4); } if ($request-&gt;has('completed_group')) { $query-&gt;whereHas('userStatus', function ($query) use ($request) { $query-&gt;where('user_id', $request-&gt;user()-&gt;id)-&gt;where('status_id', 1); }); } if ($request-&gt;has('canceled_group')) { $query-&gt;whereHas('userStatus', function ($query) use ($request) { $query-&gt;where('user_id', $request-&gt;user()-&gt;id)-&gt;where('status_id', 6); }); } if ($request-&gt;has('shift_group')) { $query-&gt;where('status_id', 1)-&gt;where('type_id', 6); } if ($request-&gt;has('announce_group')) { $query-&gt;where('type_id', 3); } if ($request-&gt;has('task_id')) { $query-&gt;where('id', 'like', '%' . $request-&gt;input('task_id') . '%'); } if ($request-&gt;has('task_statuses')) { $statuses = $request-&gt;input('task_statuses'); $query-&gt;whereIn('status_id', $statuses); } if ($request-&gt;has('task_types')) { $statuses = $request-&gt;input('task_types'); $query-&gt;whereIn('type_id', $statuses); } if ($request-&gt;has('task_priorities')) { $statuses = $request-&gt;input('task_priorities'); $query-&gt;whereIn('priority_id', $statuses); } if ($request-&gt;has('task_invite_users')) { $toUsers = $request-&gt;input('task_invite_users'); $query-&gt;whereHas('taskAssignment', function ($query) use ($request, $toUsers) { $query-&gt;whereIn('assigned_to', $toUsers); }); // $query-&gt;whereIn('to_user_id',$statuses); } if ($request-&gt;has('task_users')) { $byUsers = $request-&gt;input('task_users'); $query-&gt;whereHas('taskAssignment', function ($query) use ($request, $byUsers) { $query-&gt;whereIn('assigned_by', $byUsers); }); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-13T13:19:26.897", "Id": "475322", "Score": "0", "body": "Are those sections mutually exclusive or can a request have multiple of those?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-13T13:22:21.300", "Id": "475323", "Score": "0", "body": "@Mast they are exclusive." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-13T13:23:56.460", "Id": "475324", "Score": "1", "body": "Then shouldn't you be using `if...else if` ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-13T14:42:07.307", "Id": "475333", "Score": "0", "body": "@MD.TabishMahfuz At least, with a bit of magic a switch could work too, or a foreach over an array with the supported content." } ]
[ { "body": "<p>You could try something like this:</p>\n\n<pre><code>private function applyFiltering($query, $request)\n{\n\n $query-&gt;when($request-&gt;has('active_group'), function($query) use($request) {\n $query-&gt;whereNotIn('status_id', [1, 6, 4]);\n $query-&gt;whereHas('userStatus', function ($query) use ($request) {\n $query-&gt;where('user_id', $request-&gt;user()-&gt;id)-&gt;whereNotIn('status_id', [1, 6, 4]);\n });\n })-&gt;when($request-&gt;has('waiting_group'), function($query) use ($request) {\n $query-&gt;whereNotIn('status_id', [1, 6]);\n $query-&gt;whereHas('userStatus', function ($query) use ($request) {\n $query-&gt;where('user_id', $request-&gt;user()-&gt;id)-&gt;whereNotIn('status_id', [1, 6])-&gt;where('status_id',4);\n });\n })\n ........\n ........\n ........\n}\n<span class=\"math-container\">```</span>\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-13T22:07:37.037", "Id": "475368", "Score": "0", "body": "While this technically removes the `if` statements, I'm not sure this looks any better than the original." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-17T21:22:03.933", "Id": "479143", "Score": "0", "body": "Any callable should be able to be passed into `Builder::when()` so the filters could be moved to another class / separate private functions." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-13T13:23:08.203", "Id": "242201", "ParentId": "242197", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-13T13:14:32.923", "Id": "242197", "Score": "3", "Tags": [ "php", "laravel" ], "Title": "Filtering multiple request parameters" }
242197
<p>I made a system monitor on Linux which gives you all this information:</p> <p><a href="https://i.stack.imgur.com/Op3qf.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Op3qf.png" alt="enter image description here"></a></p> <p>The full project can be found in my repo: <a href="https://github.com/sandro4912/System-Monitor" rel="nofollow noreferrer">https://github.com/sandro4912/System-Monitor</a></p> <p>In short it works as following:</p> <p>I read the data from various folders in the Linux file system</p> <p>This Data gathering is organized in the classes:</p> <ul> <li><p>Memory -> reads Memory consumption from file and calculates various parts of the memory usage</p></li> <li><p>Processor -> reads Data from the CPU and its Cores. Calculates the utilization for cpu and each core</p></li> <li><p>Process -> Reads data from a process. It just needs the PID.</p></li> <li><p>Parser -> Not a class but some freestanding functions which read addition information like OS name for system</p></li> </ul> <p>I made an abstract base class for these classes so depending of the OS (currently only Linux) the right Memory Process and Processor classes are selected at runtime.</p> <p>The Class System gathers all the data from Memory Process and Processor and presents it to an output with NCurses.</p> <p>I would like to present some classes here for review (all is probably too much).</p> <p>Please let me know.</p> <ul> <li>What do you think about the design?</li> <li>Is the code clean, easy to read?</li> <li>What would you improve?</li> <li>Any bad habits?</li> </ul> <p>Feel free to also look in the other code in the git repo and comment on them aswell.</p> <p>As A side node. I know the code for NCurses is quite messy. I plan to replace it later with QT.</p> <p><strong>system.h</strong></p> <pre><code>#ifndef SYSTEM_H #define SYSTEM_H #include &lt;string&gt; #include &lt;vector&gt; #include &lt;chrono&gt; #include &lt;memory&gt; #include "memory.h" #include "process.h" #include "processor.h" class System { public: System(); std::string Kernel() const; std::string OperatingSystem() const; std::shared_ptr&lt;Processor&gt; Cpu(); std::vector&lt;std::shared_ptr&lt;Process&gt;&gt; Processes(); std::shared_ptr&lt;Memory&gt; MemoryUtilization(); long UpTime() const; int TotalProcesses() const; int RunningProcesses() const; private: std::vector&lt;std::shared_ptr&lt;Process&gt;&gt; updateProcesses(); const std::string mKernel; const std::string mOperatingSystem; std::shared_ptr&lt;Processor&gt; mCpu; std::shared_ptr&lt;Memory&gt; mMemory; std::vector&lt;std::shared_ptr&lt;Process&gt;&gt; mProcesses = {}; std::chrono::time_point&lt;std::chrono::system_clock&gt; mLastCpuTimePoint{}; std::chrono::time_point&lt;std::chrono::system_clock&gt; mLastMemoryTimePoint{}; std::chrono::time_point&lt;std::chrono::system_clock&gt; mLastProcessTimePoint{}; static constexpr auto mMinReadDifferenceInMS = 100; }; #endif </code></pre> <p><strong>system.cpp</strong></p> <pre><code>#include "system.h" #include "parser.h" #include &lt;unistd.h&gt; #include &lt;algorithm&gt; #include &lt;cstddef&gt; #include &lt;set&gt; #include &lt;string&gt; #include &lt;vector&gt; System::System() : mKernel{Parser::Kernel()}, mOperatingSystem{Parser::OperatingSystem()}, mCpu{std::move(Processor::makeProcessor())}, mMemory{Memory::makeMemory()}, mLastCpuTimePoint{std::chrono::system_clock::now()}, mLastMemoryTimePoint{mLastMemoryTimePoint} {} std::string System::Kernel() const { return mKernel; } std::string System::OperatingSystem() const { return mOperatingSystem; } std::shared_ptr&lt;Processor&gt; System::Cpu() { auto newTimePoint = std::chrono::system_clock::now(); auto duration = std::chrono::duration_cast&lt;std::chrono::milliseconds&gt;( newTimePoint - mLastCpuTimePoint); if (duration.count() &gt; mMinReadDifferenceInMS) { mCpu = std::move(Processor::makeProcessor()); mLastCpuTimePoint = newTimePoint; } return mCpu; } std::vector&lt;std::shared_ptr&lt;Process&gt;&gt; System::Processes() { auto newTimePoint = std::chrono::system_clock::now(); auto duration = std::chrono::duration_cast&lt;std::chrono::milliseconds&gt;( newTimePoint - mLastProcessTimePoint); if (duration.count() &gt; mMinReadDifferenceInMS) { mProcesses = updateProcesses(); mLastProcessTimePoint = newTimePoint; } return mProcesses; } // DONE: Return the system's memory utilization std::shared_ptr&lt;Memory&gt; System::MemoryUtilization() { auto newTimePoint = std::chrono::system_clock::now(); auto duration = std::chrono::duration_cast&lt;std::chrono::milliseconds&gt;( newTimePoint - mLastMemoryTimePoint); if (duration.count() &gt; mMinReadDifferenceInMS) { mMemory = std::move(Memory::makeMemory()); mLastMemoryTimePoint = newTimePoint; } return mMemory; } // DONE: Return the number of seconds since the system started running long System::UpTime() const { return Parser::UpTime(); } // DONE: Return the number of processes actively running on the system int System::RunningProcesses() const { return Parser::RunningProcesses(); } // DONE: Return the total number of processes on the system int System::TotalProcesses() const { return Parser::TotalProcesses(); } std::vector&lt;std::shared_ptr&lt;Process&gt;&gt; System::updateProcesses() { auto pids = Parser::Pids(); std::vector&lt;std::shared_ptr&lt;Process&gt;&gt; processes; processes.reserve(pids.size()); for (const auto&amp; pid : pids) { processes.emplace_back(std::move(Process::makeProcess(pid))); } auto comparator = [](const std::shared_ptr&lt;Process&gt;&amp; a, const std::shared_ptr&lt;Process&gt;&amp; b) { return *b &lt; *a; }; std::sort(processes.begin(), processes.end(), comparator); return processes; } </code></pre> <p><strong>memory.h</strong></p> <pre><code>#ifndef MEMORY_H #define MEMORY_H #include &lt;memory&gt; class Memory { public: virtual ~Memory() = default; virtual double TotalUsedMemoryInPercent() const = 0; virtual double CachedMemoryInPercent() const = 0; virtual double NonCacheNonBufferMemoryInPercent() const = 0; virtual double BuffersInPercent() const = 0; virtual double SwapInPercent() const = 0; static std::shared_ptr&lt;Memory&gt; makeMemory(); }; #endif </code></pre> <p><strong>memory.cpp</strong></p> <pre><code>#include "memory" #include "linux/memory.h" std::shared_ptr&lt;Memory&gt; Memory::makeMemory() { #ifdef __linux__ Linux::Memory memory = Linux::Memory::createFromFile(); return std::move(std::make_unique&lt;Linux::Memory&gt;(memory)); #elif _WIN32 #endif } </code></pre> <p><strong>linux/memory.h</strong></p> <pre><code>#ifndef LINUX_MEMORY_H #define LINUX_MEMORY_H #include "../memory.h" #include &lt;iosfwd&gt; namespace Linux { class Memory : public ::Memory { public: Memory() = default; Memory(long memTotal, long memFree, long buffers, long cached, long swapTotal, long swapFree, long shmem, long sReclaimable); ~Memory() = default; double TotalUsedMemoryInPercent() const override; double CachedMemoryInPercent() const override; double NonCacheNonBufferMemoryInPercent() const override; double BuffersInPercent() const override; double SwapInPercent() const override; private: long mTotalMemory = 0; long mSwapTotal = 0; long mTotalUsedMemory = 0; long mCachedMemory = 0; long mNonCacheNonBufferMemory = 0; long mBuffers = 0; long mSwap = 0; public: static Memory createFromFile(); static Memory createFromFile(const std::string&amp; filename); }; std::istream&amp; operator&gt;&gt;(std::istream&amp; is, Memory&amp; obj); } // namespace Linux #endif </code></pre> <p><strong>linux/memory.cpp</strong></p> <pre><code>#include "../linux/memory.h" #include "../helper.h" #include &lt;fstream&gt; #include &lt;iostream&gt; namespace Linux { const std::string kProcDirectory{"/proc/"}; const std::string kMeminfoFilename{"/meminfo"}; Memory::Memory(long memTotal, long memFree, long buffers, long cached, long swapTotal, long swapFree, long shmem, long sReclaimable) : mTotalMemory{memTotal}, mSwapTotal{swapTotal}, mTotalUsedMemory{memTotal - memFree}, mCachedMemory{cached + sReclaimable - shmem}, mNonCacheNonBufferMemory{mTotalUsedMemory - (buffers + mCachedMemory)}, mBuffers{buffers}, mSwap{swapTotal - swapFree} {} double Memory::TotalUsedMemoryInPercent() const { double percent = static_cast&lt;double&gt;(mTotalUsedMemory) / static_cast&lt;double&gt;(mTotalMemory); return percent; } double Memory::NonCacheNonBufferMemoryInPercent() const { double percent = static_cast&lt;double&gt;(mNonCacheNonBufferMemory) / static_cast&lt;double&gt;(mTotalMemory); return percent; } double Memory::BuffersInPercent() const { double percent = static_cast&lt;double&gt;(mBuffers) / static_cast&lt;double&gt;(mTotalMemory); return percent; } double Memory::CachedMemoryInPercent() const { double percent = static_cast&lt;double&gt;(mCachedMemory) / static_cast&lt;double&gt;(mTotalMemory); return percent; } double Memory::SwapInPercent() const { double percent = static_cast&lt;double&gt;(mSwap) / static_cast&lt;double&gt;(mSwapTotal); return percent; } Memory Memory::createFromFile() { return createFromFile(kProcDirectory + kMeminfoFilename); } Memory Memory::createFromFile(const std::string&amp; filename) { Memory memory; std::ifstream ifs{filename}; if (ifs.is_open()) { ifs &gt;&gt; memory; } return memory; } std::istream&amp; operator&gt;&gt;(std::istream&amp; is, Memory&amp; obj) { std::string line; std::getline(is, line); auto memTotalOpt = Helper::ReadValueFromLine&lt;long&gt;(line, "MemTotal:"); if (!memTotalOpt) { is.setstate(std::ios_base::failbit); return is; } std::getline(is, line); auto memFreeOpt = Helper::ReadValueFromLine&lt;long&gt;(line, "MemFree:"); if (!memFreeOpt) { is.setstate(std::ios_base::failbit); return is; } std::getline(is, line); // MemAvailable: std::getline(is, line); auto buffersOpt = Helper::ReadValueFromLine&lt;long&gt;(line, "Buffers:"); if (!buffersOpt) { is.setstate(std::ios_base::failbit); return is; } std::getline(is, line); auto cachedOpt = Helper::ReadValueFromLine&lt;long&gt;(line, "Cached:"); if (!cachedOpt) { is.setstate(std::ios_base::failbit); return is; } for (int i = 0; i &lt; 9; ++i) { std::getline(is, line); } std::getline(is, line); auto swapTotalOpt = Helper::ReadValueFromLine&lt;long&gt;(line, "SwapTotal:"); if (!swapTotalOpt) { is.setstate(std::ios_base::failbit); return is; } std::getline(is, line); auto swapFreeOpt = Helper::ReadValueFromLine&lt;long&gt;(line, "SwapFree:"); if (!swapFreeOpt) { is.setstate(std::ios_base::failbit); return is; } for (int i = 0; i &lt; 4; ++i) { std::getline(is, line); } std::getline(is, line); auto shmemOpt = Helper::ReadValueFromLine&lt;long&gt;(line, "Shmem:"); if (!shmemOpt) { is.setstate(std::ios_base::failbit); return is; } for (int i = 0; i &lt; 2; ++i) { std::getline(is, line); } std::getline(is, line); auto sReclaimableOpt = Helper::ReadValueFromLine&lt;long&gt;(line, "SReclaimable:"); if (!sReclaimableOpt) { is.setstate(std::ios_base::failbit); return is; } obj = std::move(Memory{*memTotalOpt, *memFreeOpt, *buffersOpt, *cachedOpt, *swapTotalOpt, *swapFreeOpt, *shmemOpt, *sReclaimableOpt}); return is; } } // namespace Linux </code></pre> <p><strong>process.h</strong></p> <pre><code>#ifndef PROCESS_H #define PROCESS_H #include &lt;memory&gt; #include &lt;string&gt; class Process { public: virtual int Pid() const = 0; virtual std::string User() const = 0; virtual std::string Command() const = 0; virtual long RamInMb() const = 0; virtual long UpTime() const = 0; virtual double CpuUtilization() const = 0; bool operator&lt;(const Process&amp; a) const; static std::shared_ptr&lt;Process&gt; makeProcess(int pid); }; #endif </code></pre> <p><strong>process.cpp</strong></p> <pre><code>#include "process.h" #include "linux/process.h" bool Process::operator&lt;(const Process&amp; a) const { return CpuUtilization() &lt; a.CpuUtilization(); } std::shared_ptr&lt;Process&gt; Process::makeProcess(int pid) { #ifdef __linux__ Linux::Process process{pid}; return std::move(std::make_unique&lt;Linux::Process&gt;(process)); #elif _WIN32 #endif } </code></pre> <p><strong>linux/process.h</strong></p> <pre><code>#ifndef LINUX_PROCESS_H #define LINUX_PROCESS_H #include "../process.h" #include &lt;string&gt; namespace Linux { class Process : public ::Process { public: Process(int pid); int Pid() const override; std::string User() const override; std::string Command() const override; long RamInMb() const override; long UpTime() const override; double CpuUtilization() const override; private: double calcCpuUtilization(int pid, int upTimeProcess); int mPid; std::string mUser; std::string mCommand; long mRamInMb; long mUpTime; double mCpuUtilization; }; long ReadActiveJiffiesFromFile(int pid); std::string ReadCommandFromFile(int pid); long ReadRamInKbFromFile(int pid); std::string ReadUidFromFile(int pid); std::string ReadUserFromFile(int pid); long ReadUpTimeFromFile(int pid); long ParseProcessUptimeFromLine(const std::string&amp; line); long ClockTicksToSecond(long clockTicks); } // namespace Linux #endif </code></pre> <p><strong>linux/process.cpp</strong></p> <pre><code>#include "../linux/process.h" #include "helper.h" #include "parser.h" #include &lt;unistd.h&gt; #include &lt;algorithm&gt; #include &lt;fstream&gt; #include &lt;sstream&gt; #include &lt;string&gt; namespace Linux { const std::string kProcDirectory{"/proc/"}; const std::string kStatFilename{"/stat"}; const std::string kCmdlineFilename{"/cmdline"}; const std::string kStatusFilename{"/status"}; const std::string kPasswordPath{"/etc/passwd"}; Process::Process(int pid) : mPid{pid}, mUser{ReadUserFromFile(pid)}, mCommand{ReadCommandFromFile(pid)}, mRamInMb{ReadRamInKbFromFile(pid) / 1024}, mUpTime{ReadUpTimeFromFile(pid)}, mCpuUtilization{calcCpuUtilization(pid, mUpTime)} {} int Process::Pid() const { return mPid; } std::string Process::User() const { return mUser; } std::string Process::Command() const { return mCommand; } long Process::RamInMb() const { return mRamInMb; } long Process::UpTime() const { return mUpTime; } double Process::CpuUtilization() const { return mCpuUtilization; } double Process::calcCpuUtilization(int pid, int upTimeProcess) { auto uptime = Parser::UpTime(); long startTime = upTimeProcess; long elapsedTime = uptime - startTime; long totalTime = ClockTicksToSecond(ReadActiveJiffiesFromFile(pid)); if (elapsedTime == 0) { return 0; } return static_cast&lt;double&gt;(totalTime) / static_cast&lt;double&gt;(elapsedTime); } long ReadActiveJiffiesFromFile(int pid) { auto line = Helper::ReadFirstLineFromFile( kProcDirectory + std::to_string(pid) + kStatFilename); if (line.empty()) { return {}; } std::istringstream ist{line}; std::string part; ist &gt;&gt; part; if (!Helper::IsNumber&lt;long&gt;(part)) { return 0; } ist &gt;&gt; part; // no check value type is string char sign; ist &gt;&gt; sign; if (sign != 'S') { return 0; } for (auto i = 0; i &lt; 10; ++i) { ist &gt;&gt; part; if (!Helper::IsNumber&lt;long&gt;(part)) { return 0; } } ist &gt;&gt; part; if (!Helper::IsNumber&lt;long&gt;(part)) { return 0; } auto utime = std::stol(part); ist &gt;&gt; part; if (!Helper::IsNumber&lt;long&gt;(part)) { return 0; } auto stime = std::stol(part); ist &gt;&gt; part; if (!Helper::IsNumber&lt;long&gt;(part)) { return 0; } auto cutime = std::stol(part); ist &gt;&gt; part; if (!Helper::IsNumber&lt;long&gt;(part)) { return 0; } auto cstime = std::stol(part); return utime + stime + cutime + cstime; } std::string ReadCommandFromFile(int pid) { std::ifstream ifs{kProcDirectory + std::to_string(pid) + kCmdlineFilename}; if (ifs.is_open()) { std::string line; std::getline(ifs, line); return line; } return std::string(); } long ReadRamInKbFromFile(int pid) { return Helper::ReadValueFromFile&lt;long&gt;( kProcDirectory + std::to_string(pid) + kStatusFilename, "VmSize:"); } std::string Uid(int pid) { return std::to_string(Helper::ReadValueFromFile&lt;long&gt;( kProcDirectory + std::to_string(pid) + kStatusFilename, "Uid:")); } std::string ReadUserFromFile(int pid) { auto targetUid = Uid(pid); std::ifstream ifs{kPasswordPath}; if (ifs.is_open()) { std::string line; while (std::getline(ifs, line)) { std::replace(line.begin(), line.end(), ':', ' '); std::istringstream ist{line}; std::string user; ist &gt;&gt; user; char fill; ist &gt;&gt; fill; std::string uid; ist &gt;&gt; uid; if (uid == targetUid &amp;&amp; fill == 'x') { return user; } } } return std::string{}; } long ReadUpTimeFromFile(int pid) { auto line = Helper::ReadFirstLineFromFile( kProcDirectory + std::to_string(pid) + kStatFilename); if (line.empty()) { return 0; } return ParseProcessUptimeFromLine(line); } long ParseProcessUptimeFromLine(const std::string&amp; line) { std::istringstream ist{line}; std::string part; ist &gt;&gt; part; if (!Helper::IsNumber&lt;long&gt;(part)) { return 0; } ist &gt;&gt; part; // no check value type is string char sign; ist &gt;&gt; sign; if (sign != 'S') { return 0; } for (auto i = 0; i &lt; 19; ++i) { ist &gt;&gt; part; if (!Helper::IsNumber&lt;long&gt;(part)) { return 0; } } return ClockTicksToSecond(std::stol(part)); } long ClockTicksToSecond(long clockTicks) { return clockTicks / sysconf(_SC_CLK_TCK); } } // namespace Linux </code></pre> <p><strong>processor.h</strong></p> <pre><code>#ifndef PROCESSOR_H #define PROCESSOR_H #include &lt;memory&gt; #include &lt;vector&gt; class Processor { public: virtual ~Processor() = default; virtual double Utilization() const = 0; virtual std::vector&lt;double&gt; CoreUtilizations() const = 0; virtual int CountOfCores() const = 0; static std::shared_ptr&lt;Processor&gt; makeProcessor(); }; #endif </code></pre> <p><strong>processor.cpp</strong></p> <pre><code>#include "processor.h" #include "linux/processor.h" std::shared_ptr&lt;Processor&gt; Processor::makeProcessor() { #ifdef __linux__ Linux::Processor processor = Linux::Processor::createFromFile(); return std::move(std::make_unique&lt;Linux::Processor&gt;(processor)); #elif _WIN32 #endif } </code></pre> <p><strong>linux/processor.h</strong></p> <pre><code>#ifndef LINUX_PROCESSOR_H #define LUNIX_PROCESSOR_H #include "../processor.h" #include "cpu_states.h" #include &lt;iosfwd&gt; #include &lt;optional&gt; namespace Linux { class Processor : public ::Processor { public: Processor() = default; Processor(const CpuStates&amp; firstCpuState, const CpuStates&amp; secondCpuState, const std::vector&lt;CpuStates&gt;&amp; firstCoreStates, const std::vector&lt;CpuStates&gt;&amp; secondCoreStates); ~Processor() = default; double Utilization() const override; std::vector&lt;double&gt; CoreUtilizations() const override; int CountOfCores() const override; private: double calcUtilization(const CpuStates&amp; firstState, const CpuStates&amp; secondState) const; CpuStates mFirstCpuState{}; CpuStates mSecondCpuState{}; std::vector&lt;CpuStates&gt; mFirstCoreStates{}; std::vector&lt;CpuStates&gt; mSecondCoreStates{}; public: static Processor createFromFile(); static Processor createFromFile(const std::string&amp; filename); static std::optional&lt;std::vector&lt;CpuStates&gt;&gt; readFromFile( const std::string&amp; filename); static std::optional&lt;CpuStates&gt; parseCpuState(const std::string line); }; } // namespace Linux #endif </code></pre> <p><strong>linux/processor.cpp</strong></p> <pre><code>#include "../linux/processor.h" #include "cpu_states.h" #include &lt;cassert&gt; #include &lt;fstream&gt; #include &lt;iostream&gt; #include &lt;sstream&gt; #include &lt;thread&gt; namespace Linux { const std::string kProcDirectory{"/proc/"}; const std::string kStatFilename{"/stat"}; Processor::Processor(const CpuStates&amp; firstCpuState, const CpuStates&amp; secondCpuState, const std::vector&lt;CpuStates&gt;&amp; firstCoreStates, const std::vector&lt;CpuStates&gt;&amp; secondCoreStates) : mFirstCpuState{firstCpuState}, mSecondCpuState{secondCpuState}, mFirstCoreStates{firstCoreStates}, mSecondCoreStates{secondCoreStates} { assert(firstCoreStates.size() == secondCoreStates.size()); } double Processor::Utilization() const { return calcUtilization(mFirstCpuState, mSecondCpuState); } std::vector&lt;double&gt; Processor::CoreUtilizations() const { std::vector&lt;double&gt; coreUtilizations; coreUtilizations.reserve(mFirstCoreStates.size()); for (std::size_t i = 0; i &lt; mFirstCoreStates.size(); ++i) { coreUtilizations.emplace_back( calcUtilization(mFirstCoreStates[i], mSecondCoreStates[i])); } return coreUtilizations; } int Processor::CountOfCores() const { return mFirstCoreStates.size(); } double Processor::calcUtilization(const CpuStates&amp; firstState, const CpuStates&amp; secondState) const { double deltaTotalTime = secondState.Jiffies() - firstState.Jiffies(); double deltaActiveTime = secondState.ActiveJiffies() - firstState.ActiveJiffies(); return deltaActiveTime / deltaTotalTime; } Processor Processor::createFromFile() { return createFromFile(kProcDirectory + kStatFilename); } Processor Processor::createFromFile(const std::string&amp; filename) { auto firstStates = readFromFile(filename); if (!firstStates) { return Processor{}; } std::this_thread::sleep_for(std::chrono::milliseconds(100)); auto secondStates = readFromFile(filename); if (!secondStates) { return Processor{}; } auto firstCpuState = firstStates-&gt;front(); auto firstCoreStates = std::vector&lt;CpuStates&gt;{ firstStates.value().begin() + 1, firstStates.value().end()}; auto secondCpuState = secondStates-&gt;front(); auto secondCoreStates = std::vector&lt;CpuStates&gt;{ secondStates.value().begin() + 1, secondStates.value().end()}; return Processor{firstCpuState, secondCpuState, firstCoreStates, secondCoreStates}; } std::optional&lt;std::vector&lt;CpuStates&gt;&gt; Processor::readFromFile( const std::string&amp; filename) { std::ifstream ifs{filename}; if (!ifs.is_open()) { return {}; } std::string line; // Assume there must be also the CPUState std::getline(ifs, line); auto optCpuState = parseCpuState(line); if (!optCpuState) { return {}; } // Assume there must be atleast one CoreState std::getline(ifs, line); auto optCoreState = parseCpuState(line); if (!optCoreState) { return {}; } // optional cores std::vector&lt;CpuStates&gt; states; states.emplace_back(*optCpuState); states.emplace_back(*optCoreState); while (std::getline(ifs, line)) { auto optNextCoreState = parseCpuState(line); if (!optNextCoreState) { break; } states.emplace_back(*optNextCoreState); } return {states}; } std::optional&lt;CpuStates&gt; Processor::parseCpuState(const std::string line) { CpuStates cpuStates; std::istringstream ist{line}; ist &gt;&gt; cpuStates; if (ist.fail()) { return {}; } return {cpuStates}; } } // namespace Linux </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-13T13:18:03.653", "Id": "242198", "Score": "3", "Tags": [ "c++", "linux" ], "Title": "Linux System Monitor" }
242198
<p>So I've attempted this project from <a href="https://hyperskill.org/projects/90/stages/503/implement#solutions" rel="nofollow noreferrer">hyperskills</a> where you're asked to make a calculator script that can calculate annuity and differentiated payments given that 3 of 4 values are known. I think i went with a real hardcoding way of doing this, as such I would like some advice on making my code more compact and efficient.</p> <pre class="lang-py prettyprint-override"><code>import math import sys def convert_month_into_years_months(months): years, months = divmod(months, 12) if years != 1: s_year = "s" else: s_year = "" if months != 1: s_month = "s" else: s_month = "" if not years: return f"You need {months} month{s_month} to repay this credit!" elif not months: return f"You need {years} year{s_year} to repay this credit!" else: return f"You need {years} year{s_year} and {months} month{s_month} to repay this credit!" credit_principal_given = False period_count_given = False credit_interest_given = False monthly_payment_given = False annuity = False diff = False period_count = monthly_payment = credit_principal = credit_interest = 1 command_line = sys.argv number_of_arguments = len(command_line[1:]) type_of_payment = command_line[1] if number_of_arguments != 0 else None run = True if type_of_payment == "--type=diff" and number_of_arguments == 4: diff = True elif type_of_payment == "--type=annuity" and number_of_arguments == 4: annuity = True else: run = False if run: for arg in command_line[2:]: try: if arg[:10] == "--periods=": period_count = int(arg[10:]) period_count_given = True elif arg[:10] == "--payment=" and annuity: monthly_payment = float(arg[10:]) monthly_payment_given = True elif arg[:11] == "--interest=": credit_interest = float(arg[11:]) credit_interest_given = True elif arg[:12] == "--principal=": credit_principal = float(arg[12:]) credit_principal_given = True except: run = False break # Checks if any of the values are negative values = [period_count ,monthly_payment ,credit_principal ,credit_interest] if not all(True if value &gt; 0 else False for value in values): run = False if run: nominal_interest_rate = (credit_interest/100)/12 if annuity: if credit_principal_given and monthly_payment_given and credit_interest_given: period_count = math.ceil(math.log( (monthly_payment/( monthly_payment - ( nominal_interest_rate * credit_principal ) ) ), 1+nominal_interest_rate )) print(convert_month_into_years_months(period_count)) elif monthly_payment_given and period_count_given and credit_interest_given: credit_principal = math.floor(monthly_payment / ( (nominal_interest_rate * (1 + nominal_interest_rate)**period_count )/( (1 + nominal_interest_rate)**period_count - 1) ) ) print(f"Your credit principal = {credit_principal}!") elif credit_principal_given and period_count_given and credit_interest_given: monthly_payment = math.ceil(credit_principal * ( (nominal_interest_rate * (1 + nominal_interest_rate)**period_count )/( (1 + nominal_interest_rate)**period_count - 1) ) ) print(f"Your annuity payment = {monthly_payment}!") elif diff: sum_diff_payments = 0 for month in range(1, period_count+1): diff_payment = (credit_principal/period_count) + (nominal_interest_rate * (credit_principal - ( (credit_principal * (month-1))/period_count ) ) ) diff_payment = math.ceil(diff_payment) sum_diff_payments += diff_payment print(f"Month {month}: paid out {diff_payment}") overpayment = round(abs(credit_principal - (period_count * monthly_payment))) print(f"\nOverpayment = {overpayment}") else: print("Incorrect parameters") </code></pre>
[]
[ { "body": "<p>The one thing that is immediately apparent to me is that parsing of <strong>command line arguments</strong> could be done better using the built-in <a href=\"https://docs.python.org/3/library/argparse.html\" rel=\"nofollow noreferrer\">argparse</a> module but for an intro you can start with the <a href=\"https://docs.python.org/3/howto/argparse.html#id1\" rel=\"nofollow noreferrer\">tutorial</a>.</p>\n\n<p>Here is how the routine could be written, assuming all parameters are mandatory:</p>\n\n<pre><code>import argparse\n\n# check command line options\nparser = argparse.ArgumentParser()\n\nparser.add_argument(\"--type\", dest=\"type_of_payment\", type=str, choices=[\"diff\", \"annuity\"], required=True, help=\"Add some help text here\")\nparser.add_argument(\"--periods\", dest=\"period_count\", type=int, required=True)\nparser.add_argument(\"--payment\", dest=\"monthly_payment\", type=float, required=True)\nparser.add_argument(\"--interest\", dest=\"credit_interest\", type=float, required=True)\nparser.add_argument(\"--principal\", dest=\"credit_principal\", type=float, required=True)\n\nargs = parser.parse_args()\n\n# show the values\nprint(f\"Type of payment: {args.type_of_payment}\")\nprint(f\"Periods: {args.period_count}\")\nprint(f\"Payment: {args.monthly_payment}\")\nprint(f\"Interest: {args.credit_interest}\")\nprint(f\"Principal: {args.credit_principal}\")\n</code></pre>\n\n<p>This is more flexible, because:</p>\n\n<ul>\n<li>you can provide parameters in any order</li>\n<li>you can assign default values</li>\n<li>you can specify the expected type and also restrict to a specific range of values - in this example type_of_payment must be either \"diff\" or \"annuity\"</li>\n<li>you can also define your own function if you require more fine-tuned validation of certain parameters</li>\n<li>you can easily define groups of mutually exclusive parameters</li>\n</ul>\n\n<p>This is an example but you can customize it further. Then your code will become quite shorter = less distraction and more focus on the important stuff.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-13T20:28:09.303", "Id": "475360", "Score": "0", "body": "may i ask how do you stumble across these modules, like is there a road map for learning modules that make your life easier?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-13T20:57:10.707", "Id": "475363", "Score": "0", "body": "Roadmap ? Yes, there are many tutorials online, and books. Afaik `argparse` is used a lot in command line applications, it is the standard.\nMaybe you could have a look here for an overview: [The Python Standard Library](https://docs.python.org/3/library/index.html). And here too: [Python Module Index](https://docs.python.org/3/py-modindex.html). You don't have to master everything but it's good to know what already exists, so you will keep this in mind before you reinvent the wheel. There are also many third-party modules that can be installed with `pip`." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-13T19:47:43.990", "Id": "242226", "ParentId": "242199", "Score": "1" } } ]
{ "AcceptedAnswerId": "242226", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-13T13:19:21.293", "Id": "242199", "Score": "1", "Tags": [ "python", "python-3.x", "console", "mathematics", "finance" ], "Title": "A Credit Payment Calculator" }
242199
<p>I have an outer div with...</p> <ol> <li>Width </li> <li>Number of slots the outer div represents</li> </ol> <p>The intent is to add a child div, but position the child div based on the start and end slot in the parent div.</p> <p>To achieve this behavior, I am calculating the width per slot and the width of child div, plus the margin left of child div.</p> <pre><code>import React from 'react'; let parentDivStyle = { border: '1px solid black', height: '50px', align: 'center', display: 'inline-block' } let childDivStyle = { backgroundColor: 'darkseagreen', marginTop: '5px', height: '40px', } const DivColoring = (props) =&gt; { let parentDivWith = props.parentDivWidth; let totalSlots = props.totalSlots; let startSlot = props.startSlot; let endSlot = props.endSlot; let widthPerSlot = Math.round(parentDivWith / totalSlots); console.log('widthPerSlot= ', widthPerSlot); let childWidth = parentDivWith; let marginLeft = 0; //if startSlot is greater than 1, calculate the Left Margin and Width. if (startSlot &gt; 1) { marginLeft = (startSlot - 1) * widthPerSlot; } //if end is present and is less than totalSlots update childWidth if (endSlot &amp;&amp; endSlot &lt;= totalSlots) { childWidth = widthPerSlot * (endSlot - startSlot + 1); } //add 1 px to marginLeft of child div marginLeft = marginLeft + 1; //remove 2 px from childWidth to add a padding of 1px at end childWidth = childWidth - 2; return (&lt;div style={{ ...parentDivStyle, width: parentDivWith + 'px', }}&gt; &lt;div style={{ ...childDivStyle, marginLeft: marginLeft , width: childWidth + 'px' }}&gt;&lt;/div&gt; &lt;/div&gt;); } export default DivColoring; </code></pre> <p>Please see the working example here <a href="https://stackblitz.com/edit/react-be8wxg" rel="nofollow noreferrer">https://stackblitz.com/edit/react-be8wxg</a></p> <p>Is there any better of achieving this behavior. Thanks.</p>
[]
[ { "body": "<p>There are 2 more ways to do this using <code>css</code> without the calculation. They are:</p>\n\n<ul>\n<li><h1><a href=\"https://developer.mozilla.org/en-US/docs/Learn/CSS/CSS_layout/Positioning\" rel=\"nofollow noreferrer\">css positioning</a></h1>\n\nMake the <em>position</em> of parent relative and child absolute. Now, using the slots value, left and right properties can be easily calculated for child div which will place it properly. The entire logic is reduces to the following without adding any additional elements:</li>\n</ul>\n\n<pre><code>const DivColoring = props =&gt; {\n let parentDivWidth = props.parentDivWidth;\n let totalSlots = props.totalSlots;\n let startSlot = props.startSlot;\n let endSlot = props.endSlot;\n return (\n &lt;div style={{ ...parentDivStyle, width: parentDivWidth + \"px\" }}&gt;\n &lt;div\n style={{\n ...childDivStyle,\n position: \"absolute\",\n left: `${((startSlot - 1) * 100) / totalSlots}%`,\n right: `${((totalSlots - endSlot) * 100) / totalSlots}%`\n }}\n /&gt;\n &lt;/div&gt;\n );\n};\n</code></pre>\n\n<p>The entire code can be found here: <a href=\"https://stackblitz.com/edit/react-qj3xsp\" rel=\"nofollow noreferrer\">https://stackblitz.com/edit/react-qj3xsp</a></p>\n\n<ul>\n<li><h1><a href=\"https://developer.mozilla.org/en-US/docs/Web/CSS/flex\" rel=\"nofollow noreferrer\">css flex</a></h1>\n\nThe <code>DivColoring</code> component can contain 3 child divs instead of one and you can use flex property to define relative width of the divs. The relative width can be easily calculated using totalSlots, startSlot and endSlot. The basic logic can be written as:</li>\n</ul>\n\n<pre><code>const DivColoring = props =&gt; {\n let totalSlots = props.totalSlots;\n let startSlot = props.startSlot;\n let endSlot = props.endSlot;\n let div3 = totalSlots - endSlot;\n let div2 = endSlot - startSlot + 1;\n let div1 = startSlot - 1;\n return (\n &lt;div style={{ ...parentDivStyle, width: props.parentDivWidth + \"px\" }}&gt;\n &lt;div id=\"\" style={{ flex: div1 }} /&gt;\n &lt;div id=\"\" style={{ ...childDivStyle, flex: div2 }} /&gt;\n &lt;div id=\"\" style={{ flex: div3 }} /&gt;\n &lt;/div&gt;\n );\n};\n</code></pre>\n\n<p>The complete code can be found here: <a href=\"https://stackblitz.com/edit/react-4mgl4c\" rel=\"nofollow noreferrer\">https://stackblitz.com/edit/react-4mgl4c</a>.<br>\nYou also need to apply some extra css. Pros are calculation is reduced but con is that DOM will become heavy. Instead of 1, now there are 3 divs for each block.</p>\n\n<p>The recommended approach will be using <strong>css positioning</strong>.</p>\n\n<p>Hope it helps. Revert for any doubts/clarifications.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-14T17:01:48.263", "Id": "475458", "Score": "0", "body": "Thanks Sunil. I understand the cons in the second approach. Certainly do not want to introduce additional divs making the DOM heavy." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-14T14:30:39.700", "Id": "242278", "ParentId": "242203", "Score": "1" } } ]
{ "AcceptedAnswerId": "242278", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-13T13:36:20.270", "Id": "242203", "Score": "0", "Tags": [ "html", "css", "react.js" ], "Title": "Splitting a div and positioning an inner div" }
242203
<p>I made some code to get RTTI information of a polymorphic object, it works both if you pass it directly or a pointer to it(the pointer will get dereferenced until null or the object is found), it's going to be used only for debugging log, can this solution be improved in some way?</p> <pre><code>#include &lt;cstdint&gt; #include &lt;string&gt; #include &lt;sstream&gt; #include &lt;type_traits&gt; #include &lt;typeinfo&gt; #include &lt;utility&gt; #include &lt;vector&gt; #include &lt;memory&gt; class RuntimeInfos final { private: //Prevent external construction, use the static method to use the functionality RuntimeInfos() noexcept = default; RuntimeInfos(const RuntimeInfos&amp;) noexcept = default; public: //Everything is passed by reference, other templated functions will dispatch them based on the template type's properties template&lt;typename T, std::enable_if_t&lt;!std::is_array_v&lt;T&gt;, int&gt; = 0&gt; static std::string get_runtime_infos(const T&amp; val) { return RuntimeInfos().get_result(val); } private: //Utitlities template&lt;typename Test, template&lt;typename...&gt; class Ref&gt; struct is_specialization : std::false_type {}; template&lt;template&lt;typename...&gt; class Ref, typename... Args&gt; struct is_specialization&lt;Ref&lt;Args...&gt;, Ref&gt; : std::true_type {}; template&lt;typename T&gt; static inline constexpr bool is_smart_ptr_v = is_specialization&lt;T, std::unique_ptr&gt;::value || is_specialization&lt;T, std::shared_ptr&gt;::value || is_specialization&lt;T, std::weak_ptr&gt;::value; //Entry point template&lt;typename T&gt; std::string get_result(const T&amp; val) { var_type = typeid(val).name(); var_address = reinterpret_cast&lt;std::uintptr_t&gt;(&amp;var_type); full_chain.push_back(std::make_pair(var_type, var_address)); exec(val); return get_message(); } // A pointer has been passed by reference, copy the pointer and start the job template&lt;typename T, std::enable_if_t&lt;std::is_pointer_v&lt;T&gt; &amp;&amp; !is_smart_ptr_v&lt;T&gt;, int&gt; = 0&gt; void exec(const T&amp; val) { T bak = val; type_name_runtime(bak); } // The user has passed a object reference which is ok as we don't need to modify anything in this case template&lt;typename T, std::enable_if_t &lt;!is_smart_ptr_v&lt;T&gt; &amp;&amp; !std::is_pointer_v&lt;T&gt;, int&gt; = 0&gt; void exec(const T&amp; val) { return; } // In the special case of smart pointer it gets the raw pointer and call the correct exec function that will handle that type of pointer template&lt;typename T, std::enable_if_t &lt;is_smart_ptr_v&lt;T&gt; &amp;&amp; !std::is_pointer_v&lt;T&gt;, int&gt; = 0&gt; void exec(const T&amp; val) { exec(val.get()); } // This get called if T is a pointer template&lt;typename T, std::enable_if_t&lt;std::is_pointer_v&lt;T&gt;, int&gt; = 0&gt; void type_name_runtime(T val) { is_at_least_level_one_pointer = true; ++dereference_count; if (val) { // Save the current info of the dereferenced val, because if it's not a pointer the job will terminate and we need this info points_to = typeid(*val).name(); points_to_address = reinterpret_cast&lt;std::uintptr_t&gt;(&amp;*val); full_chain.push_back(std::make_pair(points_to, points_to_address)); //This will call itself if the dereference value is still a pointer, else it will call the other template that will end the job type_name_runtime(*val); } else { // Since the dereference value is null, use nullptr as if it was a normal value for consistency and simplicity points_to = typeid(nullptr).name(); points_to_address = reinterpret_cast&lt;std::uintptr_t&gt;(nullptr); full_chain.push_back(std::make_pair(points_to, points_to_address)); // Don't call any function, set the flag and exit, job is terminated null_ending = true; } } // This get called if T is not a pointer template&lt;typename T, std::enable_if_t&lt;!std::is_pointer_v&lt;T&gt;, int&gt; = 0&gt; void type_name_runtime(T val) { // Job has finished return; } // Give the result, the information is not taken from vector.front() and vector.back() to give a little bit more of flexibility std::string get_message() { std::stringstream message; message &lt;&lt; "(0x" &lt;&lt; std::hex &lt;&lt; var_address &lt;&lt; ") " &lt;&lt; "\"" &lt;&lt; var_type &lt;&lt; "\""; if (is_at_least_level_one_pointer) { message &lt;&lt; " ---&gt; "; message &lt;&lt; " ... dereference count (" &lt;&lt; std::dec &lt;&lt; dereference_count &lt;&lt; ") ..."; message &lt;&lt; " ---&gt; "; message &lt;&lt; "(0x" &lt;&lt; std::hex &lt;&lt; points_to_address &lt;&lt; ") \"" &lt;&lt; points_to &lt;&lt; "\""; } return message.str(); } // Since pointers are not polymorphic, the chain will contain the same pointer type, with the difference being only the level of the pointer, so it's better to just count and show how many dereference have been made std::uintmax_t dereference_count = 0; // Information about the type passed to the class std::string var_type = ""; std::uintptr_t var_address = 0; // At the end of the job it will contains information about the polymorphic object or about null std::string points_to = ""; std::uintptr_t points_to_address = 0; // True if the job has been interrupted because a null pointer has been found, false otherwise. Unused for now bool null_ending = false; // True if the type passed to the class was at least a pointer, false otherwise bool is_at_least_level_one_pointer = false; // Contains full chain, unused for now std::vector&lt;std::pair&lt;std::string, std::uintptr_t&gt;&gt; full_chain{}; }; </code></pre> <p>Some basic code to test:</p> <pre><code> #include &lt;iostream&gt; #include &lt;vector&gt; #include &lt;memory&gt; class BaseClz { public: BaseClz() noexcept = default; virtual ~BaseClz() noexcept = default; }; class Derived1 : public BaseClz { public: Derived1() noexcept = default; ~Derived1() noexcept = default; }; class Derived2 : public BaseClz { public: Derived2() noexcept = default; ~Derived2() noexcept = default; }; class DerivedDerived1 : public Derived1 { public: DerivedDerived1() noexcept = default; ~DerivedDerived1() noexcept = default; }; class DerivedDerived2 : public Derived2 { public: DerivedDerived2() noexcept = default; ~DerivedDerived2() noexcept = default; }; class LastDerived : public DerivedDerived1, DerivedDerived2 { public: LastDerived() noexcept = default; ~LastDerived() noexcept = default; }; void do_something_example(BaseClz*** base_clz) { std::cout &lt;&lt; "Entered do_something function with parameter: " &lt;&lt; RuntimeInfos::get_runtime_infos(base_clz) &lt;&lt; std::endl; try { throw std::runtime_error(""); } catch (...) { std::cout &lt;&lt; "Exception occurred, parameter info: " &lt;&lt; RuntimeInfos::get_runtime_infos(base_clz) &lt;&lt; std::endl; } } int main() { BaseClz* base = new Derived2; Derived1* derived1 = new LastDerived; BaseClz* derived2 = new Derived2; DerivedDerived2* derivedderived2 = new DerivedDerived2; BaseClz* base2 = new BaseClz; DerivedDerived1* derivderiv1 = new LastDerived; BaseClz** ptr = &amp;base; BaseClz*** ptr_ptr = &amp;ptr; std::vector&lt;BaseClz*&gt; test {base, derived1, derived2, derivedderived2, base2, nullptr}; std::cout &lt;&lt; std::endl; for (BaseClz* a : test) { std::cout &lt;&lt; RuntimeInfos::get_runtime_infos(a) &lt;&lt; std::endl; std::cout &lt;&lt; std::endl; } std::cout &lt;&lt; RuntimeInfos::get_runtime_infos(ptr_ptr) &lt;&lt; std::endl; std::cout &lt;&lt; std::endl; do_something_example(ptr_ptr); std::cout &lt;&lt; std::endl; std::unique_ptr&lt;BaseClz&gt; smart_ptr = std::make_unique&lt;DerivedDerived2&gt;(); std::cout &lt;&lt; RuntimeInfos::get_runtime_infos(smart_ptr) &lt;&lt; std::endl; return 0; } </code></pre> <p>Output will like the following except the address and the rtti string based on the compiler, this is from MSVC:</p> <pre><code>(0xA) "class BaseClz * __ptr64" ---&gt; ... dereference count (1) ... ---&gt; (0xB) "class Derived2" (0xC) "class BaseClz * __ptr64" ---&gt; ... dereference count (1) ... ---&gt; (0xD) "class LastDerived" (0xE) "class BaseClz * __ptr64" ---&gt; ... dereference count (1) ... ---&gt; (0xF) "class Derived2" (0x10) "class BaseClz * __ptr64" ---&gt; ... dereference count (1) ... ---&gt; (0x11) "class DerivedDerived2" (0x12) "class BaseClz * __ptr64" ---&gt; ... dereference count (1) ... ---&gt; (0x13) "class BaseClz" (0x14) "class BaseClz * __ptr64" ---&gt; ... dereference count (1) ... ---&gt; (0x0) "std::nullptr_t" (0x15) "class BaseClz * __ptr64 * __ptr64 * __ptr64" ---&gt; ... dereference count (3) ... ---&gt; (0x16) "class Derived2" Entered do_something function with parameter: (0x16) "class BaseClz * __ptr64 * __ptr64 * __ptr64" ---&gt; ... dereference count (3) ... ---&gt; (0x17) "class Derived2" Exception occurred, parameter info: (0x18) "class BaseClz * __ptr64 * __ptr64 * __ptr64" ---&gt; ... dereference count (3) ... ---&gt; (0x19) "class Derived2" (0x1A) "class std::unique_ptr&lt;class BaseClz,struct std::default_delete&lt;class BaseClz&gt; &gt;" ---&gt; ... dereference count (1) ... ---&gt; (0x1B) "class DerivedDerived2" </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-13T15:03:47.623", "Id": "475335", "Score": "0", "body": "I don't completely understand what you're trying to do, but could you make use of `dynamic_cast`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-13T15:07:55.583", "Id": "475337", "Score": "0", "body": "I'm going to use it for debugging log only, i'm not going to use it to write any logic. I'm going to add an example" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-13T15:32:13.343", "Id": "475341", "Score": "0", "body": "Added the example." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-13T16:00:26.760", "Id": "475347", "Score": "0", "body": "Does it de-reference through smart pointers? Pointers themselves are not very common in modern C++ they are usually encapsulated in a memory management object like a smart pointer." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-13T16:44:56.740", "Id": "475348", "Score": "0", "body": "If you get the raw pointer with the get() method it works, i don't think it will be a goog idea to add the option to pass smart pointers, because as i said it's for debugging log, if for example i have an std::unique_ptr i don't want to transfer the ownership to this debugging log function." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-13T22:49:03.517", "Id": "475371", "Score": "0", "body": "@MartinYork thanks for the suggestion, in the end i decided to implement it, there's a template specialization for the smart pointers that retrieve the raw pointer, i also made it that i could pass variables by const reference at the start function without any problem, so no problems like moving std::unique_ptr or incrementing the reference count of std::shared_ptr, for other templated types (like for example std::optional, or even your own) you still have to pass the value like shown in the vector example part, or you can create your specialization, the pieces are there" } ]
[ { "body": "<p>This code is <em>really</em> excessively confusing. It seems like basically you're just doing this:</p>\n<pre><code>template&lt;class T&gt;\nstd::string get_runtime_info(const T&amp; t) {\n if constexpr (std::is_pointer_v&lt;T&gt;) {\n if (t == nullptr) {\n using U = decltype(*t);\n return std::string(&quot;null pointer to &quot;) + typeid(U).name();\n } else {\n return &quot;pointer to &quot; + get_runtime_info(*t);\n }\n } else {\n return typeid(t).name();\n }\n}\n</code></pre>\n<p>but you've surrounded this logic with so much OOP cruft (eight different data members, of a &quot;class&quot; with no public member functions?!) and template metaprogramming (<code>is_specialization_v</code>) that it's hard to tell what's going on.</p>\n<hr />\n<p>You've declared your copy constructor <code>noexcept</code>, but it has to copy a bunch of strings and a vector; it is <em>not</em> noexcept. Don't lie to the compiler!</p>\n<p>Vice versa, your default constructor is probably noexcept, but since it's explicitly defaulted, I'm pretty sure you don't have to say it's <code>noexcept</code> — the compiler will figure that out on its own. <a href=\"https://godbolt.org/z/F_22ct\" rel=\"nofollow noreferrer\">Godbolt agrees.</a></p>\n<hr />\n<p>If you're going to use member functions, make sure you const-qualify the appropriate ones (e.g. <code>get_message()</code> should be const-qualified).</p>\n<hr />\n<p>At one point you write <code>std::is_pointer_v&lt;T&gt; &amp;&amp; !is_smart_ptr_v&lt;T&gt;</code>, which is redundant; you should just write <code>std::is_pointer_v&lt;T&gt;</code>. Likewise, <code>is_smart_ptr_v&lt;T&gt; &amp;&amp; !std::is_pointer_v&lt;T&gt;</code> should just be <code>is_smart_ptr_v&lt;T&gt;</code>.</p>\n<p>Since you're doing C++20, you <em>could</em> use constrained templates instead of <code>enable_if</code>:</p>\n<pre><code>template&lt;class T&gt; requires std::is_pointer_v&lt;T&gt;\nvoid exec(const T&amp; val) {\n T bak = val;\n type_name_runtime(bak);\n}\n\ntemplate&lt;class T&gt; requires is_smart_ptr_v&lt;T&gt;\nvoid exec(const T&amp; val) {\n exec(val.get());\n}\n\ntemplate&lt;class T&gt;\nvoid exec(const T&amp; val) {\n return;\n}\n</code></pre>\n<p>But it's much better to use a plain old C++17 <code>if constexpr</code>, as in my &quot;simple&quot; rewrite up top:</p>\n<pre><code>template&lt;class T&gt;\nvoid exec(const T&amp; val) {\n if constexpr (std::is_pointer_v&lt;T&gt;) {\n T bak = val;\n type_name_runtime(bak);\n } else if constexpr (is_smart_ptr_v&lt;T&gt;) {\n exec(val.get());\n }\n}\n</code></pre>\n<hr />\n<p>The line <code>T bak = val;</code> is pointless; C++ copies by default. Since <code>type_name_runtime</code> takes by value (i.e., by copy), therefore there is no observable difference between</p>\n<pre><code> T bak = val;\n type_name_runtime(bak);\n</code></pre>\n<p>and</p>\n<pre><code> type_name_runtime(val);\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-06T08:27:59.607", "Id": "484601", "Score": "1", "body": "The extra `T bak = val` can have an observable difference if `T`'s constructor and/or destructor has side-effects." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-07T06:15:31.360", "Id": "245117", "ParentId": "242206", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-13T14:28:42.983", "Id": "242206", "Score": "4", "Tags": [ "c++", "c++17", "c++20", "rtti" ], "Title": "Is there a better solution to get RTTI info about a polymorphic type?" }
242206
<pre class="lang-rust prettyprint-override"><code>extern crate serde; use serde::{Deserialize, Serialize}; use serde_json::json; use std::error::Error; use std::fs::File; use std::io::prelude::*; use std::io::{BufReader}; use std::time::Duration; const NER_SERVER: &amp;'static str = "http://127.0.0.1:5000/parse"; #[derive(Serialize, Deserialize)] struct Article { url: String, text: String, id: String, } #[derive(Serialize, Deserialize)] struct NER { begin: u32, end: u32, } fn run() -&gt; Result&lt;u64, Box&lt;Error&gt;&gt; { let file = File::open("data/test").unwrap(); let client = reqwest::blocking::Client::builder() .timeout(Duration::from_secs(100)) .build()?; let reader = BufReader::new(file); let mut count : u64 = 0; for line in reader.lines() { let article: Article = serde_json::from_str(&amp;line.unwrap_or_default())?; let ners: Vec&lt;NER&gt; = client.post(NER_SERVER) .json(&amp;json!({"data": article.text})) .send()?.json()?; // TODO change to async for item in ners.iter() { println!("{} {}", item.begin, item.end); } count = count + 1; } Ok(count) } fn main() { match run() { Ok(e) =&gt; println!("{}", e), Err(e) =&gt; println!("{:#}", e) } } </code></pre> <p>Piggyback question: How to set up a general JSON schema for the project. Currently, in this [line][2], the schema is supposed to match this [line][3], which I think is extremely ugly, but could not think of another way to shape it.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-13T16:30:55.860", "Id": "242211", "Score": "2", "Tags": [ "json", "rust" ], "Title": "A service that posts JSON to a server and works with responses" }
242211
<p>Can someone please review the code and suggest any improvements / changes? Note that this method works but wanted to see if there is a better way to reset the currentYearMeetingCount to -1. I just want to print the data if there is data for that year and for the past 3 years.</p> <pre><code> class Program { static void Main(string[] args) { List&lt;Meeting&gt; Meeting = new List&lt;Meeting&gt;(); Meeting.Add(new Meeting() { Name="a", Year = 2019 }); Meeting.Add(new Meeting() { Name="b", Year = 2019 }); Meeting.Add(new Meeting() { Name = "c", Year = 2019 }); Meeting.Add(new Meeting() { Name = "d", Year = 2018 }); Meeting.Add(new Meeting() { Name = "e", Year = 2018 }); Meeting.Add(new Meeting() { Name = "f", Year = 2017 }); Meeting.Add(new Meeting() { Name = "g", Year = 2016 }); Meeting.Add(new Meeting() { Name = "h", Year = 2015 }); //string Ids = peopleList.Select(x =&gt; x.ID); int totalYearCount = 3; DateTime aDate = DateTime.Now; int currentYearMeetingCount = Meeting.Where(x =&gt; x.Year == aDate.Year).Count(); if (currentYearMeetingCount == 0) { aDate = DateTime.Now.AddYears(-1); } foreach (var year in Enumerable.Range(aDate.Year - totalYearCount + 1, totalYearCount).Reverse()) { var meetingList = Meeting.Where(x =&gt; x.Year == year); foreach (var meeting in meetingList) { Console.WriteLine("{0}-{1}", meeting.Name, meeting.Year); } } } class Meeting { public int Year { get; set; } public string Name { get; set; } } } </code></pre>
[]
[ { "body": "<p>You could also write</p>\n\n<pre><code>int lastYear = Meeting.Max(m =&gt; m.Year);\nif (lastYear &lt; aDate.Year) {\n aDate = DateTime.Now.AddYears(-1);\n}\n</code></pre>\n\n<p>And if you want to automatically make the date be the last year in your data set</p>\n\n<pre><code>DateTime aDate = DateTime.Now;\nint lastYear = Meeting.Max(m =&gt; m.Year);\naDate = new DateTime(lastYear, aDate.Month, aDate.Day);\n</code></pre>\n\n<p>But since you are only using the <code>Year</code> part of the date, there is no point in using a <code>DateTime</code> variable. You can simply write:</p>\n\n<pre><code>int y = DateTime.Now.Year;\nint lastYear = Meeting.Max(m =&gt; m.Year);\nif (y &gt; lastYear) {\n y--;\n}\n\nfor (int year = y; year &gt; y - totalYearCount; year--) {\n ...\n}\n</code></pre>\n\n<p>or simply use the last year (my favourite solution):</p>\n\n<pre><code>int lastYear = Meeting.Max(m =&gt; m.Year);\nfor (int year = lastYear; year &gt; lastYear - totalYearCount; year--) {\n ...\n}\n</code></pre>\n\n<hr>\n\n<p>You can simplify the initialization of the list with a collection initializer:</p>\n\n<pre><code>List&lt;Meeting&gt; Meeting = new List&lt;Meeting&gt; {\n new Meeting { Name = \"a\", Year = 2019 },\n new Meeting { Name = \"b\", Year = 2019 },\n new Meeting { Name = \"c\", Year = 2019 },\n new Meeting { Name = \"d\", Year = 2018 },\n new Meeting { Name = \"e\", Year = 2018 },\n new Meeting { Name = \"f\", Year = 2017 },\n new Meeting { Name = \"g\", Year = 2016 },\n new Meeting { Name = \"h\", Year = 2015 }\n};\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-13T18:23:40.103", "Id": "242219", "ParentId": "242216", "Score": "0" } }, { "body": "<p>There is no need for this </p>\n\n<pre><code>DateTime aDate = DateTime.Now;\n\nint currentYearMeetingCount = Meeting.Where(x =&gt; x.Year == aDate.Year).Count();\n\nif (currentYearMeetingCount == 0)\n{\n aDate = DateTime.Now.AddYears(-1);\n\n}\n</code></pre>\n\n<p>if the collection has no data for the current year, it'll only get the past 3 years if any. so, you can do this directly : </p>\n\n<pre><code>var totalYearCount = 3;\nvar maxYear = DateTime.Now.Year;\nvar minYear = maxYear - totalYearCount;\n\nvar result = Meeting.Where(x=&gt; x.Year &gt;= minYear &amp;&amp; x.Year &lt;= maxYear).ToList();\n\nif(result.Count == 0) \n{\n // no data, do something \n}\n\nforeach(var meeting in result)\n{\n Console.WriteLine($\"{meeting.Name}-{meeting.Year}\");\n}\n</code></pre>\n\n<p>this will output 2017-2019 records. However, if your logic has a special case, let's say if there is no records for current year, then start with the last year instead so the output will be from 2016 to 2019. If this is the case, then instead of depending on <code>DateTime.Now.Year</code> you can get the max year from the collection, and subtract the past x years from it. Something like this : </p>\n\n<pre><code>var totalYearCount = 3;\nvar maxYear = Meeting.Max(x=&gt; x.Year);\nvar minYear = maxYear - totalYearCount;\nvar result = Meeting.Where(x=&gt; x.Year &gt;= minYear &amp;&amp; x.Year &lt;= maxYear).ToList();\n\nif(result.Count == 0) \n{\n // no data, do something \n}\n\nforeach(var meeting in result)\n{\n Console.WriteLine($\"{meeting.Name}-{meeting.Year}\");\n}\n</code></pre>\n\n<p>this will output 2016-2019 records, and if there is any records for the current year (say 2020), then it'll output 2017-2020.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-13T19:04:27.727", "Id": "242223", "ParentId": "242216", "Score": "1" } } ]
{ "AcceptedAnswerId": "242223", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-13T18:02:40.000", "Id": "242216", "Score": "1", "Tags": [ "c#" ], "Title": "Collection base on year" }
242216
<p>So, I am trying to create a PNG compression library, and to do that I need to use the DEFLATE algorithm; DEFLATE consists of two parts, the LZ77 compression, and the Huffman Compression. Currently, my LZ77 algorithm has a pretty good compression rate, although I think it could be better, the problem is that is really slow. I have tried some optimizations but its compression speed isn't acceptable. I have seen that libraries such as ZLIb implement something called a "Lazy matching" but I have just found vague explanations. To summarize I was wondering if someone could help me improve the algorithm. My main focus is to make it faster but if there is something I can do to increase the compression rate it'll also be really helpful.</p> <p><strong>Header</strong></p> <pre><code>class LZ77{ public: RawData encode(RawData const&amp; data); private: // searches for matches in the current // index of the look ahead buffer bool search(RawData const&amp; data); // moves data from the lookahead buffer into the search buffer // by quantity positions void shift(RawData const&amp; data, unsigned int quantity); // given an index in the search buffer , it returns the length // the longest match from that position unsigned int searchFromIndex(RawData const&amp; data, int i) const; // the buffer size fixes the physical size of the search buffer // determined by the DEFLATE specifications static const unsigned int BUFFER_SIZE = 32 * 1024; // to limit the max length of an encountered string match static const unsigned int MAX_LENGTH = 258; // stop searching if length is long enough static const unsigned int MARGIN_LENGTH = 200; // to limit the minimum length a match must have to // be considered a match static const unsigned int MIN_LENGTH = 5; // Min length for a match // aheadSize is a pointer to the first element in the // look ahead buffer, hence the name unsigned int aheadPointer; // when a match is encounter the distance from the 0 position // and the match begining is saved as the offset unsigned int offset; // contains the largest match at a given time unsigned int matchLength; // represents the search buffer of the algorithm // where characters that have already been seen // are saved and discarted on buffer fill std::array&lt;ByteType, BUFFER_SIZE&gt; searchBuffer; }; </code></pre> <p><strong>Source</strong></p> <pre><code>/* LOOKAHEAD BUFFER The lookahead buffer is implicit within the data and its size is limited by the max match length SEARCH BUFFER The search buffer is implemented as a fixed array of size 32KB (32 * 1024), specified in the PNG standard The first position of the buffer is indexed by a 0 */ /************************ PUBLIC *************************/ RawData LZ77::encode(RawData const&amp; data){ RawData output; aheadPointer = 0; // setup // main algorithm while(aheadPointer &lt; data.size()){ bool match = search(data);// 1. search if(match){ shift(data, matchLength); // shift output.push("["+ std::to_string(offset) +"," + std::to_string(matchLength) + "]"); aheadPointer += matchLength; }else{ shift(data, 1); // no match =&gt; add a single character output.push(data.get(aheadPointer)); ++aheadPointer; } } std::cout &lt;&lt; "LZ77 compression ratio: " &lt;&lt; (float(data.size()) / output.size()) * 100 &lt;&lt; std::endl; return output; } /************************ PRIVATE *************************/ // pre: quantity &lt;= BUFFER_SIZE void LZ77::shift(RawData const&amp; data, unsigned int quantity){ // min is needed when search buffer is not full unsigned int size = std::min(BUFFER_SIZE, aheadPointer); // shift search buffer elements for(int i = quantity; i &lt; size; ++i) searchBuffer[i - quantity] = searchBuffer[i]; // move elements betweeen buffers for(int i = size - quantity; i &lt; size; ++i) searchBuffer[i] = data.get(aheadPointer + i); } bool LZ77::search(RawData const&amp; data){ bool found = false; // min is needed when search buffer is not full unsigned int size = std::min(BUFFER_SIZE, aheadPointer); // set the matchLength to the minimum, this way // I only accept matches with at least that length matchLength = MIN_LENGTH; offset = 1; // 0 is the last element of the search buffer bool stopSearching = false; for(unsigned int i = 0; i &lt; size &amp;&amp; !stopSearching; ++i){ if(searchBuffer[i] == data.get(aheadPointer)){ auto length = searchFromIndex(data, i + 1); // find sequence with max length if(length &gt; matchLength){ found = true; offset = size - i; matchLength = length; } auto separation = size - i + MAX_LENGTH; // if length is long enough or given the current // position we cannot get a better one, stop searching if(length &gt;= separation || length &gt;= MARGIN_LENGTH){ stopSearching = true; } } } return found; } unsigned int LZ77::searchFromIndex(RawData const&amp; data, int i) const{ unsigned int length = 1; unsigned int size = std::min(BUFFER_SIZE, aheadPointer); // continue comparing characters and incrementing the length // of the matching string // CONDITIONS // 1. check length is less than maximum lenght // 2. check iterator lesser than size of the buffer // 3. while there is a character match // RESULT // 1. increment the iterator -&gt; decrements buffer position // 2. increment length while(length &lt; MAX_LENGTH &amp;&amp; i &lt; size &amp;&amp; searchBuffer[i] == data.get(length + aheadPointer)){ ++i; length++; } // when we have compared all the search buffer // we can continue to compare data from within the lookup // buffer, this way we can compress the data even further if(i &gt;= size){ i = aheadPointer; auto currentLength = length; while(i &lt; data.size() &amp;&amp; length &lt; MAX_LENGTH &amp;&amp; data.get(i) == data.get(i + currentLength)){ ++i; ++length; } } return length; } </code></pre> <p>The RawData class is just a container for a byte vector.</p> <p><strong>Other</strong></p> <pre><code> typedef unsigned char ByteType; class RawData{ public: ... private: std::vector&lt;ByteType&gt; bytes; }; </code></pre> <p>You can test the entire program in <a href="https://github.com/polmonroig/sfic" rel="nofollow noreferrer">https://github.com/polmonroig/sfic</a></p> <p>Best regards, thanks!</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-14T04:34:54.120", "Id": "475378", "Score": "0", "body": "Is this an exercise, or is there some functionality the half a dozen or so LZ77 implementations are missing?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-14T06:05:03.920", "Id": "475381", "Score": "0", "body": "Its not an exercice, its it is a personal project I wanted to code. But the project is not LZ77 is involves PNG" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-20T21:02:06.707", "Id": "476200", "Score": "0", "body": "`shift` looks suspiciously slow. You may want a ring queue for `searchBuffer`. Also, you have to allocate/initialize `output` [`RawData`] on each call to `encode`. Might be faster to pre-allocate it and pass as a 2nd arg (ensuring there is sufficient space so that `push` does _not_ grow/reallocate from the heap. To do a ring queue, you might consider: https://en.cppreference.com/w/cpp/container/deque" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-20T21:11:39.387", "Id": "476202", "Score": "0", "body": "@CraigEstey I'll modify the things that you mentioned. Yes, shifts looks very slow, but I didn't know how to optimize it. Thanks for your help!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-20T22:41:07.427", "Id": "476212", "Score": "0", "body": "Also, `to_string` seems to be implemented with `vsnprintf` and there are two calls, so you might be better off with doing your own single `sprintf` call [a bit \"dirty\", but ...]" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-21T06:14:36.780", "Id": "476247", "Score": "0", "body": "@CraigEstey humm, I have always tried to use a lot the std library, thought it would give me the most efficient implementation, seems I was wrong...I'll write it myself then" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-21T07:18:29.160", "Id": "476254", "Score": "0", "body": "I've seen the term \"realtime safe\", which amongst other things means, once the program is initialized, no call that can do heap allocation in the critical path. STL is reasonably fast, but not blazing. And, if you're not _very_ careful, it can be slow. STL implementations can vary wildly in performance. IIRC, impl of `std::map` can vary by 5x. See my answer: https://codereview.stackexchange.com/questions/191747/c-interview-problem-finding-an-island-in-a-2d-grid/191921#191921 It talks about some of the issues with STL and performance [that you may be encountering]" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-21T07:29:29.507", "Id": "476255", "Score": "0", "body": "@CraigEstey good to know there is a term for that, I have always tried to allocate the data beforehand, although I have only done it when I know exactly the space it is going to use." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-13T18:43:32.593", "Id": "242221", "Score": "1", "Tags": [ "c++", "performance", "compression" ], "Title": "How can I make my LZ77 algorithm to compress faster or to compress more?" }
242221
<p>Hi I am creating a website for my chiropractor and I am creating the API for data access. </p> <p>I am creating a HttpPatch Method and want to know if this is the right approach so would be grateful if you could look over my code and let me know if I am doing it right, or if I need to change some things. </p> <p>Patient Controller</p> <pre><code>[ValidateAntiForgeryToken] [HttpPatch] [Route("PatchPatient/{patientId:guid}")] public async Task&lt;IActionResult&gt; PatchPatient([FromBody]Guid patientId, JsonPatchDocument&lt;PatientModel&gt; model) { if (!ModelState.IsValid) { return BadRequest(ModelState); } var result = await _patient.PatchPatient(patientId, model); return Ok(result); } </code></pre> <p>PatientService</p> <pre><code>public async Task&lt;JsonPatchDocument&lt;PatientModel&gt;&gt; PatchPatient(Guid patientId, JsonPatchDocument&lt;PatientModel&gt; model) { var patient = await GetPatients(patientId); var mappedPatientModel = _mapper.Map&lt;Patient, PatientModel&gt;(patient.FirstOrDefault()); model.ApplyTo(mappedPatientModel); await _dbContext.SaveChangesAsync(); return model; } private async Task&lt;List&lt;Patient&gt;&gt; GetPatients(Guid? patientId) { var patients = await _dbContext.Patients.AsNoTracking().ToListAsync(); return patientId != null ? patients.Where(patient =&gt; patient.Id == patientId).ToList() : patients; } </code></pre> <p>The idea of what I am trying to achieve is to update the patient record with the patch object that is going in. </p> <p>Because I am doing this work in the service layer the model.ApplyTo(...) I cannot do a validation on the model state so unless I do a back and forth between controller and service I am not sure of the best approach and some guidance would be very much appreciated. </p>
[]
[ { "body": "<p>In general the patch endpoint should consist of the following steps (<strong>order is important</strong>): </p>\n\n<ol>\n<li>Preliminary check(s) (for example in case of null return BadRequest)</li>\n<li>Load existing object (based on the request's key)</li>\n<li>Apply the existing object (if any) onto the patch request</li>\n<li>Validate model state (and return BadRequest if it is ain't valid)</li>\n<li>Save changes</li>\n<li>Return with appropriate status code</li>\n</ol>\n\n<p>I would suggest to check the <a href=\"https://httpwg.org/specs/rfc5789.html#rfc.section.2.2\" rel=\"nofollow noreferrer\">corresponding error handing</a>. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-14T10:21:38.393", "Id": "242261", "ParentId": "242229", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-13T21:48:04.347", "Id": "242229", "Score": "-1", "Tags": [ "c#", ".net", "asp.net-core", "asp.net-core-webapi" ], "Title": "ASP.Net Core API JsonPatchDocument" }
242229
<p>I've recently started teaching myself basic C++ and decided to implement a simple stack with pointers.</p> <pre><code>#include &lt;iostream&gt; using namespace std; struct StackElement { char value; StackElement* next; StackElement(char value, StackElement* next) : value(value), next(next) {} }; struct Stack { StackElement* top = NULL; bool isEmpty() { return top == NULL; } void push(char value) { StackElement* newElement = new StackElement(value, top); top = newElement; } StackElement pop() { StackElement* toBeDeleted = top; StackElement toBeReturned = *top; top = top-&gt;next; delete toBeDeleted; return toBeReturned; } }; int main() { Stack* stack = new Stack(); cout &lt;&lt; "Created a stack at " &lt;&lt; &amp;stack &lt;&lt; endl; int number_of_inputs; cout &lt;&lt; "Enter the number of elements you want to push at the stack: "; cin &gt;&gt; number_of_inputs; for (int i = 0; i &lt; number_of_inputs; i++) { char input; cin &gt;&gt; input; stack-&gt;push(input); } cout &lt;&lt; "- - - - - - - - - - - - - - - - " &lt;&lt; endl; cout &lt;&lt; "Displaying content of the stack: " &lt;&lt; endl; while (!stack-&gt;isEmpty()) { cout &lt;&lt; stack-&gt;pop().value &lt;&lt; endl; } return 0; } </code></pre> <p>My questions are: - what could be <em>generally</em> done better here? - is the <code>pop()</code> method written correctly? Does it create any memory leaks? Is there a way to write it shorter?</p> <p>Thank you in advance! (And forgive use of <code>using namespace std</code>)</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-14T09:58:56.243", "Id": "475412", "Score": "4", "body": "In `std` stack is implemented via `std::vector` by default. The thing is linked list is slow as allocating new item per push is too much. `std::vector` stores data contiguously allowing much better performance on all fronts." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-14T15:49:40.113", "Id": "475442", "Score": "2", "body": "Just a quick comment about writing a class like this. Start with behaviors. What do you want this to do? What do you want this to NOT do? Verify behavior with unit tests. Make sure to test both the things you want it to do and what you don't want it to do. The first thing I would ask someone new to do is to write a test that pushes once, but then pops twice. What behavior would you expect? What actually happens." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-14T21:47:05.160", "Id": "475486", "Score": "2", "body": "It's unusual for `pop()` to return an internal data object. Shouldn't it return the value?" } ]
[ { "body": "<p>Your <strong>linked-list implementation</strong> of a stack is well written in respect to you're being a learner.</p>\n\n<h3>Observations</h3>\n\n<p>.. from a foreign Software Developer's perspective (experienced in Java) that never coded in C++:</p>\n\n<ul>\n<li><code>Stack</code> could be implemented as <code>class</code>, instead of <code>struct</code> (benefit: information hiding)</li>\n<li><code>pop()</code> should return a value (e.g. <code>char</code> instead of a node or <code>StackElement</code>)</li>\n<li>there's no method <code>size()</code> which returns the stack's size as <code>int</code></li>\n</ul>\n\n<p>See <em>Robert Sedgwick</em>'s book <a href=\"https://www.pearson.com/us/higher-education/program/Sedgewick-Algorithms-in-C/PGM326041.html\" rel=\"nofollow noreferrer\">Algorithms in C++, 3rd ed.</a>, where he writes about <strong>Stack Implementations</strong>. Beware it's from 1999 but includes following <a href=\"https://www.cs.princeton.edu/~rs/Algs3.cxx1-4/code.txt\" rel=\"nofollow noreferrer\">example C++ Stack class</a> to derive some <strong>encapsulation advice</strong> (private VS public):</p>\n\n<pre class=\"lang-c prettyprint-override\"><code>template &lt;class Item&gt;\n\nclass STACK {\n\n private:\n\n struct node {\n Item item;\n node * next;\n node(Item x, node * t) {\n item = x;\n next = t;\n }\n };\n\n typedef node * link;\n link head;\n\n public:\n\n STACK(int) {\n head = 0;\n }\n\n int empty() const {\n return head == 0;\n }\n\n void push(Item x) {\n head = new node(x, head);\n }\n\n Item pop() {\n Item v = head - &gt; item;\n link t = head - &gt; next;\n delete head;\n head = t;\n return v;\n }\n};\n</code></pre>\n\n<h3>Incompleteness Warning</h3>\n\n<p>Since I am a \"native\" Java developer, I can better judge on the or similar <a href=\"https://algs4.cs.princeton.edu/13stacks/Stack.java.html\" rel=\"nofollow noreferrer\">Java Implementation of a Stack</a> using <em>generics</em>.\nThus I will miss some points that other experienced C++ developers may answer for sure.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-14T16:53:19.780", "Id": "475456", "Score": "2", "body": "The difference between `struct` and `class` is only *default* visibility of members" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-14T21:22:55.850", "Id": "475485", "Score": "0", "body": "Why would `pop()` return a `char` value, instead of the actual item (node) that was popped from the stack?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-14T22:01:01.220", "Id": "475489", "Score": "1", "body": "You're leaking memory of the stack goes out of scope when not empty." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-14T02:08:27.310", "Id": "242232", "ParentId": "242231", "Score": "0" } }, { "body": "<p>1) You can use templates to extend the functionality of your stack class to other types.</p>\n\n<p>2) Use <code>nullptr</code> instead of <code>NULL</code>.</p>\n\n<p>3) Implement <code>Stack</code> as a <code>class</code> instead of <code>struct</code>, since the former has private access specifier as default. You don't want users of this library to be manually able to access <code>top</code>.</p>\n\n<p>4) <code>pop()</code> should return the value stored, not <code>StackElement</code>.</p>\n\n<p>5) Your solution leaks memory. Your current way of releasing memory is assuming that the user will <code>pop()</code> on all elements; more of than that, it will not be the case. Consider this:</p>\n\n<pre><code>int main()\n{\n {\n Stack st;\n for(auto i = 0; i &lt; 10; i++)\n {\n st.push(static_cast&lt;char&gt;(i));\n }\n }\n}\n</code></pre>\n\n<p>No <code>pop()</code> is called, and <code>st</code> object is deleted. All the allocations aren't deallocated, and you're leaking memory. The C++ way to solve this is <a href=\"https://stackoverflow.com/q/2321511\">RAII</a> - delete all the elements in the destructor.</p>\n\n<p>6) <code>using namespace std</code> is generally frowned upon.</p>\n\n<p>7) Wrap your code inside a namespace.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-14T09:18:28.433", "Id": "475406", "Score": "1", "body": "All valid points, except that the OP explicitly asked to be absolved from the sin of using namespace std." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-14T09:23:15.193", "Id": "475407", "Score": "3", "body": "@Peter-ReinstateMonica: Just because they ask not to be reprimanded for something doesn't mean answerers are not allowed to, as they are allowed to comment on any and all aspects of the code. However, for something minor as this I agree. In addition, I edited your edit to remove the tracking of your user ID from the link. Not sure what the policy is for this, but it felt weird for you to get the referrals on a link in somebody else's answer." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-14T10:02:44.910", "Id": "475413", "Score": "1", "body": "@Graipher (UID): Oh, I was not aware of that! I simply clicked \"share\" and copied the URL. Right, it mentions that in the accompanying text. So it's better to copy from the URL in the address field... funny." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-14T03:07:59.743", "Id": "242237", "ParentId": "242231", "Score": "5" } }, { "body": "<p>In addition to Rish's good answer, here are some <strong>software engineering</strong> (rather than coding) remarks.</p>\n\n<ul>\n<li><p>Show us that you <strong>organized the code</strong> properly by factoring out what you actually are presenting: The \"library\" part, consisting of two files: The header and the implementation, unless you decide to keep all functions inline which seems defensible in this case.</p>\n\n<p>The code containing the test/usage demonstration should be in a separate file. This separation is relevant because neither the stack header nor the implementation would, for example, include <code>&lt;iostream&gt;</code>.</p></li>\n<li><p>Use <a href=\"http://www.doxygen.nl/\" rel=\"nofollow noreferrer\">doxygen style <strong>comments</strong></a> to document your code. Good documentation focuses on the non-obvious. A function with a speaking name (e.g., <code>pop()</code>) does not need a general explanation. But you <em>should</em> document non-obvious parameters and return values, invariants, non-obvious side effects and generally any peculiarities. In short, establish <em>context.</em> E.g. leave information about <em>where an (internal) function is used or called from</em>.</p>\n\n<p>It is generally good practice to write at least a short description for every class. </p></li>\n<li><p>For anything but a toy project I would also really appreciate a <strong>module test</strong>. Such a test is essential for a library like this stack which will be used by \"third parties\" (perhaps yourself in a different role). A comprehensive test takes on the role of a specification: As long as the users don't do anything that does not occur in the test, they can expect that a library upgrade does not introduce bugs into their software. If the test is comprehensive it will prevent most errors from reaching the users.</p>\n\n<p>For open source projects tests are typically deployed together with the source code, so users can run them after they built their version. </p>\n\n<p>Typically there is limited time or interest for writing tests, so it should focus on problems. The following questions can help to identify <strong>spots worth testing:</strong></p>\n\n<ul>\n<li>Which part did I find <strong>difficult to implement</strong>/where am I least confident? </li>\n<li>Which part is the <strong>hardest to understand</strong> when I look at the code? (And: Should I rework that to be simpler?)</li>\n<li>What are the <strong>border conditions</strong> (empty/any max element number)? </li>\n<li>What are the <strong>failure modes:</strong> Your empty stack aborts with a null pointer exception upon <code>pop()</code>, wouldn't it be nice to throw a custom exception? What about an out-of-memory condition?</li>\n</ul></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-16T03:59:56.047", "Id": "475635", "Score": "0", "body": "This is the first time I ever hear of _doxygen_ - I think the claim _it's the quasi-standard of documentation_ (on it's homepage) is wildly exaggerated, and I don't think it's that great a recommendation to give." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-16T04:59:53.823", "Id": "475640", "Score": "0", "body": "@Aganju It is surely *mandatory* to document your work in a professional environment, and the general idea to do so *in the source code* is surely superior to separate documents: It is closer to to the subject of documentation and hence less likely to be wrong, and it avoids creating a parallel tree of files which must be maintained. Doxygen has the added bonus to be machine readable so that it can be checked for miss-spelled or undocumented parameters etc. This is supported by IDEs like MS VS. What have you used in your professional projects instead? What would you recommend instead?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-16T05:25:01.960", "Id": "475643", "Score": "0", "body": "My point was not about the merits of doxygen, but about the claim of it being 'the quasi standard', which is at best wishful thinking. - i have used many different concepts, for 38 years, changing ever so often, and basically all homegrown. I think there simply is no accepted 'typical' way to document in the software world, just general concepts and ideas, and a million implementations of them." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-16T05:39:38.643", "Id": "475646", "Score": "0", "body": "@Aganju If you have 10 homegrown systems and one 3rd party solution that is used frequently in the field by multiple players, the 1 is the de-facto standard. The other ones are proprietary solutions. I'm astonished that you never came across doxygen in 38 years. What is (or was) your field of software expertise/occupation? (I have seen doxygen in automotive (infotainment) and transportation.)" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-14T09:54:33.313", "Id": "242256", "ParentId": "242231", "Score": "3" } }, { "body": "<p>Your stack implementation is terrible, and so is <a href=\"https://codereview.stackexchange.com/a/242232/8999\">@hc_dev</a>: neither handles memory correctly.</p>\n\n<h3>Resource Handling</h3>\n\n<p>It is generally frowned upon to call <code>new</code> and <code>delete</code> directly, simply because doing it <em>correctly</em> is hard.</p>\n\n<p>Proper resource handling requires:</p>\n\n<ul>\n<li>Thinking about moves.</li>\n<li>Thinking about copies.</li>\n<li>Thinking about destruction.</li>\n</ul>\n\n<p>This used to be called the <a href=\"https://en.wikipedia.org/wiki/Rule_of_three_(C%2B%2B_programming)\" rel=\"noreferrer\">Rule of 3</a> in C++03 (Copy Constructor, Copy Assignment Operator and Destructor) and is called the Rule of 5 since C++11 (+Move Constructor, +Move Assignment Operator).</p>\n\n<p>Your current Stack implements neither of those 5 operations correctly -- it doesn't implement them at all, and the default generated operations are buggy due to your use of a raw pointer.</p>\n\n<p>The best advice for resource handling, though, is to use the <strong>Rule of Zero</strong>: just delegate it to something that works!</p>\n\n<p>In your case, look into <code>std::unique_ptr</code> and <code>std::make_unique</code>!</p>\n\n<p>Corrected resource management:</p>\n\n<pre><code>struct StackElement {\n char value;\n std::unique_ptr&lt;StackElement&gt; next;\n\n StackElement(char value, std::unique_ptr&lt;StackElement&gt; next) : \n value(value), next(std::move(next)) {}\n};\n\nstruct Stack {\n std::unique_ptr&lt;StackElement&gt; top = nullptr;\n\n bool isEmpty() { return top == nullptr; }\n\n void push(char value) {\n top = std::make_unique&lt;StackElement&gt;(value, std::move(top));\n }\n\n char pop() {\n assert(!isEmpty());\n\n char toBeReturned = top-&gt;value;\n\n top = std::move(top-&gt;next);\n\n return toBeReturned;\n }\n};\n</code></pre>\n\n<p>This <code>struct</code> is no longer copiable, as <code>std::unique_ptr</code> is not copiable.</p>\n\n<h3>Limited stack depth.</h3>\n\n<p>The previous rewrite is good, but its destructor suffers from stack overflow (!).</p>\n\n<p>That is, when the destructor is executed, you get:</p>\n\n<ul>\n<li>Call destructor of <code>Stack</code></li>\n<li>Call destructor of <code>Stack::top</code></li>\n<li>Call destructor of <code>StackElement</code> (<code>stack-&gt;top</code>)</li>\n<li>Call destructor of <code>StackElement::next</code>.</li>\n<li>Call destructor of <code>StackElement</code> (<code>stack-&gt;top-&gt;next</code>)</li>\n<li>...</li>\n</ul>\n\n<p>To handle this, create a <code>clear</code> method, and manually write the destructor.</p>\n\n<pre><code>struct Stack {\n // ...\n\n Stack(Stack&amp;&amp;) = default; // automatic generation is disabled when\n // the destructor is explicit, so explicitly\n // ask for it.\n\n Stack&amp; operator=(Stack&amp;&amp;) = default; // automatic generation...\n\n ~Stack() { clear(); }\n\n void clear() {\n while (!isEmpty()) {\n pop();\n }\n }\n};\n</code></pre>\n\n<h3>General</h3>\n\n<p>Once you have the memory part correct, further improvements:</p>\n\n<ul>\n<li>Encapsulation: do not expose your privates.</li>\n<li>Generalization: make it work for any type.</li>\n</ul>\n\n<p>This yields:</p>\n\n<pre><code>// No need for a class here, it's internal.\ntemplate &lt;typename T&gt;\nstruct StackElement {\n StackElement(T value, std::unique_ptr&lt;StackElement&gt; next):\n value(std::move(value)), next(std::move(next)) {}\n\n T value;\n std::unique_ptr&lt;StackElement&lt;T&gt;&gt; next;\n};\n\ntemplate &lt;typename T&gt;\nclass Stack {\npublic:\n ~Stack() { this-&gt;clear(); }\n\n Stack() = default;\n\n Stack(Stack&amp;&amp;) = default;\n Stack&amp; operator=(Stack&amp;&amp;) = default;\n\n bool isEmpty() const { return this-&gt;head == nullptr; }\n\n T const&amp; top() const {\n assert(!this-&gt;isEmpty());\n\n return this-&gt;head-&gt;value;\n }\n\n void clear() {\n while (!isEmpty()) {\n this-&gt;pop();\n }\n }\n\n void push(T value) {\n // Create empty node first, in case moving `value` throws an exception.\n auto neo = std::make_unique&lt;StackElement&lt;T&gt;&gt;(std::move(value), nullptr);\n\n neo-&gt;next = std::move(this-&gt;head);\n this-&gt;head = std::move(neo);\n }\n\n T pop() {\n assert(!isEmpty());\n\n // Pop top first, in case moving `current-&gt;value` throws an exception.\n auto current = std::move(this-&gt;head);\n this-&gt;head = std::move(current-&gt;next);\n\n return std::move(current-&gt;value);\n }\n\nprivate:\n std::unique_ptr&lt;StackElement&lt;T&gt;&gt; head;\n};\n</code></pre>\n\n<h3>Miscellaneous</h3>\n\n<p>There are few nits in your <code>main</code>:</p>\n\n<ul>\n<li>There is no need to allocate <code>Stack</code> on the heap, just <code>Stack stack;</code> works.</li>\n<li>Don't use <code>std::endl</code>, just use <code>'\\n'</code> or <code>\"\\n\"</code>.\n\n<ul>\n<li><code>std::endl</code> <em>both</em> appends <code>\\n</code> <em>and</em> calls <code>flush</code>, the latter kills all performance benefit of internally buffering.</li>\n</ul></li>\n</ul>\n\n<p>With that in mind, the rewritten <code>main</code> is:</p>\n\n<pre><code>int main() {\n Stack&lt;char&gt; stack;\n std::cout &lt;&lt; \"Created a stack at \" &lt;&lt; &amp;stack &lt;&lt; \"\\n\";\n\n int number_of_inputs;\n std::cout &lt;&lt; \"Enter the number of elements you want to push at the stack: \";\n std::cin &gt;&gt; number_of_inputs;\n\n for (int i = 0; i &lt; number_of_inputs; i++) {\n char input;\n std::cin &gt;&gt; input;\n stack.push(input);\n }\n\n std::cout &lt;&lt; \"- - - - - - - - - - - - - - - - \" &lt;&lt; \"\\n\";\n std::cout &lt;&lt; \"Displaying content of the stack: \" &lt;&lt; \"\\n\";\n\n while (!stack.isEmpty()) {\n std::cout &lt;&lt; stack.pop() &lt;&lt; \"\\n\";\n }\n\n return 0;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-14T12:51:16.173", "Id": "475425", "Score": "0", "body": "I highly appreciate your detailed explanation. Thank you. However, if I wanted to use STL, I'd just #include <stack> and that'd be it. I'm doing this to learn myself a bit about dynamic data structures in CPP and want to do it using raw pointers and not those \"cool\" shared and unique ones." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-14T14:41:37.157", "Id": "475433", "Score": "4", "body": "@Baftek: Then my advice is _Separation of Responsibility_. The `Stack` class is already managing the stack logic, it should _not_ also fiddle with low-level new/delete. Instead, you should create a `Box`, `Ptr`, `unique_ptr` class that handles those low-level details correctly, and then implement `Stack` on top. `Box` will handle the technical details of managing a resource (memory, here), and `Stack` will handle the functional details of implementing a stack. This means you can test `Box` in isolation, and in `Stack` you don't have to worry about those details any longer." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-14T16:25:30.370", "Id": "475452", "Score": "3", "body": "@hc_dev: Please don't take the \"blame\" personally, it's your answer I warn against, not you. As for C++ books, and online tutorials, unfortunately most are terrible or terribly outdated. A [curated list of known good books](https://stackoverflow.com/a/388282/147192) is maintained on Stack Overflow, and even helpfully \"sorts\" the books for various levels of expertise. If you have the choice, pick one of those." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-14T19:07:40.800", "Id": "475470", "Score": "0", "body": "Appreciate the book list! Followed the mentioned [rules-of-thumb](https://en.wikipedia.org/wiki/Rule_of_three_(C%2B%2B_programming)) and added a link. Researching about _Garbage Collection_ I found background info to mentioned [Smart Pointers](https://en.wikipedia.org/wiki/Smart_pointer) in another answer of you: [Why doesn't C++ have a garbage collector? - Stack Overflow](https://stackoverflow.com/questions/147130/why-doesnt-c-have-a-garbage-collector/2326748#2326748)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-14T22:11:22.333", "Id": "475493", "Score": "0", "body": "Please don't recommend to blanket avoid `std::endl` it's always correct but might not be the fastest option. On the contrary `\\n` may be wrong in some situations, e.g. when writing logs, you want the flush so you get the last message before the crash. Also see: https://stackoverflow.com/a/25569849/2498188" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-15T04:57:35.633", "Id": "475521", "Score": "1", "body": "@Emily Surely, for logging, you should be using an *unbuffered* stream, like `std::clog`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-15T08:38:31.150", "Id": "475536", "Score": "0", "body": "After turning the stack into a template, would you consider changing the signature of `push` to `push(T& value)` in order to avoid unnecessary copying (assuming that the typical T is costlier to copy than a pointer)? Would it make sense to also provide a `push(T&&)` to efficiently push rvalues? Last: Would it make sense to permit (deep) copying a stack, like with the standard containers?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-15T08:58:13.137", "Id": "475538", "Score": "0", "body": "@Peter-ReinstateMonica: I generally go with \"Want Speed? Pass by Value!\". It's simple, and will serve beginner and intermediate C++ programmers well for a surprisingly long time." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-15T09:00:06.567", "Id": "475540", "Score": "0", "body": "@Peter-ReinstateMonica: Yes, deep-copying is a good exercise. However, since the OP didn't implement it, I don't want to overwhelm them. With access to the internals it's relatively simple (O(N))." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-15T17:46:39.453", "Id": "475596", "Score": "0", "body": "When you say \"pass by value for speed\", do you mean for small objects like you might keep in a stack? Or is that because in this case you'd have to make a copy inside `push` instead of `std::move` if you had a reference to the caller's object? If not for that, const reference is still good for passing around `std::vector` and maybe `std::string`, right?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-15T21:39:08.160", "Id": "475614", "Score": "3", "body": "@PeterCordes Pass by reference-to-const is only faster if the function doesn't need to copy or mutate the referenced object. If it does, then you're stuck always doing a full copy and never a move. Pass by value allows the caller the flexibility to have the object be copied or moved as appropriate. The alternative is to have two overloads: one that accepts its parameter by reference-to-const and one that accepts its parameter by rvalue-reference." } ], "meta_data": { "CommentCount": "11", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-14T10:28:08.137", "Id": "242262", "ParentId": "242231", "Score": "20" } } ]
{ "AcceptedAnswerId": "242262", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-13T23:50:22.100", "Id": "242231", "Score": "9", "Tags": [ "c++", "beginner", "stack" ], "Title": "Simple Stack implementation in C++" }
242231
<p>Doing <a href="https://github.com/rust-lang/rustlings/blob/master/exercises/conversions/from_into.rs" rel="nofollow noreferrer">this Rustlings</a> I find I'm unhappy with the code I wrote,</p> <pre><code>let person: Person = args.next() .unwrap_or_default() .parse::&lt;usize&gt;() .map_or_else( |age| Person{ age, name }, || Person::default() ); </code></pre> <p>What I want is something like</p> <pre><code>let person: Person = args.next() .unwrap_or_default() .parse::&lt;usize&gt;() .unwrap_or_default() .map_magic( |age| Person { name, age } ) </code></pre> <p>That would make me happy. Any other ideas on how I can clean up? I guess I just really want to use <code>unwrap_or_default()</code> twice. I can call <code>.parse</code> on a <code>&amp;str</code>. I want to be able to call .map on an int.</p> <pre><code>.map(|age| Person { age, name }); ^^^ method not found in `usize` </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-14T16:17:35.960", "Id": "475449", "Score": "1", "body": "Welcome to Code Review! Unfortunately this question is not [on-topic](https://codereview.stackexchange.com/help/on-topic) because the code is not working. as expected.. Please inform yourself, [take the tour](https://codereview.stackexchange.com/tour), and read up at our [help center](https://codereview.stackexchange.com/help/on-topic) before posting here. When the code works as expected then feel free to [edit] your post to include it for a review." } ]
[ { "body": "<p>Just switch the order, <a href=\"https://doc.rust-lang.org/std/result/enum.Result.html#method.map\" rel=\"nofollow noreferrer\"><code>.map()</code> on an result is documented as</a></p>\n\n<blockquote>\n <p>Maps a Result to Result by applying a function to a contained Ok value, <strong>leaving an Err value untouched.</strong></p>\n</blockquote>\n\n<pre><code>let person: Person = args\n .next()\n .unwrap_or_default()\n .parse::&lt;usize&gt;()\n .map(|age| Person { age, name })\n .unwrap_or_default();\n</code></pre>\n\n<hr>\n\n<p><em>thanks goes out to GreenJello on irc.freenode.net/##rust for the help</em></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-14T04:07:40.340", "Id": "475375", "Score": "1", "body": "Could you go a step further and also ignore the first `unwrap_or_default()` by doing the parse inside a map?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-14T04:20:33.210", "Id": "475376", "Score": "0", "body": "I asked the same question, 22:18 < GreenJello> you could do this, but I don't think it's better: `args.next().and_then(|arg| arg.parse::<usize>().ok()).map(|age| Person { name, age }).unwrap_or_default()`" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-14T03:13:11.343", "Id": "242239", "ParentId": "242235", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-14T02:39:07.797", "Id": "242235", "Score": "-1", "Tags": [ "rust" ], "Title": "Return a default object unless you get Some( Ok() )" }
242235
<p>The <strong>Cantor Pairing function</strong> is a mathematical function which takes two integers and combines them into a single integer that is unique to that pair. This single integer can later be "unpaired" back into the two original, separate integers. Further information on this function can be found <a href="https://en.wikipedia.org/wiki/Pairing_function" rel="nofollow noreferrer">here</a> and <a href="http://szudzik.com/ElegantPairing.pdf" rel="nofollow noreferrer">here</a>.</p> <p>The Cantor pairing function can be used to pair more than just two integers together, however this must be done in a smart manner, as the size of the output of this function can jump to astronomical levels very, very quickly, which explains why I'm using Java's <code>BigInteger</code> class in my code.</p> <p>I've written a small utility-type class in Java which contains one method capable of recursively pairing two or more integers, and another method that can unpair a single integer back into <em>n</em> original integers (along with two private helper methods):</p> <pre><code>package pairing; import java.math.BigInteger; import java.util.Arrays; public class CantorPair { private CantorPair() { } // This method recursively pairs two or more integers into a single, unique integer public static BigInteger pair(final BigInteger... integers) { final int n = integers.length; if (n == 0) throw new IllegalArgumentException("Argument list length cannot be zero!"); final BigInteger x = integers[0]; if (n == 1) return x; final BigInteger y = integers[1]; // If we've only been given two integers, we can pair them together and return the result! if (n == 2) { final BigInteger sum = x.add(y); return sum.add(BigInteger.ONE).multiply(sum).divide(BigInteger.TWO).add(y); } // I've found that using a parallel stream here reduces the computation time significantly when pairing a large number of integers return pair(Arrays.stream(makePairs(integers)).map(CantorPair::pair).parallel().toArray(BigInteger[]::new)); } // This method recursively unpairs an integer into [n] separate integers public static BigInteger[] unpair(final BigInteger integer, final int n) { if (n &lt; 1) throw new IllegalArgumentException("Argument list length cannot be less than one!"); if (n == 1) return new BigInteger[]{integer}; if (n == 2) { final BigInteger i = integer.multiply(BigInteger.valueOf(8)).add(BigInteger.ONE).sqrt() .subtract(BigInteger.ONE) .divide(BigInteger.TWO); return new BigInteger[]{ i.add(BigInteger.valueOf(3)).multiply(i).divide(BigInteger.TWO).subtract(integer), integer.subtract(i.add(BigInteger.ONE).multiply(i).divide(BigInteger.TWO)) }; } final BigInteger[] result = new BigInteger[n]; final BigInteger[] splitIntegers = unpair(integer, 2); final int nearestPowerOfTwo = nearestPowerOfTwo(n); if (n == nearestPowerOfTwo) { System.arraycopy(unpair(splitIntegers[0], n / 2), 0, result, 0, n / 2); System.arraycopy(unpair(splitIntegers[1], n / 2), 0, result, n / 2, n / 2); } else { System.arraycopy(unpair(splitIntegers[0], n - (n - nearestPowerOfTwo)), 0, result, 0, (n - (n - nearestPowerOfTwo))); System.arraycopy(unpair(splitIntegers[1], n - nearestPowerOfTwo), 0, result, (n - (n - nearestPowerOfTwo)), n - nearestPowerOfTwo); } return result; } // This method splits an array of integers into groups of two private static BigInteger[][] makePairs(final BigInteger[] inputList) { final BigInteger[][] result = new BigInteger[(int) Math.ceil(inputList.length / 2.0)][]; for (int i = 0; i &lt; inputList.length; i += 2) result[i / 2] = (i == inputList.length - 1) ? new BigInteger[]{inputList[i]} : new BigInteger[]{inputList[i], inputList[i + 1]}; return result; } // This method returns the nearest power of two that is less than or equal to [x] private static int nearestPowerOfTwo(int x) { x |= x &gt;&gt; 1; x |= x &gt;&gt; 2; x |= x &gt;&gt; 4; x |= x &gt;&gt; 8; x |= x &gt;&gt; 16; return x ^ (x &gt;&gt; 1); } </code></pre> <p>I am quite happy with the <code>pair</code> method, as I have used it to pair lists of 100000+ integers nearly instantly on my machine, however the <code>unpair</code> method does not preform nearly as well, especially once it is tasked with unpairing large integers. The computation time for this second method is long enough that I've used a stopwatch to time it - Integer lists which take the <code>pair</code> method ~1 second to complete take the <code>unpair</code> method more than 15 seconds to unpair. I've written a small test Class below which illustrates this fact (the variable <code>numberOfIntegersToPair</code> can be adjusted to change how many integers are paired/unpaired):</p> <pre><code>package main; import java.math.BigInteger; import java.util.stream.IntStream; import pairing.CantorPair; public class Main { public static void main(String[] args) { // Around 100000 is where I really begin to notice a slowdown on my machine // Pairing completes instantly, but unpairing takes about 16 seconds // The time difference between the two continues to noticeably increase after this int numberOfIntegersToPair = 100000; // Make an array containing [numberOfIntegersToPair] integers BigInteger[] bigIntegers = IntStream.range(0, numberOfIntegersToPair) .mapToObj(BigInteger::valueOf) .toArray(BigInteger[]::new); System.out.println("Starting to pair..."); // Let's pair our integer list and store the result BigInteger pairedIntegers = CantorPair.pair(bigIntegers); System.out.println("Done pairing!"); System.out.println("Starting to unpair..."); // Now let's unpair our large integer back into the smaller integers that formed it // As the [numberOfIntegersToPair] increases, this function will begin to take significantly longer to complete BigInteger[] unpairedIntegers = CantorPair.unpair(pairedIntegers, bigIntegers.length); System.out.println("Done unpairing!"); } } </code></pre> <p>I've tried to optimize this code as much as I know how (parallel streams, System.arraycopy instead of manual array copys, the use of arrays over lists wherever possible, etc.), and my adjustments have helped a bit (they helped speed up the <code>pair</code> function a lot), but I am unable to speed up the <code>unpair</code> method any further on my own. Perhaps there is nothing that can be done, but I'm open to any and all suggestions.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-14T14:59:11.383", "Id": "475440", "Score": "1", "body": "I have seen in your pdf link an alternative method called elegantpair, it has the same performance of your method ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-14T16:43:02.790", "Id": "475455", "Score": "0", "body": "@dariosicily Very similar performance, yes, I actually just tried it out (it sped up the unpair function by about 1-2 seconds). Although the \"elegantpair\" function requires fewer calculations to pair/unpair, it produces numbers which are larger than the Cantor function that I used above, which ultimately causes the calculations to take about the same time." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-14T17:09:26.230", "Id": "475461", "Score": "0", "body": "Ok, the only thing I'm seeing at the moment is it is possible to create variables inside the method to store repeatition of operations I'm seeing in the copy of array and maybe some other minor changes, but I doubt you can see a great improvement after modifies. Anyway I will submit an answer with my modifies , but I doubt it will help you with performance." } ]
[ { "body": "<p>Some minor changes can be applied to your <code>unpair</code> function, you have the following code in the body of 'unpair':</p>\n\n<blockquote>\n<pre><code>final BigInteger i = integer.multiply(BigInteger.valueOf(8)).add(BigInteger.ONE).sqrt()\n .subtract(BigInteger.ONE)\n .divide(BigInteger.TWO);\nreturn new BigInteger[]{\n i.add(BigInteger.valueOf(3)).multiply(i).divide(BigInteger.TWO).subtract(integer),\n integer.subtract(i.add(BigInteger.ONE).multiply(i).divide(BigInteger.TWO))\n};\n</code></pre>\n</blockquote>\n\n<p>You can store <code>BigInteger.valueOf(8)</code> and <code>BigInteger.valueOf(3)</code> into two constants to reuse in your calls:</p>\n\n<pre><code>private static final BigInteger EIGHT = BigInteger.valueOf(8);\nprivate static final BigInteger THREE = BigInteger.valueOf(3);\n</code></pre>\n\n<p>Similar approach for this code present in your function:</p>\n\n<blockquote>\n<pre><code>if (n == nearestPowerOfTwo) {\n System.arraycopy(unpair(splitIntegers[0], n / 2), 0, result, 0, n / 2);\n System.arraycopy(unpair(splitIntegers[1], n / 2), 0, result, n / 2, n / 2);\n} else {\n System.arraycopy(unpair(splitIntegers[0], n - (n - nearestPowerOfTwo)), 0, result, 0, (n - (n - nearestPowerOfTwo)));\n System.arraycopy(unpair(splitIntegers[1], n - nearestPowerOfTwo), 0, result, (n - (n - nearestPowerOfTwo)), n - nearestPowerOfTwo);\n}\n</code></pre>\n</blockquote>\n\n<p>You can create variables storing repeated operations:</p>\n\n<pre><code>if (n == nearestPowerOfTwo) {\n final int halfN = n / 2;\n System.arraycopy(unpair(splitIntegers[0], halfN), 0, result, 0, halfN);\n System.arraycopy(unpair(splitIntegers[1], halfN), 0, result, halfN, halfN);\n} else {\n System.arraycopy(unpair(splitIntegers[0], nearestPowerOfTwo), 0, result, 0, nearestPowerOfTwo);\n final int nMinusNearestPowerOfTwo = n - nearestPowerOfTwo;\n System.arraycopy(unpair(splitIntegers[1], nMinusNearestPowerOfTwo), 0, result, nearestPowerOfTwo, nMinusNearestPowerOfTwo);\n}\n</code></pre>\n\n<p>Probably there is a slight improvement of performance due to the changes, but the core math still remains the same. Below the code of the <code>unpair</code> function modified:</p>\n\n<pre><code>private static final BigInteger EIGHT = BigInteger.valueOf(8);\nprivate static final BigInteger THREE = BigInteger.valueOf(3);\n\n// This method recursively unpairs an integer into [n] separate integers\npublic static BigInteger[] unpair(final BigInteger integer, final int n) {\n if (n &lt; 1)\n throw new IllegalArgumentException(\"Argument list length cannot be less than one!\");\n if (n == 1)\n return new BigInteger[]{integer};\n if (n == 2) {\n final BigInteger i = integer.multiply(EIGHT).add(BigInteger.ONE).sqrt()\n .subtract(BigInteger.ONE)\n .divide(BigInteger.TWO);\n return new BigInteger[]{\n i.add(THREE).multiply(i).divide(BigInteger.TWO).subtract(integer),\n integer.subtract(i.add(BigInteger.ONE).multiply(i).divide(BigInteger.TWO))\n };\n }\n\n final BigInteger[] result = new BigInteger[n];\n final BigInteger[] splitIntegers = unpair(integer, 2);\n\n final int nearestPowerOfTwo = nearestPowerOfTwo(n);\n\n if (n == nearestPowerOfTwo) {\n final int halfN = n / 2;\n System.arraycopy(unpair(splitIntegers[0], halfN), 0, result, 0, halfN);\n System.arraycopy(unpair(splitIntegers[1], halfN), 0, result, halfN, halfN);\n } else {\n System.arraycopy(unpair(splitIntegers[0], nearestPowerOfTwo), 0, result, 0, nearestPowerOfTwo);\n final int nMinusNearestPowerOfTwo = n - nearestPowerOfTwo;\n System.arraycopy(unpair(splitIntegers[1], nMinusNearestPowerOfTwo), 0, result, nearestPowerOfTwo, nMinusNearestPowerOfTwo);\n }\n\n return result;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-14T19:45:13.740", "Id": "475478", "Score": "0", "body": "I know there wasn't much to work with here so I appreciate you taking the time to look through it and sharing these suggestions." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-14T20:15:12.640", "Id": "475479", "Score": "0", "body": "@HomeworkHopper You are welcome." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-14T17:56:16.567", "Id": "242286", "ParentId": "242238", "Score": "1" } } ]
{ "AcceptedAnswerId": "242286", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-14T03:12:51.370", "Id": "242238", "Score": "1", "Tags": [ "java", "performance", "array", "recursion" ], "Title": "Speeding up a recursive Cantor pairing function" }
242238
<pre><code>TA.ServiceProxy.RoleManagement.GetSubPrivilagesResponses subPrivilagesResponses = GetSubPrivilagesFromPrivilageCodeStatic("Authoring01"); if (subPrivilagesResponses != null &amp;&amp; subPrivilagesResponses.SubprivilagesList != null) { for (int j = 0; j &lt; subPrivilagesResponses.SubprivilagesList.Length; j++) { if (subPrivilagesResponses.SubprivilagesList[j].PrivilageCode == "CREATOR") { objTemplate.IsTagged = true; break; } } } </code></pre> <p>The above code is written as</p> <pre><code>TA.ServiceProxy.RoleManagement.GetSubPrivilagesResponses subPrivilagesResponses = GetSubPrivilagesFromPrivilageCodeStatic("Authoring01"); if (subPrivilagesResponses != null &amp;&amp; subPrivilagesResponses.SubprivilagesList != null) { var item = subPrivilagesResponses.SubprivilagesList.SingleOrDefault(cd =&gt; cd.PrivilageCode == "CREATOR"); if(item != null &amp;&amp; item.PrivilageCode == "CREATOR") objTemplate.IsTagged = true; } </code></pre> <p>In what are the different way it can be modified in order to boost performance and efficiency by making use of Lambda or LINQ</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-14T08:30:39.437", "Id": "475398", "Score": "2", "body": "The first version finds the first of possible more items having `PrivilageCode == \"CREATOR\"`, while the second actually ensures that there is only one (or none) item having that predicate - if more items satisfy the condition a `ThrowMoreThanOneMatchException` exception is thrown. So they are not doing the exact same thing. Which one is the correct/preferred?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-14T09:41:08.460", "Id": "475410", "Score": "0", "body": "Good Catch. It will always be only one or none. Apart from `SingleOrDefault`. What are all possible ways to match `PrivilageCode == \"CREATOR\"`. I mean to say how can the above snippet can be rewritten in different possible ways to yield the above condition. Even I or the readers would benefit a lot @HenrikHansen" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-14T17:06:40.777", "Id": "475460", "Score": "0", "body": "do you actually have any performance issue with the current code ? if yes, then please explain what is the issue, and where it happens. (include any code if any)." } ]
[ { "body": "<p>The only think that comes to my mind is to rewrite this:</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>var item = subPrivilagesResponses.SubprivilagesList.SingleOrDefault(cd =&gt; cd.PrivilageCode == \"CREATOR\");\n if(item != null &amp;&amp; item.PrivilageCode == \"CREATOR\")\n objTemplate.IsTagged = true; \n</code></pre>\n\n<p>into this:</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>if (subPrivilagesResponses.SubprivilagesList.Any(cd =&gt; cd.PrivilageCode == \"CREATOR\"))\n objTemplate.IsTagged = true;\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-14T08:38:44.150", "Id": "475399", "Score": "2", "body": "You could set `objTemplate.IsTagged` to equal `...Any()` directly instead of the `if`-statement." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-14T07:08:08.193", "Id": "242246", "ParentId": "242240", "Score": "2" } }, { "body": "<p>If you're using C#6 or above, you can use the <a href=\"https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/operators/member-access-operators#null-conditional-operators--and-\" rel=\"nofollow noreferrer\">null conditional operator <code>?.</code></a>:</p>\n\n<pre><code>var hasCreator = GetSubPrivilagesFromPrivilageCodeStatic(\"Authoring01\")?.SubprivilagesList?.Any(cd =&gt; cd.PrivilageCode == \"CREATOR\") ?? false;\nif (hasCreator) \n{\n objTemplate.IsTagged = true;\n}\n</code></pre>\n\n<p>If it's not too late, I'd correct the spelling of privilege in your code. I misspelt latitude (as lattitude) in some key js once and frustrated my colleagues for years.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-14T17:04:41.400", "Id": "475459", "Score": "0", "body": "you could inline it with `objTemplate.IsTagged` directly." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-14T07:47:39.100", "Id": "242249", "ParentId": "242240", "Score": "3" } }, { "body": "<p>Because the question is about <strong>performance</strong> and <strong>efficiency</strong> that's why some sort of benchmarking would be essential to compare different implementations. I have found <a href=\"https://www.nuget.org/packages/BenchmarkDotNet/\" rel=\"noreferrer\">BenckmarkDotNet</a> really useful for these kind of experiments. </p>\n\n<p>You can define the for loop version as your <strong>baseline</strong> and the tool will compare the other implementation against that. Here is my simplified example how to setup your environment for measurement:</p>\n\n<pre><code>[HtmlExporter]\n[MemoryDiagnoser]\n[SimpleJob(BenchmarkDotNet.Engines.RunStrategy.ColdStart, targetCount: 100)]\npublic class IterationOptimalizationExperiment\n{\n private static List&lt;Data&gt; target;\n private const string TheOne = \"TheOne\";\n\n [GlobalSetup]\n public void Setup()\n {\n target = Enumerable.Range(0, 10000)\n .Select(i =&gt; new Data { Id = i, Type = i % 7777 == 0 ? TheOne : \"NotTheOne\" })\n .ToList();\n }\n\n [Benchmark(Baseline = true)]\n public void WithFor()\n {\n bool hasFound = false;\n for (int i = 0; i &lt; target.Count; i++)\n if (string.Equals(target[i].Type, TheOne, StringComparison.OrdinalIgnoreCase))\n {\n hasFound = true;\n break;\n }\n\n }\n\n [Benchmark]\n public void WithForEach()\n {\n bool hasFound = false;\n foreach (var t in target)\n if (string.Equals(t.Type, TheOne, StringComparison.OrdinalIgnoreCase))\n {\n hasFound = true;\n break;\n }\n }\n\n [Benchmark]\n public void WithAny()\n {\n bool hasFound = target.Any(t =&gt; string.Equals(t.Type, TheOne, StringComparison.OrdinalIgnoreCase));\n }\n}\n</code></pre>\n\n<p>And you should simply call the following command to start your experiment: <code>BenchmarkRunner.Run&lt;IterationOptimalizationExperiment&gt;();</code></p>\n\n<p>When you run it in Release mode it will dump something like this:\n<a href=\"https://i.stack.imgur.com/o6GnN.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/o6GnN.png\" alt=\"enter image description here\"></a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-14T09:06:42.860", "Id": "242254", "ParentId": "242240", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-14T05:18:50.787", "Id": "242240", "Score": "4", "Tags": [ "c#", "linq", "lambda" ], "Title": "Finding the string from the list of array objects" }
242240
<p>Here is a Java Spring web application built as an educational project that fetches and displays data returned from NASA's Mars Weather Service API. The project is essentially an attempt to reverse engineer this page: <a href="https://mars.nasa.gov/insight/weather/" rel="nofollow noreferrer">https://mars.nasa.gov/insight/weather/</a>.</p> <p>GitHub repository: <a href="https://github.com/jkey774/mars-insight-weather" rel="nofollow noreferrer">https://github.com/jkey774/mars-insight-weather</a></p> <p>Example API payload: <a href="https://github.com/jkey774/mars-insight-weather/blob/master/src/main/java/com/springboot/app/InsightWeather/ExampleJSON.json" rel="nofollow noreferrer">https://github.com/jkey774/mars-insight-weather/blob/master/src/main/java/com/springboot/app/InsightWeather/ExampleJSON.json</a>.</p> <p>Live demo: <a href="https://mars-insight-weather.herokuapp.com/" rel="nofollow noreferrer">https://mars-insight-weather.herokuapp.com/</a> </p> <p>Note the app is running on a free dyno so it can be slow to load if the application goes to sleep from being unused for some period of time and is not related to code quality.</p> <p>1) Have I built the application in a way that is acceptable within the Spring framework? Am I making proper use of Dependency Injection? Do you see any anti-patterns?</p> <p>2) Should I have implemented Interfaces with the different classes (i.e. Sol, AirTemperature, AirPressure, WindSpeed, WindDirection) <a href="https://github.com/jkey774/mars-insight-weather/tree/master/src/main/java/com/springboot/app/InsightWeather" rel="nofollow noreferrer">https://github.com/jkey774/mars-insight-weather/tree/master/src/main/java/com/springboot/app/InsightWeather</a></p> <p>3) Does the project seem scalable and extensible? If not, how could I make it more so? Here is the Controller class and primary Component class</p> <pre><code>@Controller public class SolsController { @GetMapping("/") public String sols(@RequestParam(name="sols", required=false, defaultValue="") String name, Model model) throws IOException { RestTemplateBuilder restTemplateBuilder = new RestTemplateBuilder(); RestService restService = new RestService(restTemplateBuilder); ObjectMapper objectMapper = new ObjectMapper(); JsonNode rootNode = objectMapper.readTree(restService.getSols()); JsonNode solKeyNodes = rootNode.get("sol_keys"); Iterator&lt;JsonNode&gt; solKeys = solKeyNodes.elements(); ArrayNode solsData = objectMapper.createArrayNode(); ObjectNode lastSolNode = null; int i = 0; while (solKeys.hasNext()) { String solKey = solKeys.next().asText(); ObjectNode sol = objectMapper.convertValue(rootNode.path(solKey), ObjectNode.class); sol.put("id", solKey); solsData.add(sol); if (i == solKeyNodes.size() - 1) { lastSolNode = sol; } i++; } Sol mostRecentSol = objectMapper.convertValue(lastSolNode, Sol.class); model.addAttribute("mostRecentSol", mostRecentSol); Sol[] sols = objectMapper.convertValue(solsData, Sol[].class); model.addAttribute("solsCalendar", sols); model.addAttribute("solsTable", reverseSols(sols, sols.length)); return "sols"; } private static Sol[] reverseSols(Sol[] original, int length) { Sol[] reversed = new Sol[length]; int j = length; for (int i = 0; i &lt; length; i++) { reversed[j - 1] = original[i]; j -= 1; } return reversed; } } </code></pre> <hr> <pre><code>@Component @JsonIgnoreProperties(ignoreUnknown = true) public class Sol implements Serializable { private String id; private String earthDateTimestamp; private EarthDate earthDate; private ObjectNode airTemperatureData; private AirTemperature airTemperature; private ObjectNode airPressureData; private AirPressure airPressure; private ObjectNode windSpeedData; private WindSpeed windSpeed; private ObjectNode windDirectionData; private WindDirection windDirection; public Sol() {} @JsonCreator public Sol( @JsonProperty("id") String id, @JsonProperty("First_UTC") String earthDateTimestamp, @JsonProperty("AT") ObjectNode airTemperatureData, @JsonProperty("PRE") ObjectNode airPressureData, @JsonProperty("HWS") ObjectNode windSpeedData, @JsonProperty("WD") ObjectNode windDirectionData ) { this.id = id; this.earthDateTimestamp = earthDateTimestamp; this.airTemperatureData = airTemperatureData; this.airPressureData = airPressureData; this.windSpeedData = windSpeedData; this.windDirectionData = windDirectionData; } public String getId() { return id; } public void setId(String id) { this.id = id; } public EarthDate getEarthDate() { return new EarthDate(this.earthDateTimestamp); } public void setEarthDate() { this.earthDate = new EarthDate(this.earthDateTimestamp); } public AirTemperature getAirTemperature() { return new AirTemperature(this.airTemperatureData); } public void setAirTemperature() { this.airTemperature = new AirTemperature(this.airTemperatureData); } public AirPressure getAirPressure() { enter code herereturn new AirPressure(this.airPressureData); } public void setAirPressure() { this.airPressure = new AirPressure(this.airPressureData); } public WindSpeed getWindSpeed() { return new WindSpeed(this.windSpeedData); } public void setWindSpeed() { this.windSpeed = new WindSpeed(this.windSpeedData); } public WindDirection getWindDirection() { return new WindDirection(this.windDirectionData); } public void setWindDirection() { this.windDirection = new WindDirection(this.windDirectionData); } } </code></pre> <p>4) In src/main/java/com/springboot/app/InsightWeather/Sol.java this class implements Serializable. This worked well with Thymeleaf's 'for each' templating, but could implementing Serializable be frowned upon?</p> <pre><code>public class Sol implements Serializable </code></pre> <p>...</p> <pre><code>&lt;div class="item" th:each="sol : ${solsCalendar}"&gt; &lt;span class="dateSol" th:text="${'Sol ' + sol.id}"&gt;&lt;/span&gt; </code></pre> <p>5) "I don't know what I don't know." Is there anything else not listed above that you feel is worth mentioning in terms of performance, security, or overall setup?</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-14T06:44:16.860", "Id": "242244", "Score": "2", "Tags": [ "java", "spring" ], "Title": "Java Spring web application" }
242244
<p>I have the following code, made in C language, which reproduces the functionality of the mv (move) command from linux. The problem is that the code is very inefficient. How I can optimize or make the code more efficient without changing the structure too much?</p> <pre><code>#include &lt;limits.h&gt; #include &lt;fcntl.h&gt; #include "ourhdr.h" #include &lt;sys/stat.h&gt; #include &lt;dirent.h&gt; int main(int argc,char *argv[]) { if(argc!=3) { printf("&lt;Sintaxa&gt; &lt;fisier sursa&gt; &lt;fisier destinatie&gt; \n"); exit(1); } int ren1,ren2; struct stat buf1; struct stat buf2; lstat(argv[2],&amp;buf1); lstat(argv[1],&amp;buf2); char src[PATH_MAX]; strcpy(src,argv[1]); char dst[PATH_MAX]; strcpy(dst,argv[2]); int src_size = (int)strlen(src); int dst_size = (int)strlen(dst); dst[dst_size] = '/'; dst[dst_size + 1] = '\0'; dst_size++; int i; int index=0; int index1=src_size; while(--index1&gt;0) { if(src[index1]=='/') { index1=0; } else index++; } for (i = src_size-index-1; i &lt; src_size; i++) { dst[dst_size++] = src[i]; } dst[dst_size] = '\0'; if (access(src,F_OK)==-1) { err_ret("%s: cannot stat '%s'", argv[0],argv[1]); return -1; } if(S_ISDIR(buf1.st_mode)) { if(((S_ISDIR(buf2.st_mode))&amp;&amp;(!(opendir(argv[1]))))||(!(opendir(argv[2])))) { err_quit("%s: cannot move '%s' to '%s': Permission denied \n", argv[0],argv[1],dst); } ren1=rename(src,dst); if(ren1!=0) { err_quit("Error: unable to move the file"); } } else { ren2=rename(argv[1],argv[2]); if(ren2!=0) { err_quit("Error: unable to rename the file "); } } } </code></pre> <p>The code above works fine but is way to inefficient</p>
[]
[ { "body": "<p>This is a small program, so some of the problems are not likely that big. If this were part of the API, problems may stack up and then make an actual difference. </p>\n\n<p>There are several points which you should work on:</p>\n\n<ul>\n<li><code>opendir</code> leak: <code>opendir</code> opens a file descriptor. You open 2 directories, none of which are closed. Make sure to call <code>closedir</code>. If this is part of an API, those memory leaks will stack up. Otherwise, this might not be a problem, since when the process ends, the descriptors should be cleared automatically.</li>\n<li>Error checks: If I were to run this code a lot of times, some of which are intended to end in errors, there would be some clatter due to the positioning of your error checks. Checks like <em>does src exist</em> or <em>can dst dir be accessed</em>, should be done first. This will eliminate the need for some operations. Generally, it is always best to perform error checks first. </li>\n<li>Finding the name: A big part of the code is dedicated to finding the name of the <code>src</code>, and copying it to <code>dst</code>. You might improve it by using built-in functions instead. Use <a href=\"https://www.geeksforgeeks.org/strrchr-function-in-c-c/\" rel=\"nofollow noreferrer\"><code>strrchr</code></a> to find the last <code>/</code> and <a href=\"https://www.tutorialspoint.com/c_standard_library/c_function_strcpy.htm\" rel=\"nofollow noreferrer\"><code>strcpy</code></a> to copy the name.</li>\n</ul>\n\n<p>Maybe there are other possible changes, but that should be the gist of it. Most of those problems have a small effect. This is a small program, so you won't notice must performance changes (unless this is an API).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-15T11:24:12.327", "Id": "242332", "ParentId": "242248", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-14T07:41:33.913", "Id": "242248", "Score": "2", "Tags": [ "performance", "c", "linux" ], "Title": "Reproduce Linux move command in C" }
242248
<p>I have the following code that creates a directory in C. I tested it multiple times, reviewed it a few times and it looks fine at the moment.</p> <p>What I really wanna know is what bugs does it have and how can I fix them ? (comparing it with the <code>mkdir</code> command from linux)</p> <pre><code>#include "ourhdr.h" #include &lt;sys/stat.h&gt; #include &lt;limits.h&gt; #include &lt;dirent.h&gt; int main(int argc, char **argv) { if(argc != 2) { printf("./i78 /locatie/nume_director sau ./i78 nume_director\n"); return 1; } char buff[PATH_MAX]; strcpy(buff,argv[1]); if (mkdir(buff,S_IRWXU|S_IRWXG|S_IRWXO)&lt;0) { printf("%s: cannot create directory '%s': File exists\n",argv[0],buff); } else printf("\n Creare director [%s]\n",buff); } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-14T09:02:27.807", "Id": "475404", "Score": "0", "body": "Please state explicitly, in the question, whether or not [the code presented works as intended, to the best of your knowledge](https://codereview.stackexchange.com/help/on-topic). (`looks fine [from my perspective]` doesn't *quite* cut it in my book.)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-14T10:09:25.190", "Id": "475414", "Score": "0", "body": "@greybeard happy ? that was the last problem of the post" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-14T18:02:07.143", "Id": "475466", "Score": "0", "body": "Fine with me. To be entirely explicit, you could use *Potential bugs in unanticipated cases* (a wording from the on-topic page)." } ]
[ { "body": "<p>There is a potential buffer overflow - the length of <code>argv[1]</code> may be up to <a href=\"https://stackoverflow.com/a/7499490/10396\"><code>ARG_MAX</code></a>, which is likely larger than <code>PATH_MAX</code>.</p>\n\n<p>The \"File Exists\" message may be misleading, <a href=\"http://man7.org/linux/man-pages/man2/mkdir.2.html#ERRORS\" rel=\"nofollow noreferrer\"><code>mkdir</code></a> can also fail because of permissions, out of space, invalid characters in the name, ...</p>\n\n<p>It's good practice to put <code>{</code> <code>}</code> around all conditionals, including the <code>else</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-14T19:08:12.440", "Id": "242291", "ParentId": "242250", "Score": "1" } }, { "body": "<ul>\n<li><p><code>strcpy(buff,argv[1]);</code> is unnecessary. You may work directly with <code>argv[1]</code>.</p></li>\n<li><p>The error message is misleading. There are plenty of reasons for <code>mkdir</code> to fail, other than \"File exists\". Use <code>perror</code>.</p></li>\n<li><p>Do not <code>#include</code> files you don't need, in this case <code>&lt;limits.h&gt;</code> and <code>\"ourhdr.h\". BTW, what _is_</code>\"ourhdr.h\"`?</p></li>\n<li><p>Do not mix languages. The error message is in English, the rest are in Portugese. In the production-grade code, one would use <code>i18n</code>.</p></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-14T19:09:47.413", "Id": "242292", "ParentId": "242250", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-14T07:57:02.437", "Id": "242250", "Score": "0", "Tags": [ "c", "error-handling", "linux" ], "Title": "Bugs - Program that Creates a Directory in C" }
242250
<p>I've written a function to get the smallest date from an date[ ] and check for null. If null == infinity</p> <pre><code> /** * @param DateTimeInterface|null ...$dates * @return DateTime|null */ public static function minDateTime(?DateTimeInterface ...$dates) { $dateList = []; $dates = array_filter($dates); if (empty($dates)) { // all values where null return null; } foreach ($dates as $date) { $dateList[] = $date-&gt;getTimestamp(); } return (new DateTime())-&gt;setTimeStamp(min($dateList)); } </code></pre> <p>Its working but could this be written smaller or with more comments, so that external coworkers can read this?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-14T17:01:13.870", "Id": "475457", "Score": "0", "body": "The `$dateList = [];` at the start of the function isn't needed." } ]
[ { "body": "<p>Things to be aware of:</p>\n\n<ul>\n<li><code>array_filter()</code> does a full loop of the array.</li>\n<li><code>foreach()</code>, of course, does a full loop of the array.</li>\n<li><code>min()</code> does a full loop of the array.</li>\n<li><code>empty()</code> does a couple of things: it checks if a variable is not set AND if it is \"falsey\". Because the <code>$dates</code> variable will be unconditionally set, there is no need to check this -- just use <code>!$dates</code> if you want to check if the array is empty.</li>\n<li><code>array_filter()</code>, like <code>empty()</code> is a \"greedy\" seeker of \"falsey\" values. I assume that this is a non-issue for your task because there should be no <code>0</code> or <code>false</code> (etc.) values -- only datetime values or <code>null</code>s.</li>\n<li><a href=\"https://stackoverflow.com/q/961074/2943403\">datetime objects can be compared</a>.</li>\n<li>you don't need to make iterated calls to <code>getTimestamp()</code>, nor do you need to declare a new datetime object and set its time manually -- just use the one you found.</li>\n</ul>\n\n<p>I suppose I'll recommend that you loop the data just one time. No array generation, no function calls, very direct and concise. Your custom method name is descriptive. Go with this:</p>\n\n<p>Code: (<a href=\"https://3v4l.org/nFLpk\" rel=\"nofollow noreferrer\">Demo</a>)</p>\n\n<pre><code>public static function minDateTime(?DateTimeInterface ...$dates)\n{\n $minDate = null;\n foreach ($dates as $date) {\n if ($date &amp;&amp; (!$minDate || $date &lt; $minDate)) {\n $minDate = $date;\n }\n }\n return $minDate;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-15T06:45:12.963", "Id": "475530", "Score": "1", "body": "This was really helpfull. Didn't know until now that null == false. That did not cross my mind for years. Thanks for additional information on the different loops, too!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-14T23:26:26.743", "Id": "242303", "ParentId": "242252", "Score": "1" } } ]
{ "AcceptedAnswerId": "242303", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-14T08:48:48.920", "Id": "242252", "Score": "3", "Tags": [ "php", "static" ], "Title": "PHP get minDateTime from array" }
242252
<p>I am experimenting with the <code>ServiceLocator</code> pattern. I'd like to support lazy loading of items.</p> <pre class="lang-swift prettyprint-override"><code>protocol Resolver { func resolve&lt;T&gt; () -&gt; T } protocol Register { func register&lt;T&gt;(instance: T) func register&lt;T&gt;(reference: @escaping () -&gt; T) } final class LazyServiceLocator { enum ObjectRegistry { case instance(Any) case reference(() -&gt; Any) func unwrap() -&gt; Any { switch self { case let .instance(instance): return instance case let .reference(reference): return reference() } } } private lazy var store: Dictionary&lt;ObjectIdentifier, ObjectRegistry&gt; = [:] } extension LazyServiceLocator: Resolver { func resolve&lt;T&gt;() -&gt; T { let key = ObjectIdentifier(type(of: T.self)) if let item = store[key], let instance = item.unwrap() as? T { switch item { case .reference: register(instance: instance) default: break } return instance } else { preconditionFailure("Could not resolve service for \(type(of: T.self))") } } } extension LazyServiceLocator: Register { func register&lt;T&gt;(instance: T) { let key = ObjectIdentifier(type(of: T.self)) store[key] = .instance(instance) } func register&lt;T&gt;(reference: @escaping () -&gt; T) { let key = ObjectIdentifier(type(of: T.self)) store[key] = .reference(reference) } } </code></pre> <p>This can run with the following in a playground</p> <pre class="lang-swift prettyprint-override"><code> let foo = LazyServiceLocator() class Test { init() { print("Test") } } class OtherTest { init(foo: Test) { print("OtherTest") } } foo.register(instance: Test()) foo.register(reference: { return OtherTest(foo: foo.resolve()) }) let bar: Test = foo.resolve() let boo: OtherTest = foo.resolve() </code></pre> <p>Commenting out <code>let bar: Test = foo.resolve()</code> still runs the print statement in it's init method, so I can see that works.</p> <p>Commenting out <code>let boo: OtherTest = foo.resolve()</code> does not run the print statement, so I believe this also works.</p> <p>I am very new to the pattern and Swift, so would appreciate some feedback on where this can be improved or what I have missed, being new to the language.</p>
[]
[ { "body": "<p>This is mostly good, but it can be improved.</p>\n<p>You might want to constrain the Resolver and Register protocols to classes. Since you want to share instances this won’t work with structs.</p>\n<pre><code>protocol Register: class { ... }\n</code></pre>\n<p>Your <code>store</code> property doesn’t have to be lazy. Initializing an empty dictionary is cheap, so you can do that directly when your LazyServiceLocator is initialized.</p>\n<p>The biggest issue I found is the ObjectIdentifier you use as the dictionary key. You don’t store the type of T (which would be <code>T.self</code>) but the type of the type of T - it’s metatype. I’m not quite sure if this can lead to problems, but it is unnecessary. Just use <code>ObjectIdentifier(T.self)</code>.</p>\n<p>The other thing you might want to consider is renaming your <code>register(reference:)</code> method to <code>register(factory:)</code>. Calling something that creates an object reference is rather uncommon.</p>\n<p>And finally you might want to consider adding an overload for <code>resolve</code> that takes the requested type as a parameter:</p>\n<pre><code>extension Resolver {\n func resolve&lt;T&gt;(_ type: T.Type) -&gt; T {\n return resolve()\n }\n}\n</code></pre>\n<p>With that you can write <code>let x = resolve(Foo.self)</code> instead of <code>let x: Foo = resolve()</code>. IMHO this is a bit more readable.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-21T10:43:19.857", "Id": "479525", "Score": "0", "body": "Thank you so much, very helpful." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-12T16:56:49.607", "Id": "243783", "ParentId": "242253", "Score": "1" } } ]
{ "AcceptedAnswerId": "243783", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-14T08:52:32.840", "Id": "242253", "Score": "1", "Tags": [ "swift", "ios", "dependency-injection" ], "Title": "Service Locator with Lazy Loading in Swift" }
242253
<p>I was reading about private variables and functions in Python and I managed to get almost everything except one thing.</p> <p>Is it recommended to write underscore before variables defined inside a function?</p> <p>Here is the code so it can be more clear:</p> <p><strong>Version 1:</strong></p> <pre><code>class House(): def __init__(self): self.color = "RED" self._discount_coefficient = 0.8 def get_total_charges(self, json_from_communal_company): _water_price = json_from_communal_company["waterPrice"] _electricity_price = json_from_communal_company["electricityPrice"] _total_charges = self._discount_coefficient * (_water_price + _electricity_price) return _total_charges </code></pre> <p><strong>Version 2:</strong></p> <pre><code>class House(): def __init__(self): self.color = "RED" self._discount_coefficient = 0.8 def get_total_charges(self, json_from_communal_company): water_price = json_from_communal_company["waterPrice"] electricity_price = json_from_communal_company["electricityPrice"] total_charges = self._discount_coefficient * (water_price + electricity_price) return total_charges </code></pre> <p>I know that variable <code>_discount_coefficient</code> needs to have underscore, but I am not sure if variables <code>water_price</code>, <code>electricity_price</code> and <code>total_charges</code> should have underscore or not.</p> <p>Can someone tell me which version is better and why?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-15T01:43:46.167", "Id": "475512", "Score": "0", "body": "Where did you read the recommendation about prefixing an underscore, and what does that source suggest regarding *where*?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-15T15:42:38.127", "Id": "475590", "Score": "0", "body": "I got that recommendation at dozens of different places like some Q&A sites, tutorial sites, etc.\nOne of them is this question at StackOverflow (https://stackoverflow.com/questions/1641219/does-python-have-private-variables-in-classes).\nIn those articles I managed to get that attributes and functions which should not be accessed outside of the class should have underscore as prefix.\n\nBut the thing which confused me was about variables declared inside functions of a class. I could nowhere find if they should have underscore or not so I wrote this question." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-15T16:01:47.487", "Id": "475591", "Score": "0", "body": "You are making the exact decision in the correct tense. The document to refer to is the [Style Guide for Python Code](https://www.python.org/dev/peps/pep-0008/#id36) on *special forms using leading or trailing underscores*." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-15T16:11:30.443", "Id": "475592", "Score": "0", "body": "I read PEP 8 before I started searching elsewhere, but there it is only written this about leading underscores: \"_single_leading_underscore: weak \"internal use\" indicator. E.g. from M import * does not import objects whose names start with an underscore.\"\n\nExact case which I wrote in the question was not mentioned." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-15T21:55:12.930", "Id": "475616", "Score": "1", "body": "`Use one leading underscore only for non-public methods and instance variables.` (→ do not use this for function/method local variables.)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-16T14:40:59.030", "Id": "475700", "Score": "0", "body": "I read this part, but somehow I didn't notice this. Thank you for clearing it out!" } ]
[ { "body": "<p>For Python object names, a single leading underscore denotes <em>private</em> status, like you said.\nUnlike other languages, this is not enforced however.\nIt is only a (strong) suggestion for users of your code not to use these objects.</p>\n\n<p>This could be internal variables, like your <code>self._discount_coefficient</code>.\nFor example, maybe you implement a <code>@property</code> that secrectly stores something in <code>self._discount_coefficient</code>, but for the calling code, you need to enforce an invariant (in this case, maybe <code>0 &lt;= self._discount_coefficient &lt;= 1</code>).\nThis way, users can only set the <code>discount_coefficient</code> instance attribute (notice no underscore) to be within <code>0</code> and <code>1</code>, otherwise an error is thrown.\nNothing keeps people from directly mingling with <code>self._discount_coefficient</code>, however.\nTherefore, the convention of underscores; basically a contract where all guarantees you make about your code are void if private objects are modified directly.</p>\n\n<p>Having said all that (which you probably heard of already), it becomes clear that users of your <code>House</code> class can never directly access the variables inside your method anyway.\nThey either access <code>get_total_charges</code> as a whole, or nothing.\nThe decision is therefore to either hide <code>get_total_charges</code> as a whole, if it is private, or leave it like in your case.</p>\n\n<p><code>water_price</code>, <code>electricity_price</code> and <code>total_charges</code> are only temporary variables and tossed the moment the function returns.\nThey are never relevant to the entire private/public debate because they are never seen from calling code.\nIf you assigned any of them as instance attributes via <code>self</code>, you would have to decide for or against a leading underscore.</p>\n\n<p>As it is, Version 2 looks fine.\nAs for remaining style, <code>House()</code> can just be <code>House</code> and the equal signs before <code>json_from_communal_company</code> should not be aligned (looks fine now but is a maintenance nightmare).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-14T11:12:48.490", "Id": "475417", "Score": "1", "body": "\"water_price, electricity_price and total_charges are only temporary variables and tossed the moment the function returns. They are never relevant to the entire private/public debate because they are never seen from calling code. If you assigned any of them as instance attributes via self, you would have to decide for or against a leading underscore.\" - This explains everything. Great answer." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-14T11:07:44.607", "Id": "242265", "ParentId": "242263", "Score": "1" } } ]
{ "AcceptedAnswerId": "242265", "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-14T10:32:47.590", "Id": "242263", "Score": "0", "Tags": [ "python" ], "Title": "Python private variables in a class" }
242263
<p>I started to learn C++ after programming for some years in Java, and this is my first (header-only) library. When switching from another language, it is always difficult not to project the old habits into the new medium, and thus I wonder how idiomatic my C++ code is, so it would be awesome if someone reviewed this piece.</p> <pre><code>#ifndef __FILE_READER_H__ #define __FILE_READER_H__ #include &lt;filesystem&gt; #include &lt;fstream&gt; #include &lt;functional&gt; #include &lt;stdexcept&gt; #include &lt;string&gt; #include &lt;vector&gt; // API namespace octarine { // Read a CSV file into a vector of vectors of strings. // Each string is trimmed of whitespace. inline std::vector&lt;std::vector&lt;std::string&gt;&gt; read_csv( const std::filesystem::path &amp;filename, bool has_header = true, char separator = ','); // Read a CSV file into a vector of objects of a predefined type. template &lt;typename T&gt; inline std::vector&lt;T&gt; read_csv( const std::filesystem::path &amp;filename, const std::function&lt;T(const std::vector&lt;std::string&gt;&amp;)&gt;&amp; mapper, bool has_header = true, char separator = ',' ); } // Implementation namespace octarine { namespace { size_t count_items(const std::string&amp; line, char separator); std::vector&lt;std::string&gt; parse_line(const std::string &amp;line, char separator, size_t num_items, size_t line_number); const char* k_whitespace = " \t"; } template &lt;typename T&gt; std::vector&lt;T&gt; read_csv( const std::filesystem::path &amp;filename, const std::function&lt;T(const std::vector&lt;std::string&gt;&amp;)&gt;&amp; mapper, bool has_header, char separator) { const auto&amp; lines = read_csv(filename, has_header, separator); std::vector&lt;T&gt; result; result.reserve(lines.size()); for (const auto&amp; line : lines) { result.emplace_back(mapper(line)); } return result; } std::vector&lt;std::vector&lt;std::string&gt;&gt; read_csv( const std::filesystem::path &amp;filename, bool has_header, char separator) { std::ifstream f(filename); if (!f.good()) { throw std::invalid_argument("unable to read file '" + filename.string() + "'"); } // read header line std::string header; std::getline(f, header); if (!f.good()) { throw std::invalid_argument("error reading header line from '" + filename.string() + "'"); } // count number of items per line size_t num_items = count_items(header, separator); // if we don't have the header, add the first line to the results std::vector&lt;std::vector&lt;std::string&gt;&gt; lines; size_t line_number = 1; if (!has_header) { lines.push_back(parse_line(header, separator, num_items, line_number)); line_number += 1; } std::string line; while (!f.bad()) { std::getline(f, line); if (f.eof()) { break; } if (f.fail()) { throw std::invalid_argument("error reading line from '" + filename.string() + "'"); } lines.push_back(parse_line(line, separator, num_items, line_number)); line_number += 1; } return lines; } namespace { // counts number of comma-separated items in a line from a CSV file size_t count_items(const std::string &amp;line, char separator) { size_t count = 1; for (char c : line) { if (c == separator) { ++count; } } return count; } // splits a line from a CSV file when the number of items per line is known in advance std::vector&lt;std::string&gt; parse_line( const std::string &amp;line, char separator, size_t num_items, size_t line_number) { if (num_items == 0) { throw std::invalid_argument("number of items must be positive"); } std::vector&lt;std::string&gt; result(num_items); size_t item = 0; size_t offset = 0, end_offset = 0; size_t max_offset = line.size(); size_t index; while (end_offset != max_offset) { if (item &gt;= num_items) { throw std::length_error( "line " + std::to_string(line_number) + ": found more items in a line than expected"); } index = line.find(separator, offset); end_offset = (index != std::string::npos) ? index : max_offset; size_t non_space_start = line.find_first_not_of(k_whitespace, offset); size_t non_space_end = line.find_last_not_of(k_whitespace, end_offset - 1); if (non_space_start == std::string::npos || non_space_end == std::string::npos || non_space_start == index) { result[item] = ""; } else { result[item] = line.substr(non_space_start, non_space_end - non_space_start + 1); } offset = end_offset + 1; item += 1; } return result; } } } #endif </code></pre>
[]
[ { "body": "<p>A few observations:</p>\n\n<ul>\n<li><p>I would never write <code>x += 1;</code> if I wanted to increment <code>x</code>. I think this is confusing and more prone to error than writing <code>++x;</code>. Of course, there should be no difference for the compiler.</p></li>\n<li><p>In <code>count_items</code>, do you really want to return 1 even if there are no matches? Be as it may, you don't have to write an explicit loop as this is equivalent to using <a href=\"https://en.cppreference.com/w/cpp/algorithm/count\" rel=\"nofollow noreferrer\"><code>std::count</code></a>, i.e., you could just write </p>\n\n<pre><code>std::size_t count_items(const std::string &amp;line, char separator) {\n return std::count(line.cbegin(), line.cend(), separator) + 1;\n}\n</code></pre></li>\n<li><p>I find your split function <code>parse_line</code> quite difficult to read. There are several alternatives to this including many in Boost (Tokenizer, boost::algorithm::split, ...).</p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-17T03:56:33.317", "Id": "475774", "Score": "0", "body": "Thanks for the review! Regarding count_items, \"1\" definitely should be returned if there are no commas found (e.g. \"item\"), and \"2\" if there is one comma (\"item1,item2\"), so this behaviour is correct, however using std::count is much better! As for using boost, this library is intended to be easy to include as a header and thus no dependencies is a must." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-16T10:56:28.623", "Id": "242390", "ParentId": "242264", "Score": "4" } }, { "body": "<h1>Basic review</h1>\n<p>A couple of simple mistakes that are easily addressed:</p>\n<ul>\n<li>We're using a reserved identifier in the include guard - anything beginning with <code>_</code> followed by a letter, or containing <code>__</code> anywhere, is reserved for the implementation.</li>\n<li><code>size_t</code> is defined in the <code>std</code> namespace, so should be written <code>std::size_t</code>. Implementations are <em>allowed</em> to also define it in the global namespace, but as that's not <em>required</em>, it's a portability error to rely on that.</li>\n<li><code>std::invalid_argument</code> is a misleading exception to throw for I/O failure - use <code>std::ios_base::failure</code> for this (and consider using the stream's <code>exceptions()</code> method to cause the stream to throw this for itself).</li>\n</ul>\n<p>Slightly more involved:</p>\n<ul>\n<li><code>std::vector&lt;std::string&gt; result(num_items)</code> will construct <code>num_items</code> string objects, but we're going to overwrite them all. It's more efficient to create an empty result, then <code>reserve()</code> enough space for us to <code>push_back()</code> (or <code>emplace_back()</code>) each string.</li>\n</ul>\n<hr />\n<h1>Testing</h1>\n<p>This is the kind of code that would benefit from some unit tests to give confidence in its correctness.</p>\n<p>It's hard to test as it stands, as the interface only admits named files, but we can improve that by splitting the functions' responsibilities so that we have one function that deals with file access and another that accepts a <code>std::istream&amp;</code> and does the actual parsing.</p>\n<p>We would really like to test <code>parse_line()</code> in isolation, so I'd be inclined to make that part of the public interface, rather than being hidden in the anonymous namespace.</p>\n<hr />\n<h1>Interface/usability</h1>\n<p>The second version would be better if it created <code>T</code> objects on the fly, rather than constructing an entire <code>std::vector&lt;std::vector&lt;std::string&gt;&gt;</code> before starting to construct the first <code>T</code> object. I think we could combine the two functions into one, if we provide a default mapper that just returns the <code>std::vector&lt;std::string&gt;&amp;</code> that it was given (take care to ensure we have no unnecessary copying, though - Valgrind can help with that).</p>\n<p>Consider providing an interface that accepts an output iterator to which it can write the results, rather than storing everything into a <code>std::vector</code>. That will be more useful to programs that are able to operate on one line at a time (e.g. a <code>cut</code>-like utility to select particular columns). It's easy to adapt that to give the current behaviour (by providing a back-inserter to create a vector), but impossible to adapt in the opposite direction.</p>\n<hr />\n<h1>Maintainability</h1>\n<p><code>count_items()</code> duplicates the parsing logic, and must be kept in sync with <code>parse_line()</code>. If we improve the parsing (to deal with quoted columns, for instance), then we have two places that need to change. We can make this easier for ourselves if we create a utility function that can identify the end of a value and the start of the next value, if there is one.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-09T09:34:01.337", "Id": "268805", "ParentId": "242264", "Score": "1" } } ]
{ "AcceptedAnswerId": "242390", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-14T10:50:40.660", "Id": "242264", "Score": "6", "Tags": [ "c++", "csv" ], "Title": "A header-only library to read CSV" }
242264
<p>Because C# .NET does not come with a <code>MultiDictionary</code>, I implemented one based on <a href="https://stackoverflow.com/a/4554628/8473031">this StackOverflow answer</a>.</p> <p>The <code>MultiDictionary</code> should be able to hold multiple values for one key and remove the key, if no value is assigned to the key anymore.</p> <p>I wanted to implement nearly all methods, which the standard <code>Dictionary</code> provides:</p> <pre><code>void Add(TKey key, TValue value); bool Remove(TKey key); void Clear(); bool ContainsKey(TKey key); bool TryGetValue(TKey key, out TValue value); </code></pre> <p>To use the <code>MultiDictionary</code> properly some signatures needed to be changed. This is my implementation:</p> <pre><code>public class MultiDictionary&lt;TKey, TValue&gt; { private readonly Dictionary&lt;TKey, List&lt;TValue&gt;&gt; _Data = new Dictionary&lt;TKey, List&lt;TValue&gt;&gt;(); public Dictionary&lt;TKey, List&lt;TValue&gt;&gt;.ValueCollection Values =&gt; _Data.Values; public Dictionary&lt;TKey, List&lt;TValue&gt;&gt;.KeyCollection Keys =&gt; _Data.Keys; public void Add(TKey key, TValue value) { this[key].Add(value); } public bool Remove(TKey key, TValue value) { return this[key].Remove(value); } public void Clear() { _Data.Clear(); } public bool ContainsKey(TKey key) { return _Data.ContainsKey(key); } public bool TryGetValue(TKey key, out List&lt;TValue&gt; value) { return _Data.TryGetValue(key, out value); } private struct Entry : IEnumerable&lt;TValue&gt; { private readonly MultiDictionary&lt;TKey, TValue&gt; _Dictionary; private TKey Key { get; } internal void Add(TValue value) { if (!_Dictionary._Data.TryGetValue(Key, out var list)) list = new List&lt;TValue&gt;(); list.Add(value); _Dictionary._Data[Key] = list; } internal bool Remove(TValue value) { if (!_Dictionary._Data.TryGetValue(Key, out var list)) return false; var result = list.Remove(value); if (list.Count == 0) _Dictionary._Data.Remove(Key); return result; } internal Entry(MultiDictionary&lt;TKey, TValue&gt; dictionary, TKey key) { _Dictionary = dictionary; Key = key; } public IEnumerator&lt;TValue&gt; GetEnumerator() { return !_Dictionary._Data.TryGetValue(Key, out var list) ? Enumerable.Empty&lt;TValue&gt;().GetEnumerator() : list.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } private Entry this[TKey key] =&gt; new Entry(this, key); } </code></pre> <p>I wanted to know, if this implementation is valid (working as I expect) and if you have improvements regarding coding style, safety and so on. </p> <p>Thanks in Advance!</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-14T17:53:57.670", "Id": "475464", "Score": "1", "body": "`IEnumerable<KeyValuePair<TKey, TValue>> _Data` would be much more easier to handle and would have simpler implementation." } ]
[ { "body": "<p>couple of points from my side:</p>\n\n<ol>\n<li>If you add same TKey instance to your List it will be added only\nonce. But if you add other instance of TKey but with the same\n'content' the end result of Add method is dictionary with two keys with same content and two\nlists. Is that part of requirement?</li>\n</ol>\n\n<p>Example:</p>\n\n<pre><code>public class Foo\n{\n public string X;\n public int Y;\n\n public Foo(string x, int y)\n {\n X = x;\n Y = y;\n }\n}\n\nvar multiDict = new MultiDict&lt;Foo, string&gt;();\n\nvar firstFoo = new Foo(\"abc\", 1);\nmultiDict.Add(firstFoo, \"someValue1\");\nmultiDict.Add(firstFoo, \"someValue2\");\n\nvar secondFoo = new Foo(\"abc\", 1);\nmultiDict.Add(secondFoo, \"someValue3\");\n</code></pre>\n\n<ol start=\"2\">\n<li>Similar problem is for TValue, but it's related with removing elements. Solution for both cases is implementing IEqualityComparer for both TKey and TValue and force class user to inject it via constructor and use <a href=\"https://docs.microsoft.com/pl-pl/dotnet/api/system.collections.generic.dictionary-2.-ctor?view=netcore-3.1#System_Collections_Generic_Dictionary_2__ctor_System_Collections_Generic_IEqualityComparer__0__\" rel=\"noreferrer\">[THIS]</a> dictonary constructor. That will guarantee uniqueness for your key. <strong>Please keep in mind that you should also use RemoveAll method on list to be sure that all elements that matches predicate are removed.</strong> </li>\n<li>You're incosistent with indentations of methods, curly brackets,\nwhitespaces between methods. Please clean that up.</li>\n<li>I don't see the point of Entry struct. You can easily get rid of it\nand put all methods in MultiDictionary class itself.</li>\n<li>I would consider to change interface to more 'detailed' interface.\nWhat I mean by that? Let's say that Remove returns count of elements\nactually removed. Point only to consideration.</li>\n<li>I will change implementation of Add method to something different,\nbecause you always (when key exists in dictionary or not) seeking\nthrough dictionary twice: first time is on TryGetValue method and\nsecond while attaching list to key. Attaching list to key is\nnecessary only when you're creating new one.</li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-14T16:06:57.097", "Id": "242281", "ParentId": "242267", "Score": "5" } }, { "body": "<p>What you actually need is just a thin layer that would handle your requirements on top of the generic <code>Dictionary&lt;TKey, TValue&gt;</code>. You don't need any fancy or complex work to achieve that, as you're not building the collection from the scratch. </p>\n\n<p>So, your implementation would use </p>\n\n<pre><code>Dictionary&lt;TKey, IEnumerable&lt;TValue&gt;&gt; _Data\n</code></pre>\n\n<p>Now, you don't the struct that you have in your code, you just need to create your own interface that would have your requirements along with the minimum necessary methods or properties that needed. </p>\n\n<p>Something like : </p>\n\n<pre><code>public interface IMultiDictionary&lt;TKey, TValue&gt;\n{\n\n IEnumerable&lt;TValue&gt; this[TKey key] { get; set; }\n\n IEnumerable&lt;TKey&gt; Keys { get; }\n\n IEnumerable&lt;TValue&gt; Values { get; }\n\n int Count { get; }\n\n void AddOrUpdate(TKey key, TValue value);\n\n bool ContainsKey(TKey key);\n\n // remove a key along with its values\n bool RemoveKey(TKey key);\n\n // remove a single value from a key values.\n bool RemoveValue(TKey key, TValue value);\n\n //Clear All Key values, but keep the key\n void Clear(TKey key);\n\n bool TryGetValue(TKey key, out IEnumerable&lt;TValue&gt; value);\n}\n</code></pre>\n\n<p>now you can do this : </p>\n\n<pre><code>public class MultiDictionary&lt;TKey, TValue&gt; : IMultiDictionary&lt;TKey, TValue&gt;, IEnumerable\n{\n private readonly Dictionary&lt;TKey, IEnumerable&lt;TValue&gt;&gt; _Data = new Dictionary&lt;TKey, IEnumerable&lt;TValue&gt;&gt;();\n\n public IEnumerable&lt;TValue&gt; Values =&gt; _Data.Values.SelectMany(x =&gt; x);\n\n public IEnumerable&lt;TKey&gt; Keys =&gt; _Data.Keys;\n\n public int Count =&gt; _Data.Count;\n\n public IEnumerable&lt;TValue&gt; this[TKey key]\n {\n get =&gt; _Data[key];\n set =&gt; AddOrUpdate(key, value);\n }\n\n public void AddOrUpdate(TKey key, IEnumerable&lt;TValue&gt; values)\n {\n if (ContainsKey(key)) // if key exists\n {\n (_Data[key] as List&lt;TValue&gt;)?.AddRange(values); \n }\n else\n {\n // add the new key with its value.\n _Data.Add(key, values);\n }\n }\n\n public void AddOrUpdate(TKey key, TValue value)\n {\n if (ContainsKey(key)) // if key exists\n {\n //check value and add it if not exists\n if (!_Data[key].Contains(value)) { (_Data[key] as List&lt;TValue&gt;)?.Add(value); }\n }\n else\n {\n // add the new key with its value.\n _Data.Add(key, new List&lt;TValue&gt;() { value });\n }\n }\n\n public void Clear(TKey key)\n {\n if (ContainsKey(key))\n {\n (_Data[key] as List&lt;TValue&gt;)?.Clear();\n }\n }\n\n public bool TryGetValue(TKey key, out IEnumerable&lt;TValue&gt; values) =&gt; _Data.TryGetValue(key, out values);\n\n public bool ContainsKey(TKey key) =&gt; _Data.ContainsKey(key);\n\n public bool RemoveKey(TKey key) =&gt; _Data.Remove(key);\n\n public bool RemoveValue(TKey key, TValue value) =&gt; ContainsKey(key) &amp;&amp; (_Data[key] as List&lt;TValue&gt;)?.Remove(value) == true;\n\n public void Clean()\n {\n foreach (var item in _Data.Where(x =&gt; !x.Value.Any()))\n {\n _Data.Remove(item.Key);\n }\n }\n // enabling foreach loop\n public IEnumerator GetEnumerator() =&gt; _Data.GetEnumerator();\n\n}\n</code></pre>\n\n<p><em>(NOTE : I skipped validations just to minimize the code for demonstration purpose).</em> </p>\n\n<p>If you see the <code>AddOrUpdate</code> there is two overloads (one accepts single value, and the other accepts a collection). This would give more flexibility when you adding or updating a key. And since each key has a collection of values, we needed something like <code>RemoveKey</code> and <code>RemoveValue</code> you can rename them to <code>Remove</code> but I found it would be more readable this way. Both will come in handy. The <code>Clean()</code> method can be called whenever you need to delete empty keys.</p>\n\n<p>The use of <code>IEnumerable</code> is to have the minimum collection requirement, meaning, it'll be flexible with other collection types, since most generic collections (including Array) implements it. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-16T04:48:37.507", "Id": "242374", "ParentId": "242267", "Score": "1" } }, { "body": "<p>Both Karol and iSR5 have some good points, and I can't add something new.</p>\n\n<p>One thing you should be aware of, if you consider to use iSR5's <code>IEnumerable&lt;TValue&gt;</code>-approach, is as follows:</p>\n\n<pre><code> MultiDictionary&lt;int, int&gt; dict = new MultiDictionary&lt;int, int&gt;();\n\n List&lt;int&gt; data = Enumerable.Range(1, 30).ToList();\n IEnumerable&lt;int&gt; query = data.Where(i =&gt; i % 3 == 0);\n\n dict.AddOrUpdate(0, query);\n Console.WriteLine(string.Join(\", \", dict[0]));\n data.Remove(15);\n Console.WriteLine(string.Join(\", \", dict[0]));\n</code></pre>\n\n<p>which outputs:</p>\n\n<pre><code>3, 6, 9, 12, 15, 18, 21, 24, 27, 30\n3, 6, 9, 12, 18, 21, 24, 27, 30\n</code></pre>\n\n<p>As you can see, the content of an entry in <code>dict</code> is changed outside <code>dict</code> itself. IMO this can lead to undesired and unexpected behavior, that can be difficult to debug and find, for instance if the original data is maintained \"far away\" from <code>dict</code>. I can only recommend that you have a concrete container type as value of the inner dictionary <code>_Data</code> - and it should only be maintained/accessible by the dictionary itself.</p>\n\n<p>Else I see no reason for <code>MultiDictionary&lt;K, V&gt;</code> class at all, as you could just have a normal <code>Dictionary&lt;K, IEnumerable&lt;T&gt;&gt;</code> that is transparent in respect to the value container.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-16T08:00:54.873", "Id": "242384", "ParentId": "242267", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-14T11:45:59.667", "Id": "242267", "Score": "3", "Tags": [ "c#" ], "Title": "MultiDictionary implementation C#" }
242267
<p>I'm new to Rust and would like to know if my code is using the language well, if there are big improvements and if the code in general is rust-like. At the moment it feels very C. I haven't yet developed good feeling on how to incorporate the match function or how to check in a range of chars. The flushing and input part feels bulky as well. Here the description and <a href="https://cs50.harvard.edu/x/2020/psets/2/readability/" rel="nofollow noreferrer">link</a>:</p> <ol> <li>Your program must prompt the user for a string of text (using <code>get_string</code>).</li> <li>Your program should count the number of letters, words, and sentences in the text. You may assume that a letter is any lowercase character from <code>a</code> to <code>z</code> or any uppercase character from <code>A</code> to <code>Z</code>, any sequence of characters separated by spaces should count as a word, and that any occurrence of a period, exclamation point, or question mark indicates the end of a sentence.</li> <li>Your program should print as output <code>"Grade X"</code> where <code>X</code> is the grade level computed by the Coleman-Liau formula, rounded to the nearest integer.</li> <li>If the resulting index number is 16 or higher (equivalent to or greater than a senior undergraduate reading level), your program should output <code>"Grade 16+"</code> instead of giving the exact index number. If the index number is less than 1, your program should output <code>"Before Grade 1"</code>.</li> </ol> <pre><code>// Rust implementation of C problem from: https://cs50.harvard.edu/x/2020/psets/2/readability/ use std::io; fn main() { print!("Text: "); io::Write::flush(&amp;mut io::stdout()).expect("flush failed!"); let mut line = String::new(); match io::stdin().read_line(&amp;mut line) { Ok(_) =&gt; (), Err(err) =&gt; println!("Could not parse input: {}", err), } let bytes = line.into_bytes(); let mut l = 0.0; let mut w = 1.0; let mut s = 0.0; let sentmarker = ['?', '.', '!']; for b in bytes { if b &gt;= 65 &amp;&amp; b &lt;= 90 || b &gt;= 97 &amp;&amp; b &lt;= 122 { // check if character in [a-zA-Z] l += 1.0; } else if sentmarker.contains(&amp;(b as char)) { s += 1.0; } else if (b as char) == ' ' { w += 1.0; } } let average_letters = l / w * 100.0; // the average number of letters per 100 words in the text let average_sentences = s / w * 100.0; // the average number of sentences per 100 words in the text let index = 0.0588 * average_letters - 0.296 * average_sentences - 15.8; // Coleman-Liau index let indexresult = if index &gt; 16.0 { String::from("Grade 16+") } else if index &lt; 1.0 { String::from("Before Grade 1") } else { format!("Grade {:.0}", index) }; println!("{}", indexresult); } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-14T14:52:40.710", "Id": "475437", "Score": "1", "body": "Welcome to Code Review, if you aim to receive more detailed answers adding the description of the problem to your question can help you." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-14T17:39:38.860", "Id": "475462", "Score": "0", "body": "Okay, thanks. Was wondering what the MO is over here." } ]
[ { "body": "<blockquote>\n<pre><code>match io::stdin().read_line(&amp;mut line) {\n Ok(_) =&gt; (),\n Err(err) =&gt; println!(\"Could not parse input: {}\", err),\n}\n</code></pre>\n</blockquote>\n\n<p>Instead of continuing, the program should panic if it fails to read input. Use <a href=\"https://doc.rust-lang.org/std/result/enum.Result.html#method.expect\" rel=\"nofollow noreferrer\"><code>expect</code></a> instead:</p>\n\n<pre><code>io::stdin()\n .read_line(&amp;mut input)\n .expect(\"Failed to read input\");\n</code></pre>\n\n<blockquote>\n<pre><code>let mut l = 0.0;\nlet mut w = 1.0;\nlet mut s = 0.0;\nlet sentmarker = ['?', '.', '!'];\n\nfor b in bytes {\n if b &gt;= 65 &amp;&amp; b &lt;= 90 || b &gt;= 97 &amp;&amp; b &lt;= 122 { // check if character in [a-zA-Z]\n l += 1.0;\n } else if sentmarker.contains(&amp;(b as char)) {\n s += 1.0;\n } else if (b as char) == ' ' {\n w += 1.0;\n }\n}\n</code></pre>\n</blockquote>\n\n<p>This parse can be simplified using <a href=\"https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.filter\" rel=\"nofollow noreferrer\"><code>filter</code></a> and <a href=\"https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.count\" rel=\"nofollow noreferrer\"><code>count</code></a>. Also, use <a href=\"https://doc.rust-lang.org/std/primitive.u8.html#method.is_ascii_alphabetic\" rel=\"nofollow noreferrer\"><code>is_ascii_alphabetic</code></a> instead of hard-coding the values.</p>\n\n<p>It is probably clearer to create a dedicated <code>struct</code> to hold the parameters.</p>\n\n<hr>\n\n<p>My version of the code: (takes advantage of the Unicode definition of letters and whitespace)</p>\n\n<pre><code>use std::io::{self, prelude::*};\n\nfn main() {\n println!(\"Text: \");\n io::stdout().flush().expect(\"Failed to flush stdout\");\n\n let mut input = String::new();\n io::stdin()\n .read_line(&amp;mut input)\n .expect(\"Failed to read input\");\n\n let analysis = Analysis::new(&amp;input);\n match analysis.index() {\n 0 =&gt; println!(\"Before Grade 1\"),\n index @ 1..=16 =&gt; println!(\"Grade {}\", index),\n _ =&gt; println!(\"Grade 16+\"),\n }\n}\n\nstruct Analysis {\n n_letters: usize,\n n_words: usize,\n n_sentences: usize,\n}\n\nimpl Analysis {\n fn new(text: &amp;str) -&gt; Analysis {\n Analysis {\n n_letters: text.chars().filter(|c| c.is_alphabetic()).count(),\n n_words: text.split_whitespace().count(),\n n_sentences: text.split_terminator(|c| \".!?\".contains(c)).count(),\n }\n }\n fn index(&amp;self) -&gt; usize {\n let n_letters_per_100_words = self.n_letters as f64 / self.n_words as f64 * 100.0;\n let n_sentences_per_100_words = self.n_sentences as f64 / self.n_words as f64 * 100.0;\n\n let index = 0.0588 * n_letters_per_100_words - 0.296 * n_sentences_per_100_words - 15.8;\n index.round() as usize\n }\n}\n</code></pre>\n\n<p>(<a href=\"https://play.rust-lang.org/?version=stable&amp;mode=debug&amp;edition=2018&amp;gist=63b5ab7b305947cd551777ed4c2527e4\" rel=\"nofollow noreferrer\">playground</a>, with some tests)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-21T19:28:17.897", "Id": "476330", "Score": "0", "body": "Thank you @L.F., I looked into this a few times and learned a lot from it. It#s easy to read and very condensed. The part that I have not yet though enough about are the || functions and all the idea about the preludes" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-22T09:17:27.967", "Id": "476391", "Score": "1", "body": "@vaeng You're welcome. The `||` functions are called [closures](https://doc.rust-lang.org/stable/book/ch13-01-closures.html), and importing [`std::io::prelude`](https://doc.rust-lang.org/stable/std/io/prelude/index.html) is a convenient way to import some common I/O functionalities (`flush` in this case)." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-17T02:34:19.490", "Id": "242439", "ParentId": "242269", "Score": "4" } } ]
{ "AcceptedAnswerId": "242439", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-14T12:25:56.933", "Id": "242269", "Score": "3", "Tags": [ "rust" ], "Title": "Readability Check" }
242269
<p>I was working on Leet code design a <a href="https://leetcode.com/problems/design-linked-list/submissions/" rel="nofollow noreferrer">Linked List problem</a>. My solution with a <code>@tail</code> pointer, althought it added complexity it made adding to tail O(1), also having a variable size <code>@size</code> made it easier to counter edge cases. Here are some of the stats:</p> <blockquote> <p>Success Details Runtime: 100 ms, faster than 84.62% of Ruby online submissions for Design Linked List. Memory Usage: 9.6 MB, less than 100.00% of Ruby online submissions for Design Linked List.</p> </blockquote> <p>If there is any enhancements or feedback please share some. Could the Linked List be optimize? Are you able to understand how is design when reading the code? </p> <pre><code>class MyLinkedList attr_accessor :head, :size, :tail =begin Initialize your data structure here. =end def initialize() @head = nil @size = 0 @tail = nil end =begin Get the value of the index-th node in the linked list. If the index is invalid, return -1. :type index: Integer :rtype: Integer =end def get(index) return -1 if @head == nil return -1 if index &gt; @size - 1 return @head.val if index == 0 return @tail.val if index == @size - 1 i = @head j = 0 while i != nil if j == index return i.val end i = i.next j += 1 end -1 end =begin Add a node of value val before the first element of the linked list. After the insertion, the new node will be the first node of the linked list. :type val: Integer :rtype: Void =end def add_at_head(val) new_node = Node.new(val) new_node.next = @head @tail = new_node if @head == nil @head = new_node @size += 1 end =begin Append a node of value val to the last element of the linked list. :type val: Integer :rtype: Void =end def add_at_tail(val) return add_at_head(val) if @head == nil node = Node.new(val) @tail.next = node @tail = node @size += 1 end =begin Add a node of value val before the index-th node in the linked list. If index equals to the length of linked list, the node will be appended to the end of linked list. If index is greater than the length, the node will not be inserted. :type index: Integer :type val: Integer :rtype: Void =end def add_at_index(index, val) return add_at_head(val) if index == 0 return add_at_tail(val) if @head == @tail return add_at_tail(val) if @size == index return if index &gt; @size i = @head j = 0 while i != nil if j == index - 1 tmp = i.next node = Node.new(val) i.next = node node.next = tmp @size += 1 return end i = i.next j += 1 end end =begin Delete the index-th node in the linked list, if the index is valid. :type index: Integer :rtype: Void =end def delete_at_index(index) return if index &lt; 0 || index &gt; @size - 1 return delete_at_head if index == 0 return delete_at_tail if index == @size - 1 i = @head j = 0 while i != nil if j == index - 1 i.next = i.next.next @size -= 1 return end i = i.next j += 1 end end def delete_at_head if @head == nil return nil elsif @head == @tail #one element in the linked list @head = nil @tail = nil @size -= 1 return else @head = @head.next @size -= 1 end end def delete_at_tail if @head == nil return nil elsif @head == @tail return delete_at_head end current = @head prev = nil while(current != tail) prev = current current = current.next end prev.next = nil @tail = prev @size -= 1 return end private class Node attr_accessor :val, :next def initialize(val) @val = val @next = nil end end end </code></pre>
[]
[ { "body": "<blockquote>\n <p>My solution with a @tail pointer, althought it added complexity it made adding to tail O(1), also having a variable size @size made it easier to counter edge cases.</p>\n</blockquote>\n\n<p>Having a <code>tail</code> pointer and a <code>size</code> variable makes totally sense.</p>\n\n<blockquote>\n <p>Could the Linked List be optimize?</p>\n</blockquote>\n\n<p>I don't think you can improve performance much here, you already cover most / all of the corner cases. Well done to implement <code>add_at_index</code> with one iteration. </p>\n\n<blockquote>\n <p>Are you able to understand how is design when reading the code?</p>\n</blockquote>\n\n<p>Here are some suggestions to make the code more readable</p>\n\n<h2>Extract helper methods</h2>\n\n<p>In your code you do several times <code>if @head == nil</code> to check if the list is empty. What about extracting an <code>empty?</code> method?</p>\n\n<pre><code>def empty?\n head.nil?\nend\n</code></pre>\n\n<p>Same goes for instance with increasing the size.</p>\n\n<pre class=\"lang-rb prettyprint-override\"><code> def increase_size\n @size += 1\n end\n</code></pre>\n\n<h2>Use getter / setter methods</h2>\n\n<p>You already define getter and setter methods in your class but then fail to use them.</p>\n\n<pre class=\"lang-rb prettyprint-override\"><code>attr_accessor :head, :size, :tail\n</code></pre>\n\n<p>Instead of doing <code>@head</code> you should use <code>head</code> etc. Another problem is that the getter / setter are public, move them to the private section of the class. There is no need that consumer of this class know about these implementation details.</p>\n\n<h2>Implement the Enumerable interface</h2>\n\n<p>At several places in your code you need to iterate over your list with a while loop. If you implement the <code>Enumerable</code> interface of Ruby, you only need to do this once.</p>\n\n<pre class=\"lang-rb prettyprint-override\"><code>class MyLinkedList\n include Enumerable\n\n def initialize\n @head = nil\n @size = 0\n @tail = nil\n end\n\n def each\n current = head\n until current.nil?\n yield current\n current = current.next\n end\n end\n\n def [](index)\n each_with_index do |item, i|\n return item.val if i == index\n end\n end\n</code></pre>\n\n<p><a href=\"https://ruby-doc.org/core-2.7.1/Enumerable.html\" rel=\"nofollow noreferrer\">https://ruby-doc.org/core-2.7.1/Enumerable.html</a></p>\n\n<h2>Use Ruby method names</h2>\n\n<p>You probably use the method stubs provided from LeetCode but I think it's still worth mentioning. Whenever possible you should use similar methods as already in the Ruby standard library. If we look at the Array class, we see for instance these methods.</p>\n\n<pre class=\"lang-rb prettyprint-override\"><code>def [](index) # get(index)\ndef unshift(value) # add_at_head(val)\ndef &lt;&lt;(value) # add_at_tail(val)\ndef append(value) # add_at_tail(val)\ndef [](index, value) # def add_at_index(index, val)\ndef shift # delete_at_head\ndef pop # delete_at_tail\n</code></pre>\n\n<h2>Summary</h2>\n\n<p>Here are some of my suggestions applied</p>\n\n<pre class=\"lang-rb prettyprint-override\"><code>class MyLinkedList\n include Enumerable\n\n def initialize\n @head = nil\n @size = 0\n @tail = nil\n end\n\n def [](index)\n return if empty?\n return if index &gt; size - 1\n return head.val if index.zero?\n return tail.val if index == size - 1\n\n each_with_index do |item, i|\n return item.val if i == index\n end\n end\n\n def unshift(value)\n node = Node.new(value)\n node.next = head\n\n @tail = node if empty?\n @head = node\n increase_size\n\n value\n end\n\n def &lt;&lt;(value)\n return unshift(value) if empty?\n\n node = Node.new(value)\n tail.next = node\n @tail = node\n increase_size\n\n value\n end\n\n def []=(index, value)\n return add_at_head(value) if index == 0\n return add_at_tail(value) if head == tail\n return add_at_tail(value) if size == index\n return if index &gt; size\n\n each_with_index do |item, i|\n insert_node(item, value) if i == index - 1\n end\n end\n\n def each\n current = head\n until current.nil?\n yield current\n current = current.next\n end\n end\n\n private\n\n attr_accessor :head, :size, :tail\n\n def insert_node(item, value)\n tmp = item.next\n node = Node.new(value)\n item.next = node\n node.next = tmp\n increase_size\n end\n\n def empty?\n @head.nil?\n end\n\n def increase_size\n @size += 1\n end\n\n class Node\n attr_accessor :val, :next\n\n def initialize(val)\n @val = val\n @next = nil\n end\n end\nend\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-08T13:27:42.730", "Id": "243557", "ParentId": "242272", "Score": "1" } } ]
{ "AcceptedAnswerId": "243557", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-14T13:14:53.060", "Id": "242272", "Score": "2", "Tags": [ "algorithm", "ruby", "linked-list" ], "Title": "Linked List implementation in Ruby" }
242272
<p>I recently (Yesterday) started working with python and my goal is to not use any tutorials etc where I have to follow along and make a small project. My first project I was recommended to do was a simple game of Rock, Paper, Scissors. I made it in about thirty minutes and it works fine. It goes up to 3 points for each game etc. It's super simple, but now since I'm done with it I'm hoping to find a way to simplify the code, if there is any other way. I really stretched it out since I'm using basics with no help. </p> <pre><code># Rock Papers Scissors import random option = ["Rock", "Paper", "Scissor"] game = True def start_game(): point_player = 0 point_ai = 0 game_end = True while game: rock = False paper = False scissor = False if point_player == 3: game_end = False elif point_ai == 3: game_end = False if game_end: print("Choose an option. (R,P,S)") selection = input() if selection == 'R': selection = 'Rock' rock = True elif selection == 'P': selection = 'Paper' paper = True elif selection == 'S': selection = 'Scissor' scissor = True else: print("That's not an option") exit() print("=======================") print("You chose " + selection) ai_response = random.choice(option) print("The A.I chose " + ai_response) print("=======================") if ai_response == "Rock": while rock: print("Oh! That's a tie no points.") break while scissor: print("Oh, you lost :( +1 to A.I") point_ai = point_ai + 1 break while paper: print("Looks like you beat the A.I! +1 Point") point_player = point_player + 1 break elif ai_response == "Paper": while rock: print("Oh, you lost :( +1 to A.I") point_ai = point_ai + 1 break while scissor: print("Looks like you beat the A.I! +1 Point") point_player = point_player + 1 break while paper: print("Oh! That's a tie no points.") break elif ai_response == "Scissor": while rock: print("Looks like you beat the A.I! +1 Point") point_player = point_player + 1 break while scissor: print("Oh! That's a tie no points.") break while paper: print("Oh, you lost :( +1 to A.I") point_ai = point_ai + 1 break print("You have " + str(point_player) + " points") print("The A.I has " + str(point_ai) + " points.") print("=======================") else: if point_ai &gt; point_player: print("The A.I won! RIP U") else: print("Dang! You won this time.") exit() print("|=========================|") print("| Rock Paper Scissor |") print("| (R) (P) (S) |") print("|=========================|") print("Would you like to start? y/n") answer = input() if answer == "y": print("Welcome to the game of Rock Paper Scissors") start_game() elif answer == "n": print('Well ok then.. Fine leave') exit() else: print("That's not an option.") </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-05T21:02:17.310", "Id": "475429", "Score": "2", "body": "Do not do `while stuff:... break` just use an `if`. ALso don't save both user input in a string as a value, and as a boolnea in a second variable that's useless" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-05T21:06:58.027", "Id": "475430", "Score": "1", "body": "A simplification can be to replace the choices internally by numbers 0, 1 and 2. Then choice `x` beats `(x-1)%3` and is beaten by `(x+1)%3`." } ]
[ { "body": "<p>This general topic is called <a href=\"https://en.wikipedia.org/wiki/Code_refactoring\" rel=\"nofollow noreferrer\">refactoring</a>. I could link you to one of my many favorite books and websites on the topic but I'll leave some general pieces of advice.</p>\n\n<p>A good start is to break your program into smaller chunks of functionality. Make sure they're well named and easy to understand, in other words imagine you were someone who's never seen this code and had to fix an issue with it.</p>\n\n<p>If a file is growing too large, you may want to break it into several files each with their own sub-functionality.</p>\n\n<p>There are many great sites and talks on the topic both within the Python programming language and beyond. I encourage you to look into them after breaking down the first pieces of advice and sharing this code with a peer and receiving feedback from them. See what you understand, and ask for clarification about the parts you don't. Keep an open mind and know that much of this is subjective.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-05T21:05:36.883", "Id": "242274", "ParentId": "242273", "Score": "0" } }, { "body": "<pre><code>game_end = True\nwhile game: \n if point_player == 3:\n game_end = False\n elif point_ai == 3:\n game_end = False\n if game_end:\n\n ...\n\n\n else:\n if point_ai &gt; point_player:\n print(&quot;The A.I won! RIP U&quot;)\n else:\n print(&quot;Dang! You won this time.&quot;)\n exit()\n</code></pre>\n<p>Could be simplified to:</p>\n<pre><code>while True: \n if point_player == 3 or point_ai == 3:\n break\n\n ...\n\nif point_ai &gt; point_player:\n print(&quot;The A.I won! RIP U&quot;)\nelse:\n print(&quot;Dang! You won this time.&quot;)\n</code></pre>\n<hr />\n<p>All of the</p>\n<pre><code>while rock:\n print(&quot;Oh! That's a tie no points.&quot;)\n break\n</code></pre>\n<p>Could be written as:</p>\n<pre><code>if rock:\n print(&quot;Oh! That's a tie no points.&quot;)\n</code></pre>\n<hr />\n<p>Instead of <code>point_ai = point_ai + 1</code>, you can shorten that to <code>point_ai += 1</code>. I would also separate out the code that decides who wins as it makes it a little bit easier to understand what is going on with the logic.</p>\n<pre><code> winner = 'tie' # should be either 'player', 'tie', or 'ai'\n if ai_response == &quot;Rock&quot;:\n if scissor: \n winner = 'ai'\n if paper: \n winner = 'player'\n elif ai_response == &quot;Paper&quot;:\n if rock: \n winner = 'ai'\n if scissor: \n winner = 'player'\n elif ai_response == &quot;Scissor&quot;:\n if rock: \n winner = 'player'\n if paper: \n winner = 'ai'\n\n if winner == 'tie':\n print(&quot;Oh! That's a tie no points.&quot;)\n if winner == 'player':\n print(&quot;Looks like you beat the A.I! +1 Point&quot;)\n player_points += 1\n if winner == 'ai':\n print(&quot;Oh, you lost :( +1 to A.I&quot;)\n ai_points += 1\n</code></pre>\n<hr />\n<p>It feels weird having the <code>rock</code>, <code>paper</code>, <code>scissors</code> Booleans to represent the choice the player made, and then having a string for the choice the ai made. I would use the same data type for both. If we stuck with using strings for both, and with some changes to some variable names, we get:</p>\n<pre><code>while True:\n if player_points == 3 or ai_points == 3:\n break\n print(&quot;Choose an option. (R,P,S)&quot;)\n player_choice = input()\n if player_choice == 'R':\n player_choice = 'Rock'\n elif player_choice == 'P':\n player_choice = 'Paper'\n elif player_choice == 'S':\n player_choice = 'Scissor'\n else:\n print(&quot;That's not an option&quot;)\n exit()\n print(&quot;=======================&quot;)\n print(&quot;You chose &quot; + player_choice)\n ai_choice = random.choice(option)\n print(&quot;The A.I chose &quot; + ai_choice)\n print(&quot;=======================&quot;)\n\n winner = 'tie' # should be either 'player', 'tie', or 'ai'\n if ai_choice == &quot;Rock&quot;:\n if player_choice == 'Scissor': \n winner = 'ai'\n if player_choice == 'Paper': \n winner = 'player'\n elif ai_choice == &quot;Paper&quot;:\n if player_choice == 'Rock': \n winner = 'ai'\n if player_choice == 'Scissor':\n winner = 'player'\n elif ai_choice == &quot;Scissor&quot;:\n if player_choice == 'Rock': \n winner = 'player'\n if player_choice == 'Paper': \n winner = 'ai'\n\n if winner == 'tie':\n print(&quot;Oh! That's a tie no points.&quot;)\n if winner == 'player':\n print(&quot;Looks like you beat the A.I! +1 Point&quot;)\n player_points += 1\n if winner == 'ai':\n print(&quot;Oh, you lost :( +1 to A.I&quot;)\n ai_points += 1\n \n print(&quot;You have &quot; + str(player_points) + &quot; points&quot;)\n print(&quot;The A.I has &quot; + str(ai_points) + &quot; points.&quot;)\n print(&quot;=======================&quot;)\n</code></pre>\n<hr />\n<p>That looks worse in some ways, mostly because of the longer variable names, but everything is going to get better soon. I think now it's about time to break this game up into multiple functions. I like to have all of my print statements in a separate from the logic. In this case, I'm going to keep all of the print statements inside of the <code>start_game</code> function, and we'll put all of the logic outside of the <code>start_game</code> function. This helps us easily read through and understand what is going on, and then if we're having a problem, we can investigate the particular function whose logic is producing incorrect results. This also makes it easier to unit test the logic.</p>\n<pre><code>def get_players_choice():\n print(&quot;Choose an option. (R,P,S)&quot;)\n player_choice = input()\n if player_choice == 'R':\n player_choice = 'Rock'\n elif player_choice == 'P':\n player_choice = 'Paper'\n elif player_choice == 'S':\n player_choice = 'Scissor'\n else:\n player_choice = False\n\n return player_choice\n\ndef get_ai_choice():\n return random.choice(option)\n\ndef calculate_winner(player_choice, ai_choice):\n ''' returns either 'player', 'tie', or 'ai' '''\n winner = 'tie'\n if ai_choice == &quot;Rock&quot;:\n if player_choice == 'Scissor': \n winner = 'ai'\n if player_choice == 'Paper': \n winner = 'player'\n elif ai_choice == &quot;Paper&quot;:\n if player_choice == 'Rock': \n winner = 'ai'\n if player_choice == 'Scissor':\n winner = 'player'\n elif ai_choice == &quot;Scissor&quot;:\n if player_choice == 'Rock': \n winner = 'player'\n if player_choice == 'Paper': \n winner = 'ai'\n return winner\n\ndef display_results(winner):\n if winner == 'tie':\n print(&quot;Oh! That's a tie no points.&quot;)\n elif winner == 'player':\n print(&quot;Looks like you beat the A.I! +1 Point&quot;)\n elif winner == 'ai':\n print(&quot;Oh, you lost :( +1 to A.I&quot;)\n \n print(&quot;You have &quot; + str(player_points) + &quot; points&quot;)\n print(&quot;The A.I has &quot; + str(ai_points) + &quot; points.&quot;)\n print(&quot;=======================&quot;)\n\ndef start_game():\n player_points = 0\n ai_points = 0\n while True:\n if player_points == 3 or ai_points == 3:\n break\n\n player_choice = get_players_choice()\n if player_choice is False:\n print(&quot;That's not an option&quot;)\n exit()\n \n print(&quot;=======================&quot;)\n print(&quot;You chose &quot; + player_choice)\n ai_choice = get_ai_choice()\n print(&quot;The A.I chose &quot; + ai_choice)\n print(&quot;=======================&quot;)\n\n winner = calculate_winner(player_choice, ai_choice)\n\n if winner == 'player':\n player_points += 1\n elif winner == 'ai':\n ai_points += 1\n \n display_results(winner)\n\n if ai_points &gt; player_points:\n print(&quot;The A.I won! RIP U&quot;)\n else:\n print(&quot;Dang! You won this time.&quot;)\n</code></pre>\n<hr />\n<p>Now a little improvement as we refactor. This is kind of like chess, the more you do it, the more patterns just jump out at you. Let's start with the <code>get_players_choice</code> function. One pattern is that when asking for input from the user, instead of requiring 'R', 'P', 'S', we can grab the first character, lowercase it, and then check against that. We would then be accepting 'r', 'R', 'rock', 'Rock', or anything else that starts with the letter 'r'. Some other things:</p>\n<pre><code> print(&quot;Choose an option. (R,P,S)&quot;)\n player_choice = input()\n</code></pre>\n<p>Is the same as</p>\n<pre><code>player_choice = input(&quot;Choose an option. (R,P,S)&quot;)\n</code></pre>\n<p>While I said I like to keep the print statements and the logic separate, <code>display_results</code> is a function that is obviously all about displaying text on the screen, and in the same way it would be expected that a function called <code>get_players_choice</code> is doing more than just logic. We're going to be using the input function, and that requires asking the user for input, and it requires telling them if the input is invalid. Anyhow, here is my revised <code>get_players_choice</code> function.</p>\n<pre><code>def get_players_choice():\n while True:\n player_choice = input(&quot;Choose an option (R,P,S), or push enter to exit&quot;)\n\n if not player_choice: # If they pushed enter\n return False\n\n first_char = player_choice[0].lower()\n\n if first_char == 'r':\n return 'Rock'\n elif first_char == 'p':\n return 'Paper'\n elif first_char == 's':\n return 'Scissor'\n\n print(&quot;That's not an option&quot;)\n</code></pre>\n<hr />\n<p>That display_choices and display_results can actually be combined together. And we end up with this as the final result. There are still some additional improvements that can be made, but what those are matters on what your goals are. Is it important that the code can be extended easily? Is performance important? Do you like object oriented designs? Etc.</p>\n<pre><code>''' A Rock Papers Scissors game '''\nimport random\n\ndef get_players_choice():\n while True:\n player_choice = input(&quot;Choose an option (R,P,S), or push enter to exit: &quot;)\n\n if not player_choice: # If they pushed enter\n return False\n\n first_char = player_choice[0].lower()\n\n if first_char == 'r':\n return 'Rock'\n if first_char == 'p':\n return 'Paper'\n if first_char == 's':\n return 'Scissor'\n\n print(&quot;That's not an option&quot;)\n\n\ndef get_ais_choice():\n return random.choice([&quot;Rock&quot;, &quot;Paper&quot;, &quot;Scissor&quot;])\n\ndef calculate_winner(player, ai):\n ''' Takes either 'Rock', 'Paper', or 'Scissors', for both the player and the ai.\n returns either 'player', 'tie', or 'ai' '''\n\n if ai == &quot;Rock&quot;:\n if player == 'Scissor': return 'ai'\n if player == 'Paper': return 'player'\n\n elif ai == &quot;Paper&quot;:\n if player == 'Rock': return 'ai'\n if player == 'Scissor': return 'player'\n\n elif ai == &quot;Scissor&quot;:\n if player == 'Rock': return 'player'\n if player == 'Paper': return 'ai'\n\n return 'tie'\n\ndef display_round_outcome(player_choice, ai_choice, winner, player_points, ai_points):\n print(&quot;=======================&quot;)\n print(&quot;You chose &quot; + player_choice)\n print(&quot;The A.I chose &quot; + ai_choice)\n print(&quot;=======================&quot;)\n\n if winner == 'tie':\n print(&quot;Oh! That's a tie no points.&quot;)\n elif winner == 'player':\n print(&quot;Looks like you beat the A.I! +1 Point&quot;)\n elif winner == 'ai':\n print(&quot;Oh, you lost :( +1 to A.I&quot;)\n\n print(f&quot;You have {player_points} points&quot;)\n print(f&quot;The A.I has {ai_points} points.&quot;)\n print(&quot;=======================&quot;)\n\n\ndef start_game():\n player_points = 0\n ai_points = 0\n\n while True:\n if player_points &gt;= 3 or ai_points &gt;= 3:\n break\n\n player_choice = get_players_choice()\n ai_choice = get_ais_choice()\n\n if player_choice is False:\n break\n\n winner = calculate_winner(player_choice, ai_choice)\n\n if winner == 'player':\n player_points += 1\n elif winner == 'ai':\n ai_points += 1\n\n display_round_outcome(player_choice, ai_choice, winner, player_points, ai_points)\n\n if ai_points &gt; player_points:\n print(&quot;The A.I won! RIP U&quot;)\n elif ai_points == player_points:\n print(&quot;It's a tie.&quot;)\n else:\n print(&quot;Dang! You won this time.&quot;)\n\n\nprint(&quot;|=========================|&quot;)\nprint(&quot;| Rock Paper Scissor |&quot;)\nprint(&quot;| (R) (P) (S) |&quot;)\nprint(&quot;|=========================|&quot;)\nprint(&quot;Would you like to start? y/n&quot;)\nanswer = input()\nif answer == &quot;y&quot;:\n print(&quot;Welcome to the game of Rock Paper Scissors&quot;)\n start_game()\nelif answer == &quot;n&quot;:\n print('Well ok then.. Fine leave')\nelse:\n print(&quot;That's not an option.&quot;)\n</code></pre>\n<p>Let me know what questions you have, and what I wrote to quickly and didn't do a good job in explaining me decisions with. But I hope that kind of helps seeing how I would refactor this code, and hopefully you can see how much easier it is to read and debug the final version when you have everything split chunks of code. The difference is a lot more obvious when it's complicated code that you wrote a long time ago, or that something else wrote, and you're trying to figure out what is going on.</p>\n<hr />\n<p><strong>Edit:</strong></p>\n<p>My brother came to a very similar conclusion for how he would refactor this code, but he found a shorter way of checking who the winner is. Here is his <code>calculate_winner</code> function.</p>\n<pre><code>what_beats_what = {\n 'Paper': 'Rock',\n 'Scissors': 'Paper',\n 'Rock': 'Scissors',\n}\n\ndef get_winner(user_weapon, ai_weapon):\n if what_beats_what[user_weapon] == ai_weapon:\n return 'USER'\n elif what_beats_what[ai_weapon] == user_weapon:\n return 'AI'\n else:\n return 'TIE'\n</code></pre>\n<p>Also, it's impossible for the game to end in a tie as whoever reaches 3 points first will always be the winner.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-05T21:14:03.267", "Id": "242275", "ParentId": "242273", "Score": "1" } } ]
{ "AcceptedAnswerId": "242275", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-05T20:59:39.277", "Id": "242273", "Score": "0", "Tags": [ "python", "python-3.x" ], "Title": "Looking to simplify my first python Rock, paper, Scissors project" }
242273
<p><strong>Context</strong></p> <p>The original idea is to create an efficient grid structure for a Sudoku like board but this can be applied to many such grid structures (like wavelet transform on images, JPEG2000 etc). This particular one is basically a 9x9 <code>Board</code> which is made up of 3x3 <code>Block</code>s where each <code>Block</code> is made up of 3 x <code>Axis a a a</code> type. You may think <code>Axis</code> type like a list limited to having only 3 elements (no more no less) and no empty or identiy element.</p> <p>I have defined the <code>Axis</code>, <code>Block</code> and <code>Board</code> types as;</p> <pre><code>data Axis a = Axis { _0 :: a , _1 :: a , _2 :: a } deriving (Eq, Functor) type Block a = (Axis(Axis a)) type Board a = (Axis(Axis (Block a))) instance Show a =&gt; Show (Axis a) where showsPrec _ (Axis x y z) = shows x . (' ':) . shows y . (' ':) . shows z </code></pre> <p>As you notice, polymorphic <code>Axis</code> type is like a ternary tree with no leaves where the nodes can either be another <code>Axis a</code> type or an <code>a</code> type value. <em>Does anybody know a general name for such data types in Haskell literature?</em></p> <p>Anyways, by doing so, once i have a <code>Board</code> then i can easily access any <code>Block</code> or <code>Cell</code> quite efficiently. To access one of the 9 <code>Block</code>s i can now simply do</p> <pre><code>_0 . _1 $ myBoard -- like (row 0, col 1) from myBoard </code></pre> <p>where to gain access to any cell within the <code>Board</code> all i have to do is to get to the <code>Block</code> and then to the cell like</p> <pre><code>_2 . _1 . _0 . _1 $ myBoard -- coord of cell . coord of Block =&gt; (_2 . _1) . (_0 . _1) </code></pre> <p><strong>Problem</strong></p> <p>The problem arose when building up my <code>Board</code> type from a provided <code>String</code>. Since i post this here, I have done it but it smells like a fish and i think there must be a better way.</p> <p>So the input data comes in the form of a string of 81 numeric characters among <code>0..9</code>. The string should fill up the board line by line. So if my board supposed to be a 2D list, then a <code>chunksOf 9 . map ((read :: String-&gt; Int) . pure)</code> would be sufficient. However the <code>Board</code> type is a 4 fold nested <code>Axis</code> type.</p> <p>To start with, I couldn't even find a way to write a <code>Read</code> instance for the <code>Board</code> type at all. My solution is to first convert the flat list into a nested list of proper structure like.</p> <pre><code>nestList :: [a] -&gt; [[[[a]]]] nestList = map transpose . chunksOf 3 . chunksOf 3 . chunksOf 3 </code></pre> <p>and then after a 2 days war with GHC infinite type errors and whatnot, i could finally come up with this stinky part.</p> <pre><code>axify :: [[[[a]]]] -&gt; Board a axify ([a,b,c]) = Axis (Axis (axify' $ a !! 0) (axify' $ a !! 1) (axify' $ a !! 2)) (Axis (axify' $ b !! 0) (axify' $ b !! 1) (axify' $ b !! 2)) (Axis (axify' $ c !! 0) (axify' $ c !! 1) (axify' $ c !! 2)) where axify' ([a,b,c]) = Axis (Axis (a !! 0) (a !! 1) (a !! 2)) (Axis (b !! 0) (b !! 1) (b !! 2)) (Axis (c !! 0) (c !! 1) (c !! 2)) </code></pre> <p>Now this works. I can fill the <code>Board</code> properly from a flat string and the <code>Show</code> instance just gives back a stringified version of the <code>nestedList</code>.</p> <p><strong>Question</strong></p> <p>Could anybody please help me with a proper <code>Read</code> instance or at least an <code>axify</code> function that is idiomatic (generalized to <code>n</code> fold <code>Axis a</code> type)?</p> <p>Many thanks in advance.</p>
[]
[ { "body": "<p>Consider the polymorphic function:</p>\n\n<pre><code>axis :: [a] -&gt; Axis a\naxis [x,y,z] = Axis x y z\n</code></pre>\n\n<p>You want to apply this at each of the four \"list levels\" of the output <code>[[[[a]]]]</code> of <code>nestList</code>. So, if you have:</p>\n\n<pre><code>lst4 : [[[[Char]]]]\nlst4 = nestList \"295743861431865927876192543387459216612387495549216738763534189928671354154938672\"\n</code></pre>\n\n<p>you want to write:</p>\n\n<pre><code>axis lst4 :: Axis [[[Char]]]\n</code></pre>\n\n<p>to replace the outermost list with an <code>Axis</code>, then you want to <code>fmap axis</code> over the <code>Axis</code>:</p>\n\n<pre><code>fmap axis . axis $ lst4 :: Axis (Axis [[Char]])\n</code></pre>\n\n<p>to replace the second-level list with an <code>Axis</code>, then you want to do a double-<code>fmap (fmap axis)</code>:</p>\n\n<pre><code>fmap (fmap axis) . fmap axis . axis $ lst4 :: Axis (Axis (Axis [Char]))\n</code></pre>\n\n<p>to replace the third-level list, and finally the innermost list:</p>\n\n<pre><code>fmap (fmap (fmap axis)) . fmap (fmap axis) . fmap axis . axis $ lst4 :: Axis (Axis (Axis (Axis Char)))\n</code></pre>\n\n<p>So, you actually have:</p>\n\n<pre><code>axify :: [[[[a]]]] -&gt; Board a\naxify = fmap (fmap (fmap axis)) . fmap (fmap axis) . fmap axis . axis\n</code></pre>\n\n<p>Alternatively, instead of using the functor instance for <code>Axis</code>, you could use the functor instance for lists, starting from the inside out:</p>\n\n<pre><code>axify = axis . map axis . map (map axis) . map (map (map axis))\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-16T06:28:49.280", "Id": "475651", "Score": "0", "body": "Thank you for your time. That's soo much better. i can't help questioning though.. what would be the proper approach in Haskell to axify into an indefinite depth..? Since `axify` can not be made recursive, should one look into dependent types or type families or perhaps comonads. I am quite lost there. I was reading [this](https://stackoverflow.com/a/42917974/4543207) and [this](https://stackoverflow.com/a/15893440/4543207)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-16T19:10:24.773", "Id": "475743", "Score": "1", "body": "That would make a very good Stack Overflow question, particularly if you could give a simplified example that illustrates exactly how you'd want `axify` to behave. For example, are you maybe looking for something like `axify 1 [\"foo\",\"bar\",zip\"] = Axis \"foo\" \"bar\" \"zip\"` vs. `axify 2 [\"foo\",\"bar\",\"zip\"] = Axis (Axis \"f\" \"o\" \"o\", Axis \"b\" \"a\" \"r\", Axis \"z\" \"i\" \"p\")`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-16T20:15:06.997", "Id": "475747", "Score": "0", "body": "So in other words you say, *\"Find a new data type for nested lists bearing the depth in the first place\"* such that the type signature for `nesrList` would become like `nestList :: [a] -> Nested a` whereas `data Nested a = Nested Int [Nested a]` perhaps or stg. I feel this quest might require a whole new library. :) I will think about it." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-16T05:48:24.757", "Id": "242379", "ParentId": "242277", "Score": "3" } }, { "body": "<p>@K. A. Buhr's answer is good but eventhough i have accepted, it is very tailored to a single problem. A more generalized one would be more idiomatic alas dealing with such nested data structures in Haskell quickly take you into many rabbit holes. Think about flattening an indefinitelly nested list with a recursive function. We have a similar problem at hand here.</p>\n\n<p>As it turns out, we can do it without getting our hands wet with dependent types and type famillies etc. So here I am answering my own question starting with a little prologue. </p>\n\n<p><strong>Prologue</strong></p>\n\n<p>When I started with Haskell the most intimidating part happened to be (still is) the Language extensions. To start with there are so many of them. While some are very straightforward, some have the potentital to turn the language into a signifcantly different one. When you study them through some tutorials you are forced to walk on a specific case of authors choice. Most of the time i can not even tell which one to apply for a particular need of mine. Just like in this case.</p>\n\n<p>Let's get started. As always most of the time, deep inside, at the dark corners of SO there are gem like answers. For this particular case my starting point was <a href=\"https://stackoverflow.com/a/5994717/4543207\">Is there a function to flatten a nested list of elements?</a> This answer is old but really bears the answer to many similar problems. Deserves upvoting :)</p>\n\n<p><strong>Solution</strong></p>\n\n<p>We best start with a new type class which will be the home of the <code>axify</code> function. This particular type class definition will be unusual though. We will constrain it both with the input (<code>i</code>) and the output (<code>o</code>) types, well type parameters. So 2 type parameters and 1 type class => <a href=\"https://downloads.haskell.org/~ghc/latest/docs/html/users_guide/glasgow_exts.html#extension-MultiParamTypeClasses\" rel=\"nofollow noreferrer\"><code>{-# LANGUAGE MultiParamTypeClasses #-}</code></a>.</p>\n\n<pre><code>class Axable i o where\n axify :: [i] -&gt; Axis o\n</code></pre>\n\n<p>So <code>axify</code> function takes a list of <code>i</code> types and gives an <code>Axis o</code> type. <code>axify</code> also is a recursive function. So we need a base case for termination. If we think about the simplest case of <code>axify [1,2,3] == Axis 1 2 3</code>. We notice that both <code>i</code> and <code>o</code> are of the same type which is <code>Int</code>. This base case deserves an instance of it's own.</p>\n\n<pre><code>instance Axable a a where\n axify [a,b,c] = Axis a b c\n</code></pre>\n\n<p>Now how about having a nested list to <code>axify</code> at hand?</p>\n\n<pre><code>instance Axable i o =&gt; Axable [i] (Axis o) where\n axify [as,bs,cs] = Axis (axify as) (axify bs) (axify cs)\n</code></pre>\n\n<p>which says, given both <code>i</code> and <code>o</code> are of Axable class, we define an instance for the case when the input is of <code>[i]</code> and the output is of <code>Axis o</code> types.</p>\n\n<p><code>:r</code> and</p>\n\n<pre><code>• Illegal instance declaration for ‘Axable a a’\n (All instance types must be of the form (T a1 ... an)\n where a1 ... an are *distinct type variables*,\n and each type variable appears at most once in the instance head.\n Use FlexibleInstances if you want to disable this.)\n</code></pre>\n\n<p>Ok throw a <a href=\"https://downloads.haskell.org/~ghc/latest/docs/html/users_guide/glasgow_exts.html#extension-FlexibleInstances\" rel=\"nofollow noreferrer\"><code>{-# LANGUAGE FlexibleInstances #-}</code></a> in the mix to see <code>Ok, one module loaded.</code></p>\n\n<pre><code>ts = \"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 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 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81\"\nnestList :: String -&gt; [[[[Int]]]]\nnestList = map transpose . chunksOf 3 . chunksOf 3 . chunksOf 3 . map read . words\n\nλ&gt; axify (nestList ts) :: Board Int\n1 2 3 10 11 12 19 20 21 4 5 6 13 14 15 22 23 24 7 8 9 16 17 18 25 26 27 28 29 30 37 38 39 46 47 48 31 32 33 40 41 42 49 50 51 34 35 36 43 44 45 52 53 54 55 56 57 64 65 66 73 74 75 58 59 60 67 68 69 76 77 78 61 62 63 70 71 72 79 80 81\n</code></pre>\n\n<p><strong>Epilogue</strong></p>\n\n<p>The above answer in SO uses the <code>OverlappingInstances</code> language extension which is depreciated in the favor of the new <em>instance only</em> pragmas <code>{-# OVERLAPPING #-}</code>, <code>{-# OVERLAPPABLE #-}</code>, <code>{-# OVERLAPS #-}</code>, or <code>{-# INCOHERENT #-}</code>. So i was getting prepared to use one of them but it seems nothing is overlapping here. Now of course we shall consider embedding the nesting functionality <code>nestList</code> into <code>axify</code> as well but that's a relatively trivial job which is out of the concerns of this topic.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-19T13:13:55.127", "Id": "242561", "ParentId": "242277", "Score": "2" } }, { "body": "<p>You can use recursive type class to parse arbitrarily nested axes. </p>\n\n<pre><code>instance Read a =&gt; Read (Axis a) where\n readsPrec n str = do\n (a, str) &lt;- readsPrec n str\n (b, str) &lt;- readsPrec n str\n (c, str) &lt;- readsPrec n str\n return (Axis a b c, str)\n</code></pre>\n\n<p>Now you can</p>\n\n<pre><code>read $ unwords $ map show [1..3^2] :: Axis (Axis Int)\nread $ unwords $ map show [1..3^3] :: Axis (Axis (Axis Int))\nread $ unwords $ map show [1..3^4] :: Axis (Axis (Axis (Axis Int)))\n...\n</code></pre>\n\n<hr>\n\n<p>It is handy to use <a href=\"https://wiki.haskell.org/GHC/Type_families#An_associated_type_synonym_example\" rel=\"nofollow noreferrer\">associated type synonyms</a> to implement <code>axify</code>:</p>\n\n<pre><code>{-# LANGUAGE TypeFamilies #-}\n\nclass Axify a where\n type Res a\n axify :: a -&gt; Res a\n\ninstance Axify Int where\n type Res Int = Int\n axify a = a\n\ninstance Axify a =&gt; Axify [a] where\n type Res [a] = Axis (Res a)\n axify [a,b,c] = Axis (axify a) (axify b) (axify c)\n\n-- axify [1,2,3::Int] :: Axis Int\n-- axify [[1,2,3], [4,5,6], [7,8,9::Int]] :: Axis (Axis Int)\n</code></pre>\n\n<p>Actually this is the same approach as in your own answer (with <code>MultiParamClassTypes</code>) but a bit more robust as associated types establish one-to-one correspondence between <code>[a]</code> and <code>Axis a</code>.</p>\n\n<p>This allows type checker to infer more types. E.g.</p>\n\n<pre><code>axify [1,2,3::Int]\n</code></pre>\n\n<p>typechecks with associated types but requires additional type signature with multiparam type class.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-19T15:08:53.353", "Id": "476008", "Score": "0", "body": "Thank you. This is great `Read` instance which earns an upvote but it's only a half measure. It's fine in nesting the `Axis Int` type from a `String` but the `Board Int ~ Axis (Axis (Axis (Axis Int)))` gets populated incorrectly. The point of `nestList` function is to put the input `String` into such a nested structure that will yield a correct axifying process. I mean the first `Block Int` would be `Axis (Axis 1 2 3) (Axis 10 11 12) (Axis 19 20 21)` not `Axis (Axis 1 2 3) (Axis 4 5 6) (Axis 7 8 9)`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-19T15:35:35.463", "Id": "476013", "Score": "0", "body": "Thank you for extending your answer. This might form a reasonable exercise for me to step into type families." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-19T14:27:04.700", "Id": "242568", "ParentId": "242277", "Score": "2" } } ]
{ "AcceptedAnswerId": "242379", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-14T14:24:05.933", "Id": "242277", "Score": "4", "Tags": [ "haskell" ], "Title": "Reading String data into a Tree like nested grid structure (like Sudoku Board)" }
242277
<p>I am learning the xlib library and I made a xmenu utility in order to practice it.</p> <p>It receives as input a menu specification where each line is a menu entry.<br> Each line can be indented with tabs to represent nested menus.<br> Each line is made of a label and a command separated by tab.<br> When you select an entry in the menu, the corresponding command is output to the stdout.<br> It becomes clearer by trying it.</p> <p>Here is a sample input (the site may convert tabs to spaces, you have to know that lines are indented by tabs and labels and commands are separated by tabs):</p> <pre><code>Label A Command 1 Label B Command 2 Label C Command 3 sub A Command 4 sub B Command 5 subsubA Command 6 subsubB Command 7 sub C Command 8 Label D Command 9 sub D Command 10 subsubC Command 11 Label E Command 12 Label F Command 13 </code></pre> <p>By using this as stdin, the program will draw a menu with 6 entries (<code>Label A</code> to <code>Label F</code>), where <code>Label C</code> and <code>Label D</code> contains submenus.</p> <p>The previous input will generate the following menu stack: <a href="https://i.stack.imgur.com/xJDrG.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/xJDrG.png" alt="menus"></a></p> <p>Here is the code:</p> <pre><code>#include &lt;err.h&gt; #include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;string.h&gt; #include &lt;unistd.h&gt; #include &lt;X11/Xlib.h&gt; #include &lt;X11/Xutil.h&gt; /* macros */ #define LEN(x) (sizeof (x) / sizeof (x[0])) #define MAX(x,y) ((x)&gt;(y)?(x):(y)) #define MIN(x,y) ((x)&lt;(y)?(x):(y)) #define FONT "-*-*-medium-*-*-*-14-*-*-*-*-*-*-*" #define UNPRESSEDBG "#222222" #define UNPRESSEDFG "#cccccc" #define PRESSEDBG "#ffffff" #define PRESSEDFG "#000000" #define DECORATIONBG "#bbbbbb" #define DECORATIONFG "#000000" #define ITEMW 130 #define ITEMB 5 #define BORDER 2 /* color enum */ enum {ColorFG, ColorBG, ColorLast}; /* draw context structure */ struct DC { unsigned long unpressed[ColorLast]; unsigned long pressed[ColorLast]; unsigned long decoration[ColorLast]; Drawable d; GC gc; XFontStruct *font; int fonth; }; /* menu geometry structure */ struct Geometry { int itemb; /* item border */ int itemw; /* item width */ int itemh; /* item height */ int border; /* window border */ }; /* screen geometry structure */ struct ScreenGeom { int cursx, cursy; /* cursor position */ int screenw, screenh; /* screen width and height */ }; /* menu item structure */ struct Item { char *label; char *output; int x, y; struct Item *next; struct Menu *submenu; }; /* menu structure */ struct Menu { struct Menu *parent; struct Item *list; struct Item *selected; int x, y, w, h; unsigned level; unsigned nitems; Window win; }; /* function declarations */ static unsigned long getcolor(const char *s); static void setupdc(void); static void setupgeom(void); static void setupgrab(void); static struct Item *allocitem(size_t count, const char *label, const char *output); static struct Menu *allocmenu(struct Menu *parent, struct Item *list, unsigned level); static void getmenuitem(Window win, int x, int y, struct Menu **menu_ret, struct Item **item_ret); static void printmenu(size_t level, struct Menu *menu); static void drawmenu(void); static void calcscreengeom(void); static void calcmenu(struct Menu *menu); static void setcurrmenu(struct Menu *menu); static void parsestdin(void); static void run(void); static void cleanupexit(void); static void usage(void); /* X variables */ static Colormap colormap; static Display *dpy; static Window rootwin; static int screen; static struct DC dc; /* menu variables */ static struct Menu *rootmenu = NULL; static struct Menu *currmenu = NULL; /* geometry variables */ static struct Geometry geom; static struct ScreenGeom sgeom; /* flag variables */ static Bool override_redirect = True; int main(int argc, char *argv[]) { int ch; while ((ch = getopt(argc, argv, "w")) != -1) { switch (ch) { case 'w': override_redirect = False; break; default: usage(); break; } } argc -= optind; argv += optind; /* open connection to server and set X variables */ if ((dpy = XOpenDisplay(NULL)) == NULL) errx(1, "cannot open display"); screen = DefaultScreen(dpy); rootwin = RootWindow(dpy, screen); colormap = DefaultColormap(dpy, screen); /* setup */ setupdc(); setupgeom(); setupgrab(); /* generate menus and recalculate them */ parsestdin(); if (rootmenu == NULL) errx(1, "no menu generated"); calcscreengeom(); calcmenu(rootmenu); setcurrmenu(rootmenu); /* debug */ //printmenu(0, rootmenu); /* run event loop */ run(); return 1; /* UNREACHABLE */ } /* get color from color string */ static unsigned long getcolor(const char *s) { XColor color; if(!XAllocNamedColor(dpy, colormap, s, &amp;color, &amp;color)) errx(1, "cannot allocate color: %s", s); return color.pixel; } /* init draw context */ static void setupdc(void) { /* get color pixels */ dc.unpressed[ColorBG] = getcolor(UNPRESSEDBG); dc.unpressed[ColorFG] = getcolor(UNPRESSEDFG); dc.pressed[ColorBG] = getcolor(PRESSEDBG); dc.pressed[ColorFG] = getcolor(PRESSEDFG); dc.decoration[ColorBG] = getcolor(DECORATIONBG); dc.decoration[ColorFG] = getcolor(DECORATIONFG); /* try to get font */ if ((dc.font = XLoadQueryFont(dpy, FONT)) == NULL) errx(1, "cannot load font"); dc.fonth = dc.font-&gt;ascent + dc.font-&gt;descent; /* create GC and set its font */ dc.gc = XCreateGC(dpy, rootwin, 0, NULL); XSetFont(dpy, dc.gc, dc.font-&gt;fid); } /* init menu geometry values */ static void setupgeom(void) { geom.itemb = ITEMB; geom.itemh = dc.fonth + ITEMB * 2; geom.itemw = ITEMW; geom.border = BORDER; } /* grab pointer */ static void setupgrab(void) { XGrabPointer(dpy, rootwin, True, ButtonPressMask, GrabModeAsync, GrabModeAsync, None, None, CurrentTime); } /* allocate an item */ static struct Item * allocitem(size_t count, const char *label, const char *output) { struct Item *p; if ((p = malloc(sizeof *p)) == NULL) err(1, "malloc"); if ((p-&gt;label = strdup(label)) == NULL) err(1, "strdup"); if ((p-&gt;output = strdup(output)) == NULL) err(1, "strdup"); p-&gt;x = 0; p-&gt;y = count * geom.itemh; p-&gt;next = NULL; p-&gt;submenu = NULL; return p; } /* allocate a menu */ static struct Menu * allocmenu(struct Menu *parent, struct Item *list, unsigned level) { XSetWindowAttributes swa; struct Menu *p; if ((p = malloc(sizeof *p)) == NULL) err(1, "malloc"); p-&gt;parent = parent; p-&gt;list = list; p-&gt;selected = NULL; p-&gt;x = 0; p-&gt;y = 0; p-&gt;w = geom.itemw; p-&gt;h = geom.itemh; p-&gt;level = level; p-&gt;nitems = 0; swa.override_redirect = override_redirect; swa.background_pixel = dc.decoration[ColorBG]; swa.border_pixel = dc.decoration[ColorFG]; swa.event_mask = ExposureMask | KeyPressMask | ButtonPressMask | ButtonReleaseMask | PointerMotionMask; p-&gt;win = XCreateWindow(dpy, rootwin, 0, 0, geom.itemw, geom.itemh, geom.border, CopyFromParent, CopyFromParent, CopyFromParent, CWOverrideRedirect | CWBackPixel | CWBorderPixel | CWEventMask, &amp;swa); return p; } /* create menus and items from the stdin */ static void parsestdin(void) { char *s, buf[BUFSIZ]; char *label, *output; unsigned level = 0; unsigned i; struct Item *item, *p; struct Menu *menu; struct Menu *prevmenu = NULL; size_t count = 0; /* number of items in the current menu */ while (fgets(buf, BUFSIZ, stdin) != NULL) { level = 0; s = buf; while (*s == '\t') { level++; s++; } label = output = s; while (*s != '\0' &amp;&amp; *s != '\t' &amp;&amp; *s != '\n') s++; while (*s == '\t') *s++ = '\0'; if (*s != '\0' &amp;&amp; *s != '\n') output = s; while (*s != '\0' &amp;&amp; *s != '\n') s++; if (*s == '\n') *s = '\0'; item = allocitem(count, label, output); if (prevmenu == NULL) { /* there is no menu yet */ menu = allocmenu(NULL, item, level); rootmenu = menu; prevmenu = menu; count = 1; } else if (level &lt; prevmenu-&gt;level) { /* item is continuation of previous menu*/ for (menu = prevmenu, i = level; menu != NULL &amp;&amp; i &lt; prevmenu-&gt;level; menu = menu-&gt;parent, i++) ; if (menu == NULL) errx(1, "reached NULL menu"); for (p = menu-&gt;list; p-&gt;next != NULL; p = p-&gt;next) ; p-&gt;next = item; prevmenu = menu; } else if (level == prevmenu-&gt;level) { for (p = prevmenu-&gt;list; p-&gt;next != NULL; p = p-&gt;next) ; p-&gt;next = item; } else if (level &gt; prevmenu-&gt;level) { menu = allocmenu(prevmenu, item, level); for (p = prevmenu-&gt;list; p-&gt;next != NULL; p = p-&gt;next) ; p-&gt;submenu = menu; prevmenu = menu; } } } /* calculate screen geometry */ static void calcscreengeom(void) { Window w1, w2; /* unused variables */ int a, b; /* unused variables */ unsigned mask; /* unused variable */ XQueryPointer(dpy, rootwin, &amp;w1, &amp;w2, &amp;sgeom.cursx, &amp;sgeom.cursy, &amp;a, &amp;b, &amp;mask); sgeom.screenw = DisplayWidth(dpy, screen); sgeom.screenh = DisplayHeight(dpy, screen); } /* recursivelly calculate height and position of the menus */ static void calcmenu(struct Menu *menu) { XWindowChanges changes; struct Item *item, *p; size_t i; /* calculate number of items */ i = 0; for (item = menu-&gt;list; item != NULL; item = item-&gt;next) i++; menu-&gt;nitems = i; menu-&gt;h = geom.itemh * i; /* calculate menu's x and y positions */ if (menu-&gt;parent == NULL) { /* if root menu, calculate in respect to cursor */ if (sgeom.screenw - sgeom.cursx &gt;= menu-&gt;w) menu-&gt;x = sgeom.cursx; else if (sgeom.cursx &gt; menu-&gt;w) menu-&gt;x = sgeom.cursx - menu-&gt;w; if (sgeom.screenh - sgeom.cursy &gt;= menu-&gt;h) menu-&gt;y = sgeom.cursy; else if (sgeom.screenh &gt; menu-&gt;h) menu-&gt;y = sgeom.screenh - menu-&gt;h; } else { /* else, calculate in respect to parent menu */ /* search for the item in parent menu that generates this menu */ for (p = menu-&gt;parent-&gt;list; p-&gt;submenu != menu; p = p-&gt;next) ; if (sgeom.screenw - (menu-&gt;parent-&gt;x + menu-&gt;parent-&gt;w) &gt;= menu-&gt;w) menu-&gt;x = menu-&gt;parent-&gt;x + menu-&gt;parent-&gt;w; else if (menu-&gt;parent-&gt;x &gt; menu-&gt;w) menu-&gt;x = menu-&gt;parent-&gt;x - menu-&gt;w; if (sgeom.screenh - p-&gt;y &gt; menu-&gt;h) menu-&gt;y = p-&gt;y; else if (sgeom.screenh - menu-&gt;parent-&gt;y &gt; menu-&gt;h) menu-&gt;y = menu-&gt;parent-&gt;y; else if (sgeom.screenh &gt; menu-&gt;h) menu-&gt;y = sgeom.screenh - menu-&gt;h; } /* calculate position of each item in the menu */ for (i = 0, item = menu-&gt;list; item != NULL; item = item-&gt;next, i++) { item-&gt;x = menu-&gt;x; item-&gt;y = menu-&gt;y + i * geom.itemh; } /* update menu geometry */ changes.height = menu-&gt;h; changes.x = menu-&gt;x; changes.y = menu-&gt;y; XConfigureWindow(dpy, menu-&gt;win, CWHeight | CWX | CWY, &amp;changes); for (item = menu-&gt;list; item != NULL; item = item-&gt;next) { if (item-&gt;submenu != NULL) calcmenu(item-&gt;submenu); } } /* print menus */ static void printmenu(size_t level, struct Menu *menu) { struct Item *item; size_t i; for (item = menu-&gt;list; item != NULL; item = item-&gt;next) { for (i = 0; i &lt; level; i++) putchar('\t'); printf("%u:%s: %s\n", menu-&gt;nitems, item-&gt;label, item-&gt;output); if (item-&gt;submenu != NULL) printmenu(level+1, item-&gt;submenu); } } /* get menu and item of given window and position */ static void getmenuitem(Window win, int x, int y, struct Menu **menu_ret, struct Item **item_ret) { struct Menu *menu = NULL; struct Item *item = NULL; for (menu = currmenu; menu != NULL; menu = menu-&gt;parent) { if (menu-&gt;win == win) { for (item = menu-&gt;list; item != NULL; item = item-&gt;next) { if (x &gt;= item-&gt;x &amp;&amp; x &lt;= item-&gt;x + geom.itemw &amp;&amp; y &gt;= item-&gt;y &amp;&amp; y &lt;= item-&gt;y + geom.itemh) { *menu_ret = menu; *item_ret = item; return; } } } } } /* set currentmenu to menu, umap previous menus and map current menu and its parents */ static void setcurrmenu(struct Menu *menu) { struct Menu *p; for (p = currmenu; p != NULL; p = p-&gt;parent) XUnmapWindow(dpy, p-&gt;win); currmenu = menu; for (p = currmenu; p != NULL; p = p-&gt;parent) XMapWindow(dpy, p-&gt;win); } /* draw items of the current menu and of its ancestors */ static void drawmenu(void) { struct Menu *menu; struct Item *item; size_t nitems; /* number of items before current item */ unsigned long *color; size_t labellen; int labelx, labely; int y; for (menu = currmenu; menu != NULL; menu = menu-&gt;parent) { nitems = 0; for (item = menu-&gt;list; item != NULL; item = item-&gt;next) { /* determine item color */ if (item == menu-&gt;selected) color = dc.pressed; else color = dc.unpressed; /* calculate item's y position */ y = nitems * geom.itemh; /* draw item box */ XSetForeground(dpy, dc.gc, color[ColorBG]); XFillRectangle(dpy, menu-&gt;win, dc.gc, 0, y, geom.itemw, geom.itemh); /* draw item label */ labellen = strlen(item-&gt;label); labelx = 0 + dc.fonth; labely = y + dc.fonth + geom.itemb; XSetForeground(dpy, dc.gc, color[ColorFG]); XDrawString(dpy, menu-&gt;win, dc.gc, labelx, labely, item-&gt;label, labellen); /* draw triangle, if item contains a submenu */ if (item-&gt;submenu != NULL) { int trianglex = geom.itemw - (geom.itemb + dc.fonth); int triangley = y + geom.itemb; XPoint triangle[] = { {trianglex, triangley}, {trianglex + dc.fonth, triangley + dc.fonth/2}, {trianglex, triangley + dc.fonth}, {trianglex, triangley} }; XFillPolygon(dpy, menu-&gt;win, dc.gc, triangle, LEN(triangle), Convex, CoordModeOrigin); } nitems++; } } } /* run event loop */ static void run(void) { struct Menu *menu; struct Item *item; XEvent ev; while (!XNextEvent(dpy, &amp;ev)) { switch(ev.type) { case Expose: drawmenu(); break; case MotionNotify: getmenuitem(ev.xbutton.window, ev.xbutton.x_root, ev.xbutton.y_root, &amp;menu, &amp;item); if (menu != NULL &amp;&amp; item != NULL) { menu-&gt;selected = item; drawmenu(); } break; case ButtonPress: getmenuitem(ev.xbutton.window, ev.xbutton.x_root, ev.xbutton.y_root, &amp;menu, &amp;item); if (menu != NULL &amp;&amp; item != NULL) { if (item-&gt;submenu != NULL) { setcurrmenu(item-&gt;submenu); } else { printf("%s\n", item-&gt;output); cleanupexit(); } drawmenu(); } else { cleanupexit(); } break; } } } /* cleanup and exit */ static void cleanupexit(void) { XCloseDisplay(dpy); exit(0); } /* show usage */ static void usage(void) { (void)fprintf(stderr, "usage: xmenu [-w] menuname\n"); exit(1); } </code></pre> <p>You compile it with the following commands (You may have to change <code>/usr/X11R6</code> to <code>/usr/</code> on Linux):</p> <pre><code>cc -Wall -Wextra -I/usr/X11R6/include -c xmenu.c cc -o xmenu xmenu.o -L/usr/X11R6/lib -lX11 </code></pre>
[]
[ { "body": "<h2>Comments and Observations</h2>\n<p>On code review we review working code, it is best to remove all debug code prior to posting the question on code review, so that we don't suspect the code isn't working.</p>\n<p>Don't include code that isn't used, this is actually a bad programming practice. Of the 3 macros in the code, <code>LEN(x)</code>, <code>MAX(x,y)</code> and <code>MIN(x,y)</code> only <code>LEN(x)</code> is being used. Including unused code can confuse maintainers of the code. It increases the amount of code they have to go through when fixing bugs or adding new features. Never expect to be the only one that needs to reads or modifies the code, write for the audience.</p>\n<p>Note, the first answer for this <a href=\"https://stackoverflow.com/questions/3437404/min-and-max-in-c\">stackoverflow.com question</a> provides better definitions for <code>MAX(x,y)</code> and <code>MIN(x,y)</code>.</p>\n<p>If you are using <code>stdin</code> for input, there is no reason to use <code>X11</code>, the whole point of <code>X11</code> is to provide graphic user interfaces. Don't mix text input with graphic input.</p>\n<p>If you're not going to use the advice in the reviews, why bother to post to code review? Going back through your questions, I'm not the first person to remark on this.</p>\n<h2>Choice of Language for Graphic Programming</h2>\n<p>Prefer C++ over C for graphic programs. Graphic programming is generally Object Oriented and C++ is an object oriented language. Some of the benefits are that you can create a basic class/type for a window, menu or label and then add to that class through inheritance, which removes a lot of programming.</p>\n<p>Another benefit of C++ over C is the improved ability of error handling through exceptions which also allows recovery. <a href=\"https://docs.oracle.com/javase/tutorial/essential/exceptions/definition.html\" rel=\"nofollow noreferrer\">An exception is an event which occurs during the execution of a program</a>. Exceptions are available in most modern programming languages. Recovery means that the program can return to a known state after an error, which is much better than exiting the program.</p>\n<h2>Avoid calling exit() From Lower Level Functions</h2>\n<p>The only way to exit the program is a lower level function where <code>exit(EXIT_FAILURE)</code> is called, this is not a good programming practice in C. It prevents the program from recovering or cleaning up after itself and can have side effects. If this was an operating system instead of a compiler it would bring the system down. A better way would be to call <a href=\"https://stackoverflow.com/questions/14685406/practical-usage-of-setjmp-and-longjmp-in-c\">setjmp() in main.c and longjmp()</a> where the error occurs. To use <code>setjmp()</code> and <code>longjmp()</code> include <a href=\"https://en.wikipedia.org/wiki/Setjmp.h\" rel=\"nofollow noreferrer\">setjmp.h</a>. The call to <code>exit()</code> should really only occur if there is no recovery path, it is always a good practice to exit from main.</p>\n<h2>Prefer System Define Macros Over Hard Coded Numbers</h2>\n<p>The standard header file <code>stdlib.h</code> includes system macro definitions for <code>EXIT_FAILURE</code> and <code>EXIT_SUCCESS</code> these make the code much more readable than <code>return 0;</code> or <code>return 1;</code> in <code>main()</code> or <code>exit(1);</code> in a sub function. Using these macros are a best practice.</p>\n<h2>Global Variables</h2>\n<p>As previously mentioned in your <a href=\"https://codereview.stackexchange.com/questions/241843/c-word-frequency-counter\">last question</a> global variables generally are considered a bad practice because they make the code harder to write, read, debug and maintain because without searching the whole program it's not clear where the variables are modified. Use local variables whenever possible, and pass necessary information into functions as needed.</p>\n<h2>Complexity</h2>\n<p>The code in the functions <code>main()</code>, <code>static void drawmenu(void)</code> and <code>static void calcmenu(struct Menu *menu)</code> is too complex (does too much). As programs grow in size the use of <code>main()</code> should be limited to calling functions that parse the command line, calling functions that set up for processing, calling functions that execute the desired function of the program, and calling functions to clean up after the main portion of the program.</p>\n<p>There is also a programming principle called the Single Responsibility Principle that applies here. The <a href=\"https://en.wikipedia.org/wiki/Single_responsibility_principle\" rel=\"nofollow noreferrer\">Single Responsibility Principle</a> states:</p>\n<blockquote>\n<p>that every module, class, or function should have responsibility over a single part of the functionality provided by the software, and that responsibility should be entirely encapsulated by that module, class or function.</p>\n</blockquote>\n<p>Break the code into smaller functions, with an eye for reuse.</p>\n<h2>Struct and Variable Names</h2>\n<p>The good here is that you are generally using variable names longer than one character (exceptions such as <code>p</code> in <code>calcmenu</code> should be noted), the bad is that the variables names are still to short or use abbreviations. This program doesn't need commenting as much as it needs self documenting code. A variable called <code>geom</code> might be something other than geometry, what geometry is it referring to. What is <code>menu-&gt;w</code>? when I'm fixing code I don't have time to go searching for comments.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-14T18:48:29.210", "Id": "475468", "Score": "1", "body": "the `w`'s, `h`'s, `x`'s and `y`'s are widiths, heights, x positions and y positions, respectivelly. I based my program in [thingmenu](https://github.com/singpolyma/thingmenu), which also uses a lot of global variables. It is hard to use an event-based code like the ones using xlib without using global variables a lot. I do not know C++. C is the only language I know." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-14T18:53:08.277", "Id": "475469", "Score": "0", "body": "*\"If you are using stdin for input, there is no reason to use X11, the whole point of X11 is to provide graphic user interfaces. Don't mix text input with graphic input.\"*. I write this program to work as a filter like [dmenu](https://tools.suckless.org/dmenu/) (I also based my code on dmenu, which also uses xlib and also contains a lot of global variables)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-14T19:16:46.100", "Id": "475472", "Score": "1", "body": "Oh, you beat me with an answer, and I missed it!" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-14T18:22:49.250", "Id": "242287", "ParentId": "242279", "Score": "1" } }, { "body": "<h1>Prefer functions and const variables over macros</h1>\n\n<p>While the <code>LEN</code> macro might be unavoidable, <code>MIN</code> and <code>MAX</code> can typically be implemented as functions. This avoids problems with side-effects, because in your macros one of the arguments is always evaluated twice.</p>\n\n<p>For the constants, declare <code>static const</code> variables, like:</p>\n\n<pre><code>static const char *FONT = \"-*-*-medium-*-*-*-14-*-*-*-*-*-*-*\";\nstatic int ITEMW = 130;\n...\n</code></pre>\n\n<h1>Don't write what you don't use</h1>\n\n<p><code>MIN</code> and <code>MAX</code> are not used in the code you posted, so it's better to remove them completely.</p>\n\n<h1>Use consistent naming</h1>\n\n<p>In your code, you sometimes write things out completely, in other cases you are abbreviating things. While overly long names might be detrimental, with autocompletion nowadays it should not be a problem to write somewhat long names. Things I would change:</p>\n\n<ul>\n<li><code>DC</code> -> <code>DrawContext</code></li>\n<li><code>ScreenGeom</code> -> <code>ScreenGeometry</code></li>\n<li><code>win</code> -> <code>window</code></li>\n<li><code>cursx</code> -> <code>cursorx</code></li>\n</ul>\n\n<p>If you use all lower-case names, you might consider using underscores to separate words for extra clarity, such as <code>cursor_x</code>.</p>\n\n<p>Also, when you have a pointer to something, don't use <code>p</code> for the name of the pointer, but rather choose a name that describes what is being pointed to. So instead of:</p>\n\n<pre><code>struct Menu *p;\n</code></pre>\n\n<p>Write:</p>\n\n<pre><code>struct Menu *menu;\n</code></pre>\n\n<p>In places where this results in conflicts, like in <code>setcurrmenu()</code>, consider renaming one variable to make the distinction clear, like:</p>\n\n<pre><code>static void\nsetcurrmenu(struct Menu *new_currmenu)\n{\n ...\n currmenu = new_currmenu;\n ...\n}\n</code></pre>\n\n<p>Some abbreviations are commonplace, and it's fine to keep those, like <code>x</code>, <code>y</code>, <code>w</code> and <code>h</code> for coordinates and dimensions, and <code>i</code> and <code>j</code> for loop counters, <code>n</code> and <code>len</code> for counts.</p>\n\n<h1>Declare variables as close as possible to the place of use</h1>\n\n<p>A long time ago compilers needed all local variables to be declared at the top of a function, however nowadays that is not necessary. Consider declaring them at the place where they are first used. Also, you can declare variables inside <code>for</code> and <code>while</code>-statements. For example, you can write:</p>\n\n<pre><code>for (struct Menu *menu = currmenu, menu != NULL; menu = menu-&gt;parent) {\n size_t nitems = 0;\n for (struct Item *item = menu-&gt;list; item != NULL; item = item-&gt;next) {\n ...\n int y = nitems * geom.itemh;\n ...\n</code></pre>\n\n<p>Note that you are already doing that in some places.</p>\n\n<h1>Avoid forward declarations</h1>\n\n<p>Your code starts with a list of forward function declarations, followed by the actual function definitions. However, this means you are repeating yourself unnecessarily. You can avoid forward declarations by reordering your functions. For example, <code>main()</code> calls <code>parsestdin()</code>, so by writing the definition of <code>parsestdin()</code> before that of <code>main()</code> you don't need the forward declarations.</p>\n\n<p>Only in rare cases, like two functions both calling each other, should you need forward declarations.</p>\n\n<h1>Have the parsing function take a <code>FILE *</code> pointer</h1>\n\n<p>Instead of always reading from <code>stdin</code>, you can make the parser take a <code>FILE *</code> argument to allow it to read from other sources. This is very easy to do and makes the function much more generic.</p>\n\n<h1>Simplify parsing by using convenient standard library functions</h1>\n\n<p>You are parsing the input lines byte by byte. You can simplify it by using standard library functions like <code>strspn()</code> and <code>strtok_r()</code>, or alternatively <code>scanf()</code>. Here are two alternatives, the first using <code>str*()</code> functions:</p>\n\n<pre><code>while (fgets(buf, BUFSIZ, stdin) != NULL) {\n /* Get the indentation level */\n size_t level = strspn(buf, \"\\t\");\n\n /* Get the label */\n char *s = buf + level;\n char *saveptr = NULL;\n char *label = strtok_r(s, \" \\t\\n\", &amp;saveptr);\n\n /* Get the output */\n char *output = strtok_r(NULL, \"\\n\", &amp;saveptr);\n if (output == NULL)\n output = label;\n</code></pre>\n\n<p>The second alternative uses <code>scanf()</code>, using the <code>%n</code> conversion to get the size of each element of the line, instead of copying the elements to separate buffers:</p>\n\n<pre><code>while (fgets(buf, BUFSIZ, stdin) != NULL) {\n int level;\n int labelend;\n int outputstart;\n int outputend = 0;\n\n if (sscanf(buf, \"%*[\\t]%n%*s%n %n%*[^\\n]%n\", &amp;level, &amp;labelend, &amp;outputstart, &amp;outputend) &lt; 2)\n err(1, \"error parsing input\");\n\n char *label = buf + level;\n buf[labelend] = '\\0';\n\n char *output = label;\n if (outputend &gt; 0) {\n output = buf + outputstart;\n buf[outputend] = '\\0';\n }\n</code></pre>\n\n<h1>Split parsing the textual input and building internal data structures</h1>\n\n<p>You are doing both in <code>parsestdin()</code> at the moment. But consider that in the future, you might want to programmatically build menus. In that case it makes more sense to have a function like <code>addmenuitem()</code> to add an item to an existing <code>struct Menu</code>.</p>\n\n<h1>Avoid global variables</h1>\n\n<p>Global variables are convenient at first, but as your projects grow, they become a burden. For example, what if you want to have two menus visible at the same time? Start by moving the global variables into <code>main()</code>, and if functions called by <code>main()</code>, either directly or indirectly, access the previously global variables, ensure you pass pointers to the local variables to these functions as arguments and return variables.</p>\n\n<p>For example, <code>parsestdin()</code> should not use the global variable <code>rootmenu</code>, but rather declare a local one and return it at the end:</p>\n\n<pre><code>static struct Menu *\nparsestdin(void)\n{\n struct Menu *rootmenu;\n ...\n return rootmenu;\n}\n</code></pre>\n\n<p>Some functions can return by value, for example <code>calcscreengeom()</code>. Other functions should get passed information as parameters; for example <code>drawmenu()</code> should get <code>currmenu</code>, <code>dpy</code> and <code>dc</code> as parameters.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-14T19:27:26.267", "Id": "475476", "Score": "0", "body": "I forgot to remove the unused macros and the debug function before sending the code to review, sorry about that. The unused macros are there because I needed them in a previous version of the code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-14T22:07:06.920", "Id": "475491", "Score": "0", "body": "I thought use #define to create constants was still acceptable in C, it used to be the only way." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-14T22:31:55.487", "Id": "475497", "Score": "0", "body": "It must have been a long time ago that it was the only way. `static const` variables have been a thing since at least C89. There are a few issues with them though; for example you can't use them for array sizes or for `case` statements. See also: https://stackoverflow.com/questions/1674032/static-const-vs-define-vs-enum" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-30T02:53:19.383", "Id": "477171", "Score": "0", "body": "The program is now very mature (thanks for your review), and is now [a project in github](https://github.com/phillbush/xmenu). I would appreciate if you checked it out." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-30T07:12:21.857", "Id": "477182", "Score": "0", "body": "PS: I haven't removed the forward declarations because it would generate an enormous `git diff`, and the only global variables are the variables used by the xlib functions (which should be global, anyway)." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-14T19:15:19.577", "Id": "242294", "ParentId": "242279", "Score": "5" } } ]
{ "AcceptedAnswerId": "242294", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-14T14:32:13.750", "Id": "242279", "Score": "4", "Tags": [ "c", "graphics", "unix", "x11" ], "Title": "Menu for X11 using Xlib in C" }
242279
<p>I am new to this community; I have tried my best to respect the policy of the community. I have written the Monte Carlo metropolis algorithm for the ising model. I want to optimize the code. I have tried my best. I want to optimize it further. The following is the code:</p> <p>(I have used tricks like finding exponential only once, careful generation of random number, etc.)</p> <pre><code>import numpy as np import time import random def monteCarlo(N,state,Energy,Mag,Beta,sweeps): if sweeps &gt; 10000: print("Warning:Number of sweeps exceeded 10000\n\tsetting number of sweeps to 10000") sweeps = 10000 start_time = time.time() expBeta = np.exp(-Beta*np.arange(0,9)) E = np.zeros(sweeps) M = np.zeros(sweeps) for t in range(sweeps): for tt in range(N*N): a = random.randint(0, N-1) b = random.randint(0, N-1) s = state[a,b] delta_E = 2*s*(state[(a+1)%N,b] + state[a,(b+1)%N] + state[(a-1)%N,b] + state[a,(b-1)%N]) if delta_E &lt; 0: s *= -1 Energy += delta_E Mag += 2*s elif random.random() &lt; expBeta[delta_E]: s *= -1 Energy += delta_E Mag += 2*s state[a, b] = s E[t] = Energy M[t] = Mag print("%d monte carlo sweeps completed in %d seconds" %(sweeps,time.time()-start_time)) return E,M #returning list of Energy and Magnetization set #####lattice config##### """N is lattice size nt is number of Temperature points sweeps are number of mc steps per spin""" print("Starting Ising Model Simulation") N = int(input("Enter lattice size : ")) startTime = time.time() nt = 10 N2 = N*N sweeps = 10000 #mc steps per spin """we will plot the following wrt temperature, T""" T = np.linspace(2, 3, nt) #you can set temperature range """preparing lattice with all spins up""" state = np.ones((N,N),dtype="int") Energy = -N2 Mag = N2 #temperature loop #for k in tqdm_gui(range(nt)): for k in range(nt): temp = T[k] Beta=1/temp print("____________________________________\nTemperature is %0.2f, time is %d" %(temp,time.time()-startTime)) E, M = monteCarlo(N,state,Energy,Mag,Beta,sweeps) #list of Energy and Magnetization Energy = E[-1] Mag = M[-1] #further code is finding magnetization, autocorrelation, specific heat, autocorrelation, etc. <span class="math-container">```</span> </code></pre>
[]
[ { "body": "<h2>Naming variables</h2>\n\n<p>The usual rule of variable names in <code>snake_case</code> applies, i.e. <code>energyFunctional</code> would become <code>energy_functional</code>. Class names on the other hand should be written in <code>CamelCase</code>. I don't mind using single capital letters for matrices.</p>\n\n<p>Why use <code>a,b</code> for discrete indices? I would use one of <code>i,j,k,l,n,m,p,q,r</code>.</p>\n\n<p>Use descriptive names: e.g. <code>energies</code> instead of <code>E</code>.</p>\n\n<h2>Merging conditions</h2>\n\n<p>Instead of</p>\n\n<pre><code>if delta_E &lt; 0:\n s *= -1\n Energy += delta_E\n Mag += 2*s\nelif random.random() &lt; expBeta[delta_E]:\n s *= -1\n Energy += delta_E\n Mag += 2*s\n</code></pre>\n\n<p>you could simply write</p>\n\n<pre><code>if delta_E &lt; 0 or random.random() &lt; expBeta[delta_E]:\n s *= -1\n Energy += delta_E\n Mag += 2*s\n</code></pre>\n\n<p>which is easier to read.</p>\n\n<h2>String formatting</h2>\n\n<p>Use the sweet <code>f-strings</code>.</p>\n\n<pre><code>sweep_time = int(time.time() - start_time)\nprint(f\"{sweeps} monte carlo sweeps completed in {sweep_time} seconds\")\n</code></pre>\n\n<h2>Logging warnings</h2>\n\n<p>Consider using the <code>logging</code> library. I'd write warnings to <code>stderr</code>, but it's up to you, <a href=\"https://stackoverflow.com/questions/1430956/should-i-output-warnings-to-stderr-or-stdout\">see</a>.</p>\n\n<pre><code>import sys\n\nprint(\"Warning: Number of sweeps exceeded 10000\", file=sys.stderr)\nprint(\" setting number of sweeps to 10000\", file=sys.stderr)\n</code></pre>\n\n<p>Truncating it to a single line allows for easier parsing later.</p>\n\n<pre><code>print(\"Warning: Number of sweeps truncated to 10000.\", file=sys.stderr)\n</code></pre>\n\n<h2>Refactorisation</h2>\n\n<p>If performance wasn't the primary goal, I'd introduce a few new functions.\nI'd separate the timing part anyway.</p>\n\n<pre><code>start_time = time.time()\nenergies, mags = monte_carlo(n, state, energy, mag, beta, sweeps)\nelapsed_seconds = int(time.time() - start_time)\nprint(f\"{sweeps} monte carlo sweeps completed in {elapsed_seconds} seconds\")\n</code></pre>\n\n<h2><code>monte_carlo</code></h2>\n\n<p>Applying these ideas, the <code>monteCarlo</code> function becomes the following.</p>\n\n<pre><code>def monte_carlo(n, state, energy, mag, beta, sweeps):\n if sweeps &gt; 10000:\n print(\"Warning: Number of sweeps truncated to 10000.\", file=sys.stderr)\n sweeps = 10000\n\n exp_betas = np.exp(-beta*np.arange(0,9))\n\n energies = np.zeros(sweeps)\n mags = np.zeros(sweeps)\n for t in range(sweeps):\n for tt in range(n*n):\n j = random.randint(0, n-1)\n k = random.randint(0, n-1)\n s = state[j,k]\n\n neighbour_sum = (state[(j-1)%n, k] +\n state[j, (k-1)%n] + state[j, (k+1)%n] +\n state[(j+1)%n, k])\n energy_diff = 2*s*neighbour_sum\n\n if energy_diff &lt; 0 or random.random() &lt; exp_betas[energy_diff]:\n s *= -1\n energy += energy_diff\n mag += 2*s\n\n state[j, k] = s\n\n energies[t], mags[t] = energy, mag\n\n return energies, mags\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-15T09:04:50.327", "Id": "475541", "Score": "0", "body": "Albeit, numpy random is better for scientific and statistical \nanalysis purposes. (https://stackoverflow.com/a/7030595/8081272) @Gucio I have gone through your answer and you're correct. The only problem I am facing right now is, if I run my earlier code (the one in question), the average magnetisation is zero above ```temp >2.269```. This ain't case when I use numpy's random. What I will do is, I will try @Andrew 's code with MT as generator." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-15T11:31:36.030", "Id": "475561", "Score": "0", "body": "I have updated my question, pointing the problem faced with your suggestions wrt my original code. Though, your suggestion is very helpful for beginners. For example, as a newb coder, I earlier did not know when to use snake_case and when to use camelCase." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-15T11:48:11.903", "Id": "475562", "Score": "0", "body": "@KartikChhajed Can you post the exact code used in generating your plots? Pastebin or something would work." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-15T12:07:19.443", "Id": "475565", "Score": "0", "body": "I have updated my question again with ```code```. Sorry, I have not incorporated your suggestions in my code: like using ```snake_case```. I was avoiding posting this complicated stuff earlier. Thank You for your advise given more first." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-15T13:30:57.007", "Id": "475574", "Score": "0", "body": "@KartikChhajed No problem. Generally it is best not to edit your original question as the answers arrive. It is also good practice to not accept answers too quickly. It seems that I have overlooked something regarding the batch-generation of these pseudo-random numbers. I've removed the relevant parts from my answer. I'll update it if I think of something useful." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-15T20:17:16.723", "Id": "475607", "Score": "0", "body": "@KartikChhajed FWIW my mistake was assuming that `random.randint(0, n-1) == np.random.randint(0, n-1)`. It is not, indeed: `random.randint(0, n-1) == np.random.randint(0, n)`. That's the reason for the different simulational outcomes. My testing shows that the `random` library has been optimized to fit your use case. Pre-generating the numbers looks to be about 10% faster if you use them all, but you don't do that." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-16T00:52:36.800", "Id": "475630", "Score": "0", "body": "Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/108063/discussion-between-kartik-chhajed-and-andrew)." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-14T19:25:53.947", "Id": "242295", "ParentId": "242282", "Score": "2" } }, { "body": "<p>I cannot yet comment due to my reputation, so I'll write this as an answer to your comment on Andrew's answer, and delete if someone comments this information or Andrew updates his answer.</p>\n\n<p>Saying that numpy's random is not a good random number generator does not seem right to me.\nFrom <a href=\"https://numpy.org/devdocs/reference/random/index.html\" rel=\"nofollow noreferrer\">numpy's reference</a> : </p>\n\n<blockquote>\n <p>By default, Generator uses bits provided by PCG64 which has better statistical properties than the legacy MT19937 used in RandomState.</p>\n</blockquote>\n\n<p>So to me it seems that :</p>\n\n<ol>\n<li>numpy uses the PCG64 random generator which, according to numpy, has better statistical properties than <em>legacy</em> MT19937</li>\n<li>numpy used to use MT19937</li>\n<li>you can still chose to use the MT19937 random number generator </li>\n</ol>\n\n<pre class=\"lang-py prettyprint-override\"><code>from numpy.random import Generator, MT19937\nrg = Generator(MT19937(12345))\nrg.random()\n</code></pre>\n\n<p>Maybe there is something I'm missing, and maybe it is in this part of your comment </p>\n\n<blockquote>\n <p>It produces 53-bit precision floats and has a period of 2**19937-1</p>\n</blockquote>\n\n<p>If so, I'd be interested to know how numpy's random would still be flawed for a Monte-Carlo analysis.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-15T09:30:15.323", "Id": "475544", "Score": "0", "body": "I have tried importing ```from numpy.random import Generator```. But, it shows import error: ```ImportError: cannot import name 'Generator' from 'numpy.random' (/usr/lib/python3/dist-packages/numpy/random/__init__.py)```." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-15T09:37:40.687", "Id": "475545", "Score": "0", "body": "Generator seems to have appeared in numpy v1.17.0, so see if your numpy version is up to date. I can run the snippet on numpy v1.18.1." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-15T10:27:16.773", "Id": "475551", "Score": "0", "body": "An answer that elaborates on random number generation is always welcome. No need to delete yours." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-15T08:01:40.613", "Id": "242318", "ParentId": "242282", "Score": "4" } } ]
{ "AcceptedAnswerId": "242295", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-14T16:13:05.640", "Id": "242282", "Score": "4", "Tags": [ "python", "performance", "python-3.x", "random" ], "Title": "Ising model simulation using metropolis algorithm" }
242282
<p>I have a Bash script that resides on Remote Server A and transfers files from Remote Server 1 to Remote Server 2. Remote Server 2 is a Dropbox folder so in this script, I call another script (that's not mine) to interface with the Dropbox API.</p> <p>This is one of my 1st forays into the Bash-scripting world (I'm mostly a designer and front-end guy), so I'd love to hear some input on how close to "best practices" I've come. Also, I'm not 100% positive I've handled errors correctly (using a combination of <code>trap</code> and checking various commands' return signals). And of course, if there are any blaring performance or security issues, let me know. Thanks in advance.</p> <pre><code>#!/usr/bin/env bash clean_up () { ARG=$? if mount | grep $localPath &gt; /dev/null; then fusermount -u $localPath fi if [ -d $localPath ]; then rm -rf $timestamp fi if [ ${#errors[@]} -gt 0 ] ; then figlet -f small Error ( IFS=$'\n'; echo "${errors[*]}" ) echo "***" echo "This is not typical - please copy the error message above and notify your developer immmediately." echo "***" else figlet -f small Success echo "Upload Complete - Files now accessible via Dropbox" fi echo echo exit $ARG } trap clean_up EXIT timestamp=$(date +%Y.%m.%d-%H.%M.%S) localPath=$PWD/$timestamp token="MY_TOKEN" sourcePath=chef/revel destPath=/chef_uploads pattern=*.txt user=me server=example.com DIR=/chef_uploads errors=() mkdir $timestamp sshfs $user@$server:$sourcePath ${localPath} if [ $? -eq 0 ]; then echo echo echo "Transferring $timestamp to $destPath" ./dropbox_uploader.sh -p -h upload "$timestamp/" "$destPath/" if [ $? -gt 0 ]; then errors+=(" !! ERROR: cannot copy files to $timestamp.") fi else errors+=(" ERROR: cannot mount remote filesystem - $timestamp") fi </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-14T17:27:41.573", "Id": "242285", "Score": "1", "Tags": [ "performance", "beginner", "bash", "error-handling" ], "Title": "One of my first Bash scripts - checking for best practice and error handling" }
242285
<p>My CS teacher sent me the following code for implementing the stack. I've been programming for a few years in higher-level languages, but have rather weak experience with C++. I mean, this code just doesn't seem right to me. What is done in a bad way here and what would you improve?</p> <pre><code>#include &lt;iostream&gt; using namespace std; struct stackElem { stackElem* nxt; int dana; }; bool isEmpty(stackElem* S) { return !S; } stackElem* top(stackElem* S) { return S; } void add(int value, stackElem** S) { stackElem* elem = new stackElem; elem-&gt;dana = value; elem-&gt;nxt = *S; *S = elem; } void get(stackElem** S) { if (*S) { stackElem* elem = *S; *S = (*S)-&gt;nxt; delete elem; } } int main() { stackElem* S = NULL; int i; // fill the stack for (i = 1; i &lt;= 10; i++) { add(i, &amp;S); } while (!isEmpty(S)) { cout &lt;&lt; top(S)-&gt;dana &lt;&lt; endl; get(&amp;S); } return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-14T19:23:18.803", "Id": "475474", "Score": "2", "body": "Welcome to Code Review Stack Exchange! Unfortunately, 'what is wrong with this' type of questions are not allowed. This site is for people who want a critique of working code that they have written." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-14T20:45:58.820", "Id": "475482", "Score": "0", "body": "Sure. Changed my question." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-14T21:58:22.473", "Id": "475488", "Score": "2", "body": "Unfortunately the title is implying that the code isn't working which is going to cause people here to think it's of topic and vote to close..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-14T22:04:28.070", "Id": "475490", "Score": "3", "body": "\"_My CS teacher sent me the following code..._\" Code Review will only review code posted by the author (or maintainer) of the code. While the code may be working, if this is not your code, you cannot ask for a review of it here." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-15T01:38:39.687", "Id": "475511", "Score": "0", "body": "(FWIW, I don't see C++ code but for `new`&`delete`. Just about ***everything*** is wrong: this got to be intentional.)" } ]
[ { "body": "<p>This code looks more like C than C++. The only C++ feature used is <code>cout</code>. While the standard C++ library already provides <a href=\"https://en.cppreference.com/w/cpp/container/stack\" rel=\"nofollow noreferrer\"><code>std::stack</code></a>, I assume the idea is to implement a stack from scratch to show how that would work. With that in mind, here's what I would change to make it better C++ code:</p>\n\n<h1>Create a <code>class</code> representing a stack</h1>\n\n<p>The code as it is only defines a single stack element, and has global functions that manipulate pointers to elements. In C++, you would create a <code>class</code> to manage everything related to the stack:</p>\n\n<pre><code>class Stack {\n struct Element {\n Element *next;\n int value;\n };\n\n Element *top = nullptr;\n\npublic:\n ~Stack() {\n // Write code here to clean up the stack\n }\n\n bool isEmpty() const {\n return top == nullptr;\n }\n\n void push(int value) {\n // Create a new Element and make it the new top\n }\n\n // other functions here\n ...\n}; \n</code></pre>\n\n<p>This hides the management of stack elements, forcing the rest of the code to use the public functions to manipulate the stack, making it harder to make mistakes. You would use it like so:</p>\n\n<pre><code>int main() {\n Stack S;\n\n for (int i = 1; i &lt;= 10; ++i)\n S.push(i);\n\n while (!S.empty()) {\n std::cout &lt;&lt; S.top() &lt;&lt; '\\n';\n S.get();\n }\n}\n</code></pre>\n\n<h1>Consider making a <code>pop()</code> function that combines <code>top()</code> and <code>get()</code></h1>\n\n<p>This would be a logical mirror of the <code>push()</code> function, and allows writing a bit shorter code, like:</p>\n\n<pre><code> while (!S.empty())\n std::cout &lt;&lt; S.pop() &lt;&lt; '\\n';\n</code></pre>\n\n<h1>Make the <code>class</code> a <code>template</code></h1>\n\n<p>One big issue with your version of a stack is that it can only store <code>int</code>s. What if you want a stack that stores floats, or strings, or anything else? You want to avoid having to write different versions of the stack just to handle different types. This is what templates are made for. It's quite easy to make a template:</p>\n\n<pre><code>template&lt;typename T&gt;\nclass Stack {\n struct Element {\n Element *next;\n T value;\n };\n\n ...\n\n void push(T value) {\n ...\n }\n\n T get() {\n return top-&gt;value;\n }\n\n ...\n};\n</code></pre>\n\n<p>And then you can use it like:</p>\n\n<pre><code>int main() {\n Stack&lt;int&gt; S;\n\n for (int i = 1; i &lt;= 10; ++i)\n S.push(i);\n\n ...\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-15T19:20:47.137", "Id": "475600", "Score": "0", "body": "Sometimes it is better to not answer a question, especially when there are already comments that it is off-topic." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-14T22:26:32.413", "Id": "242301", "ParentId": "242288", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-14T18:49:28.590", "Id": "242288", "Score": "-3", "Tags": [ "c++", "stack" ], "Title": "What's wrong with this stack implementation?" }
242288
<p>I am trying a code challenge. Here is the problem description:</p> <blockquote> <p>When an element is deleted from an array, the higher-indexed elements shift down one index to fill the gap. A &quot;balancing element&quot; is defined as an element that, when deleted from the array, results in the sum of the even-indexed elements being equal to the sum of the odd-indexed elements. Determine how many balancing elements a given array contains.</p> </blockquote> <blockquote> <p>Example <code>n=5</code> where <code>n</code> is the size, <code>arr = [5, 5, 2, 5, 8]</code></p> </blockquote> <blockquote> <p>When the first or second 5 is deleted, the array becomes <code>[5, 2, 5, 8]</code>. The <code>sumeven = 5 + 5 = 10</code> and <code>sumodd = 2 + 8 = 10</code>. No other elements of the original array have that property.</p> </blockquote> <blockquote> <p>There are 2 balancing elements that is <code>arr[0]</code> and <code>arr[1]</code>.</p> </blockquote> <p>And here is my solution:</p> <pre><code>public class Challenge { public static void main(String[] args) { countBalancingElements(new int[] {1, 1, 1}); } static int countBalancingElements(int[] arr) { int count = 0; for (int i = 0; i &lt; arr.length; i++) { if (evenIndexValEqualsOddIndexVal(removeElementInArr(arr, i))) { count++; } } } static int[] removeElementInArr(int[] arr, int index) { int[] result = new int[arr.length - 1]; for (int i = 0, j = 0; i &lt; arr.length &amp;&amp; j &lt; result.length; i++, j++) { if (i == index) { result[j] = arr[i + 1]; i++; } else { result[j] = arr[i]; } } return result; } static boolean evenIndexValEqualsOddIndexVal(int[] arr) { int evensum = 0; int oddsum = 0; for (int i = 0; i &lt; arr.length; i++) { if (i % 2 == 0) { evensum += arr[i]; } else { oddsum += arr[i]; } } return evensum == oddsum &amp;&amp; evensum != 0 &amp;&amp; oddsum != 0; } } </code></pre> <p>It looks like its runtime is <span class="math-container">\$O(n^2)\$</span>.</p> <p><code>evensum != 0 &amp;&amp; oddsum != 0;</code> is added to satisfy this input <code>[0, 0]</code>, but it breaks for input <code>{-5, 7, 0, 5 }</code> whose <code>evensum</code> and <code>oddsum</code> is 0. So, cases like [0,0] are to be dealt with separately.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-15T13:43:32.430", "Id": "475575", "Score": "0", "body": "You should add a link to the actual challenge. It will include details such as valid ranges and so on, and may include wording which detail why `[0, 0]` should produce zero balancing elements." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-15T21:57:32.810", "Id": "475617", "Score": "1", "body": "Case in point, searching for the challenge, I can find something like it on one site with constraints \\$1 \\le n \\le 2*10^5\\$ and \\$1 \\le arr[i] \\le 10^9\\$, which suggests neither `{0, 0}` nor `{-5, 7, 0, 5}` will ever be a valid input." } ]
[ { "body": "<pre><code> return evensum == oddsum &amp;&amp; evensum != 0 &amp;&amp; oddsum != 0;\n</code></pre>\n\n<p>Why can't sums be zero? With this array ... <code>{-5, 7, 0, 5 }</code> ... if you remove the <code>7</code>, then the even elements <code>-5</code> and <code>5</code> would sum to zero, and the odd elements <code>0</code> also sum to zero, giving a \"balanced\" array.</p>\n\n<hr>\n\n<p>Move tests out of loops wherever possible.</p>\n\n<pre><code> for (int i = 0; i &lt; arr.length; i++) {\n if (i % 2 == 0) {\n evensum += arr[i];\n } else {\n oddsum += arr[i];\n }\n }\n</code></pre>\n\n<p>Here, with a 1 million element array, <code>i % 2 == 0</code> is being done 1 million times. If you summed the even and odd elements separately ...</p>\n\n<pre><code> for (int i = 0; i &lt; arr.length; i += 2) {\n evensum += arr[i];\n }\n for (int i = 1; i &lt; arr.length; i += 2) {\n oddsum += arr[i];\n }\n</code></pre>\n\n<p>... you never have to even test <code>i % 2 == 0</code>, which should be a speed improvement.</p>\n\n<hr>\n\n<p>The above also applies to copying elements in <code>removeElementInArr()</code>:</p>\n\n<pre><code> for (int i = 0, j = 0; i &lt; arr.length &amp;&amp; j &lt; result.length; i++, j++) {\n if (i == index) {\n result[j] = arr[i + 1];\n i++;\n } else {\n result[j] = arr[i];\n }\n }\n</code></pre>\n\n<p>You know you'll be copying elements up to <code>index</code>, and then copying the elements after <code>index</code>, but you do an <code>i == index</code> inside the loop. With a million elements, that is a lot of extraneous testing.</p>\n\n<pre><code> // Copy elements before index:\n for (int i = 0; i &lt; index; i++) {\n result[i] = arr[i];\n }\n\n // Copy elements after index:\n for (int i = index + 1, j = index; i &lt; arr.length; i++, j++) {\n result[j] = arr[i];\n }\n</code></pre>\n\n<p>But this is still a lot of manual copying. The JVM can do the copying for you, a lot more efficiently using <a href=\"https://docs.oracle.com/en/java/javase/13/docs/api/java.base/java/lang/System.html#arraycopy(java.lang.Object,int,java.lang.Object,int,int)\" rel=\"noreferrer\"><code>System.arraycopy</code></a></p>\n\n<pre><code> System.arraycopy(arr, 0, result, 0, index);\n System.arraycopy(arr, index + 1, result, index, result.length - index);\n</code></pre>\n\n<p>Now the JVM does all the bound-checking once for each call, instead of two million times when done manually on an array of one million entries. Much faster.</p>\n\n<hr>\n\n<p>If you add elements of <code>int[]</code>, you may overflow, especially if you have a lot of elements in those arrays. You may want to use <code>long</code> accumulators.</p>\n\n<hr>\n\n<h1>Algorithmic Improvement</h1>\n\n<p>While the above optimizations will speed up the code, the algorithm is still <span class=\"math-container\">\\$O(N^2)\\$</span>. I believe you can improve this to <span class=\"math-container\">\\$O(N)\\$</span>.</p>\n\n<p>The problem is you are doing a whole lot of additions, and the partial results of those additions aren't changing. Given an array of one million entries, when you are deleting the element around index 500,000 or so, the sums of the first 200,000 even indices and the first 200,000 odd indices don't change.</p>\n\n<p>Consider the array:</p>\n\n<pre><code>1, 3, 5, 7, 9, 11, 13, 15, 17, 19, ...\n</code></pre>\n\n<p>If you were asked to find the sum of various spans of elements, say 4rd through 8th, how would you go about doing it? How about 2nd through 9th? Can you save any work?</p>\n\n<p>If you maintained a list of cumulative sums:</p>\n\n<pre><code>1, 4, 9, 16, 25, 36, 49, 64, 81, 100, ...\n</code></pre>\n\n<p>The sum of the 4rd through 8th element would be:</p>\n\n<pre><code> 7 + 9 + 11 + 13 + 15\n= (1 + 3 + 5) + (7 + 9 + 11 + 13 + 15) - (1 + 3 + 5)\n= (1 + 3 + 5 + 7 + 9 + 11 + 13 + 15) - (1 + 3 + 5)\n= 64 - 9\n= cumulative[8] - cumulative[3]\n</code></pre>\n\n<p>We've preprocessed the input into a cumulative sum array, which is done once <span class=\"math-container\">\\$O(N)\\$</span>, and then any subrange sum can be computed in <span class=\"math-container\">\\$O(1)\\$</span> by a simple subtraction.</p>\n\n<p>You've got some issues to work out, such as how and where to store cumulative sums of only the even/odd indices, how to compute the sum of all even indices after an element at index <code>x</code> is removed, etc. But given this is a programming challenge, the implementation is left to student.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-14T21:45:18.210", "Id": "242300", "ParentId": "242289", "Score": "10" } }, { "body": "<p>My answer is about how you can obtain the same results with a less complex code using a <code>List</code> more adapt than arrays to the nature of the problem. Examining your example :</p>\n\n<pre><code>arr = [5, 5, 2, 5, 8], --&gt; erase the first 5 is equal to left shift the original array obtaining the array [5, 2, 5, 8] deleting the last position\n\narr = [5, 5, 2, 5, 8], --&gt; erase the second 5 is equal to left shift the original array obtaining the array [5, 2, 5, 8] deleting the last position\n\narr = [5, 5, 2, 5, 8], --&gt; erase the 2 is equal to left shift the original array obtaining the array [5, 5, 5, 8] deleting the last position\n\n... other iterations\n</code></pre>\n\n<p>This can be obtained using the <code>List</code> method <code>remove</code> equal to the left shift and after adding the removed element to the <code>List</code> at the same position so you obtain again the original list.\nYour method <code>countBalancingElements</code> can be rewritten in the following way :</p>\n\n<pre><code>public static int countBalancingElements(int[] arr) {\n int count = 0;\n List&lt;Integer&gt; list = Arrays.stream(arr).boxed().collect(Collectors.toList());\n final int length = arr.length;\n\n for (int i = 0; i &lt; length; ++i) {\n int oddSum = 0;\n int evenSum = 0;\n int removed = list.remove(i); //&lt;--remove one element at every iteration\n for (int j = 0; j &lt; length - 1; ++j) {\n if (j % 2 == 0) { evenSum += list.get(j); }\n else { oddSum += list.get(j); }\n }\n if (oddSum == evenSum) { ++count; }\n list.add(i, removed); //&lt;-- add the removed element at the same position \n }\n\n return count;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-15T11:00:12.510", "Id": "475558", "Score": "1", "body": "Thanks for the answer. Looks like it is again `O(n^2)` and `Arrays.stream(arr)` is not performant when arr size is > 50000. Some coding challenges restrict/limit us from not using other data structures apart from given ones, provided can use extra space." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-15T11:07:55.303", "Id": "475559", "Score": "0", "body": "@srk You are correct, it is the same complexity, the method to reduce it has been suggested by AJNeufeld." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-15T10:24:06.653", "Id": "242329", "ParentId": "242289", "Score": "3" } }, { "body": "<p>Basically when you remove a number, the odd elements to the right of it become even elements and vice-versa.</p>\n<blockquote>\n<p>e.g. [4,6,2,5,7,8,9]</p>\n</blockquote>\n<p>odd --&gt; 4,2,<strong>7,9</strong>\neven --&gt; 6,5,<strong>8</strong>\nif we remove say 5 from the array, then our array becomes</p>\n<blockquote>\n<p>[4,6,2,7,8,9]</p>\n</blockquote>\n<p>odd --&gt; 4,2,<strong>8</strong>\neven --&gt; 6,<strong>7,9</strong>\nas you can observe that elements to the right of removed element, odd elements have become even and even elements have become odd.\nNow we can use this fact to our advantage and solve this question. How?\nWe will pre compute the odd and even sum to the left of <strong>i</strong>th element and store it. Similarly we will compute the odd and even sum to the right of <strong>i</strong>th element and store it. Finally all we need to check the number of times</p>\n<blockquote>\n<p>leftOdd[i] + rightEven[i] == leftEven[i] + rightOdd[i]</p>\n</blockquote>\n<p>Here is a quick C++ implementation of the same.</p>\n<pre><code>int findNumberOfBalancingElements(vector&lt;int&gt; &amp;arr){\nint n = arr.size();\nint balancingElemnts = 0;\nvector&lt;int&gt; leftOdd(n,0);\nvector&lt;int&gt; leftEven(n,0);\nvector&lt;int&gt; rightOdd(n,0);\nvector&lt;int&gt; rightEven(n,0);\nint odd = 0;\nint even = 0;\n// pre compute the left side odd and even elements sum;\nfor(int i=0;i&lt;n;i++){\n leftOdd[i] = odd;\n leftEven[i] = even;\n if(i%2==0){\n odd += arr[i];\n }else{\n even += arr[i];\n }\n}\nodd = 0;\neven = 0;\n// pre compute the right side odd and even elements sum;\nfor(int i=n-1;i&gt;=0;i--){\n rightOdd[i] = odd;\n rightEven[i] = even;\n if(i%2==0){\n odd += arr[i];\n }else{\n even += arr[i];\n }\n}\n\n//find the number of times this condition evaluates to true. Thats our answer.\nfor(int i=0;i&lt;n;i++){\n if(leftOdd[i]+rightEven[i]==leftEven[i]+rightOdd[i]){\n balancingElemnts++;\n }\n}\nreturn balancingElemnts;\n</code></pre>\n<p>}</p>\n<p><strong>The Time Complexity of this is <code>O(n)</code></strong></p>\n<p>Why it works better than the original?</p>\n<p><em>What we are checking is basically if we remove that element does our array remain balanced? Sum of odd and even elements is equal or not? And as I mentioned in the starting the odd elements on the right become even and vice versa.. that is why we are adding leftOdd + rightEven which represents the sum of all odd elements. and similarly rightOdd + leftEven which represents the sum of all even elements after the ith element is removed from the array. And for getting the sum of odd and even elements after the removal of certain element the only work we are doing is constant time thanks to saving it earlier. We are just optimizing on time by using a little more space. That is how we are managing to do better. So instead of calculating the sum of all odd and even elements after removing each element we are just getting it from saved array. Which reduces linear work to a constant time search. This is how we are doing better.</em></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-28T19:19:03.723", "Id": "486958", "Score": "1", "body": "You have presented an alternative solution, but haven't reviewed the code. Please explain your reasoning (how your solution works and why it is better than the original) so that the author and other readers can learn from your thought process." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-28T19:53:19.207", "Id": "486962", "Score": "0", "body": "I have added explanation on why it works. Thanks" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-28T19:54:43.157", "Id": "486963", "Score": "0", "body": "Thank you, but the whole point is to show why it works better than the original. Not simply why it works. You got a good start here, now please bring it home." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-28T20:03:54.467", "Id": "486964", "Score": "1", "body": "Updated the explanation @Mast" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-17T15:04:44.837", "Id": "521677", "Score": "0", "body": "Nice exppanation @ShubhamPatel" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-28T19:02:43.537", "Id": "248566", "ParentId": "242289", "Score": "1" } } ]
{ "AcceptedAnswerId": "242300", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-14T18:57:58.203", "Id": "242289", "Score": "8", "Tags": [ "java", "performance", "programming-challenge", "complexity" ], "Title": "Counting Balanced numbers in a given array" }
242289
<p>I'm writing driver code for the SPI peripheral (as part of a tutorial) on a Nucleo64 (STM32F446RE). The instructor recommends writing this code:</p> <pre><code>// General macros #define EnableStatus uint8_t #define DISABLE 0 #define ENABLE !DISABLE void SPI_EnablePeripheralClock(SPI_RegDef_t *pSPIx, EnableStatus status) { if (status) { if (pSPIx == SPI1) SPI1_PCLK_ENA(); else if (pSPI == SPI2) SPI2_PCLK_ENA(); // ... done for 4 SPI modules } else { if (pSPIx == SPI1) SPI1_PCLK_DIS(); else if (pSPI == SPI2) SPI2_PCLK_DIS(); // ... done for 4 SPI modules } ... // You can treat RCC-&gt;APB2ENR as the value at some address. ENA() sets a bit. DIS() clears a bit. #define SPI1_CLK_ENA() (RCC-&gt;APB2ENR |= (1 &lt;&lt; 12)) #define SPI2_CLK_ENA() (RCC-&gt;APB1ENR |= (1 &lt;&lt; 14)) #define SPI1_CLK_DIS() (RCC-&gt;APB2ENR &amp;= ~(1 &lt;&lt; 12)) #define SPI2_CLK_DIS() (RCC-&gt;APB1ENR &amp;= ~(1 &lt;&lt; 14)) ... #define IO volatile typedef struct { IO uint32_t CR1; // Control Reg. 1 IO uint32_t CR2; // Control Reg. 2 IO uint32_t SR; // Status Reg. IO uint32_t DR; // Data Reg. IO uint32_t CRCPR; // CRC Polynomial Reg. IO uint32_t RXCRCR; // RX CRC Reg. IO uint32_t TXCRCR; // TX CRC Reg. IO uint32_t I2SCFGR; // I2S Configuration Reg. IO uint32_t I2SPR; // I2S Prescaler Reg. } SPI_RegDef_t; #define SPI1 ((SPI_RegDef_t*)SPI1_BASEADDR) #define SPI2 ((SPI_RegDef_t*)SPI2_BASEADDR) </code></pre> <p>Several things I don't like about this implementation:</p> <ol> <li>The chain of if-elses in the function to set or clearing one bit. It's a lot of lines-of-code to express a simple task.</li> <li>It's comparing peripheral device base addresses to figure out which of the four SPI peripheral it's working with. </li> </ol> <p>I rewrote it like this to address the issues:</p> <pre><code>// Assigns the boolean value b to the p'th bit position (0-based indexing) of the number `num`. void BitAssign(volatile uint32_t *num, uint8_t p, bool b) { // https://stackoverflow.com/a/47990/3396951 b = !!b; // booleanize b (if it was previously non-zero, it is now 1 otherwise it's 0) *num = (*num &amp; ~(1UL &lt;&lt; p)) | (b &lt;&lt; p); } // To be used as first argument in SPI_EnablePeripheralClock() and other functions #define SPI1 1 #define SPI2 2 #define SPI3 3 #define SPI4 4 void SPI_EnablePeripheralClock(uint8_t SPIx, EnableStatus status) { // 12, 14, 15, 13 are values provided by the datasheet if (SPIx == SPI1) BitAssign(&amp;RCC-&gt;APB2ENR, 12, status); else if (SPIx == SPI2) BitAssign(&amp;RCC-&gt;APB1ENR, 14, status); else if (SPIx == SPI3) BitAssign(&amp;RCC-&gt;APB1ENR, 15, status); else if (SPIx == SPI4) BitAssign(&amp;RCC-&gt;APB2ENR, 13, status); } </code></pre> <p>This avoids relying on the ENA()/DIS() functions (I can remove them) and utilizes a bit-operation to perform the bit assignment. I'm unsure if <code>BitAssign()</code> is a good idea since I might have to overload it for non-volatile parameters. </p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-14T20:16:22.327", "Id": "475480", "Score": "0", "body": "What is `pSPIx` in the first snippet?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-15T00:56:47.047", "Id": "475504", "Score": "0", "body": "Typo, thanks for catching. The argument to the function should have been `pSPIx`, a pointer to a `SPI_RegDef_t` struct (the registers of the SPI peripheral)." } ]
[ { "body": "<p>The variable names in both of those snippets are absolutely insane! But at least it seems clear on close inspection that <code>ENA</code> and <code>DIS</code> are abbreviations of \"enable\" and \"disable.\" I would write those out.</p>\n\n<p>I would rewrite the instructor's code like this:</p>\n\n<pre><code>typedef uint8_t EnableStatus;\n\nvoid SPI_EnablePeripheralClock1(EnableStatus status) {\n if (status) {\n RCC-&gt;APB2ENR |= (1 &lt;&lt; 12);\n } else {\n RCC-&gt;APB2ENR &amp;= ~(1 &lt;&lt; 12);\n }\n}\n\nvoid SPI_EnablePeripheralClock2(EnableStatus status) {\n if (status) {\n RCC-&gt;APB1ENR |= (1 &lt;&lt; 14);\n } else {\n RCC-&gt;APB1ENR &amp;= ~(1 &lt;&lt; 14);\n }\n}\n\nvoid SPI_EnablePeripheralClock(SPI_RegDef_t *pSPI, EnableStatus status) {\n switch (pSPIx) {\n case SPI1: SPI_EnablePeripheralClock1(status); break;\n case SPI2: SPI_EnablePeripheralClock2(status); break;\n default: assert(false); break; // what goes here?\n }\n}\n</code></pre>\n\n<p>But it really depends on how this <code>SPI_EnablePeripheralClock</code> function is going to be used \"upstream\" in the caller. For example, why is <code>EnableStatus</code> a typedef for <code>uint8_t</code> instead of <code>bool</code>?</p>\n\n<p>In fact, I would be tempted to write two convenience functions with English names:</p>\n\n<pre><code>void EnablePeripheralClock() {\n SPI_EnablePeripheralClock(&amp;spi, true);\n}\nvoid DisablePeripheralClock() {\n SPI_DisablePeripheralClock(&amp;spi, false);\n}\n</code></pre>\n\n<p>Alternatively, it might make sense to refactor along those lines from the very beginning...</p>\n\n<pre><code>void EnablePeripheralClock() {\n switch (pSPIx) {\n case 1: RCC-&gt;APB2ENR |= (1 &lt;&lt; 12); break;\n case 2: RCC-&gt;APB1ENR |= (1 &lt;&lt; 14); break;\n default: assert(false);\n }\n}\n\nvoid DisablePeripheralClock() {\n switch (pSPIx) {\n case 1: RCC-&gt;APB2ENR &amp;= ~(1 &lt;&lt; 12); break;\n case 2: RCC-&gt;APB1ENR &amp;= ~(1 &lt;&lt; 14); break;\n default: assert(false);\n }\n}\n</code></pre>\n\n<p>Here we're breaking down the code <em>from the top down</em>, focusing on \"what task needs accomplishing\" (e.g. \"disable the clock\"), rather than taxonomizing from the bottom up. Of course it's hard to know if we've done it right, when we don't know what top-level tasks need accomplishing. :)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-15T01:12:06.373", "Id": "475505", "Score": "0", "body": "`For example, why is EnableStatus a typedef for uint8_t instead of bool`. I thought C didn't define `bool`. (After some googling) I guess it does if the cross compiler uses C99. I will use `bool` from now on. That brings up another question: should you create macros for binary choices (True/False, Set/Clear, Set/Reset, On/Off, Enable/Disable), as you can imagine, using True to indicate the status of an LED or to say that clock has been enabled impairs readability." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-15T01:24:04.637", "Id": "475507", "Score": "0", "body": "`Of course it's hard to know if we've done it right, when we don't know what top-level tasks need accomplishing`. I'm a beginner and I haven't used SPI much to know how it would be called or the many different contexts in which it could be called (i.e., concurrently or inside an interrupt). Being a communication protocol, SPI could be used to communicate with sensors/actuators or to send data to another MCU. To test it, I'll probably use SPI1 to communicate with SPI2 (i.e., the MCU sends data to itself)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-15T01:29:54.257", "Id": "475508", "Score": "1", "body": "`Here we're breaking down the code from the top down, focusing on \"what task needs accomplishing\" (e.g. \"disable the clock\"), rather than taxonomizing from the bottom up.` That's a good suggestion. I'll refactor my code, code up a use case, and create a follow-up post." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-14T20:33:12.880", "Id": "242297", "ParentId": "242293", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-14T19:11:36.070", "Id": "242293", "Score": "1", "Tags": [ "c", "embedded" ], "Title": "MCU (Embedded C): Use nested if/elses or use an ugly function?" }
242293
<p>So, I've implemented Huffman Encoding in JavaScript, you can see it live <a href="https://flatassembler.github.io/huffman.html" rel="nofollow noreferrer">here</a>. Here is the code:</p> <pre><code>var letters,maxX,maxY,minX,maximumDepth,inputString; if (typeof Math.log2=="undefined") //Internet Explorer 11 Math.log2=function(x){ return Math.log(x)/Math.log(2); } function onButtonClick() { inputString=document.getElementById("input").value; if (inputString.length&lt;2) { alert("Strings of length less than two can't be Huffman encoded."); return; } console.log("Making a Huffman tree for the string \""+inputString+"\"."); letters=new Object(); for (let i=0; i&lt;inputString.length; i++) { if (letters[inputString[i]]==undefined) { letters[inputString[i]]=new Object(); letters[inputString[i]].frequency=0; letters[inputString[i]].hasBeenUsed=false; letters[inputString[i]].childrenNodes=[]; } letters[inputString[i]].frequency++; } var entropy=0,numberOfDistinctLetters=0; for (let i in letters) { letters[i].probability=letters[i].frequency/inputString.length; entropy-=letters[i].probability*Math.log2(letters[i].probability); numberOfDistinctLetters++; } var bitsInEqualCode=Math.ceil(Math.log2(numberOfDistinctLetters)); if (numberOfDistinctLetters&lt;2) { alert("There need to be at least two different symbols!"); return; } var howManyUnused=numberOfDistinctLetters; var rootNode; do { let minimum1,minimum2; for (let i in letters) if (letters[i].hasBeenUsed==false &amp;&amp; (minimum1==undefined || letters[i].frequency&lt;letters[minimum1].frequency)) minimum1=i; for (let i in letters) if (letters[i].hasBeenUsed==false &amp;&amp; i!=minimum1 &amp;&amp; (minimum2==undefined || letters[i].frequency&lt;letters[minimum2].frequency)) minimum2=i; console.log("Connecting \'"+minimum1+"\' and \'"+minimum2+"\' into a single node."); letters[minimum1].hasBeenUsed=true; letters[minimum2].hasBeenUsed=true; letters[minimum1+minimum2]=new Object(); letters[minimum1+minimum2].childrenNodes=[minimum1, minimum2]; letters[minimum1+minimum2].frequency=letters[minimum1].frequency+letters[minimum2].frequency; if (letters[minimum1+minimum2].frequency==inputString.length) rootNode=minimum1+minimum2; letters[minimum1+minimum2].hasBeenUsed=false; howManyUnused=0; for (let i in letters) if (letters[i].hasBeenUsed==false) howManyUnused++; } while (howManyUnused&gt;1); stackWithNodes=[rootNode]; stackWithCodes=[""]; stackWithDepths=[0]; var averageSymbolLength=0; maximumDepth=0; var counter=0; document.getElementById("table").innerHTML="&lt;tr&gt;&lt;td&gt;symbol&lt;/td&gt;&lt;td&gt;frequency&lt;/td&gt;&lt;td&gt;Huffman code&lt;/td&gt;&lt;td&gt;equal-length code&lt;/td&gt;&lt;/tr&gt;"; while (stackWithNodes.length&gt;0) { let currentNode=stackWithNodes.pop(); let currentCode=stackWithCodes.pop(); let currentDepth=stackWithDepths.pop(); maximumDepth=Math.max(maximumDepth,currentDepth); letters[currentNode].code=currentCode; if (letters[currentNode].childrenNodes.length==0) { averageSymbolLength+=letters[currentNode].probability*currentCode.length; equalLengthCode=counter.toString(2); while (equalLengthCode.length&lt;bitsInEqualCode) equalLengthCode='0'+equalLengthCode; document.getElementById("table").innerHTML+="&lt;tr&gt;&lt;td&gt;"+ currentNode+"&lt;/td&gt;&lt;td&gt;"+ letters[currentNode].frequency+"/"+inputString.length+ "&lt;/td&gt;&lt;td&gt;"+currentCode+"&lt;/td&gt;&lt;td&gt;"+equalLengthCode+"&lt;/td&gt;&lt;/tr&gt;"; counter++; continue; } stackWithNodes.push(letters[currentNode].childrenNodes[0]); stackWithNodes.push(letters[currentNode].childrenNodes[1]); stackWithCodes.push(currentCode+"0"); stackWithCodes.push(currentCode+"1"); stackWithDepths.push(currentDepth+1); stackWithDepths.push(currentDepth+1); } console.log("The Huffman tree is constructed:"); console.log("node\tfreq\tcode\tleft\tright") for (let i in letters) console.log("'"+i+"'\t"+letters[i].frequency+"/"+inputString.length+"\t"+ letters[i].code+"\t"+((letters[i].childrenNodes[0])?("'"+letters[i].childrenNodes[0]+"'"):"null")+ "\t"+(letters[i].childrenNodes[1]?("'"+letters[i].childrenNodes[1]+"'"):"null")); console.log("The Huffman encoding is:"); output=""; for (let i=0; i&lt;inputString.length; i++) output+=letters[inputString[i]].code; console.log(output); console.log("The average length of a symbol in Huffman code is: "+averageSymbolLength+" bits."); document.getElementById("avgLength").innerHTML=averageSymbolLength; console.log("The average length of a symbol in the equal-length code is: "+bitsInEqualCode+" bits."); document.getElementById("bitsInEqualCode").innerHTML=bitsInEqualCode; console.log("The entropy of the input string is: "+entropy+" bits."); document.getElementById("entropy").innerHTML=entropy; console.log("The efficiency of the Huffman code is: "+(entropy/averageSymbolLength)); console.log("The efficiency of the equal-length code is: "+(entropy/bitsInEqualCode)); document.getElementById("output").innerText=output; var tree=document.getElementById("tree"); var svgNS=tree.namespaceURI; while (document.getElementById("tree").childNodes.length) //Clear the diagram ("innerHTML" won't work because... SVG). document.getElementById("tree").removeChild(document.getElementById("tree").firstChild); maxX=maxY=minX=0; draw(rootNode,0,0,30*Math.pow(2,maximumDepth),0); for (let i = 0; i &lt; document.getElementById("tree").childNodes.length; i++) //In case a node falls left of the diagram, move all nodes rightwards. { if (document.getElementById("tree").childNodes[i].getAttribute("x")) document.getElementById("tree").childNodes[i].setAttribute("x", document.getElementById("tree").childNodes[i].getAttribute("x") * 1 - minX); if (document.getElementById("tree").childNodes[i].getAttribute("x1")) document.getElementById("tree").childNodes[i].setAttribute("x1", document.getElementById("tree").childNodes[i].getAttribute("x1") * 1 - minX); if (document.getElementById("tree").childNodes[i].getAttribute("x2")) document.getElementById("tree").childNodes[i].setAttribute("x2", document.getElementById("tree").childNodes[i].getAttribute("x2") * 1 - minX); } document.getElementById("tree").style.height = maxY + 100 + "px"; document.getElementById("tree").style.width= maxX - minX + 100 + "px"; document.getElementById("diagramSpan").scrollLeft = document.getElementById("node0").getAttribute("x") - document.getElementById("diagramSpan").clientWidth / 2 + 75; //The root of the tree will be in the center of the screen. } function draw(nodeName, x, y, space, id) { if (x &gt; maxX) maxX = x; if (x &lt; minX) minX = x; if (y &gt; maxY) maxY = y; var svgNS = document.getElementById("tree").namespaceURI; var rectangle = document.createElementNS(svgNS, "rect"); rectangle.setAttribute("x", x); rectangle.setAttribute("y", y); rectangle.setAttribute("width", 50); rectangle.setAttribute("height", 50); rectangle.setAttribute("id", "node" + id); rectangle.setAttribute("fill","#EEEEEE"); document.getElementById("tree").appendChild(rectangle); var text = document.createElementNS(svgNS, "text"); text.appendChild(document.createTextNode(letters[nodeName].frequency+"/"+inputString.length)); text.setAttribute("x", x+5); text.setAttribute("y", y + 20); text.style.fill = "black"; text.setAttribute("font-family", "monospace"); text.setAttribute("font-size", 14); document.getElementById("tree").appendChild(text); if (nodeName.length==1) { let character = document.createElementNS(svgNS, "text"); character.appendChild(document.createTextNode(nodeName)); character.setAttribute("x", x+20); character.setAttribute("y", y + 40); character.style.fill = "black"; character.setAttribute("font-family", "monospace"); character.setAttribute("font-size", 14); document.getElementById("tree").appendChild(character); } for (let i = 0; i &lt; letters[nodeName].childrenNodes.length; i++) { draw(letters[nodeName].childrenNodes[i], x + (i - 0.5) * space, y + 100, space / 2, id + 1); let line = document.createElementNS(svgNS, "line"); line.setAttribute("x1", x + 25); line.setAttribute("y1", y + 50); line.setAttribute("x2", x + (i - 0.5) * space + 25); line.setAttribute("y2", y + 100); line.setAttribute("stroke-width", 2); line.setAttribute("stroke", "black"); document.getElementById("tree").appendChild(line); let bit = document.createElementNS(svgNS,"text"); bit.appendChild(document.createTextNode(i)); bit.setAttribute("x", x + (i - 0.5) * space + 25); bit.setAttribute("y", y + 80); bit.style.fill = "black"; bit.setAttribute("font-family", "monospace"); bit.setAttribute("font-size", 14); document.getElementById("tree").appendChild(bit); } } </code></pre> <p>A sample HTML that uses it (I know it can be made a lot better) is:</p> <pre><code>&lt;!doctype html&gt; &lt;html lang="en"&gt; &lt;head&gt; &lt;title&gt;Huffman Encoding in JavaScript&lt;/title&gt; &lt;script src="huffman.js"&gt;&lt;/script&gt; &lt;style&gt; table,th,td { border:1px black solid; } &lt;/style&gt; &lt;/head&gt; &lt;body&gt; Enter the string here:&lt;br/&gt; &lt;input type="text" id="input" value="TEO SAMARZIJA"/&gt; &lt;button onclick="onButtonClick()"&gt;Encode!&lt;/button&gt;&lt;br/&gt; The Huffman encoded string is: &lt;span id="output" style="font-family:monospace"&gt;&lt;/span&gt;&lt;br/&gt; &lt;span id="diagramSpan" style="display:block; width:100%; height:50%; overflow:scroll"&gt; &lt;svg id="tree"&gt; &lt;/svg&gt; &lt;/span&gt;&lt;br/&gt; &lt;table id="table"&gt;&lt;/table&gt;&lt;br/&gt; The average length of a symbol in the Huffman code is &lt;span id="avgLength"&gt;0&lt;/span&gt; bits.&lt;br/&gt; The average length of a symbol in the equal-length code is &lt;span id="bitsInEqualCode"&gt;0&lt;/span&gt; bits.&lt;br/&gt; The entropy of the input string is &lt;span id="entropy"&gt;0&lt;/span&gt; bits.&lt;br/&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>So, what do you think about it?</p>
[]
[ { "body": "<p>You have</p>\n\n<blockquote>\n<pre><code>&lt;button onclick=\"onButtonClick()\"&gt;Encode!&lt;/button&gt;\n</code></pre>\n</blockquote>\n\n<p>Better to <a href=\"https://stackoverflow.com/a/59539045\">avoid inline handlers</a> in a modern codebase, they have too many problems to be worth using. Attach the listener properly in the Javascript by using <code>addEventListener</code> instead.</p>\n\n<p>Consider always strict mode to reduce silent bugs. For example, you never define the <code>stackWithNodes</code>, <code>stackWithCodes</code>, <code>stackWithDepths</code>, <code>output</code>, and some other variables, so they're implicitly global, which is not a good idea. Always declare variables before using them. Strict mode will throw an error when an undeclared variable is used, allowing you to fix it immediately (rather than it causing a hard-to-identify bug down the line).</p>\n\n<p>If you're going to use ES2015 syntax like <code>let</code> in the code, great (it often makes code shorter and more readable!) - but if you're going to use ES2015 syntax, best to use it <em>everywhere</em> - avoid <code>var</code>. Only use <code>let</code> when you must reassign the variable - otherwise, <a href=\"https://softwareengineering.stackexchange.com/questions/278652/how-much-should-i-be-using-let-vs-const-in-es6\">use <code>const</code></a>.</p>\n\n<p>You declare a bunch of global variables shared between <code>onButtonClick</code> and <code>draw</code>:</p>\n\n<pre><code>var letters, maxX, maxY, minX, maximumDepth;\n</code></pre>\n\n<p>If you want to communicate data between functions, it would be more appropriate to <em>pass</em> arguments instead.</p>\n\n<blockquote>\n<pre><code>letters = new Object();\n</code></pre>\n</blockquote>\n\n<p>If you want to create an empty object, just use <code>{}</code> - using the Object constructor is verbose and weird.</p>\n\n<p>Rather than iterating over the string manually with:</p>\n\n<pre><code>for (let i = 0; i &lt; inputString.length; i++) {\n if (letters[inputString[i]] == undefined) {\n letters[inputString[i]] = new Object();\n letters[inputString[i]].frequency = 0;\n letters[inputString[i]].hasBeenUsed = false;\n letters[inputString[i]].childrenNodes = [];\n }\n letters[inputString[i]].frequency++;\n}\n</code></pre>\n\n<p>Since we can use ES2015, using <code>for..of</code> wll make the code a lot cleaner - no manual iteration required, and no having to mess with indicies. You can also assign the whole object all at once, rather than first creating an object, then assigning to its keys. (See next code block after this one for an example.) You also have:</p>\n\n<pre><code>for (let i in letters) {\n letters[i].probability = letters[i].frequency / inputString.length;\n entropy -= letters[i].probability * Math.log2(letters[i].probability);\n numberOfDistinctLetters++;\n}\n</code></pre>\n\n<p>You don't care at all what the <code>i</code> is (the character), so iterating over the keys with <code>in</code> doesn't make much sense. If all you care about is the values, use <code>Object.values</code> instead. Rather than incrementing <code>numberOfDistinctLetters</code> each time, it would be clearer to assign it to its final value immediately, by checking the number of values in the object. This would also be a nice thing to put into a standalone function, to make the <code>onbuttonclick</code> less bulky. The creation of the <code>entropy</code> number is not tied to the assignment of the probabilities to each letter object, so best to separate them. The assignment to the probabilities can go in the function that creates the letter object.</p>\n\n<pre><code>const constructLettersObj = (inputString) =&gt; {\n const lettersObj = {};\n for (const char of inputString) {\n if (!lettersObj[char]) {\n lettersObj[char] = {\n frequency: 0,\n hasBeenUsed: false,\n childrenNodes: [],\n };\n }\n lettersObj[char].frequency++;\n }\n for (const letterObj of Object.values(lettersObj)) {\n letterObj.probability = letterObj.frequency / inputString.length;\n }\n return lettersObj;\n};\n</code></pre>\n\n<p>If you <em>did</em> want to stick with the <code>for..in</code> loop for whatever reaason, don't name the character <code>i</code> (<code>i</code> is generally understood to be a <em>numeric index</em>, but characters aren't numeric), and make sure to declare it with <code>const</code>, not <code>let</code>, since you aren't reassigning the variable. Maybe call it <code>char</code> instead of <code>i</code>. You use that same pattern various other places in the code - to keep the code clean, if you only need to iterate over object <em>values</em>, but not keys, then use <code>Object.values</code>.</p>\n\n<p>Once the above letters object has been constructed, you can create the <code>entropy</code> number by mapping to the <code>probabilities</code> multiplied by the logarithm, then summing them all together with <code>.reduce</code>:</p>\n\n<pre><code>const entropy = vals\n .map(({ probability }) =&gt; probability * Math.log2(probability))\n .reduce((a, b) =&gt; a + b);\n</code></pre>\n\n<p>This way, you can declare <code>entropy</code> with <code>const</code>, no reassignment or generic looping required, and its value will be easier to determine at a glance by a reader.</p>\n\n<p>While connecting the nodes together, you do:</p>\n\n<pre><code>for (let i in lettersObj)\n if (lettersObj[i].hasBeenUsed == false &amp;&amp; (minimum1 == undefined || lettersObj[i].frequency &lt; lettersObj[minimum1].frequency))\n minimum1 = i;\nfor (let i in lettersObj)\n if (lettersObj[i].hasBeenUsed == false &amp;&amp; i != minimum1 &amp;&amp; (minimum2 == undefined || lettersObj[i].frequency &lt; lettersObj[minimum2].frequency))\n minimum2 = i;\nconsole.log(\"Connecting \\'\" + minimum1 + \"\\' and \\'\" + minimum2 + \"\\' into a single node.\");\nlettersObj[minimum1].hasBeenUsed = true;\nlettersObj[minimum2].hasBeenUsed = true;\nlettersObj[minimum1 + minimum2] = new Object();\nlettersObj[minimum1 + minimum2].childrenNodes = [minimum1, minimum2];\nlettersObj[minimum1 + minimum2].frequency = lettersObj[minimum1].frequency + lettersObj[minimum2].frequency;\nif (lettersObj[minimum1 + minimum2].frequency == inputString.length)\n rootNode = minimum1 + minimum2;\nlettersObj[minimum1 + minimum2].hasBeenUsed = false;\nhowManyUnused = 0;\nfor (const i in lettersObj)\n if (lettersObj[i].hasBeenUsed == false)\n howManyUnused++;\n</code></pre>\n\n<p>You can clean this up the same way as above - initialize the <code>lettersObj[minimum1 + minimum2]</code> with an object literal instead, and <code>i</code> should probably be renamed to <code>char</code> (since it's a character, not an index), and since it doesn't get reassigned, declare it with <code>const</code> <a href=\"https://stackoverflow.com/questions/359494/which-equals-operator-vs-should-be-used-in-javascript-comparisons\">Always use</a> <code>===</code> and <code>!==</code> to compare - don't use <code>==</code> or <code>!=</code>, it has strange rules that developers are better off not having to memorize. Or, since the <code>minimum</code>s will always be characters, a simple truthy test would also be enough. To iterate over both the object's values and keys at once, use <code>Object.entries</code>. Save the <code>minimum1 + minimum2</code> in a variable instead of repeating the calculation multiple times - write <a href=\"https://en.wikipedia.org/wiki/Don%27t_repeat_yourself\" rel=\"nofollow noreferrer\">DRY</a> code:</p>\n\n<pre><code>for (const [char, letterObj] of Object.entries(lettersObj))\n if (!letterObj.hasBeenUsed &amp;&amp; (!minimum1 || letterObj.frequency &lt; lettersObj[minimum1].frequency))\n minimum1 = char;\nfor (const [char, letterObj] of Object.entries(lettersObj))\n if (!letterObj.hasBeenUsed &amp;&amp; char != minimum1 &amp;&amp; (!minimum2 || letterObj.frequency &lt; lettersObj[minimum2].frequency))\n minimum2 = char;\nconsole.log(\"Connecting \\'\" + minimum1 + \"\\' and \\'\" + minimum2 + \"\\' into a single node.\");\nlettersObj[minimum1].hasBeenUsed = true;\nlettersObj[minimum2].hasBeenUsed = true;\nlettersObj[minimum1 + minimum2] = {\n childrenNodes: [minimum1, minimum2],\n frequency: lettersObj[minimum1].frequency + lettersObj[minimum2].frequency,\n};\nconst combinedKey = minimum1 + minimum2;\nif (lettersObj[combinedKey].frequency == inputString.length)\n rootNode = combinedKey;\nlettersObj[combinedKey].hasBeenUsed = false;\nhowManyUnused = Object.values(lettersObj)\n .reduce((a, letterObj) =&gt; a + !letterObj.hasBeenUsed, 0);\n</code></pre>\n\n<p>On a similar note, for the code to be DRY, don't select elements over and over again, like with:</p>\n\n<pre><code>while (document.getElementById(\"tree\").childNodes.length) //Clear the diagram (\"innerHTML\" won't work because... SVG).\n document.getElementById(\"tree\").removeChild(document.getElementById(\"tree\").firstChild);\nmaxX = maxY = minX = 0;\ndraw(rootNode, 0, 0, 30 * Math.pow(2, maximumDepth), 0, inputString.length, lettersObj);\nfor (let i = 0; i &lt; document.getElementById(\"tree\").childNodes.length; i++) //In case a node falls left of the diagram, move all nodes rightwards.\n{\n if (document.getElementById(\"tree\").childNodes[i].getAttribute(\"x\"))\n document.getElementById(\"tree\").childNodes[i].setAttribute(\"x\", document.getElementById(\"tree\").childNodes[i].getAttribute(\"x\") * 1 - minX);\n if (document.getElementById(\"tree\").childNodes[i].getAttribute(\"x1\"))\n document.getElementById(\"tree\").childNodes[i].setAttribute(\"x1\", document.getElementById(\"tree\").childNodes[i].getAttribute(\"x1\") * 1 - minX);\n if (document.getElementById(\"tree\").childNodes[i].getAttribute(\"x2\"))\n document.getElementById(\"tree\").childNodes[i].setAttribute(\"x2\", document.getElementById(\"tree\").childNodes[i].getAttribute(\"x2\") * 1 - minX);\n}\ndocument.getElementById(\"tree\").style.height = maxY + 100 + \"px\";\ndocument.getElementById(\"tree\").style.width = maxX - minX + 100 + \"px\";\ndocument.getElementById(\"diagramSpan\").scrollLeft = document.getElementById(\"node0\").getAttribute(\"x\") - document.getElementById(\"diagramSpan\").clientWidth / 2 + 75; //The root of the tree will be in the center of the screen.\n</code></pre>\n\n<p>Select elements <em>once</em> and save them in a variable. Also, <code>.childNodes</code> will iterate over text nodes too, which is not desirable - if you ever had text nodes, they would cause problems. Because you only want to iterate over <em>elements</em>, use <code>.children</code> instead - and instead of iterating manually, invoke the HTMLCollection's iterator instead. When you want to check if an element has an attribute, it's most appropriate to use <code>hasAttribute</code> (not <code>getAttribute</code>):</p>\n\n<pre><code>const tree = document.getElementById(\"tree\");\nfor (const child of tree.children) {\n child.remove();\n}\nmaxX = maxY = minX = 0;\ndraw(rootNode, 0, 0, 30 * Math.pow(2, maximumDepth), 0, inputString.length, lettersObj);\n// In case a node falls left of the diagram, move all nodes rightwards:\nfor (const child of tree.children) {\n if (child.hasAttribute(\"x\"))\n child.setAttribute(\"x\", child.getAttribute(\"x\") * 1 - minX);\n if (child.hasAttribute(\"x1\"))\n child.setAttribute(\"x1\", child.getAttribute(\"x1\") * 1 - minX);\n if (child.hasAttribute(\"x2\"))\n child.setAttribute(\"x2\", child.getAttribute(\"x2\") * 1 - minX);\n}\ntree.style.height = maxY + 100 + \"px\";\ntree.style.width = maxX - minX + 100 + \"px\";\nconst diagramSpan = document.getElementById(\"diagramSpan\");\ndiagramSpan.scrollLeft = document.getElementById(\"node0\").getAttribute(\"x\") - diagramSpan.clientWidth / 2 + 75;\n</code></pre>\n\n<p>The <code>draw</code> function is a bit long and difficult to read. You can make it much nicer by typing HTML markup directly instead of large numbers of <code>setAttribute</code> calls. (You wouldn't do this when you might be concatenating untrusted input, but it's fine when you know exactly what sort of things are being interpolated.) You can do it like this:</p>\n\n<pre><code>const lineHTML = `\n &lt;line\n x1=${x + 25}\n y1=${y + 50}\n x2=${x + (i - 0.5) * space + 25}\n y2=${y + 100}\n strike-width=2\n stroke=black\n &gt;&lt;/line&gt;\n`;\ntree.insertAdjacentHTML('beforeend', lineHTML);\n</code></pre>\n\n<p>You can follow the same pattern in the various places where you have to create elements with lots of attributes.</p>\n\n<p>There are lots of other improvements that can be made, but this should be a good start.</p>\n\n<p>You should strongly consider using a <a href=\"https://eslint.org/\" rel=\"nofollow noreferrer\">linter</a> which will automatically prompt you to fix many of these potential mistakes/code smells.</p>\n\n<p>Live demo of the mostly-fixed code:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"false\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>'use strict';\n\nlet maxX, maxY, minX, maximumDepth;\n\nconst constructLettersObj = (inputString) =&gt; {\n const lettersObj = {};\n for (const char of inputString) {\n if (!lettersObj[char]) {\n lettersObj[char] = {\n frequency: 0,\n hasBeenUsed: false,\n childrenNodes: [],\n };\n }\n lettersObj[char].frequency++;\n }\n for (const letterObj of Object.values(lettersObj)) {\n letterObj.probability = letterObj.frequency / inputString.length;\n }\n return lettersObj;\n};\n\nfunction onButtonClick() {\n const inputString = document.getElementById(\"input\").value;\n if (inputString.length &lt; 2) {\n alert(\"Strings of length less than two can't be Huffman encoded.\");\n return;\n }\n console.log(\"Making a Huffman tree for the string \\\"\" + inputString + \"\\\".\");\n const lettersObj = constructLettersObj(inputString);\n const vals = Object.values(lettersObj);\n const numberOfDistinctLetters = vals.length;\n if (numberOfDistinctLetters &lt; 2) {\n alert(\"There need to be at least two different symbols!\");\n return;\n }\n const entropy = vals\n .map(({ probability }) =&gt; probability * Math.log2(probability))\n .reduce((a, b) =&gt; a + b);\n const bitsInEqualCode = Math.ceil(Math.log2(numberOfDistinctLetters));\n \n let howManyUnused = numberOfDistinctLetters;\n let rootNode;\n do {\n let minimum1, minimum2;\n for (const [char, letterObj] of Object.entries(lettersObj))\n if (!letterObj.hasBeenUsed &amp;&amp; (!minimum1 || letterObj.frequency &lt; lettersObj[minimum1].frequency))\n minimum1 = char;\n for (const [char, letterObj] of Object.entries(lettersObj))\n if (!letterObj.hasBeenUsed &amp;&amp; char != minimum1 &amp;&amp; (!minimum2 || letterObj.frequency &lt; lettersObj[minimum2].frequency))\n minimum2 = char;\n console.log(\"Connecting \\'\" + minimum1 + \"\\' and \\'\" + minimum2 + \"\\' into a single node.\");\n lettersObj[minimum1].hasBeenUsed = true;\n lettersObj[minimum2].hasBeenUsed = true;\n const combinedKey = minimum1 + minimum2;\n lettersObj[combinedKey] = {\n childrenNodes: [minimum1, minimum2],\n frequency: lettersObj[minimum1].frequency + lettersObj[minimum2].frequency,\n };\n if (lettersObj[combinedKey].frequency == inputString.length)\n rootNode = combinedKey;\n lettersObj[combinedKey].hasBeenUsed = false;\n howManyUnused = Object.values(lettersObj)\n .reduce((a, letterObj) =&gt; a + !letterObj.hasBeenUsed, 0);\n }\n while (howManyUnused &gt; 1);\n const stackWithNodes = [rootNode];\n const stackWithCodes = [\"\"];\n const stackWithDepths = [0];\n let averageSymbolLength = 0;\n maximumDepth = 0;\n let counter = 0;\n document.getElementById(\"table\").innerHTML = \"&lt;tr&gt;&lt;td&gt;symbol&lt;/td&gt;&lt;td&gt;frequency&lt;/td&gt;&lt;td&gt;Huffman code&lt;/td&gt;&lt;td&gt;equal-length code&lt;/td&gt;&lt;/tr&gt;\";\n while (stackWithNodes.length &gt; 0) {\n const currentNode = stackWithNodes.pop();\n const currentCode = stackWithCodes.pop();\n const currentDepth = stackWithDepths.pop();\n maximumDepth = Math.max(maximumDepth, currentDepth);\n lettersObj[currentNode].code = currentCode;\n if (lettersObj[currentNode].childrenNodes.length == 0) {\n averageSymbolLength += lettersObj[currentNode].probability * currentCode.length;\n let equalLengthCode = counter.toString(2);\n while (equalLengthCode.length &lt; bitsInEqualCode)\n equalLengthCode = '0' + equalLengthCode;\n document.getElementById(\"table\").innerHTML += \"&lt;tr&gt;&lt;td&gt;\" +\n currentNode + \"&lt;/td&gt;&lt;td&gt;\" +\n lettersObj[currentNode].frequency + \"/\" + inputString.length +\n \"&lt;/td&gt;&lt;td&gt;\" + currentCode + \"&lt;/td&gt;&lt;td&gt;\" + equalLengthCode + \"&lt;/td&gt;&lt;/tr&gt;\";\n counter++;\n continue;\n }\n stackWithNodes.push(lettersObj[currentNode].childrenNodes[0]);\n stackWithNodes.push(lettersObj[currentNode].childrenNodes[1]);\n stackWithCodes.push(currentCode + \"0\");\n stackWithCodes.push(currentCode + \"1\");\n stackWithDepths.push(currentDepth + 1);\n stackWithDepths.push(currentDepth + 1);\n }\n console.log(\"The Huffman tree is constructed:\");\n console.log(\"node\\tfreq\\tcode\\tleft\\tright\")\n for (const i in lettersObj)\n console.log(\"'\" + i + \"'\\t\" + lettersObj[i].frequency + \"/\" + inputString.length + \"\\t\" +\n lettersObj[i].code + \"\\t\" + ((lettersObj[i].childrenNodes[0]) ? (\"'\" + lettersObj[i].childrenNodes[0] + \"'\") : \"null\") +\n \"\\t\" + (lettersObj[i].childrenNodes[1] ? (\"'\" + lettersObj[i].childrenNodes[1] + \"'\") : \"null\"));\n console.log(\"The Huffman encoding is:\");\n let output = \"\";\n for (let i = 0; i &lt; inputString.length; i++)\n output += lettersObj[inputString[i]].code;\n console.log(output);\n console.log(\"The average length of a symbol in Huffman code is: \" + averageSymbolLength + \" bits.\");\n document.getElementById(\"avgLength\").innerHTML = averageSymbolLength;\n console.log(\"The average length of a symbol in the equal-length code is: \" + bitsInEqualCode + \" bits.\");\n document.getElementById(\"bitsInEqualCode\").innerHTML = bitsInEqualCode;\n console.log(\"The entropy of the input string is: \" + entropy + \" bits.\");\n document.getElementById(\"entropy\").innerHTML = entropy;\n console.log(\"The efficiency of the Huffman code is: \" + (entropy / averageSymbolLength));\n console.log(\"The efficiency of the equal-length code is: \" + (entropy / bitsInEqualCode));\n document.getElementById(\"output\").innerText = output;\n const tree = document.getElementById(\"tree\");\n for (const child of tree.children) {\n child.remove();\n }\n maxX = maxY = minX = 0;\n draw(rootNode, 0, 0, 30 * Math.pow(2, maximumDepth), 0, inputString.length, lettersObj);\n // In case a node falls left of the diagram, move all nodes rightwards:\n for (const child of tree.children) {\n if (child.hasAttribute(\"x\"))\n child.setAttribute(\"x\", child.getAttribute(\"x\") * 1 - minX);\n if (child.hasAttribute(\"x1\"))\n child.setAttribute(\"x1\", child.getAttribute(\"x1\") * 1 - minX);\n if (child.hasAttribute(\"x2\"))\n child.setAttribute(\"x2\", child.getAttribute(\"x2\") * 1 - minX);\n }\n tree.style.height = maxY + 100 + \"px\";\n tree.style.width = maxX - minX + 100 + \"px\";\n const diagramSpan = document.getElementById(\"diagramSpan\");\n diagramSpan.scrollLeft = document.getElementById(\"node0\").getAttribute(\"x\") - diagramSpan.clientWidth / 2 + 75; //The root of the tree will be in the center of the screen.\n}\n\nfunction draw(nodeName, x, y, space, id, inputLength, lettersObj) {\n if (x &gt; maxX)\n maxX = x;\n if (x &lt; minX)\n minX = x;\n if (y &gt; maxY)\n maxY = y;\n const svgNS = document.getElementById(\"tree\").namespaceURI;\n const rectangle = document.createElementNS(svgNS, \"rect\");\n rectangle.setAttribute(\"x\", x);\n rectangle.setAttribute(\"y\", y);\n rectangle.setAttribute(\"width\", 50);\n rectangle.setAttribute(\"height\", 50);\n rectangle.setAttribute(\"id\", \"node\" + id);\n rectangle.setAttribute(\"fill\", \"#EEEEEE\");\n document.getElementById(\"tree\").appendChild(rectangle);\n const text = document.createElementNS(svgNS, \"text\");\n text.innerHTML = lettersObj[nodeName].frequency + \"/\" + inputLength;\n text.setAttribute(\"x\", x + 5);\n text.setAttribute(\"y\", y + 20);\n text.style.fill = \"black\";\n text.setAttribute(\"font-family\", \"monospace\");\n text.setAttribute(\"font-size\", 14);\n document.getElementById(\"tree\").appendChild(text);\n if (nodeName.length == 1) {\n const character = document.createElementNS(svgNS, \"text\");\n character.innerHTML = nodeName;\n character.setAttribute(\"x\", x + 20);\n character.setAttribute(\"y\", y + 40);\n character.style.fill = \"black\";\n character.setAttribute(\"font-family\", \"monospace\");\n character.setAttribute(\"font-size\", 14);\n document.getElementById(\"tree\").appendChild(character);\n }\n for (let i = 0; i &lt; lettersObj[nodeName].childrenNodes.length; i++) {\n draw(lettersObj[nodeName].childrenNodes[i], x + (i - 0.5) * space, y + 100, space / 2, id + 1, inputLength, lettersObj);\n const str = `\n &lt;line\n x1=${x + 25}\n y1=${y + 50}\n x2=${x + (i - 0.5) * space + 25}\n y2=${y + 100}\n strike-width=2\n stroke=black\n &gt;&lt;/line&gt;\n `;\n tree.insertAdjacentHTML('beforeend', str);\n const bitHTML = `\n &lt;text\n x=${x + (i - 0.5) * space + 25}\n y=${y + 80}\n style=\"fill: black;\"\n font-family=monospace\n font-size=14\n &gt;${i}&lt;/text&gt;\n `;\n tree.insertAdjacentHTML('beforeend', bitHTML);\n }\n}</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>table,\nth,\ntd {\n border: 1px black solid;\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>Enter the string here:&lt;br/&gt;\n&lt;input type=\"text\" id=\"input\" value=\"TEO SAMARZIJA\" /&gt;\n&lt;button onclick=\"onButtonClick()\"&gt;Encode!&lt;/button&gt;&lt;br/&gt; The Huffman encoded string is: &lt;span id=\"output\" style=\"font-family:monospace\"&gt;&lt;/span&gt;&lt;br/&gt;\n&lt;span id=\"diagramSpan\" style=\"display:block; width:100%; height:50%; overflow:scroll\"&gt;\n &lt;svg id=\"tree\"&gt;\n &lt;/svg&gt;\n &lt;/span&gt;&lt;br/&gt;\n&lt;table id=\"table\"&gt;&lt;/table&gt;&lt;br/&gt; The average length of a symbol in the Huffman code is &lt;span id=\"avgLength\"&gt;0&lt;/span&gt; bits.&lt;br/&gt; The average length of a symbol in the equal-length code is &lt;span id=\"bitsInEqualCode\"&gt;0&lt;/span&gt; bits.&lt;br/&gt; The entropy of the input string is\n&lt;span id=\"entropy\"&gt;0&lt;/span&gt; bits.&lt;br/&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-15T20:55:19.583", "Id": "475611", "Score": "0", "body": "Thanks. I didn't even know about \"Object.values\" method, or that JavaScript had multiline strings. BTW, \"innerHTML\" on SVG elements doesn't work in Internet Explorer 11." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-15T16:11:33.113", "Id": "242350", "ParentId": "242296", "Score": "3" } }, { "body": "<p>I agree with the many great points already mentioned by CertainPerformance - especially ES6 features. There are a few other aspects mentioned below.</p>\n\n<h2>Brackets</h2>\n\n<p>There are lines with no braces/brackets - e.g.</p>\n\n<blockquote>\n<pre><code>for (let i=0; i&lt;inputString.length; i++)\n output+=letters[inputString[i]].code;\n</code></pre>\n</blockquote>\n\n<p>and </p>\n\n<blockquote>\n<pre><code> if (document.getElementById(\"tree\").childNodes[i].getAttribute(\"x\"))\n document.getElementById(\"tree\").childNodes[i].setAttribute(\"x\", document.getElementById(\"tree\").childNodes[i].getAttribute(\"x\") * 1 - minX);\n if (document.getElementById(\"tree\").childNodes[i].getAttribute(\"x1\"))\n document.getElementById(\"tree\").childNodes[i].setAttribute(\"x1\", document.getElementById(\"tree\").childNodes[i].getAttribute(\"x1\") * 1 - minX);\n if (document.getElementById(\"tree\").childNodes[i].getAttribute(\"x2\"))\n document.getElementById(\"tree\").childNodes[i].setAttribute(\"x2\", document.getElementById(\"tree\").childNodes[i].getAttribute(\"x2\") * 1 - minX);\n</code></pre>\n</blockquote>\n\n<p>It is a better practice to use braces even on single-line if-else statements. Not doing so can sometimes lead to <a href=\"https://www.imperialviolet.org/2014/02/22/applebug.html\" rel=\"nofollow noreferrer\">freaky bugs</a>.</p>\n\n<h2>Alerts</h2>\n\n<p>There are two places <code>alert()</code> is called (in <code>onButtonClick()</code>). Some users may have disabled alerts in a browser setting. It is better to use HTML5 <a href=\"https://developer.mozilla.org/en-US/docs/Web/HTML/Element/dialog\" rel=\"nofollow noreferrer\"><code>&lt;dialog&gt;</code></a> element - it allows more control over the style and doesn't block the browser. Bear in mind that it <a href=\"https://developer.mozilla.org/en-US/docs/Web/HTML/Element/dialog#Browser_compatibility\" rel=\"nofollow noreferrer\">isn't supported by IE and Safari</a> but <a href=\"https://github.com/GoogleChrome/dialog-polyfill\" rel=\"nofollow noreferrer\">there is a polyfill</a></p>\n\n<h2>Numbers in <code>draw()</code></h2>\n\n<p>There are various numbers used in calculations in the <code>draw()</code> function - e.g. 50, 40, 25, 20, 100, etc.. Presumably those are for widths, heights, etc. It would be wise to store those as constants so if you need to update the values you can do it in one place.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-15T23:29:15.760", "Id": "242370", "ParentId": "242296", "Score": "1" } } ]
{ "AcceptedAnswerId": "242350", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-14T19:51:21.887", "Id": "242296", "Score": "3", "Tags": [ "javascript", "ecmascript-6", "compression" ], "Title": "Huffman Encoding in Javascript" }
242296
<p>The method <code>list_all()</code> is the code I am starting with. It just lists all files in "c:\windows".</p> <p>I want to adjust it to list only the first 10 files (if there are as many files as that there).</p> <p>I can see that <code>Directory.GetFiles(sDir)</code> returns an array of string. The original method <code>list_all()</code>, takes all of them. I want mine to just take the first 10, or if there's less than 10 then all of them. But i've added four lines of code and used a list, to do it. My amended method is <code>list_some()</code></p> <p>It's far from a disaster, but I'm sure there's a better way though I'm not sure.</p> <pre><code>using System; using System.Collections.Generic; using System.IO; namespace ConsoleApp1 { class Program { static void Main(string[] args) { static void list_all() { string sDir = "c:\\windows"; foreach (string f in Directory.GetFiles(sDir)) { Console.WriteLine(f); } } static void list_some() { string sDir="c:\\windows"; List&lt;string&gt; lstsomefiles = new List&lt;string&gt;(); int count = Directory.GetFiles(sDir).Length; string[] strs_fileslst = Directory.GetFiles(sDir); for (int i = 0; i &lt; count &amp;&amp; i &lt; 10; i++) lstsomefiles.Add(strs_fileslst[i]); foreach (string f in lstsomefiles) { Console.WriteLine(f); } } } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-14T22:10:00.853", "Id": "475492", "Score": "2", "body": "Welcome to Code Review! 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." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-14T22:13:47.977", "Id": "475494", "Score": "0", "body": "@SᴀᴍOnᴇᴌᴀ better?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-14T22:17:41.590", "Id": "475495", "Score": "0", "body": "Maybe I should have linked to [this help center page: _How do I ask a good question?_](https://codereview.stackexchange.com/help/how-to-ask)... it is an improvement but hopefully, after reading that page, you understand what would make it even better..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-14T22:29:49.660", "Id": "475496", "Score": "2", "body": "Welcome to Code Review, where we review actual working code from your project. The function names `blah_all` and `blah_some` as well as the variable name `lstsomefiles` seem more hypothetical than real code. In C# this code would also be in a class, and that I don't see. As Sam indicated above, please read the Asking section of the Code Review Guidelines." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-14T22:37:31.980", "Id": "475498", "Score": "2", "body": "@pacmaninbw i've now included the class and improved the function names. I made a simple example to give a simple easily demonstrable code that gets to the crux of the question I am asking. Maybe my question is more for stackoverflow if you don't want simple easily demonstrable code?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-15T14:01:36.283", "Id": "475584", "Score": "0", "body": "We require **concrete code** from a project with sufficient context to understand how that code is used. **Pseudocode**, stub code, **hypothetical code** & obfuscated code are outside the scope of this site. Please [**follow the tour**](https://CodeReview.StackExchange.com/tour), and read [**\"What topics can I ask about here?\"**](https://CodeReview.StackExchange.com/help/on-topic), [**\"How do I ask a good question?\"**](https://CodeReview.StackExchange.com/help/how-to-ask) and [**\"What types of questions should I avoid asking?\"**](https://CodeReview.StackExchange.com/help/dont-ask)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-15T14:45:38.300", "Id": "475587", "Score": "0", "body": "@BCdotWEB Yes I saw from asking somebody in chat, you aren't really looking to run the code. So my Q was better for SO. And people on this site would improve by eye, code that they can't run, (And wouldn't really look to run it), so that explains why you don't want a small demonstrable example of a problem. And so I also suppose it's more for so people don't commit code that defies conventions? And in those situations the poster is often unaware of what their issue(s) are, is that right?" } ]
[ { "body": "<p>You can utilize the <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.linq.enumerable.take?view=netcore-3.1\" rel=\"noreferrer\"><code>.Take()</code></a> method in LINQ which:</p>\n\n<blockquote>\n <p>Returns a specified number of contiguous elements from the start of a sequence</p>\n</blockquote>\n\n<p>Using this, your code would look as follows:</p>\n\n<pre><code>string sDir = \"c:\\\\windows\";\n\nforeach (string f in Directory.GetFiles(sDir).Take(10))\n{\n Console.WriteLine(f);\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-14T23:31:52.710", "Id": "475501", "Score": "0", "body": "wow that's beautiful" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-15T06:38:13.570", "Id": "475529", "Score": "4", "body": "I think, you can optimize a bit by using `Directory.EnumerateFiles(path).Take(10)`. `EnumerateFiles` does not materialize all the file names in an array before returning. It operates directly on an Enumerator." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-15T09:42:18.380", "Id": "475547", "Score": "2", "body": "@barlop: In general, whenever you iterate over a list, 9 times out of 10 there's a cleaner LINQ approach. It's really worth having a look at what LINQ offers since it will dramatically improve code readability and prevent you from having to juggle list manipulation yourself." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-15T12:38:59.127", "Id": "475566", "Score": "0", "body": "As a second choice, supposing one didn't use LINQ, was what I wrote in my amendment unnecessarily laborious? what is a good way?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-15T15:21:02.523", "Id": "475588", "Score": "0", "body": "[To support @HenrikHansen's point](https://docs.microsoft.com/en-us/dotnet/api/system.io.directory.getfiles): \"The `EnumerateFiles` and `GetFiles` methods differ as follows: When you use `EnumerateFiles`, you can start enumerating the collection of names before the whole collection is returned; when you use `GetFiles`, you must wait for the whole array of names to be returned before you can access the array. Therefore, when you are working with many files and directories, `EnumerateFiles` can be more efficient.\"" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-14T23:31:00.143", "Id": "242304", "ParentId": "242298", "Score": "5" } } ]
{ "AcceptedAnswerId": "242304", "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-14T21:13:02.493", "Id": "242298", "Score": "3", "Tags": [ "c#", "strings" ], "Title": "Amending code to make it list some files in a directory, rather than all" }
242298
<p>The following method works. I am looking for advice to make it more readable. To see if I could avoid any unneccesary checks / casting and the instance of check. Also not a fan of having to recreate the initial String with every loop but not sure if there is a way around it. </p> <blockquote> <p>Things to note.<br> I am using Java 8 and Spring boot.<br> I can't change the productMap. It will remain as a Map &lt; String, Object> .<br> Can use external library Apache commons but not Guava.<br> It is possible for initialText and productMap to be null / empty.<br> In the map, I am only looking for values which are of type String and value contains only numbers. If it exists, I want to use it and replace initialText</p> </blockquote> <p>Example scenario with following data in the parameters being passed in: </p> <pre><code>String initialText = "This is a sample text with PLACEHOLDER and yet another PLACEHOLDER and more message." productMap = { "Some key" : new SomeObject(), // I won't use this cos value is not String. "PLACEHOLDER" : "26000", // I will use this to replace cos the key PLACEHOLDER exists in above text and it contains only numbers. "SOME_OTHER" : "SOME_TEXT", // it is a String value but the key doesn't exist in the initial text thus no difference. } </code></pre> <p>After executing the following code, I expect the method to return the updated String as follows (notice the comma due to String format):</p> <p>"This is a sample text with 26,000 and yet another 26,000 and more message."</p> <p>Method as follows. Appreciate the advices. Thanks. </p> <pre><code>public String update(String initialText, Map&lt;String, Object&gt; productMap){ if(StringUtils.isBlank(initialText) || MapUtils.isEmpty(productMap)){ return initialText; } for (Map.Entry&lt;String, Object&gt; productData : productMap.entrySet()) { String key = productData.getKey(); Object value = productData.getValue(); if(value instanceof String &amp;&amp; ((String) value).matches("[0-9]+")){ String offerValue = (String)value; initialText = initialText.replaceAll(key, String.format("%,d", Integer.parseInt(offerValue))); } } return initialText; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-15T08:04:17.840", "Id": "475535", "Score": "0", "body": "Do you check only non-negative numbers? Can the map contain integer?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-15T08:43:02.880", "Id": "475537", "Score": "0", "body": "@shanif No integer values in map. The String values can contain only non negative numbers." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-15T09:38:02.087", "Id": "475546", "Score": "0", "body": "You can use only objects derived from an interface with `public String format()`. Then you can do allways `value.format()` These objects can get more infos like decimal places." } ]
[ { "body": "<pre><code>public String update(String initialText, Map&lt;String, Object&gt; productMap){ // 1\n if(StringUtils.isBlank(initialText) || MapUtils.isEmpty(productMap)){ // 2\n return initialText; // 3\n } // 4\n for (Map.Entry&lt;String, Object&gt; productData : productMap.entrySet()) { // 5\n String key = productData.getKey(); // 6\n Object value = productData.getValue(); // 7\n if(value instanceof String &amp;&amp; ((String) value).matches(\"[0-9]+\")){ // 8\n String offerValue = (String)value; // 9\n initialText = initialText.replaceAll(key, String.format(\"%,d\", Integer.parseInt(offerValue))); //10\n } // 11\n } // 12\n return initialText; // 13\n} // 14\n</code></pre>\n\n<hr>\n\n<h2>Line 1</h2>\n\n<p>The method and parameter names could be clearer. A method named <code>update</code> could do many things. How about something akin to <code>replacePlaceholders</code>. Analogously, <code>initialText</code> would become <code>template</code>. Also, the <a href=\"https://en.wikipedia.org/wiki/Hungarian_notation\" rel=\"nofollow noreferrer\">Hungarian notation</a> for the map parameter isn't needed (<a href=\"https://stackoverflow.com/questions/2253453/how-should-i-name-a-java-util-map\">How should I name a java.util.Map?</a>). Maybe <code>substitutionByPlaceholder</code> or something similar. I feel like there could be a better name, but I lack the domain knowledge.</p>\n\n<p>Also, I always make parameters, variables and such <code>final</code>. I swear by it, but maybe your style guide disallows it.</p>\n\n<p>Making the parameters <code>final</code> also prevents you from reassigning them, which is usually a good thing, because it prevents silly mistakes like</p>\n\n<pre><code>public void setFoo(int foo) {\n foo = foo;\n}\n</code></pre>\n\n<p>It looks obvious now, but in a more complex method, it can cause a bug real' quick.</p>\n\n<h2>Lines 5, 6, 7</h2>\n\n<p>Again, <code>final</code> variables are recommended. </p>\n\n<h2>Lines 6, 7</h2>\n\n<p><code>key</code> and <code>value</code> aren't great names. How about <code>placeholder</code> and <code>replacement</code>?</p>\n\n<h2>Line 8</h2>\n\n<p>Your method of testing if the <code>String</code> is an <code>int</code> is flawed. How about negative Integers, or something like <code>100000000000000000000000000</code>. That sure isn't an Integer. Be sure to think about corner cases like this!</p>\n\n<p>If it's almost always an Integer or performance doesn't matter to you, you can just use <code>Integer.parseInt</code> wrapped in a try catch block. Deliberately catching Exceptions for control flow is usually not recommended though. For alternatives, see <a href=\"https://stackoverflow.com/questions/5439529/determine-if-a-string-is-an-integer-in-java\">What's the best way to check if a String represents an integer in Java?</a></p>\n\n<hr>\n\n<p>The rest looks okay, but it's a big method. Not huge by any means, but it still does too much. To quote Robert C. Martin in Clean Code:</p>\n\n<blockquote>\n <p>Functions should do one thing. They should do it well. They should do it only.</p>\n</blockquote>\n\n<p>If you look at your method, it does multiple things. It guards against bad input, it loops over the map, it checks if entries are valid, and it does the replacement.</p>\n\n<p>If we split your method into four method, they all become just a few lines each, each method doing exactly one thing (Barring the last one, which does two things, checking if the String is an integer and replacing, which is a symptom of us using try-catch for control flow) that is very easy to understand.</p>\n\n<p>Also all methods may be static since they don't use any instance members.</p>\n\n<pre><code>public static String replacePlaceholders(final String template, final Map&lt;String, Object&gt; productMap) {\n if (StringUtils.isBlank(template) || MapUtils.isEmpty(productMap)) {\n return template;\n }\n\n return replaceAllPlaceholders(template, productMap);\n}\n\nprivate static String replaceAllPlaceholders(final String template, final Map&lt;String, Object&gt; productMap) {\n String result = template;\n\n for (final Map.Entry&lt;String, Object&gt; productData : productMap.entrySet()) {\n result = replacePlaceholderIfValueIsIntegerString(result, productData);\n }\n\n return result;\n}\n\nprivate static String replacePlaceholderIfValueIsIntegerString(final String template, final Map.Entry&lt;String, Object&gt; entry) {\n if (entry.getValue() instanceof String) {\n return replacePlaceholderIfReplacementIsInteger(entry.getKey(), (String) entry.getValue(), template);\n }\n return template;\n}\n\nprivate static String replacePlaceholderIfReplacementIsInteger(final String placeholder, final String replacement, final String template) {\n try {\n return template.replaceAll(placeholder, String.format(\"%,d\", Integer.parseInt(replacement)));\n } catch (final NumberFormatException e) {\n return template;\n }\n}\n</code></pre>\n\n<p>Recommended reading: </p>\n\n<ul>\n<li><p><a href=\"https://www.oreilly.com/library/view/clean-code/9780136083238/\" rel=\"nofollow noreferrer\">Robert C. Martin; Clean Code</a></p></li>\n<li><p><a href=\"https://www.oreilly.com/library/view/effective-java-3rd/9780134686097/\" rel=\"nofollow noreferrer\">Joshua Block; Effective Java, 3rd Edition</a></p></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-15T02:35:08.177", "Id": "242309", "ParentId": "242302", "Score": "2" } }, { "body": "<h1>Single Responsibility</h1>\n<p>Your function do 2 things:</p>\n<ol>\n<li>Filter the map to contain only numbers</li>\n<li>Fill template string with relevant values</li>\n</ol>\n<p>I suggest to separate to 2 functions.</p>\n<h1>Filter the map</h1>\n<p>Will be more readable with Java Streams <code>filter</code> and <code>map</code>.</p>\n<p>The result should be a map from string to int.</p>\n<h1>Fill template</h1>\n<p>Can be done with Java streams <code>reduce</code> or <code>collect</code>.</p>\n<p>StringBuilder could be usufull here but it doesn't contains a function <code>replaceAll</code>.</p>\n<h1>Code review</h1>\n<ul>\n<li><p>Don't reassign input parameters. It will make it harder for you to debug and it is confusing because the name don't fit the purpose of the variable. Do this instead</p>\n<p><code>string res =initialText</code>\nand keep changing res.</p>\n</li>\n<li><p>I like to name maps in following format: keyName2valueName. In your case placeholder2number.</p>\n</li>\n<li><p>The following code can be removed and the function still works.</p>\n</li>\n</ul>\n<pre><code>if(StringUtils.isBlank(initialText) || MapUtils.isEmpty(productMap)){\n return initialText;\n }\n</code></pre>\n<p>I don't think it helps very much to the performance either.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-15T08:58:45.463", "Id": "475539", "Score": "0", "body": "For you last point, If I don't do that, this could throw null errors > productMap.entrySet() ." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-15T11:13:03.667", "Id": "475560", "Score": "0", "body": "@karvai You mean in case productMap is null? Why should you have such a case?" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-15T08:01:49.620", "Id": "242319", "ParentId": "242302", "Score": "1" } } ]
{ "AcceptedAnswerId": "242309", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-14T23:22:07.257", "Id": "242302", "Score": "4", "Tags": [ "java" ], "Title": "Looping over a map requiring casting and instance checks" }
242302
<p>I wanted to get some thread support on windows with very simple headers for a library that I'm working on but it had to work on both Windows and Linux. Since C11 threads are not widely supported, this was a great opportunity to learn more about the Windows API and POSIX threads. I decided to post this here because I'm not very experienced with threads and mutexes from both Windows and POSIX and I'd like it to be reviewed. Some things are omitted because they are part of the aforementioned library.</p> <p><strong>flags.h</strong></p> <pre class="lang-c prettyprint-override"><code>/** * cmc_flags * * Defines common error codes used by the entire library. */ static struct { int OK; // No errors int THREAD; // Generic error regarding threads int MUTEX; // Generic error regarding mutexes } cmc_flags = { 0, /* Omitted */ 8, 9 }; </code></pre> <p><strong>mutex.h</strong></p> <pre class="lang-c prettyprint-override"><code>/** * A very simple, header-only and minimalistic cross-platform mutex * * Types * - cmc_mutex * * Functions * - cmc_mtx_init * - cmc_mtx_destroy * - cmc_mtx_lock * - cmc_mtx_unlock * - cmc_mtx_trylock */ #include &lt;stdbool.h&gt; #include "flags.h" #if defined(_WIN32) #define CMC_MUTEX_WINDOWS #elif defined(__unix__) #define CMC_MUTEX_UNIX #else #error "Unknown platform for CMC Mutex" #endif /* Platform specific includes */ #if defined(CMC_MUTEX_WINDOWS) #include &lt;windows.h&gt; #elif defined(CMC_MUTEX_UNIX) #include &lt;errno.h&gt; #include &lt;pthread.h&gt; #endif /** * struct cmc_mutex * * A mutex wrapper. */ struct cmc_mutex { #if defined(CMC_MUTEX_WINDOWS) HANDLE mutex; #elif defined(CMC_MUTEX_UNIX) pthread_mutex_t mutex; #endif int flag; }; /** * Acquire resources for a mutex. * * \param mtx An uninitialized mutex wrapper. * \return True or false if the mutex was successfully initialized. */ static inline bool cmc_mtx_init(struct cmc_mutex *mtx) { #if defined(CMC_MUTEX_WINDOWS) mtx-&gt;mutex = CreateMutex(NULL, FALSE, NULL); if (mtx-&gt;mutex == NULL) mtx-&gt;flag = cmc_flags.MUTEX; else mtx-&gt;flag = cmc_flags.OK; return mtx-&gt;mutex != NULL; #elif defined(CMC_MUTEX_UNIX) int err = pthread_mutex_init(&amp;(mtx-&gt;mutex), NULL); if (err != 0) mtx-&gt;flag = cmc_flags.MUTEX; else mtx-&gt;flag = cmc_flags.OK; return err == 0; #endif } /** * Release all resources from a mutex. Calling this function on a locked mutex * causes undefined behavior. * * \param mtx A mutex to be destroyed. * \return True or false if the mutex was successfully destroyed. */ static inline bool cmc_mtx_destroy(struct cmc_mutex *mtx) { #if defined(CMC_MUTEX_WINDOWS) if (!CloseHandle(mtx-&gt;mutex)) { mtx-&gt;flag = cmc_flags.MUTEX; return false; } mtx-&gt;flag = cmc_flags.OK; return true; #elif defined(CMC_MUTEX_UNIX) if (pthread_mutex_destroy(&amp;(mtx-&gt;mutex)) != 0) { mtx-&gt;flag = cmc_flags.MUTEX; return false; } mtx-&gt;flag = cmc_flags.OK; return true; #endif } /** * Locks a mutex. If the mutex is already locked, the thread is blocked until * the mutex can be acquired. * * \param mtx A mutex to be locked. * \return True or false if the lock on the mutex was successfully acquired. */ static inline bool cmc_mtx_lock(struct cmc_mutex *mtx) { #if defined(CMC_MUTEX_WINDOWS) DWORD result = WaitForSingleObject(mtx-&gt;mutex, INFINITE); if (result == WAIT_FAILED || result == WAIT_ABANDONED) { mtx-&gt;flag = cmc_flags.MUTEX; return false; } mtx-&gt;flag = cmc_flags.OK; return true; #elif defined(CMC_MUTEX_UNIX) if (pthread_mutex_lock(&amp;mtx-&gt;mutex) != 0) { mtx-&gt;flag = cmc_flags.MUTEX; return false; } mtx-&gt;flag = cmc_flags.OK; return true; #endif } /** * Unlocks a mutex. If the mutex is already locked, the thread is blocked until * the mutex can be acquired. * * \param mtx A mutex to be unlocked. * \return True or false if the mutex was successfully unlocked. */ static inline bool cmc_mtx_unlock(struct cmc_mutex *mtx) { #if defined(CMC_MUTEX_WINDOWS) if (!ReleaseMutex(mtx-&gt;mutex)) mtx-&gt;flag = cmc_flags.MUTEX; else mtx-&gt;flag = cmc_flags.OK; return mtx-&gt;flag == cmc_flags.OK; #elif defined(CMC_MUTEX_UNIX) if (pthread_mutex_unlock(&amp;mtx-&gt;mutex) != 0) mtx-&gt;flag = cmc_flags.MUTEX; else mtx-&gt;flag = cmc_flags.OK; return mtx-&gt;flag == cmc_flags.OK; #endif } /** * Tries to lock a mutex. If the mutex is already locked, the thread is not * blocked and the function returns false. * * \param mtx A mutex to try to lock. * \return True or false if the lock on the mutex was successfully acquired. */ static inline bool cmc_mtx_trylock(struct cmc_mutex *mtx) { #if defined(CMC_MUTEX_WINDOWS) DWORD result = WaitForSingleObject(mtx-&gt;mutex, 0); if (result == WAIT_FAILED || result == WAIT_ABANDONED) { mtx-&gt;flag = cmc_flags.MUTEX; return false; } mtx-&gt;flag = cmc_flags.OK; return result != WAIT_TIMEOUT; #elif defined(CMC_MUTEX_UNIX) int err = pthread_mutex_trylock(&amp;mtx-&gt;mutex); if (err == EINVAL || err == EFAULT) mtx-&gt;flag = cmc_flags.MUTEX; else mtx-&gt;flag = cmc_flags.OK; return err == 0; #endif } </code></pre> <p><strong>thread.h</strong></p> <pre class="lang-c prettyprint-override"><code>/** * A very simple, header-only utility for spawning and joining threads * * Types * - cmc_thread * - cmc_thread_proc * * Functions * - cmc_thrd_create * - cmc_thrd_join */ #include &lt;inttypes.h&gt; #include &lt;stdbool.h&gt; #include "flags.h" #if defined(_WIN32) #define CMC_THREAD_WINDOWS #elif defined(__unix__) #define CMC_THREAD_UNIX #else #error "Unknown platform for CMC Threads" #endif #if defined(CMC_THREAD_WINDOWS) #include &lt;windows.h&gt; #elif defined(CMC_THREAD_UNIX) #include &lt;pthread.h&gt; #endif /* The type of a process run by a thread */ typedef int (*cmc_thread_proc)(void *); /** * struct cmc_thread * * A thread wrapper. */ struct cmc_thread { #if defined(CMC_THREAD_WINDOWS) HANDLE thread; #elif defined(CMC_THREAD_UNIX) pthread_t thread; #endif int flag; void *args; cmc_thread_proc process; }; /* A thread wrapper */ #if defined(CMC_THREAD_WINDOWS) static DWORD cmc_thread_wrapper(void *arg) #elif defined(CMC_THREAD_UNIX) static void *cmc_thread_wrapper(void *arg) #endif { struct cmc_thread *thr = (struct cmc_thread *)arg; int result = thr-&gt;process(thr-&gt;args); #if defined(CMC_THREAD_WINDOWS) return result; #elif defined(CMC_THREAD_UNIX) return (void *)(intptr_t)result; #endif } /** * Creates and spawns a new thread. * * \param thr An uninitialized thread wrapper. * \param proc Pointer to a function that will run in a new thread. * \param args The arguments passed to the proc function. * \return True or false if the thread creation was successfull. */ static inline bool cmc_thrd_create(struct cmc_thread *thr, cmc_thread_proc proc, void *args) { #if defined(CMC_THREAD_WINDOWS) thr-&gt;args = args; thr-&gt;process = proc; thr-&gt;thread = CreateThread(NULL, 0, cmc_thread_wrapper, thr, 0, NULL); if (!thr-&gt;thread) thr-&gt;flag = cmc_flags.THREAD; else thr-&gt;flag = cmc_flags.OK; return thr-&gt;flag == cmc_flags.OK; #elif defined(CMC_THREAD_UNIX) thr-&gt;args = args; thr-&gt;process = proc; if (pthread_create(&amp;(thr-&gt;thread), NULL, cmc_thread_wrapper, thr) != 0) thr-&gt;flag = cmc_flags.THREAD; else thr-&gt;flag = cmc_flags.OK; return thr-&gt;flag == cmc_flags.OK; #endif } /** * Blocks the current thread until the target thread terminates. * * \param thr The target thread to wait on. * \param result The value returned by the target thread. Optional. * \return True or false if the join was successfull. */ static inline bool cmc_thrd_join(struct cmc_thread *thr, int *result) { #if defined(CMC_THREAD_WINDOWS) if (WaitForSingleObject(thr-&gt;thread, INFINITE) == WAIT_FAILED) { thr-&gt;flag = cmc_flags.THREAD; return false; } DWORD exit_code; if (result) { if (GetExitCodeThread(thr-&gt;thread, &amp;exit_code) == 0) { thr-&gt;flag = cmc_flags.THREAD; return false; } else *result = (int)exit_code; } thr-&gt;flag = cmc_flags.OK; if (CloseHandle(thr-&gt;thread) == 0) { thr-&gt;flag = cmc_flags.THREAD; return false; } thr-&gt;flag = cmc_flags.OK; return true; #elif defined(CMC_THREAD_UNIX) void *exit_value; if (pthread_join(thr-&gt;thread, &amp;exit_value) != 0) { thr-&gt;flag = cmc_flags.THREAD; return false; } if (result) { *result = (int)(intptr_t)exit_value; } thr-&gt;flag = cmc_flags.OK; return true; #endif } </code></pre> <p><strong>example.c</strong></p> <pre class="lang-c prettyprint-override"><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include "mutex.h" #include "thread.h" #define NTHREADS 1000 struct cmc_mutex lck; /* How many trylock failed */ struct cmc_mutex flck; int trylock_fails = 0; int thread_process(void *arg) { int *sum = (int *)arg; if (rand() % 2 == 0) { cmc_mtx_lock(&amp;lck); for (int i = 0; i &lt; 1000; i++) *sum += 1; cmc_mtx_unlock(&amp;lck); } else { if (!cmc_mtx_trylock(&amp;lck)) { cmc_mtx_lock(&amp;flck); trylock_fails += 1; cmc_mtx_unlock(&amp;flck); return 0; } for (int i = 0; i &lt; 1000; i++) *sum += 1; cmc_mtx_unlock(&amp;lck); } return 0; } int main(void) { cmc_mtx_init(&amp;lck); cmc_mtx_init(&amp;flck); struct cmc_thread threads[NTHREADS]; int sum = 0; for (int i = 0; i &lt; NTHREADS; i++) cmc_thrd_create(&amp;threads[i], thread_process, &amp;sum); for (int i = 0; i &lt; NTHREADS; i++) cmc_thrd_join(&amp;threads[i], NULL); printf("Total sum : %d\n", sum); printf("Failed trylocks : %d\n", trylock_fails); } <span class="math-container">```</span> </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-14T23:57:36.037", "Id": "242305", "Score": "1", "Tags": [ "c", "multithreading", "linux", "windows", "pthreads" ], "Title": "Simple header-only thread and mutex for both windows and linux in C" }
242305
<p>I just started learning to code during quarantine and whilst learning python, I created this program for a binary search. This is really basic so I assume that there is a way easier method. If anyone knows how I can make this way simpler, your help would be appreciated. </p> <pre><code>list = [1,15,37,53,29,22,31,90,14,6,37,40] finished = False target = 37 list.sort() print(list) while finished == False: n = len(list) print(n) if target &lt; list[int(n/2)]: for items in range(int(n / 2), n): list.pop() print('Item is too large.') elif target == list[int(n/2)]: finished = True print('The item has been found.') else: list.reverse() for items in range(int(n / 2), n): list.pop() list.reverse() print('Item is too small.') print(list) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-15T00:26:18.363", "Id": "475502", "Score": "1", "body": "i'm no expert but have studied computer science. You are going to keep reversing the entire list? seriously? how can that possibly be efficient. No binary search i've seen even reverses it once. And you should know there are already binary search algorithms written, you can look up any of them and none of them do anything like what you are doing. Binary search is a fairly standard algorithm, not something you make up as you go along" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-15T01:53:12.630", "Id": "475514", "Score": "0", "body": "[bisect](https://docs.python.org/3/library/bisect.html) is what I'd imagine reading `Basic binary search`: Please introduce your code with a description what it is to achieve, and how the implementation is a *basic binary search*." } ]
[ { "body": "<ul>\n<li>Avoid using <code>list</code> as the variable name, because it is <a href=\"https://www.programiz.com/python-programming/methods/built-in/list\" rel=\"nofollow noreferrer\">a\nfunction</a> in Python. </li>\n<li>You don't need to manipulate the list, such\nas <code>list.pop()</code> and <code>list.reverse()</code>. It is inefficient. You can\ndetermine the updated search range with index. </li>\n<li>When <code>target</code> is assigned a value not within <code>list</code>, there will be <code>IndexError: list index out of range</code>. It means you didn't handle the case well.</li>\n</ul>\n\n<p><strong>Modified code:</strong> </p>\n\n<pre><code>search_list = [1,15,37,53,29,22,31,90,14,6,37,40]\ntarget = 37\nstart = 0\nend = len(search_list)-1 \nsearch_list.sort()\nprint('The sorted list:',search_list)\nwhile start&lt;=end:\n n = int((end + start)/2)\n if target &lt; search_list[n]: # the target is small \n end = n-1\n elif target &gt; search_list[n]: # the target is large \n start = n+1\n elif target == search_list[n]: # the target is found \n print('The item {} has been found at the index {} in the sorted list.'.format(target,n))\n break \nelse:\n print('The item is not found.')\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-15T05:13:31.633", "Id": "242313", "ParentId": "242306", "Score": "2" } }, { "body": "<p>In addition to Chris Tang's answer, I strongly suggest that you encapsulate your binary search algorithm in a function.</p>\n\n<p>Currently, your code only works for the list defined at the beginning of the program. But what if you want to reuse it with another list later on? Or reuse this snippet in your next program? Encapsulating your code in a function would allow you to do that much more easily.</p>\n\n<p>I understand that, as a beginner, you just wanted to see if you could implement that algorithm, and don't actually reuse it, but it is a good habit to take on early. Including docstrings to document your code to document what it does is also a good things.</p>\n\n<p>Here is a slightly modified version of Chris Tang's code, encapsulating the logic:</p>\n\n<pre><code>def binary_search(search_list, target):\n \"\"\"Search a sorted list for the target value\n Returns the target's index, or None if the target is not in the list\"\"\"\n\n start = 0\n end = len(search_list) - 1\n\n while start&lt;=end:\n n = int((end + start) / 2)\n if target &lt; search_list[n]: # the target is small \n end = n-1\n elif target &gt; search_list[n]: # the target is large \n start = n+1\n else: # the target is found \n return n\n return None\n\n\nif __name__ == '__main__':\n my_list = [1,15,37,53,29,22,31,90,14,6,37,40]\n my_list.sort()\n target = 37\n target_index = binary_search(my_list, target)\n if target is not None:\n print(f'{target} was found at index {target_index}')\n else:\n print(f'{target} was not found in the list')\n</code></pre>\n\n<p>Some other remarks about my code:</p>\n\n<ul>\n<li>The function returns a value, instead of printing it. This means, should you reuse the function in some other code, you can decide what to do with the value.</li>\n<li>I include the execution code in a <code>if __name__ == '__main__':</code>. This means that, should you <code>import</code> your script in another piece of code, it will not run the code included in that <code>if</code> statement, but it will be executed if you run your script directly. You will probably never <code>include</code> this particular script, but I believe this is a good habit to take.</li>\n<li>I use f-strings instead of <code>string.format()</code> as it works mostly the same and I believe it is more readable. It is a matter of preference, I suppose.</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-15T09:05:27.340", "Id": "242324", "ParentId": "242306", "Score": "1" } } ]
{ "AcceptedAnswerId": "242313", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-15T00:06:36.673", "Id": "242306", "Score": "2", "Tags": [ "python", "array", "search", "binary-search" ], "Title": "Basic binary search in python" }
242306
<p>I'm a computer-science hobbyist and found an NP-complete problem that is similar to both <a href="https://cs.stackexchange.com/questions/7907/is-the-subset-product-problem-np-complete">subset-product</a> and <a href="https://npcomplete.owu.edu/2014/06/10/exact-cover-by-3-sets/" rel="nofollow noreferrer">Exact Cover by 3-sets</a>.</p> <p>Here is a Reduction of Exact-Cover into my problem. I am multiplying all integers in sets of C.</p> <pre class="lang-none prettyprint-override"><code>Input prior to reduction s: [1, 2, 3, 4, 5, 6] c: [[5, 2, 1], [6, 4, 3]] Output after reduction s : [1, 2, 3, 4, 5, 6] c : [10, 72] Integers needed for True subset-product [[5, 2, 1], [6, 4, 3]] </code></pre> <h2>Algorithm</h2> <pre class="lang-py prettyprint-override"><code>import itertools from itertools import combinations from itertools import permutations import operator from operator import mul from functools import reduce s = [1,2,3,4,5,6] c = 10,72 # Preparing all possible # three-element sets find_X_thr_covers=[]; for jj in permutations((s), 3): if len(jj) == len(set(jj)): # I will "remember" multiplied sets in c for later use. if reduce(mul, jj) in c: find_X_thr_covers.append(jj) # Here, I will use len(s)//3 combinations # for a special case of the Exact Cover # problem by 3-sets. solutions = [] solutions_two = [] for jj in combinations(find_X_thr_covers, len(s)//3): # Here I will verify that every possible combination # is indeed a true solution. jj_flat = [item for sub in jj for item in sub] jj_set = set(jj_flat) if set(s) == jj_set and len(jj_set) == len(jj_flat): solution = list(jj) # I will use a for loop to multiply all elements in # the Exact Three Cover solutions. for a in range(0, len(solution)): solution[a] = reduce(mul, solution[a]) if a == len(solution) - 1: solutions.append(solution) solutions_two = jj break # removing repeating sets solutions =[solutions[x] for x in range(len(solutions)) if not(solutions[x] in solutions[:x])] print(solutions) print(solutions_two) print('Found Exact Three Product Cover') </code></pre> <h2>Output</h2> <pre class="lang-none prettyprint-override"><code>[[10, 72], [72, 10]] ((5, 2, 1), (6, 4, 3)) Found Exact Three Product Cover </code></pre> <h2>Questions</h2> <p>Is using fixed permutations of 3 a bad way to solve this problem? </p> <p>What's the slowest parts of my Python script and how do I improve execution speed with <a href="https://www.geeksforgeeks.org/exact-cover-problem-algorithm-x-set-1/" rel="nofollow noreferrer">Algorithm X</a>? </p> <p>The Algorithm X isn't necessary to be provided as a solution but should only be explained if possible in a pythonic manner. I'm fine with an answer that only explains the problems with my code.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-15T23:56:56.233", "Id": "475625", "Score": "0", "body": "Just found out that if I limit input length to the 31 facrors of 720 it woul speed up algorithim?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-16T00:03:08.997", "Id": "475626", "Score": "0", "body": "Just check that all values in C are a factor of the total product of s. And remove repeating values. Thus the maximum possible length of c would be 31 factora." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-15T03:01:17.173", "Id": "242310", "Score": "2", "Tags": [ "python", "math-expression-eval", "set" ], "Title": "Solving Exact Cover by Three Products in Python" }
242310
<pre><code>$scope.selectAllProctoringUser = function(checked) { try { for (var k = 0; k &lt; $scope.scheduleUsers.lstOnlineProctoring.length; k++) { $scope.scheduleUsers.lstOnlineProctoring[k].selected = checked; if (checked) { let flag = 0; if($scope.selectedUserListOP.length == 0) { $scope.selectedUserListOP.push($scope.scheduleUsers.lstOnlineProctoring[k]); flag = 1; } else { angular.forEach($scope.selectedUserListOP, (el, idx) =&gt; { if(el.StudentScheduleUsrID === $scope.scheduleUsers.lstOnlineProctoring[k].StudentScheduleUsrID) { flag = 1; } }); } if(flag === 0){ $scope.selectedUserListOP.push($scope.scheduleUsers.lstOnlineProctoring[k]); } } else { angular.forEach($scope.selectedUserListOP, (el, idx) =&gt; { if(el.StudentScheduleUsrID === $scope.scheduleUsers.lstOnlineProctoring[k].StudentScheduleUsrID) { $scope.selectedUserListOP.splice(idx, 1); } }); } } } catch(e) { console.log('Method: selectAllProctoringUser: ' + e.message); } } </code></pre> <p>I had replaced the above with below snippets and working perfectly</p> <pre><code>$scope.selectAllProctoringUser = function(checked) { try { $scope.scheduleUsers.lstOnlineProctoring.forEach(x =&gt; { x.selected = checked; if(checked){ if($scope.selectedUserListOP.filter(m =&gt; m.StudentScheduleUsrID == x.StudentScheduleUsrID).length == 0) $scope.selectedUserListOP.push(x); } else if(!checked){ if($scope.selectedUserListOP.filter(m =&gt; m.StudentScheduleUsrID == x.StudentScheduleUsrID).length &gt; 0) $scope.selectedUserListOP.splice(x, 1); } }); } catch(e) { console.log('Method: selectAllProctoringUser: ' + e.message); } } </code></pre> <p>If the above code could still get reduced? or written instead making use of <code>filter</code> operator</p> <p>Are there any use cases, substituting the above code may cause failure or exceptions?</p> <p>Expecting more solutions from what that I had initially coded</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-15T09:54:16.540", "Id": "475548", "Score": "1", "body": "What is the purpose of the `try`/`catch`? Are you expecting to encounter errors? If so, where?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-15T10:33:02.883", "Id": "475553", "Score": "0", "body": "Default way to handle any exceptions. What happens if it was there or not there? Incase if any exception was thrown from any `JS` how would you identify it or Have you got any idea about how to deal with exceptions @CertainPerformance" } ]
[ { "body": "<p>I see what looks like a bug. The <code>x</code> variable (which should probably be renamed to something more informative - maybe <code>user</code>?) is a object (with <code>selected</code> and <code>StudentScheduleUsrID</code> properties) which you remove from the array in the upper code with</p>\n\n<pre><code>} else {\n angular.forEach($scope.selectedUserListOP, (el, idx) =&gt; {\n if(el.StudentScheduleUsrID === $scope.scheduleUsers.lstOnlineProctoring[k].StudentScheduleUsrID) {\n $scope.selectedUserListOP.splice(idx, 1);\n }\n });\n}\n</code></pre>\n\n<p><code>splice</code>'s first argument should be the <em>index</em> of the element you want to start deleting from. That's fine. But in the lower code, the first argument you pass to <code>splice</code> is the <em>object</em> <code>x</code>, not the index:</p>\n\n<pre><code>$scope.scheduleUsers.lstOnlineProctoring.forEach(x =&gt; {\n // ...\n } else if(!checked){\n if($scope.selectedUserListOP.filter(m =&gt; m.StudentScheduleUsrID == x.StudentScheduleUsrID).length &gt; 0)\n $scope.selectedUserListOP.splice(x, 1);\n }\n</code></pre>\n\n<p>That won't work, because the first argument is not a number. If you want to remove this <code>x</code> from the array there, find its <em>index</em> in the array with <code>findIndex</code>, then pass that number to <code>splice</code>.</p>\n\n<pre><code>const selectedUserIndex = $scope.selectedUserListOP.findIndex(\n selectedUser =&gt; selectedUser.StudentScheduleUsrID === user.StudentScheduleUsrID\n);\nif (selectedUserIndex !== -1) {\n $scope.selectedUserListOP.splice(selectedUserIndex, 1);\n}\n</code></pre>\n\n<hr>\n\n<p>On a different note: Errors <strong>should not arise</strong> in synchronous code in most cases. If you have code that sometimes results in an unexpected error, you should fix the code so that the error doesn't ever occur (as far as you can tell). If you've tested the code in various situations (which you should be doing anyway, as a developer) and you can't think of any which might cause an error to occur, there shouldn't be any reason to use <code>try</code>/<code>catch</code>, since it'll just clutter up the code - and besides, you aren't doing anything with the error other than logging it to the console, but the error will be logged to the console anyway. So, feel free to remove the <code>try</code>/<code>catch</code>.</p>\n\n<p>It can be reasonable to have a <code>try</code>/<code>catch</code> if any of the following are true <em>and</em> you can do something useful with the error (such as send it to your server logs for examination, or gracefully degrade functionality for the user):</p>\n\n<ul>\n<li>You're <code>await</code>ing an asynchronous operation that might throw (eg, due to a network problem - very common)</li>\n<li>Synchronous code you're calling and don't have control over may throw (pretty unusual)</li>\n<li>Despite implementing your own tests, the logic is extremely complicated and you're not sure if there lingering issues (pretty unusual)</li>\n<li>You need to break out of a deeply nested function with <code>throw</code> and yield control flow back to a much higher calling function (pretty unusual and somewhat of a code smell - better to test values and return when invalid)</li>\n</ul>\n\n<p>None of the above are going on here.</p>\n\n<hr>\n\n<p>Instead of filtering inside the loop to check to see if any of the elements in the <code>selectedUserListOP</code> have a matching <code>StudentScheduleUsrID</code>, it would be more elegant and less computationally complex to construct a Set of all the <code>StudentScheduleUsrID</code>s in the <code>selectedUserListOP</code> beforehand. Then, all you need to do inside the loop is check whether that set <code>.has</code> it:</p>\n\n<pre><code>$scope.selectAllProctoringUser = function(checked) {\n const selectedUserStudentIds = new Set(\n $scope.selectedUserListOP.map(\n user =&gt; user.StudentScheduleUsrID\n )\n );\n $scope.scheduleUsers.lstOnlineProctoring.forEach(user =&gt; {\n user.selected = checked;\n if (checked) {\n if (!selectedUserStudentIds.has(user.StudentScheduleUsrID)) {\n $scope.selectedUserListOP.push(x);\n }\n } else {\n const selectedUserIndex = $scope.selectedUserListOP.findIndex(\n selectedUser =&gt; selectedUser.StudentScheduleUsrID === user.StudentScheduleUsrID\n );\n if (selectedUserIndex !== -1) {\n $scope.selectedUserListOP.splice(selectedUserIndex, 1);\n }\n }\n });\n}\n</code></pre>\n\n<p>If you <em>did</em> have to iterate over the array there, instead of <code>if (someArr.filter(...).length == 0)</code>, it would be better to</p>\n\n<ul>\n<li>Use <a href=\"https://stackoverflow.com/questions/359494/which-equals-operator-vs-should-be-used-in-javascript-comparisons\">strict equality</a> with <code>===</code>, not loose equality (consider using a linter)</li>\n<li><p>To check whether every items in an array passes a test (or doesn't pass a test), use <code>.every</code> or <code>.some</code> - <em>don't</em> use <code>.filter</code> to construct a new array only to check its length. Eg:</p>\n\n<pre><code>if ($scope.selectedUserListOP.every(m =&gt; m.StudentScheduleUsrID !== x.StudentScheduleUsrID))\n</code></pre></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-15T16:46:39.807", "Id": "242353", "ParentId": "242315", "Score": "2" } } ]
{ "AcceptedAnswerId": "242353", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-15T06:23:25.810", "Id": "242315", "Score": "1", "Tags": [ "javascript", "unit-testing", "ecmascript-6", "angular.js", "ecmascript-8" ], "Title": "Selecting/ Deselecting All from Checkbox" }
242315
<p>Here is my code, however, I am unsure whether it is the fastest way to achieve this objective. </p> <pre><code>import random add_to = int(input("2 numbers must add to: ")) multiply_to = int(input("2 numbers must multiyply to: ")) solved = False while solved == False: nums = random.sample(range(-100, 150), 2) if (nums[0] + nums[1] == add_to) and (nums[0] * nums[1] == multiply_to): print(nums) print('Solved') break </code></pre> <p>Question: 1. Is it possible for the range to be set based upon the input of numbers given by the user. </p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-15T07:27:30.870", "Id": "475534", "Score": "3", "body": "Using random numbers is one of the **slowest ways** to find the two numbers. The much faster way is to solve two equations, `x1+x2=sum;x1x2=product`, which is not hard." } ]
[ { "body": "<p>Rather than generating two random numbers it would be much faster to generate one and determine the other.</p>\n\n<p><span class=\"math-container\">$$\n\\begin{align}\n x + y &amp;= \\text{sum}\\\\\n x * y &amp;= \\text{product}\n\\end{align}\n$$</span></p>\n\n<p>Since <span class=\"math-container\">\\$\\text{sum}\\$</span> and <span class=\"math-container\">\\$\\text{product}\\$</span> are constants we can determine <span class=\"math-container\">\\$y\\$</span> from either. And go on to find the equation that <span class=\"math-container\">\\$x\\$</span> must hold.</p>\n\n<p><span class=\"math-container\">$$\n\\begin{align}\n x + y &amp;= \\text{sum}\\\\\n y &amp;= \\text{sum} - x\\\\\n x * y &amp;= \\text{product}\\\\\n x * (\\text{sum} - x) &amp;= \\text{product}\\\\\n \\text{sum}x - x^2 &amp;= \\text{product}\\\\\n\\end{align}\n$$</span></p>\n\n<p>This means that we can find the solution by only using <span class=\"math-container\">\\$x\\$</span>, and determining <span class=\"math-container\">\\$y\\$</span> after the fact.</p>\n\n<p>We can see how this effects your code by using <code>range</code> rather than <code>random.sample</code>. When generating both <span class=\"math-container\">\\$x\\$</span> and <span class=\"math-container\">\\$y\\$</span> you'll need two <code>for _ in range(n)</code> loops, which are nested. This means your code will run in <span class=\"math-container\">\\$O(n^2)\\$</span> time. With only <span class=\"math-container\">\\$x\\$</span> it will however run in <span class=\"math-container\">\\$O(n)\\$</span> time as it will have only one for loop.</p>\n\n<p>However we can get better than <span class=\"math-container\">\\$O(n)\\$</span> time. As you should be able to see that the math is producing a quadratic, and so we can just use the <a href=\"https://en.wikipedia.org/wiki/Quadratic_formula\" rel=\"nofollow noreferrer\">Quadratic Formula</a>.</p>\n\n<p><span class=\"math-container\">$$\n\\begin{align}\n \\text{sum}x - x^2 &amp;= \\text{product}\\\\\n 0 &amp;= x^2 - \\text{sum}x + \\text{product}\\\\\n x &amp;= \\frac{\\text{sum} \\pm \\sqrt{\\text{sum}^2 - 4\\text{product}}}{2}\\\\\n y &amp;= \\text{sum} - x\n\\end{align}\n$$</span></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-17T15:06:40.213", "Id": "475821", "Score": "0", "body": "You goofed your quadratic formula substitution. \"-sum x\" means \"b = -sum\", so the first term \"-b\" becomes \"-(-sum)\", which is \"+sum\", not \"-sum\"." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-17T15:09:19.720", "Id": "475822", "Score": "0", "body": "@AJNeufeld Indeed I must have misread something without a minus. Thank you :)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-15T10:50:35.280", "Id": "242330", "ParentId": "242317", "Score": "2" } }, { "body": "<h1>Code Review</h1>\n\n<p><code>while solved == False:</code> is an awkward way of writing the loop condition. <code>while not solved:</code> would be clearer and more Pythonic.</p>\n\n<hr>\n\n<p>You never set <code>solved = True</code> anywhere. Instead, you unconditionally <code>break</code> out of the loop. This means your loop could actually be written <code>while True:</code>, but I don't think this is clearer. Using <code>solved = True</code> instead of <code>break</code> would terminate the loop in an expected way.</p>\n\n<hr>\n\n<p>This is verbose:</p>\n\n<pre><code> nums = random.sample(range(-100, 150), 2)\n if (nums[0] + nums[1] == add_to) and (nums[0] * nums[1] == multiply_to):\n</code></pre>\n\n<p>You could unpack <code>nums</code> into to individual variables, and avoid the <code>[0]</code> and <code>[1]</code> indexing operations, for more performant code:</p>\n\n<pre><code> x1, x2 = random.sample(range(-100, 150), 2)\n if x1 + x2 == add_to and x1 * x2 == multiply_to:\n</code></pre>\n\n<hr>\n\n<p>If you give values which can never work with integers, like add to <code>2</code> and multiply to <code>3</code>, you have an infinite loop. You should have a \"give up after so many attempts\" procedure.</p>\n\n<hr>\n\n<h1>Monte Carlo</h1>\n\n<p>As pointed out by <a href=\"https://codereview.stackexchange.com/a/242330/100620\">Peilonrayz</a>, there is an <span class=\"math-container\">\\$O(1)\\$</span> solution to the problem.</p>\n\n<p>However, if your goal is to utilize a <a href=\"https://en.wikipedia.org/wiki/Monte_Carlo_method\" rel=\"nofollow noreferrer\">Monte Carlo simulation method</a> ...</p>\n\n<p>If <code>multiply_to</code> is:</p>\n\n<ul>\n<li>positive, then the numbers must be the same sign, both positive or both negative, which you could determine by looking at the <code>add_to</code> sign,</li>\n<li>negative, then one number must be greater than zero, and the other must be less than zero,</li>\n<li>zero, then one number must be zero.</li>\n</ul>\n\n<p>eg)</p>\n\n<pre><code>if multiply_to &gt; 0:\n if add_to &gt; 0:\n r1 = range(1, add_to)\n r2 = range(1, add_to)\n else:\n r1 = range(add_to + 1, 0)\n r2 = range(add_to + 1, 0)\n\nelif multiply_to &lt; 0:\n r1 = range(1, 150) # A positive value in your initial range bracket\n r2 = range(-100, 0) # A negative value in your initial range bracket\n\nelse:\n r1 = range(add_to, add_to + 1)\n r2 = range(0, 1)\n\n\nfor _ in range(10_000):\n x1 = random.choice(r1)\n x2 = random.choice(r2)\n if x1 + x2 == add_to and x1 * x2 == multiply_to:\n print(f\"Solved: {x1} + {x2} = {add_to}, {x1} * {x2} = {multiply_to}\")\n break\nelse:\n print(\"Couldn't find a solution\")\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-15T19:59:25.683", "Id": "475604", "Score": "0", "body": "Nice answer. I'd prefer `while True` over a flag. But otherwise agree +1." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-15T16:06:03.647", "Id": "242349", "ParentId": "242317", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-15T07:02:09.257", "Id": "242317", "Score": "1", "Tags": [ "python", "python-3.x" ], "Title": "Find 2 numbers that multiply to a number and add to another number" }
242317
<p>I haven't done C in a while. This looks like a simple problem to start. </p> <p><a href="https://leetcode.com/problems/add-strings/" rel="noreferrer">Leetcode problem 415</a></p> <blockquote> <p>Given two non-negative integers <code>num1</code> and <code>num2</code> represented as string, return the sum of <code>num1</code> and <code>num2</code>.<br> …<br> Note: [1. … 2. … 3. … ] 4. You <strong>must not</strong> <em>use any built-in BigInteger library</em> or <em>convert the inputs to integer</em> directly.</p> </blockquote> <p>It is working but I would like the comment on the style and being proper C code.</p> <pre><code>char * addStrings(char * num1, char * num2){ int len1 = strlen(num1); int len2 = strlen(num2); int result_len = len1 &gt; len2? len1: len2; result_len += 1; char *result = malloc(result_len+1); char *p1 = num1 + len1-1; char *p2 = num2 + len2-1; char *rp = result + result_len; *rp = '\0'; rp--; int carry = 0; char zero='0'; int digit; int d1; int d2; while (len1 || len2) { if (len1) { d1 = (*p1)-zero; p1--; len1--; } if (len2) { d2 = (*p2)-zero; p2--; len2--; } int tmp = d1 + d2 + carry; digit = tmp % 10; carry = tmp / 10; *rp = digit+zero; rp--; d1 = 0; d2 = 0; } if (carry) { *rp = carry+zero; } else { rp++; } return rp; } </code></pre>
[]
[ { "body": "<ul>\n<li><p>The caller cannot <code>free</code> the result: if the loop completes without carry, the pointer returned is not the pointer allocated. Memory leaks.</p></li>\n<li><p>Missing <code>#include &lt;stdlib.h&gt;</code> and <code>#include &lt;string.h&gt;</code>.</p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-15T17:59:04.847", "Id": "475597", "Score": "0", "body": "Yes. Need another copy for final result and free the current one. I will update it." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-15T16:05:05.787", "Id": "242348", "ParentId": "242320", "Score": "2" } }, { "body": "<h2>Always Initialize Variables</h2>\n\n<p>There is one possible bug in the code, the variables <code>d1</code> and <code>d2</code> assume that both <code>num1</code> and <code>num2</code> have values, this may not be true. The C programming language does not initialize variables by default like some other languages, especially local variables. All of the variables should be initialized before the loop.</p>\n\n<p>This also creates multiple paths through the code if either <code>num1</code> or <code>num2</code> do not have a value and error checking is added.</p>\n\n<pre><code>char * addStrings(char * num1, char * num2){\n int len1 = strlen(num1);\n int len2 = strlen(num2);\n\n if (!len1 &amp;&amp; !len2)\n {\n fprintf(stderr, \"Neither string has an integer value.\");\n return \"0\";\n }\n else\n {\n if (!len1)\n {\n return num2;\n }\n if (!len2)\n {\n return num1;\n }\n }\n\n ...\n\n return rp;\n}\n</code></pre>\n\n<h2>Complexity</h2>\n\n<p>With the added error check the function <code>addStrings()</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/Don%27t_repeat_yourself\" rel=\"nofollow 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>Probably the best thing to do here is to break <code>addStrings()</code> into 2 functions, one that does the error checking, and one that calculates the value of the string. The <code>addStrings()</code> function should do the error checking itself, and then call a function to calculate the value of the string.</p>\n\n<h2>Missing Headers</h2>\n\n<p>In addition to the missing header files noted by <code>vnp</code> an include of the header file <code>string.h</code> is necessary to allow <code>strlen()</code> to compile, at least on my computer with my C compiler (Windows 10, Visual Studio 2019).</p>\n\n<h2>DRY Code</h2>\n\n<p>There is a programming principle called the <a href=\"https://en.wikipedia.org/wiki/Don%27t_repeat_yourself\" rel=\"nofollow noreferrer\">Don't Repeat Yourself Principle</a> sometimes referred to as DRY code. If you find yourself repeating the same code multiple times it is better to encapsulate it in a function. If it is possible to loop through the code that can reduce repetition as well.</p>\n\n<p>This code is repetitive and the manipulation of the pointers and counters isn't necessary at this point.</p>\n\n<pre><code> if (len1) {\n d1 = (*p1)-zero;\n p1--;\n len1--;\n } \n if (len2) {\n d2 = (*p2)-zero;\n p2--;\n len2--;\n }\n</code></pre>\n\n<p>It might be better to just check if <code>pN</code> has a value and use what it points to if it does, change the pointers and the counters at the end of the loop. </p>\n\n<pre><code> if (p1) {\n d1 = (*p1) - zero;\n }\n\n if (p2) {\n d2 = (*p2) - zero;\n }\n</code></pre>\n\n<h2>Scope of Variables</h2>\n\n<p>The integer variables <code>digit</code>, <code>d1</code> and <code>d2</code> are never used outside the loop so they can be declared within the loop itself. Only declare the variables when they are needed.</p>\n\n<h2>In Summation</h2>\n\n<p>As noted by <code>vnp</code> there is a memory leak.</p>\n\n<p>An example of what how I would write the code:</p>\n\n<pre><code>#include &lt;stdio.h&gt;\n#include &lt;stdlib.h&gt;\n#include &lt;string.h&gt;\n\nstatic const unsigned char zero = '0';\n\nchar addCharacters(char *p1, char *p2, int *carry)\n{\n int digit = 0;\n int d1 = 0;\n int d2 = 0;\n\n if (p1) {\n d1 = (*p1) - zero;\n }\n\n if (p2) {\n d2 = (*p2) - zero;\n }\n\n int tmp = d1 + d2 + *carry;\n digit = tmp % 10;\n *carry = tmp / 10;\n\n return digit + zero;\n}\n\nchar* calculateStringValue(char *result, char num1[], int len1, char num2[], int len2, int result_len)\n{\n char *rp = result + result_len;\n *rp = '\\0';\n rp--;\n\n int carry = 0;\n char *p1 = num1 + len1-1;\n char *p2 = num2 + len2-1;\n\n while (len1 || len2)\n {\n *rp = addCharacters(p1, p2, &amp;carry);\n --len1;\n --len2;\n p1 = (len1 &gt; 0) ? --p1 : NULL;\n p2 = (len2 &gt; 0) ? --p2 : NULL;\n --rp;\n }\n\n if (carry) {\n *rp = carry + zero;\n } else {\n rp++;\n }\n\n return rp;\n}\n\nchar * addStrings(char * num1, char * num2){\n int len1 = strlen(num1);\n int len2 = strlen(num2);\n\n if (!len1 &amp;&amp; !len2)\n {\n fprintf(stderr, \"Neither string has an integer value.\");\n return \"0\";\n }\n else\n {\n if (!len1)\n {\n return num2;\n }\n if (!len2)\n {\n return num1;\n }\n }\n\n int result_len = len1 &gt; len2? len1: len2;\n result_len += 1; // allow for carry.\n\n char *result = malloc(result_len + 1);\n if (result == NULL)\n {\n fprintf(stderr, \"malloc failed in addStrings\\n\");\n return NULL;\n }\n\n return calculateStringValue(result, num1, len1, num2, len2, result_len);\n}\n\nint main() {\n char num1[] = \"2048\";\n char num2[] = \"9999\";\n printf(\"AddStrings returns %s\\n\", addStrings(num1, num2));\n return 0;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-15T19:51:00.327", "Id": "475603", "Score": "1", "body": "This is great. Thanks a lot ! I will try to write something close to your example on my own. In my haste, the original code was straight from my Leetcode's online answer area. So there is no main or library. I will post full code with main and headers in the future." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-15T20:14:51.810", "Id": "475606", "Score": "0", "body": "You can also see here why you would want to store numbers in little-endian order: it avoids having to read backwards. Also if either `num1` or `num2` is allowed to be `\"\"`, and be treated as `\"0\"`, then why not allow both `num1` and `num2` to be `\"\"` and cause the result to be `\"0\"`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-15T20:24:20.830", "Id": "475609", "Score": "0", "body": "@G.Sliepen I could, but it isn't specified in the question." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-15T19:06:50.700", "Id": "242362", "ParentId": "242320", "Score": "4" } }, { "body": "<p><strong>Very long strings</strong></p>\n\n<p>String length is not limited to <code>INT_MAX</code>. Better to use <code>size_t</code></p>\n\n<pre><code>// int len1 = strlen(num1);\nsize_t len1 = strlen(num1);\n</code></pre>\n\n<p><strong><code>const</code></strong></p>\n\n<p>As code does not alter data pointed to by <code>num1, num2</code>, use <code>const</code>. This allows code to be called with <code>const</code> strings, add info for a user to know the strings are not changed and provides easier to find compiler optimizations.</p>\n\n<pre><code>// addStrings(char * num1, char * num2){\naddStrings(const char * num1, const char * num2){\n</code></pre>\n\n<p><strong>Error check</strong></p>\n\n<p>As code is attempting to handle arbitrary long numbers, a failed allocation is even more likely. Add a check.</p>\n\n<pre><code>char *result = malloc(result_len+1);\nif (result == NULL) {\n // maybe a message on stderr?\n return NULL;\n}\n</code></pre>\n\n<p>Pedantic code would also check for addition overflow.</p>\n\n<pre><code>size_t len1 = strlen(num1);\nsize_t len2 = strlen(num2);\nif (SIZE_MAX - len1 &lt;= len2) {\n return NULL;\n}\n</code></pre>\n\n<p><strong><code>zero</code> vs. <code>'0'</code></strong></p>\n\n<p>Code promotes sub-<code>int</code> operands to <code>int</code> before subtraction. Might as well use an <code>int zero</code>.</p>\n\n<p>Subtracting <code>'0'</code> is idiomatic. Recommend: </p>\n\n<pre><code>//char zero='0';\n// d1 = (*p1)-zero;\n d1 = *p - '0';\n</code></pre>\n\n<p><strong>Code should return the allocated pointer</strong></p>\n\n<p><strong>UB with empty string</strong></p>\n\n<p>Corner concern:</p>\n\n<pre><code>char *p1 = num1 + len1-1;\n// same as \nchar *p1 = num1 - 1; //UB\n</code></pre>\n\n<p><strong>Sample</strong></p>\n\n<p>Note: <em>untested</em></p>\n\n<pre><code>char* addStrings(const char *num1, const char *num2) {\n size_t len1 = strlen(num1);\n size_t len2 = strlen(num2);\n if (len1 &gt;= SIZE_MAX - 1 - len2) {\n return NULL;\n }\n size_t len_max = len1 &gt; len2 ? len1 : len2;\n size_t len_min = len1 &lt; len2 ? len1 : len2;\n\n char *result = malloc(len_max + 2); // +1 for carry, +1 for \\0\n if (result == NULL) {\n return NULL;\n }\n\n char rp = result + len_max + 1;\n *rp = '\\0';\n char *p1 = num1 + len1;\n char *p2 = num2 + len2;\n\n int acc = 0;\n len1 -= len_min;\n len2 -= len_min;\n while (len_min-- &gt; 0) {\n acc += *--p1 - '0' + *--p2 - '0';\n *--rp = acc % 10 + '0';\n acc /= 10;\n }\n while (len1-- &gt; 0) {\n acc += *--p1 - '0';\n *--rp = acc % 10 + '0';\n acc /= 10;\n }\n while (len2-- &gt; 0) {\n acc += *--p2 - '0';\n *--rp = acc % 10 + '0';\n acc /= 10;\n }\n if (acc) {\n *--rp = acc % 10 + '0';\n\n } else {\n memmove(rp - 1, rp, len_max + 1);\n rp--;\n }\n return rp;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-19T18:54:44.413", "Id": "476031", "Score": "0", "body": "Thanks. It looks like I have been writing code with wreckless abandon." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-19T19:04:06.870", "Id": "476033", "Score": "0", "body": "@wispymisty We all LSNED." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-19T18:30:18.430", "Id": "242585", "ParentId": "242320", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-15T08:08:19.150", "Id": "242320", "Score": "5", "Tags": [ "c", "programming-challenge", "strings", "pointers" ], "Title": "Add two digit strings and return the result as string" }
242320
<p>I have a task wrapper which stores tasks, their <code>CancellationToken</code>s and of course their names (<code>botName</code>). <code>botName</code> is important, because when I want to stop a bot/cancel task, I will have to find it in the collection.</p> <p>I wonder if there is a better collection to do that, because it looks ugly, especially the CancellationToken cancellation logic.</p> <pre><code>public class BotWrapper { private readonly static ConcurrentDictionary&lt;string, Tuple&lt;Task, CancellationTokenSource&gt;&gt; _bots = new ConcurrentDictionary&lt;string, Tuple&lt;Task, CancellationTokenSource&gt;&gt;(); public void Start(string botName, string symbol, KlineInterval interval, StrategyBase strategy) { CancellationTokenSource cts = new CancellationTokenSource(); Task task = Task.Run(() =&gt; strategy.Start(symbol, interval, cts.Token), cts.Token); _bots.TryAdd(botName, new Tuple&lt;Task, CancellationTokenSource&gt;(task, cts)); } public void Stop(string botName) { foreach (var bot in _bots) { if (bot.Key.Contains(botName)) { CancellationTokenSource cts = bot.Value.Item2; cts.Cancel(); Thread.Sleep(2500); cts.Dispose(); // unmanaged _bots.TryRemove(botName, out _); } } } } </code></pre> <p>By the way StrategyBase.Start is nothing specific:</p> <pre><code>public virtual void Start(string symbol, KlineInterval interval, CancellationToken token) { ... logic ... and at some point if (token.IsCancellationRequested) { try { token.ThrowIfCancellationRequested(); } catch (OperationCanceledException) { SocketClient.UnsubscribeAll(); Console.WriteLine("Task canceled."); } } } <span class="math-container">```</span> </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-15T09:21:26.587", "Id": "475543", "Score": "0", "body": "Have you considered to use `TaskCompletionSource` along with `CancellationTokenSource`?" } ]
[ { "body": "<h2>Duplicate logic</h2>\n\n<pre><code>if (token.IsCancellationRequested)\n{\n try\n {\n token.ThrowIfCancellationRequested();\n }\n catch (OperationCanceledException)\n {\n SocketClient.UnsubscribeAll();\n Console.WriteLine(\"Task canceled.\");\n }\n}\n</code></pre>\n\n<p>This code is weird. You first check if a cancellation is requested, then you ask for an exception to be throw if a cancellation is requested (which you already know it is), and then you immediately catch that exception. It seems like you've conflated two ways of doing the same thing. You could instead use <em>either</em>:</p>\n\n<pre><code>try\n{\n token.ThrowIfCancellationRequested();\n}\ncatch (OperationCanceledException)\n{\n SocketClient.UnsubscribeAll();\n Console.WriteLine(\"Task canceled.\");\n}\n</code></pre>\n\n<p>OR</p>\n\n<pre><code>if (token.IsCancellationRequested)\n{\n SocketClient.UnsubscribeAll();\n Console.WriteLine(\"Task canceled.\");\n}\n</code></pre>\n\n<p>Which approach you use depends on whether it's meaningful to throw an exception, and it doesn't seem meaningful here (though you have actually omitted the surrounding code so I can't give you a guarantee). </p>\n\n<p>Throwing an exception is an expensive operation, and its main purpose is to bubble an exception up through multiple layers without requiring manual handling at every step. Since you're throwing and catching at the same layer, the cost of the expensive throw is not worth the benefit.</p>\n\n<p>Based on what I see, a simple <code>if</code> suffices here.</p>\n\n<hr>\n\n<h2>Tuples</h2>\n\n<p>I don't like tuples (in this particular scenario, at least). They're a honeytrap. </p>\n\n<p>At first sight, they look really easy by allowing you to skip creating a custom class, but then you are stuck using unreadable <code>Item1</code>, <code>Item2</code>, ... properties which have no meaning. In any reasonably sized codebase, I'd have to look up which item is stored in which slot several times during the development cycle.</p>\n\n<p>I suggest replacing this with a custom class just so you can keep the property names relevant:</p>\n\n<pre><code>public class BotTask\n{\n public Task Task { get; private set; }\n public CancellationTokenSource CancellationTokenSource { get; private set; }\n\n public BotTask (Task task, CancellationTokenSource cancellationTokenSource)\n {\n this.Task = task;\n this.CancellationTokenSource = cancellationTokenSource;\n }\n}\n</code></pre>\n\n<p>It's a few lines extra, but it significantly improves readability in the code that uses these objects, e.g.:</p>\n\n<pre><code>// Previously\n\nCancellationTokenSource cts = bot.Value.Item2;\ncts.Cancel();\n\n// Now\n\nbot.Value.CancellationTokenSource.Cancel();\n</code></pre>\n\n<p>The increased readability and somewhat shortened line count in the usage generally outweighs the effort of writing a simple DTO class.</p>\n\n<hr>\n\n<h2>Contains</h2>\n\n<p>It seems to me that you're conflating the <code>Dictionary.ContainsKey</code> and <code>String.Contains</code> methods:</p>\n\n<pre><code>public void Stop(string botName)\n{\n foreach (var bot in _bots)\n {\n if (bot.Key.Contains(botName))\n {\n // ...\n }\n }\n}\n</code></pre>\n\n<p>If you have a list of botTasks with names <code>Alice, Bob, Cindy</code> and you ask to stop the both with name <code>ind</code>, then you should come up dry since no bot with that exact name exists. However, in your current logic, that is not the case, since <code>\"Cindy\".Contains(\"ind\")</code> returns <code>true</code>!</p>\n\n<p>What you presumably want is to check if the dictionary contains the key <code>\"ind\"</code> (exactly), instead of whether the dictionary contains any key which contains <code>\"ind\"</code> in part of the key. That can be achieved like so:</p>\n\n<pre><code>public void Stop(string botName)\n{\n if(_bots.ContainsKey(botName))\n {\n var bot = _bots[botName];\n\n // ...\n }\n}\n</code></pre>\n\n<p>Or alternatively:</p>\n\n<pre><code>public void Stop(string botName)\n{\n if(_bots.TryGetValue(botName, out bot))\n {\n // ...\n }\n}\n</code></pre>\n\n<hr>\n\n<h2>Thread.Sleep</h2>\n\n<pre><code>Thread.Sleep(2500);\n</code></pre>\n\n<p>Since you're using async in your code, it seems counterproductive to then use <code>Thread.Sleep</code> instead of the asynchronous ´Task.Delay´, i.e.:</p>\n\n<pre><code>await Task.Delay(2500);\n</code></pre>\n\n<p>This is a tiny aside, because I'll omit this delay in the next section, but it's still important to point out in case a delay was actually needed here.</p>\n\n<hr>\n\n<h2>Manual disposing</h2>\n\n<p>I think you can skip the \"sleep and dispose\" logic here.</p>\n\n<p>It's good to see that you are managing your resources responsibly, but in this particular case the management is causing an undesirable blocking of the thread for 2.5 seconds. That's not good. Even if you use an <code>await Task.Delay</code> instead, I'm still not convinced that it's necessary to manually handle this.</p>\n\n<p>When nothing references the cancellation token source anymore, the garbage collector will eventually pick this up and dispose of the object itself. There are cases where you don't have the luxury of waiting on the garbage collector to kick into action, but in such cases blocking the thread for 2.5 seconds would still be a bigger evil.</p>\n\n<p>You can simplify the logic:</p>\n\n<pre><code>public void Stop(string botName)\n{\n if(_bots.ContainsKey(botName))\n {\n var bot = _bots[botName];\n\n bot.Value.CancellationTokenSource.Cancel();\n\n _bots.TryRemove(botName, out _);\n }\n}\n</code></pre>\n\n<p>Instead of waiting for the task to cancel itself, your code instead entrusts that the task will eventually end itself, and your code only focuses on getting its own affairs in order, i.e. removing the task from your dictionary.</p>\n\n<hr>\n\n<h2>Static ConcurrentDictionary</h2>\n\n<p><em>This is more of an educated guess than a guarantee.</em></p>\n\n<p>Your static <code>ConcurrentDictionary</code> comes across as a red flag to me, where you're misusing statics.</p>\n\n<p>It seems to me like you're intending to spawn multiple <code>BotWrapper</code> instances which you expect to share the same static botlist, but that's a flawed approach. It would be better if you instead pass the same <code>BotWrapper</code> instance around in your codebase (whether through DI containers or manually, I don't know how your architecture is set up), and then keep the botlist as a non-static property of that instance.</p>\n\n<p>The benefits of managing a single instance are a minor memory improvement (since you don't need multiple instances anymore), and it allows you to scale out your codebase in case you ever need to manage two different lists of bottasks. Using statics, it's impossible to have more than one. While it may not be necessary right now to maintain different lists, <em>never say never</em>, and it's good practice to allow for maximum reusability down the line.</p>\n\n<p>However, you didn't actually provide enough code for me to make a final decision on this. This is just an educated guess based on the code as it is presented.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-15T10:41:00.180", "Id": "475554", "Score": "0", "body": "First of all, thank you, I didn't even think that I could get a such incredible answer! Nice example for the exceptions. It's indeed unnecessary to throw an exception and then catch it in same layer. You were right about `CancellationToken`'s disposal (https://stackoverflow.com/questions/6960520/when-to-dispose-cancellationtokensource @Bryan Crosby). I thought it was unmanaged, but it seems people actually checked it with dnSpy/ILSpy." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-15T10:52:31.130", "Id": "475556", "Score": "0", "body": "Continuing the comment, because it was too long. I will actually have only one instance of `BotWrapper`. I didn't misuse `static` at first point, because I had other thoughts (because I remember how Hangfire was)." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-15T09:24:34.620", "Id": "242326", "ParentId": "242321", "Score": "5" } } ]
{ "AcceptedAnswerId": "242326", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-15T08:26:46.190", "Id": "242321", "Score": "0", "Tags": [ "c#", "multithreading" ], "Title": "A collection of tasks and their CancellationTokens" }
242321
<p>Ive written this code over the course of the last days and it seems to work. However I'm not an experienced Coder so I don't know if my code is efficient enough. Any advice for improvements or nez approaches to this challenge would be very welcome.</p> <pre><code>def lex(task): def isOperator(c): return c in "+-*/^" # Push “(“onto Stack postfix, stack = [], ["("] # add “)” to the end of task task = task.replace(" ","") + ")" # Position in task pos = 0 # operators with precedence operator = {"+": 1, "-": 1, "*": 2, "/": 2,"^": 3, "(": 0, ")": 0} # Using variables to avoid IndexError lastTok = "" nextTok = "" while pos &lt; len(task): lastTok = task[pos - 1] if pos else "" current = task[pos] nextTok = task[pos + 1] if pos &lt; len(task) - 1 else "" if current.isnumeric() or isOperator(current) and not lastTok.isnumeric() and nextTok.isnumeric(): for c in task[pos + 1:]: if c.isnumeric() or c == ".": current += c pos += 1 else: break # Add operands to Postfix expression postfix.append(current) # If left paranthesis, push to stack elif current == "(": stack.append(current) elif isOperator(current): # Pop from stack top each operator with same or higher precedence while operator[stack[-1]] &gt;= operator[current]: postfix.append(stack.pop()) # Avoid out of index error if not stack: break # Add current to stack stack.append(current) elif current == ")": # Pop from stack to postfix until left paranthesis is stack top while stack[-1] != "(": postfix.append(stack.pop()) # Remove the left paranthesis del stack[-1] else: raise ValueError(f"Illegal character at position {pos}") pos += 1 return postfix def evaluate(task): # Position in task pos = 0 # if the task has one element its over while len(task) &gt; 1: current = task[pos] if current in "+-*/^": # Get numbers left from operator; merge together num1 = float(task[pos - 2]) num2 = float(task[pos - 1]) if current == "+": task[pos - 2:pos + 1] = [num1 + num2] elif current == "-": task[pos - 2:pos + 1] = [num1 - num2] elif current == "*": task[pos - 2:pos + 1] = [num1 * num2] elif current == "/": task[pos - 2:pos + 1] = [num1 / num2] elif current == "^": task[pos - 2:pos + 1] = [num1 ** num2] # List size changed, position needs to be adjusted pos -= 1 else: # If we encounter operands we move on pos += 1 return float(task[0]) def calc(task): postfix = lex(task) return evaluate(postfix) def lex(task): def isOperator(c): return c in "+-*/^" # Push “(“onto Stack postfix, stack = [], ["("] # add “)” to the end of task task = task.replace(" ","") + ")" # Position in task pos = 0 # operators with precedence operator = {"+": 1, "-": 1, "*": 2, "/": 2,"^": 3, "(": 0, ")": 0} # Using variables to avoid IndexError lastTok = "" nextTok = "" while pos &lt; len(task): lastTok = task[pos - 1] if pos else "" current = task[pos] nextTok = task[pos + 1] if pos &lt; len(task) - 1 else "" if current.isnumeric() or isOperator(current) and not lastTok.isnumeric() and nextTok.isnumeric(): for c in task[pos + 1:]: if c.isnumeric() or c == ".": current += c pos += 1 else: break # Add operands to Postfix expression postfix.append(current) # If left paranthesis, push to stack elif current == "(": stack.append(current) elif isOperator(current): # Pop from stack top each operator with same or higher precedence while operator[stack[-1]] &gt;= operator[current]: postfix.append(stack.pop()) # Avoid out of index error if not stack: break # Add current to stack stack.append(current) elif current == ")": # Pop from stack to postfix until left paranthesis is stack top while stack[-1] != "(": postfix.append(stack.pop()) # Remove the left paranthesis del stack[-1] else: raise ValueError(f"Illegal character at position {pos}") pos += 1 return postfix def evaluate(task): # Position in task pos = 0 # if the task has one element its over while len(task) &gt; 1: current = task[pos] if current in "+-*/^": # Get numbers left from operator; merge together num1 = float(task[pos - 2]) num2 = float(task[pos - 1]) if current == "+": task[pos - 2:pos + 1] = [num1 + num2] elif current == "-": task[pos - 2:pos + 1] = [num1 - num2] elif current == "*": task[pos - 2:pos + 1] = [num1 * num2] elif current == "/": task[pos - 2:pos + 1] = [num1 / num2] elif current == "^": task[pos - 2:pos + 1] = [num1 ** num2] # List size changed, position needs to be adjusted pos -= 1 else: # If we encounter operands we move on pos += 1 return float(task[0]) def calc(task): postfix = lex(task) return evaluate(postfix) </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-15T08:42:17.420", "Id": "242322", "Score": "1", "Tags": [ "python", "math-expression-eval" ], "Title": "A math parser written in Python and using infix to postfix conversion" }
242322
<p>This is my naive approach on implementing a Sudoku solver, which is okay for simple Sudokus like this:</p> <pre><code>puzzle = [[5,3,0,0,7,0,0,0,0], [6,0,0,1,9,5,0,0,0], [0,9,8,0,0,0,0,6,0], [8,0,0,0,6,0,0,0,3], [4,0,0,8,0,3,0,0,1], [7,0,0,0,2,0,0,0,6], [0,6,0,0,0,0,2,8,0], [0,0,0,4,1,9,0,0,5], [0,0,0,0,8,0,0,7,9]] </code></pre> <p>However, it is rather slow for hard Sudokus like this:</p> <pre><code>[[9, 0, 0, 0, 8, 0, 0, 0, 1], [0, 0, 0, 4, 0, 6, 0, 0, 0], [0, 0, 5, 0, 7, 0, 3, 0, 0], [0, 6, 0, 0, 0, 0, 0, 4, 0], [4, 0, 1, 0, 6, 0, 5, 0, 8], [0, 9, 0, 0, 0, 0, 0, 2, 0], [0, 0, 7, 0, 3, 0, 2, 0, 0], [0, 0, 0, 7, 0, 5, 0, 0, 0], [1, 0, 0, 0, 4, 0, 0, 0, 7]] </code></pre> <p>The challenge description is:</p> <blockquote> <p>Write a function that will solve a 9x9 Sudoku puzzle. The function will take one argument consisting of the 2D puzzle array, with the value 0 representing an unknown square.</p> <p>The Sudokus tested against your function will be "insane" and can have multiple solutions. The solution only needs to give one valid solution in the case of the multiple solution sodoku.</p> <p>It might require some sort of brute force.</p> <p><strong>Tests:</strong> 100 random tests and 5 assertions per test</p> <p><strong>Time limit:</strong> 12sec</p> </blockquote> <p>My code:</p> <pre><code>def sudoku(board): (x, y) = find_empty_cell(board) if (x, y) == (-1, -1): return True for i in {1,2,3,4,5,6,7,8,9}: if valid(x,y,i,board): board[x][y] = i if sudoku(board): return board board[x][y] = 0 def valid(x,y,n,board): #check row and column for i in range(9): if board[x][i] == n or board[i][y] == n: return False #check box new_x = x//3 * 3 new_y = y//3 * 3 for i in range(3): for j in range(3): if board[new_x + i][new_y + j] == n: return False return True def find_empty_cell(board): for i in range(9): for j in range(9): if board[i][j] == 0: return (i,j) return (-1,-1) </code></pre> <p>I am trying to succeed in passing a coding challenge in a competitive platform, which my specific code times out.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-15T10:32:02.783", "Id": "475552", "Score": "0", "body": "What is the time restriction?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-15T10:41:41.593", "Id": "475555", "Score": "0", "body": "Hey @ChrisTang it is 12 sec. I will edit my post and add the full description of it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-15T11:49:33.323", "Id": "475563", "Score": "1", "body": "Your code doesn't take into account problems with multiple candidates for a cell, and so it'll produce a wrong answer on Hard boards." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-15T13:47:50.260", "Id": "475577", "Score": "2", "body": "[codewars' Hard Sudoku Solver](https://www.codewars.com/kata/hard-sudoku-solver)?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-15T13:49:37.157", "Id": "475578", "Score": "0", "body": "@greybeard yeap that's the one :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-16T09:59:15.143", "Id": "475666", "Score": "0", "body": "https://www.youtube.com/watch?v=G_UYXzGuqvM" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-16T10:17:57.307", "Id": "475669", "Score": "0", "body": "@stackzebra that is inefficient :( (too slow)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-16T20:49:58.907", "Id": "475748", "Score": "0", "body": "This is much more an approach/algorithm issue than a code issue." } ]
[ { "body": "<p>I am going to provide a much more over-the-top strategies to deal with Sudoku rather than outright code snippets so you can try it out on your own.\n[Also I am avoiding code-refactor, so that you can focus on Algorithm first, and then we will talk about Code Design, and finally implementation]</p>\n\n<p>However, if you need more explicit help or I am not clear enough, leave a comment, and I would provide more details as needed.</p>\n\n<p>So, the first thing I noticed about your program is that you implement a simple way to select which cell to fill: Find the first empty one, and try filling that.</p>\n\n<p>There is a much more efficient way to do this: find the cell which has only one Value, and fill that first, this will lead you to fill in first few digits of board pretty quickly, and constrain your solution space.</p>\n\n<p>For this: Just iterate over every cell, and store it in dict what are possible values this cell can have. \nNaively: A Cell C can have only values which are not available in its row, its column and its box.\nThis will lead to something like this:</p>\n\n<pre><code>A1 -- {1, 3, 5}\nA2 - {1, 6}\nA3 - {6}\n</code></pre>\n\n<p>and so on...</p>\n\n<p>Now, fun fact! You found out that A3 has only one value, so you fill in that. What this means is that you can now remove 6 from A row and 3rd column as well the box, which will further give 1-value cells, and you can repeat this process till there are no 1-value cells are left.</p>\n\n<p>This will give tremendous speed improvements over your current solution.</p>\n\n<p>But we are not done yet!</p>\n\n<hr>\n\n<p>Moving forward, there are two ways to go:</p>\n\n<ul>\n<li><p>Improve our function which determines the values for cell. Remember, our naive function was that a cell has values which are not in row, cell and box. But in Sudoku, we apply other logics as well. For example if both A2 and A3 has value of {2, 4}, then we know that no other cell in A row can have value of 2 and 4, and we can remove it. There are several such strategies which can help you out.\nThis is how Humans solve Sudoku</p></li>\n<li><p>Next is Computer's way. Now, you already have a solution which is close to this, which is to have a backtracking mechanism. However, instead of selecting cell randomly, select a cell with least possible values to fill in the random value. For example if you have to choose between A2 which has 2 choices and A4 which has 3 possible choices, fill in A2 first.</p></li>\n</ul>\n\n<hr>\n\n<p>These will result in very fast Sudoku solvers :)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-15T13:50:21.733", "Id": "475580", "Score": "0", "body": "Hello, @kushj will try and work on implementing what you suggested. Thank you for your time and effort :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-16T10:15:51.603", "Id": "475668", "Score": "0", "body": "Okay so, your brilliant insight and some further research helped me make it through :) Completed the task!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-16T23:48:52.947", "Id": "475766", "Score": "1", "body": "IDK if it would help in Python, but in a compiled language without huge interpreter overhead you might use an array of integer bitmaps to implement the dictionary of sets. Removing members from the set is just bitwise AND with `~(1<<n)`, and you can remove multiple bits at once. You can also quickly detect a bitmap that has only a single bit set with [`v & (v - 1) == 0`](https://graphics.stanford.edu/~seander/bithacks.html#DetermineIfPowerOf2). This all works for *these* sets because the members are integers in the 1..9 range. Most of the bit manipulation can even be done with SIMD vectors" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-15T12:07:40.813", "Id": "242335", "ParentId": "242327", "Score": "18" } }, { "body": "<p>I did this once in javascript, think the fastest algorithm was:</p>\n\n<ul>\n<li>create your board</li>\n<li>visit each cell, if it is empty, iterate through all possible values</li>\n<li>if the board has an inconsistency, take the next value</li>\n<li>if all values are used up, it cannot be solved</li>\n<li>if the value is valid, go directly to the next cell</li>\n</ul>\n\n<p>basically a depth-search-first, creating the board that will be the solution. each inconsistency only goes back one step and tries the next possible value there, so you have very little overhead for checking one scenario.</p>\n\n<p>edit: okay, that is called backtracking according to wikipedia:</p>\n\n<p><a href=\"https://en.wikipedia.org/wiki/Sudoku_solving_algorithms\" rel=\"nofollow noreferrer\">https://en.wikipedia.org/wiki/Sudoku_solving_algorithms</a>&lt;</p>\n\n<p>what i think is faster than your solution:</p>\n\n<ul>\n<li><p>you don't iterate the whole board to find the next empty cell because you already know that the previous ones are filled.</p></li>\n<li><p>you can just check the \"adjecent cells\" (same row, same column, same box) to see if the entered value is in them. no need to check the whole board for correctness. maybe you should check it once in the beginning just to be sure the problem is not bonkers already.</p></li>\n</ul>\n\n<p>okay, think i am wrong again, you already know that the values are good because you used the \"adjecent cells\" to calculate the possible values.</p>\n\n<p>i think i wasn't even keeping the possible values as lookup table, could be too much overhead to maintain them. just read them directly fom the board. or try both and see what's faster. you want to learn coding, so trying out stuff and measuring your solutions is a very good technique.</p>\n\n<p>good luck / have fun!</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-15T22:18:29.857", "Id": "242367", "ParentId": "242327", "Score": "1" } }, { "body": "<p>This is a classic <a href=\"https://en.wikipedia.org/wiki/Constraint_satisfaction_problem\" rel=\"nofollow noreferrer\">constraint satisfaction problem</a>.</p>\n\n<p>There are a couple of general techniques you can use to greatly speed up the search for a solution:</p>\n\n<ul>\n<li><p><strong>constraint propagation</strong> --- using the constraints of the game to immediately rule out possible values a variable can take; and</p></li>\n<li><p><strong>variable ordering</strong> --- being clever about deciding which variable to attempt to assign next.</p></li>\n</ul>\n\n<p>In Sudoku, the variables are the cells, and the possible values are the digits, <code>1-9</code>.</p>\n\n<p>You may wish to use a more refined search-state representation. With your current representation, a cell is either filled in or isn't, but you might be better off keeping track of all the possible values the cell could have (initially, the set <code>{1, 2, ..., 9}</code>), which would allow you to incrementally rule out values.</p>\n\n<p>The improved algorithm would be a backtracking search, like the one you already have, but at each node of the search tree you apply constraint propagation to immediately rule out some of the options. If you reach a state in which all of the values of a variable have been ruled out, you know the sudoku is not solvable from that state, so you backtrack.</p>\n\n<p><strong>Constraint Propagation</strong></p>\n\n<p>An inference procedure looks at the present search state, and uses knowledge of the constraints to eliminate possible assignments. You can make full use of a procedure by repeatedly applying it until it produces no change.</p>\n\n<p>Here are a couple of inference procedures you might apply:</p>\n\n<ul>\n<li><p>When the value of a cell has been deduced, you can remove that value from all other cells in the same unit (row, column, or box).</p></li>\n<li><p>When two cells in a unit have been reduced to the exact same pair of possible values, you can rule those values out for all other cells in the same unit. This is known as the <a href=\"https://www.learn-sudoku.com/naked-pairs.html\" rel=\"nofollow noreferrer\">'naked pairs'</a> strategy.</p></li>\n</ul>\n\n<p>There are <a href=\"https://www.learn-sudoku.com/basic-techniques.html\" rel=\"nofollow noreferrer\">other strategies</a> you might want to try implementing, although you will get diminishing returns.</p>\n\n<p><strong>Variable Ordering</strong></p>\n\n<p>This one's simple: simply choose the most constrained variable first -- that is, the cell with the least options. Intuitively, this is likely to rule out bad assignments earlier, resulting in a larger portion of the search tree being pruned by backtracking.</p>\n\n<hr>\n\n<p>Leave a comment if there's anything I haven't explained clearly.</p>\n\n<p>You can find an excellent write-up on Sudoku solving <a href=\"http://norvig.com/sudoku.html\" rel=\"nofollow noreferrer\">here</a>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-16T19:10:08.563", "Id": "242420", "ParentId": "242327", "Score": "3" } }, { "body": "<ul>\n<li><p>For each positions (row, col), eliminate unnecessary values in row,<br />\ncol, block by using set difference. This will shorten your code.</p>\n<p>e.g.</p>\n<pre><code>{1,2,3,4,5,6,7,8,9}.difference(puzzle[row,:]) # for row \n\n{1,2,3,4,5,6,7,8,9}.difference(puzzle[:,col]) # for col \n\nr = row//3*3, c = col//3*3, \n{1,2,3,4,5,6,7,8,9}.difference(puzzle[r:r+3,c:c+3]) # for block 3x3 \n</code></pre>\n<p>For any (row, col), the only possible values will be<br />\nthe intersection set of the above three sets.</p>\n<p>Complete code at <a href=\"https://github.com/chanshukwong/sodoku\" rel=\"nofollow noreferrer\">https://github.com/chanshukwong/sodoku</a></p>\n</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-12T13:08:40.230", "Id": "257066", "ParentId": "242327", "Score": "1" } } ]
{ "AcceptedAnswerId": "242335", "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-15T09:34:16.563", "Id": "242327", "Score": "10", "Tags": [ "python", "python-3.x", "programming-challenge", "sudoku" ], "Title": "Simple Sudoku Solver in Python" }
242327
<p>I am trying to solve the Challenging Palindromes problem from HackerRank. The code that I have got so far fails only for large inputs due to timeout, every other test it passes successfully.</p> <p>The problem in a nutshell is that a function is to be written, which will take two string arguments, and return the largest palindrome possible from the substrings of the two.</p> <p>Code for my solution is at the bottom, but if you rather fancy to go through it on GitHub, then here are the links: </p> <p>Link to problem: <a href="https://www.hackerrank.com/challenges/challenging-palindromes/problem" rel="nofollow noreferrer">https://www.hackerrank.com/challenges/challenging-palindromes/problem</a><br> Link to solution: <a href="https://github.com/atulvani/hackerrank/blob/master/challenging-palindromes/challenging-palindromes.js" rel="nofollow noreferrer">https://github.com/atulvani/hackerrank/blob/master/challenging-palindromes/challenging-palindromes.js</a><br> Link to the test failing in the innermost while loop: <a href="https://github.com/atulvani/hackerrank/blob/master/challenging-palindromes/timeout-test1.js" rel="nofollow noreferrer">https://github.com/atulvani/hackerrank/blob/master/challenging-palindromes/timeout-test1.js</a><br> Link to the test failing because of getPalindromsInString function: <a href="https://github.com/atulvani/hackerrank/blob/master/challenging-palindromes/timeout-test2.js" rel="nofollow noreferrer">https://github.com/atulvani/hackerrank/blob/master/challenging-palindromes/timeout-test2.js</a></p> <p>The approach that I have taken to solve the problem is as follows:</p> <ol> <li>Build an object out of the second string such that it allows to compute which character in it is followed by what other character in constant time. Complexity: O(n)</li> <li>Then I make a list of palindromes in both the strings so that I can find in constant time if there exists a palindrome at a given index in any of the strings. It is O(n^3) in complexity but I figured it wouldn't be that scary for most inputs.</li> <li>Then I loop (outer while) through the first string, generate list of indexes to check in the second string using the object built in step #2. For every such index I loop again (for loop) and compare if the characters that follow in the first (inner while) are also followed in the second string. The inner most while loops ends when characters to match, the for loop does not break and checks all possibilities, and outer while loop does not break either until all the characters of the first string are processed. Complexity: O(n^3)</li> </ol> <p>There are two kinds of inputs that makes my program to not finish in time:</p> <ol> <li>When there are way too many palindromes in one of the two strings, and hence the step #2 takes up a lot of time.</li> <li>When way too many long sequences from the first string are present in the second as well, in which case the inner while loop ends up consuming too much time.</li> </ol> <p>I would like to know how I could have done better in the solution that I came up with. As well as, if there's any other efficient approach/algorithm/solution that I couldn't even imagine.</p> <p>I would be very grateful for any comment that can help me improve. Thanks.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>// https://www.hackerrank.com/challenges/challenging-palindromes/problem function makePalindrom (str, mid) { let result = str + mid; for (let i = str.length - 1; i &gt;= 0; i--) { result += str[i]; } return result; } function getLongestStr (arr) { return arr.reduce((acc, item) =&gt; { return item.length &gt; acc.length ? item : (item.length === acc.length ? [item, acc].sort()[0] : acc); }, ''); } function getPalindromsInString (str, shouldIndexFromEnd = false) { let result = {}; const calcResultIndex = (i, j, isEvenLengthedPalindrom) =&gt; { if (shouldIndexFromEnd) { return isEvenLengthedPalindrom ? i + j - 1 : i + j; } else { return i - j; } }; for (let i = 0; i &lt; str.length; i++) { let j = 0; while(str[i - 1 - j] &amp;&amp; str[i + j] &amp;&amp; str[i - 1 - j] === str[i + j]) { j++; const k = calcResultIndex(i, j, true); if (!result[k] || result[k].length &lt; j * 2) { result[k] = str.slice(i - j, i) + str.slice(i, i + j); } } j = 0; while (str[i - 1 - j] &amp;&amp; str[i + j + 1] &amp;&amp; str[i - 1 - j] === str[i + j + 1]) { j++; const k = calcResultIndex(i, j, false); if (!result[k] || result[k].length &lt; ((j * 2) + 1)) { result[k] = str.slice(i - j, i) + str.slice(i, i + j + 1); } } } return result; } function makeFancyDataStructureFromString (str) { const ds = {}; for (let i = str.length - 1; i &gt;= 0; i--) { const char = str[i], prevChar = str[i + 1]; ds[char] = ds[char] || { '@@': [] }; ds[char]['@@'].push(i); if (prevChar) { ds[prevChar][char] = ds[prevChar][char] || {}; ds[prevChar][char][i] = ds[char]; } } return { hasAt: ((c) =&gt; ds[c] ? ds[c]['@@'] : []), is_X_At_N_FollowedBy_Y_: ((x, n , y) =&gt; !!ds[x][y] &amp;&amp; !!ds[x][y][n]), get_X_FollowedBy_Y_: ((x, y) =&gt; Object.keys(ds[x][y] || {})), }; } function buildPalindrome(a, b) { const fancyDs = makeFancyDataStructureFromString(b), palindromsInFirstString = getPalindromsInString(a, false), palindromsInSecondString = getPalindromsInString(b, true); let i = 0, result = ''; while (i &lt; a.length) { const char = a[i], charInSecondStrAt = fancyDs.hasAt(char); if (charInSecondStrAt.length !== 0) { if (i + 1 &lt; a.length) { const nextChar = a[i + 1]; result = getLongestStr([result, char + (palindromsInFirstString[i + 1] || nextChar) + char, ...(charInSecondStrAt.filter(i =&gt; i).map(i =&gt; char + (palindromsInSecondString[i - 1] || b[i - 1]) + char))]); const leads = fancyDs.get_X_FollowedBy_Y_(char, nextChar); for (let lead of leads) { let j = 1, temp = char + nextChar; while (i + j + 1 &lt; a.length) { if (fancyDs.is_X_At_N_FollowedBy_Y_(a[i + j], lead - j, a[i + j + 1])) { temp += a[i + j + 1]; j++; } else { break; } } const palindromFromFirstStr = makePalindrom(temp, palindromsInFirstString[i + j + 1] || a[i + j + 1] || ''), palindromFromSecondStr = makePalindrom(temp, palindromsInSecondString[lead - j] || b[lead - j] || ''); let newResult; if (palindromFromFirstStr.length &gt; palindromFromSecondStr.length) { newResult = palindromFromFirstStr; } else if (palindromFromSecondStr.length &gt; palindromFromFirstStr.length) { newResult = palindromFromSecondStr; } else { newResult = [palindromFromFirstStr, palindromFromSecondStr].sort()[0]; } if (result.length &lt; newResult.length) { result = newResult; } else if (result.length === newResult.length) { result = [result, newResult].sort()[0]; } } } else if (result.length &lt;= 2 &amp;&amp; charInSecondStrAt.length === 1 &amp;&amp; charInSecondStrAt[0] === 0) { result = getLongestStr([result, char + char]); } else { result = getLongestStr([result, ...(charInSecondStrAt.filter(i =&gt; i).map(i =&gt; char + (palindromsInSecondString[i - 1] || b[i - 1]) + char))]); } } i++; } return result || -1; } // test for which innermost while in buildPalindrome function timesout buildPalindrome('zzkbdgivaqismrzwzrirolxivizyppqzkwkbylhaugjmzfjtwroeyxgilqjvavmbnvnacclngqubsmcvunjucgfioptgoyykapnmepjdgjvmqjsqirrbvyqnokggyhpovlwmzwhwrejjwscgfipkmjthrdqoxquosqabzfzuuzajsmtxculipprztefmsehhjecneedirscuiltmygqnmaitiafoozliiluuymtrvilsswawpfpprfwbutkzmazbjwiidpszbmisizdprofirunfzwtbvvmusunigwyjvdnvkxgymrxriikyyjcrwozzmuyhgjhmmlnahjkvivbuatrykwsojhbagwlsjzqtnbomrugnhvbdvyewvnvhalvxueykbxrtdqrlyrryrxmbcvzahwuqwnfqrmksakubleisxlzgvqewgbeuprelfafutwacildojcaermoqnpvwwmzrajlfccaxwgkbcbualdufxhssfcrjtymfzuwnscuvswdafeblkfiszvgfhjwxhwqzchslfakrxiuzvqvkygmeqvgogzbufsptxmutxpzoaqqcpkokpaohxmknazavgzjzedbbkjygkyuaqbgvhpxbqpkexbumyhuyaimdizwzpzyelpbtjzapmllpewksjlcacvfnvjxcpgpckincgmdsseftjnugstnwbhnehmktshazfpzniwoimeuykivspupjbanmisbscdomuhlhpvworeicuuveovnzalfiaueumcgjyvduxupocubrbrhxzxxgykbzxhluqxzqhfhsiyopvstrtwvagtfkvjmfrwnyvkrkfqfinlgonngmhxvwrsggklsdsocqvgjkbagkcozzlltvzhsjgpuriyyslknfobecisdsdzwvuxoezgalvbhdtfbwaljcsfyfhiujluqoiuvncktvrvhwbarnvtrzvqfnfjekakkilhvxshugseegumlgjzecegklweststdytqklpdkmklckcnjwrrirqztqxemigiujdlbluedrqqdvwjnjbimzrhzevojqinaddpjvfwjnvgoncaojywmivydvqvskmqjrhdyhudkinplvkobpzoibiwhktqbwtrcaytawpmvujieztjymxgjvkguowmksticgftenjdxasllnptqwpnvdceohqyjxirwqngcuepcbtlkemwiqtrlcplnamxurqolatjubcyirazwifkfddrqnjdqfasgmuklgxzinapkiuwpswoyfgawulxsnufnfblzupgqeukmkqbhmjfkjhbjdudjhabjsmykaqpeigeyhwpgmjptrfhgzjyyvoskxdpwoxauppygnxdgdabypltpxaxunalzmugkjfkpjtmfhioasefuhtiohleaqmgondmyknzfceffdwfupigehmrxpihpvqodehrfuxeegzolcrdlieoxzxdqdkiatiaiqrorpqnrxkfqnldmsioxakzjszxxafddbagurzirhtynujhkrlcbblihbtcnsbbbtyfrewckksloocajybwwabqskxjduwmvbbniloereysasfewlwklzycgfhgmvhlzftcifkzuuhqtmdudcqersskxftnnpbtchgglhagkszenocwdsyektpubnwjscwsuybrszfzjcbuenvldqaonsjtltgbecnsafmfofmgajlveqrpfiwckkajlrrdsxneebhfrzfokmlgwpmaomhcjnymnhschjdbrjrwclxyzhkhksnbnrxrwkbznifkahqokxyogdtvhwqbjgtxchajtojbvhqoybghfhluyollnataaaqxfoftzfhlxaxsvwfbyvcblqcxchgyswfazbkfgauoatzhademcxxfkotnyvlnqzrlfdfnhwolchkbykodlkbpzdogwvovywwjpuvoffqznqgqlacyzkajxvqymeskdxbgqoimczqrnuymzsdicncplrmmvwzwowbggmgjpjheadyhdizgkidyogqpvndpkwgoastlnacihxyxnifldmlctofefcxryebxkuqnvigwuurkonwkgpnwmngoufnqkwnybnlkkvnuhuxgromslliiucwkmrdexfffqwwyvujharstsbpqrdecurcffubhqybfpzybrgopzxrmmsmdvpjalhgsqmctsxqhyspxsohlmgqlnibswxtfovcubquiswtcusigxyaywapffcueyyglitjewtzreooepvlbpuhfbioobpfqhfdfxqaxzfuwrwwdpemrlblttcgxodygfkwbuoalmavaggcyyxlmeucdlefmuebdknpzqiwnxpoquvcskegxwheqolrsotcxgxhpwrwnceguouxqlsecgyljuyrwndjndcasfvncupjjfnmjxmpsftyxctxiyuklxpdcxivqntnujkdvjsatecenwkslsztqtammhxjedvnbxepgrqhoqzmsvjwgahebthhvgxmvdtliuetlfdezfjmfntjtshztjrenruasedvzkeojadyowfdnvtrafkpngjbmpdpwkknahfqnrbpdelisixsgmxzikhfsgdxkkyovwppbexlgcphxmhvkivbbvbfobwufozkqzmkmslazvrjkdazomfyptwbfzctmxyrqbybudwnwhhtmbpeiydmpwayynkjitwwqhzeujzqvfbtpmskwbzkeqybaydxgbhpikvbopsbgwayiflfnadnxnsljilohkhefhkwbrjxljhlgsqdhkkuxckgtstsdgpofogxurjycnsiyxozjutwpxxcckrdjpbxmubgwfiirhhutwebdlnlpsnofqyvvkorzkercpeojxtiscksyrmbsjbuaqboiyvbaqfibdaswkngafyoydijwkgqmucegfstwlxbcnjolzslcndfbyxwamsozlyromjttblaaejxameifmvpnxxpwndygvjykqmwvixtsqmzshdjuacywfmnftlfbjdjvjiiszhoqxfcvzstmkhbekfwagpgyqzchabparixzaavdwkjhhxbbfepupndjqaapxtqlsjzvfpiyldiibemlpkeqilwogsqwhillgkedxzlmvlwfzwyyzesvmbjlyuqvqoamjiklnfetdnilsotkwmyewzoygdtdcnfywmuernjrswhwgrlrkzsaszgxbtejktoawkdshhwmitrxgzfqkpieowqomliowzwsjotamapcewlbyujlmhahtccjjlekmayzhdvcumdxxvwrzbelmqqetnhcfbeqmnsvlkkrewxlxnmvowesoprhwmwhvlziepgfthtendmfndexunllrbixqsaoajpzmbudgnpcgkjwlbvyrvqcdkqcrnrmbrtvsnscbcksycviwbpxuatpsssbrhlnbkunhafrebotrsheuvzhhocikzmyfmaqydwdzsscmnygszmyrvmlgntqxcostlnarfwskvdhaacwjmhewzpjrpvgabkwhxghvmlkjycczheyysusdmitckskjdirzwpmhyamqovfeqmqflrvjzasejueljiyxcbwyzvvsjuauhbdqkbjamqorkwjrneismebucbwbzebnrezceczuzouphocsfdqcvcreifihzhfunwvtcrbvchmghezvczvbhowyujgitrvmmtxvmivalwnsiaygdqqteqeukkjhpbfyqeecirmlefniotroypykcurqizzsydgbxojzmkijijdovmjbujmbwjhsskskrvvtmpzqqtijuneezzijrfzklpjvosvryciducsapzugarfeyopwalsdnwmraicrhqgkpasgztwgogdyddekukjcqwmjjwxdcftbgbcbzxkibxnegssyhnpjukqirnllacjzgivmfhjrqiezzdpsyyobwmbqryaecdelwwntnhhswubpuzdyhwitrwvqqjzgimgtjvehazdydsdsyjgsseorjrltszbxqiganalyygouhyfgmnazwxccnrbkohxzpnavwklwsomlhvmzklbxarexjszmhkfnypyjopvftswrqujezhndbqlktpnkfpdtfjijqorysinzcyvvpseyptyuechdkyqkafnbuagpikzwfskousupmuewyxrjrthfnjvexfotuveqmunbbrnzlrcsqxzzlndhjvotvmsnkpcawiziyglidwnstybkyndelpmzlyesiavoszfqmvdrrayqkczuaurhdunxsordeepwmijpwilmzmpicszqsezmtfijmjgimhyhuqwvnpardzapcqvoncupiwbqqxymgalwdekkkdqakdsbpuxfhxnmjtzbmifhqgphoooasoeapjjmafqjtthtfslruzjlltkozkxsxuejgcxwijgechahznxdnxxpvbjlonggjexpvkbmduwvampwapsqizmnagsntnqgeagkxohcoyomtrhkwxbckugkdwtfmixqyfrsxfsosztvwilrcxgmdsvdqithpmyezzwenwdemyxpoanbcffbtwklnrutxgrofelqwjdyfchrzetzenmukkafqgrbnrjszmarzsbvyhiramwzwbzisjqvbxgixkzfzbzualsgkvsbmshfnyejbiwimlxvtpotriuildfvyevqbxxxawjsettemhmghnwsesgwpgtxjurczbznbzjmlffjfdplndgdabktpuxcvuiebcctdkrydxurhvupxbhtvgqhhcmxrdbbyebverbxxibiiubsyayszqrxchxadszzetociuygpksnbsilfxrnouhclgzorzcjorjcyeehhehofzytiykqiwbqcrxsoieirxjfwtcnmvrxifxmfyculypbftjuzbdbzsmkrbkjjjhejmonpkijzksehtsgadqjwwbltbndpzozsjvrpqnemvahdjebhjxszsmoufjgcszfvxtpghaocabzvsdxlchdbsuvjfoyeudkfpecwyvxlwfpsfuuqcegwpzefgoasktgmrdltqkfyngpwfhierzvcaspyixexddfpjfgazwjpiaosqklsluimvcisvxmnuuvvxemmymhpcnvbcqjthlfnxcmqqidgdseamjprsptadtxdugfdlydjxffcdifuiszuhrznbdhspuloljbwpbapswzfivxdtgmptsyrwnruacoxykcqmotwpeubbhzdhhlwmopczzhmatpzqcrygxdgeoweatvhifxzcyazttnbmwckherbpafexnejizeektnmdhvupuizszohosahdxomrgqfgcqumhhjwhyrmuoqtxuaenwrpcaavqesoqodnuuuzixlvtnxdeqkthphpcasevkkouobqzadcgllqwzhabfmyvlpvltypgqqianiajtjusqdkkcwvifisaaymieumpzgkfiehjmujyrdtqdiyiuldwswqjgpinlyfcfyrktmbvlfonkkfczdsglwkrdqvaurmnbcnrzivffluqduosdcmewkwogmubysbmhbaazkbhyzhiwxiiwmpwvasnefevjhwleunabsjvikshwybwtjsrkjrzmtzvcwpcndvrheijqlqcpsjmrxsywhkkdergjoaphniisoandcsvcijcfbeaptmeztqpcdkguhjwsmhloxmpgjpeceysnucphrmpfnrvjnlkflxdycjymufxfixxkcfpgrczogtguluwftavuvanxghgnzomyrighjhafqxgfkotwuffgizapokdcpzmvzlivfctmuznchicihjvvqrfbelvdqxivjuvulzpqzruaqouksadaitjrblkvewovqehzlporgifghesapiztwnoppexaozpvatvptrqliqdnpufupjtgggyjegmqejhnhwczauylvliwxsealqkadlmcfvwobdplefcuwsebfwkyxiywdnwlwbbsnubmiotrncazkjjpvnossmejxuaaccfyqslhxqceqwqvzlunjkmmrupjqkbqfgqbcccmdiqyhjwwxftnbyvnwpkotzbhdtzqicerxogfazjjfnlhadvedlkgsfzwjsqskevrrnwfwszvexapojsklgkjbiudarbdsilhlaznqabiyejohhuqxjapppyisuhypbowexqnrgrppldstzsmrpldiyrpvgctaxgpppaoylzccexfwnwfwshzuxdckalspmfjcdglpsbpwogridvoftxxgjkykvmwqtpjxqnswizepirqoxtosrtptkulexgxesurfkerwsnjzjztgmkivngrpsxekffovjxihyjjfrdzdasiuxcgrlhcsijmqqugtoazifxalyekcjlnxkqnzkfuihkwjsmnzscguzwsdxwritiyvdcunbnjiotfkwqtknwszbpltuinwyohoudkeaglxbelvtpjyvatmamzhoghxndxdloonobcbjerykojnlfzkuyuzfsknhyglvpdyotzeijcxdqfefirykzhpvragspiqfwmdbxitdwnegsphyzcsbsodlnutppngbnvtzuxbitxlszffgsystbtylndftclsjarpczauvmovlffudrxkzxwetaaofhfphnxpruhqzfdhxvpylohdovfniosdzfbjrufwpjlpmgxjohgaynlozytsmfbpabvsmnueblmywevrliwpveieklwbvboctirbeepvoiiqtpcffqvnpssenhgamqoyufrshqlbcnbdgtqxjkouwedgwvlnlegqilxnumvqstpxfkkvbadtpwfqowbomvxtqhyddowqhwgnovzoojiurllebjdvwmafscgritlrnryzgwwthfvkhcwrhqrcbuhjviprgiqjlqaznpggvvwzzlaedglinffomspntneceaahpyyxycvdrzzoihjoimpwxsmbpfmjkiwbdbprazcxxkkhhsvtlgerjdraryekkntbnxzdtrvimshdnjioxvpgxvqpfmbijuzpzmjwlzlabnleatpwtkusdpnovxrwxjcfermiailxdxpqqgwpphsheyidefvkvegxcxslcweessznkviakiwlvppriojqkenfdiyaaxcnveomawslzsnhrcojjsvrurtrftrqckmgzzltqmemwnqmczcvmfoqchiwxbsjipssqhpjqqrszucmtdjlnjqvrhjmugsbnksqkuhdhbaroxxmbbhpocexsvubtmifwskmbminwchmjewdwwkmrwsppsxemjnaubwqtjhicwcbhfstbrwtqrilrcykgvvjkqcsbfqitknygmlnhckqgmvfrjbjmlhyiwdrfnukoweopwqvabwhcjxypkflgwodmidimnunqvouujnjdrylcphnelguqwzdllgngmcwttpidaaxvhuzaxpoyaqpkgdjgypdznhkclryjdipgmhdqzmoggtlglurkujqyglhsnoliyytzonrwoxgcizyxjrjqomydiidpefluaqklgxrnlkkaafqefdxuztwasdkguexfxkjlnmqyouaogpytjdnfkoelexxaapxccsxjksfqlkhvrmhikshlmftesgqxgatdkrwcltyichwmvznfugopevxamskgvvawdmyteyzbnqvyabwkwqdspoiwqvwqehleshjymroeqekbpacoqdmmtefgqkstqxsruawhacgbrgsjibypiohhjlpayosyaxtxfzmvntqhmsozgejfkawztzeavlduxwnldpecqmkjtvjztypfmrvaecugejmamcunvlooilfljkhhmeymkcaiysappwppswdjinmbixpnltctjsnbssyxkmsmfzvtoaukqpqriqwvlhbxlriavssflopodxycqvzsnkowsmnwoilrdmdktpgsskzbluzbrgdjrumqjfiwsihrariazdqykualuwdftnatlojvpdifxfrvxexyvfjhqhhgueybzilnovcoltvykfjvliomdvizvzqlpsroluzdcfjpdftjnnrtzezmungtwccvljmucvgxmjoyonhqtzylocbeitpzqqahwgddczemkbockfsriqajhvffohrnivazapnibsnculskuxenanpfpvolrmryfcudbzxgasgxkpvcxxdlbrbnvxhvjoallkmlfrwobxocktpjgycljbnkbrhxmmyyrnzpqcmdwwdragqmmwxysxvsugwfcjdulgkyejzbqtnmugtocvznhegxaveuzcwiahxdntwxunqoaaxkvlovvqykevptuyfnthykzbfgireqacgcuyyucbzqufxelbdjugwpyvjyzpihuxuvfmjtlixzvxjkhbdsnjpydlrfuiyquwphewmrut', 'uriarvrcnimdeplhtadpjgtxfosuwsqokbiphrlpylyvdmxtztyyriojrqwjkruuykqqhgqzsfksrhygijlxudccyiwtevoemhzpqjuoesplqloeuspngsiawvqgxjtplhvfcwkpjdvmfyisjqitoymrianbfjnyeowkpguugtbvqxgbfhijihtydhfwdudoeipvindapvptmmjdezydeytslmodfcfwgdcpuakseezocainjidtsypwhgxmcvtjdljsjvppseuuazbuouzrpxyqdpkhhtinyadechyaqyrytbcyozaxlsaksyqtwsrosontrkpdqwwqafcchrqrvtddoapxhptpogvzlmmtgodrzcerkrymvjyvwnnwgyyujebhywnnnwtzyyqtbtfzwysufdrmkuihkaabzmzhmmyaxbpnrjbxcunwizljeufyfrabgtdmwpuygrkoruekzxcocxobrgzetajwhtjazncdxfvmiklchqyxenblolekgduywwpsucaawiachpdtshhynfjcbalxzrcclhnrruttlyqtbhobsxxzmrbxmimnsyrwqynhjpofmdyijmuhrjzpsnwutmebaxnujqtgmaxkqvqzquvirckrsaynvtsunizvitomnrwcfxvlbryjmwyfzmzsukqsbsqklujdhkdamsibagqmvgmogffidhpofuycsewdvhhirydzwxdhnpnpwhcbklrxkipqstjlssxspngqfkzsqynxnesbonwxzqdffgtnxbtguqenqflqvuicwfnfpmkfbqxmoqtjzxzvehwgrejopmneyeypztvgbairrmcctcylvzaujoznwihzajjbqglcmpswrbuhweyclcyewhubrwspmclgqbjjazhiwnzojuazvlyctccmrriabgvtzpyeyenmpojergwhevzxzjtqomxqbfkmpfnfwciuvqlfqnequgtbxntgffdqzxwnobsenxnyqszkfqgnpsxssljtsqpikxrlkbchwpnpnhdxwzdyrihhvdwescyufophdiffgomgvmqgabismadkhdjulkqsbsqkuszmzfywmjyrblvxfcwrnmotivzinustvnyasrkcrivuqzqvqkxamgtqjunxabemtuwnspzjrhumjiydmfopjhnyqwrysnmimxbrmzxxsbohbtqyltturrnhlccrzxlabcjfnyhhstdphcaiwaacuspwwyudgkelolbnexyqhclkimvfxdcnzajthwjatezgrboxcocxzkeurokrgyupwmdtgbarfyfuejlziwnucxbjrnpbxaymmhzmzbaakhiukmrdfusywzftbtqyyztwnnnwyhbejuyygwnnwvyjvmyrkreczrdogtmmlzvgoptphxpaoddtvrqrhccfaqwwqdpkrtnosorswtqyskaslxazoycbtyryqayhcedaynithhkpdqyxprzuoubzauuesppvjsjldjtvcmxghwpystdijniacozeeskaupcdgwfcfdomlstyedyzedjmmtpvpadnivpieodudwfhdythijihfbgxqvbtguugpkwoeynjfbnairmyotiqjsiyfmvdjpkwcfvhlptjxgqvwaisgnpsueolqlpseoujqpzhmeovetwiyccduxljigyhrskfszqghqqkyuurkjwqrkxaaoqnuxwtndxhaiwczuevaxgehnzvcotgumntqbzjeykgludjcfwgusvxsyxwmmqgardwwdmcqpznryymmxhrbknbjlcygjptkcoxbowrflmkllaojvhxvnbrbldxxcvpkxgsagxzbducfyrmrlovpfpnanexukslucnsbinpazavinrhoffvhjaqirsfkcobkmezcddgwhaqqzptiebcolyztqhnoyojmxgvcumjlvccwtgnumzeztrnnjtfdpjfcdzulorsplqzvzivdmoilvjfkyvtlocvonlizbyeughhqhjfvyxexvrfxfidpvjoltantfdwulaukyqdzairarhiswifjqmurjdgrbzulbzkssgptkdmdrliownmswoknszvqcyxdopolfssvairlxbhlvwqirqpqkuaotvzfmsmkxyssbnsjtctlnpxibmnijdwsppwppasyiackmyemhhkjlflioolvnucmamjeguceavrmfpytzjvtjkmqcepdlnwxudlvaeztzwakfjegzosmhqtnvmzfxtxaysoyapljhhoipybijsgrbgcahwaursxqtskqgfetmmdqocapbkeqeormyjhselheqwvqwiopsdqwkwbayvqnbzyetymdwavvgksmaxvepogufnzvmwhciytlcwrkdtagxqgsetfmlhskihmrvhklqfskjxsccxpaaxxeleokfndjtypgoauoyqmnljkxfxeugkdsawtzuxdfeqfaakklnrxglkqaulfepdiidymoqjrjxyzicgxowrnoztyyilonshlgyqjukrulgltggomzqdhmgpidjyrlckhnzdpygjdgkpqayopxazuhvxaadipttwcmgnglldzwquglenhpclyrdjnjuuovqnunmidimdowglfkpyxjchwbavqwpoewokunfrdwiyhlmjbjrfvmgqkchnlmgynktiqfbscqkjvvgkycrlirqtwrbtsfhbcwcihjtqwbuanjmexsppswrmkwwdwejmhcwnimbmkswfimtbuvsxecophbbmxxorabhdhukqsknbsgumjhrvqjnljdtmcuzsrqqjphqsspijsbxwihcqofmvczcmqnwmemqtlzzgmkcqrtfrtrurvsjjocrhnszlswamoevncxaayidfnekqjoirppvlwikaivknzsseewclsxcxgevkvfediyehshppwgqqpxdxliaimrefcjxwrxvonpdsuktwptaelnbalzlwjmzpzujibmfpqvxgpvxoijndhsmivrtdzxnbtnkkeyrardjregltvshhkkxxczarpbdbwikjmfpbmsxwpmiojhiozzrdvcyxyyphaaecentnpsmoffnilgdealzzwvvggpnzaqljqigrpivjhubcrqhrwchkvfhtwwgzyrnrltirgcsfamwvdjbellruijoozvongwhqwoddyhqtxvmobwoqfwptdabvkkfxptsqvmunxliqgelnlvwgdewuokjxqtgdbncblqhsrfuyoqmaghnesspnvqffcptqiiovpeebritcobvbwlkeievpwilrvewymlbeunmsvbapbfmstyzolnyaghojxgmpljpwfurjbfzdsoinfvodholypvxhdfzqhurpxnhpfhfoaatewxzkxrdufflvomvuazcprajslctfdnlytbtsysgffzslxtibxuztvnbgnpptunldosbsczyhpsgenwdtixbdmwfqipsgarvphzkyrifefqdxcjieztoydpvlgyhnksfzuyukzflnjokyrejbcbonooldxdnxhgohzmamtavyjptvlebxlgaekduohoywniutlpbzswnktqwkftoijnbnucdvyitirwxdswzugcsznmsjwkhiufkznqkxnljckeylaxfizaotguqqmjischlrgcxuisadzdrfjjyhixjvoffkexsprgnvikmgtzjzjnswrekfrusexgxeluktptrsotxoqripeziwsnqxjptqwmvkykjgxxtfovdirgowpbsplgdcjfmpslakcdxuzhswfwnwfxecczlyoapppgxatcgvpryidlprmsztsdlpprgrnqxewobpyhusiypppajxquhhojeyibaqnzalhlisdbraduibjkglksjopaxevzswfwnrrveksqsjwzfsgkldevdahlnfjjzafgoxreciqztdhbztokpwnvybntfxwwjhyqidmcccbqgfqbkqjpurmmkjnulzvqwqecqxhlsqyfccaauxjemssonvpjjkzacnrtoimbunsbbwlwndwyixykwfbeswucfelpdbowvfcmldakqlaesxwilvlyuazcwhnhjeqmgejygggtjpufupndqilqrtpvtavpzoaxepponwtzipasehgfigroplzheqvowevklbrjtiadaskuoqaurzqpzluvujvixqdvlebfrqvvjhicihcnzumtcfvilzvmzpcdkopazigffuwtokfgxqfahjhgirymoznghgxnavuvatfwulugtgozcrgpfckxxifxfumyjcydxlfklnjvrnfpmrhpcunsyecepjgpmxolhmswjhugkdcpqtzemtpaebfcjicvscdnaosiinhpaojgredkkhwysxrmjspcqlqjiehrvdncpwcvztmzrjkrsjtwbywhskivjsbanuelwhjvefensavwpmwiixwihzyhbkzaabhmbsybumgowkwemcdsoudqulffvizrncbnmruavqdrkwlgsdzcfkknoflvbmtkryfcfylnipgjqwswdluiyidqtdryjumjheifkgzpmueimyaasifivwckkdqsujtjainaiqqgpytlvplvymfbahzwqllgcdazqbouokkvesacphphtkqedxntvlxizuuundoqoseqvaacprwneauxtqoumryhwjhhmuqcgfqgrmoxdhasohozsziupuvhdmntkeezijenxefapbrehkcwmbnttzayczxfihvtaewoegdxgyrcqzptamhzzcpomwlhhdzhbbuepwtomqckyxocaurnwrystpmgtdxvifzwspabpwbjlolupshdbnzrhuzsiufidcffxjdyldfgudxtdatpsrpjmaesdgdiqqmcxnflhtjqcbvncphmymmexvvuunmxvsicvmiulslkqsoaipjwzagfjpfddxexiypsacvzreihfwpgnyfkqtldrmgtksaogfezpwgecquufspfwlxvywcepfkdueyofjvusbdhclxdsvzbacoahgptxvfzscgjfuomszsxjhbejdhavmenqprvjszozpdnbtlbwwjqdagstheskzjikpnomjehjjjkbrkmszbdbzujtfbpylucyfmxfixrvmnctwfjxrieiosxrcqbwiqkyityzfohehheeycjrojczrozglchuonrxflisbnskpgyuicotezzsdaxhcxrqzsyaysbuiibixxbrevbeybbdrxmchhqgvthbxpuvhruxdyrkdtccbeiuvcxuptkbadgdnlpdfjfflmjzbnzbzcrujxtgpwgseswnhgmhmettesjwaxxxbqveyvfdliuirtoptvxlmiwibjeynfhsmbsvkgslauzbzfzkxigxbvqjsizbwzwmarihyvbszramzsjrnbrgqfakkumneztezrhcfydjwqleforgxturnlkwtbffcbnaopxymedwnewzzeymphtiqdvsdmgxcrliwvtzsosfxsrfyqximftwdkgukcbxwkhrtmoyochoxkgaegqntnsganmziqspawpmavwudmbkvpxejggnoljbvpxxndxnzhahcegjiwxcgjeuxsxkzoktlljzurlsfthttjqfamjjpaeosaooohpgqhfimbztjmnxhfxupbsdkaqdkkkedwlagmyxqqbwipucnovqcpazdrapnvwquhyhmigjmjiftmzesqzscipmzmliwpjimwpeedrosxnudhruauzckqyarrdvmqfzsovaiseylzmplednykbytsnwdilgyiziwacpknsmvtovjhdnlzzxqscrlznrbbnumqevutofxevjnfhtrjrxyweumpusuoksfwzkipgaubnfakqykdhceuytpyespvvycznisyroqjijftdpfknptklqbdnhzejuqrwstfvpojypynfkhmzsjxeraxblkzmvhlmoswlkwvanpzxhokbrnccxwzanmgfyhuogyylanagiqxbzstlrjroessgjysdsdydzahevjtgmigzjqqvwrtiwhydzupbuwshhntnwwledceayrqbmwboyyspdzzeiqrjhfmvigzjcallnriqkujpnhyssgenxbikxzbcbgbtfcdxwjjmwqcjkukeddydgogwtzgsapkgqhrciarmwndslawpoyefraguzpascudicyrvsovjplkzfrjizzeenujitqqzpmtvvrksksshjwbmjubjmvodjijikmzjoxbgdyszziqruckypyortoinfelmriceeqyfbphjkkueqetqqdgyaisnwlavimvxtmmvrtigjuywohbvzcvzehgmhcvbrctvwnufhzhifiercvcqdfscohpuozuzceczernbezbwbcubemsienrjwkroqmajbkqdbhuaujsvvzywbcxyijleujesazjvrlfqmqefvoqmayhmpwzridjkskctimdsusyyehzccyjklmvhgxhwkbagvprjpzwehmjwcaahdvkswfranltsocxqtnglmvrymzsgynmcsszdwdyqamfymzkicohhzvuehsrtoberfahnukbnlhrbsssptauxpbwivcyskcbcsnsvtrbmrnrcqkdcqvryvblwjkgcpngdubmzpjaoasqxibrllnuxednfmdnethtfgpeizlvhwmwhrposewovmnxlxwerkklvsnmqebfchnteqqmlebzrwvxxdmucvdhzyamkeljjccthahmljuyblwecpamatojswzwoilmoqwoeipkqfzgxrtimwhhsdkwaotkjetbxgzsaszkrlrgwhwsrjnreumwyfncdtdgyozweymwktoslindtefnlkijmaoqvquyljbmvsezyywzfwlvmlzxdekgllihwqsgowliqekplmebiidlyipfvzjslqtxpaaqjdnpupefbbxhhjkwdvaazxirapbahczqygpgawfkebhkmtszvcfxqohzsiijvjdjbfltfnmfwycaujdhszmqstxivwmqkyjvgydnwpxxnpvmfiemaxjeaalbttjmorylzosmawxybfdnclszlojncbxlwtsfgecumqgkwjidyoyfagnkwsadbifqabvyiobqaubjsbmryskcsitxjoepcrekzrokvvyqfonsplnldbewtuhhriifwgbumxbpjdrkccxxpwtujzoxyisncyjruxgofopgdststgkcxukkhdqsglhjlxjrbwkhfehkholijlsnxndanflfiyawgbspobvkiphbgxdyabyqekzbwksmptbfvqzjuezhqwwtijknyyawpmdyiepbmthhwnwdubybqryxmtczfbwtpyfmozadkjrvzalsmkmzqkzofuwbofbvbbvikvhmxhpcglxebppwvoykkxdgsfhkizxmgsxisiledpbrnqfhankkwpdpmbjgnpkfartvndfwoydajoekzvdesaurnerjtzhstjtnfmjfzedflteuiltdvmxgvhhtbehagwjvsmzqohqrgpexbnvdejxhmmatqtzslskwnecetasjvdkjuntnqvixcdpxlkuyixtcxytfspmxjmnfjjpucnvfsacdnjdnwryujlygceslqxuougecnwrwphxgxctosrloqehwxgekscvuqopxnwiqzpnkdbeumfeldcuemlxyycggavamlaoubwkfgydoxgcttlblrmepdwwrwufzxaqxfdfhqfpbooibfhupblvpeooerztwejtilgyyeucffpawyayxgisuctwsiuqbucvoftxwsbinlqgmlhosxpsyhqxstcmqsghlajpvdmsmmrxzpogrbyzpfbyqhbuffcrucedrqpbstsrahjuvywwqfffxedrmkwcuiillsmorgxuhunvkklnbynwkqnfuognmwnpgkwnokruuwgivnqukxbeyrxcfefotclmdlfinxyxhicanltsaogwkpdnvpqgoydikgzidhydaehjpjgmggbwowzwvmmrlpcncidszmyunrqzcmioqgbxdksemyqvxjakzycalqgqnzqffovupjwwyvovwgodzpbkldokybkhclowhnfdflrzqnlvyntokfxxcmedahztaouagfkbzafwsyghcxcqlbcvybfwvsxaxlhfztfofxqaaatanlloyulhfhgbyoqhvbjotjahcxtgjbqwhvtdgoyxkoqhakfinzbkwrxrnbnskhkhzyxlcwrjrbdjhcshnmynjchmoampwglmkofzrfhbeenxsdrrljakkcwifprqevljagmfofmfasncebgtltjsnoaqdlvneubcjzfzsrbyuswcsjwnbuptkeysdwconezskgahlgghctbpnntfxkssreqcdudmtqhuuzkfictfzlhvmghfgcyzlkwlwefsasyereolinbbvmwudjxksqbawwbyjacoolskkcwerfytbbbsnctbhilbbclrkhjunythrizrugabddfaxxzsjzkaxoismdlnqfkxrnqprorqiaitaikdqdxzxoeildrclozgeexufrhedoqvphipxrmhegipufwdffecfznkymdnogmqaelhoithufesaoihfmtjpkfjkgumzlanuxaxptlpybadgdxngyppuaxowpdxksovyyjzghfrtpjmgpwhyegiepqakymsjbahjdudjbhjkfjmhbqkmkueqgpuzlbfnfunsxluwagfyowspwuikpanizxglkumgsafqdjnqrddfkfiwzariycbujtaloqruxmanlpclrtqiwmekltbcpeucgnqwrixjyqhoecdvnpwqtpnllsaxdjnetfgcitskmwougkvjgxmyjtzeijuvmpwatyacrtwbqtkhwibiozpbokvlpnikduhydhrjqmksvqvdyvimwyjoacnogvnjwfvjpddaniqjovezhrzmibjnjwvdqqrdeulbldjuigimexqtzqrirrwjnckclkmkdplkqtydtstsewlkgecezjglmugeesguhsxvhlikkakejfnfqvzrtvnrabwhvrvtkcnvuioquljuihfyfscjlawbftdhbvlagzeoxuvwzdsdsicebofnklsyyirupgjshzvtllzzockgabkjgvqcosdslkggsrwvxhmgnnoglnifqfkrkvynwrfmjvkftgavwtrtsvpoyishfhqzxqulhxzbkygxxzxhrbrbucopuxudvyjgcmueuaiflaznvoevuucierowvphlhumodcsbsimnabjpupsvikyuemiowinzpfzahstkmhenhbwntsgunjtfessdmgcnikcpgpcxjvnfvcacljskwepllmpazjtbpleyzpzwzidmiayuhymubxekpqbxphvgbqauykgyjkbbdezjzgvazankmxhoapkokpcqqaozpxtumxtpsfubzgogvqemgykvqvzuixrkaflshczqwhxwjhfgvzsifklbefadwsvucsnwuzfmytjrcfsshxfudlaubcbkgwxaccfljarzmwwvpnqomreacjodlicawtufaflerpuebgweqvgzlxsielbukaskmrqfnwquwhazvcbmxryrrylrqdtrxbkyeuxvlahvnvweyvdbvhngurmobntqzjslwgabhjoswkyrtaubvivkjhanlmmhjghyumzzowrcjyykiirxrmyexhkzfnhdaonyrnnjohsjxfxcgfrsfocixpzrzliephjpzxbmvhlqatlgddkqcxzhqqvuly') // test for which getPalindromsInString function in buildPalindrome function timesout buildPalindrome('hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh', 'ozejdqxfbqtajywwxdnfitdbqntrilepymliwfpfseigdmbvnoavmfpermnxxzapaeanicrtgqmmlttmoznsuaeemrrzzxyefmexpasqqrxxwzxljwelsyfyadgyunzczbvrsrlbdooyexcytlsjxksfqeaynnknkbzslvzxowcyzzgavqbjvferdakpcyjgvgsdgseetazbpkibcsimkjmrylgfnaykbtbyccntjocbqbjmddxiqeqdfgrjyjcwuxatlgblmvbmruyzurqvweprgljydzeuddxlbwkbryvxlsqvuadatakzogkoxxeslvsdrpgvmixljemmjkovydkmaxvnzbbcnipqmoqsjtbxxaevieapxuormwmliovkiptsuddbggusmmunxjjjorrkoducsktuwbnwaubnaseofrqzfwykqjmnkbpqnzwtejaecmuylmljsibzfoumfomcsgstpsrszjpqzpkqtrzfaatbzgsqyqolgnlkjxmxbcjxxvnogidoslmrdqpngklpboqewsumipqsarmagqnrctfqtaeblcwyyvzglvorwtmtwmbmegsrpubwicjaoonvttbgqkcsarecdrtqggtqdvucdplckjcksdqclkaubfmtbrjpdvbrzqnfrqxfzoodjcsapggzcwnbquyjayfjloblqkopsjoifxolqxjrzjufxyqimuciotgefgzpmcrixztnbrloakcyabrywxggqjpbtafgcekugbrkfbkclutdoxfqqkwqgqoupecbasvbbromdabbrltntofbendpjrxtsvdcdodzcnbkjjsvbvabcsjamauiimsasqxmzjxnnayweazeuxbrlplgzvvmdbrpfutoznbuowdtanpedowasqjsiafxkuvomngbdfggooufijipwjeumrurcutkbpzozzuuwfzuluxlvemuynjzmyrgojsyzqdllsiqpjitmmgivfukclyoictguvdvkslqswvmrgeylswtblgoygbzgbemavyyzbcsyjqijtlyzkoemkjgvfjsyxcyeapufybpqvlfosicqvsfdjskcdjseqylxezvpatusdpjbnslsjexfyousogsdsqbiobmvxjvfotqikzcjfbwvfyviufazomkmnqdtmkflcfidaolqrpgjzqiygnbdrxscgtlkgzgvkzmalpsrbgmasjjzimgnbacctjtxtwmikpqgjezpejnaievkqlbzawogojwnpfddalvstnmqwyskqawrfmpmfmrypkkirxeywttgegjmjvoxogqjosxtirvvmlstiwzjukalocmyorkpfdikbrxskavzzkbnmwcluexxoiwzltyitgwgtzpcydjvgvfdptnqxadnmoqvmvvqymaexcrtuqmmqdjaknmznmxrlnkwzknqsirfnylwesrknjrgdlbrkfxmswjudjnkvrkokvmejkmaytligzvjcckqmvlsafxdtxmarxfdxtkfaqdoipdrcszzrwpbtjctebxjildqysugeaayggklmwizuccuzgvgpbxcyscxprtxidolwlslepwxeeqrnuyyvnluevykmitxpuemtyxfkuaesgocrtpqpqwnddaiykryenzuzpkruqfoqaclfepfzrsdmjexubqnsfvmfgzcnpgrfxxjqgpxkznuxgyjytbzujjugvdoewcnfyzqypxwovvluwcrdxbycgbfzgcybgsffxuualvmvcwsrryzqxdgilyozldkntavwjfydwqprjxqtpetxvcsxapiaivyudikqfejunialystytcqwdxubxdzcbuzyrualvemsvwcnqbnedvjwvylqosxzftdyxyxsurkrmfzrycfvylqgjiebgsocqmpkjdugtaexoygneusbzatdqktreibueskvvdpbxptqubjckkveykwazivjlwpvmgnrlsrowademgpywksstexsbmjvxizkqtnsekxgfjvarextrqqedbptlobiyfrqfceclxozgborvsinwedrwstymvmbjslxyrnbsqjugnaauirqsxidwapmeszfwywovjfamnaekdyomsdbatdfbgncxuydrtbixmkbnmmzpykqnvcpkxqjmszasdwiyzommztxrjkwkvnqqmmursbtjbsigaskjakbybsdtvbznazckigxufrdwyzofcvmatgtybaepxlsmjgaleivdkalkrjmtcivbyrfkcnxdzfkksfcugjiorrfqofucfimlqozyynpecrwemajxljennfxlzevczxljdwdrbptokrnsyraczurpzzzjqdbalxktxdmuytfylqvqozgkzxrrmpouzulqrpirpsfqldkvnnuzquempivyxuvvkkmztjtnvjozeasonftyjpeokiwbygmxjrtswaligrwqaqwlyqbvvjcfykgoqpoonffraaoqljtkqoazuqcjwytwvfnafbqokqpixnlsjtfykmxvdunfaxtvxdzjoknokduoanquibuzwbyexqtzoxaivabkweutmtejmkzdbvavzduqexeigyxdrjgybybejbrcnwdnxagdtcxesbfkvglgtmzneerxkqecqeqpwkqejpeqyltpfzenlpnnodxfktfccwynaurrojiumrarkxydunadmjwnlqzswmgmilidrbiytpnxqelyolutoecviftlzxwyyykiucopbfkyyjpbnwodvfipwvonkiyqaoowwqfmntsqzsxanmctbuafrpsrpaiteomgcraeemivcjiplskvoctoajwqxpdbzdwnoskqgskoifvjspmptnvwzrjbtzenylpzpngicksenrxmelirlrkboopdtkxbvvlpjvvwmskzyebmosmwjymrnbzvzqxiccxesbiofxbaivxjlnddjzjjabqwwbakwbpeuorftfqbvpydoglnrdpfkmdcvmalxccvbrkncgtnvqijqndyccoyoyrnezaxdstfnlzokseipcazrdnzytfdpuilgioassfbclinsvsdseixuqnebbswvftexjfrxabmlefjamtfwuxtiukvcdrjcuptssgfjbogfypubiqlgenroyadszqtumkvtfimtxqevckayjovjguxzegktzckunanpqbfztidmpitaorylxcsxyjzfdzrejeurxvxzpvekawgvqyidlkxneaobgsqgrvfndmnnydopufwbzswjyqveptjnppgstjwccuietgyigiwloekoswgbtxjapjpjzwetswyxfklntsgpaerrqxuyzttjzmulxriytpddocaqcbdppdyssyztlmarldzstawdwcrjnndsejbuzcgjtjdqmfmippxvjotnqfkplfkxoywvvbyngnbwdbtosvnbagguzpgkqpgspededuqkqvjnepaqcqdirgvxljtkjiczxzrouedvmoezsyumiepyikqdtsaraplawuuntgvdokvacnzkddpfvuqsgnerkvpgqauwrmstnpugqqbifrzfrwdnjosnrtobcwzzcwjxlraxafdmqkxndifexaileqqoipqfioumsysjliaubtwlqwvyusajigqzsdtdnmltjuljanteixojyuujfkirmswvfevtweuynvxgmxbfyggmuwtbsdkpamyodvxlrfmyudogqtqtpxsczmlxckstllzkirbvwappcvpljnlziqcdgqfwnlcxdbzyyzacaqbovsfrqvzdkagejufrrvmzkaozvcxytleusxnvssypfiwmdddnpanxlcgrkxzlqtscavgkwcbvnuxfarzugjsragebkbayuddxqsbgtpievukkpbteesazqvpqqsqsjnvcdeuvcvubicexpflvdxcjbvsklbfirxioraflvlnnriscvfjkpwimjiwgiiwmuqdmsaizvudusbjrwlwcuesppqdzkpcasngrryemyofllxoawvczcgfkpsimvvyypsurbzjkepdlogpznmlxytqqtvukgwibbbapyutmsyusxtpormllmsacpfvosugovqgujfertmecfnwdxonrgdwpwrgkeypxczfruzxzokgyttrjtkateckyqqdsasqqxmxxfdnosnvqydfxprjzixlumkwrbaizxwixvoddlxdbzmbfkwbpmpopokmisrkjzqrvnvwgypdisfngxsjlgyreamcmjcbsxqimiffpqseaxmcjjepxvvitrvojfigtejifrpcgxiwbzdniclmytisniufzjfkkazcscvapbtlvcbpxwljlygdsmkcvlyieugyzakfbqlkideauiytrtssqztkeggjxgrrlngtpgzyaubdopnjxmzmbgibdogrzxwvgunteamvekgwjugvzjfgjujzklpgdlemxcjzvknupsqrbpytvfpncwxkcbitedrjxqscgmsjgqcvngazxqurvpotwnsieerilabckpdsndccmyoaxzxkppwbxktwewjmtbdkdaveomjwiuabkffjwbceikfyxqsuylyxaygirfogeyipgdagxryizdjifwmyrzpamrbpumkwifrqjqgbkekqnldibaqqsykyqmopodcuxbnlzyguffzokrfyidnwbdevseaiytxzdbtlsqpirmnpjpvwcswvygvdgnybvpkmupjpzmsgwuswpdlrgxavccmdeqemtkjildcvkbmxssnwtwpufdaoxlujjlblipkqertcvtixpeyxjimujsjylznbloiogjmgdyygoiesljrfuuigudyztfkdddntmjdewoesmyyvmgzemotazlrrmuuxoxgyxediduqufzrrdzpxycljbdqybwticcxumcffwrtgfeycqiaesnsuwnyvvpjuegyotqogfajfczkvwwfmdrfjdqkjydrnxctoronxzpwukveagisrnfrngqdwsqqturpjgwczfanvmfojvidyauswsgbtadoyarameuxeafzpamvsukjjlywagztijxodsnqjdcpvtvlpqljqcetxsylwconazmaatjxyifmuqyvtxblacjlxbvkcvliaotmiveynrnkfyjxxrdtubmkseiydzklrcausncwpecwimnsydxitiucevbcqsetkzlircelekceazvxpjbzpnqivjvocriyugwfuplbqvjqbaxuxevelgqizzvlkwfytomlzpvoznpmkrwzutqnoacgfbfdejxndikpsykqjsnixdovklalwcspjmspxmejyymngrczfctauuffyoyakobijlcttstocyfzqgrvcbainfwwmdmgtstdcqefmidwybmapgpzpactbptiounzfgfvkslflffawivticvimqqiuccitfqlbudjdfzsyoifykeqpdfeoinarytpokfgxlgjxiaweojkkqcfcsiuqgomikwolzaeeseeofnquxjryjgplygqmjcadkrjrmzkqdjxornouxferwovzrrtrqogfwiypwrbutptenzetgvawxktgnabrtmfvybtrjrcxmftpatsfllznoxvkocdbbvzwlqsjmsevempzffqxeamxsgfbzwinnunjowxiquwdrpgczirotemsesbeetpydkwrzorbeancjjzcbuwpslttzkulkymqvofxglfgcogvungkpntvcrcajnnvallpvyoupqzjzuavtckjmeueqedfkmscxbqxfvoexufyxkkcwpyrusqfxnbrxilautmrmyjiookpfdrfwmbtkwkcooiaykpunnwrnzxqmsqmpfmtzigdrclzgmgnwfryyotrkdpiaanpqleyvsgidvwunsfoybtxsaswrcvxkbtndujudjzpklrbzpdbftxeyobfvayjwqfpsguwtlutgnjggagxzktfsrszykmpztenxpnwgatvggbsfuiygitkwbmqjesuknbkbnmqlnbdlddlerfpvuymjkwpsbxwmzllbcekokozddxefrbaqpeqwibufuaqvzkqqpgfbkdijcfsblazgmwneeawpkxlonjmxanwqsnseraitfqpwgyfgeuodbkldkdyygvnpfnznwocjvdvbcwksxydompvzvtlwmpllvgjeqoeqsjosvirwclqbpucvgpysxrwnguacevyztceywoqxxcvnpqfzxgkpwrdxxckqmywdoodpztmgdsjxqinlxeyqmpteafzrumbilpjmtcltfvyozilfdrnvilbttxnrpuacvoejzbkjyazkexiarolbqagrkwtnerebjpicgkzkcqkabpkepqjsvtymftynpgnwnxbpgngzgrdrlgsongtkujxcygtasalzigvvnooidpxlegktzzkncekcbqmlkcabtqbetlvaplzzyumvgrfzdowpljosjxwioxjgpfplwzyevqvviwigitfzxwercaunzlvxbxzlnznmyggngqapxbzgnondqbjkovfvgwknrcizlgvcjvtxpnrrzefspjfdvvdxwqmuvcjdkmxxkpsyeyykfqeojsptpmjzwdteaddpukjgpvagkdetqubogerzlpmuxtdwpxwgroskykjofkbsknqiwidbbjiatjomrkfunbgdomplbsbpsqemnmtursaaxdmzefibgeneuskqgrayodeyosblivqdcfvianpjlypxttleszjierwlgfiiwvgnwbyjpqqbrvmjvpirwefogpurscaoxozbyibquxmkliwqitkwrobnjtqbzwaqkjoqitxxaeoyzkpxgrllujidqzqwvqvskubsdggyummtsvygjzxnbykdsalvacywotbsdikkvexbucwvloirbfcdbzfdgwbeoyxvspiucbtjlgkaaiyvymxfxwzzjjcdnipkumbwszfoxeuvqcvujovrterftdbbjigkjdbtkatfybdsdlyildoawiyvbyogapqaogrkntcryxdaetfbnsbixxjnbaqsczbiwkvajrzlrnwsobveorxfrbazdelecugplxfdaggznbyacbsyfkuqavxjfvilgxeefizecanulxntakwsvpwrkloaiszyuzqvgioibqfmmewvnyfiqtraygoorzujtvvogjatdbnjymvtyrpvjupgmzidxjdrdojujeaargoabdnjzrvrqtzzgxroaljwvigpypydogcujqccwtttsawnelktptiiaujoufsgdgenltwipxvowzuujpeyeegcfqudqqedltqdswjjevfdcnbwamnzyfnvqbcsxtvbiuzxobavfouevkzavnbrbteyusqofqistruyrscwwwclixmwrserecxtnxqivlobjjxwxsdxbbeybdgmqvbsmgkpnklukdjqnwravixrfnjmjkouoxnllzkeimlltxevcqksjegspjcmxwqdfwwtxupxizlaxkcilutuxtoegbztcuoujbiuurjxpqqrryondrxnlftksgrpuvuoytuprisezmzxngolugkudxcznvtvttmbprtduoexmydbmrtivfeyztmjjubolsxjembirvzewmpggylqesqdxswuyaiixzvlsvjeavbqnmqssplmmroqbzifssznqnmeouvucitgcakdzjjgsbjerxkrdbckwbrvjieywqqjsjmmqndpfaieetbnullvkkbuidzesnlcgbkqfuabkgmulrspljglfyzavwcptbevxmwkkydytdiaxoegwdicftayejeujxfqzrvwegfxgngvfzbkdwicxvcnoijvntiowpbplzrimgxrrtnjscevbrycavwbxtfojqmyqgvilwtzpkeiusovsfzrrpixfqiwyiidyjfzqfwdjqadfzzniejnxjjmlajsrasxgxqmkdxrbjbyblqgknrdfgbzonbyvorerlimllfwnuudmoqatcdkfaszsbwbpolitueujxtbwxfvdeqtfljvedmrnvoopumfnaqzyqadmqpcripqaqkyaatqlcygidqwabnlupfgfkqqyzwxfvywdanvkgkxeedkccbstwlpqnryjtyvmssmjresrjtfjgbmlqmgsjtxssqczifnkjoduknbauwvgrjbgjlnbwixzbseiyldceynzikdjadrtoryboirzitsmgdwvtlpfvgmkulgeqgjfpyvbgpyiejjaslexixtxpxspgpurdaddyskqybupnnssasjemmexffjvucofwnpsiyiznennvtcdqdcumknvdqcwkpwdllaqxzkadtoasocdrgzzakvmufjbtcmljczpbeelgbbucliajfalodmoeddrrdojokbcujvfctlzzmgusktszkgmlssnystrsiupsnkfaugrjbjrabtzlaecbfwpnptfozatqxzvrsaddivaedikddtckoolwnblbjffdkpcltgrtibsppbavnupqtprsfzikzdzbfcwtbtxcjutemeupusqtxwogcquxtjpqwavegvxabeygiopeakifcpgyytfixflmyskdwqtxrsastdsyqkppamngxgvattatoaiolzplxicvtxamzttwptpvikgebqxaxidiqukstaltgnbdfixpgvixtcmkpubwpqbzyjyeqasrumxafudbturiubjkcutcclnctnfrgwaepfayjtxylrttyzvonxbdamvjfxpwaxrrqrgnusnafbpxgrwozuidsetxluqjmteloketslusfccmuygnbgaxqiufoxdiirewkwrnntcojidstjnmlctqtzfxjtqdtwsngftqextpuefpelnludryxsiaqywffgkfmpkptqegocmdszjpaekbamvugttdsbvgzpwvnjpoobofuzrabyqkisdkxybprpevfxacebxpadpjgjobmddanjoswyqkjxkkoejjivngyictjyxuvyxldrwedyjkwccaakkxkrgqoeokimkosmmtpnlmqzniqcmfstigyxebpgfbpxqasrixxpodyafkqvvbxkwnnntjnrwwniaqoijwzudrxtjonmvkbkdetplisttvfjrikedjxcysarrlgsecakplumyxbcojbpitlrfoxzsdoxfljzkedwpnkgxdmndqglriniigpcduycbgimqqitfsskkapkbrzswpurnznrdrwswkidzjdufllpexgrdbxljgboxdudxdkugiksixdibzdkkkxfjcvtwmoeyakgemrxrlifpgpwyitckfwxxekkaznvxefrdzkgrucdsdyppykesiluciwacsgqkrlsefxflznvxztlblxnbzixczvtjkpkmxgykpmpltymgtsnawsmwngtukedofssdlqwinoyozzaanuduinmcppsoeqbodzxsxgocbmeqwdlgvmxiudzazgxiigsjqgsnpxxvgxzcwblolxcqpzzfgovtgofqgcbzogbjogyccrbtlpadswbgfbqrkjpwmiomgaolcuftvnawjpdonmdnqrwcpaojjitatkyedeuvrpuxtezrfgajqbgtsignnnadidvyjamqjllmwdaamwmknbptgqesflscsqetnpjrpsagoamsvjyftxicluckgmpfzufiwzdttrmwmyzmttmumymtuyqqzzowqjkktz')</code></pre> </div> </div> </p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-17T05:38:18.513", "Id": "475778", "Score": "0", "body": "Really sorry @Vogel6112, I will make sure that this does not happen again." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-15T11:42:52.020", "Id": "242333", "Score": "2", "Tags": [ "javascript", "algorithm", "time-limit-exceeded", "palindrome" ], "Title": "HackerRank's Challenging Palindromes solution times out for certain tests" }
242333
<p>I'm starting with Kotlin recently and am hoping to improve.</p> <p>I wrote a small app to parse the list of <a href="https://www.springernature.com/gp/librarians/news-events/all-news-articles/industry-news-initiatives/free-access-to-textbooks-for-institutions-affected-by-coronaviru/17855960" rel="nofollow noreferrer">free Springer books</a> and download the books into your chosen local folder.</p> <p>Comments around obvious mistakes, unidiomatic Kotlin, any other points of improvements will be greatly appreciated. Thank you.</p> <p>Gradle dependencies:</p> <pre><code> implementation("org.apache.poi:poi:4.1.2") implementation("org.apache.poi:poi-ooxml:4.1.2") implementation("org.jsoup:jsoup:1.13.1") </code></pre> <p>Kotlin code:</p> <pre class="lang-kotlin prettyprint-override"><code>package dev.rayfdj.kotlinutils.springer import org.apache.poi.ss.usermodel.WorkbookFactory import org.jsoup.Jsoup import java.io.File import java.io.FileOutputStream import java.net.URL import java.nio.channels.Channels import java.nio.file.Files import java.nio.file.Path import java.nio.file.Paths data class Book(val title: String, val author: String, val edition: String, val year: String, val category: String, val url: String) { fun suggestedFileName(): String { return "$title, $edition - $author.pdf" } } fun extractBooksFromExcelFile(xlsxFile: File): List&lt;Book&gt; { // drop(1): skip the first row because it contains the headers return WorkbookFactory.create(xlsxFile).getSheetAt(0).drop(1).map { Book(it.getCell(0).stringCellValue, it.getCell(1).stringCellValue, it.getCell(2).stringCellValue, it.getCell(4).numericCellValue.toString(), it.getCell(11).stringCellValue, it.getCell(18).stringCellValue) } } fun deriveFullLocalPathForBook(downloadFolder: String, book: Book): Path { val fullLocalFileName = arrayOf( downloadFolder, book.category, book.suggestedFileName()).joinToString(separator = File.separator) return Paths.get(fullLocalFileName) } fun createDirectoriesAndFile(fullLocalFilePath: Path) { Files.createDirectories(fullLocalFilePath.parent) if(!Files.exists(fullLocalFilePath)) { Files.createFile(fullLocalFilePath) } } fun getBookDownloadURL(book: Book): URL { val bookPage = Jsoup.connect(book.url).get() val bookCanonicalURL = bookPage.select("link[rel=canonical]").attr("href") val bookCanonicalPage = Jsoup.connect(bookCanonicalURL).get() val bookPDFRelativeURL = bookCanonicalPage.select("a[href^=\"/content/pdf/\"]").attr("href") return URL("https://link.springer.com${bookPDFRelativeURL}") } fun downloadAndSaveBook(bookDownloadURL: URL, fullLocalFilePath: Path) { Channels.newChannel(bookDownloadURL.openStream()).use { inChannel -&gt; FileOutputStream(fullLocalFilePath.toFile()).channel.use { outChannel -&gt; print("Saving $bookDownloadURL to $fullLocalFilePath... ") outChannel.transferFrom(inChannel, 0, Long.MAX_VALUE) println("DONE.") } } } fun main(args: Array&lt;String&gt;) { if(args.size != 2) { println("Please pass &lt;full_path_to_springer_excel_file&gt; and &lt;full_path_to_download_folder") kotlin.system.exitProcess(-1) } val (excelFile, downloadFolder) = args val books = extractBooksFromExcelFile(File(excelFile)) books.forEach { book -&gt; val fullLocalFilePath = deriveFullLocalPathForBook(downloadFolder, book) createDirectoriesAndFile(fullLocalFilePath) val bookDownloadURL = getBookDownloadURL(book) downloadAndSaveBook(bookDownloadURL, fullLocalFilePath) } } </code></pre>
[]
[ { "body": "<p>It's not exact translation of your code, but still :) I've just tried!</p>\n\n<p>Unfortunately, it's not a github project, so I don't have an access to the excel sheet, so I can't really run and test it. But, anyways, ideas are:</p>\n\n<ol>\n<li>Utilization of <code>toString()</code> java method </li>\n<li>Using of lazy properties allows to 'cache' the URL easily. It's also possible because all of the <code>Book</code>s properties are immutable.</li>\n<li>Extension method <code>download()</code> doesn't really belong to a <code>book</code>, but, instead,\ncan easily download any <code>URL</code></li>\n<li>I used <code>require()</code>, though, it's not really correct, since it throws an exception, instead of gracefully exiting the app. I used it, just to demonstrate it, nothing more.</li>\n</ol>\n\n<p>And, probably, something else. <strong>Please, tell me what you're thinking!</strong></p>\n\n<pre class=\"lang-kotlin prettyprint-override\"><code>data class Book(\n val title: String,\n val author: String,\n val edition: String,\n val year: String,\n val category: String,\n val url: String\n) {\n constructor(row: Row) : this(\n row.getCell(0).stringCellValue, row.getCell(1).stringCellValue,\n row.getCell(2).stringCellValue, row.getCell(4).numericCellValue.toString(),\n row.getCell(11).stringCellValue, row.getCell(18).stringCellValue\n )\n\n override fun toString() = \"$title, $edition - $author\"\n\n val downloadURL by lazy {\n val canonicalURL = Jsoup.connect(url).get().select(\"link[rel=canonical]\").attr(\"href\")\n val pdfRelativeURL =\n Jsoup.connect(canonicalURL).get().select(\"\"\"a[href^=\"/content/pdf/\"]\"\"\").attr(\"href\")\n URL(\"https://link.springer.com${pdfRelativeURL}\")\n }\n}\n\nfun URL.download(to: Path): Path {\n Files.createDirectories(to.parent)\n\n Channels.newChannel(openStream()).use { inChannel -&gt;\n FileOutputStream(to.toFile()).channel.use { outChannel -&gt;\n print(\"Saving $this to $to... \")\n outChannel.transferFrom(inChannel, 0, Long.MAX_VALUE)\n println(\"DONE.\")\n }\n }\n\n return to\n}\n\nfun main(args: Array&lt;String&gt;) {\n require(args.size == 2) { \"Please pass &lt;full_path_to_springer_excel_file&gt; and &lt;full_path_to_download_folder\" }\n\n val (excelPath, downloadFolder) = args\n val excelFile = WorkbookFactory.create(File(excelPath))\n\n // drop(1): skip the first row because it contains the headers\n val books = excelFile.getSheetAt(0).drop(1).map { Book(it) }\n\n books.map { book -&gt;\n val path = Paths.get(downloadFolder, book.category, \"$book.pdf\")\n book.downloadURL.download(to = path)\n }\n}\n<span class=\"math-container\">```</span>\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-16T03:25:58.173", "Id": "475634", "Score": "1", "body": "Thank you very much! I learned a few things more about Kotlin from your answer :)\n\nThe code is in github, [here](https://github.com/rayfdj/kotlin-utils/tree/master/springer). Will keep this in mind next time I'm posting.\n\nIn case you're interested in getting the books yourself, the Excel is available from Springer themselves (link in my original post, if you scroll down a bit and look for \"Free English textbook titles (all disciplines)\")." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-16T06:00:58.360", "Id": "475649", "Score": "1", "body": "(I thought it funny they offer different editions of the same title.)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-16T07:09:54.203", "Id": "475654", "Score": "1", "body": "For this one: \n```books.map { book ->\n val path = Paths.get(downloadFolder, book.category, \"$book.pdf\")\n book.downloadURL.download(to = path)\n }\n```\n\nWouldn't forEach represent the intent more closely? Because strictly speaking we're not \"map\"-ping the books to anything, are we?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-16T08:10:53.250", "Id": "475660", "Score": "1", "body": "Yeah :) Actually, you're exactly right. I was thinking about editing this code, but was already done with this example at that time. I believe, here `forEach` is better AND it would also be nice to move _printing_ from URL.download to this loop, since it's not related to the downloading, but, more, to the script scenario itself." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-15T15:28:51.050", "Id": "242347", "ParentId": "242336", "Score": "4" } } ]
{ "AcceptedAnswerId": "242347", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-15T12:12:19.930", "Id": "242336", "Score": "3", "Tags": [ "beginner", "kotlin" ], "Title": "Springer book downloader in Kotlin" }
242336
<p>I am adding below code for review as i am bit new to boto3. This Script adds tags (key and value) to All Volumes of EC2 listed in Excel. Is there any more effective way i could have written this? Also I am using AWS temporary credentials by editing ~/aws/config and making profiles. Is there any other way i can use w.r.t login with temporary credentials in boto3 ?</p> <pre class="lang-py prettyprint-override"><code>def tagging(profilename): print("") print("Using Profile: {}".format(profilename)) print("") path = input("Please enter the full path of Excel to execute: ") wb=load_workbook('Data_TagVolumes.xlsx') Sheet1 = wb.active max_row=Sheet1.max_row max_column=Sheet1.max_column Tag_Key = Sheet1.cell(2,1).value Tag_Value = Sheet1.cell(2,2).value print("") print("All Volumes of each Below EC2 Servers will be Tagged:") print("") tag_vm = [] for each in range(2,max_row+1): print("{}".format(Sheet1.cell(each,3).value)) tag_vm.append(Sheet1.cell(each,3).value) print("") print("With Tag Key as : {}".format(Tag_Key)) print("") print("And Tag Value as : {}".format(Tag_Value)) print("") confirm = input("Please Confirm Yes to proceed or No to exit: ").lower() print("") if confirm == 'yes': session = boto3.Session(profile_name=profilename) ec2 = session.client('ec2') tag_vol = [] for vm in tag_vm: response = ec2.describe_instances( Filters=[ { 'Name': 'tag:Name', 'Values': [vm] }, ], ) for each in list(range(len(response['Reservations'][0]['Instances'][0]['BlockDeviceMappings']))): vm_vol = response['Reservations'][0]['Instances'][0]['BlockDeviceMappings'][each]['Ebs']['VolumeId'] print("{} {}".format(vm,vm_vol)) tag_vol.append(vm_vol) ec2.create_tags(Resources= tag_vol, Tags=[ { 'Key': Tag_Key, 'Value': Tag_Value }, ] ) print("") print("All Volumes Tagged. please validate on AWS Console") print("") else: print("") print ("OK Exited") print("") def main(): profilename = input("Please enter aws credentials profile name: ") tagging(profilename) if __name__ == '__main__': main() </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-15T13:10:03.473", "Id": "242340", "Score": "2", "Tags": [ "python", "amazon-web-services" ], "Title": "Code and Inputs on to use AWS temporary Credentials" }
242340