body
stringlengths
25
86.7k
comments
list
answers
list
meta_data
dict
question_id
stringlengths
1
6
<p>The setup is that I have a vector of a class, and I need to sort it by the <em>quantity</em> of a data member value, not the value itself. The below code exhibits the correct behavior, and part of that behavior is &quot;stable&quot; sorting where the order of elements should be preserved when possible.</p> <p>Between the <code>/*** Starting here ***/</code> and <code>/*** Ending here ***/</code> comments, are there some Standard Library functions and/or classes that can be substituted? Per the tag, the code needs to exist in C++14. Yes, I realize that the MRE is written with C++17 (maybe some 20, but I compiled it as C++17), but the code in question [hopefully] isn't.</p> <pre class="lang-cpp prettyprint-override"><code>#include &lt;algorithm&gt; #include &lt;iostream&gt; #include &lt;iterator&gt; #include &lt;random&gt; #include &lt;utility&gt; #include &lt;vector&gt; struct Foo { int fizz = 0; int buzz = 0; }; std::ostream &amp;operator&lt;&lt;(std::ostream &amp;sout, const Foo &amp;obj) { return sout &lt;&lt; &quot;(&quot; &lt;&lt; obj.fizz &lt;&lt; &quot;, &quot; &lt;&lt; obj.buzz &lt;&lt; &quot;)&quot;; } template &lt;typename Container&gt; void print(const Container &amp;container, std::ostream &amp;sout = std::cout) { std::copy(container.begin(), container.end(), std::ostream_iterator&lt;typename Container::value_type&gt;(sout, &quot; &quot;)); sout &lt;&lt; '\n'; } int main() { std::mt19937 prng(std::random_device{}()); std::uniform_int_distribution&lt;int&gt; dist(0, 9); std::uniform_int_distribution&lt;int&gt; large(500, 999); std::vector&lt;Foo&gt; devices; for (int i = 0; i &lt; 100; ++i) { devices.push_back(Foo{.fizz = dist(prng), .buzz = large(prng)}); } print(devices); std::cout &lt;&lt; '\n'; /*** Starting here ***/ // Counting occurrences std::vector&lt;std::pair&lt;int, int&gt;&gt; counts; int index = 0; for (int i = 0; i &lt; 10; ++index, ++i) { counts.emplace_back(index, 0); } for (auto i : devices) { ++counts[i.fizz].second; } // Descending sort using counts of occurrence of a fizz value std::stable_sort(counts.begin(), counts.end(), [](auto a, auto b) { return a.second &gt; b.second; }); std::vector&lt;int&gt; sort_by(10); for (int i = 0; i &lt; 10; ++i) { sort_by[i] = counts[i].first; } print(sort_by); // Prints fizz values in order of descending count std::cout &lt;&lt; '\n'; // Sort devices according to highest quantity of fizz auto walker = devices.begin(); for (auto i : sort_by) { for (auto it = devices.begin(); it != devices.end(); ++it) { if (it-&gt;fizz == i) { std::iter_swap(walker, it); ++walker; } } } /*** Ending here ***/ print(devices); } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-25T21:34:01.447", "Id": "486619", "Score": "2", "body": "Title changed. There are too many help pages based around asking questions, and the edges of those pages are fuzzy and overlap slightly." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-26T10:38:40.750", "Id": "486658", "Score": "0", "body": "Is there a reason to not initialise `devices` but rather push_back on an empty container ? Also is `.fizz =` and `.buzz =` necessary ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-26T13:20:54.157", "Id": "486671", "Score": "0", "body": "I don't care about those parts of the code (per what I've written); they are set-up for the part I do care about. This is obviously not production code, but a test for an algorithm." } ]
[ { "body": "<pre><code> int index = 0;\n for (int i = 0; i &lt; 10; ++index, ++i) {\n counts.emplace_back(index, 0);\n }\n</code></pre>\n<p>Not sure why you use <code>index</code> here which is same as <code>i</code> ?</p>\n<hr>\n<pre><code>[](auto a, auto b) { return a.second &gt; b.second; }\nfor (auto i : sort_by) {\n</code></pre>\n<p><code>a</code> and <code>b</code>, <code>i</code> can be marked <code>const</code>.</p>\n<hr>\n<pre><code> std::vector&lt;int&gt; sort_by(10);\n for (int i = 0; i &lt; 10; ++i) {\n sort_by[i] = counts[i].first;\n }\n</code></pre>\n<p>Not sure that there's a big improvement, but here's a change anyway.</p>\n<pre><code> std::vector&lt;int&gt; sort_by;\n sort_by.reserve(10);\n std::for_each(counts.begin(), counts.end(), [&amp;sort_by](const auto &amp;i) {\n sort_by.push_back(i.first);\n });\n</code></pre>\n<hr>\n<pre><code>for (auto it = devices.begin(); it != devices.end(); ++it) {\n if (it-&gt;fizz == i) {\n std::iter_swap(walker, it);\n ++walker;\n }\n}\n</code></pre>\n<p>Can be made a bit simpler by using range based for loop &amp; address instead of iterator. Note the reference in <code>&amp;it</code>.</p>\n<pre><code>for (auto &amp;it : devices) {\n if (it.fizz == i) {\n std::iter_swap(walker, &amp;it);\n ++walker;\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-26T15:34:01.857", "Id": "486682", "Score": "0", "body": "The index thing is a hold-over from when `i` and `index` didn't match up. Also outside the area I care about. In range-for where you say i can be marked const, I see marking a copy as const as completely pointless. `std::for_each` is not a bad idea, but universal capture by reference is. I don't like the last change at all." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-26T15:55:13.547", "Id": "486687", "Score": "0", "body": "You haven't really done a great job at defining what area you care about.. it's in the starting-ending region. // Marking new objects `const` is a good practice, at least where I work. // what's the problem with universal capture by reference ? // Why don't you like the last change at all ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-26T16:20:54.693", "Id": "486692", "Score": "0", "body": "My bad on the first one, I thought I'd put all the set-up outside the comments. A copy being marked const is pointless. So what if I modify it? It's a copy. I gain no safety or security in marking it const. The problem with universal capture by reference is exactly that it's universal. It's addressed in Effective Modern C++ Item 31: Avoid default capture modes. They can lead to dangling references and a false sense of security. I don't like the last change at all because I consider it hacky. If I want the iterators, range-based for isn't the right tool." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-26T16:37:14.777", "Id": "486696", "Score": "0", "body": "no worries // https://stackoverflow.com/questions/18157523/why-would-you-use-the-keyword-const-if-you-already-know-variable-should-be-const?noredirect=1&lq=1 // Thanks for telling me about universal capture. I fixed it. // okay.. seems like a matter of taste. I see iterator as a fancy pointer." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-26T16:58:32.793", "Id": "486708", "Score": "0", "body": "It's not that I know it will be constant or not. It's that I literally don't care if it is or not. **It's a copy.** My original data is untouched. I understand the need for const. I use it when it makes sense. It doesn't in a range-based for loop that's copying the values. Had it been `auto&`, then I'd definitely use const if I didn't intend to modify the values." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-26T14:09:27.500", "Id": "248462", "ParentId": "248427", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-25T21:06:02.523", "Id": "248427", "Score": "2", "Tags": [ "c++", "c++14" ], "Title": "Code to sort based on quantities of a data member occuring" }
248427
<p>I wrote a some what &quot;simple&quot; module to retain ETS tables should the owner crash. I think it's small enough for review; big enough to make enough mistakes. Honestly I'm a hobbyist programmer aiming for production code. I will take any criticism to get me closer.</p> <p>More logging? Use of <code>spec()</code>? Anything.</p> <p>Thank you.</p> <p><strong>ets_manager.hrl</strong></p> <pre><code>-define(MASTER_TABLE, etsmgr_master). </code></pre> <p><strong>ets_supervisor.erl</strong></p> <pre><code>-module(ets_supervisor). -behaviour(supervisor). -include(&quot;ets_manager.hrl&quot;). -export([start_link/1, init/1]). %% ==================================================================== %% API/Exposed functions %% ==================================================================== -export([spawn_init/1]). spawn_init(SupRef) -&gt; register(ets_fallback, self()), monitor(process, SupRef), loop(). %% ==================================================================== %% Internal functions %% ==================================================================== loop() -&gt; receive {give_away,{?MASTER_TABLE, Pid}} -&gt; try {registered_name, ets_manager} = erlang:process_info(Pid, registered_name), ets:give_away(?MASTER_TABLE, Pid, []) catch error:{badmatch, _} -&gt; logger:error(&quot;Illegal process (~p) attempting ETS Manager table ownership.&quot;,[Pid]), {error, badmatch}; error:badarg -&gt; gen_server:cast(ets_manager, initialize); Type:Reason -&gt; logger:error(&quot;Unhandled catch -&gt; ~p : ~p&quot;,[Type, Reason]), {Type, Reason} end; {'DOWN',_,_,_,_} -&gt; case proplists:get_value(owner,ets:info(?MASTER_TABLE)) =:= self() of true -&gt; ets:delete(?MASTER_TABLE); false -&gt; continue end, exit(shutdown); _ -&gt; continue end, loop(). %% ==================================================================== %% Behavioural functions %% ==================================================================== start_link([]) -&gt; supervisor:start_link({local, ?MODULE}, ?MODULE, []). init([]) -&gt; Pid = spawn(?MODULE, spawn_init, [self()]), {ok, { #{}, [ % === ETS Manager: gen_server to not lose table data #{ id =&gt; ets_manager, start =&gt; {ets_manager, start_link, [Pid]} } ]}}. </code></pre> <p><strong>ets_manager.erl</strong></p> <pre><code>-module(ets_manager). -behaviour(gen_server). -include(&quot;ets_manager.hrl&quot;). -export([start_link/1, init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]). %% ==================================================================== %% API functions %% ==================================================================== -export([request_table/1, create_table/2, create_table/3, update_pid/3]). request_table(TableId) -&gt; gen_server:call(?MODULE, {tbl_request, TableId}). create_table(TableId, TblOpts) -&gt; create_table(TableId, TblOpts, []). create_table(TableId, TblOpts, HeirData) -&gt; gen_server:call(?MODULE, {tbl_create, TableId, TblOpts, HeirData}). update_pid(TableId, Pid, HeirData) -&gt; case process_info(Pid, registered_name) of {registered_name, ?MODULE} -&gt; ets:setopts(TableId, {heir, Pid, HeirData}); _ -&gt; {error, eperm} end. %% ==================================================================== %% Behavioural functions %% ==================================================================== start_link(Pid) when is_pid(Pid) -&gt; gen_server:start_link({local, ?MODULE}, ?MODULE, Pid, []). %% ==================================================================== %% Framework Functions %% ==================================================================== %% init/1 %% ==================================================================== init(FallbackPID) -&gt; FallbackPID ! {give_away,{?MASTER_TABLE, self()}}, {ok, FallbackPID}. %% handle_call/3 %% ==================================================================== handle_call({tbl_request, TableId}, {Pid, _}, FallbackPID) -&gt; Me = self(), case ets:lookup(?MASTER_TABLE, TableId) of [{TableId, Me, Requestor, HeirData}] -&gt; case process_info(FallbackPID, registered_name) of {registered_name, Requestor} -&gt; ets:give_away(TableId, Pid, HeirData), {reply, {ok, TableId},FallbackPID}; _ -&gt; {reply, {error, eaccess}, FallbackPID} end; [] -&gt; {reply, {error, einval}, FallbackPID}; [{TableId, _, _, _}] -&gt; {reply, {error, ebusy}, FallbackPID} end; handle_call({tbl_create, TableId, TblOpts, HeirData}, {Pid, _}, FallbackPID) -&gt; Opts = proplists:delete(heir, proplists:delete(named_table, TblOpts)), Requestor = case process_info(Pid, registered_name) of {registered_name, Module} -&gt; Module; _ -&gt; [] end, Reply = try ets:new(TableId,[named_table | [ {heir, self(), HeirData} | Opts]]), ets:insert(?MASTER_TABLE, {TableId, Pid, Requestor, HeirData}), ets:give_away(TableId, Pid, HeirData) catch _:_ -&gt; case ets:info(TableId) of undefined -&gt; continue; _ -&gt; ets:delete(TableId) end, ets:delete(?MASTER_TABLE, TableId), {error, ecanceled} end, {reply, Reply, FallbackPID}. %% handle_info/2 %% ==================================================================== handle_info({'ETS-TRANSFER', ?MASTER_TABLE, _, _}, FallbackPID) -&gt; [{?MODULE, OldPid}] = ets:lookup(?MASTER_TABLE, ?MODULE), ets:foldl(fun xfer_state/2,OldPid,?MASTER_TABLE), {noreply, FallbackPID}; handle_info({'ETS-TRANSFER', TableId, _, _}, FallbackPID) -&gt; ets:update_element(?MASTER_TABLE, TableId,{2, self()}), {noreply, FallbackPID}. %% handle_cast/2 %% ==================================================================== handle_cast(initialize, FallbackPID) -&gt; ?MASTER_TABLE = ets:new(?MASTER_TABLE,[named_table, set, private, {heir, FallbackPID, []}]), ets:insert(?MASTER_TABLE, {?MODULE, self()}), {noreply, FallbackPID}. %% Placeholders %% ==================================================================== terminate(_, _) -&gt; ok. code_change(_, FallbackPID, _) -&gt; {ok, FallbackPID}. %% ==================================================================== %% Internal Functions %% ==================================================================== xfer_state({TableId, OldPid, _, _}, OldPid) -&gt; ets:delete(?MASTER_TABLE, TableId), OldPid; xfer_state({TableId, Pid, _, HeirData}, OldPid) -&gt; Pid ! {'ETS-NEWMANAGER', self(), TableId, HeirData}, OldPid; xfer_state({?MODULE, OldPid}, OldPid) -&gt; ets:insert(?MASTER_TABLE, {?MODULE, self()}), OldPid. </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-25T21:06:30.370", "Id": "248428", "Score": "2", "Tags": [ "database", "erlang" ], "Title": "Erlang: Seeking advice on BEST practices with ETS table manager" }
248428
<p>I'm currently designing a class template to represent scientific notation or a floating-point number system. There are currently 4 distinct types: <code>BIN</code>, <code>DEC</code>, <code>OCT</code>, &amp; <code>HEX</code>. This could easily be expanded by the user.</p> <p>This class utilizes some of the power of <code>C++17</code> or greater such as <code>scoped-enums</code>, <code>lambdas</code>, <code>string_view</code>, and <code>regular-expressions</code>. With that being said, here is what the current state of my class looks like:</p> <p><strong>fpn.h</strong></p> <pre><code>#pragma once #include &lt;algorithm&gt; #include &lt;array&gt; #include &lt;cassert&gt; #include &lt;cstdint&gt; #include &lt;cmath&gt; #include &lt;iostream&gt; #include &lt;map&gt; #include &lt;optional&gt; #include &lt;regex&gt; #include &lt;string&gt; #include &lt;utility&gt; namespace /*your namespace here*/ { enum class BaseTy { BIN = 2, OCT = 8, DEC = 10, HEX = 16 }; static const std::regex bin_regex(R&quot;((-?[01]*)\.?([01]*))&quot;); static const std::regex oct_regex(R&quot;((-?[0-7]*)\.?([0-7]*))&quot;); static const std::regex dec_regex(R&quot;((-?[0-9]*)\.?([0-9]*))&quot;); static const std::regex hex_regex(R&quot;((-?[0-9a-fA-F]*)\.?([0-9a-fA-F]*))&quot;); static const std::regex bin_exp_regex(R&quot;(-?[01]*)&quot;); static const std::regex oct_exp_regex(R&quot;(-?[0-7]*)&quot;); static const std::regex dec_exp_regex(R&quot;(-?[0-9]*)&quot;); static const std::regex hex_exp_regex(R&quot;(-?[0-9a-fA-F]*)&quot;); static const std::map&lt;BaseTy, std::regex&gt; ValidDigitSets = { {BaseTy::BIN, bin_regex}, {BaseTy::OCT, oct_regex}, {BaseTy::DEC, dec_regex}, {BaseTy::HEX, hex_regex} }; static const std::map&lt;BaseTy, std::regex&gt; ValidExponentSets = { {BaseTy::BIN, bin_exp_regex}, {BaseTy::OCT, oct_exp_regex}, {BaseTy::DEC, dec_exp_regex}, {BaseTy::HEX, hex_exp_regex} }; static const auto match = [](const std::string&amp; digits, const std::regex&amp; regex) -&gt; bool { std::smatch base_match; return std::regex_match(digits, base_match, regex); }; template&lt;BaseTy BASE = BaseTy::DEC&gt; class Fpn { public: const uint16_t Base = static_cast&lt;uint16_t&gt;(BASE); // Member variables are public for now while designing this class. // Eventually they'll be made private with functions to view // their current values. There will not be any modifying functions. // This is where the copy constructor and assignment - operator=() // will come into play. I'm not sure if I'm going to use move // semantics or not. I might just stick with the rule of 0 // since there is no dynamic memory being explicitly used or any kind // of memory or resource management, however, I may still have to // define the copy constructor and assignment operator public: /*private:*/ std::string digits_{ &quot;0&quot; }; int64_t integral_value_{ 0 }; uint64_t decimal_value_{ 0 }; int64_t exponent_{1}; size_t decimal_location_{1}; public: Fpn() = default; Fpn(const std::string_view digit_sequence, const std::string_view exponent = &quot;&quot;) { std::cmatch digit_match; if (!std::regex_match(digit_sequence.data(), digit_match, ValidDigitSets.at(BASE))) { throw std::runtime_error(&quot;invalid digit sequence&quot;); } // Assert to make sure that the input has the correct character sets assert( (match(exponent.data(), ValidDigitSets.at(BASE))) &amp;&amp; &quot;invalid character sequence entered&quot; ); // if exponent is empty we can treat this as a value raised to the 1st power exponent_ = exponent.empty() ? 1 : std::stoi(exponent.data(), nullptr, static_cast&lt;int&gt;(BASE)); if (exponent_ == 0) { digits_ = { &quot;1&quot; }; integral_value_ = 1; decimal_value_ = 0; decimal_location_ = 1; return; } // Set the digits_ member value... digits_ = digit_sequence.data(); decimal_location_ = digit_match[1].length(); if (digit_match[1].length() != 0) { integral_value_ = std::stoi(digit_match[1].str().c_str(), nullptr, static_cast&lt;int&gt;(BASE)); } if (digit_match[2].length() != 0) { decimal_value_ = std::stoi(digit_match[2].str().c_str(), nullptr, static_cast&lt;int&gt;(BASE)); } } template &lt;typename OS&gt; friend OS&amp; operator &lt;&lt; (OS&amp; os, const Fpn&amp; fpn) { return os &lt;&lt; &quot;digits{&quot; &lt;&lt; fpn.digits_ &lt;&lt; &quot;}\n\t&quot; &lt;&lt; &quot;integral = &quot; &lt;&lt; fpn.integral_value_ &lt;&lt; &quot;\n\t&quot; &lt;&lt; &quot;decimal = &quot; &lt;&lt; fpn.decimal_value_ &lt;&lt; &quot;\n\t&quot; &lt;&lt; &quot;dec loc = &quot; &lt;&lt; fpn.decimal_location_ &lt;&lt; &quot;\n\t&quot; &lt;&lt; &quot;exponent = &quot; &lt;&lt; fpn.exponent_ &lt;&lt; &quot;\n\n&quot;; } }; } // namespace /*your namespace*/ </code></pre> <p>Here is the driver program that uses the above class:</p> <p><strong>main.cpp</strong></p> <pre><code>#include &quot;fpn.h&quot; int main() { try { // using namespace /*your namespace*/; Fpn large(&quot;314195.2&quot;); Fpn small(&quot;1.24&quot;); Fpn sample(&quot;420&quot;); std::cout &lt;&lt; &quot;large:\n\t&quot; &lt;&lt; large; std::cout &lt;&lt; &quot;small:\n\t&quot; &lt;&lt; small; std::cout &lt;&lt; &quot;sample:\n\t&quot; &lt;&lt; sample; std::cout &lt;&lt; &quot;bin:\n\t&quot; &lt;&lt; Fpn&lt;BaseTy::BIN&gt;(&quot;10.11&quot;); std::cout &lt;&lt; &quot;octal:\n\t&quot; &lt;&lt; Fpn&lt;BaseTy::OCT&gt;(&quot;17&quot;); std::cout &lt;&lt; &quot;hex:\n\t&quot; &lt;&lt; Fpn&lt;BaseTy::HEX&gt;(&quot;2A&quot;); } catch (const std::exception&amp; e) { std::cerr &lt;&lt; e.what() &lt;&lt; std::endl; return EXIT_FAILURE; } return EXIT_SUCCESS; } </code></pre> <p>Here is the generated output for simple basic cases:</p> <p><strong>Output</strong></p> <pre><code>large: digits{314195.2} integral = 314195 decimal = 2 dec loc = 6 exponent = 1 small: digits{1.24} integral = 1 decimal = 24 dec loc = 1 exponent = 1 sample: digits{420} integral = 420 decimal = 0 dec loc = 3 exponent = 1 bin: digits{10.11} integral = 2 decimal = 3 dec loc = 2 exponent = 1 octal: digits{17} integral = 15 decimal = 0 dec loc = 2 exponent = 1 hex: digits{2A} integral = 42 decimal = 0 dec loc = 2 exponent = 1 </code></pre> <hr> <p>I have not tested the <code>exponent</code> part just yet and I have not implemented any of the arithmetic or logical operators. However, the class appears to be working as expected.</p> <hr> <p>The overall concept of this class is that it is not just fixed around a floating-point number that is fixed to a specific number system such as <code>Decimal</code>. The idea here is that it should be flexible for any number system... <code>Log2 - Binary</code>, <code>Log8 - Octal</code>, <code>Log10 - Decimal</code>, <code>Log16 - Hexadecimal</code>, <code>LogX - Polynomial</code>, etc.</p> <p>There are four predefined types to this library. However, the user has the capability of extending this to any <code>LogX</code> number system by adding in their type to the <code>enumerated class</code>, updating the predefined <code>regular expressions</code> and their equivalent <code>static const map</code>s. The class itself should automatically handle the rest.</p> <hr> <p>As for the structure of the representation of the numbering systems, the following applies for all types:</p> <p>The left-hand side of the <code>.</code> is the integral part, the right-hand side of the <code>.</code> up to the <code>^</code> is the decimal part which is represented by the <code>1st</code> <code>string_view</code> passed into the constructor, and everything to the right of the <code>^</code> is the exponent which is represented by the <code>2nd</code> <code>string_view</code> passed into the constructor.</p> <p>Here are some examples:</p> <ul> <li>Binary: <ul> <li>1011.1101^1011</li> </ul> </li> <li>Hexadecimal <ul> <li>AF2C.B2AB^BA3F</li> </ul> </li> </ul> <p>The class will calculate the integral and decimal values as well as the decimal point location or position. The exponent is handled separately in which I have yet to implement it to populate the internal member variable. The class is in its early stage so it is far from complete. This is now where I'm at within the design decisions...</p> <hr> <p>From a design perspective, I am interested in your thoughts, concerns, and feedback.</p> <ul> <li>Are there any code smells?</li> <li>Does it seem to be modular and portable?</li> <li>Is it generic and reusable?</li> <li>Does it express intent and is it readable?</li> <li>Does it exhibit the ability to be computationally efficient?</li> <li>What kind of improvements can be made?</li> <li>Are there any corner cases or gotchas that I'm missing or overlooking?</li> <li>Even just personal feedback, opinions, or suggestions are welcomed.</li> </ul> <p>These are the things I'd like to have answered or looked at before I continue to add any &quot;functionality&quot; to this class.</p> <hr> <p><strong>Edit</strong></p> <p><em>Note:</em> Outside of the class I have two sets of <code>regular expressions</code> one for the sequence of digits and another for the exponent. Since this is in the early stages of development, I'm restricting exponents to be only integral values to keep things simple. In a future version, I may extend this to where the exponents could also be represented by <code>floating-point</code> values such as <code>12.34^5.6</code>. In that case, then only the first set of <code>regex</code> would be needed where the second set might be considered redundant. This is just an additional note to the reader.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-27T20:02:32.337", "Id": "486839", "Score": "1", "body": "The only minor nitpick I can think of is to use `std::` prefix for fix-length integers." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-25T23:25:51.993", "Id": "248432", "Score": "3", "Tags": [ "c++", "strings", "regex", "c++17", "number-systems" ], "Title": "Early Stages of floating point class template in C++" }
248432
<p>I have a component that displays a bunch of selectable options in a single row. It takes a <code>pageSize</code> prop from the parent component due to responsiveness requirements.</p> <p>If the <code>pageSize</code> prop ever changes, I need to reset the <code>currentPage</code> (currently active page), which is held in state, to 0.</p> <pre><code>class OptionsRow extends React.PureComponent { state = { currentPage: 0 } ... static getDerivedStateFromProps(props, state) { // Reset page on pageSize change return { currentPage: props.pageSize === state.prevPageSize ? state.currentPage : 0, prevPageSize: props.pageSize } } ... } </code></pre> <p>This code works as intended.</p> <p>The reason I'm asking for a review is that React in it's documentation warns against <code>getDerivedStateFromProps</code> so I'm not sure if this is a correct usage. In order to avoid derived state, it recommends making the component completely controlled/uncontrolled, so I should lift the <code>currentPage</code> up to the parent component. But is this really necessary? Is something wrong with my solution except for &quot;<a href="https://reactjs.org/docs/react-component.html#static-getderivedstatefromprops" rel="nofollow noreferrer">verbose code</a>&quot;?</p> <p>Thank you!</p>
[]
[ { "body": "<p>There is a small and subtle issue with your usage of <code>getDerivedStateFromProps</code>.</p>\n<blockquote>\n<p><code>getDerivedStateFromProps</code> is invoked right before calling the render\nmethod, both on the initial mount and <em><strong>on subsequent updates</strong></em>. It should\nreturn an object to update the state, or <em><strong>null to update nothing</strong></em>.</p>\n</blockquote>\n<p>and</p>\n<blockquote>\n<p>Note that this method is fired on every render, regardless of the cause.</p>\n</blockquote>\n<p>Your implementation returns a new state object every render regardless, but it should return null when nothing needs to be updated. By returning a new state object each render then unnecessary re-renders may occur in children components if passed any values from this component's state as they would fail shallow object comparison.</p>\n<pre><code>class OptionsRow extends React.PureComponent {\n state = {\n currentPage: 0\n }\n\n ...\n\n static getDerivedStateFromProps(props, state) {\n if (props.pageSize !== state.prevPageSize) {\n // Reset page on pageSize change\n return {\n currentPage: 0,\n prevPageSize: props.pageSize\n }\n }\n\n // Nothing changed, return null to keep existing state\n return null;\n }\n\n ...\n\n}\n</code></pre>\n<p><em><strong>However</strong></em>, in 3+ years working with react I've not ever had any compelling reason to reach for <code>getDerivedStateFromProps</code> and the docs even specify</p>\n<blockquote>\n<p>This method exists for rare use cases where the state depends on\nchanges in props <em><strong>over time</strong></em>.</p>\n</blockquote>\n<p>The last bit bolded is the important bit. Your component's behavior appears to simply be an effect of a prop updating, i.e. a side-effect to reset state, and <em>could</em> be implemented via the <code>componentDidUpdate</code> lifecycle method.</p>\n<h2>Solution 1 - Bronze</h2>\n<pre><code>class OptionsRow extends React.PureComponent {\n state = {\n currentPage: 0,\n }\n\n ...\n\n componentDidUpdate(prevProps, prevState) {\n // Reset page on pageSize change\n if (this.props.pageSize !== prevState.prevPageSize) {\n this.setState({\n currentPage: 0,\n prevPageSize: this.props.pageSize,\n });\n }\n }\n\n ...\n\n}\n</code></pre>\n<p>But notice now that the state <code>currentPage</code> only needs to be reset when <code>props.pageSize</code> updates, so you can directly compare current and previous props and drop the storage of the &quot;last&quot; pageSize in local component state.</p>\n<h2>Solution 2 - Silver</h2>\n<pre><code>class OptionsRow extends React.PureComponent {\n state = {\n currentPage: 0,\n }\n\n ...\n\n componentDidUpdate(prevProps) {\n // Reset page on pageSize change\n if (this.props.pageSize !== prevProps.pageSize) {\n this.setState({ currentPage: 0 });\n }\n }\n\n ...\n\n}\n</code></pre>\n<p>There is still room for improvement though, using the third bullet point from the docs.</p>\n<blockquote>\n<p>If you want to <strong>“reset” some state when a prop changes</strong>, consider either\nmaking a component fully controlled or <a href=\"https://reactjs.org/blog/2018/06/07/you-probably-dont-need-derived-state.html#recommendation-fully-uncontrolled-component-with-a-key\" rel=\"nofollow noreferrer\">fully uncontrolled with a key</a>\ninstead.</p>\n</blockquote>\n<p>What this means is you can completely forego the <code>getDerivedStateFromProps</code> <em><strong>and</strong></em> <code>componentDidUpdate</code> logic to check and compare the props' <code>pageSize</code> value and simply use a react key that updates when the pageSize does.</p>\n<blockquote>\n<p>When a <code>key</code> changes, React will <a href=\"https://reactjs.org/docs/reconciliation.html#keys\" rel=\"nofollow noreferrer\"><em>create</em> a new component instance rather\nthan <em>update</em> the current one</a>.</p>\n</blockquote>\n<h2>Solution 3 - Gold</h2>\n<pre><code>&lt;OptionsRow key={pageSize} pageSize={pageSize} /&gt;\n</code></pre>\n<p><a href=\"https://codesandbox.io/s/mixing-controlled-uncontrolled-behaviour-with-getderivedstatefromprops-lgog5?fontsize=14&amp;hidenavigation=1&amp;module=%2Fsrc%2FApp.js&amp;theme=dark\" rel=\"nofollow noreferrer\"><img src=\"https://codesandbox.io/static/img/play-codesandbox.svg\" alt=\"Edit mixing-controlled-uncontrolled-behaviour-with-getderivedstatefromprops\" /></a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-29T21:35:12.457", "Id": "487073", "Score": "0", "body": "Perfect! Thank you for explanation. I completely forgot about the `key` thing, very nice solution indeed." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-29T05:44:51.153", "Id": "248602", "ParentId": "248433", "Score": "1" } } ]
{ "AcceptedAnswerId": "248602", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-25T23:39:42.307", "Id": "248433", "Score": "3", "Tags": [ "javascript", "react.js" ], "Title": "Mixing controlled/uncontrolled behaviour with `getDerivedStateFromProps`" }
248433
<p>I am new to coding and looking for a few pointers on how I can improve my first project.</p> <p>At work, I often need to create Medicare Beneficiary Identifiers (MBI) when creating test patients with Medicare coverage, and have to look up the format every time. I thought creating an MBI generator would be a great first project. Doing a quick search, I found a similar project on this site (which is what lead me here), but the questioner wants to create 10,000 records, whereas I may only need one or two MBIs at a time (their question can be found here: <a href="https://codereview.stackexchange.com/questions/230430/generating-sequential-alphanumeric-values-that-match-a-certain-pattern">Sequential MBI generator</a>). Being new and not understanding all of the code, I was nervous to follow in their path and end up with a ton of records, so I actually followed an example of a random password generator and tweaked it to meet my needs. As the outcome is vastly different from the linked example and seems verbose, I wondered if anyone with more experience would be able to give me some pointers to get me off to improve my work.</p> <pre><code>#MBI is 11 characters in the following format # 1 - 2 - 3 - 4 - 5 - 6 - 7 - 8 - 9 - 10 - 11 # C - A - AN- N - A - AN- N - A - A - N - N # C = Numeric 1 - 9 # N = Numeric 0 - 9 # A = Alphabetic A...Z; Not S, L, O, I, B, Z # AN = Either A or N import random letter = 'ACDEFGHJKMNPQRTUVWXY' # not = B, I, L, O, S, Z digit = str('0123456789') partdig = str('123456789') dig_let = digit + letter while 1: mbi_return = 1 mbi_need = int(input(&quot;How many MBI numbers do you need to generate?: &quot;)) for x in range(0,mbi_need): mbi = &quot;&quot; for x in range(0, mbi_return): mbi_char0 = random.choice(partdig) mbi_char1 = random.choice(letter) mbi_char2 = random.choice(dig_let) mbi_char3 = random.choice(digit) mbi_char4 = random.choice(letter) mbi_char5 = random.choice(dig_let) mbi_char6 = random.choice(digit) mbi_char7 = random.choice(letter) mbi_char8 = random.choice(letter) mbi_char9 = random.choice(digit) mbi_char10 = random.choice(digit) mbi = (mbi_char0 + mbi_char1 + mbi_char2 + mbi_char3 + mbi_char4 + mbi_char5 + mbi_char6 + mbi_char7 + mbi_char8 + mbi_char9 + mbi_char10) # I imagine this could be much cleaner print(mbi) </code></pre> <p>Thanks in advance!</p>
[]
[ { "body": "<p>Instead of <code>while 1:</code> please just use <code>while True</code>. <code>while 1:</code> is a throwback from <em>old</em> versions of C that didn't have <code>stdbool.h</code>. <code>while True:</code> is much most explicit a about what your intent is.</p>\n<hr />\n<p>At the top you have</p>\n<pre><code>letter = 'ACDEFGHJKMNPQRTUVWXY' # not = B, I, L, O, S, Z\ndigit = str('0123456789')\npartdig = str('123456789')\ndig_let = digit + letter\n</code></pre>\n<p>Python actually has built-ins for these:</p>\n<pre><code>from string import digits, ascii_uppercase\n\n# letter is the set of ascii characters minus B, I, L. . .\nletter = &quot;&quot;.join(set(ascii_uppercase) - {'B', 'I', 'L', 'O', 'S', 'Z'})\n# Just use digits instead of digit\npartdig = digits[1:] # Remove the first digit\ndig_let = digits + letter\n</code></pre>\n<p>That saves you from needing to type out each of the letters to include.</p>\n<p>Also note, even if <code>string.digits</code> didn't exist, you could have also defined <code>digit</code> as:</p>\n<pre><code>&gt;&gt;&gt; digit = &quot;&quot;.join(str(n) for n in range(0, 10))\n&gt;&gt;&gt; digit\n'0123456789'\n</code></pre>\n<hr />\n<p>Also, <a href=\"https://www.python.org/dev/peps/pep-0008/#function-and-variable-names\" rel=\"nofollow noreferrer\">all variable names here should be lowercase, separated by underscores</a>. <code>partdig</code> should be <code>part_dig</code>, or <code>part_digits</code>, or even better: <code>non_zero_digits</code>.</p>\n<p>I also think <code>letter</code> should be <code>letters</code>, since it's a collection of letters. It's a small change, but it lets your readers know that it's multiple letters, not just a single one.</p>\n<hr />\n<p>Watch your indentation:</p>\n<pre><code>mbi_need = int(input(&quot;How many MBI numbers do you need to generate?: &quot;))\n for x in range(0,mbi_need):\n</code></pre>\n<p>Especially in Python that matters a lot. If that was just a pasting error, it's a good idea to look over the code before posting just to double check that errors weren't introduced accidentally.</p>\n<p>You're using a odd 5-space indentation in the loop though, which is part of the problem. <a href=\"https://www.python.org/dev/peps/pep-0008/#indentation\" rel=\"nofollow noreferrer\">Please use 4-space indentation</a>.</p>\n<hr />\n<pre><code>for x in range(0,mbi_need):\n mbi = &quot;&quot;\n for x in range(0, mbi_return):\n</code></pre>\n<p>Both loops define a <code>x</code> variable! Since you never use <code>x</code> in either loop though, use <code>_</code> instead:</p>\n<pre><code>for _ in range(0,mbi_need):\n mbi = &quot;&quot;\n for _ in range(0, mbi_return):\n</code></pre>\n<p><code>_</code> is a convention that says &quot;I needed to create a name, but don't need the variable&quot;, which is the case here.</p>\n<hr />\n<pre><code>range(0, mbi_need)\n</code></pre>\n<p><code>0</code> is the implicit start; it's not necessary to specify it if you only otherwise need to specify the ending number. Just write:</p>\n<pre><code>range(mbi_need)\n</code></pre>\n<hr />\n<pre><code>mbi_char0 = random.choice(partdig)\nmbi_char1 = random.choice(letter)\nmbi_char2 = random.choice(dig_let)\nmbi_char3 = random.choice(digits)\n. . .\n</code></pre>\n<p>Whenever you find yourself creating many similar variables, and you're differentiating them by putting numbers in the name, stop! You should likely be using a list instead. Because the make-up of the MBIs doesn't follow an easy pattern, fixing this isn't <em>super</em> straightforward, but it's still possible. First, I'd create a list holding the order of <code>partdig</code>, <code>letter</code>, <code>dig_let</code>, <code>digits</code>. . . which will define the order of the different character types:</p>\n<pre><code>mbi_pattern = [non_zero_digits, letters, digit_letters, digits,\n letters, digit_letters, digits, letters,\n letters, digits, digits]\n</code></pre>\n<p>This looks ugly, but it will clean up the code later. Sometimes all you can do is move the ugly bulk to the side. Once you've defined that list, creating a MBI is trivial and tiny:</p>\n<pre><code>mbi = &quot;&quot;.join(random.choice(part) for part in mbi_pattern)\nprint(mbi)\n</code></pre>\n<p>Get each of the part sets, generate a random character from each of them, then join them into a string.</p>\n<hr />\n<p>Your inner</p>\n<pre><code>for _ in range(mbi_return):\n</code></pre>\n<p>loop doesn't appear to be doing anything. It seems like it's doing a similar job as the other loop, except it will always be <code>range(1)</code>, which will only run once, which means it isn't really a loop. I got rid of it because it isn't doing anything except complicating the code.</p>\n<p>The same can be said about the <code>while True</code> as well. You want to generate 10000 codes, repeatedly, forever? The <code>while True</code> loop will never end since you never <code>break</code> from it. I also got rid of it because it is also complicating the code without good reason.</p>\n<hr />\n<pre><code> mbi = &quot;&quot;\n</code></pre>\n<p>This isn't necessary. Even if you needed <code>mbi</code> in the outer scope, loops in Python don't create scopes like they do in other languages. <code>mbi</code> &quot;defined&quot; inside the loop can be accessed from outside of the loop.</p>\n<hr />\n<p>In your remaining loop, you're creating an <code>mbi</code>, then just printing it. That doesn't allow you to do anything with the data though, like save it to file. It would be much cleaner to store the generated MBIs in a list so that they can potentially be used later. If you do that, your loop can be made into a list comprehension:</p>\n<pre><code>mbis = [&quot;&quot;.join(random.choice(part) for part in mbi_pattern)\n for _ in range(mbi_need)]\n</code></pre>\n<p>Each MBI is generated using the same generator expression as before, but now it's wrapped in a list comprehension to generate multiple.</p>\n<hr />\n<p>In the end, this is what I'm left with:</p>\n<pre><code>import random\nfrom string import digits, ascii_uppercase\n\nletters = &quot;&quot;.join(set(ascii_uppercase) - {'B', 'I', 'L', 'O', 'S', 'Z'})\nnon_zero_digits = digits[1:]\ndigit_letters = digits + letters\n\nmbi_pattern = [non_zero_digits, letters, digit_letters, digits,\n letters, digit_letters, digits, letters,\n letters, digits, digits]\n\nmbi_need = int(input(&quot;How many MBI numbers do you need to generate?: &quot;))\n\nmbis = [&quot;&quot;.join(random.choice(part) for part in mbi_pattern)\n for _ in range(mbi_need)]\n\nprint(&quot;\\n&quot;.join(mbis))\n</code></pre>\n<p>And its usage:</p>\n<pre><code>How many MBI numbers do you need to generate?: &gt;? 10\n5V70VK4JP28\n8Y12N77RC51\n9JM2JN8RQ38\n3X08DH7FH95\n3MH6Y49KU87\n6N70AC7MW75\n9A67A62TU38\n4A48C94QT38\n2NP7TY0DC65\n1GP8A57JQ27\n</code></pre>\n<hr />\n<p>As mentioned in the comment though, really, code should be tucked into functions. In larger programs, that eases testing and comprehension of your code.</p>\n<p>Here, you could have a function that generates a single MBI, then use it to generate a list of them. I also always have a <code>main</code> function that ties the whole program together so I can control the execution of the code easier.</p>\n<p>I also realized after I had my coffee that all the variables at the top are really constants, so they should be in UPPER_SNAKE_CASE.</p>\n<p>After those changes, I'm left with:</p>\n<pre><code>import random\nfrom string import digits, ascii_uppercase\n\nLETTERS = &quot;&quot;.join(set(ascii_uppercase) - {'B', 'I', 'L', 'O', 'S', 'Z'})\nNON_ZERO_DIGITS = digits[1:]\nDIGIT_LETTERS = digits + LETTERS\n\nMBI_PATTERN = [NON_ZERO_DIGITS, LETTERS, DIGIT_LETTERS, digits,\n LETTERS, DIGIT_LETTERS, digits, LETTERS,\n LETTERS, digits, digits]\n\n\ndef generate_mbi():\n return &quot;&quot;.join(random.choice(part) for part in MBI_PATTERN)\n\n\ndef main():\n mbi_need = int(input(&quot;How many MBI numbers do you need to generate?: &quot;))\n mbis = [generate_mbi() for _ in range(mbi_need)]\n print(&quot;\\n&quot;.join(mbis))\n \nif __name__ == '__main__':\n main()\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-26T17:43:46.863", "Id": "486721", "Score": "1", "body": "This is a very good review, indeed. One final improvement I would suggest either to the OP or to you, if you feel inclined to augment your answer: use functions. One to create a single MBI. The other to orchestrate the program: get user input and loop the needed number of times." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-26T17:51:33.057", "Id": "486723", "Score": "1", "body": "@FMc Yes. I completely agree with the use of functions here. I've started limiting that suggestion though to more \"developed\" programs where the benefits are much more obvious. I can certainly add something in though" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-26T20:38:42.683", "Id": "486746", "Score": "0", "body": "This is great! Thanks so much for the review! I knew there must be easier ways to address all of these issues (e.g., \"...(ascii_uppercase) - {B, I,..etc.}), but I am limited by my cursory knowledge after a week of studying the language. This gives me a huge head start in learning these concepts." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-26T20:48:42.343", "Id": "486748", "Score": "1", "body": "@LostAsHeat Glad to help. I'm not sure if you're familiar with them, but the code here is using [generator expressions](https://www.python.org/dev/peps/pep-0289/), which are similar to [list comprehensions](https://www.python.org/dev/peps/pep-0202/). If you haven't used either before, they're very useful constructs. [`join`](https://docs.python.org/3/library/stdtypes.html#str.join) is also extremely useful." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-26T14:19:19.240", "Id": "248463", "ParentId": "248438", "Score": "6" } } ]
{ "AcceptedAnswerId": "248463", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-26T06:04:05.593", "Id": "248438", "Score": "7", "Tags": [ "python", "beginner" ], "Title": "Improving a Medicare Beneficiary Identifier (MBI) generator" }
248438
<p>Good day. My code works but I think there is a better way to do this. Like string pattern or string manipulation. I'm not yet familiar with both terms.</p> <p>The goal is to get &quot;=A1-A2-B3-D4-WHATEVER STRING=&quot;. From array of strings.</p> <p>The code is :</p> <pre><code>string[] arr = { &quot;A1&quot;, &quot;A2&quot;, &quot;B3&quot;, &quot;D4&quot;, &quot;WHATEVER STRING&quot;}; // can be any string value string newString = &quot;=&quot;; for (int i = 0; i &lt; arr.Length; i++) { if (i == arr.Length-1) { newString += arr[i].ToString() + &quot;=&quot;; } else { newString += arr[i].ToString() + &quot;-&quot;; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-27T01:34:31.657", "Id": "486760", "Score": "1", "body": "To the reviewers: while not particularly well-written, I do think this question is simple enough that it can't be closed for Missing Review Context. Please notify me if you disagree." } ]
[ { "body": "<p>You should use <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.string.join?view=netcore-3.1#System_String_Join_System_String_System_String___\" rel=\"noreferrer\"><code>String.Join()</code></a> here. Its easier to read and shorter as well.</p>\n<p>Like</p>\n<pre><code>string[] arr = { &quot;A1&quot;, &quot;A2&quot;, &quot;B3&quot;, &quot;D4&quot;, &quot;WHATEVER STRING&quot; }; // can be any string value\nstring result = &quot;=&quot; + string.Join(&quot;-&quot;, arr) + &quot;=&quot;;\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-26T08:06:43.063", "Id": "248441", "ParentId": "248439", "Score": "5" } }, { "body": "<p>Another simpler and more universal way than the original code in the OP (without using <code>String.Join()</code>) would be</p>\n<pre><code>string[] arr = { &quot;A1&quot;, &quot;A2&quot;, &quot;B3&quot;, &quot;D4&quot;, &quot;WHATEVER STRING&quot;}; // can be any string value\nstring newString = &quot;&quot;;\nforeach (string elem in arr) {\n if(newString &lt;&gt; &quot;&quot;) {\n newString += &quot;-&quot;\n }\n newString += elem; // ToString() is not needed in this case\n}\nnewString = &quot;=&quot; + newString + &quot;=&quot;;\n</code></pre>\n<p>I often use that pattern in the <code>foreach</code> (or other kind of) loop to concatenate strings with a delimiter. This works in many programming languages, which don't offer the functionality of C#'s <code>String.Join()</code>, or also when you need some <code>ToString()</code> operation for the array elements (e.g. <code>int</code> values).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-26T14:31:42.557", "Id": "486677", "Score": "1", "body": "I am the downvoter and usually do not DV. (1) I strongly disagree that this is simpler. When the framework offers a short, performant method, one should favor it. `String.Join` is such a method, whereas some LINQ calls are not since they are not the best perfomers. (2) If you do this extra coding, you should use `StringBuilder` instead of re-creating each freakin' string with each small change." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-26T14:44:07.613", "Id": "486679", "Score": "1", "body": "@RickDavin 1. I didn't say that this is simpler than using `String.Join()` (I probably should clarify that). What I meant is that it's simpler and better readable than the OPs original approach 2. As mentioned this approach is quite universal and works with many programming languages (I have to work with a great variety of PLs professionally). 3. That said, not every programming language offers a class like `StringBuilder` either." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-26T08:08:45.667", "Id": "248442", "ParentId": "248439", "Score": "0" } } ]
{ "AcceptedAnswerId": "248441", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-26T07:44:02.117", "Id": "248439", "Score": "2", "Tags": [ "c#" ], "Title": "concatenate string, with different first and last iteration" }
248439
<p>I'm using PHP, I have a class that generates an id based on the calling class, so the id of the class won't change after it has been initialised, now I'm wondering which of my two methods is preferrable.</p> <ul> <li>Set the id in the constructor</li> <li>Generate the id when asked for</li> </ul> <pre class="lang-php prettyprint-override"><code>/* Set the id in the constructor */ abstract class Badge { protected $activities; protected $id; abstract public function check(); public function __construct(array $activities) { $this-&gt;activities = $activities; $this-&gt;id = $this-&gt;getId(); } public function getId(): string { $class = explode('\\', get_class($this)); $classWithoutNamespace = array_pop($class); $snakeCased = strtolower(preg_replace('/(?&lt;!^)[A-Z]/', '_$0', $classWithoutNamespace)); return &quot;{$snakeCased}_{$this-&gt;target}&quot;; } public function toArray(): array { return [ 'id' =&gt; $this-&gt;id, ]; } } </code></pre> <pre class="lang-php prettyprint-override"><code>/* Generate the id when asked for */ abstract class Badge { protected $activities; abstract public function check(); public function __construct(array $activities) { $this-&gt;activities = $activities; } public function getId(): string { $class = explode('\\', get_class($this)); $classWithoutNamespace = array_pop($class); $snakeCased = strtolower(preg_replace('/(?&lt;!^)[A-Z]/', '_$0', $classWithoutNamespace)); return &quot;{$snakeCased}_{$this-&gt;target}&quot;; } public function toArray(): array { return [ 'id' =&gt; $this-&gt;getId(), ]; } } <span class="math-container">```</span> </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-26T12:42:23.757", "Id": "486665", "Score": "0", "body": "Your code seems to reference undefined member property `$this->target`. Also please provide some code that shows how the class is used." } ]
[ { "body": "<p>I would go with lazy loading. Generate the id when requested</p>\n<pre><code>private $id;\n\npublic function getId()\n{\n if ($this-&gt;id === null) {\n $this-&gt;id = //your logic to generate the id here\n }\n return $this-&gt;id;\n}\n</code></pre>\n<p>and don't use anywhere else <code>$this-&gt;id</code> even inside the class. Use <code>$this-&gt;getId()</code> everywhere.</p>\n<p>using <code>$this-&gt;getId()</code> everywhere will ensure that you always get the generated id (the same one everytime) and you are sure you don't get the <code>null</code> initial value.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-26T11:14:45.920", "Id": "248451", "ParentId": "248445", "Score": "4" } }, { "body": "<p>It seems that the process of generating an ID is going to be the same for all descendants, it will only differ by the actual class used. So how about doing the work outside the class?</p>\n<pre><code>abstract class Badge\n{\n private string $id;\n protected array $activities;\n \n final public function __construct(string $id, array $activities)\n {\n $this-&gt;id = $id;\n $this-&gt;activities = $activities;\n }\n\n public function getId(): string\n {\n return $this-&gt;id;\n }\n\n public function toArray(): array\n {\n return ['id' =&gt; $this-&gt;id];\n }\n}\n\n/**\n * @template T of Badge\n * @param class-string&lt;T&gt; $class\n * @param array $activities\n * @return T\n */\nfunction createBadge(string $class, array $activities, string $target)\n{\n $parts = explode('\\\\', get_class($this));\n $classWithoutNamespace = array_pop($parts);\n $snakeCased = strtolower(preg_replace('/(?&lt;!^)[A-Z]/', '_$0', $classWithoutNamespace));\n\n return new $class(&quot;{$snakeCased}_{$target}&quot;, $activities);\n}\n\n$badgeX = createBadge(BadgeX::class, $activitiesX, $targetX);\n$badgeY = createBadge(BadgeY::class, $activitiesY, $targetY);\n</code></pre>\n<p>Notice that the <code>$target</code> comes from your original code where it is referenced but never defined. I don't know what it is or how to treat it. Depending on the context my review could have pointed out that the <code>abstract class</code> may be a sign of bad design. But unless you provide more context, I cannot say...</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-26T12:49:15.303", "Id": "248456", "ParentId": "248445", "Score": "1" } } ]
{ "AcceptedAnswerId": "248451", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-26T09:21:19.417", "Id": "248445", "Score": "0", "Tags": [ "php", "constructor" ], "Title": "Set id in constructor, or generate it when asked for?" }
248445
<p>It's a web project. The code is working. The question is a design pattern question to write code that's more elegant, you know.</p> <p>I've created a <a href="https://codepen.io/jhon_se/pen/eYZvXbb" rel="nofollow noreferrer">Codepen</a> of this question.</p> <p>I created a <code>css</code> grid WITHOUT using 'grid' but using <code>float and clear</code>. I know such project works better written in React but it's just a try. The grid I'm creating is entirely recreated when calling the <code>render(world)</code> method.</p> <p>I'm not using any HTML outside of javascript (typescript). I'm only using 4 CSS classes:</p> <pre><code>.block-first, .block-lasts { width: 20px; height: 20px; border-radius: 20px; float: left; } .block-first { clear: both; } .image-in-block { width: 20px; height: 20px; } .container { } </code></pre> <p>In the grid are square blocks of equal size being 1- a uniformly colored block or 2- a block containing an image. So I first fill up a <code>matrix 20x20</code> of instances of classes that <code>implements a IBlock interface</code> containing a <code>getProperty()</code> method. Those classes are 1- <code>ColorBlock</code> or 2- <code>ImageBlock</code>. Below are these <code>classes and the interface</code>:</p> <pre><code>interface IBlock { getProperty() : string; } class ImageBlock implements IBlock{ url: string; constructor(url: string) { this.url = url; } getProperty() : string { return this.url; } } class ColorBlock implements IBlock{ color: string; constructor(hexColor: string) { this.color = hexColor; } getProperty() : string { return this.color; } } </code></pre> <p>My problem is that I need to use different code to render each. For the ColorBlock I'm going with a colored <code>div</code> with <code>background: '#ff00ff';</code> But for the ImageBlock I'm going with a nested <code>img tag</code> instead of a <code>background-image: url('https://...');</code>.</p> <p>For distinguishing between the different classes, I'm using <code>object_instance.constructor.name</code>, I think that's the whole problem.</p> <p>Now the rest of my code:</p> <p>Matrix prepping:</p> <pre><code>const world = new Array(20); for(let i=0; i&lt;20; i++) { world[i] = new Array(20); world[i].fill(new ColorBlock('#ff00ff')); } </code></pre> <p>The function rendering each block as <code>ColorBlock or ImageBlock</code>:</p> <pre><code>function html_process_image_or_color_block(dom, block_instance) { const html_block = dom; const block = block_instance; const block_property = block.getProperty(); switch (block.constructor.name) { case 'ImageBlock': const image_tag = document.createElement('img'); image_tag.src = block_property; image_tag.classList.add('image-in-block'); html_block.appendChild(image_tag); break; case 'ColorBlock': html_block.setAttribute('style', `background: ${block_property};`) break; default: break; } // return html_block; } </code></pre> <p>And finally the <code>render(world)</code> function that uses the <code>20x20 Matrix</code> and the above function:</p> <pre><code>function render(world) { const html_container = document.createElement('div'); html_container.classList.add('container'); for(let i=0; i&lt;20; i++) { //code for rendering first left most block const html_first_block = document.createElement('div'); html_first_block.classList.add('block-first'); const first_block = world[i][0]; html_process_image_or_color_block(html_first_block, first_block); html_container.appendChild(html_first_block); //code for rendering all other blocks on its right for(let j=1; j&lt;20; j++) { const html_block = document.createElement('div'); html_block.classList.add('block-lasts'); const block = world[i][j]; html_process_image_or_color_block(html_block, block); html_container.appendChild(html_block); } } document.body.innerHTML = ''; document.body.appendChild(html_container); } render(world); </code></pre> <p>In my opinion the code is terrible :) and I appreciate all your time and effort!</p> <p><a href="https://codepen.io/jhon_se/pen/eYZvXbb" rel="nofollow noreferrer">Codepen</a></p>
[]
[ { "body": "<p>So I know there gotta be a better way but I found a satisfying one:</p>\n<pre><code>interface IBlock {\n getProperty() : string;\n render() : Object;\n}\n\nclass ColorBlock {\n color: string;\n constructor(color: string) {\n this.color = color;\n }\n getProperty() : string {\n return this.color;\n }\n render(isFirstBlock: boolean) : Object/*Well it's an HTML dom object*/ {\n const tag = document.createElement('div');\n isFirstBlock? tag.classList.add('block-first') : tag.classList.add('block-lasts');\n tag.setAttribute('style', `background: ${this.color};`);\n return tag;\n }\n}\n\nclass ImageBlock {\n url: string;\n constructor(url: string) {\n this.url = url;\n }\n getProperty() : string {\n return this.url;\n }\n render(isFirstBlock: boolean) : Object/*Well it's an HTML dom object*/ {\n const tag = document.createElement('div');\n isFirstBlock? tag.classList.add('block-first') : tag.classList.add('block-lasts');\n const image_tag = document.createElement('img');\n image_tag.src = this.url;\n image_tag.classList.add('image-block');\n tag.appendChild(image_tag);\n return tag;\n }\n}\n\nconst global_x = 10;\nconst global_y = 10;\n\nconst world = new Array&lt;Array&lt;IBlock&gt;&gt;(global_x);\n\nconst default_ColorBlock = new ColorBlock('#ff00ff');\n\nfor(let i=0; i&lt;global_x; i++) {\n world[i] = new Array&lt;IBlock&gt;(global_y);\n world[i].fill(default_ColorBlock);\n}\n\nfunction render(world: Array&lt;Array&lt;IBlock&gt;&gt;) {\n const html_container = document.createElement('div');\n for(let i=0; i&lt;global_x; i++) {\n html_container.appendChild(world[i][0].render(true));\n for(let j=0; j&lt;global_y; j++) {\n html_container.appendChild(world[i][j].render(false));\n }\n }\n document.body.innerHTML = '';\n document.body.appendChild(html_container);\n}\n\nrender(world);\n</code></pre>\n<p>CSS being:</p>\n<pre><code>:root {\n --global-width: 20px;\n --global-height: 20px;\n}\n\n.block-first, .block-lasts {\n width: var(--global-width);\n height: var(--global-height);\n border-radius: 50%;\n float: left;\n}\n\n.block-first {\n clear: both;\n}\n\n.image-block {\n width: var(--global-width);\n height: var(--global-height);\n}\n</code></pre>\n<p>And no HTML outside of javascript (typescript) .</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-26T15:31:28.370", "Id": "248468", "ParentId": "248448", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-26T10:08:15.523", "Id": "248448", "Score": "3", "Tags": [ "javascript", "object-oriented", "design-patterns", "css", "typescript" ], "Title": "Typescript design pattern for rendering different objects with similarities" }
248448
<p>While working on the following leetcode problem: <a href="https://leetcode.com/problems/top-k-frequent-elements/" rel="nofollow noreferrer">https://leetcode.com/problems/top-k-frequent-elements/</a> I used a Priority Queu implementation in Ruby. I have learned how to implement a Priority Queu in Java in <a href="https://algs4.cs.princeton.edu/24pq/" rel="nofollow noreferrer">Robert Sedgewick's Algorithms book</a>. When inserting Hashes into the Priority Queue for example <code>{ 1 =&gt; 3}</code> this made me refactored the Priotity's Queue in such a way so I was able to compare two hashes values.</p> <p>The implementation is much straight forward when your dealing with numbers and characters but it made me wonder what would be the best implementation with using objects or hashes.</p> <pre><code>def top_k_frequent(nums, k) ans = [] h = Hash.new(0) nums.each do |num| h[num] += 1 end heap = Heap.new h.each do |k,v| heap.insert({k =&gt; v}) end k.times do a = heap.del_max ans.push(a.keys[0]) end ans end class Heap def initialize @n = 0 @pq = [] end def insert(v) @pq[@n += 1] = v swim(@n) end def swim(k) while k &gt; 1 &amp;&amp; less((k / 2).floor, k) swap((k / 2).floor, k) k = k/2 end end def swap(i, j) temp = @pq[i] @pq[i] = @pq[j] @pq[j] = temp end def less(i, j) @pq[i].values[0] &lt; @pq[j].values[0] end def del_max max = @pq[1] swap(1, @n) @n -= 1 @pq[@n + 1] = nil sink(1) max end def sink(k) while 2 * k &lt;= @n j = 2 * k if !@pq[j + 1].nil? j += 1 if j &gt; 1 &amp;&amp; @pq[j].values[0] &lt; @pq[j + 1].values[0] end break if !less(k, j) swap(k, j) k = j end end end </code></pre> <p>There are a few things that come to mind that I wish to probably learn. Keep in mind that I would like to prepare for algorithm interviews and so I would like to avoid as much synthetic sugar as possible.</p> <ul> <li><code>@pq[j].values[0]</code> check for example how to get to a hash values I need to use <code>values[0]</code> is there a better way for this?</li> <li>There are 3 loops in the <code>top_k_frequent</code> method. How would yo go about optimizing this implementation?</li> <li><code>a.keys[0]</code> notice how I get the key of the element in Ruby is there a cleaner way of doing this?</li> </ul> <p>This brought to my attention that in case of dealing with more complex objects the Priority Queue's API might be needed to refactored to be able to compare between objects, what would be the best way of dealing with that? Would creating another class which you pass to the Priority Queue would be a better solution?</p> <p>Here is the implementation I have for Priority Queue's prior to editing to deal with hashes.</p> <pre><code>class Heap attr_accessor :pq, :n def initialize @pq = [] # heap order complete binary tree @n = 0 # in pq[1..N] with pq[0] unused end def empty? @n == 0 end def size @n end def insert(v) @pq[@n += 1] = v swim(@n) # position in heap end # trickleup def swim(k) while k &gt; 1 &amp;&amp; less((k / 2).floor, k) # parent: k/2 parent less than child? swap((k/2).floor, k) k = k / 2 end end def del_max max = @pq[1] # Retrieve max key from top. swap(1, @n) # Exchange with last item. @n -= 1 @pq[@n + 1] = nil # Avoid loitering. max added to end on swap make nil sink(1) # Restore HEAP property max end # Trickledown def sink(k) while 2 * k &lt;= @n j = 2 * k # child if !@pq[j + 1].nil? # check if there is a right child j += 1 if j &gt; 1 &amp;&amp; @pq[j] &lt; @pq[j + 1] # if left child less than right child end break if @pq[k] &gt; @pq[j] # If parent greater than child break swap(k, j) k = j end end def less(i, j) @pq[i] &lt; @pq[j] end def swap(i, j) temp = @pq[i] @pq[i] = @pq[j] @pq[j] = temp end end </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-29T15:01:37.340", "Id": "487041", "Score": "0", "body": "It's not quite clear what you mean by \"deal with hashes\". Why would that be a problem? A priority queue stores values according to an associated priority, it doesn't really care what the values it stores are." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-31T11:08:02.447", "Id": "487228", "Score": "0", "body": "@JörgWMittag well I agree with you that values are stored according to an associated priority but I disagree with you on \"It doesn't really care what the values it stores are\". In order for there to be a comparison values must be compared. It is not the same comparing `\"A\" < \"B\"`, or `1 < 2` with comparing objects. `obj_1` < `obj_2`, in this case the API must be implemented in such a way that is able to compare `obj_1` with `obj_2` just in the case shown above. Notice how I need to use `@pq[j].values[0]` in order to get to the value. https://ruby-doc.org/core-2.7.1/Hash.html" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-31T11:15:47.283", "Id": "487232", "Score": "0", "body": "Ah, so, in your priority queue, the element and the priority are the same thing? In other words, you are using the natural ordering of the elements? In that case, it is still trivial to deal with hashes: hashes don't have a natural ordering, so they cannot be stored in a priority queue whose ordering is the natural ordering of the elements." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-31T11:45:11.707", "Id": "487233", "Score": "0", "body": "@JörgWMittag you can that is how I solved this leetcode question https://leetcode.com/problems/top-k-frequent-elements/" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-09-05T18:53:52.880", "Id": "487867", "Score": "0", "body": "It is still not clear to me how you decide the priority of a hash. For example, what is the priority of `{ [] => {}, 'two' => 2.0, 3 => :three, Time.now => Object.new }`? Normally, a priority queue stores items with associated priority. In your implementation, you store items *without* an associated priority, instead the item itself is the priority. However, that obviously limits you to only storing items that have a natural total ordering, e.g. numbers or strings. But objects in general, including hashes, are neither totally ordered nor do they have a natural ordering." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-21T19:54:10.090", "Id": "503092", "Score": "0", "body": "I guess this is about priority queues, but there are simpler ways to solve the problem: [1,1,1,2,2,3].tally.max_by(2,&:last).map(&:first) #=> [1,2]`." } ]
[ { "body": "<p>The objects in the priority queue (as implemented above) have their priority determined by <code>&lt;</code>, <code>&gt;</code>, and <code>==</code>. So however equality is defined for the object determines its priority. For numbers and strings, this is fairly obvious but the default implementation of equality, less than and greater than for hashes may surprise you and not give the result you are expecting.</p>\n<p>Perhaps you could consider passing in a block to your initialize method to allow you to provide your own comparison function in those cases where the default one doesn't match your needs. Like <code>Enumerable::sort</code> does.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-09-06T12:34:59.723", "Id": "487931", "Score": "0", "body": "Hashes simply *do not have* a default implementation of `Comparable` at all, precisely because there is no sensible natural ordering." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-09-07T13:13:33.293", "Id": "488012", "Score": "0", "body": "Hash A is considered to be 'less than' hash B if A is a subset of B, and this appears to be true even if `a == {}`. See https://ruby-doc.org/core-2.7.0/Hash.html#method-i-3C" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-09-07T13:22:04.420", "Id": "488013", "Score": "0", "body": "A priority queue requires a total ordering, though, which this isn't. (Hence why hashes don't implement `Comparable`.) Sorry, I should have written \"a natural ordering that is also total\". Strings have at least two different natural orderings that are also total (lexicographic and length), numbers have an obvious natural total ordering. (Well, integers, reals, rationals, at least; complex numbers is a different matter.) For hashes, I don't see that. The OP is using the ordering of the value of the first key-value-pair which to me seems to be totally random." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-09-05T21:52:55.457", "Id": "248974", "ParentId": "248452", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-26T11:15:27.390", "Id": "248452", "Score": "1", "Tags": [ "algorithm", "ruby", "heap" ], "Title": "Priority Queue implementation for top k frequent elements leetcode in Ruby" }
248452
<p><strong>I need to know whether I have implemented Strategy pattern correctly</strong> for below 3 classes provided to me for 2 tasks.1) Report Generation 2) Movie Type. <em>Below 3 classes were provided to me</em></p> <ol> <li><p>Rental.java</p> </li> <li><p>Movie.java</p> </li> <li><p>Customer.java</p> <pre><code>public class Rental { private Movie _movie; private int _daysRented; public Rental(Movie movie, int daysRented) { _movie = movie; _daysRented = daysRented; } public int getDaysRented() { return _daysRented; } public Movie getMovie() { return _movie; } } </code></pre> </li> </ol> <p>/* Movie.java */</p> <pre><code>public class Movie { public static final int CHILDRENS = 2; public static final int REGULAR = 0; public static final int NEW_RELEASE = 1; private String _title; private int _priceCode; public Movie(String title, int priceCode) { _title = title; _priceCode = priceCode; } public int getPriceCode() { return _priceCode; } public void setPriceCode(int arg) { _priceCode = arg; } public String getTitle() { return _title; }; } </code></pre> <p>/* Customer.java */</p> <pre><code>public class Customer { private String _name; private Vector _rentals = new Vector(); public Customer(String name) { _name = name; }; public void addRental(Rental arg) { _rentals.addElement(arg); } public String getName() { return _name; } public static void main(String[] args) { Customer c = new Customer(&quot;Chhavi&quot;); Movie m = new Movie(&quot;Jab Tak Hai Jaan&quot;, 1); Rental r = new Rental(m, 10); c.addRental(r); // Rental calculation String s = c.statement(); System.out.println(&quot;s: &quot; + s); } public String statement() { // TODO Auto-generated method stub double totalAmount = 0; int frequentRenterPoints = 0; Enumeration rentals = _rentals.elements(); String result = &quot;Rental Record for &quot; + getName() + &quot;\n&quot;; while (rentals.hasMoreElements()) { double thisAmount = 0; Rental each = (Rental) rentals.nextElement(); // determine amounts for each line switch (each.getMovie().getPriceCode()) { case Movie.REGULAR: thisAmount += 2; if (each.getDaysRented() &gt; 2) thisAmount += (each.getDaysRented() - 2) * 1.5; break; case Movie.NEW_RELEASE: thisAmount += each.getDaysRented() * 3; break; case Movie.CHILDRENS: thisAmount += 1.5; if (each.getDaysRented() &gt; 3) thisAmount += (each.getDaysRented() - 3) * 1.5; break; } // add frequent // renter points frequentRenterPoints++; // add bonus for a two day new release rental if ((each.getMovie().getPriceCode() == Movie.NEW_RELEASE) &amp;&amp; each.getDaysRented() &gt; 1) frequentRenterPoints++; // show figures for this rental result += &quot;\t&quot; + each.getMovie().getTitle() + &quot;\t&quot; + String.valueOf(thisAmount) + &quot;\n&quot;; totalAmount += thisAmount; } // add footer lines result += &quot;Amount owed is &quot; + String.valueOf(totalAmount) + &quot;\n&quot;; result += &quot;You earned &quot; + String.valueOf(frequentRenterPoints) + &quot; frequent renter points&quot;; return result; } } </code></pre> <p>I have modified above classes to below.</p> <ol> <li><p>Customer.java</p> </li> <li><p>MovieType.java</p> <p>a) MovieTypeInterface.java</p> <p>b) Movie.java</p> <p>c) Childrens.java</p> <p>d) NewRelease.java</p> <p>e) Regular.java</p> </li> <li><p>Rental.java</p> </li> <li><p>RentalCalculationStrategyInterface.java</p> </li> <li><p>MainClass.java</p> </li> </ol> <p>/* Customer class */</p> <pre><code>public class Customer { private String name; private List&lt;Rental&gt; rentals = new ArrayList&lt;Rental&gt;(); public Customer(String name, List&lt;Rental&gt; list) { this.name = name; rentals.addAll(list); } // getters and setters for class variables } </code></pre> <ol start="2"> <li><p>MovieType and its child classes implementation:</p> <pre><code> public interface MovieTypeInterface { Movie getMovieType(Movie movie, int movieEnum); } public class MovieType implements MovieTypeInterface { public Movie getMovieType(Movie movie, int movieEnum) { Movie m = null; if (movieEnum == Constants.CHILDRENS) { m = new Childrens(movie.getTitle(), movie.getPriceCode()); } if (movieEnum == Constants.REGULAR) { m = new Regular(movie.getTitle(), movie.getPriceCode()); } if (movieEnum == Constants.NEW_RELEASE) { m = new NewRelease(movie.getTitle(), movie.getPriceCode()); } return m; } // @Override public Movie getMovie(Movie movie, int moviePriceCode) { return new MovieType().getMovieType(movie, moviePriceCode); } } public class Childrens extends Movie { public Childrens(String title, int priceCode) { super(title, priceCode); } @Override public Map&lt;Double, Integer&gt; getPoints(int daysRented) { thisAmount += 1.5; if (daysRented &gt; 3) thisAmount += (daysRented - 3) * 1.5; frequentRenterPoints++; map.put(thisAmount, frequentRenterPoints); return map; } } public class NewRelease extends Movie { public NewRelease(String title, int priceCode) { super(title, priceCode); // TODO Auto-generated constructor stub } @Override public Map&lt;Double, Integer&gt; getPoints(int daysRented) { thisAmount += daysRented * 3; frequentRenterPoints++; // HashMap&lt;Double, Integer&gt; map = new HashMap&lt;Double, Integer&gt;(); if (daysRented &gt; 1) frequentRenterPoints++; map.put(thisAmount, frequentRenterPoints); return map; } } public class Regular extends Movie { public Regular(String title, int priceCode) { super(title, priceCode); // TODO Auto-generated constructor stub } @Override public Map&lt;Double, Integer&gt; getPoints(int daysRented) { thisAmount += 2; if (daysRented &gt; 2) thisAmount += (daysRented - 2) * 1.5; frequentRenterPoints++; map.put(thisAmount, frequentRenterPoints); return map; } } public class Movie { protected double thisAmount = 0; protected int frequentRenterPoints; private String _title; private int _priceCode; protected Map&lt;Double, Integer&gt; map = new HashMap&lt;Double, Integer&gt;(); public Map&lt;Double, Integer&gt; getPoints(int daysRented) { this.thisAmount = 0; frequentRenterPoints = 0; map.put(thisAmount, frequentRenterPoints); return map; } private MovieType movieType; public Movie(String title, int priceCode) { _title = title; _priceCode = priceCode; } public int getPriceCode() { return _priceCode; } public void setPriceCode(int arg) { _priceCode = arg; } public String getTitle() { return _title; } public MovieType getMovieType() { return movieType; } public void setMovieType(MovieType movieType) { //movieType.getMovieType(this._priceCode); this.movieType = movieType; } } </code></pre> </li> </ol> <p>/* Rental.java */</p> <pre><code> public class Rental { private Movie _movie; private int _daysRented; public Rental(Movie movie, int daysRented) { _movie = movie; _daysRented = daysRented; } public int getDaysRented() { return _daysRented; } public Movie getMovie() { return _movie; } } </code></pre> <p>/* RentalCalculationStrategyInterface.java */</p> <pre><code>public interface RentalCalculationStrategyInterface { public String statement(); } </code></pre> <p>/* RentalCalculationClass.java */</p> <pre><code>public class RentalCalculationClass implements RentalCalculationStrategyInterface { double totalAmount = 0; int frequentRenterPoints = 0; String title = &quot;&quot;; private Movie movie; private Customer customer; public Movie getMovie() { return movie; } public void setMovie(Movie movie) { this.movie = movie; } public Customer getCustomer() { return customer; } public void setCustomer(Customer customer) { this.customer = customer; } @Override public String statement() { List&lt;Rental&gt; _rentals = this.getCustomer().get_rentals(); MovieType movieType = new MovieType(); Iterator&lt;Rental&gt; rentals = _rentals.iterator();// .elements(); String result = &quot;Rental Record for &quot; + this.getCustomer().getName() + &quot;\n&quot;; while (rentals.hasNext()) { Rental each = (Rental) rentals.next(); title = each.getMovie().getTitle(); Movie movie = movieType.getMovie(each.getMovie(), each.getMovie().getPriceCode()); Map&lt;Double, Integer&gt; mape = movie.getPoints(each.getDaysRented()); for (Map.Entry&lt;Double, Integer&gt; map : mape.entrySet()) { totalAmount = map.getKey(); frequentRenterPoints = map.getValue(); } } result += &quot;\t&quot; + title + &quot;\t&quot; + title + &quot;\n&quot;; // add footer lines result += &quot;Amount owed is &quot; + String.valueOf(totalAmount) + &quot;\n&quot;; result += &quot;You earned &quot; + String.valueOf(frequentRenterPoints) + &quot; frequent renter points. &quot;; return result; } } </code></pre> <p>/* ReportInterface.java */</p> <pre><code>public interface ReportInterface { public void printReport(String data); } </code></pre> <p>/* ReportHTML.java */</p> <pre><code> public class ReportHTML implements ReportInterface { @Override public void printReport(String data) { System.out.println(&quot;Html Report with data=&quot;+data); } } </code></pre> <p>/* ReportPDF.java */</p> <pre><code> public class ReportPDF implements ReportInterface { @Override public void printReport(String data) { System.out.println(&quot;PDF Report with data=&quot; + data); } } </code></pre> <p>/* Finally the main class to test the program */</p> <pre><code> public class MainClass { public static void main(String[] args) { RentalCalculationClass rent = new RentalCalculationClass(); insertData(rent); // Rental calculation String s = rent.statement(); System.out.println(&quot;s: &quot; + s); // Report generation ReportInterface ir = new ReportHTML(); ir.printReport(s); /* If we want to generate PDF report then we can call PDF Report class*/ /*ir = new ReportPDF(); ir.printReport(s);*/ } /* Insert data into class before testing the problem statement */ private static void insertData(RentalCalculationClass rent) { Movie movie1 = new Movie(&quot;ABC&quot;, 1); List&lt;Rental&gt; list = new ArrayList&lt;Rental&gt;(); Rental rental = new Rental(movie1, 10); list.add(rental); Customer customer1 = new Customer(&quot;ABC&quot;, list); rent.setCustomer(customer1); rent.setMovie(movie1); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-26T16:40:02.993", "Id": "486698", "Score": "1", "body": "That's a lot of code and classes, you should provide additional information so that wen can easier digest all that and now how it interacts...and more important, what it does and how they interact with each other." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-26T16:56:04.563", "Id": "486707", "Score": "0", "body": "Welcome to Code Review! The current question title is a bit vague. The site standard 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) for examples, and revise the title and description accordingly." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-26T19:36:57.993", "Id": "486738", "Score": "0", "body": "Without a description of what the code is trying to do it is very difficult to provide good answers. The title and the first paragraph of the question should provide this information. Please read the link provided by @Edward." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-27T07:02:26.583", "Id": "486774", "Score": "0", "body": "Okay. I will add more details. However the only details provided to me were the 3 files and to implement strategy pattern for the same." } ]
[ { "body": "<p>The Report Generation has been done with the Strategy pattern.</p>\n<p>The Movie Type probably has not. Why probably? Strategy pattern is about behavior, about doing something, a verb, like running, like reporting, like calculating. Movie Type is a classification, a way to organize, to group. In this case Movies.</p>\n<p>The Rental Calculation looks like the Strategy pattern.</p>\n<p>It doesn't look like the strategies are being used though. Strategy pattern allows behavior to be swapped in or out. For example, a Rental Calculator using different Rental Calculation strategies based on a collection of different Movie Types; each Movie Type being calculated differently with it's own Calculation strategy. Not seeing that anywhere and it's what you should implement next.</p>\n<p>Hope that helps. Happy coding.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-26T17:40:24.590", "Id": "248475", "ParentId": "248455", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-26T12:29:29.243", "Id": "248455", "Score": "2", "Tags": [ "java", "design-patterns", "strategy-pattern" ], "Title": "Implement Strategy pattern for 1. Print Report. 2. Movie type" }
248455
<p>I have a list of rescues for ambulance drivers in different states that are displayed on a kanban board. My JSON object is divided by the status of the rescues, and then grouped by driver. The structure is like this:</p> <p>--Status (unassigned/assigned/arrived/rescued)</p> <p>----Driver group</p> <p>-------Rescue list</p> <p>The rescues have a datetime and lat/long associated with them, so I can use map/reduce to find the rescue that the drivers attended most recently, and show that location on a map.</p> <p>One issue is that a driver group can exist in one swimlane and none of the other.</p> <p><strong>I want to</strong>: filter the list down to the arrived/rescued states only, (although logically this may not be necessary as it's not possible to have an arrival time without a driver associated, but this is out of scope) and for each driver group return their latest rescue by arrival time or rescue time. This will leave me with a distinct list of driver groups, with only the most recent rescue for that group</p> <p>Here's the working code:</p> <pre><code>let groups = cases .filter(swimlane =&gt; parseInt(swimlane.rescueStatus) &gt;= 3) .map(groups =&gt; groups.rescuerGroups) .map(rescuerGroups =&gt; rescuerGroups) .reduce((result, current) =&gt; { if(result.length === 0){ return current; } else{ current.forEach(currentRescueGroup =&gt; { let index = result.findIndex(parentRescueGroup =&gt; { return parseInt(parentRescueGroup.rescuer1) == parseInt(currentRescueGroup.rescuer1) &amp;&amp; parseInt(parentRescueGroup.rescuer2) == parseInt(currentRescueGroup.rescuer2) }) index &gt; -1 ? result[index].rescues = result[index].rescues.concat(currentRescueGroup.rescues) : result.push(currentRescueGroup); }) return result; }}, []) .map(rescueGroup =&gt; { let maxRescue = rescueGroup.rescues.reduce((current, previous) =&gt; { let currentTime = new Date(current.ambulanceArrivalTime) &gt; (new Date(current.rescueTime) || new Date(1901, 01, 01)) ? current.ambulanceArrivalTime : current.rescueTime; let previousTime = new Date(previous.ambulanceArrivalTime) &gt; (new Date(previous.rescueTime) || new Date(1901, 01, 01)) ? previous.ambulanceArrivalTime : previous.rescueTime; return previousTime &gt; currentTime ? current : previous; }) return { rescuer1Abbreviation: rescueGroup.rescuer1Abbreviation, rescuer2Abbreviation: rescueGroup.rescuer2Abbreviation, latestLocation: maxRescue.latLngLiteral, rescues: rescueGroup.rescues } }) </code></pre> <p>And here's a JSBin including the working code:</p> <p><a href="https://jsbin.com/hocasob/edit?js,console" rel="nofollow noreferrer">https://jsbin.com/hocasob/edit?js,console</a></p> <p>Any help to make the reduce sections simpler would be much appreciated</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-28T18:56:47.350", "Id": "486953", "Score": "2", "body": "One often given suggestion is to use a linter. One thing it will tell you, as an example, is that the `parseInt` requires a radix (it does not default to `10`). Another option would be to use the `Number` constructor instead. Also you could extract the accumulators outside as a variable and use argument destructuring." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-29T22:32:19.883", "Id": "487078", "Score": "0", "body": "Sorry I meant reducer instead of accumulator." } ]
[ { "body": "<p><em>Turning a comment into a review (I provide an alternative implementation, but the basic ideas can be applied to the OP implementation).</em></p>\n<p>First, some general thoughts.\nAs I mention in the comments regarding the <code>parseInt</code> function, a linter can help spot any problems. A popular one is <a href=\"https://eslint.org\" rel=\"nofollow noreferrer\">ESLint</a>. But perhaps more to the point, the data seems to already be a number, so there shouldn't be any need to parse it.</p>\n<p>It can help to clean up the code quite a bit by extracting the filters, reducers, mappers, sorters, etc. outside as a variable and give them a descriptive name, for example:</p>\n<pre><code>// filter\nconst arrivedOrRescued = ({rescueStatus}) =&gt; rescueStatus &gt;= 3\n\n// sorter\nconst byArrivalOrRescueTime = (a, b) =&gt;\n Date.parse(a.ambulanceArrivalTime || a.rescueTime)\n - Date.parse(b.ambulanceArrivalTime || b.rescueTime)\n\n// reducer\nconst byRescuers = (acc, {rescuerGroups}) =&gt; {\n rescuerGroups.forEach(({\n rescues\n , rescuer1Abbreviation: r1\n , rescuer2Abbreviation: r2\n }) =&gt; {\n let group = `${r1}-${r2}`\n acc.has(group) ? acc.get(group).push(...rescues) : acc.set(group, rescues)\n })\n\n return acc\n}\n</code></pre>\n<p>so getting a <code>Map</code> (just an example) by rescuers out of the swimlanes could then become</p>\n<pre><code>let rescuers = cases.filter(arrivedOrRescued).reduce(byRescuer, new Map())\n</code></pre>\n<p>and sorting their rescues could become</p>\n<pre><code>rescuers.forEach((rescues, abbrevs) =&gt; rescues.sort(byArrivalOrRescueTime))\n</code></pre>\n<p>after which the latest rescue is the last element of the array now that they have all been collected into a single array and sorted.</p>\n<p>One thing I would like to promote here when there can be somewhat complex nested objects in the data, is to use <a href=\"https://jsdoc.app\" rel=\"nofollow noreferrer\">JSDoc</a> comments to document the data shape.\nFor example:</p>\n<pre><code>/*\n * @typedef {Object} Swimlane\n * @property {Array.&lt;RescuerGroup&gt;} rescuerGroups\n * @property {Number} rescueStatus\n * @property {String} rescueStatusName\n *\n * @typedef {Object} RescuerGroup\n * @property {Array.&lt;Rescue&gt;} rescues\n * @property {?Number} rescuer1\n * @property {?Number} rescuer2\n * @property {?String} rescuer1Abbreviation\n * @property {?String} rescuer2Abbreviation\n *\n * @typedef {Object} Rescue\n * @property {?String} ambulanceArrivalTime\n * @property {?String} callDateTime\n * @property {?String} callerName\n * @property {String} callerNumber\n * @property {?Number} callOutcomeId\n * @property {Number} emergencyCaseId\n * @property {Number} emergencyCodeId\n * @property {Number} emergencyNumber\n * @property {Number} isLargeAnimal\n * @property {Number} latitude\n * @property {Number} longitude\n * @property {{lat: Number, lng: Number}} latLngLiteral\n * @property {String} location\n * @property {Array.&lt;String&gt;} patients\n * @property {Number} rescuer1\n * @property {Number} rescuer2\n * @property {?String} rescueTime\n * @property {Number} RescueStatus\n */\n</code></pre>\n<p>This makes it easier for others especially in data transformations.</p>\n<p><em>Just a note that I haven't tested any of this, so take the above code with a grain of salt. Also, many will probably tell me to use more braces and semicolons.</em></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-30T15:32:46.233", "Id": "248662", "ParentId": "248457", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-26T12:56:13.873", "Id": "248457", "Score": "2", "Tags": [ "javascript", "json" ], "Title": "Map/Reduce multi level JSON object" }
248457
<p>I have written a selection sort code in java. I know its very elementary algorithm, but since i am learning, so wanted your input about the quality of the code. Please have a look at the code: package selection_sort;</p> <pre><code>import java.util.Scanner; public class SelectionSort { int [] arrayToBeSorted; Scanner scan=new Scanner(System.in); SelectionSort(){ System.out.println(&quot;Enter the number of elements&quot;); int total=scan.nextInt(); this.arrayToBeSorted=new int[total]; for(int i=0;i&lt;total;i++) { System.out.println(&quot;Enter the &quot;+i+&quot; number of elements&quot;); this.arrayToBeSorted[i]=scan.nextInt(); } } public void Sort() { int minIndex,min; boolean swapRequired=false; for(int i=0;i&lt;arrayToBeSorted.length;i++) { minIndex=i; min=this.arrayToBeSorted[i]; for(int j=i+1;j&lt;this.arrayToBeSorted.length;j++) { if(this.arrayToBeSorted[j]&lt;min) { min=this.arrayToBeSorted[j]; minIndex=j; swapRequired=true; } } if(swapRequired) { swap(i,minIndex); } } for(int x:this.arrayToBeSorted) { System.out.print(x+&quot; &quot;); } } public void swap(int i,int j) { //System.out.println(&quot;swap called, pos=&quot;+i+&quot;and minindex=&quot;+j); int temp=this.arrayToBeSorted[i]; this.arrayToBeSorted[i]=this.arrayToBeSorted[j]; this.arrayToBeSorted[j]=temp; //System.out.println(&quot;------------&quot;); } public static void main(String[] args) { SelectionSort s=new SelectionSort(); s.Sort(); } } </code></pre> <p>Also about Analysis, as selection is O(n2), is it because I am using nested for loop. Is there any tool which tells us about complexity of code .Thanks in advance and please be patient if its very naive</p>
[]
[ { "body": "<pre class=\"lang-java prettyprint-override\"><code>int [] arrayToBeSorted;\nScanner scan=new Scanner(System.in);\n</code></pre>\n<p>Without any modifier, members and functions are <code>package-private</code>. Which means that they are accessible from the same package, but not by instances extending the class. That's an extremely odd thing, actually, when looking at it from an object-oriented point of view. You want to either make them <code>private</code>, or if extending classes should be able to access them, <code>protected</code>.</p>\n<p>Same goes for the constructor.</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code> System.out.println(&quot;Enter the number of elements&quot;);\n int total=scan.nextInt();\n this.arrayToBeSorted=new int[total];\n</code></pre>\n<p>You could use a <code>List</code>/<code>ArrayList</code> instead of an array, which would mean that you can receive as many numbers from the users as they want without having to specify the count beforehand. An empty input could be used for declaring the end of the list. However, that has the downside that you must use <code>Integer</code> instead of <code>int</code>, so it' is kinda hard to tell what is better. It also has the downside that detecting an empty input is that readily available from <code>Scanner</code>, as you'd need to use <code>nextLine</code> for that, with manual conversion to <code>int</code>.</p>\n<p>You could also emulate a <code>List</code> by dynamically growing the array. Either by doing it for every item, performance does not matter in this use-case, or by doubling the size when needed.</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code>this.arrayToBeSorted=new int[total];\n</code></pre>\n<p>You only require the <code>this</code> modifier if you have a variable with the same name in the same scope, for example in a constructor:</p>\n<pre class=\"lang-java prettyprint-override\"><code>public ValueContainer(int value) {\n this.value = value;\n}\n</code></pre>\n<p>It's common practice to omit <code>this</code> if not needed. If you ever find yourself in the situation that it is confusing whether an instance, static or local variable is used, you did something wrong there anyway.</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code>for(int i=0;i&lt;total;i++) {\n</code></pre>\n<p>I'm a very persistent advocate for using &quot;real&quot; names for variables in loops.</p>\n<pre class=\"lang-java prettyprint-override\"><code>for (int counter = 0; counter &lt; total; counter++) {\n// or\nfor (int index = 0; index &lt; total; index++) {\n</code></pre>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code>public void Sort() {\n</code></pre>\n<p>The Java naming conventions state that methods/functions should be lowerCamelCase.</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code>int minIndex,min;\n</code></pre>\n<p>Personally I'd avoid declaring multiple variables on the same line. It makes it easy to miss declaration.</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code>boolean swapRequired=false;\n</code></pre>\n<p>That's a great example of a great name for a variable, thank you!</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code> for(int x:this.arrayToBeSorted) {\n System.out.print(x+&quot; &quot;);\n }\n</code></pre>\n<p>That, unfortunately, is a bad name for a variable. Only use &quot;x&quot;, &quot;y&quot; and &quot;z&quot; when working with dimensions. &quot;value&quot; or &quot;number&quot; would be a great name here.</p>\n<hr />\n<p>Overall, it looks valid. I did not run it to test the functionality, though. What you should change is that you have logic in the constructor. Nobody expects constructors to be filled with logic, because you can't see the intent of logic from them. They should be as nothing doing as possible. That means that you should move the logic into <code>sort</code> or, even better, into <code>main</code>. Your Sorter should not be concerned with input at all, it should only be concerned with sorting values, ideally, and another class (<code>InputReader</code>?) should be concerned with getting the input. So what you could do is something like this:</p>\n<pre class=\"lang-java prettyprint-override\"><code>public static final void main(String[] args) {\n InputReader inputReader = new InputReader();\n \n int[] values = inputReader.readValues();\n \n Sorter sorter = new Sorter();\n sorter.sort(value);\n \n // TODO Print sorted output.\n}\n</code></pre>\n<p>That also has the upside that you don't need to hold state in <code>Sorter</code> at all, which would make it thread-safe by default.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-26T23:44:22.450", "Id": "486756", "Score": "0", "body": "Thanks a lot for such detailed review ..will inculcate these points specially the constructer one and the naming" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-26T16:37:53.807", "Id": "248471", "ParentId": "248459", "Score": "1" } } ]
{ "AcceptedAnswerId": "248471", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-26T13:22:54.717", "Id": "248459", "Score": "5", "Tags": [ "java", "algorithm", "sorting" ], "Title": "Selection Sort Java and Analysis" }
248459
<p>I want to test my CRUD operation to a <code>MySql</code> database (I use dapper as my <code>ORM</code>).</p> <p>This is what I wrote with <code>xUnit</code>:</p> <pre><code> private IPaymentRepository paymentRepository; private Payment testPayment; private string connectionString = &quot;Database=...&quot;; //Test DB public PaymentRepositoryTest() { paymentRepository = new PaymentRepository(connectionString); //My model has private setters so I have a builder to initialize the object. testPayment = new Payment.Builder() .Id(0) .Description(&quot;Test&quot;) .Type(1) .WithPercentageDiscount(10) .WithAdvancePercentageDiscount(0) .WithInstallments(new int[] { 30 }).Build; } </code></pre> <p><strong>CREATE</strong></p> <pre><code>[Fact] public void Insert_Payment_ReturnId() { long id = 0; using(var transaction = new TransactionScope()) { id = paymentRepository.Insert(testPayment); } Assert.True(id &gt; 0); } </code></pre> <p><strong>READ</strong></p> <pre><code>[Fact] public void Get_Payment_ReturnPaymentFromDb() { using (var transaction = new TransactionScope()) { long id = paymentRepository.Insert(testPayment); var payment = paymentRepository.GetById(id); Assert.NotNull(payment); } } </code></pre> <p><strong>UPDATE</strong></p> <p>I don't really like this code, having private setter here is unfortunate because I have to recreate the object. I'm also not really sure about checking only one field.</p> <pre><code> public void Update_Payment() { long id = 0; const string UPDATED_DESCRIPTION = &quot;Test2&quot;; using (var transaction = new TransactionScope()) { id = paymentRepository.Insert(testPayment); var updatedPayment = new Payment.Builder() .Id(id) .Description(UPDATED_DESCRIPTION) .Type(1) .WithPercentageDiscount(10) .WithAdvancePercentageDiscount(0) .WithInstallments(new int[] { 30 }).Build(); paymentRepository.Update(updatedPayment); updatedPayment = paymentRepository.GetById(id); Assert.Equal(UPDATED_DESCRIPTION, updatedPayment.Description); } } </code></pre> <p><strong>DELETE</strong></p> <p>Just like the update, I don't like having to recreate the object just to have the proper ID.</p> <pre><code>[Fact] public void Delete_Payment_ReturnNull() { using (var transaction = new TransactionScope()) { long id = paymentRepository.Insert(testPayment); var paymentToDelete = new Payment.Builder() .Id((int)id) .Description(&quot;Test&quot;) .Type(1) .WithPercentageDiscount(10) .WithAdvancePercentageDiscount(0) .WithInstallments(new int[] { 30 }).Build(); paymentRepository.Delete(paymentToDelete); var payment = paymentRepository.GetById(id); Assert.Null(payment); } } </code></pre> <p>The code of course works and I get the proper results, but I feel I'm repeating basically the same test over and over especially in Update and Delete.</p> <p>Is this integration code good ? How can I make it better ?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-26T16:26:26.570", "Id": "486694", "Score": "1", "body": "\"Is this integration code good?\" Did you test it? Are you running into any troubles?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-26T17:24:52.990", "Id": "486719", "Score": "0", "body": "Yes it does work. There no problem, but since this is the first time I do integration test I'm not sure if it make sense at all. It seems to me that I'm basically testing the same thing over and over. 3 test out of 4 calls GetById, is that good ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-27T10:15:24.603", "Id": "486790", "Score": "1", "body": "In End2End tests it is a quite common practice to issue direct commands against the database server. Your application can rely on any ORM, but your tests can use a different channel to pre-populate, verify and cleanup. Sometimes E2E tests are rewritten in different language than the SUT to avoid re-usage of any component. If you wish you can use this concept on this level of testing as well." } ]
[ { "body": "<p>Adding automated integration tests is a great way to take testing to the next level, and what you've written is really good for a first attempt. Here are some pointers/suggestions that might help you along your way.</p>\n<hr />\n<p>It's almost inevitable that your tests will end up effectively testing the same thing multiple times. As you've identified, most of your tests use the <code>GetById</code> method, and in fact all of them <code>Insert</code> a payment. The only potential problem this causes is that if one of those methods stops working you suddenly have most/all of your tests failing and it may not be immediately obvious where the problem is. In the grand scheme of things, this isn't that much of an issue as you'll almost certainly be able to figure out where the problem is by looking at the test output and/or by stepping through the test with a debugger.</p>\n<hr />\n<p>Although it seems like your tests are very similar, a lot of the similarities are down to them sharing common setup steps, e.g. inserting a payment so you have something to get/update/delete. It is absolutely fine to have this sort of duplication in unit/integration tests, and again is inevitable in most circumstances. As the number of tests grows, you might find that it makes sense to pull out some of the setup into a separate method that's used by multiple tests. This is also fine to do, as long as it doesn't affect the readability of the test, so avoid using generic method names like <code>Setup()</code> and instead prefer clear (if slightly verbose) names like <code>CreateRepositoryWithSinglePayment(testPayment)</code>.</p>\n<hr />\n<p>The fluent payment builder makes it hard to know which properties are required and which are optional (if any). I can't advise a great deal on this without seeing the <code>Payment</code> or <code>PaymentBuilder</code> classes, but if all of the properties are required, consider just creating a <code>Payment</code> constructor that assigns parameter values to readonly properties. Then there's no doubt about what values are required to create a valid <code>Payment</code>.</p>\n<hr />\n<p>One thing to be aware of when integration testing is that it's often easy to end up with shared state between tests. Here, you are inserting a payment into your database as part of every test and this is not always deleted afterwards (or at least there's no tear-down code included in your post). Since you are actually persisting something in a database, it will therefore exist across tests unless explicitly deleted after each test is run. This could result in some very confusing test behaviour in the future as your tests might not be testing what you intended! You should add a tear-down step by implementing <code>IDisposable</code> and deleting every payment in your test database inside the <code>Dispose()</code> method. This ensures that every test will start from the same fresh state.</p>\n<p>On a similar note, be aware that you can get strange behaviour when running integration tests in parallel if they share the same data store(s). You're fine at the moment because by default xUnit runs test cases within the same class in serial, but if you had another test class using the same database these would be run in parallel by default. There are ways to control this behaviour, but it's more something to be aware of as this shouldn't be an issue given your current test organisation.</p>\n<hr />\n<p>You shouldn't need to provide the entire <code>Payment</code> object to delete it from the database. If you can read a payment by its <code>Id</code> using the <code>GetById</code> method then you should also be able to delete a payment by its <code>Id</code>. This should simplify the <code>Delete</code> test case somewhat.</p>\n<hr />\n<p>There are plenty of other things you could test here. You've got tests for the 'happy' paths, i.e. the paths where everything goes as expected, but there are certainly lots of edge cases (or unexpected cases) that you could also test. Maybe you've already considered some/all of these, but off the top of my head:</p>\n<ul>\n<li>What happens when you insert a payment that already exists in the database?</li>\n<li>What happens when you try to read a payment that does not exist in the database?</li>\n<li>What happens when trying to update a payment that doesn't exist in the database?</li>\n<li>Can you update the payment with a <code>null</code> description? What happens if the description is really long or contains special characters? You'd probably want to use a <code>[Theory]</code> with <code>[InlineData]</code> to enumerate several different test cases if doing this.</li>\n<li>What happens when updating properties other than the description?</li>\n<li>What happens when trying to delete a payment that doesn't exist in the database?</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-27T06:38:14.033", "Id": "486772", "Score": "0", "body": "Oh man, thanks for the feedback. I really appreciate it. For the dispose part I use new TransactionScope() and never call .Complete() so the database should always be in a clear state. I tested it and it seems to work." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-26T21:32:36.240", "Id": "248483", "ParentId": "248467", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-26T15:26:15.477", "Id": "248467", "Score": "3", "Tags": [ "c#", "mysql", "dapper", "xunit" ], "Title": "CRUD integration test, is it ok?" }
248467
<p>I need to write a <code>CustomBasicMatrix</code> class implementation for college. This includes basic operations such as <code>int</code> and <code>CustomBasicMatrix</code> addition and subtraction, Transposition and <strong>iterations / const iterations</strong>.</p> <p>I would like to know if there are coding conventions, or more importantly, <strong>Memory Leak / Segmentation Faults Possibilities</strong>.</p> <p>Context:</p> <ul> <li>Implementation must be wrapped in a namespace &quot;sys&quot;.</li> <li>The only external file in use is &quot;Auxiliaries.h&quot;, which contains: &quot;Dimension&quot; struct, only holds 'width' and 'height', with additional helper functions for printing a matrix.</li> <li>Instead of transposing a function by flipping dimensions, I saved a boolean value indicates if the matrix is transposed, thus when fetching the value we use said boolean to determine if we fetch (i,j) or (j,i). This is to save memory and overhead.</li> </ul> <p>Thanks in advance!</p> <p><strong>CustomBasicMatrix .h:</strong></p> <pre><code> #include &lt;ostream&gt; #include &quot;Auxiliaries.h&quot; namespace sys{ class CustomBasicMatrix{ private: int rows; int cols; int** data; bool trans = false; public: explicit CustomBasicMatrix(Dimensions dim, int initValue = 0); CustomBasicMatrix(const CustomBasicMatrix&amp; other); virtual ~CustomBasicMatrix(); CustomBasicMatrix&amp; operator=(const CustomBasicMatrix&amp; other); static CustomBasicMatrix Identity(int dims); int height() const; int width() const; int size() const; CustomBasicMatrix transpose() const; CustomBasicMatrix operator-() const; CustomBasicMatrix&amp; operator+=(int scalar); CustomBasicMatrix&amp; operator+=(const CustomBasicMatrix&amp; rhs); int &amp;operator()(int row, int col); int &amp;operator()(int row, int col) const; class iterator{ private: CustomBasicMatrix* matrix; int row; int col; public: iterator(CustomBasicMatrix* matrix, int row=0, int col=0); virtual ~iterator() = default; iterator&amp; operator=(const iterator&amp; other); int&amp; operator*(); iterator&amp; operator++(); const iterator operator++(int); bool operator==(const iterator&amp; other) const; bool operator!=(const iterator&amp; other) const; }; iterator begin(); iterator end(); class const_iterator{ private: const CustomBasicMatrix* matrix; int row; int col; public: const_iterator(const CustomBasicMatrix *matrix, int row = 0, int col = 0); virtual ~const_iterator() = default; const_iterator&amp; operator=(const const_iterator&amp; other); const int&amp; operator*() const; const_iterator operator++(); const const_iterator operator++(int); bool operator==(const const_iterator&amp; other) const; bool operator!=(const const_iterator&amp; other) const; }; const_iterator begin() const; const_iterator end() const; }; bool any(const CustomBasicMatrix&amp; mat); bool all(const CustomBasicMatrix&amp; mat); CustomBasicMatrix operator+(const CustomBasicMatrix&amp; lhs, const CustomBasicMatrix&amp; rhs); CustomBasicMatrix operator+(const CustomBasicMatrix&amp; lhs, int scalar); CustomBasicMatrix operator+(int scalar, const CustomBasicMatrix&amp; matrix); CustomBasicMatrix operator-(const CustomBasicMatrix &amp;lhs, const CustomBasicMatrix &amp;rhs); CustomBasicMatrix operator&lt;(const CustomBasicMatrix&amp; lhs, int scalar); CustomBasicMatrix operator&lt;=(const CustomBasicMatrix&amp; lhs, int scalar); CustomBasicMatrix operator&gt;(const CustomBasicMatrix&amp; lhs, int scalar); CustomBasicMatrix operator&gt;=(const CustomBasicMatrix&amp; lhs, int scalar); CustomBasicMatrix operator!=(const CustomBasicMatrix&amp; lhs, int scalar); CustomBasicMatrix operator==(const CustomBasicMatrix&amp; lhs, int scalar); std::ostream &amp;operator&lt;&lt;(std::ostream &amp;os, const CustomBasicMatrix &amp;matrix); } </code></pre> <p><strong>CustomBasicMatrix .cpp:</strong></p> <pre><code> #include &quot;CustomBasicMatrix.h&quot; #include &quot;Auxiliaries.h&quot; #define CBM sys::CustomBasicMatrix CBM::CustomBasicMatrix(sys::Dimensions dim, int initValue) { this-&gt;rows = dim.getRow(); this-&gt;cols = dim.getCol(); this-&gt;data = new int*[this-&gt;rows]; int i; try{ for (i = 0; i &lt; this-&gt;rows; ++i){ this-&gt;data[i] = new int[this-&gt;cols]; } } catch(const std::exception&amp; e){ for (int j = 0; j &lt; i; ++j){ delete[] this-&gt;data[j]; } delete[] this-&gt;data; throw e; } for(int i=0; i&lt; this-&gt;rows ; i++){ for (int j = 0; j &lt; this-&gt;cols; ++j){ this-&gt;data[i][j] = initValue; } } } CBM::CustomBasicMatrix(const CBM &amp;other) { this-&gt;rows = other.rows; this-&gt;cols = other.cols; this-&gt;trans = other.trans; this-&gt;data = new int*[this-&gt;rows]; int i; try{ for (i = 0; i &lt; this-&gt;rows; ++i){ this-&gt;data[i] = new int[this-&gt;cols]; } } catch(const std::exception&amp; e){ for (int j = 0; j &lt; i; ++j){ delete[] this-&gt;data[j]; } delete[] this-&gt;data; throw e; } for(int i=0; i&lt; this-&gt;rows ; i++){ for (int j = 0; j &lt; this-&gt;cols; ++j){ this-&gt;data[i][j] = other.data[i][j]; } } } CBM::~CustomBasicMatrix() { for (int i = 0; i &lt; this-&gt;rows; ++i){ delete[] this-&gt;data[i]; } delete[] this-&gt;data; } CBM &amp;CBM::operator=(const CBM &amp;other) { if(this == &amp;other) return *this; for (int i = 0; i &lt; this-&gt;rows; ++i){ delete[] this-&gt;data[i]; } delete[] this-&gt;data; this-&gt;rows = other.rows; this-&gt;cols = other.cols; this-&gt;trans = other.trans; this-&gt;data = new int*[this-&gt;rows]; int i; try{ for (i = 0; i &lt; this-&gt;rows; ++i){ this-&gt;data[i] = new int[this-&gt;cols]; } } catch(const std::exception&amp; e){ for (int j = 0; j &lt; i; ++j){ delete[] this-&gt;data[j]; } delete[] this-&gt;data; throw e; } for(int i=0; i&lt; this-&gt;rows ; i++){ for (int j = 0; j &lt; this-&gt;cols; ++j){ this-&gt;data[i][j] = other.data[i][j]; } } return *this; } CBM CBM::Identity(int dims) { Dimensions dim = Dimensions(dims, dims); CustomBasicMatrix ret(dim, 0); for (int i = 0; i &lt; dims; ++i){ ret.data[i][i] = 1; } return ret; } int CBM::height() const { return this-&gt;trans ? this-&gt;cols : this-&gt;rows; } int CBM::width() const { return this-&gt;trans ? this-&gt;rows : this-&gt;cols; } int CBM::size() const { return this-&gt;rows * this-&gt;cols; } CBM CBM::transpose() const { CustomBasicMatrix ret(*this); ret.trans = !ret.trans; return ret; } CBM&amp; CBM::operator+=(int scalar) { for (int i = 0; i &lt; this-&gt;rows ; ++i){ for (int j = 0; j &lt; this-&gt;cols ; ++j){ this-&gt;data[i][j] += scalar; } } return *this; } CBM &amp;CBM::operator+=(const CBM &amp;rhs) { for (int i = 0; i &lt; this-&gt;rows ; ++i){ for (int j = 0; j &lt; this-&gt;cols ; ++j){ this-&gt;data[i][j] += rhs.data[i][j]; } } return *this; } CBM CBM::operator-() const { CustomBasicMatrix reg(*this); for (int i = 0; i &lt; reg.rows ; ++i){ for (int j = 0; j &lt; reg.cols; ++j){ reg.data[i][j] = -reg.data[i][j]; } } return reg; } int &amp;CBM::operator()(int row, int col) { if(this-&gt;trans) return this-&gt;data[col][row]; else return this-&gt;data[row][col]; } int &amp;CBM::operator()(int row, int col) const { if(this-&gt;trans) return this-&gt;data[col][row]; else return this-&gt;data[row][col]; } CBM sys::operator+(const CBM &amp;lhs, const CBM &amp;rhs) { CBM temp(lhs); return (temp += rhs); } CBM sys::operator+(const CBM &amp;lhs, int scalar) { CBM temp = lhs; return (temp += scalar); } CBM sys::operator-(const CBM &amp;lhs, const CBM &amp;rhs) { CBM temp = lhs; return (temp += -rhs); } CBM sys::operator&lt;(const CBM&amp; lhs, int scalar) { CBM res(lhs); for (int i = 0; i &lt; res.height() ; ++i){ for (int j = 0; j &lt; res.width(); ++j){ res(i,j) = res(i,j) &lt; scalar; } } return res; } CBM sys::operator&lt;=(const CBM&amp; lhs, int scalar) { CBM res1 = lhs == scalar; CBM res2 = lhs &lt; scalar; return (res1 += res2); } CBM sys::operator&gt;(const CBM&amp; lhs, int scalar) { CBM res(lhs); for (int i = 0; i &lt; res.height() ; ++i){ for (int j = 0; j &lt; res.width(); ++j){ res(i,j) = res(i,j) &gt; scalar; } } return res; } CBM sys::operator&gt;=(const CBM&amp; lhs, int scalar) { CBM res1 = lhs == scalar; CBM res2 = lhs &gt; scalar; return res1 += res2; } CBM sys::operator!=(const CBM&amp; lhs, int scalar) { CBM res1 = lhs &gt; scalar; CBM res2 = lhs &lt; scalar; return res1 += res2; } CBM sys::operator==(const CBM&amp; lhs, int scalar) { CBM res(lhs); for (int i = 0; i &lt; res.height() ; ++i){ for (int j = 0; j &lt; res.width(); ++j){ res(i,j) = res(i,j) == scalar; } } return res; } CBM sys::operator+(int scalar, const CBM &amp;matrix) { return matrix + scalar; } CBM::iterator CBM::begin() { return iterator (this); } CBM::iterator CBM::end() { return iterator(this, this-&gt;rows, this-&gt;cols); } bool sys::any(const CBM &amp;mat) { for (CBM::const_iterator it = mat.begin() ; it != mat.end() ; it++){ if((*it) != 0) return true; } return false; } bool sys::all(const CBM &amp;mat) { for (CBM::const_iterator it = mat.begin() ; it != mat.end() ; it++){ if((*it) == 0) return false; } return true; } CBM::const_iterator CBM::begin() const { return const_iterator(this); } CBM::const_iterator CBM::end() const { return const_iterator(this, this-&gt;rows, this-&gt;cols); } std::ostream &amp;sys::operator&lt;&lt;(std::ostream &amp;os, const CBM &amp;matrix) { int *vals = new int[matrix.size()]; for (int i = 0; i &lt; matrix.height(); ++i){ for (int j = 0; j &lt; matrix.width(); ++j){ vals[i * matrix.width() + j] = matrix(i,j); } } Dimensions dim(matrix.height(), matrix.width()); std::string res = printMatrix(vals, dim); delete[] vals; return os &lt;&lt; res; } /************************************/ CBM::iterator::iterator(CBM *matrix, int row, int col) : matrix(matrix), row(row), col(col){} CBM::iterator &amp;CBM::iterator::operator=(const iterator&amp; other) { if(this == &amp;other) return *this; this-&gt;matrix = other.matrix; this-&gt;row = other.row; this-&gt;col = other.col; return *this; } int &amp;CBM::iterator::operator*() { return this-&gt;matrix-&gt;operator()(this-&gt;row, this-&gt;col); } CBM::iterator &amp;CBM::iterator::operator++() { this-&gt;col++; this-&gt;row += this-&gt;col / this-&gt;matrix-&gt;cols; this-&gt;col = this-&gt;col % this-&gt;matrix-&gt;cols; if(this-&gt;row == this-&gt;matrix-&gt;rows || this-&gt;col == this-&gt;matrix-&gt;cols){ this-&gt;row = this-&gt;matrix-&gt;rows; this-&gt;col = this-&gt;matrix-&gt;cols; } return *this; } const CBM::iterator CBM::iterator::operator++(int) { iterator i = (*this); ++(*this); return i; } bool CBM::iterator::operator==(const CBM::iterator &amp;other) const { bool matrixEquals = (this-&gt;matrix) == (other.matrix); bool colsEquals = this-&gt;col == other.col; bool rowsEquals = this-&gt;row == other.row; return matrixEquals &amp;&amp; colsEquals &amp;&amp; rowsEquals; } bool CBM::iterator::operator!=(const CBM::iterator &amp;other) const { return !this-&gt;operator==(other); } /************************************/ CBM::const_iterator::const_iterator(const CustomBasicMatrix *matrix, int row, int col) : matrix(matrix), row(row), col(col){} CBM::const_iterator &amp;CBM::const_iterator::operator=(const CBM::const_iterator &amp;other) { if(this == &amp;other) return *this; this-&gt;matrix = other.matrix; this-&gt;row = other.row; this-&gt;col = other.col; return *this; } const int &amp;CBM::const_iterator::operator*() const { return this-&gt;matrix-&gt;operator()(this-&gt;row, this-&gt;col); } CBM::const_iterator CBM::const_iterator::operator++() { this-&gt;col++; this-&gt;row += this-&gt;col / this-&gt;matrix-&gt;cols; this-&gt;col = this-&gt;col % this-&gt;matrix-&gt;cols; if(this-&gt;row == this-&gt;matrix-&gt;rows || this-&gt;col == this-&gt;matrix-&gt;cols){ this-&gt;row = this-&gt;matrix-&gt;rows; this-&gt;col = this-&gt;matrix-&gt;cols; } return *this; } const CBM::const_iterator CBM::const_iterator::operator++(int) { const_iterator i = (*this); ++(*this); return i; } bool CBM::const_iterator::operator==(const CBM::const_iterator &amp;other) const { bool matrixEquals = (this-&gt;matrix) == (other.matrix); bool colsEquals = this-&gt;col == other.col; bool rowsEquals = this-&gt;row == other.row; return matrixEquals &amp;&amp; colsEquals &amp;&amp; rowsEquals; } bool CBM::const_iterator::operator!=(const CBM::const_iterator &amp;other) const { return !this-&gt;operator==(other); } </code></pre> <p>Edit: Added Auxiliaries header file. It is provided so the cpp file is not available, and you can ignore it in the review</p> <p><strong>Auxiliaries.h:</strong></p> <pre><code> #include &lt;iostream&gt; #include &lt;string&gt; #include &lt;cmath&gt; namespace sys { typedef int units_t; class Dimensions { int row, col; public: Dimensions( int row_t, int col_t); std::string toString() const; bool operator==(const Dimensions&amp; other) const; bool operator!=(const Dimensions&amp; other) const; int getRow() const ; int getCol() const ; }; std::string printMatrix(const int* matrix,const Dimensions&amp; dim); template&lt;class ITERATOR_T&gt; std::ostream&amp; printMatrix(std::ostream&amp; os,ITERATOR_T begin, ITERATOR_T end, unsigned int width){ unsigned int row_counter=0; for (ITERATOR_T it= begin; it !=end; ++it) { if(row_counter==width){ row_counter=0; os&lt;&lt; std::endl; } os &lt;&lt;*it&lt;&lt;&quot; &quot;; row_counter++; } os&lt;&lt; std::endl; return os; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-26T19:28:27.620", "Id": "486737", "Score": "0", "body": "Generally we prefer to see the contents of all the header files. If you didn't write it you can explain that and ask that it be excluded from the review. If I answer this question I will mention using `#define` rather than `using`." } ]
[ { "body": "<ol>\n<li>\n<blockquote>\n<p>Instead of transposing a function by flipping dimensions, I saved a boolean value indicates if the matrix is transposed, thus when fetching the value we use said boolean to determine if we fetch (i,j) or (j,i). This is to save memory and overhead.</p>\n</blockquote>\n</li>\n</ol>\n<p>Unfortunately, this only increases overhead. This way you have an unnecessary branch whenever one simply want to access an element of the matrix slowing down the code and furthermore it will surely result in poor memory accessing slowing down the code even further.</p>\n<p>Also the implementation of operations like <code>+=</code> ignores whether the matrices are transposed. And the only way to transpose a matrix is to call <code>transpose()</code> which makes a copy anyways.</p>\n<ol start=\"2\">\n<li>\n<blockquote>\n<p><code>int** data;</code></p>\n</blockquote>\n</li>\n</ol>\n<p>This isn't good. You make an allocation for each column element of the matrix - contributing a to memory fragmentation. It is preferable to store the whole data array as a contiguous piece of data, i.e., <code>int* data;</code> you figure out where columns begin and end via size of <code>row</code>. Or better wrap in an existing overhead-free smart pointer <code>std::unique_ptr&lt;int[]&gt; data;</code> and as an aside you won't need to write all the <code>try/catch</code> for deallocation.</p>\n<ol start=\"3\">\n<li><p>Why no default constructor? At least enable it. Also there is absolutely no need here to make destructor virtual - it is unnecessary for this class. Make destructors virtual for classes that have polymorphic methods.</p>\n</li>\n<li>\n<blockquote>\n<p><code>int &amp;operator()(int row, int col);</code>\n<code>int &amp;operator()(int row, int col) const;</code></p>\n</blockquote>\n</li>\n</ol>\n<p>I believe you wanted the <code>const</code> version to return either <code>int</code> or <code>const int&amp;</code> and not <code>int&amp;</code>.</p>\n<ol start=\"5\">\n<li><p>The class should have move constructor and move assignment operator. This is crucial for memory purposes.</p>\n</li>\n<li><p>What does the <code>iterator</code> do in the matrix? What does it iterate over and in which order? It is not clear from the header. Also, the <code>iterator</code> should be iterating over rows instead of elements of the matrix.</p>\n</li>\n<li></li>\n</ol>\n<pre><code>CustomBasicMatrix operator&lt;(const CustomBasicMatrix&amp; lhs, int scalar);\nCustomBasicMatrix operator&lt;=(const CustomBasicMatrix&amp; lhs, int scalar);\nCustomBasicMatrix operator&gt;(const CustomBasicMatrix&amp; lhs, int scalar);\nCustomBasicMatrix operator&gt;=(const CustomBasicMatrix&amp; lhs, int scalar);\nCustomBasicMatrix operator!=(const CustomBasicMatrix&amp; lhs, int scalar);\nCustomBasicMatrix operator==(const CustomBasicMatrix&amp; lhs, int scalar);\n</code></pre>\n<p>Is this really how you want to use the matrix? It looks odd to me. I could understand if you wanted something like this for an image... opencv uses its <code>cv::Mat</code> for both matrices and images but I don't find it a good design choice to wrap everything via one class.</p>\n<ol start=\"8\">\n<li><p>All your function implementations are in cpp file. It is not good. Functions cannot be inlined if their definition is hidden. You should move all small functions definitions to the header.</p>\n</li>\n<li><p>I believe the primary operations of a dynamic range matrix should be multiplication by vector and computing its inverse. Both of which are missing. Though, not surprising considering that you wrote an <code>int</code> type matrix instead of more suitable types for a matrix like <code>float</code> and <code>double</code>.</p>\n</li>\n<li><p>I am sure you could write a few simple functions like <code>reserve</code> or <code>resize</code> and just use them instead of copy pasting the allocation procedure. Also, copy assignment will unnecessary delete all the data even if the dimensions match.</p>\n</li>\n<li><p>As a part of general design now in C++ viewers are pretty popular and recommended - classes that don't own memory (don't delete or allocate). A MatrixViewer class would be very efficient in wrapping things up.</p>\n</li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-26T20:53:16.040", "Id": "486749", "Score": "0", "body": "Thanks alot for the review! A few clarifications to minimize confusion:\nAll is by following the course Regulations and Rules:\n\n3. They asked to refrain adding a Default Constructor || 6. They explicitly asked to write an Iterator that goes through all the elements of the matrix, by order of first row to last, from left to right (as in [0,0], [0,1], ... [0,col-1], [1,0], ... [1, col-1], ... ,[row-1,0], ... [row-1, col-1] || 7. yeah they also asked for this... Over a Relational Operation with a scalar, return a 'binary' matrix that with 'true' value in each cell that satisfies the comparison." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-27T12:09:11.120", "Id": "486801", "Score": "0", "body": "Nice comments! Re **8** I'd rather trust compilers and keep declarations in hh, implementations in cc files. Re **1** while in theory this may be true, but best to measure optimised code. Re **5** they can be marked deleted too if the class doesn't need to be moved around." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-27T12:56:48.943", "Id": "486805", "Score": "0", "body": "@anki Re **8** that's the whole point that keeping implementations in cpp makes compilers unable to inline at all making this important optimization impossible. Re **5** tested in practice as well when optimising matrix/vector multiplication - though I utilised simd and doubt that I could write a decent implementation if I were to wonder what happens if matrices are transposed." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-26T20:02:37.047", "Id": "248479", "ParentId": "248476", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-26T18:07:45.243", "Id": "248476", "Score": "4", "Tags": [ "c++", "matrix", "homework" ], "Title": "Basic Integer Matrix Implementation" }
248476
<p>I have a &quot;Palindrome&quot; class that has some functions for verifying if certain things are Palindromes. For the verification, I have 2 different algorithms, one being recursive and the other iterative.</p> <p>I'm happy with the algorithms however I'm unsure whether the way that I do the overloading and eventually parsing everything to the check charArray function is a smart thing.</p> <p>I also have some Junit 5 Tests that prove that everything works. Here I'm just unsure if its good code with the multiple nests and the methods/tests I chose and if pretty much having duplicate code for the Iterative and Recursive algorithm is good. Thank you in advance.</p> <p>Palindrome Class</p> <pre><code>package com.gr; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.LocalTime; import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.List; /** * @author Lucifer Uchiha * @version 1.0 */ public class Palindrome { /* Iterative */ /** * Returns a boolean of whether the char array is a palindrome or not. * This is determined by using the iterative algorithm. * * @param chars char array containing the characters to be checked. * @return boolean of whether the char array is a palindrome or not. */ public static boolean isCharArrayPalindromeIterative(char[] chars) { if (chars.length &lt; 1) return false; char[] formattedChars = convertAllCharsToUpperCase(chars); boolean isPalindrome = true; for (int i = 0; i != formattedChars.length / 2; i++) if (formattedChars[i] != formattedChars[(formattedChars.length - 1) - i]) { isPalindrome = false; break; } return isPalindrome; } /** * Returns a boolean of whether the word of type String is a palindrome or not. * This is determined by using the iterative algorithm. * * @param word the word to be checked. * @return boolean of whether the word is a palindrome or not. */ public static boolean isWordPalindromeIterative(String word) { return isCharArrayPalindromeIterative(word.toCharArray()); } /** * Returns a boolean of whether the sentence of type String is a palindrome or not. * This is determined by using the iterative algorithm. * * @param sentence the sentence to be checked. * @return boolean of whether the sentence is a palindrome or not. */ public static boolean isSentencePalindromeIterative(String sentence) { String newSentence = sentence.replaceAll(&quot;[^a-zA-Z]&quot;, &quot;&quot;); return isWordPalindromeIterative(newSentence); } /** * Returns a boolean of whether the number of type byte (-128 to 127) is a palindrome or not. * This is determined by using the iterative algorithm. * * @param number the number to be checked. * @return boolean of whether the number is a palindrome or not. */ public static boolean isNumberPalindromeIterative(byte number) { return isWordPalindromeIterative(String.valueOf(number)); } /** * Returns a boolean of whether the number of type short (32,768 to 32,767) is a palindrome or not. * This is determined by using the iterative algorithm. * * @param number the number to be checked. * @return boolean of whether the number is a palindrome or not. */ public static boolean isNumberPalindromeIterative(short number) { return isWordPalindromeIterative(String.valueOf(number)); } /** * Returns a boolean of whether the number of type int (-2,147,483,648 to 2,147,483,647) is a palindrome or not. * This is determined by using the iterative algorithm. * * @param number the number to be checked. * @return boolean of whether the number is a palindrome or not. */ public static boolean isNumberPalindromeIterative(int number) { return isWordPalindromeIterative(String.valueOf(number)); } /** * Returns a boolean of whether the number of type long (-9,223,372,036,854,775,808 to 9,223,372,036,854,775,807) is a palindrome or not. * This is determined by using the iterative algorithm. * * @param number the number to be checked. * @return boolean of whether the number is a palindrome or not. */ public static boolean isNumberPalindromeIterative(long number) { return isWordPalindromeIterative(String.valueOf(number)); } /** * Returns a List containing all the numbers that are palindromes in the range that is given from * start of type long to end of type long. * This is determined by using the iterative algorithm. * * @param start the start of the range, inclusive. * @param end the end of the range, exclusive. * @return List containing all the numbers that are palindromes in the given range. */ public static List&lt;Long&gt; getAllNumberPalindromesInRangeIterative(long start, long end) { List&lt;Long&gt; results = new ArrayList&lt;&gt;(); for (long number = start; number != end; number++) if (isNumberPalindromeIterative(number)) results.add(number); return results; } /** * Returns a List containing all the numbers that are palindromes in the range that is given from * start of type int to end of type int. * This is determined by using the iterative algorithm. * * @param start the start of the range, inclusive. * @param end the end of the range, exclusive. * @return List containing all the numbers that are palindromes in the given range. */ public static List&lt;Integer&gt; getAllNumberPalindromesInRangeIterative(int start, int end) { return convertLongListToIntegerList(getAllNumberPalindromesInRangeIterative((long) start, (long) end)); } /** * Returns a List containing all the numbers that are palindromes in the range that is given from * start of type short to end of type short. * This is determined by using the iterative algorithm. * * @param start the start of the range, inclusive. * @param end the end of the range, exclusive. * @return List containing all the numbers that are palindromes in the given range. */ public static List&lt;Short&gt; getAllNumberPalindromesInRangeIterative(short start, short end) { return convertLongListToShortList(getAllNumberPalindromesInRangeIterative((long) start, (long) end)); } /** * Returns a List containing all the numbers that are palindromes in the range that is given from * start of type byte to end of type byte. * This is determined by using the iterative algorithm. * * @param start the start of the range, inclusive. * @param end the end of the range, exclusive. * @return List containing all the numbers that are palindromes in the given range. */ public static List&lt;Byte&gt; getAllNumberPalindromesInRangeIterative(byte start, byte end) { return convertLongListToByteList(getAllNumberPalindromesInRangeIterative((long) start, (long) end)); } /* Recursive */ /** * Returns a boolean of whether the char array is a palindrome or not. * This is determined by using the recursive algorithm. * * @param chars char array containing the characters to be checked. * @return boolean of whether the char array is a palindrome or not. */ public static boolean isCharArrayPalindromeRecursive(char[] chars) { if (chars.length &lt; 1) return false; char[] formattedChars = convertAllCharsToUpperCase(chars); return recursion(formattedChars, 0, formattedChars.length - 1); } /** * The recursive algorithm. * * @param chars char array containing the characters to be checked. * @param start the left char being compared. * @param end the right char being compared. * @return boolean of whether the char array is a palindrome or not. */ private static boolean recursion(char[] chars, int start, int end) { if (start == end) return true; if (chars[start] != chars[end]) return false; if (start &lt; end + 1) return recursion(chars, ++start, --end); return true; } /** * Returns a boolean of whether the word of type String is a palindrome or not. * This is determined by using the recursive algorithm. * * @param word the word to be checked. * @return boolean of whether the word is a palindrome or not. */ public static boolean isWordPalindromeRecursive(String word) { return isCharArrayPalindromeRecursive(word.toCharArray()); } /** * Returns a boolean of whether the sentence of type String is a palindrome or not. * This is determined by using the recursive algorithm. * * @param sentence the sentence to be checked. * @return boolean of whether the sentence is a palindrome or not. */ public static boolean isSentencePalindromeRecursive(String sentence) { String newSentence = sentence.replaceAll(&quot;[^a-zA-Z]&quot;, &quot;&quot;); return isWordPalindromeRecursive(newSentence); } /** * Returns a boolean of whether the number of type byte (-128 to 127) is a palindrome or not. * This is determined by using the recursive algorithm. * * @param number the number to be checked. * @return boolean of whether the number is a palindrome or not. */ public static boolean isNumberPalindromeRecursive(byte number) { return isWordPalindromeRecursive(String.valueOf(number)); } /** * Returns a boolean of whether the number of type short (32,768 to 32,767) is a palindrome or not. * This is determined by using the recursive algorithm. * * @param number the number to be checked. * @return boolean of whether the number is a palindrome or not. */ public static boolean isNumberPalindromeRecursive(short number) { return isWordPalindromeRecursive(String.valueOf(number)); } /** * Returns a boolean of whether the number of type int (-2,147,483,648 to 2,147,483,647) is a palindrome or not. * This is determined by using the recursive algorithm. * * @param number the number to be checked. * @return boolean of whether the number is a palindrome or not. */ public static boolean isNumberPalindromeRecursive(int number) { return isWordPalindromeRecursive(String.valueOf(number)); } /** * Returns a boolean of whether the number of type long (-9,223,372,036,854,775,808 to 9,223,372,036,854,775,807) is a palindrome or not. * This is determined by using the recursive algorithm. * * @param number the number to be checked. * @return boolean of whether the number is a palindrome or not. */ public static boolean isNumberPalindromeRecursive(long number) { return isWordPalindromeRecursive(String.valueOf(number)); } /** * Returns a List containing all the numbers that are palindromes in the range that is given from * start of type long to end of type long. * This is determined by using the recursive algorithm. * * @param start the start of the range, inclusive. * @param end the end of the range, exclusive. * @return List containing all the numbers that are palindromes in the given range. */ public static List&lt;Long&gt; getAllNumberPalindromesInRangeRecursive(long start, long end) { List&lt;Long&gt; results = new ArrayList&lt;&gt;(); for (long number = start; number != end; number++) if (isNumberPalindromeRecursive(number)) results.add(number); return results; } /** * Returns a List containing all the numbers that are palindromes in the range that is given from * start of type int to end of type int. * This is determined by using the recursive algorithm. * * @param start the start of the range, inclusive. * @param end the end of the range, exclusive. * @return List containing all the numbers that are palindromes in the given range. */ public static List&lt;Integer&gt; getAllNumberPalindromesInRangeRecursive(int start, int end) { return convertLongListToIntegerList(getAllNumberPalindromesInRangeRecursive((long) start, (long) end)); } /** * Returns a List containing all the numbers that are palindromes in the range that is given from * start of type short to end of type short. * This is determined by using the recursive algorithm. * * @param start the start of the range, inclusive. * @param end the end of the range, exclusive. * @return List containing all the numbers that are palindromes in the given range. */ public static List&lt;Short&gt; getAllNumberPalindromesInRangeRecursive(short start, short end) { return convertLongListToShortList(getAllNumberPalindromesInRangeRecursive((long) start, (long) end)); } /** * Returns a List containing all the numbers that are palindromes in the range that is given from * start of type byte to end of type byte. * This is determined by using the recursive algorithm. * * @param start the start of the range, inclusive. * @param end the end of the range, exclusive. * @return List containing all the numbers that are palindromes in the given range. */ public static List&lt;Byte&gt; getAllNumberPalindromesInRangeRecursive(byte start, byte end) { return convertLongListToByteList(getAllNumberPalindromesInRangeRecursive((long) start, (long) end)); } /** * Converts all letters in the given char array to capital letters if they aren't already. * * @param chars the start of the range, inclusive. * @return char array with the capitalized letters. */ private static char[] convertAllCharsToUpperCase(char[] chars) { char[] formattedChars = new char[chars.length]; for (int i = 0; i != chars.length; i++) if (Character.isLetter(chars[i]) &amp;&amp; Character.isLowerCase(chars[i])) formattedChars[i] = Character.toUpperCase(chars[i]); else formattedChars[i] = chars[i]; return formattedChars; } /** * Converts a List containing Long values to a List of Bytes. * * @param listOfLongs the List containing the Long values * @return the List containing the Byte values */ private static List&lt;Byte&gt; convertLongListToByteList(List&lt;Long&gt; listOfLongs) { List&lt;Byte&gt; result = new ArrayList&lt;&gt;(); for (Long i : listOfLongs) result.add(i.byteValue()); return result; } /** * Converts a List containing Long values to a List of Shorts. * * @param listOfLongs the List containing the Long values * @return the List containing the Shorts values */ private static List&lt;Short&gt; convertLongListToShortList(List&lt;Long&gt; listOfLongs) { List&lt;Short&gt; result = new ArrayList&lt;&gt;(); for (Long i : listOfLongs) result.add(i.shortValue()); return result; } /** * Converts a List containing Long values to a List of Integers. * * @param listOfLongs the List containing the Long values * @return the List containing the Integers values */ private static List&lt;Integer&gt; convertLongListToIntegerList(List&lt;Long&gt; listOfLongs) { List&lt;Integer&gt; result = new ArrayList&lt;&gt;(); for (Long i : listOfLongs) result.add(i.intValue()); return result; } } </code></pre> <p>Palindrome Test Class</p> <pre><code>package com.gr; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.List; import static org.junit.jupiter.api.Assertions.*; @DisplayName(&quot;Palindrome Class&quot;) public class PalindromeTest { // Nested Iterative @Nested class Iterative { @Nested class Word { @Test void testEmptyString() { assertFalse(Palindrome.isWordPalindromeIterative(&quot;&quot;)); } @Test void testSingleLetter() { assertTrue(Palindrome.isWordPalindromeIterative(&quot;A&quot;)); assertTrue(Palindrome.isWordPalindromeIterative(&quot;a&quot;)); } @Test void testName() { assertTrue(Palindrome.isWordPalindromeIterative(&quot;ABBA&quot;)); assertTrue(Palindrome.isWordPalindromeIterative(&quot;Ava&quot;)); assertTrue(Palindrome.isWordPalindromeIterative(&quot;bob&quot;)); assertFalse(Palindrome.isWordPalindromeIterative(&quot;FAIL&quot;)); assertFalse(Palindrome.isWordPalindromeIterative(&quot;Fail&quot;)); assertFalse(Palindrome.isWordPalindromeIterative(&quot;fail&quot;)); } @Test void testWord() { assertTrue(Palindrome.isWordPalindromeIterative(&quot;madam&quot;)); assertTrue(Palindrome.isWordPalindromeIterative(&quot;Racecar&quot;)); assertTrue(Palindrome.isWordPalindromeIterative(&quot;RADAR&quot;)); assertFalse(Palindrome.isWordPalindromeIterative(&quot;FAIL&quot;)); assertFalse(Palindrome.isWordPalindromeIterative(&quot;Fail&quot;)); assertFalse(Palindrome.isWordPalindromeIterative(&quot;fail&quot;)); } } @Nested class Sentence { @Test void testEmptyString() { assertFalse(Palindrome.isSentencePalindromeIterative(&quot;&quot;)); } @Test void testSingleLetter() { assertTrue(Palindrome.isSentencePalindromeIterative(&quot;A&quot;)); assertTrue(Palindrome.isSentencePalindromeIterative(&quot;a&quot;)); } @Test void testSingleWord() { assertTrue(Palindrome.isSentencePalindromeIterative(&quot;madam&quot;)); assertTrue(Palindrome.isSentencePalindromeIterative(&quot;Racecar&quot;)); assertTrue(Palindrome.isSentencePalindromeIterative(&quot;RADAR&quot;)); assertFalse(Palindrome.isSentencePalindromeIterative(&quot;FAIL&quot;)); assertFalse(Palindrome.isSentencePalindromeIterative(&quot;Fail&quot;)); assertFalse(Palindrome.isSentencePalindromeIterative(&quot;fail&quot;)); } @Test void testSentence() { assertTrue(Palindrome.isSentencePalindromeIterative(&quot;Murder for a jar of red rum&quot;)); assertTrue(Palindrome.isSentencePalindromeIterative(&quot;Rats live on no evil star&quot;)); assertTrue(Palindrome.isSentencePalindromeIterative(&quot;step on no pets&quot;)); assertFalse(Palindrome.isSentencePalindromeIterative(&quot;This should fail&quot;)); assertFalse(Palindrome.isSentencePalindromeIterative(&quot;this should fail&quot;)); } @Test void testSentenceWithPunctuation() { assertTrue(Palindrome.isSentencePalindromeIterative(&quot;Do geese see God?&quot;)); assertTrue(Palindrome.isSentencePalindromeIterative(&quot;Live on time, emit no evil&quot;)); assertTrue(Palindrome.isSentencePalindromeIterative(&quot;live on time, emit no evil&quot;)); assertFalse(Palindrome.isSentencePalindromeIterative(&quot;Will this fail?&quot;)); assertFalse(Palindrome.isSentencePalindromeIterative(&quot;will this fail?&quot;)); } } @Nested class Number { @Test void testSingleLongNumber() { assertTrue(Palindrome.isNumberPalindromeIterative(0L)); assertTrue(Palindrome.isNumberPalindromeIterative(1L)); assertTrue(Palindrome.isNumberPalindromeIterative(3L)); } @Test void testBiggerLongNumber() { assertTrue(Palindrome.isNumberPalindromeIterative(123454321L)); assertTrue(Palindrome.isNumberPalindromeIterative(1234567890987654321L)); assertFalse(Palindrome.isNumberPalindromeIterative(123456789L)); assertFalse(Palindrome.isNumberPalindromeIterative(1234567890123456789L)); } @Test void testNegativeLongNumber() { assertTrue(Palindrome.isNumberPalindromeIterative(-0L)); assertFalse(Palindrome.isNumberPalindromeIterative(-123454321L)); assertFalse(Palindrome.isNumberPalindromeIterative(-1234567890987654321L)); assertFalse(Palindrome.isNumberPalindromeIterative(-123456789L)); assertFalse(Palindrome.isNumberPalindromeIterative(-1234567890123456789L)); } @Test void testSingleIntegerNumber() { assertTrue(Palindrome.isNumberPalindromeIterative(0)); assertTrue(Palindrome.isNumberPalindromeIterative(1)); assertTrue(Palindrome.isNumberPalindromeIterative(3)); } @Test void testBiggerIntegerNumber() { assertTrue(Palindrome.isNumberPalindromeIterative(123454321)); assertFalse(Palindrome.isNumberPalindromeIterative(123456789)); } @Test void testNegativeIntegerNumber() { assertTrue(Palindrome.isNumberPalindromeIterative(-0)); assertFalse(Palindrome.isNumberPalindromeIterative(-123454321)); assertFalse(Palindrome.isNumberPalindromeIterative(-123456789)); } @Test void testSingleShortNumber() { assertTrue(Palindrome.isNumberPalindromeIterative((short) 0)); assertTrue(Palindrome.isNumberPalindromeIterative((short) 1)); assertTrue(Palindrome.isNumberPalindromeIterative((short) 3)); } @Test void testBiggerShortNumber() { assertTrue(Palindrome.isNumberPalindromeIterative((short) 12321)); assertFalse(Palindrome.isNumberPalindromeIterative((short) 12345)); } @Test void testNegativeShortNumber() { assertTrue(Palindrome.isNumberPalindromeIterative((short) -0)); assertFalse(Palindrome.isNumberPalindromeIterative((short) -12321)); assertFalse(Palindrome.isNumberPalindromeIterative((short) -12345)); } @Test void testSingleByteNumber() { assertTrue(Palindrome.isNumberPalindromeIterative((byte) 0)); assertTrue(Palindrome.isNumberPalindromeIterative((byte) 1)); assertTrue(Palindrome.isNumberPalindromeIterative((byte) 3)); } @Test void testBiggerByteNumber() { assertTrue(Palindrome.isNumberPalindromeIterative((byte) 121)); assertFalse(Palindrome.isNumberPalindromeIterative((byte) 123)); } @Test void testNegativeByteNumber() { assertTrue(Palindrome.isNumberPalindromeIterative((byte) -0)); assertFalse(Palindrome.isNumberPalindromeIterative((byte) -121)); assertFalse(Palindrome.isNumberPalindromeIterative((byte) -123)); } } @Nested class NumberInRange { @Test void testEmptyRangeLong() { List&lt;Long&gt; expected = new ArrayList&lt;&gt;(); assertEquals(expected, Palindrome.getAllNumberPalindromesInRangeIterative(122L, 130L)); } @Test void testRangeSingleLong() { List&lt;Long&gt; expected = new ArrayList&lt;&gt;() { { add(1L); add(2L); add(3L); } }; assertEquals(expected, Palindrome.getAllNumberPalindromesInRangeIterative(1L, 4L)); } @Test void testRangeLong() { List&lt;Long&gt; expected = new ArrayList&lt;&gt;() { { add(121L); add(131L); add(141L); add(151L); } }; assertEquals(expected, Palindrome.getAllNumberPalindromesInRangeIterative(120L, 155L)); } @Test void testNegativeRangeLong() { List&lt;Long&gt; expected = new ArrayList&lt;&gt;(); assertEquals(expected, Palindrome.getAllNumberPalindromesInRangeIterative(-131L, 0L)); } @Test void testEmptyRangeInteger() { List&lt;Integer&gt; expected = new ArrayList&lt;&gt;(); assertEquals(expected, Palindrome.getAllNumberPalindromesInRangeIterative(122, 130)); } @Test void testRangeSingleInteger() { List&lt;Integer&gt; expected = new ArrayList&lt;&gt;() { { add(1); add(2); add(3); } }; assertEquals(expected, Palindrome.getAllNumberPalindromesInRangeIterative(1, 4)); } @Test void testRangeInteger() { List&lt;Integer&gt; expected = new ArrayList&lt;&gt;() { { add(121); add(131); add(141); add(151); } }; assertEquals(expected, Palindrome.getAllNumberPalindromesInRangeIterative(120, 155)); } @Test void testNegativeRangeInteger() { List&lt;Integer&gt; expected = new ArrayList&lt;&gt;(); assertEquals(expected, Palindrome.getAllNumberPalindromesInRangeIterative(-131, 0)); } @Test void testEmptyRangeShort() { List&lt;Short&gt; expected = new ArrayList&lt;&gt;(); assertEquals(expected, Palindrome.getAllNumberPalindromesInRangeIterative((short) 122, (short) 130)); } @Test void testRangeSingleShort() { List&lt;Short&gt; expected = new ArrayList&lt;&gt;() { { add((short) 1); add((short) 2); add((short) 3); } }; assertEquals(expected, Palindrome.getAllNumberPalindromesInRangeIterative((short) 1, (short) 4)); } @Test void testRangeShort() { List&lt;Short&gt; expected = new ArrayList&lt;&gt;() { { add((short) 121); add((short) 131); add((short) 141); add((short) 151); } }; assertEquals(expected, Palindrome.getAllNumberPalindromesInRangeIterative((short) 120, (short) 155)); } @Test void testNegativeRangeShort() { List&lt;Short&gt; expected = new ArrayList&lt;&gt;(); assertEquals(expected, Palindrome.getAllNumberPalindromesInRangeIterative((short) -131, (short) 0)); } @Test void testEmptyRangeByte() { List&lt;Byte&gt; expected = new ArrayList&lt;&gt;(); assertEquals(expected, Palindrome.getAllNumberPalindromesInRangeIterative((byte) 122, (byte) 125)); } @Test void testRangeSingleByte() { List&lt;Byte&gt; expected = new ArrayList&lt;&gt;() { { add((byte) 1); add((byte) 2); add((byte) 3); } }; assertEquals(expected, Palindrome.getAllNumberPalindromesInRangeIterative((byte) 1, (byte) 4)); } @Test void testRangeByte() { List&lt;Byte&gt; expected = new ArrayList&lt;&gt;() { { add((byte) 101); add((byte) 111); add((byte) 121); } }; assertEquals(expected, Palindrome.getAllNumberPalindromesInRangeIterative((byte) 100, (byte) 125)); } @Test void testNegativeRangeByte() { List&lt;Byte&gt; expected = new ArrayList&lt;&gt;(); assertEquals(expected, Palindrome.getAllNumberPalindromesInRangeIterative((byte) -125, (byte) 0)); } } } @Nested class Recursive { @Nested class Word { @Test void testEmptyString() { assertFalse(Palindrome.isWordPalindromeRecursive(&quot;&quot;)); } @Test void testSingleLetter() { assertTrue(Palindrome.isWordPalindromeRecursive(&quot;A&quot;)); assertTrue(Palindrome.isWordPalindromeRecursive(&quot;a&quot;)); } @Test void testName() { assertTrue(Palindrome.isWordPalindromeRecursive(&quot;ABBA&quot;)); assertTrue(Palindrome.isWordPalindromeRecursive(&quot;Ava&quot;)); assertTrue(Palindrome.isWordPalindromeRecursive(&quot;bob&quot;)); assertFalse(Palindrome.isWordPalindromeRecursive(&quot;FAIL&quot;)); assertFalse(Palindrome.isWordPalindromeRecursive(&quot;Fail&quot;)); assertFalse(Palindrome.isWordPalindromeRecursive(&quot;fail&quot;)); } @Test void testWord() { assertTrue(Palindrome.isWordPalindromeRecursive(&quot;madam&quot;)); assertTrue(Palindrome.isWordPalindromeRecursive(&quot;Racecar&quot;)); assertTrue(Palindrome.isWordPalindromeRecursive(&quot;RADAR&quot;)); assertFalse(Palindrome.isWordPalindromeRecursive(&quot;FAIL&quot;)); assertFalse(Palindrome.isWordPalindromeRecursive(&quot;Fail&quot;)); assertFalse(Palindrome.isWordPalindromeRecursive(&quot;fail&quot;)); } } @Nested class Sentence { @Test void testEmptyString() { assertFalse(Palindrome.isSentencePalindromeRecursive(&quot;&quot;)); } @Test void testSingleLetter() { assertTrue(Palindrome.isSentencePalindromeRecursive(&quot;A&quot;)); assertTrue(Palindrome.isSentencePalindromeRecursive(&quot;a&quot;)); } @Test void testSingleWord() { assertTrue(Palindrome.isSentencePalindromeRecursive(&quot;madam&quot;)); assertTrue(Palindrome.isSentencePalindromeRecursive(&quot;Racecar&quot;)); assertTrue(Palindrome.isSentencePalindromeRecursive(&quot;RADAR&quot;)); assertFalse(Palindrome.isSentencePalindromeRecursive(&quot;FAIL&quot;)); assertFalse(Palindrome.isSentencePalindromeRecursive(&quot;Fail&quot;)); assertFalse(Palindrome.isSentencePalindromeRecursive(&quot;fail&quot;)); } @Test void testSentence() { assertTrue(Palindrome.isSentencePalindromeRecursive(&quot;Murder for a jar of red rum&quot;)); assertTrue(Palindrome.isSentencePalindromeRecursive(&quot;Rats live on no evil star&quot;)); assertTrue(Palindrome.isSentencePalindromeRecursive(&quot;step on no pets&quot;)); assertFalse(Palindrome.isSentencePalindromeRecursive(&quot;This should fail&quot;)); assertFalse(Palindrome.isSentencePalindromeRecursive(&quot;this should fail&quot;)); } @Test void testSentenceWithPunctuation() { assertTrue(Palindrome.isSentencePalindromeRecursive(&quot;Do geese see God?&quot;)); assertTrue(Palindrome.isSentencePalindromeRecursive(&quot;Live on time, emit no evil&quot;)); assertTrue(Palindrome.isSentencePalindromeRecursive(&quot;live on time, emit no evil&quot;)); assertFalse(Palindrome.isSentencePalindromeRecursive(&quot;Will this fail?&quot;)); assertFalse(Palindrome.isSentencePalindromeRecursive(&quot;will this fail?&quot;)); } } @Nested class Number { @Test void testSingleLongNumber() { assertTrue(Palindrome.isNumberPalindromeRecursive(0L)); assertTrue(Palindrome.isNumberPalindromeRecursive(1L)); assertTrue(Palindrome.isNumberPalindromeRecursive(3L)); } @Test void testBiggerLongNumber() { assertTrue(Palindrome.isNumberPalindromeRecursive(123454321L)); assertTrue(Palindrome.isNumberPalindromeRecursive(1234567890987654321L)); assertFalse(Palindrome.isNumberPalindromeRecursive(123456789L)); assertFalse(Palindrome.isNumberPalindromeRecursive(1234567890123456789L)); } @Test void testNegativeLongNumber() { assertTrue(Palindrome.isNumberPalindromeRecursive(-0L)); assertFalse(Palindrome.isNumberPalindromeRecursive(-123454321L)); assertFalse(Palindrome.isNumberPalindromeRecursive(-1234567890987654321L)); assertFalse(Palindrome.isNumberPalindromeRecursive(-123456789L)); assertFalse(Palindrome.isNumberPalindromeRecursive(-1234567890123456789L)); } @Test void testSingleIntegerNumber() { assertTrue(Palindrome.isNumberPalindromeRecursive(0)); assertTrue(Palindrome.isNumberPalindromeRecursive(1)); assertTrue(Palindrome.isNumberPalindromeRecursive(3)); } @Test void testBiggerIntegerNumber() { assertTrue(Palindrome.isNumberPalindromeRecursive(123454321)); assertFalse(Palindrome.isNumberPalindromeRecursive(123456789)); } @Test void testNegativeIntegerNumber() { assertTrue(Palindrome.isNumberPalindromeRecursive(-0)); assertFalse(Palindrome.isNumberPalindromeRecursive(-123454321)); assertFalse(Palindrome.isNumberPalindromeRecursive(-123456789)); } @Test void testSingleShortNumber() { assertTrue(Palindrome.isNumberPalindromeRecursive((short) 0)); assertTrue(Palindrome.isNumberPalindromeRecursive((short) 1)); assertTrue(Palindrome.isNumberPalindromeRecursive((short) 3)); } @Test void testBiggerShortNumber() { assertTrue(Palindrome.isNumberPalindromeRecursive((short) 12321)); assertFalse(Palindrome.isNumberPalindromeRecursive((short) 12345)); } @Test void testNegativeShortNumber() { assertTrue(Palindrome.isNumberPalindromeRecursive((short) -0)); assertFalse(Palindrome.isNumberPalindromeRecursive((short) -12321)); assertFalse(Palindrome.isNumberPalindromeRecursive((short) -12345)); } @Test void testSingleByteNumber() { assertTrue(Palindrome.isNumberPalindromeRecursive((byte) 0)); assertTrue(Palindrome.isNumberPalindromeRecursive((byte) 1)); assertTrue(Palindrome.isNumberPalindromeRecursive((byte) 3)); } @Test void testBiggerByteNumber() { assertTrue(Palindrome.isNumberPalindromeRecursive((byte) 121)); assertFalse(Palindrome.isNumberPalindromeRecursive((byte) 123)); } @Test void testNegativeByteNumber() { assertTrue(Palindrome.isNumberPalindromeRecursive((byte) -0)); assertFalse(Palindrome.isNumberPalindromeRecursive((byte) -121)); assertFalse(Palindrome.isNumberPalindromeRecursive((byte) -123)); } } @Nested class NumberInRange { @Test void testEmptyRangeLong() { List&lt;Long&gt; expected = new ArrayList&lt;&gt;(); assertEquals(expected, Palindrome.getAllNumberPalindromesInRangeRecursive(122L, 130L)); } @Test void testRangeSingleLong() { List&lt;Long&gt; expected = new ArrayList&lt;&gt;() { { add(1L); add(2L); add(3L); } }; assertEquals(expected, Palindrome.getAllNumberPalindromesInRangeRecursive(1L, 4L)); } @Test void testRangeLong() { List&lt;Long&gt; expected = new ArrayList&lt;&gt;() { { add(121L); add(131L); add(141L); add(151L); } }; assertEquals(expected, Palindrome.getAllNumberPalindromesInRangeRecursive(120L, 155L)); } @Test void testNegativeRangeLong() { List&lt;Long&gt; expected = new ArrayList&lt;&gt;(); assertEquals(expected, Palindrome.getAllNumberPalindromesInRangeRecursive(-131L, 0L)); } @Test void testEmptyRangeInteger() { List&lt;Integer&gt; expected = new ArrayList&lt;&gt;(); assertEquals(expected, Palindrome.getAllNumberPalindromesInRangeRecursive(122, 130)); } @Test void testRangeSingleInteger() { List&lt;Integer&gt; expected = new ArrayList&lt;&gt;() { { add(1); add(2); add(3); } }; assertEquals(expected, Palindrome.getAllNumberPalindromesInRangeRecursive(1, 4)); } @Test void testRangeInteger() { List&lt;Integer&gt; expected = new ArrayList&lt;&gt;() { { add(121); add(131); add(141); add(151); } }; assertEquals(expected, Palindrome.getAllNumberPalindromesInRangeRecursive(120, 155)); } @Test void testNegativeRangeInteger() { List&lt;Integer&gt; expected = new ArrayList&lt;&gt;(); assertEquals(expected, Palindrome.getAllNumberPalindromesInRangeRecursive(-131, 0)); } @Test void testEmptyRangeShort() { List&lt;Short&gt; expected = new ArrayList&lt;&gt;(); assertEquals(expected, Palindrome.getAllNumberPalindromesInRangeRecursive((short) 122, (short) 130)); } @Test void testRangeSingleShort() { List&lt;Short&gt; expected = new ArrayList&lt;&gt;() { { add((short) 1); add((short) 2); add((short) 3); } }; assertEquals(expected, Palindrome.getAllNumberPalindromesInRangeRecursive((short) 1, (short) 4)); } @Test void testRangeShort() { List&lt;Short&gt; expected = new ArrayList&lt;&gt;() { { add((short) 121); add((short) 131); add((short) 141); add((short) 151); } }; assertEquals(expected, Palindrome.getAllNumberPalindromesInRangeRecursive((short) 120, (short) 155)); } @Test void testNegativeRangeShort() { List&lt;Short&gt; expected = new ArrayList&lt;&gt;(); assertEquals(expected, Palindrome.getAllNumberPalindromesInRangeRecursive((short) -131, (short) 0)); } @Test void testEmptyRangeByte() { List&lt;Byte&gt; expected = new ArrayList&lt;&gt;(); assertEquals(expected, Palindrome.getAllNumberPalindromesInRangeRecursive((byte) 122, (byte) 125)); } @Test void testRangeSingleByte() { List&lt;Byte&gt; expected = new ArrayList&lt;&gt;() { { add((byte) 1); add((byte) 2); add((byte) 3); } }; assertEquals(expected, Palindrome.getAllNumberPalindromesInRangeRecursive((byte) 1, (byte) 4)); } @Test void testRangeByte() { List&lt;Byte&gt; expected = new ArrayList&lt;&gt;() { { add((byte) 101); add((byte) 111); add((byte) 121); } }; assertEquals(expected, Palindrome.getAllNumberPalindromesInRangeRecursive((byte) 100, (byte) 125)); } @Test void testNegativeRangeByte() { List&lt;Byte&gt; expected = new ArrayList&lt;&gt;(); assertEquals(expected, Palindrome.getAllNumberPalindromesInRangeRecursive((byte) -125, (byte) 0)); } } } } <span class="math-container">```</span> </code></pre>
[]
[ { "body": "<p>Having a common interface for the algorithm would solve the code duplication between tests for different implementations. You create a set of tests that any implementation of the interface should fulfill and then just throw different implementations at it (see the <a href=\"https://en.wikipedia.org/wiki/SOLID\" rel=\"nofollow noreferrer\">L in SOLID principles</a>).</p>\n<p>For testing a large set of simple string inputs, put the valid entries into one array and invalid ones in another and create two tests that loop over each array.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-27T04:14:28.767", "Id": "248489", "ParentId": "248477", "Score": "1" } }, { "body": "<p>This looks great, enjoyable to read despite the repetition.</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code>package com.gr;\n</code></pre>\n<p>Packages should associate with the author, so they should be something like <code>com.github.lucifer.palindrome</code> for example. But depending on whether this code is being published or not, it does not matter in this case.</p>\n<hr />\n<p>This would be a great exercise for object-oriented programming by creating an interface and having two separate implementations:</p>\n<pre class=\"lang-java prettyprint-override\"><code>public interface PalindromeTester;\npublic class IterativePalindromeTester implements PalindromeTester;\npublic class RecursivePalindromeTester implements PalindromeTester;\n</code></pre>\n<p>That would solve one-half of your overloading question. The other half is the <code>Number</code>/<code>CharArray</code>/<code>Word</code> thing, you should drop that from the name as it is obvious from the accepted parameters. IT would also cleanup your test-case a bit, as it would be two different test-classes. You even have an <code>abstract</code> test-class and extend that and only set a different instance of <code>PalindromeTester</code> on <code>BeforeEach</code>.</p>\n<p>Another thing is, if you can live with widening given values, you could only provide a single method accepting a <code>long</code>. Any <code>short</code>/<code>int</code> will be automatically converted, but that, of course, requires a widening operation under the hood.</p>\n<p>There's also <code>Number</code>/<code>BigInteger</code>, which you might want to include.</p>\n<p>On another note, you could drop <code>char[]</code> in favor of <code>CharSequence</code>. The later is the base for many different classes (including <code>String</code>, so no overload required) and represents the intent a little better. Regarding that, if you accept any letter, including foreign languages, you most likely want to to work on code-points (<code>int</code>) instead of <code>char</code>s. In UTF-8/UTF-16, not all letters are only a single byte, but can be composed of multiples bytes (up to four, hence <code>int</code>).</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code> * Returns a boolean of whether the number of type short (32,768 to 32,767)\n</code></pre>\n<p>Don't include min/max values like that in the documentation. First, it's redundant as it is obvious from the used type. Second, it is prone to typos, like in this case.</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code> List&lt;Long&gt; results = new ArrayList&lt;&gt;();\n for (long number = start; number != end; number++)\n if (isNumberPalindromeRecursive(number))\n results.add(number);\n</code></pre>\n<p>Be aware that this is autoboxing, meaning a primitive is automatically converted to an <code>Object</code> instance.</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code>for (int i = 0; i != formattedChars.length / 2; i++)\n</code></pre>\n<p>First, I'm a persistent advocate of &quot;real&quot; names for loop variables, like <code>index</code> or <code>counter</code>.</p>\n<p>Second, you should revise the break condition to be more robust by checking whether the value is equal or greater the half length.</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code> boolean isPalindrome = true;\n for (int i = 0; i != formattedChars.length / 2; i++)\n if (formattedChars[i] != formattedChars[(formattedChars.length - 1) - i]) {\n isPalindrome = false;\n break;\n }\n return isPalindrome;\n</code></pre>\n<p>Don't store the result, return it directly.</p>\n<pre class=\"lang-java prettyprint-override\"><code> for (int i = 0; i != formattedChars.length / 2; i++)\n if (formattedChars[i] != formattedChars[(formattedChars.length - 1) - i])\n return false;\n \n return true;\n<span class=\"math-container\">```</span>\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-09-01T08:36:06.133", "Id": "487380", "Score": "0", "body": "Hi, thx for the extensive feedback. gr are my initials which is why I named the package com.gr but I could change it to my Github name since I have a repo there for this project. Im guessing I can create an Interface and 2 implementations for the code itself and also the test cases?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-09-01T18:16:09.860", "Id": "487444", "Score": "0", "body": "I wouldn't create an interface for the test-cases, but an `abstract` test-case with concrete implementations for each implementation would be suitable." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-27T16:51:04.613", "Id": "248509", "ParentId": "248477", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-26T18:47:23.700", "Id": "248477", "Score": "3", "Tags": [ "java", "object-oriented", "palindrome", "junit" ], "Title": "Palindrome Algorithm and JUnit 5 Tests" }
248477
<p>I'm looking for someone to really tear apart the following code I wrote for my graduate-level algorithms class. The problem was Optimal Caching, and the algorithm I'm implementing is called &quot;Farthest in Future&quot;, which looks to see which cache item is either NOT in the request, or one who's first occurrence appears LAST compared to the other items.</p> <p>I'm looking for ways to get the run-time down. Right now I think it's O(n+k), with n being the length of requests and k being the length of the cache, after the initial data structure (the indices dict) is created. Please let me know if I'm wrong! I'm still learning!</p> <p>Also looking how I can better organize my code like this in the future.</p> <pre><code>cache = ['a', 'b', 'c', 'd'] requests = ['e', 'f', 'c', 'g'] def get_items(cache, queue): # Handles cache &quot;hits&quot; def cache_hit(item): print('HIT', cache) return item def cache_miss(item): # evict &quot;farthest in future&quot; item fif = get_farthest_in_future(cache, queue) cache.remove(fif) cache.append(item) print('MISS', cache) # Predicts which item occurs &quot;farthest in the future&quot; def get_farthest_in_future(cache, requests): max_index = 0 for cache_item in cache: # next appearance if len(indices[cache_item]) &gt; 0: next_appearance = indices[cache_item][0] if next_appearance &gt; max_index: max_index = next_appearance fif = requests[max_index] break else: fif = cache_item break return fif #### CREATE DATA STRUCTURES ##### def get_indices(cache, queue): indices = {} # ensure that every cache item # has an entry in the dict for cache_item in cache: indices[cache_item] = [] for i, item in enumerate(queue): if item not in indices: indices[item] = [i] else: indices[item].append(i) return indices indices = get_indices(cache, queue) for item in queue: print('request:', item) # update indices indices[item].pop(0) if item in cache: cache_hit(item) else: cache_miss(item) get_items(cache, requests) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-26T23:20:35.420", "Id": "486754", "Score": "2", "body": "What's the expected result?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-27T01:39:17.423", "Id": "486761", "Score": "0", "body": "@StefanPochmann If I understand it correctly: see if the requested value is at the head of the cache. If it isn't, add the requested value to the tail of the cache. But I'm not 100% sure on that, so clarification is welcome." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-27T09:43:02.203", "Id": "486787", "Score": "2", "body": "@Mast Nah I don't mean how to achieve the goal, but *what is* the goal? Is it the modified `cache`? Is it the `print` outputs? And what are these for the given example data?" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-26T20:39:27.443", "Id": "248480", "Score": "2", "Tags": [ "python", "performance" ], "Title": "Optimal Caching - \"Farthest in Future\" Algorithm" }
248480
<p>I built an backend using Django and the django-rest-framework and realized that a lot of the code snippets (mainly classes) are similar. Is there any better way? I tried to wrap them into a very generic class, but didn't succeed yet. This is what I mean by &quot;similar serializers&quot;:</p> <pre><code>... class DeviceSerializer(serializers.ModelSerializer): class Meta: fields = '__all__' model = Device class UserSerializer(serializers.ModelSerializer): class Meta: fields = '__all__' model = User ... </code></pre> <p>Then there are the viewsets:</p> <pre><code>... class DeviceAPI(mixins.ListModelMixin, viewsets.GenericViewSet): model = Device serializer_class = DeviceSerializer queryset = Device.objects.all() class UserAPI(mixins.ListModelMixin, viewsets.GenericViewSet): model = User serializer_class = UserSerializer queryset = User.objects.all() ... </code></pre> <p>This goes on for about 150 lines of code as I have a lot of models. I tried wrapping them into one generic serializer and one viewset, but the Swagger generator didn't register all the serializer classes then.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-26T23:06:51.397", "Id": "248485", "Score": "1", "Tags": [ "python", "django" ], "Title": "How to eliminate repetitive serializers and API Viewsets in Django Rest Framework" }
248485
<p>I'm working on a Django project for which I'll need to store the historic information of many models.</p> <p>So far, I'm using the following strategy:</p> <ol> <li>Memoize the relevant values in <code>__init__</code>.</li> <li>When saving, check if a relevant value has changed.</li> <li>If a relevant value has changed, save memoized values into a &quot;history&quot; model.</li> </ol> <p>My code goes as follows:</p> <pre><code>from django.db import models from core.models import User class Spam(models.Model): user= models.OneToOneField(User, on_delete=models.PROTECT, related_name='spam') ham = models.CharField(max_length=10) eggs = models.IntegerField() def __init__(self, *args, **kwargs): super(Spam, self).__init__(*args, **kwargs) self.__relevant_fields = ['ham', 'eggs'] self._memoize() def _memoize(self): for f in self.__relevant_fields: setattr(self, '__prev_%s' % f, getattr(self, f)) def _get_prev_value(self, f): return getattr(self, '__prev_%s' % f) def _dirty_field(self, f) -&gt; bool: return getattr(self, '__prev_%s' % f) != getattr(self, f) def _dirty(self) -&gt; bool: return any([self._dirty_field(f) for f in self.__relevant_fields]) def _save_history(self): history = dict() for f in self.__relevant_fields: history[f] = self._get_prev_value(f) self.user.spam_history.create(**history) def save(self, *args, **kwargs): super(Spam, self).save(*args, **kwargs) if self._dirty(): self._save_history() class SpamHistory(models.Model): user = models.ForeignKey(User, on_delete=models.PROTECT, related_name='spam_history') ham = models.CharField(max_length=10) eggs = models.IntegerField() </code></pre> <p>Although this approach works, there are some things that make me uncomfortable:</p> <ol> <li>I need to do this for many models, so I'm repeating myself a lot! I'm looking into inheritance, mixins or the like, but so far I haven't found a right way to make it work.</li> <li>Is this the best approach to achieve what I want? Considering that I will need to fetch historic records frequently, I need the &quot;history&quot; model for each model I need to keep history from.</li> </ol> <p>So, my specific questions are:</p> <ul> <li>Am I implementing a good strategy for keeping the history of my model(s)?</li> <li>Is there a way to improve this strategy by using an inheritance or mixin strategy?</li> </ul>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-27T02:00:42.920", "Id": "486762", "Score": "1", "body": "Third-party tools might exist that will do this for you." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-27T02:02:07.313", "Id": "486763", "Score": "0", "body": "@FMc I'll search for them (if you know of one, could you share it?)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-27T02:06:53.757", "Id": "486764", "Score": "0", "body": "@Fmc I've found [django-model-changes-py3](https://github.com/iansprice/django-model-changes-py3); however, it seems that this just saves the current state plus the two previous states of the model instance... I'd like to keep the full history." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-27T02:13:44.763", "Id": "486765", "Score": "1", "body": "@FMc Ook! I found what I need: [django-simple-history](https://pypi.org/project/django-simple-history/)! Right now I'm feeling a bit dumb I didn't found this earlier." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-29T13:47:38.247", "Id": "487031", "Score": "1", "body": "@Graipher indeed. Correcting now" } ]
[ { "body": "<p>Ok, after googling a bit more, I found a possible solution: <a href=\"https://pypi.org/project/django-simple-history/\" rel=\"nofollow noreferrer\">django-simple-history</a>:</p>\n<pre><code>from django.db import models\nfrom core.models import User\nfrom simple_history.models import HistoricalRecords\n\nclass Spam(models.Model):\n user = models.OneToOneField(User, on_delete=models.PROTECT, related_name='spam')\n ham = models.CharField(max_length=10)\n eggs = models.IntegerField()\n history = HistoricalRecords()\n</code></pre>\n<p>This seems to do exactly what I need to do. I'll test it.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-27T02:18:03.377", "Id": "248487", "ParentId": "248486", "Score": "1" } } ]
{ "AcceptedAnswerId": "248487", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-27T00:18:09.143", "Id": "248486", "Score": "2", "Tags": [ "python", "django" ], "Title": "Keeping history of Django model (by using memoization?)" }
248486
<p>I had problems with related objects not deleted when deleting objects in bulk in Django, so I disabled the <code>delete()</code> method in Django managers and querysets. I also disabled <code>bulk_create()</code>.</p> <pre class="lang-py prettyprint-override"><code>from django.contrib.auth import models as django_auth_models from django.db import models class QuerySet(models.query.QuerySet): def delete(self): raise NotImplementedError(&quot;delete is not implemented.&quot;) class ManagerMixin(object): def bulk_create(self, *args, **kwargs): raise NotImplementedError(&quot;bulk_create is not implemented.&quot;) def delete(self): raise NotImplementedError(&quot;delete is not implemented.&quot;) def get_queryset(self): &quot;&quot;&quot; Use our own QuerySet model without method .delete(). &quot;&quot;&quot; return QuerySet(model=self.model, using=self._db, hints=self._hints) class BaseManager(ManagerMixin, models.Manager): pass class BaseUserManager(ManagerMixin, django_auth_models.BaseUserManager): pass </code></pre> <p>These classes (<code>BaseManager</code> and <code>BaseUserManager</code>) are used for managers or base classes to inherit for managers in my models (one of them, not both). For example, <code>UserManager</code> is defined like this:</p> <pre class="lang-py prettyprint-override"><code>class UserManager(BaseUserManager): </code></pre> <p>I added tests to the models to test it works:</p> <pre class="lang-py prettyprint-override"><code>def test_cannot_create_users_with_bulk_create(self): user_1 = User(slug='zzzzzz') user_2 = User(slug='ZZZ-ZZZ') with self.assertRaises(NotImplementedError) as cm: User.objects.bulk_create([user_1, user_2]) self.assertEqual(first=str(cm.exception), second=&quot;bulk_create is not implemented.&quot;) def test_cannot_delete_users_with_queryset_delete(self): with self.assertRaises(NotImplementedError) as cm: User.objects.delete() self.assertEqual(first=str(cm.exception), second=&quot;delete is not implemented.&quot;) with self.assertRaises(NotImplementedError) as cm: User.objects.all().delete() self.assertEqual(first=str(cm.exception), second=&quot;delete is not implemented.&quot;) with self.assertRaises(NotImplementedError) as cm: User.objects.filter(pk=1).delete() self.assertEqual(first=str(cm.exception), second=&quot;delete is not implemented.&quot;) with self.assertRaises(NotImplementedError) as cm: User.objects.all().exclude(pk=2).delete() self.assertEqual(first=str(cm.exception), second=&quot;delete is not implemented.&quot;) </code></pre> <p>What do you think about this solution?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-28T22:45:08.113", "Id": "486972", "Score": "0", "body": "There are fancier ways to achieve this, but your mixin strategy seems easy and practical. I do wonder why you need more than one mixin. For example, why not a single mixin called `class Undeletable`, which would override all of the necessary methods – `delete()`, `bulk_update()`, whatever? Perhaps I'm overlooking a key detail, but a general-purpose no-delete mixin would be my first instinct." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-29T02:02:34.903", "Id": "486985", "Score": "1", "body": "Related objects not being deleted probably means you need to set `on_delete=models.CASCADE` on your `ForeignKey` rather than add custom managers that remove a method that you will probably need at some point. What issue did you have?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-29T08:18:04.567", "Id": "487003", "Score": "0", "body": "@FMc I'm not sure if I understand what you mean. I could have defined a mixin that disables the `delete` method and then use it both in my own defined `QuerySet` and in `ManagerMixin`, but since it's only 2 lines of code I decided to duplicate them. But I'm not sure if that's what you meant? `BaseManager` is used either as a manager or a base class for all my defined managers, and `BaseUserManager` is used as a base class for my `UserManager`. What do you think I could have done better?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-29T08:23:12.473", "Id": "487005", "Score": "0", "body": "@IainShelvington models are already defined with `on_delete=models.CASCADE`, but it didn't work for me in a test when using `delete` in bulk. It does work when deleting each object manually. That's why I disabled the `delete` methods." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-27T02:35:42.297", "Id": "248488", "Score": "1", "Tags": [ "python", "django" ], "Title": "Disabling the delete() method in Django managers and querysets" }
248488
<p>I have started to learn Python and have chosen Conway's game of life as my first program. I would be interested in reading how to write more idiomatic Python. Also, what threw me off for some time was that everything is passed by reference and assignment of a list doesn't copy its values but copies the reference. Therefore, I have used the deepcopy function, but I am thinking that lists might be the wrong choice in this case. What would be a better choice in Python?</p> <pre><code>&quot;&quot;&quot; Implementation of LIFE &quot;&quot;&quot; import copy # PARAMETERS # Number of generations to simulate N_GENERATIONS = 10 # Define the field. Dots (.) are dead cells, the letter &quot;o&quot; represents living cells INITIAL_FIELD = \ &quot;&quot;&quot; ................... ................... ................... ................... .ooooo.ooooo.ooooo. ................... ................... ................... ................... &quot;&quot;&quot; # FUNCTIONS def print_field(field_copy, dead_cells=' ', living_cells='x'): &quot;&quot;&quot;Pretty-print the current field.&quot;&quot;&quot; field_string = &quot;\n&quot;.join([&quot;&quot;.join(x) for x in field_copy]) field_string = field_string.replace('.', dead_cells) field_string = field_string.replace('o', living_cells) print(field_string) def get_neighbours(field_copy, x, y): &quot;&quot;&quot;Get all neighbours around a cell with position x and y and return them in a list.&quot;&quot;&quot; n_rows = len(field_copy) n_cols = len(field_copy[0]) if y == 0: y_idx = [y, y+1] elif y == n_rows - 1: y_idx = [y-1, y] else: y_idx = [y-1, y, y+1] if x == 0: x_idx = [x, x+1] elif x == n_cols - 1: x_idx = [x-1, x] else: x_idx = [x-1, x, x+1] neigbours = [field_copy[row][col] for row in y_idx for col in x_idx if (row, col) != (y, x)] return neigbours def count_living_cells(cell_list): &quot;&quot;&quot;Count the living cells.&quot;&quot;&quot; accu = 0 for cell in cell_list: if cell == 'o': accu = accu + 1 return accu def update_field(field_copy): &quot;&quot;&quot;Update the field to the next generation.&quot;&quot;&quot; new_field = copy.deepcopy(field_copy) for row in range(len(field_copy)): for col in range(len(field_copy[0])): living_neighbours = count_living_cells(get_neighbours(field_copy, col, row)) if living_neighbours &lt; 2 or living_neighbours &gt; 3: new_field[row][col] = '.' elif living_neighbours == 3: new_field[row][col] = 'o' return new_field # MAIN # Convert the initial playfield to an array field = str.splitlines(INITIAL_FIELD) field = field[1:] # Getting rid of the empty first element due to the multiline string field = [list(x) for x in field] print(&quot;Generation 0&quot;) print_field(field) for generation in range(1, N_GENERATIONS+1): field = update_field(field) print(f&quot;Generation {generation}&quot;) print(&quot;&quot;) print_field(field) print(&quot;&quot;) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-27T14:15:24.513", "Id": "486809", "Score": "0", "body": "I would prefer using e.g. a numpy array to hold the field rather than a string." } ]
[ { "body": "<p><strong>Comment 1</strong></p>\n<p>There is no need to have a special case for printing Generation 0.</p>\n<p>Just let your range start from 0 and print before you update.</p>\n<pre><code>for generation in range(N_GENERATIONS+1):\n print(f&quot;Generation {generation}&quot;)\n print(&quot;&quot;)\n print_field(field)\n print(&quot;&quot;)\n field = update_field(field)\n</code></pre>\n<p><strong>Comment 2</strong></p>\n<p>Also, it looks like you are adjusting your code quite a bit to the way you define <code>INITIAL_FIELD</code> as a multiline string, just because it looks nice that way in the code window. This is backwards.</p>\n<p>You should rather define it as a list of strings so that you don't have to do splitlines and those other things on it before starting the program. If you still want to make it human-readable, you can use some line breaks <code>\\ </code>(if needed), but I think the syntax will be ok even without that.</p>\n<pre><code>INITIAL_FIELD = [\n &quot;...................&quot;,\n &quot;...................&quot;,\n etc\n ]\n</code></pre>\n<p><strong>Comment 3</strong></p>\n<pre><code>def print_field(field_copy, dead_cells=' ', living_cells='x'):\n</code></pre>\n<p>This function accepts two parameters but no call to it ever passes them in. So they are in fact just internal variables and should not be in the function definition.</p>\n<p><strong>Comment 4</strong></p>\n<pre><code>field_string = field_string.replace('.', dead_cells)\nfield_string = field_string.replace('o', living_cells)\nprint(field_string)\n</code></pre>\n<p>This is unnecessary repetition and hard to read. I would rather chain those 3 lines into one</p>\n<pre><code>print(field_string.replace('.', dead_cells).replace('o', living_cells))\n</code></pre>\n<p><strong>Comment 5</strong></p>\n<pre><code>def count_living_cells(cell_list):\n &quot;&quot;&quot;Count the living cells.&quot;&quot;&quot;\n accu = 0\n\n for cell in cell_list:\n if cell == 'o':\n accu = accu + 1\n\n return accu\n</code></pre>\n<p>This is also backwards, due to how you represent your cells as characters and strings.</p>\n<p>It would be more sensible I think to prioritize simple program logic and let the print functions adjust as needed.\nIf you represent live cells as the number 1 and dead cells as the number 0, then a cell list would look like <code>[0,1,1,0,0,1,0]</code> and this function could be written as</p>\n<pre><code>return sum(cell_list)\n</code></pre>\n<p>Actually, you wouldn't even need a function anymore, since this is so short.</p>\n<p>In your print function you could then replace 1 by some other character and 0 by some other character before printing.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-27T18:44:33.640", "Id": "486826", "Score": "0", "body": "Thanks for your suggestions! Especially comment 5 is great!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-27T14:10:56.350", "Id": "248502", "ParentId": "248491", "Score": "4" } }, { "body": "<p>I think your <code>get_neighbor</code> function can be cleaned up using <code>min</code> and <code>max</code>, and by making use of <code>range</code>s:</p>\n<pre><code>def get_neighbours(field_copy, x, y):\n &quot;&quot;&quot;Get all neighbours around a cell with position x and y\n and return them in a list.&quot;&quot;&quot;\n n_rows = len(field_copy)\n n_cols = len(field_copy[0])\n\n min_x = max(0, x - 1)\n max_x = min(x + 1, n_cols - 1)\n\n min_y = max(0, y - 1)\n max_y = min(y + 1, n_rows - 1)\n\n return [field_copy[row][col]\n for row in range(min_y, max_y + 1)\n for col in range(min_x, max_x + 1)\n if (row, col) != (y, x)]\n</code></pre>\n<p>It's still quite long, but it does away with all the messy <code>if</code> dispatching to hard-coded lists of indices. I also broke up the list comprehension over a few lines. Whenever my comprehensions start to get a little long, I break them up like that. I find it significantly helps readability.</p>\n<hr />\n<p>For</p>\n<pre><code>&quot;\\n&quot;.join([&quot;&quot;.join(x) for x in field_copy])\n</code></pre>\n<p>You don't need the <code>[]</code>:</p>\n<pre><code>&quot;\\n&quot;.join(&quot;&quot;.join(x) for x in field_copy)\n</code></pre>\n<p>Without the square brackets, it's a generator expression instead of a list comprehension. They're lazy, which saves you from creating a list just so it can be fed into <code>join</code>. The difference here isn't huge, but for long lists that can save memory.</p>\n<hr />\n<p>I wouldn't represent the board as a 2D list of strings. This likely uses up more memory than necessary, and especially with how you have it now, you're forced to remember what string symbol represents what. On top of that, you have <em>two sets</em> of string symbols: one used internally for logic (<code>'o'</code> and <code>'.'</code>), and the other for when you print out (<code>' '</code> and <code>'x'</code>). This is more confusing than it needs to be.</p>\n<p>If you <em>really</em> wanted to use strings, you should have a global constant at the top that clearly defines what string is what:</p>\n<pre><code>DEAD_CELL = '.' # At the very top somewhere\nALIVE_CELL = 'o'\n\n. . .\n\nif living_neighbours &lt; 2 or living_neighbours &gt; 3: # Later on in a function\n new_field[row][col] = DEAD_CELL\nelif living_neighbours == 3:\n new_field[row][col] = ALIVE_CELL\n</code></pre>\n<p>Strings like <code>'.'</code> floating around fall into the category of &quot;magic numbers&quot;: values that are used loose in a program that don't have a self-explanatory meaning. If the purpose of a value isn't self-evident, store it in a variable with a descriptive name so you and your readers know exactly what's going on in the code.</p>\n<p>Personally though, when I write GoL implementations, I use a 1D or 2D list of Boolean values, or a set of tuples representing alive cells. For the Boolean list versions, if a cell is alive, it's true, and if it's dead it's false. For the set version, a cell is alive if it's in the set, otherwise it's dead.</p>\n<hr />\n<p>I'd tuck all the stuff at the bottom into a <code>main</code> function. You don't necessarily always want all of that running simply because you loaded the file.</p>\n<hr />\n<p>For the sake of efficiency, instead of constantly creating new field copies every generation, a common trick is to create two right at the start, then swap them every generation.</p>\n<p>The way I do it is one field is the <code>write_field</code> and one is the <code>read_field</code>. As the names suggest, all writes happen to the <code>write_field</code>, and all reads from <code>read_field</code>. After each &quot;tick&quot;, you simply swap them; <code>read_field</code> becomes the new <code>write_field</code> and <code>write_field</code> becomes <code>read_field</code>. This saves you from the expensive <code>deepcopy</code> call once per tick.</p>\n<p>You can do this swap <a href=\"https://stackoverflow.com/q/14836228/3000206\">quite simply in Python</a>:</p>\n<pre><code>write_field, read_field = read_field, write_field\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-27T18:52:58.450", "Id": "486829", "Score": "2", "body": "You forgot to mention the pythonic way of doing a swap: `write_field, read_field = read_field, write_field`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-27T19:22:24.243", "Id": "486833", "Score": "1", "body": "@MarkRansom Added. Thank you." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-28T07:32:57.343", "Id": "486879", "Score": "0", "body": "Thanks for all your great suggestions! I have implemented them. When it comes to the read_field and write_field suggestion, I have changed the update_field function to accept two arguments (both fields) and added an else condition in order to copy the read_field value in case there are 2 neighbours (and thus no update). With that, the swap works correctly in the for loop. Was this the way how you meant it?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-28T12:03:44.343", "Id": "486905", "Score": "1", "body": "@p.vitzliputzli That sounds about right. If you can read C to any extent, you can see my first C program [here](https://codereview.stackexchange.com/q/217040/46840), which was the GoL, and implements that technique. You can see that I'm holding both arrays in a `World` struct at the top." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-28T12:08:54.093", "Id": "486906", "Score": "1", "body": "Actually, I'm realizing now that I'm doing it a kind of dumb way there and doing a copy from the one array to the other instead of swapping. Idk why I did it that way. Ffs younger self." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-28T12:53:57.530", "Id": "486909", "Score": "0", "body": "@Carcigenicate Yes, I understand your C code quite well. Thanks again for your help!" } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-27T15:05:17.603", "Id": "248506", "ParentId": "248491", "Score": "5" } }, { "body": "<p>The code you posted offers a good example of the benefits that can flow\ndownstream from a greater investment upfront in conceptual and naming\nconsistency. As written, the code has two different ways to represent alive or\ndead cells, it toggles back and forth between the language of rows/columns and\nthe language of x/y coordinates, and it switches between <code>field</code> and\n<code>field_copy</code>.</p>\n<p>When you hit that point in the development of a program, it's useful to step\nback and commit yourself to some consistency. For example:</p>\n<pre><code>field : list of rows\nrow : list of cells\ncell : either 'x' (alive) or space (dead)\n\nr : row index\nc : column index\n</code></pre>\n<p>And let's also start on a solid foundation by putting all code in functions,\nadding a tiny bit of flexibility to usage so we can vary the N of generations\non the command line (handy for debugging and testing). In addition, we want\nmaintain a strict separation between the algorithmic parts of the program and\nthe parts of the program that deal with printing and presentation. Here's one\nway to start on that path:</p>\n<pre><code>import sys\n\nALIVE = 'x'\nDEAD = ' '\n\nINITIAL_FIELD_TEMPLATE = [\n ' ',\n ' ',\n ' ',\n ' ',\n ' xxxxx xxxxx xxxxx ',\n ' ',\n ' ',\n ' ',\n ' ',\n]\n\nDEFAULT_GENERATIONS = 10\n\ndef main(args):\n # Setup: initial field and N of generations.\n init = [list(row) for row in INITIAL_FIELD_TEMPLATE]\n args.append(DEFAULT_GENERATIONS)\n n_generations = int(args[0])\n\n # Run Conway: we now have the fields for all generations.\n fields = list(conway(n_generations, init))\n\n # Analyze, report, whatever.\n for i, f in enumerate(fields):\n s = field_as_str(f)\n print(f'\\nGeneration {i}:\\n{s}')\n\ndef conway(n, field):\n for _ in range(n + 1):\n yield field # Temporary implementation.\n\ndef field_as_str(field):\n return '\\n'.join(''.join(row) for row in field)\n\nif __name__ == '__main__':\n main(sys.argv[1:])\n</code></pre>\n<p>Starting on that foundation, the next step is to make <code>conway()</code> do something\ninteresting -- namely, compute the field for the next generation. The <code>new_field()</code>\nimplementation is easy if we define a couple of range constants.</p>\n<pre><code>RNG_R = range(len(INITIAL_FIELD_TEMPLATE))\nRNG_C = range(len(INITIAL_FIELD_TEMPLATE[0]))\n\ndef new_field(field):\n return [\n [new_cell_value(field, r, c) for c in RNG_C]\n for r in RNG_R\n ]\n\ndef new_cell_value(field, r, c):\n return field[r][c] # Temporary implementation.\n</code></pre>\n<p>And then the next step is to implement a real <code>new_cell_value()</code>, which we know\nwill lead us to thinking about neighboring cells. In these 2D grid situations,\nneighbor logic can often be simplified by expressing the neighbors in relative\n<code>(R, C)</code> terms in a simple data structure:</p>\n<pre><code>NEIGHBOR_SHIFTS = [\n (-1, -1), (-1, 0), (-1, 1),\n (0, -1), (0, 1),\n (1, -1), (1, 0), (1, 1),\n]\n\ndef new_cell_value(field, r, c):\n n_living = sum(\n cell == ALIVE\n for cell in neighbor_cells(field, r, c)\n )\n return (\n field[r][c] if n_living == 2 else\n ALIVE if n_living == 3 else\n DEAD\n )\n\ndef neighbor_cells(field, r, c):\n return [\n field[r + dr][c + dc]\n for dr, dc in NEIGHBOR_SHIFTS\n if (r + dr) in RNG_R and (c + dc) in RNG_C\n ]\n</code></pre>\n<p>One final note: by adopting a consistent naming convention and by decomposing\nthe problem into fairly small functions, we can get away with many short\nvariable names, which lightens the visual weight of the code and helps with\nreadability. Within small scopes and within a clear context (both are crucial),\nshort variable names tend to <strong>increase</strong> readability. Consider\n<code>neighbor_cells()</code>: <code>r</code> and <code>c</code> work because our convention is followed\neverywhere; <code>RNG_R</code> and <code>RNG_C</code> work because they build on that convention; <code>dr</code> and\n<code>dc</code> work partly for the same reason and partly because they have the context of an\nexplicitly named container, <code>NEIGHBOR_SHIFTS</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-29T13:36:39.667", "Id": "487028", "Score": "0", "body": "Thanks for your great suggestions! I used 'field_copy' instead of field because the linter was complaining about shadowing the global, but with your approach, this is elegantly circumvented." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-28T18:12:10.727", "Id": "248563", "ParentId": "248491", "Score": "3" } } ]
{ "AcceptedAnswerId": "248506", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-27T07:55:08.000", "Id": "248491", "Score": "5", "Tags": [ "python", "python-3.x" ], "Title": "LIFE in Python 3" }
248491
<p>I need to manage lists of executables Id. Each executable belongs to a capacity (obviously the list of capacities in the code is just an example).</p> <p>For every capacity we need to be able to find the first executableId which is Available (ie not doing any treatment) and to modify the availability of an executable Id. executable Ids can be seen as the process Id.</p> <p>Is the idea of using map a good one? Or should I use two vectors for every capacities, one for the executables Availables and the other for the executables In progress?</p> <pre><code>#include &lt;iostream&gt; #include &lt;map&gt; #include &lt;vector&gt; #include &lt;algorithm&gt; constexpr int ERROR = -1; enum class Disponibility { Available, In_Progress, }; enum class Capacity { TRT_1, TRT_2, TRT_3, }; std::ostream&amp; operator&lt;&lt;(std::ostream &amp;os, const Capacity &amp; cap) { switch(cap) { case Capacity::TRT_1: os &lt;&lt; &quot;TRT_1&quot;; break; case Capacity::TRT_2: os &lt;&lt; &quot;TRT_2&quot;; break; case Capacity::TRT_3: os &lt;&lt; &quot;TRT_3&quot;; default: break; } return os; } std::ostream&amp; operator&lt;&lt;(std::ostream &amp;os, const Disponibility &amp; dispo) { switch(dispo) { case Disponibility::Available: os &lt;&lt; &quot;Available&quot;; break; case Disponibility::In_Progress: os &lt;&lt; &quot;In_Progress&quot;; break; default: break; } return os; } /* Initialize by passing a vector of all capacities the Manager should deal with Ideas : - Allow constructor to be done with any iterable container ? */ class ManageListExe { public: ManageListExe(const std::vector&lt;Capacity&gt; &amp;listCap) { for(const auto cap : listCap) { listExeByCapacity[cap] = {}; } } template&lt;typename T&gt; void updateListExe(const Capacity cap, const T&amp; listExecutableId) { //Add executable Id when not in list for(const auto exeId: listExecutableId) { if(listExeByCapacity[cap].find(exeId) == listExeByCapacity[cap].end()) { addExeFromCap(cap, exeId); } } //Remove from listExeByCapacity executableId which are not anymore in listExecutableId for(const auto val: listExeByCapacity[cap]) { if(std::find(listExecutableId.cbegin(), listExecutableId.cend(), val.first) == listExecutableId.cend()) { removeExeFromCap(cap, val.first); } } } int getFirstExeAvailable(const Capacity cap) { //return first exe available from the list for(const auto val: listExeByCapacity[cap]) { if(val.second == Disponibility::Available) { return val.first; } } return ERROR; } void changeDisponibility(const Capacity cap, const int executableId, const Disponibility dispo) { listExeByCapacity[cap][executableId] = dispo; } void printListExe() { for(const auto listByCap:listExeByCapacity) { for(const auto listExe:listByCap.second) { std::cout &lt;&lt; &quot;Capacity : &quot; &lt;&lt; listByCap.first &lt;&lt; &quot;, ExecutableId : &quot; &lt;&lt; listExe.first &lt;&lt; &quot; : &quot; &lt;&lt; listExe.second &lt;&lt; &quot;\n&quot;; } } } void printListExeFromCapacity(const Capacity cap) { std::cout &lt;&lt; &quot;Capacity : &quot; &lt;&lt; cap &lt;&lt; &quot;\n&quot;; for(const auto listExe:listExeByCapacity[cap]) { std::cout &lt;&lt; &quot;ExecutableId : &quot; &lt;&lt; listExe.first &lt;&lt; &quot; : &quot; &lt;&lt; listExe.second &lt;&lt; &quot;\n&quot;; } } private: void addExeFromCap(const Capacity cap, const int executableId) { listExeByCapacity[cap][executableId] = Disponibility::Available; } void removeExeFromCap(const Capacity cap, const int executableId) { listExeByCapacity[cap].erase(executableId); } std::map&lt;Capacity, std::map&lt;int, Disponibility&gt;&gt; listExeByCapacity; }; int main() { std::cout &lt;&lt; &quot;Start tests&quot; &lt;&lt; std::endl; //Test creating Manager std::vector&lt;Capacity&gt; vectorCapacity = {Capacity::TRT_1, Capacity::TRT_2}; ManageListExe managerList(vectorCapacity); //Test updating capacities std::vector&lt;int&gt; listExe = {1,2,0}; managerList.updateListExe(Capacity::TRT_1, listExe); listExe.push_back(4); managerList.updateListExe(Capacity::TRT_1, listExe); std::cout &lt;&lt; &quot;---\nWe should see executableId 0,1,2,4 from TRT_1 : &quot; &lt;&lt; std::endl; managerList.printListExeFromCapacity(Capacity::TRT_1); //Test with 2 capacities managerList.updateListExe(Capacity::TRT_2, listExe); std::cout &lt;&lt; &quot;---\nWe should see executableId 0,1,2,4 from TRT_1 and TRT_2 : &quot; &lt;&lt; std::endl; managerList.printListExe(); //Test changing one disponibility managerList.changeDisponibility(Capacity::TRT_1, 0, Disponibility::In_Progress); std::cout &lt;&lt; &quot;---\nWe should see executableId 0,1,2,4 from TRT_1 and executable 0 should be in progress : &quot; &lt;&lt; std::endl; managerList.printListExeFromCapacity(Capacity::TRT_1); //Test remove one element in list listExe.pop_back(); managerList.updateListExe(Capacity::TRT_1, listExe); std::cout &lt;&lt; &quot;---\nWe should see executableId 0,1,2 from TRT_1 and 0,1,2,4 from TRT_2 : &quot; &lt;&lt; std::endl; managerList.printListExe(); //Test Getting first executableId Available int firstExeAvailable = managerList.getFirstExeAvailable(Capacity::TRT_1); std::cout &lt;&lt; &quot;First executableId available from capacity TRT_1 (should be 1) : &quot; &lt;&lt; firstExeAvailable &lt;&lt; std::endl; return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-27T09:19:12.797", "Id": "486784", "Score": "1", "body": "What is meant with _Disponibility_, I can't find this word in my dictionary? Also where does _executable ID_ come from? Is that the process ID, or some hash value calculated from the name?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-27T09:34:09.947", "Id": "486785", "Score": "0", "body": "Disponibility is a bad translation from French. It is used as \"Availabilty\". Executable Ids can be seen as the proces ID. Thanks, I'll update the question" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-27T09:35:57.003", "Id": "486786", "Score": "0", "body": "You should use real, descriptive words for your symbols. If it means _Availability_, then just name it so." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-27T09:51:59.667", "Id": "486788", "Score": "0", "body": "Well indeed disponibility _is_ in the english dictionnary, and it means Availability so that's OK" } ]
[ { "body": "<p>Here are some things that may help you improve your program.</p>\n<h2>Fix the bug</h2>\n<p>There is a problem with <code>updateListExe</code> that occurs in the test program after removing one element from the list. It accesses freed memory which is an error. The easiest way to avoid this is to simplify the code to this:</p>\n<pre><code>template&lt;typename T&gt;\nvoid updateListExe(const Capacity cap, const T&amp; listExecutableId) {\n for (const auto exeId : listExecutableId) {\n auto it{listExeByCapacity[cap].find(exeId)};\n if (it == listExeByCapacity[cap].end()) {\n addExeFromCap(cap, exeId);\n } else {\n removeExeFromCap(cap, exeId);\n }\n }\n}\n</code></pre>\n<h2>Understand standard container operators</h2>\n<p>I would expect that someone calling <code>getFirstAvailable</code> with an invalid <code>cap</code> would be surprised to find out that it modifies the object because the function uses <a href=\"https://en.cppreference.com/w/cpp/container/map/operator_at\" rel=\"nofollow noreferrer\"><code>operator[]</code></a>. That operator inserts the new value if it's not already there, and that is probably not what is intended. I would suggest making this a <code>const</code> function and having it <code>throw</code> if the cap is not found. Here's one way to do that:</p>\n<pre><code>static bool isAvailable(const std::pair&lt;const T, Disponibility&gt;&amp; pair) {\n return pair.second == Disponibility::Available;\n}\n\nT getFirstExeAvailable(const Capacity cap) const\n{\n const auto end{ listExeByCapacity.at(cap).cend()};\n auto it{std::find_if(listExeByCapacity.at(cap).cbegin(), end, isAvailable)};\n return it == end ? ERROR : it-&gt;first;\n}\n</code></pre>\n<p>This will throw a <code>std::out_of_range</code> error if the passed <code>cap</code> is not in the map.</p>\n<h2>Use templates consistently</h2>\n<p>In the code quoted above the executable ID is a templated type, while everywhere else it is coded as an <code>int</code>. Choose one or the other but not both.</p>\n<h2>Consider another data structure</h2>\n<p>The application looks like a task prioritization scheme for a scheduler. It may be more appropriate to use a <code>std::priority_queue</code> rather than the current data structure, and it also has logarithmic insertion and retrieval times.</p>\n<h2>Support the use of a <code>std::initializer_list</code></h2>\n<p>The constructor takes a <code>std::vector&lt;Capacity&gt;</code> as the argument, and constructing the object currently looks like this (note I have added the template):</p>\n<pre><code>std::vector&lt;Capacity&gt; vectorCapacity = {Capacity::TRT_1, Capacity::TRT_2};\nManageListExe&lt;int&gt; managerList(vectorCapacity);\n</code></pre>\n<p>It seems to me that it would be much nicer to do this instead:</p>\n<pre><code>ManageListExe&lt;int&gt; managerList{Capacity::TRT_1, Capacity::TRT_2};\n</code></pre>\n<p>That is easily supported with this constructor:</p>\n<pre><code>ManageListExe(std::initializer_list&lt;Capacity&gt; listCap)\n{\n for(const auto cap : listCap)\n {\n listExeByCapacity[cap] = {};\n }\n}\n</code></pre>\n<h2>Use better naming</h2>\n<p>In the comments it has already been pointed out that &quot;Disponibility&quot; is a rather unusual word for many native English speakers, and &quot;Availability&quot; might be a better word. I would say that <code>ManageListExe</code> could be improved as well. I would suggest <code>Executables</code>.</p>\n<h2>Write a standard inserter</h2>\n<p>Instead of the relatively inflexible <code>printListExe</code>, I would suggest writing a standard inserter instead with the signature:</p>\n<pre><code>friend std::ostream&amp; operator&lt;&lt;(std::ostream&amp; out, const ManageListExe&amp; el);\n</code></pre>\n<h2>Don't use <code>std::endl</code> if <code>'\\n'</code> will do</h2>\n<p>Using <code>std::endl</code> emits a <code>\\n</code> and flushes the stream. Unless you really need the stream flushed, you can improve the performance of the code by simply emitting <code>'\\n'</code> instead of using the potentially more computationally costly <code>std::endl</code>.</p>\n<h2>Use <code>const auto &amp;</code> where practical</h2>\n<p>Use this common C++11 idiom to operate non-destructively on all of the data members of collection:</p>\n<pre><code>for (const auto &amp;val : myCollection) {\n std::cout &lt;&lt; val &lt;&lt; '\\n';\n}\n</code></pre>\n<p>The intent here is to print the values of all of the collection values without modifying them (hence <code>const</code>) and without copying them (hence <code>&amp;</code>).</p>\n<h2>Consider using <code>std::optional</code></h2>\n<p>If your compiler supports C++17, I would suggest that <a href=\"https://en.cppreference.com/w/cpp/utility/optional\" rel=\"nofollow noreferrer\"><code>std::optional</code></a> would be a better choice of return value for <code>getFirstExeAvailable()</code>. The requirement for an <code>ERROR</code> value would disappear and the code would more naturally express the intent.</p>\n<h2>Use unordered data structures for performance</h2>\n<p>Unless you actually need them in order, there is often a performance gain in using, for example, <code>std::unordered_map</code> rather than <code>std::map</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-27T14:32:11.283", "Id": "248503", "ParentId": "248492", "Score": "4" } } ]
{ "AcceptedAnswerId": "248503", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-27T08:11:05.053", "Id": "248492", "Score": "6", "Tags": [ "c++", "c++11" ], "Title": "Manage lists of executable id" }
248492
<p>Heyhey, I'm attempting to implement a ToggleBar control for Xamarin as there is non up to date and fully customizeable.</p> <p>Now I haven't implemented too many controls and while the control is not fully implemented yet (I want to add an Icon option for the ToggleButtons later, but want to improve on the base before I develop new features for it.</p> <p>Any tips/improvements that can be done to this control?</p> <pre><code> public class TogglesBar : ContentView { private readonly Grid _gridContainer; public TogglesBar() { _gridContainer = new Grid {Margin = 0, Padding = 0, ColumnSpacing = 0}; Content = _gridContainer; } private void Render() { try { if (ItemsSource == null || !ItemsSource.Any()) { return; } var loopIndex = 0; // Check if we have an icon if (HasIcon) { var image = new Image {Source = &quot;waterfront.jpg&quot;}; } foreach (var optionText in ItemsSource) { var button = new ToggleButton { Text = optionText, BackgroundColor = NotToggledBackgroundColor, ToggledTextColor = ToggledTextColor, NotToggledTextColor = NotToggledTextColor, ToggledBackgroundColor = ToggledBackgroundColor, NotToggledBackgroundColor = NotToggledBackgroundColor }; button.ToggledChanged += (s, toggledStatus) =&gt; { // Get all buttons var allToggleButtons = _gridContainer.Children.Where(x =&gt; x is ToggleButton); // Set all buttons to false allToggleButtons?.ForEach(x =&gt; ((ToggleButton)x).IsToggled = false); // Set this button to true button.IsToggled = true; // Add it to the selectedList //_selectedItems.Add(button); }; // Add the column to the grid _gridContainer.ColumnDefinitions.Add(new ColumnDefinition {Width = new GridLength(1, GridUnitType.Star)}); // Add the button to the grid _gridContainer.Children.Add(button); _gridContainer.Children.Add(button, loopIndex, 0); loopIndex++; // Set Initial Toggle if (ItemsSource.IndexOf(optionText) == InitialIndex) { button.IsToggled = true; } // Set the spacing between the toggles _gridContainer.ColumnSpacing = ItemsSpacing; button.OnIsToggledChanged(); } } catch (Exception ex) { Debug.WriteLine(ex); throw; } } #region Bindable Properties public static readonly BindableProperty HasIconProperty = BindableProperty.Create(nameof(HasIcon), typeof(bool), typeof(ToggleButton), false); public bool HasIcon { get =&gt; (bool)GetValue(HasIconProperty); set =&gt; SetValue(HasIconProperty, value); } public static readonly BindableProperty InitialIndexProperty = BindableProperty.Create(nameof(InitialIndex), typeof(int), typeof(TogglesBar), 0); public int InitialIndex { get =&gt; (int)GetValue(InitialIndexProperty); set =&gt; SetValue(InitialIndexProperty, value); } #region ItemSource private static void CustomPropertyChanging(BindableObject bindable, object oldValue, object newValue) { if (newValue != null) { ((TogglesBar)bindable).Render(); } } public static readonly BindableProperty ItemsSourceProperty = BindableProperty.Create(nameof(ItemsSource), typeof(IList), typeof(string), default(IList), propertyChanged: CustomPropertyChanging); public IList&lt;string&gt; ItemsSource { get =&gt; (IList&lt;string&gt;)GetValue(ItemsSourceProperty); set =&gt; SetValue(ItemsSourceProperty, value); } #endregion public static readonly BindableProperty SelectedItemsProperty = BindableProperty.Create(nameof(ItemsSource), typeof(IList), typeof(string), default(IList), propertyChanged: CustomPropertyChanging); public IList&lt;string&gt; SelectedItems { get =&gt; (IList&lt;string&gt;)GetValue(ItemsSourceProperty); set =&gt; SetValue(ItemsSourceProperty, value); } public static readonly BindableProperty ItemsSpacingProperty = BindableProperty.Create(nameof(ItemsSpacing), typeof(double), typeof(TogglesBar), 0d); public double ItemsSpacing { get =&gt; (double)GetValue(ItemsSpacingProperty); set =&gt; SetValue(ItemsSpacingProperty, value); } #region SelectedColors public static readonly BindableProperty ToggledBackgroundColorProperty = BindableProperty.Create(nameof(ToggledBackgroundColor), typeof(Color), typeof(ToggleButton), Color.Default); public Color ToggledBackgroundColor { get =&gt; (Color)GetValue(ToggledBackgroundColorProperty); set =&gt; SetValue(ToggledBackgroundColorProperty, value); } public static readonly BindableProperty ToggledTextColorProperty = BindableProperty.Create(nameof(ToggledTextColor), typeof(Color), typeof(ToggleButton), Color.Default); public Color ToggledTextColor { get =&gt; (Color)GetValue(ToggledTextColorProperty); set =&gt; SetValue(ToggledTextColorProperty, value); } #endregion #region UnselectedColors public static readonly BindableProperty NotToggledTextColorProperty = BindableProperty.Create(nameof(NotToggledTextColor), typeof(Color), typeof(ToggleButton), Color.Default); public Color NotToggledTextColor { get =&gt; (Color)GetValue(NotToggledTextColorProperty); set =&gt; SetValue(NotToggledTextColorProperty, value); } public static readonly BindableProperty NotToggledBackgroundColorProperty = BindableProperty.Create(nameof(NotToggledBackgroundColor), typeof(Color), typeof(ToggleButton), Color.Default); public Color NotToggledBackgroundColor { get =&gt; (Color)GetValue(NotToggledBackgroundColorProperty); set =&gt; SetValue(NotToggledBackgroundColorProperty, value); } #endregion #endregion } } </code></pre> <p>ToggleButton</p> <pre><code> public class ToggleButton : ContentView { private StackLayout _stackLayout; Label _label; private Image image; public ToggleButton() { var tapGestureRecognizer = new TapGestureRecognizer(); tapGestureRecognizer.Tapped += (sender, e) =&gt; ToggleButtonTapped(); _label = new Label() { VerticalTextAlignment = TextAlignment.Center, HorizontalTextAlignment = TextAlignment.Center, Text = Text, }; HorizontalOptions = LayoutOptions.Fill; VerticalOptions = LayoutOptions.Fill; _label.GestureRecognizers.Add(tapGestureRecognizer); Content = _label; } public event EventHandler&lt;bool&gt; ToggledChanged; /// &lt;summary&gt; What happens whenever we change the toggle value &lt;/summary&gt; public void OnIsToggledChanged() { _label.Text = Text; if (IsToggled) { _label.TextColor = ToggledTextColor; _label.BackgroundColor = ToggledBackgroundColor; } else { _label.TextColor = NotToggledTextColor; _label.BackgroundColor = NotToggledBackgroundColor; } } private void ToggleButtonTapped() { IsToggled = !IsToggled; ToggledChanged?.Invoke(this, IsToggled); } public static readonly BindableProperty TextProperty = BindableProperty.Create(nameof(Text), typeof(string), typeof(ToggleButton), default(string)); public string Text { get { return (string)GetValue(TextProperty); } set { SetValue(TextProperty, value); } } #region SelectedColors public static readonly BindableProperty ToggledBackgroundColorProperty = BindableProperty.Create(nameof(ToggledBackgroundColor), typeof(Color), typeof(ToggleButton), Color.Default); public Color ToggledBackgroundColor { get =&gt; (Color)GetValue(ToggledBackgroundColorProperty); set =&gt; SetValue(ToggledBackgroundColorProperty, value); } public static readonly BindableProperty ToggledTextColorProperty = BindableProperty.Create(nameof(ToggledTextColor), typeof(Color), typeof(ToggleButton), Color.Default); public Color ToggledTextColor { get =&gt; (Color)GetValue(ToggledTextColorProperty); set =&gt; SetValue(ToggledTextColorProperty, value); } #endregion #region UnselectedColors public static readonly BindableProperty NotToggledTextColorProperty = BindableProperty.Create(nameof(NotToggledTextColor), typeof(Color), typeof(ToggleButton), Color.Default); public Color NotToggledTextColor { get =&gt; (Color)GetValue(NotToggledTextColorProperty); set =&gt; SetValue(NotToggledTextColorProperty, value); } public static readonly BindableProperty NotToggledBackgroundColorProperty = BindableProperty.Create(nameof(NotToggledBackgroundColor), typeof(Color), typeof(ToggleButton), Color.Default); public Color NotToggledBackgroundColor { get =&gt; (Color)GetValue(NotToggledBackgroundColorProperty); set =&gt; SetValue(NotToggledBackgroundColorProperty, value); } #endregion #region ToggledProperty public static readonly BindableProperty IsToggledProperty = BindableProperty.Create(nameof(IsToggled), typeof(bool), typeof(ToggleButton), false, propertyChanged: (bindable, oldValue, newValue) =&gt; { ((ToggleButton)bindable).OnIsToggledChanged(); } ); public bool IsToggled { get =&gt; (bool)GetValue(IsToggledProperty); set =&gt; SetValue(IsToggledProperty, value); } #endregion } } </code></pre> <p>Implementation</p> <pre><code> &lt;controls:TogglesBar Grid.Column=&quot;2&quot; HorizontalOptions=&quot;Fill&quot; InitialIndex=&quot;0&quot; NotToggledBackgroundColor=&quot;WhiteSmoke&quot; NotToggledTextColor=&quot;#1d1d1d&quot; SelectedItems=&quot;{Binding SelectedItems}&quot; ToggledBackgroundColor=&quot;#c94263&quot; ToggledTextColor=&quot;WhiteSmoke&quot; Visual=&quot;Default&quot;&gt; &lt;controls:TogglesBar.ItemsSource&gt; &lt;x:Array Type=&quot;{x:Type x:String}&quot;&gt; &lt;x:String&gt;List View&lt;/x:String&gt; &lt;x:String&gt;Map View&lt;/x:String&gt; &lt;/x:Array&gt; &lt;/controls:TogglesBar.ItemsSource&gt; &lt;/controls:TogglesBar&gt; </code></pre> <p>UI Look: You can see two implementations of the Togglebar in this UI, the bottom buttons and the MapView/ListView.</p> <p><a href="https://i.stack.imgur.com/HkqiX.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/HkqiX.png" alt="enter image description here" /></a></p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-27T12:26:57.110", "Id": "248498", "Score": "1", "Tags": [ "c#", "xaml", "xamarin" ], "Title": "Xamarin: ToggleBar control" }
248498
<p>Does this adequately sanitize untrusted input for client side frontend templating where templates are otherwise trusted? What details remain to address or need reconsidering?</p> <p><strong>Please note</strong> the character substitutions are replacing less-than, greater-than, single and double quote, back-slash and the ampersand characters with look-alike characters of the same type which I do not expect in any circumstance to parse (or become parsable) as tag or attribute or encoding circumvention in any context of an HTML5 document. This follows, or more accurately attempts to follow, the <a href="https://cheatsheetseries.owasp.org/cheatsheets/Cross_Site_Scripting_Prevention_Cheat_Sheet.html#Output_Encoding_Rules_Summary" rel="nofollow noreferrer">OWASP replacement recommendations</a>.</p> <pre><code>function sanitizer(str, i, list){ return str + (this[i] ?? '').toString() .replace(/&lt;/g, '﹤') .replace(/&gt;/g, '﹥') .replace(/'/g, '’') .replace(/&quot;/g, '”') .replace(/&amp;/g, '&') .replace(/\//g, '/') ; } function sanitize(str, ...input){ return str.map(sanitizer, input).join(''); } function template(data){ return sanitize`&lt;div&gt;${ data }&lt;/div&gt;`; } </code></pre> <p>Calling <code>template('1&lt;23')</code> should render a HTMLDivElement with Text '1﹤23'.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-27T13:49:57.730", "Id": "486808", "Score": "0", "body": "by replacing characters with similar characters, are you inadvertantly causing people issues with copy-pasting legitimate content?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-28T02:54:25.480", "Id": "486858", "Score": "0", "body": "@TKoL helpful comment, thanks very much. In this case I don't see this as an issue simply because the objective (at this point in the view lifecycle) is to ensure if the backend services miss proper encodings or the template doesn't handle the specific scenario this sanitization will address them to prevent security problems/xss at that point. I'm simply attempting to provide an as simple as possible general solution for frontend templates." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-28T08:45:32.790", "Id": "486890", "Score": "0", "body": "personally, I would rather rely on a known and used library for sanitization than hoping that i've thought of everything..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-29T08:27:32.653", "Id": "487006", "Score": "0", "body": "@TKoL thanks, I understand and recognize that's a common perspective (to use libraries). I'd prefer to know and understand the fundamentals myself, especially critical ones, rather than pass the responsibility and trust to someone else. All things considered this of course would require comprehensive testing to prove it works." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-30T02:19:23.927", "Id": "487102", "Score": "0", "body": "@TKoL in the more general case where more feature are needed I would simply use a library (ie LitElement, lit-html) for this, however in a lightweight implementation for minor applications that I have I want to know there is a reasonable approach toward a solution (this case)." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-27T12:47:41.033", "Id": "248499", "Score": "1", "Tags": [ "javascript", "security", "html5" ], "Title": "sanitize untrusted input for templates" }
248499
<p>The idea is to make an error handling procedure, which prints messages in <code>DEV</code> mode and shows <code>MsgBox</code> in <code>PROD</code> mode. Looking for any wise idea to improve it:</p> <pre><code>Public Const SET_IN_PRODUCTION = False Sub TestMe() On Error GoTo TestMe_Error Debug.Print 0 / 0 Exit Sub TestMe_Error: StandardError Err, &quot;TestMe&quot; End Sub Public Sub StandardError(myError As Object, Optional moduleName As String = &quot;&quot;) If SET_IN_PRODUCTION Then MsgBox &quot;Error in &quot; &amp; moduleName &amp; vbCrLf &amp; myError.Description, vbCritical, title:=myError.Number Else Debug.Print &quot;Error in &quot;; moduleName &amp; vbCrLf &amp; myError.Description End If End Sub </code></pre> <p>The lines <code>StandardErr Err</code> are to be used for almost any procedure and function in the code, for &quot;advanced&quot; error handling.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-27T19:50:05.613", "Id": "486837", "Score": "0", "body": "Looks like your error handler needs an error handler." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-27T21:13:47.973", "Id": "486840", "Score": "0", "body": "@HackSlash - why, what can go wrong there once the code compiles?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-28T15:25:30.770", "Id": "486929", "Score": "0", "body": "`myError`, defined as an object could be null or something other than an error object." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-28T15:34:53.393", "Id": "486931", "Score": "0", "body": "@HackSlash - how can this happen, considering the fact that it is always called with the explicit example?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-28T15:35:59.557", "Id": "486932", "Score": "1", "body": "Make no assumptions about how your code will be used in the future." } ]
[ { "body": "<p>Passing around the Error object like this feels intuitively like a good way of freezing error state and providing it to logging/error reporting functions, so I see why you've come up with this.</p>\n<p>Reading the comments, @HackSlash does make a good point - that <code>myError</code> could hold anything if it's declared As Object, and that could lead to errors when you try to get its <code>Description</code> or <code>Number</code>. I'd probably change the signature from this:</p>\n<blockquote>\n<pre><code>Public Sub StandardError(myError As Object, Optional moduleName As String = &quot;&quot;)\n</code></pre>\n</blockquote>\n<p>... to this</p>\n<pre><code>Public Sub StandardError(ByVal myError As VBA.ErrObject, Optional ByVal moduleName As String = &quot;&quot;)\n If myError Is Nothing Then Err.Raise 5, Description:=&quot;Must pass valid Err Object&quot;\n</code></pre>\n<p><sub><em>ByVal because we don't need to change what the caller's copy of the variable points to</em></sub></p>\n<p>By declaring <code>myError</code> with the type (interface) we want, it means rather than receiving the generic and somewhat obscure error message:</p>\n<blockquote>\n<p>Run-Time Error 438</p>\n<p>Object doesn't support this property or method</p>\n</blockquote>\n<p>... or even harder to diagnose if Nothing is passed;</p>\n<blockquote>\n<p>Run-Time Error 91</p>\n<p>Object variable or With block variable not set</p>\n</blockquote>\n<p>... we get a clearer <em>Type Mismatch</em> error that takes us right to the source</p>\n<p><a href=\"https://i.stack.imgur.com/AMruf.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/AMruf.png\" alt=\"Debug View\" /></a></p>\n<p>The calling site is pretty simple though, so it's unlikely you'd type it in wrong, but still, doesn't harm to add some Error checking. But come to think of it, what does happen if an Error is raised inside the error handling routine? Or If I call Err.Clear? Doing this:</p>\n<pre><code>Public Sub StandardError(ByVal myError As ErrObject, Optional moduleName As String = &quot;&quot;)\n\n Err.Clear 'do something to modify GLOBAL error state\n \n If SET_IN_PRODUCTION Then\n MsgBox &quot;Error in &quot; &amp; moduleName &amp; vbCrLf &amp; myError.Description, vbCritical, Title:=myError.Number\n Else\n Debug.Print &quot;Error in &quot;; moduleName &amp; vbCrLf &amp; myError.Description\n End If\n\nEnd Sub\n</code></pre>\n<p>... results in no Error being printed - <code>myError.Description</code> has been cleared even though I never touched <code>myError</code> explicitly, something funny is going on here...</p>\n<hr />\n<p>It turns out <code>Err</code> is not some locally scoped variable that gets supplied as a hidden argument to every Sub or Function, and which you can just pass around. If we look in the object browser it is in fact a function in the <code>VBA.Information</code> module that returns an object of type <code>VBA.ErrObject</code>, but crucially, this is <em>the same object every time</em>. Or in other words (taken from <a href=\"https://stackoverflow.com/a/55067026/6609896\">an answer on SO</a>):</p>\n<blockquote>\n<p>When you encapsulate an <code>ErrObject</code> like you did, you're essentially\njust giving yourself another way (besides the <code>Err</code> function) to\naccess the <code>ErrObject</code> instance - but it's still the exact same object\nholding the properties of the <em>current run-time error state</em>.</p>\n</blockquote>\n<p>What this means is that you never need to pass the <em>&quot;Err Object&quot;</em> to the logging routine at all, since the <code>Err</code> <em>function</em> will provide access already. What this also means is that you need to be <em>very</em> careful about the possibility of errors creeping into your logging function, since even if these are ignored, they will reset the global error state and your logger could now misreport the errors.</p>\n<p>Admittedly, your logger is very simple, so this doesn't present any immediate problem, but what if in the future you want to log to a file:</p>\n<pre><code>Private Function GetFile(ByVal path As String) As File\n\n Dim result As File\n\n 'Try open log file, catch error if it doesn't exist\n On Error Resume Next\n Set result = File.Open(path)\n On Error Goto 0\n\n 'If log file didn't exist, make a new one \n If result = Nothing Then Set result = File.NewFile(path)\n\n Set GetFile = result\nEnd Function\n\nPublic Sub StandardError(Optional moduleName As String = &quot;&quot;)\n\n Set myFile = GetFile(&quot;C:/Users/blah/log.txt&quot;) 'Ooops, just nuked global error state\n\n If SET_IN_PRODUCTION Then\n MsgBox &quot;Error in &quot; &amp; moduleName &amp; vbCrLf &amp; Err.Description, vbCritical, title:=myError.Number\n Else\n myFile.Print &quot;Error in &quot;; moduleName &amp; vbCrLf &amp; Err.Description\n End If\n\nEnd Sub\n</code></pre>\n<p><sub>o.k that's just pseudocode, I know <code>myFile.Print</code> is invalid syntax, but you get the idea</sub></p>\n<p>As Mathieu points out in that post I linked, you can roll your own class that saves runtime error state if you want to be safe, but even that has drawbacks. I find the best way to tackle this is to pass the relevant bits to a generic logger like I did <a href=\"https://codereview.stackexchange.com/q/229656/146810\">here</a>:</p>\n<blockquote>\n<pre><code>logError &quot;WinAPI.SetTimer&quot;, Err.Number, Err.Description\n</code></pre>\n</blockquote>\n<p>and freeze the Err state precisely when you want to.</p>\n<hr />\n<h3>#Conditional Compilation</h3>\n<blockquote>\n<pre><code>Public Const SET_IN_PRODUCTION = False\n</code></pre>\n</blockquote>\n<p>I'd probably use conditional compilation here</p>\n<pre><code>#If SET_IN_PRODUCTION Then\n MsgBox &quot;Error in &quot; &amp; moduleName &amp; vbCrLf &amp; myError.Description, vbCritical, Title:=myError.Number\n#Else\n Debug.Print &quot;Error in &quot;; moduleName &amp; vbCrLf &amp; myError.Description\n#End If\n</code></pre>\n<p>and define SET_IN_PRODUCTION either in the project's settings or with code</p>\n<pre><code>#Const SET_IN_PRODUCTION = False\n</code></pre>\n<p>simply because conditional compilation is quite a standard method for Debug vs Ship mode, and it replaces a runtime <code>If</code> statement called many times with a compile time one called only once</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-31T14:50:28.977", "Id": "487252", "Score": "2", "body": "I don't know if it's just me, but the link in your post \"Or in other words (taken from an answer on SO):\" is broken for me and doesn't go anywhere" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-31T20:56:06.997", "Id": "487323", "Score": "0", "body": "@HaydenMoss oh yeah sorry, fixed now" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-29T11:28:50.780", "Id": "248612", "ParentId": "248504", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-27T14:36:52.993", "Id": "248504", "Score": "6", "Tags": [ "vba", "error-handling" ], "Title": "VBA Error Handling Sub, Working for all subs" }
248504
<h3>What I'm Doing</h3> <p>I'm writing a command line utility for starting Django projects and apps with custom files.</p> <p>The custom files build upon what Django offers, to make sure things like a custom auth user model and the ability to read environment variables from a <code>.env</code> file are added to projects from outset.</p> <h3>Why I'm Doing It</h3> <p>This is something I'm doing to get more acquainted with Django, and to improve my testing game — yes, that's why I'm writing a fruglier version of django-cookiecutter :).</p> <h3>What I'm Asking For</h3> <p>I would love to get some <strong>brutally honest</strong> review on my code. I'd especially appreciate it if you could please focus on the tests because that's the area in which I want to improve the most.</p> <h3>Important Files</h3> <p><strong>classy_start/start.py</strong></p> <pre><code>import enum import pathlib import subprocess import sys from typing import List, Optional from . import file_contents, paths @enum.unique class Startable(enum.Enum): PROJECT = 0 APP = 1 def _start(what: Startable, name: str, directory: Optional[str] = None): directive = f&quot;start{what.name.lower()}&quot; cmd: List[str] cmd = [&quot;django-admin&quot;, directive, name] if directory is not None: cmd.append(directory) templates_dir_name = f&quot;{what.name}_TEMPLATES_DIR&quot; cmd.extend([&quot;--template&quot;, str(getattr(paths, templates_dir_name))]) try: subprocess.run(cmd, check=True) except subprocess.CalledProcessError: sys.exit(1) def start_app(name: str, directory: Optional[str] = None): _start(Startable.APP, name, directory) def start_project(name: str, directory: Optional[str] = None): _start(Startable.PROJECT, name, directory) follow_up_start_project(name, directory) def follow_up_start_project(name: str, directory: Optional[str] = None): if directory is None: manage_dir = pathlib.Path(&quot;.&quot;) / name else: manage_dir = pathlib.Path(directory) manage_dir.resolve(strict=True) name_change_map = { &quot;secrets.py&quot;: &quot;.env&quot;, &quot;gitignore.py&quot;: &quot;.gitignore&quot;, &quot;requirements.py&quot;: &quot;requirements.txt&quot;, } for (old_name, new_name) in name_change_map.items(): rename_file(old_name, new_name, base_dir=manage_dir) create_accounts_app(manage_dir) def rename_file(old_name: str, new_name: str, base_dir: pathlib.Path): (base_dir / old_name).rename(base_dir / new_name) def create_accounts_app(directory: pathlib.Path): dest = directory / &quot;accounts&quot; dest.mkdir() start_app(&quot;accounts&quot;, dest) for (filename, content) in [ (&quot;models.py&quot;, file_contents.auth_user_model_file_content), (&quot;admin.py&quot;, file_contents.auth_user_admin_file_content), ]: write_file(dest / filename, content) def write_file(file: pathlib.Path, content: str): file.touch() file.write_text(content) </code></pre> <p><strong>tests/test_start.py</strong></p> <pre><code>import pathlib import random import shlex import string from unittest import mock import pytest from classy_start.file_contents import ( auth_user_model_file_content, auth_user_admin_file_content, ) from classy_start.paths import APP_TEMPLATES_DIR, PROJECT_TEMPLATES_DIR from classy_start.start import ( start_app, start_project, follow_up_start_project, rename_file, create_accounts_app, write_file, ) def test_start_app(fake_process): fake_process.keep_last_process(True) fake_process.register_subprocess([fake_process.any()]) start_app(&quot;appify&quot;) count = fake_process.call_count( shlex.split(f&quot;django-admin startapp appify --template '{APP_TEMPLATES_DIR!s}'&quot;) ) assert count == 1 @mock.patch(&quot;classy_start.start.follow_up_start_project&quot;) def test_start_project(mock_follow_up, fake_process): fake_process.keep_last_process(True) fake_process.register_subprocess([fake_process.any()]) start_project(&quot;projectible&quot;, &quot;.&quot;) count = fake_process.call_count( shlex.split( f&quot;django-admin startproject projectible . --template '{PROJECT_TEMPLATES_DIR!s}'&quot; ) ) assert count == 1 mock_follow_up.assert_called_once_with(&quot;projectible&quot;, &quot;.&quot;) @mock.patch(&quot;pathlib.Path.resolve&quot;) @mock.patch(&quot;classy_start.start.rename_file&quot;) @mock.patch(&quot;classy_start.start.create_accounts_app&quot;) def test_follow_up_start_project( mock_create_accounts_app, mock_rename_file, _mock_resolve ): &quot;&quot;&quot; Assert that ~.follow_up_start_project() calls ~.rename_file() the correct number of times and with the correct arguments. And that it also calls ~.create_accounts_app() with the correct arguments. &quot;&quot;&quot; follow_up_start_project(&quot;projectible&quot;) assert mock_rename_file.call_count == 3 mock_rename_file.assert_has_calls( [ mock.call(&quot;secrets.py&quot;, &quot;.env&quot;, base_dir=pathlib.Path(&quot;projectible&quot;)), mock.call( &quot;gitignore.py&quot;, &quot;.gitignore&quot;, base_dir=pathlib.Path(&quot;projectible&quot;) ), mock.call( &quot;requirements.py&quot;, &quot;requirements.txt&quot;, base_dir=pathlib.Path(&quot;projectible&quot;), ), ] ) mock_create_accounts_app.assert_called_once_with(pathlib.Path(&quot;projectible&quot;)) # reset the **all used** mocks mock_rename_file.reset_mock() mock_create_accounts_app.reset_mock() follow_up_start_project(&quot;projectible&quot;, pathlib.Path(&quot;.&quot;)) assert mock_rename_file.call_count == 3 mock_rename_file.assert_has_calls( [ mock.call(&quot;secrets.py&quot;, &quot;.env&quot;, base_dir=pathlib.Path(&quot;.&quot;)), mock.call(&quot;gitignore.py&quot;, &quot;.gitignore&quot;, base_dir=pathlib.Path(&quot;.&quot;)), mock.call( &quot;requirements.py&quot;, &quot;requirements.txt&quot;, base_dir=pathlib.Path(&quot;.&quot;), ), ] ) mock_create_accounts_app.assert_called_once_with(pathlib.Path(&quot;.&quot;)) @mock.patch(&quot;pathlib.Path.rename&quot;) def test_rename_file(mock_rename): &quot;&quot;&quot; Assert that ~.rename_file() calls pathlib.Path.rename with the correct target. &quot;&quot;&quot; base_dir = pathlib.Path(&quot;.&quot;) / &quot;projectible&quot; rename_file(&quot;old_name&quot;, &quot;new_name&quot;, base_dir) mock_rename.assert_called_once_with(base_dir / &quot;new_name&quot;) @pytest.mark.parametrize( &quot;manage_dir&quot;, [pathlib.Path(&quot;.&quot;), pathlib.Path(&quot;.&quot;) / &quot;projectible&quot;] ) @mock.patch(&quot;pathlib.Path.mkdir&quot;) @mock.patch(&quot;classy_start.start.start_app&quot;) @mock.patch(&quot;classy_start.start.write_file&quot;) def test_create_accounts_app(mock_write_file, mock_start_app, _mock_mkdir, manage_dir): &quot;&quot;&quot; Assert that ~.create_accoung_app() calls ~.start_app() with the correct arguments. And that it calls pathlib.Path.write_text the correct number of times and with the correct arguments. &quot;&quot;&quot; create_accounts_app(manage_dir) accounts_app_dir = manage_dir / &quot;accounts&quot; model_file = accounts_app_dir / &quot;models.py&quot; admin_file = accounts_app_dir / &quot;admin.py&quot; mock_start_app.assert_called_once_with(&quot;accounts&quot;, accounts_app_dir) assert mock_write_file.call_count == 2 assert mock_write_file.has_calls( [ mock.call(model_file, auth_user_model_file_content,), mock.call(admin_file, auth_user_admin_file_content,), ] ) @mock.patch(&quot;pathlib.Path.touch&quot;) @mock.patch(&quot;pathlib.Path.write_text&quot;) def test_write_file(mock_write_text, mock_touch): file = pathlib.Path(&quot;project&quot;) / &quot;app&quot; / &quot;an_app_file.py&quot; content = &quot;&quot;.join(random.sample(string.printable, 64)) write_file(file, content) mock_touch.assert_called_once() mock_write_text.assert_called_once_with(content) </code></pre> <h2>GitHub Repository</h2> <p><a href="https://github.com/mfonism/django-classy-start" rel="nofollow noreferrer">https://github.com/mfonism/django-classy-start</a></p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-27T14:39:27.983", "Id": "248505", "Score": "3", "Tags": [ "python", "unit-testing", "django" ], "Title": "Command Line Utility for Starting Django Projects and Apps with Custom Files" }
248505
<p>I’ve never used ResourceBundle before.</p> <p>I have a simple Google Play Scraper (uses Jsoup library) which I want to customize and introduce multilingual support.</p> <p>I have some classes. First you have to get html Document to parse later.</p> <p>GooglePlayConnection class (provides Connection, then I just need to invoke method get()):</p> <pre><code>public class GooglePlayConnection { /** * Typical base part of URL for all apps. */ private static final String BASE_URL = &quot;https://play.google.com/store/apps/details?&quot;; private final String language; private final String country; public GooglePlayConnection(String language, String country) { this.language = language; this.country = country; } /** * Tries to connect to provided URL. Uses localized version of URL that retrieves from {@link #getLocalized(Map, String, String)}. * Also checks if URL applies to APPS category to prevent from parsing books/music/movies. */ public Connection connect(String URL) throws InvalidGooglePlayUrlException, MalformedURLException, URISyntaxException { final java.net.URL url= new URL(URL); if (GooglePlayCorrectURL.isUrlValid(url)) { if (!url.getPath().contains(&quot;apps&quot;)) { throw new InvalidGooglePlayUrlException(&quot;Wrong Google Play category&quot;); } Map&lt;String, String&gt; params = getParameters(URL); URL = getLocalized(params, language, country).toString(); return Jsoup.connect(URL); } else { throw new InvalidGooglePlayUrlException(&quot;Not Google Play URL&quot;); } } /** * Gets localized version of provided URL. */ private URL getLocalized(Map&lt;String, String&gt; params, String language, String country) throws MalformedURLException, URISyntaxException { URIBuilder uriBuilder = new URIBuilder(BASE_URL) .addParameter(&quot;id&quot;, params.get(&quot;id&quot;)) .addParameter(&quot;hl&quot;, language) .addParameter(&quot;gl&quot;, country); return uriBuilder.build().toURL(); } private Map&lt;String, String&gt; getParameters(String url) throws MalformedURLException { return Arrays.stream(new URL(url).getQuery().split(&quot;&amp;&quot;)) .map(s -&gt; s.split(&quot;=&quot;)) .collect(Collectors.toMap(k -&gt; k[0], v -&gt; v.length &gt; 1 ? v[1] : &quot;&quot;)); } </code></pre> <p>Scraper:</p> <pre><code>public class GooglePlayAppsScraper { /** * Default language system settings to determine in which language to analyze HTML document. */ private static final ResourceBundle resourceBundle = ResourceBundle.getBundle(&quot;patterns&quot;, Locale.getDefault()); /** * CSS-like element selectors that find elements matching a query. */ private static final String CURRENT_VERSION = resourceBundle.getString(&quot;game.currentVersion&quot;); private static final String REQUIREMENTS = resourceBundle.getString(&quot;game.requirements&quot;); public String getCurrentVersion(Document htmlDocument) { return getIfAttributePresent(CURRENT_VERSION, htmlDocument); } public String getRequirements(Document htmlDocument) { return getIfAttributePresent(REQUIREMENTS, htmlDocument); } ... </code></pre> <p>And I've some bundles with different languages, like this:</p> <pre><code>//en game.currentVersion = div:matchesOwn(^Current Version$) game.lastUpdate = div:matchesOwn(^Updated$) game.installs = div:matchesOwn(^Installs$) game.requirements = div:matchesOwn(^Requires Android$) ... </code></pre> <pre><code>//ru game.currentVersion = div:matchesOwn(^Текущая версия$) game.lastUpdate = div:matchesOwn(^Обновлено$) game.installs = div:matchesOwn(^Количество установок$) game.requirements = div:matchesOwn(^Требуемая версия Android$) ... </code></pre> <p>What's important? I need to &quot;transfer&quot; information about language to my scraper. To search elements the language in the document must match the one that the scraper will use.</p> <p>I don't want to pass these parameters to each scraper method. It will looks like:</p> <pre><code>public String getRequirements(Document htmlDocument, String language) { ResourceBundle resourceBundle = ResourceBundle.getBundle(&quot;patterns&quot;, Locale.forLanguageTag(language)); String requirements = resourceBundle.getString(&quot;game.requirements&quot;); return getIfAttributePresent(requirements, htmlDocument); } </code></pre> <p>I created LanguageSettings:</p> <pre><code>public class LanguageSettings { private static Map&lt;String, String&gt; settings = new HashMap&lt;&gt;(); public static Map&lt;String, String&gt; getSettings() { return settings; } public static void setSettings(Map&lt;String, String&gt; settings) { LanguageSettings.settings = settings; } } </code></pre> <p>Then update connection:</p> <pre><code> private final String language; private final String country; public GooglePlayConnection(String language, String country) { this.language = language; this.country = country; LanguageSettings.getSettings().put(&quot;language&quot;, language); } </code></pre> <p>Then update scraper:</p> <pre><code>private static final ResourceBundle resourceBundle = ResourceBundle.getBundle(&quot;patterns&quot;, Locale.forLanguageTag(LanguageSettings.getSettings().get(&quot;language&quot;))); </code></pre> <p>Simple usage:</p> <pre><code>String url = &quot;https://play.google.com/store/apps/details?id=com.playdigious.cultist&quot;; Document document = new GooglePlayConnection(&quot;en&quot;, &quot;US&quot;).connect(url).get(); GooglePlayAppsScraper scraper = new GooglePlayAppsScraper(); System.out.println(scraper.getPrice(document)); </code></pre> <p>This will work if done in the right order (like in the example), but I'm sure there is a better solution.</p> <p>How should I connect my scraper and connection to one ResourceBundle in the proper way?</p>
[]
[ { "body": "<p>One problem here that I immediately see you expressed yourself: your code should be invoked in the right order for it to work.</p>\n<p>What this means is your components have a shared state that they don't state upfront (the <code>ResourceBundle</code> and <code>LanguageSettings</code>), and the <code>GooglePlayAppsScraper</code> is even built in such way that all prior operations must be gone before this class ever gets loaded - because it accesses the <code>LanguageSettings</code> statically and saves result in a <code>static final</code> field, its initialization will be done once per the app lifecycle (not quite, but close to), when the class gets loaded from disk. If you don't initialize correctly, then it, at least, fails pretty fast with a <code>NullPointerException</code>, but we can do better.</p>\n<p>What I think is a better approach is to get rid of static state in there.\nI suggest making <code>LanguageSettings</code> a more apparent part of the whole system.</p>\n<p>First, make it an object:</p>\n<pre><code>public class LanguageSettings {\n private String languageTag;\n private String country;\n\n public LanguageSettings(String language, String country) {\n this.languageTag = Objects.requireNonNull(language, &quot;languageTag&quot;);\n this.country = Objects.requireNonNull(country, &quot;country&quot;);\n }\n\n public String getLanguageTag() {\n return languageTag;\n }\n\n public String getCountry() {\n return country;\n }\n}\n</code></pre>\n<p>Then, make <code>GoogleConnection</code> depend on it:</p>\n<pre><code>public class GoogleConnection {\n private LanguageSettings settings;\n\n public GoogleConnection(LanguageSettings settings) {\n this.settings = Objects.requireNonNull(settings);\n }\n &lt;...snip...&gt;\n private URL getLocalized(Map&lt;String, String&gt; params) throws MalformedURLException, URISyntaxException {\n URIBuilder uriBuilder = new URIBuilder(BASE_URL)\n .addParameter(&quot;id&quot;, params.get(&quot;id&quot;))\n .addParameter(&quot;hl&quot;, settings.getLanguageTag())\n .addParameter(&quot;gl&quot;, settings.getCountry());\n return uriBuilder.build().toURL();\n }\n}\n</code></pre>\n<p>And also, make <code>GooglePlayAppsScraper</code> dependent on the same <code>LanguageSettings</code> object for initialization:</p>\n<pre><code>public class GooglePlayAppsScraper {\n private ResourceBundle bundle;\n\n /*\n * Notice here: I am not reading from bundle, these are now simple constants\n */\n private static final String CURRENT_VERSION = &quot;game.currentVersion&quot;;\n\n private static final String REQUIREMENTS = &quot;game.requirements&quot;;\n\n public GooglePlayAppsScraper(LanguageSettings settings) {\n this.bundle = initBundle(settings);\n }\n\n private ResourceBundle initBundle(LanguageSettings settings) {\n Objects.requireNonNull(settings);\n return ResourceBundle.getBundle(&quot;patterns&quot;, Locale.forLanguageTag(settings.getLanguageTag());\n }\n\n public String getRequirements(Document htmlDocument) {\n return getIfAttributePresent(bundle.getString(REQUIREMENTS), htmlDocument);\n }\n}\n</code></pre>\n<p>Advantages of doing it this way - the &quot;right way&quot; to invoke your code is essentially now the only way it can be done - unless you already have <code>LanguageSettings</code> object, you can't initialize neither <code>GooglePlayAppsScraper</code>, nor <code>GoogleConnection</code>. And when you do (assuming you supply the same object for both), it will always initialize correctly, it's not as easy to swap two lines of code and get exceptions because of it.\nYour app will also now support running several connections and scrapers in parallel (assuming this is something you want and external services allow it) - and scrapers can even have different language settings (they couldn't before because <code>Settings</code> was a per-app state).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-09-01T13:00:33.663", "Id": "248758", "ParentId": "248508", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-27T16:33:57.243", "Id": "248508", "Score": "2", "Tags": [ "java" ], "Title": "Proper usage of ResourceBundle" }
248508
<p>Question: Given an array numbers <span class="math-container">$$a := [2, 7, 8, 5, 1, 6, 3, 9, 4]$$</span> Check the below conditions, both the conditions should be satisfied.</p> <p><span class="math-container">\begin{gather} \text{If }a[i] &gt; a[i-1]\text{ or if first element }a[i] &gt; a[i+1] \end{gather}</span></p> <p><span class="math-container">\begin{gather} \text{If }a[i] &gt; a[i+1]\text{ or if last element }a[LastIndex] &gt; a[LastIndex - 1] \end{gather}</span></p> <ul> <li><p>1st Iteration - 8, 6, 9 are peak values.</p> <ul> <li>Remove the smallest ele.</li> <li>Remove 6.</li> <li>New arr <code>{2, 7, 8, 5, 1, 3, 9, 4}</code>.</li> <li>Output Arr - <code>{6}</code></li> </ul> </li> <li><p>2nd Iteration - 8, 9 are peak values.</p> <ul> <li>Remove the smallest ele.</li> <li>Remove 8.</li> <li>New arr <code>{2, 7, 5, 1, 3, 9, 4}</code>.</li> <li>Output Arr - <code>{6, 8}</code></li> </ul> </li> <li><p>3rd Iteration - 7, 9 are peak values.</p> <ul> <li>Remove the smallest ele.</li> <li>Remove 7. New arr <code>{2, 5, 1, 3, 9, 4}</code>.</li> <li>Output Arr - {6, 7, 8}</li> </ul> </li> <li><p>4th Iteration - 5, 9 are peak values.</p> <ul> <li>Remove the smallest ele.</li> <li>Remove 5.</li> <li>New arr <code>{2, 1, 3, 9, 4}</code>.</li> <li>Output Arr - <code>{6, 7, 8, 5}</code></li> </ul> </li> <li><p>5th Iteration - 2, 9 are peak values.</p> <ul> <li>Remove the smallest ele.</li> <li>Remove 2.</li> <li>New arr <code>{1, 3, 9, 4}</code>.</li> <li>Output Arr - <code>{6, 7, 8, 5, 2}</code></li> </ul> </li> <li><p>6th Iteration - 9 are peak values.</p> <ul> <li>Remove the smallest ele.</li> <li>Remove 9.</li> <li>New arr <code>{1, 3, 4}</code>.</li> <li>Output Arr - <code>{6, 7, 8, 5, 2, 9}</code></li> </ul> </li> <li><p>7th Iteration - 4 are peak values.</p> <ul> <li>Remove the smallest ele.</li> <li>Remove 4.</li> <li>New arr <code>{1, 3}</code>.</li> <li>Output Arr - <code>{6, 7, 8, 5, 2, 9, 4}</code></li> </ul> </li> <li><p>8th Iteration - 3 are peak values.</p> <ul> <li>Remove the smallest ele.</li> <li>Remove 3.</li> <li>New arr {1}.</li> <li>Output Arr - <code>{6, 7, 8, 5, 2, 9, 4, 3}</code></li> </ul> </li> <li><p>9th Iteration - 1 are peak values.</p> <ul> <li>Remove the smallest ele.</li> <li>Remove 1.</li> <li>New arr {1}.</li> <li>Output Arr - <code>{6, 7, 8, 5, 2, 9, 4, 3, 1}</code></li> </ul> </li> </ul> <p>Output: <code>{6, 8, 7, 5, 2, 9, 4, 3, 1}</code></p> <p>My solution is working but I am looking for optimized solution. Please let me know.</p> <p>Here is my code:</p> <pre><code>public int[] findMinimumPeaks(int[] arr){ List&lt;Integer&gt; list1 = new ArrayList&lt;Integer&gt;(arr.length); int[] output = new int[arr.length]; for(int i: arr) list1.add(i); for(int i =0; i&lt;arr.length; i++){ int minIndex = minimumPeakElement(list1); output[i] = list1.get(minIndex); list1.remove(minIndex); } return output; } public int minimumPeakElement(List&lt;Integer&gt; list1){ int minIndex = 0, peakStart = Integer.MAX_VALUE, peakEnd = Integer.MAX_VALUE; int peak = Integer.MAX_VALUE, minPeak = Integer.MAX_VALUE; if(list1.size() &gt;= 2){ if(list1.get(0) &gt; list1.get(1)) peakStart = list1.get(0); if(list1.get(list1.size() - 1) &gt; list1.get(list1.size() - 2)) peakEnd = list1.get(list1.size() - 1); if(peakStart &lt; peakEnd){ minPeak = peakStart; minIndex = 0; } else if(peakEnd &lt; peakStart){ minPeak = peakEnd; minIndex = list1.size() - 1; } } for(int i=1; i&lt;list1.size() - 1; i++){ if(list1.get(i) &gt; list1.get(i + 1) &amp;&amp; list1.get(i) &gt; list1.get(i-1)) peak = list1.get(i); if(peak &lt; minPeak){ minPeak = peak; minIndex = i; } } return minIndex; } <span class="math-container">```</span> </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-27T18:46:54.297", "Id": "486827", "Score": "3", "body": "That definition looks wrong. Is the original online somewhere?" } ]
[ { "body": "<p>Thou shalt not bruteforce.</p>\n<p>Your algorithm exhibits a quadratic time complexity, and cannot be salvaged. You need a better one.</p>\n<p>First observation you should make is that when you remove the peak, other peaks stay put. That alone is enough to see that rescanning the entire array is a waste of time.</p>\n<p>More important observation is that once you remove the peak, the new peak may appear only in the position immediately adjacent to the peak being removed. Please prove this fact (or at least convince yourself that it is so). Also notice that the newborn peak would in general be smaller than the existing peaks, if any.</p>\n<p>I hope it is enough to get you going.</p>\n<hr />\n<p>As for the proper review:</p>\n<ul>\n<li><p>Flat is better than nested. The condition <code>list1.size() &gt;= 2</code> better be reversed:</p>\n<pre><code> if (list1.size() &lt; 2) {\n // The list consists of a single element, which is a peak,\n // and it resides at index 0\n return 0;\n }\n // Proceed with a general case here\n ....\n</code></pre>\n</li>\n<li><p><code>list1</code> looks like a strange name. There are no other lists, are there?</p>\n</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-27T21:32:24.213", "Id": "486842", "Score": "0", "body": "I'd be interested in how you'd avoid the still remaining quadratic runtime." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-27T21:44:48.293", "Id": "486843", "Score": "0", "body": "@superbrain Why quadratic? I do not take the `array` as a requirement. If it is initially in the array, copy it (in linear time) into the linked list. Or am I not seeing something important?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-27T21:48:46.197", "Id": "486844", "Score": "1", "body": "Yes, the removal time is what I meant. Linked list sounds good." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-27T22:10:54.373", "Id": "486845", "Score": "0", "body": "Just saw your edit. Nice observation. So except for sorting initial peaks, this could be done in linear time, I guess?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-27T22:12:30.627", "Id": "486846", "Score": "0", "body": "@superbrain Correct." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-27T21:28:00.980", "Id": "248520", "ParentId": "248510", "Score": "9" } }, { "body": "<p>I have some suggestions for your code.</p>\n<h2>Always add curly braces to <code>loop</code> &amp; <code>if</code></h2>\n<p>In my opinion, it's a bad practice to have a block of code not surrounded by curly braces; I saw so many bugs in my career related to that, if you forget to add the braces when adding code, you break the logic / semantic of the code.</p>\n<h2>Extract the expression to variables when used multiple times.</h2>\n<p>In your code, you can extract the similar expressions into variables; this will make the code shorter and easier to read. (java.util.List#size, java.util.List#get, ect)</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-28T01:58:08.603", "Id": "248529", "ParentId": "248510", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-27T17:04:52.883", "Id": "248510", "Score": "4", "Tags": [ "java", "array" ], "Title": "Find minimum peak elements in an array" }
248510
<p>I've validator system that validates input data before saving to DB. So let's say I want to create new user. We are at the service class:</p> <pre><code>package main.user; import main.entity.User; import main.user.validator.attributesvalidators.UserAttributesValidator; import main.user.validator.availabilityvalidators.UserAvailabilityValidator; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.List; @Service public class UserCrudActivitiesService { private final UserRepository userRepository; public UserCrudActivitiesService(UserRepository userRepository) { this.userRepository = userRepository; } public List&lt;String&gt; createUser(User user) { UserAttributesValidator userAttributesValidator = new UserAttributesValidator(); UserAvailabilityValidator userAvailabilityValidator = new UserAvailabilityValidator(userRepository); List&lt;String&gt; messages = userAttributesValidator.validate(user); messages.addAll(userAvailabilityValidator.check(user)); if (messages.isEmpty()) { userRepository.save(user); //TODO passwordencoder } return messages; } public User updateUser(User user) { return userRepository.save(user); } } </code></pre> <p>We've got two validators - first which will check whether attributes of user are fine and then whether some of attributes are free so we're sure that this user will be unique.</p> <p>Validators structure:</p> <p><a href="https://i.stack.imgur.com/8gUME.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/8gUME.png" alt="enter image description here" /></a></p> <p>In both we got same interface: (for example interface for attributes)</p> <pre><code>package main.user.validator.attributesvalidators; import main.entity.User; public interface IUserAttributesValidator { String validate(User user); } </code></pre> <p>Then we got somehing which is called (again for attrubutes) <strong>UserAttributesValidator</strong> It's the class which contain all others validators and inside of it's constructor we create list of all validators so we can loop through all in one stream.</p> <pre><code>package main.user.validator.attributesvalidators; import main.entity.User; import java.util.ArrayList; import java.util.List; import java.util.Objects; import java.util.stream.Collectors; public class UserAttributesValidator { final private List&lt;IUserAttributesValidator&gt; validators; public UserAttributesValidator() { validators = new ArrayList&lt;&gt;(); validators.add(new UserEmailValidator()); validators.add(new UserFirstNameValidator()); validators.add(new UserLastNameValidator()); validators.add(new UserPasswordValidator()); validators.add(new UserPhoneValidator()); validators.add(new UsernameValidator()); } public List&lt;String&gt; validate(User user) { return validators.stream() .map(e -&gt; e.validate(user)) .filter(Objects::nonNull) .collect(Collectors.toList()); } } </code></pre> <p>We get list as an output and it's fine. Same thing is done for <strong>AvailabilityValidator</strong></p> <p>One on validator for example:</p> <pre><code>package main.user.validator.attributesvalidators; import main.entity.User; public class UsernameValidator implements IUserAttributesValidator { public static final int NAME_MAXIMUM_LENGTH = 30; public static final int NAME_MINIMUM_LENGTH = 3; public static final String NAME_ILLEGAL_CHARACTER_REGEX = &quot;[A-Za-z0-9]+&quot;; @Override public String validate(User user) { String attribute = user.getUsername(); if (attribute.length() &gt; NAME_MAXIMUM_LENGTH) { return &quot;username is too long&quot;; } else if (attribute.length() &lt; NAME_MINIMUM_LENGTH) { return &quot;username is too short&quot;; } else if (!attribute.matches(NAME_ILLEGAL_CHARACTER_REGEX)) { return &quot;username contains illegal character&quot;; } return null; } } </code></pre> <p>Now, my concern is.... I think that this is bad design. I mean, I create interface IUserAttributesValidator, then I create class that contain all others validators that has also method which is name the same as the method in interface. I wonder whether I can merge these two into one? Is it possible? Is there any possibility to improve this code? Another my thought is that both (availability and attributes checker) has the same interface with the same method but different argument, but I don't know whether it is also possible to have only one interface for both.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-28T05:41:05.873", "Id": "486863", "Score": "0", "body": "Welcome to Code Review, I have seen you are using `spring` in your system and my first thought was to use `javax.validation` package for validation that is often coupled with the framework. There is some specific reason to not use this already available package ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-28T06:24:18.123", "Id": "486872", "Score": "0", "body": "@dariosicily not really, I did not know that something like that exists" } ]
[ { "body": "<p>As I said in my comment below your question, java already covers your need of defining custom validators for your data before saving them in the database. The package coupled with the <code>spring</code> framework is the <code>javax.validation</code> package, so taking for example your custom validator code:</p>\n<pre><code>public class UsernameValidator implements IUserAttributesValidator {\n\n public static final int NAME_MAXIMUM_LENGTH = 30;\n public static final int NAME_MINIMUM_LENGTH = 3;\n public static final String NAME_ILLEGAL_CHARACTER_REGEX = &quot;[A-Za-z0-9]+&quot;;\n\n @Override\n public String validate(User user) {\n String attribute = user.getUsername();\n if (attribute.length() &gt; NAME_MAXIMUM_LENGTH) {\n return &quot;username is too long&quot;;\n } else if (attribute.length() &lt; NAME_MINIMUM_LENGTH) {\n return &quot;username is too short&quot;;\n } else if (!attribute.matches(NAME_ILLEGAL_CHARACTER_REGEX)) {\n return &quot;username contains illegal character&quot;;\n }\n return null;\n }\n}\n</code></pre>\n<p>This can be replaced using the mechanism of annotations directly inside your <code>User</code> class in this way :</p>\n<pre><code>import javax.validation.constraints.Pattern;\nimport javax.validation.constraints.Size;\n\npublic class User {\n \n @Size(min=3, max=30, message=&quot;username length should be between 3 and 30 chars&quot;)\n //it seems me username should contain just these chars\n @Pattern(regexp=&quot;[A-Za-z0-9]+&quot;, message=&quot;username contains illegal characters&quot;) \n private String username;\n}\n</code></pre>\n<p>The same mechanism can be applied to the other fields of your <code>User</code> class when you need in the same way.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-28T07:57:06.570", "Id": "486881", "Score": "0", "body": "Oh, that's great how fast can we apply these validators here. I cannot find since when this is available. I'm using the newest SpringBoot, but since what version of Spring I can use it? Do you have such a knowledge?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-28T08:02:53.230", "Id": "486883", "Score": "0", "body": "If you are using SpringBoot check [SpringBoot validation guide](https://spring.io/guides/gs/validating-form-input/) and `pom` associated for dependencies, for Spring probably you have to add manually the maven dependency." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-28T08:23:55.553", "Id": "486886", "Score": "0", "body": "Well, I'm not sure on what question you answered haha or I did not understand unfortunately. I mean, for sure it will be available for newest SpringBoot, but I'm wondering what spring version is needed for that" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-28T11:56:52.127", "Id": "486903", "Score": "0", "body": "@makiz1234 For Spring, you have to add the maven dependency to the `pom' and rebuild the project." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-28T12:21:02.230", "Id": "486907", "Score": "0", "body": "Yeah, I know that, but I asked about the least version of spring which is needed to have this validation" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-28T12:53:34.993", "Id": "486908", "Score": "0", "body": "Nevertheless I will stay with TorbenPutkonen, because I cannot catch these messages if I use javax.validaation and send for example to front. With previous solution I could collect all error messages." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-28T07:52:13.967", "Id": "248534", "ParentId": "248512", "Score": "3" } }, { "body": "<p>Ignoring the possibility of implementing this with tools provided by Spring framework... what you have there is quite close to being a <a href=\"https://en.wikipedia.org/wiki/Composite_pattern\" rel=\"nofollow noreferrer\">composite</a> design pattern so it is a well known and accepted design. What you would need to change to achieve that is to have the both individual validators and the composite validator implement the exact same interface. It makes sense to have the <code>IUserAttributesValidator</code> return a <code>List&lt;String&gt;</code> or <code>Collection&lt;String&gt;</code> as in your example the <code>UsernameValidator</code> might find more than one violation in the input and it would be convenient to return both length and charater set violations from the same invocation (although checking length and character set in the same validator does smell a bit like single responsibility violation).</p>\n<p>Also, instead of returning a List you can pass a list as a parameter so that each validator can append their errors to an existing list instead of creating a new disposable list on every error.</p>\n<pre><code>iterface Validator&lt;T&gt; {\n void validate(T target, List&lt;String&gt; errors);\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-28T08:26:43.593", "Id": "486887", "Score": "0", "body": "Could you make a gist for that solution? I'm wondering whether this solution is better or this with javax.validation which was provided by @dariosicily" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-28T08:33:36.493", "Id": "486888", "Score": "0", "body": "Agree with everything, fyi an irrilevant typo in the code example." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-29T09:41:07.417", "Id": "487011", "Score": "0", "body": "I would really appreciate if you send a gist with sample. I understand the deisgn pattern, but I dont knwo what to do with this parametrized validator how should I use it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-29T09:53:41.350", "Id": "487012", "Score": "0", "body": "What is more 1)why you say that that I should return length also, why do I need need? 2) you said that I should return List<String> then that I should pass errors, you mean I should choose one from these?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-09-07T19:26:42.073", "Id": "488049", "Score": "0", "body": "hey, you there?" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-28T08:07:38.853", "Id": "248535", "ParentId": "248512", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-27T19:23:53.613", "Id": "248512", "Score": "7", "Tags": [ "java", "spring", "interface" ], "Title": "Refactoring validator system" }
248512
<p>I have several hundreds gigabytes of photos, approximately half of them are duplicates. Average photo's size is about 4 MB, but some files (video) have size more than 100 MB.</p> <p>I want to do the following:</p> <ol> <li>Find all duplicates and move them into the separate directory - <strong>&quot;Trash_bin&quot;</strong>.</li> <li>Move all unique files into a <strong>&quot;Unique_pictures&quot;</strong> directory, which will have sub-directories named according file's modification time - by <code>year_month_day</code> format, example: <code>2010_04_25</code>.</li> </ol> <p><strong>An example of original directory structure</strong></p> <pre><code>Picture_original_dir/ ├── 001.JPG ├── 002.JPG ├── 003.JPG ├── 017.jpg ├── 033 - copy.jpg ├── 033.jpg ├── 070.JPG ├── 444 - copy (2).JPG ├── 444 - copy.JPG ├── 444.JPG ├── dir_1 │   ├── 001.JPG │   ├── 002.JPG │   ├── 003.JPG │   └── sub_dir_1 │   └── 017.jpg ├── dir_2 │   ├── 001.JPG │   ├── 002.JPG │   ├── 003.JPG │   ├── DSC009111.JPG │   └── DSC00911.JPG ├── DSC00911.JPG └── empty_dir_1 └── sub_empty_dir_1 </code></pre> <p>I want to rearrange them by this way:</p> <pre><code>Picture_test_dir/ ├── Trash_bin │   ├── 2010_04_25_00001.jpg_4 │   ├── 2010_04_25_00001.jpg_5 │   ├── 2013_07_09_00001.jpg_6 │   ├── 2013_07_09_00001.jpg_7 │   ├── 2013_08_09_00001.jpg_8 │   ├── 2013_08_09_00001.jpg_9 │   ├── 2013_08_27_00001.jpg_10 │   ├── 2014_09_17_00001.jpg_1 │   ├── 2014_09_17_00001.jpg_2 │   ├── 2014_10_09_00001.jpg_11 │   ├── 2014_10_09_00001.jpg_12 │   └── 2015_01_16_00001.jpg_3 └── Unique_pictures ├── 2010_04_25 │   └── 00001.jpg ├── 2013_07_09 │   └── 00001.jpg ├── 2013_08_09 │   └── 00001.jpg ├── 2013_08_27 │   └── 00001.jpg ├── 2014_09_17 │   └── 00001.jpg ├── 2014_10_09 │   └── 00001.jpg ├── 2014_10_14 │   └── 00001.jpg └── 2015_01_16 └── 00001.jpg </code></pre> <p>To accomplish this task I wrote a script.</p> <p>The idea is to calculate a hash of every file and put files with same hash into a dictionary with the hash as a key and a list of paths of these files as value.</p> <p>To improve performance the next trick is used - files with unique sizes skips hash calculation.</p> <p><strong>I am interested in:</strong></p> <ol> <li>Code review.</li> <li>The program is running quite long time, for example 40 000 photos, 180 GB are processed by 40 minutes, so it will be good to improve performance somehow. I have increased performance by changing <code>sha256</code> to <code>md5</code> algorithm (in price of reliability), may be you know somewhat else. I have tried shortcuting <code>os.path.getsize</code> to <code>getsize = os.path.getsize</code> but didn't get any speedup.</li> <li>Are all used modules optimal or more appropriate are existing? I wasn't use <code>Path</code> module because it is more slow comparing to <code>os.path</code> (by rumors on the internet). Also I have used <code>sys.argv[1]</code> instead of <code>argparse</code> module, because the program has just one argument at this moment.</li> </ol> <p><strong>Script</strong></p> <p>Usage: <code>./rearrange_photos.py root_dir</code></p> <pre><code>#!/usr/bin/python3 import os from hashlib import sha256, md5 import sys from time import time from datetime import timedelta, datetime def print_progress(message, interval): global prevtime global starttime new_time = time() if (new_time - prevtime) &gt;= interval: print(message) print(f&quot;Time has elapsed: {timedelta(seconds=new_time - starttime)}&quot;) prevtime = new_time def delete_empty_dirs(source_dir): for path, dirs, files in os.walk(source_dir, topdown=False): if not os.listdir(path): os.rmdir(path) def create_new_path(file_path, file_modification_time=None): global new_dir_counters if file_modification_time == None: file_modification_time = os.path.getmtime(file_path) timestamp = datetime.fromtimestamp(file_modification_time) new_dirname = timestamp.strftime('%Y_%m_%d') if new_dirname not in new_dir_counters: new_dir_counters[new_dirname] = 0 os.makedirs(f&quot;{dest_dir}/{new_dirname}&quot;, exist_ok=True) new_dir_counters[new_dirname] += 1 ext = os.path.splitext(file_path)[1].lower() new_filename = f&quot;{new_dir_counters[new_dirname]:0&gt;5}{ext}&quot; new_path = f&quot;{dest_dir}/{new_dirname}/{new_filename}&quot; return new_path def get_oldest_file(paths): return min((os.path.getmtime(path), path) for path in paths) def add_hash_to_dct(file_path, dct): with open(file_path, 'rb') as f_d: # hsh = sha256(f_d.read()).hexdigest() hsh = md5(f_d.read()).hexdigest() dct.setdefault(hsh, []) dct[hsh].append(file_path) def make_dir_unique(name): while os.path.exists(name): name = name + '1' os.makedirs(name, exist_ok=True) return name def file_uniqness(root_dir): unique_size_files = {} non_unique_size_files = {} non_unique_sizes = set() file_cnt = 0 for path, dirs, files in os.walk(root_dir): # Have put this line here for perfomance reasons, despite it makes # calculating of progress less accurate. # It would be more accurate inside the inner loop. print_progress(f&quot;{file_cnt} files have checked&quot;, 5.0) # Firstly, check every file by size, if the size hasn't appeared before, # then no copy of this file was found so far, otherwise an additinal check is # needed - by hash. for filename in files: file_1 = f&quot;{path}/{filename}&quot; file_size = os.path.getsize(file_1) file_cnt += 1 # if two or more files with same size exists if file_size in non_unique_sizes: # Calculate a hash and put it into the dictionary add_hash_to_dct(file_1, non_unique_size_files) # if only one file with same size exists, so this file was considered as unique # until the current file has appeared elif file_size in unique_size_files: file_2 = unique_size_files.pop(file_size) non_unique_sizes.add(file_size) add_hash_to_dct(file_1, non_unique_size_files) add_hash_to_dct(file_2, non_unique_size_files) # if files with the same size doesn't exist else: unique_size_files[file_size] = file_1 return unique_size_files, non_unique_size_files def process_files(unique_files, non_unique_files): for old_path in unique_files.values(): new_path = create_new_path(old_path) os.rename(old_path, new_path) trash_cnt = 1 for paths in non_unique_files.values(): # Some duplicate files have different dates, which was happend # because of updating the modification time by some programs while backuping # So, I want to find and apply the first/oldest date of file, because it is # most likely the original date. file_modification_time, oldest_file_path = get_oldest_file(paths) new_path = create_new_path(oldest_file_path, file_modification_time) os.rename(oldest_file_path, new_path) # I don't want to remove other duplicates immediately, so I just move them # into a &quot;trash&quot; directory. for same_file_path in paths: if same_file_path != oldest_file_path: path_to_original_file = '_'.join(new_path.split('/')[-2:]) os.rename(same_file_path, f&quot;{trash_dir}/{path_to_original_file}_{trash_cnt}&quot;) trash_cnt += 1 def print_summary(all_files_num, duplicate_files_num): print(&quot;\n{:#^80}&quot;.format(&quot;Result&quot;)) print(&quot;{:&lt;20s}{:d}&quot;.format(&quot;number of files:&quot;, all_files_num)) print(&quot;{:&lt;20s}{:d}&quot;.format(&quot;number of duplicates:&quot;, duplicate_files_num)) print(&quot;{:&lt;20s}{:d}&quot;.format(&quot;number of different files:&quot;, all_files_num - duplicate_files_num)) source_dir = sys.argv[1] dest_dir = f&quot;{source_dir}/Unique_pictures&quot; trash_dir = f&quot;{source_dir}/Trash_bin&quot; new_dir_counters = {} starttime = time() prevtime = starttime # Guarantee that new directories are unique. dest_dir = make_dir_unique(dest_dir) trash_dir = make_dir_unique(trash_dir) unique_files, non_unique_files = file_uniqness(source_dir) non_unique_files_num = sum(len(val) for val in non_unique_files.values()) all_files_num = len(unique_files) + non_unique_files_num duplicate_files_num = non_unique_files_num - len(non_unique_files) # Files movement happens here process_files(unique_files, non_unique_files) delete_empty_dirs(source_dir) print_summary(all_files_num, duplicate_files_num) </code></pre>
[]
[ { "body": "<blockquote>\n<p>Are all used modules optimal or more appropriate are existing? I wasn't use <code>Path</code> module because it is more slow comparing to <code>os.path</code> (by rumors on the internet).</p>\n</blockquote>\n<p>I once saw someone complain when I used an implicit generator expression rather than a list comprehension, as 'the former is slower'.\nWhilst in this case they were correct, the performance difference was so small most people would think there was no difference and many people that test the performance would think it's down to the margin of error.</p>\n<p>Additionally what you have described is called a premature optimization. This is commonly known to be bad as it causes you to use tricks that are harder to understand and makes your code hard to work with; normally with no gain. Whilst you may get a gain, you don't know if that gain was just ridiculously small.</p>\n<p>When improving performance you should:</p>\n<ol>\n<li>Identify the source of the problem.</li>\n<li>Fix the problem.</li>\n<li><em><strong>Test your fix actually fixes the problem.</strong></em></li>\n</ol>\n<p>You should notice that the core problem to premature optimizations is that you're not doing (3). So you're left with poor code, and you don't know how much you gain from that. The worst part is most of the time the performance is negligible or the added complexity has a performance hit. Here it's likely to be negligible.</p>\n<p>Looking at your question we can see that you've kinda followed the above steps twice before. (step 2&amp;3)</p>\n<blockquote>\n<p>I have increased performance by changing <code>sha256</code> to <code>md5</code> algorithm (in price of reliability), may be you know somewhat else. I have tried shortcuting <code>os.path.getsize</code> to <code>getsize = os.path.getsize</code> but didn't get any speed-up.</p>\n</blockquote>\n<ol>\n<li>\n<ol start=\"2\">\n<li>You changed SHA256 to MD5 to improve performance.</li>\n<li>You noticed a speed up.</li>\n</ol>\n</li>\n<li>\n<ol start=\"2\">\n<li>You used <code>getsize</code> rather than <code>os.path.getsize</code>.</li>\n<li>you didn't notice a speed up.</li>\n</ol>\n</li>\n</ol>\n<p>The problem is you're currently playing hit the Piñata. You're flailing that stick around, and you may get lucky. But you're mostly just going to hit nothing. This is because you don't know the source of the problem.</p>\n<p>There are three ways you can go about this.</p>\n<ol>\n<li><p>An educated guess.</p>\n<p>I can guess where the performance is being sunk and see if you're hitting a bottleneck.</p>\n<blockquote>\n<p>The program is running quite long time, for example 40 000 photos, 180 GB are processed by 40 minutes</p>\n</blockquote>\n<p><span class=\"math-container\">$$\\frac{180\\ \\text{GB} * 1000}{40\\ \\text{min} * 60} = 75 \\text{MB/s}$$</span></p>\n<ul>\n<li>SSD - An M.2 NVMe SSD has read speeds of ~2.5 - 3.5 GB/s.<sup><a href=\"https://www.samsung.com/us/computing/memory-storage/solid-state-drives/gaming-ssd/\" rel=\"nofollow noreferrer\">[1]</a></sup> Even if this is not accurate to <em>your</em> SSD (if you have one) then it's so far past the speed we're getting we can assume sequential reads from an SSD is not the problem.</li>\n<li>HDD - The fastest hard drives are getting ~150 - 200 MB/s sequential reads. <sup><a href=\"https://hdd.userbenchmark.com/\" rel=\"nofollow noreferrer\">[2]</a></sup></li>\n<li>MD5 - On some seriously older hardware this runs in ~400 MB/s. <sup><a href=\"https://stackoverflow.com/a/2723941\">[3]</a></sup></li>\n</ul>\n<p>If you're running a hard drive then it looks like you may be maxing out the performance of your disk. The speed is in sequential reads, and since you're going to be zipping back and forth from the lookup table (the sectors that say where the 40000 files are located) and the data in the files (that very may well also be fragmented). Running at 50% speed seems fair.</p>\n<p>Whilst a speed up from moving from SHA256 to MD5 may indicate that there is performance you can get out of a hard-drive I would guess the effort it'd take to get this performance would not be worth it.</p>\n</li>\n<li><p>Profile your code.</p>\n<p>This won't tell you the how fast a function is, but it'll tell you roughly where all the slowdown is. The timings are inaccurate and should only be used to see where slowness is. You then need to use another tool to verify that you have indeed increased performance.</p>\n<p>To use this is quite easy, you just use the <a href=\"https://docs.python.org/3/library/profile.html\" rel=\"nofollow noreferrer\">profile</a> library. Whilst you can profile the code from Python, it is likely easier to just use the command line interface.</p>\n<pre><code>python -m cProfile rearrange_photos.py root_dir\n</code></pre>\n</li>\n<li><p>Time small sections of your code.</p>\n<p>Once you have found a problem piece of code you can try to improve the performance by doing something differently. Like your <code>getsize = os.path.getsize</code> micro-optimization. You can use <a href=\"https://docs.python.org/3/library/timeit.html\" rel=\"nofollow noreferrer\">timeit</a> to do this. I have previously written <a href=\"https://codereview.stackexchange.com/a/221732\">an answer</a> about some issues this has, and how you can iteratively improve performance when using micro-optimizations.</p>\n</li>\n</ol>\n<hr />\n<p>Since I don't really want to emulate your images and I don't know your setup - are you using an SSD or a HDD? How fragmented are your files? What is the structure of your folders and files? - I cannot profile or time your code accurately. However I can make a couple of guesses on how to improve performance of your code.</p>\n<ul>\n<li><p>Micro-optimizations like <code>os.path.getsize</code>, <code>os.path</code>, etc. are, probably, absolutely useless to you. I don't think the bottleneck is Python - even if Python ran 100 times slower I don't think you'd notice at all. This is because most of the time is probably in IO (system) or the hash (C).</p>\n</li>\n<li><p>You want to maximize sequential reads. Most partitions have a lookup table which stores the file structure, the data is then located elsewhere. This means we can at the least get data which we know should be close to each other if we only get the file structure completely before looking at the data.</p>\n<p><strong>NOTE</strong>: This can exacerbate the <a href=\"https://en.wikipedia.org/wiki/Time-of-check_to_time-of-use\" rel=\"nofollow noreferrer\">TOCTOU</a> bugs associated with file systems.</p>\n</li>\n<li><p>Try to maximize drive usage. To do this I would employ <a href=\"https://docs.python.org/3.8/library/multiprocessing.html\" rel=\"nofollow noreferrer\">multiprocessing</a>.</p>\n<p><strong>NOTE</strong>: You may get performance increases with <a href=\"https://docs.python.org/3/library/asyncio.html\" rel=\"nofollow noreferrer\">asyncio</a> or <a href=\"https://docs.python.org/3.8/library/threading.html#module-threading\" rel=\"nofollow noreferrer\">threading</a>. Personally with a rather uneducated guess I think that the <a href=\"https://wiki.python.org/moin/GlobalInterpreterLock\" rel=\"nofollow noreferrer\">GIL</a> will kill any performance you can get with threading. Additionally I'd be careful with asyncio whilst AFAIK async IO and the GIL play ball you may need to become rather educated on two/three technologies to solve this problem.</p>\n<p>To do this you want a 'master' process that has the list (or generator or whatever) of files to validate. From the master you spawn additional processes (commonly called 'slaves') that read the drive and hash the file.</p>\n<p>We can easily see that your <code>file_uniqness</code> fits the master and <code>add_hash_to_dct</code> fits the slave descriptions quite well.</p>\n</li>\n</ul>\n<h1>Conclusion</h1>\n<p>If your data is on a hard-drive, then you time would be better allocated elsewhere. If you're using an SSD first profile your code, if the slowdowns come from what I assume then look into <a href=\"https://docs.python.org/3.8/library/multiprocessing.html\" rel=\"nofollow noreferrer\">multiprocessing</a>.</p>\n<p>You should think about how the technology you're using interacts and influences each other. Yes Python is slow and micro-optimizations can get you some speed, but will they make a hard-drive or file system run faster?</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-29T01:16:53.683", "Id": "248585", "ParentId": "248518", "Score": "3" } }, { "body": "<p>In general use threads for IO bound code and processes for CPU bound code.</p>\n<p>Here are two ideas to reduce IO load:</p>\n<ol>\n<li><p>Try hashing just a small part of the photo files. For example, just hash the first 512 or 1024 bytes. If two files have the same size and hash, then just compare the two files.</p>\n<p>CHUNKSIZE = 512</p>\n<p>hsh = md5(f_d.read(CHUNKSIZE)).hexdigest()</p>\n</li>\n<li><p>Use <code>stat()</code> to get the file size and mtime in one system call rather than separate <code>getsize()</code> and <code>getmtime()</code> (they each make a call to <code>os.stat()</code>)</p>\n</li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-29T17:00:12.737", "Id": "248627", "ParentId": "248518", "Score": "2" } } ]
{ "AcceptedAnswerId": "248585", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-27T20:52:40.000", "Id": "248518", "Score": "2", "Tags": [ "python", "python-3.x" ], "Title": "Rearranging files by separating duplicates from unique ones" }
248518
<h1>Background</h1> <p>The function makes use of <a href="https://www.rdocumentation.org/packages/base/versions/3.6.2/topics/cut" rel="nofollow noreferrer"><code>cut</code></a> function offered in R's base package in order to &quot;bin&quot; a numeric vector into provided categories and apply, meaningful user, friendly labels.</p> <h2>Example</h2> <p>For vector:</p> <pre><code>set.seed(1); x &lt;- runif(10) [1] 0.26550866 0.37212390 ... </code></pre> <p>and brackets <code>c(0.1, 0.3)</code></p> <p>The function would return <em>(for the two values above):</em></p> <pre><code>0.1 &gt;= your_value &lt;= 0.3 your_value &gt;= 0.3 </code></pre> <hr /> <h1>Implementation</h1> <pre><code>cut_into_bins &lt;- function(x, bin_groups, value_name = &quot;your_value&quot;) { # Sort vector bin_groups &lt;- sort(bin_groups) # Ensure infinity at the ends if (head(bin_groups, 1) != Inf) { bin_groups &lt;- append(bin_groups, -Inf, 0) } if (tail(bin_groups, 1) != Inf) { bin_groups &lt;- append(bin_groups, Inf) } # Create labels lbls &lt;- NULL i &lt;- 1 while (i &lt; length(bin_groups)) { lbls[i] &lt;- paste(bin_groups[i], bin_groups[i + 1]) i &lt;- i + 1 } lbls &lt;- sapply( X = lbls, FUN = function(x) { if (grepl(&quot;-Inf&quot;, x, fixed = TRUE)) { gsub(&quot;-Inf&quot;, paste(value_name, &quot;&lt;=&quot;), x) } else if (grepl(&quot;Inf&quot;, x, fixed = TRUE)) { x &lt;- gsub(&quot;Inf&quot;, &quot;&quot;, x) paste(value_name, &quot;&gt;=&quot;, x) } else { gsub(&quot;(\\d+\\.\\d+)(\\s)(\\d+\\.\\d+)&quot;, paste(&quot;\\1 &lt;=&quot;, value_name ,&quot;&lt;= \\3&quot;), x) } } ) # Cut and return simple character vector res &lt;- cut.default( x = x, breaks = bin_groups, include.lowest = TRUE, right = TRUE, labels = lbls ) as.character(trimws(res)) } </code></pre> <h2>Testing</h2> <pre><code>sample_vec &lt;- c( -198,-19292.221,-0.5, 0.1, 0.8, 0.3, 0.11, 0.5, 0.55, 0.6, 0.72, -0.72, 0.95, 1, 1.2, 9829082, 2092 ) custom_bands &lt;- c(0.1, 0.5, 0.6, 0.75, 0.9) # Run function res &lt;- cut_into_bins(x = sample_vec, bin_groups = custom_bands) # print(matrix(data = c(sample_vec, res), ncol = 2)) </code></pre> <h3>Results</h3> <pre><code># [,1] [,2] # [1,] &quot;-198&quot; &quot;your_value &lt;= 0.1&quot; # [2,] &quot;-19292.221&quot; &quot;your_value &lt;= 0.1&quot; # [3,] &quot;-0.5&quot; &quot;your_value &lt;= 0.1&quot; # [4,] &quot;0.1&quot; &quot;your_value &lt;= 0.1&quot; # [5,] &quot;0.8&quot; &quot;0.75 &lt;= your_value &lt;= 0.9&quot; # [6,] &quot;0.3&quot; &quot;0.1 &lt;= your_value &lt;= 0.5&quot; # [7,] &quot;0.11&quot; &quot;0.1 &lt;= your_value &lt;= 0.5&quot; # [8,] &quot;0.5&quot; &quot;0.1 &lt;= your_value &lt;= 0.5&quot; # [9,] &quot;0.55&quot; &quot;0.5 &lt;= your_value &lt;= 0.6&quot; # [10,] &quot;0.6&quot; &quot;0.5 &lt;= your_value &lt;= 0.6&quot; # [11,] &quot;0.72&quot; &quot;0.6 &lt;= your_value &lt;= 0.75&quot; # [12,] &quot;-0.72&quot; &quot;your_value &lt;= 0.1&quot; # [13,] &quot;0.95&quot; &quot;your_value &gt;= 0.9&quot; # [14,] &quot;1&quot; &quot;your_value &gt;= 0.9&quot; # [15,] &quot;1.2&quot; &quot;your_value &gt;= 0.9&quot; # [16,] &quot;9829082&quot; &quot;your_value &gt;= 0.9&quot; # [17,] &quot;2092&quot; &quot;your_value &gt;= 0.9&quot; </code></pre> <hr /> <h1>Sought feedback</h1> <p>In particular, I'm interested in comments addressing the following:</p> <ul> <li>The way object <code>lols</code> is constructed is inelegant. In particular, I don't appreciate reliance on <code>gsub</code>; what would be wiser approach to this challenge?</li> <li>Are there any edge cases that function may not capture? <ul> <li>In the actual implementation I'm also testing for correct types of passed vectors: <code>x</code> and <code>bin_groups</code> so there is no risk of strings being passed instead of numeric vectors, etc.</li> </ul> </li> </ul> <hr /> <h1>Some afterthoughs ...</h1> <p>Following <a href="https://codereview.stackexchange.com/users/143127/minem">@minem's</a> <a href="https://codereview.stackexchange.com/a/248537/94838">reply</a>, I've run some benchmarking tests on different approaches to label creation:</p> <pre><code># Functions --------------------------------------------------------------- unique_sort &lt;- function(x) { x &lt;- c(Inf, -Inf, x) x &lt;- unique(x) sort(x) } sort_unique &lt;- function(x) { x &lt;- c(Inf, -Inf, x) x &lt;- sort(x) unique(x) } if_logic &lt;- function(x) { if (head(x, 1) != Inf) { x &lt;- append(x, -Inf, 0) } if (tail(x, 1) != Inf) { x &lt;- append(x, Inf) } } # Benchmark --------------------------------------------------------------- bands &lt;- c(0.1, 0.5, 0.6, 0.75, 0.9) bench::mark( unique_sort(x = bands), sort_unique(x = bands), if_logic(x = bands) ) </code></pre> <h2>Results</h2> <p>It would appear that clunky <code>if</code> approach performs better; although, this is not something that is relevant to this function as labels are created only once...</p> <pre><code># A tibble: 3 x 13 expression min median `itr/sec` mem_alloc `gc/sec` n_itr n_gc total_time result memory time gc &lt;bch:expr&gt; &lt;bch:tm&gt; &lt;bch:t&gt; &lt;dbl&gt; &lt;bch:byt&gt; &lt;dbl&gt; &lt;int&gt; &lt;dbl&gt; &lt;bch:tm&gt; &lt;list&gt; &lt;list&gt; &lt;list&gt; &lt;list&gt; 1 unique_sort(x = bands) 30.01µs 33.7µs 27365. 0B 13.7 9995 5 365ms &lt;dbl [… &lt;Rprofm… &lt;bch:t… &lt;tibbl… 2 sort_unique(x = bands) 30.38µs 61.2µs 14340. 0B 8.87 6466 4 451ms &lt;dbl [… &lt;Rprofm… &lt;bch:t… &lt;tibbl… 3 if_logic(x = bands) 9.32µs 11.6µs 84078. 0B 16.8 9998 2 119ms &lt;dbl [… &lt;Rprofm… &lt;bch:t… &lt;tibbl… </code></pre>
[]
[ { "body": "<p>I would adjust the function like:</p>\n<pre><code>cut_into_bins2 &lt;- function(x, bin_groups, value_name = &quot;your_value&quot;) {\n \n # Ensure infinity at the ends\n bin_groups &lt;- c(-Inf, Inf, bin_groups)\n bin_groups &lt;- unique(bin_groups)\n bin_groups &lt;- sort(bin_groups)\n \n # Create labels\n bin_groups2 &lt;- bin_groups[-length(bin_groups)][-1]\n n2 &lt;- length(bin_groups2)\n lbls &lt;- c(\n sprintf(&quot;%s &lt;= %s&quot;, value_name, bin_groups2[1]),\n sprintf(&quot;%s &lt; %s &lt;= %s&quot;, bin_groups2[-n2], value_name, bin_groups2[-1]),\n sprintf(&quot;%s &lt; %s&quot;, bin_groups2[n2], value_name)\n )\n \n # Cut and return simple character vector\n res &lt;-\n cut.default(\n x = x,\n breaks = bin_groups,\n include.lowest = TRUE,\n right = TRUE,\n labels = lbls\n )\n res\n return(as.character(res))\n}\n</code></pre>\n<ol>\n<li>shorter addition of Inf values. We add them, take unique values and then sort.</li>\n<li>rewrote creation of labels. As we know all values are unique and sorted we can create the labels like this. + adjusted the labels to match the results ('&lt;' instead of '&lt;=' for interval matching)</li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-28T08:48:24.677", "Id": "248537", "ParentId": "248519", "Score": "1" } } ]
{ "AcceptedAnswerId": "248537", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-27T21:16:29.723", "Id": "248519", "Score": "1", "Tags": [ "r", "vectors" ], "Title": "Cutting continuous variable into predefined blocks with custom labels" }
248519
<p>I have an array of log objects with <code>log_type</code>s and <code>date</code>s, like this:</p> <pre><code>[ { log_type: 'eventOne', date: '2020-08-27T00:00:00+00:00' }, { log_type: 'eventOne', date: '2020-08-27T00:00:00+00:00' }, { log_type: 'eventTwo', date: '2020-08-27T00:00:00+00:00' }, { log_type: 'eventTwo', date: '2020-08-27T00:00:00+00:00' }, { log_type: 'eventTwo', date: '2020-08-27T00:00:00+00:00' }, { log_type: 'eventOne', date: '2020-08-27T00:00:00+00:00' }, ] </code></pre> <p>For charting purposes, I need group all these logs by their <code>log_types</code>. Then I need to take all the logs for each log type, and group them by date. These will be formatted where <code>t</code> is the date and <code>y</code> is the count of that date occurring. Like this:</p> <pre><code>{ eventOne: [ { x: 2020-08-21T04:00:00.000Z, y: 0 }, { x: 2020-08-22T04:00:00.000Z, y: 6 }, { x: 2020-08-23T04:00:00.000Z, y: 0 }, { x: 2020-08-24T04:00:00.000Z, y: 16 }, { x: 2020-08-25T04:00:00.000Z, y: 0 }, { x: 2020-08-26T04:00:00.000Z, y: 0 }, { x: 2020-08-27T04:00:00.000Z, y: 22 } ], eventTwo: [ { x: 2020-08-21T04:00:00.000Z, y: 0 }, { x: 2020-08-22T04:00:00.000Z, y: 0 }, { x: 2020-08-23T04:00:00.000Z, y: 1 }, { x: 2020-08-24T04:00:00.000Z, y: 0 }, { x: 2020-08-25T04:00:00.000Z, y: 0 }, { x: 2020-08-26T04:00:00.000Z, y: 0 }, { x: 2020-08-27T04:00:00.000Z, y: 17 } ] } </code></pre> <p>So in plain english the goal is to get the number of events that were logged for each day, for each log type.</p> <p>I've accomplished this, but it is a series of mangled lodash functions to where any sense of readability or efficiency has gone out the window.</p> <pre><code>// First group by log_type const logTypes = _.groupBy(logs, 'log_type'); const mappedLogs = {}; // Iterate through each log type _.forOwn(logTypes, (value, key) =&gt; { const logDates = _.chain(value) // For each log type, group by date .groupBy('date') // Then map each log to the correct format .map((logValue, logKey) =&gt; ({ t: logKey, y: logValue.length })) .value(); // Once we get the final mapped date values, assign them to the final object mappedLogs[key] = logDates; }); </code></pre> <p>I'm really hoping to find a way to do this more efficiently, I'm having trouble determining the efficiency of this current algorithm but I know the initial <code>_groupBy</code> touches each log <code>O(n)</code>, the second <code>_forOwn</code> plus <code>_groupBy</code> I believe is another <code>O(n)</code>, then the final mapping to correct format would own another <code>O(n)</code>.</p> <p>This is an application where there could be many thousands of logs so that is not an ideal efficiency.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-28T01:46:29.753", "Id": "486857", "Score": "0", "body": "I’m not sure I really understand. What you do is indeed O(n). You can’t hope to do better than this as clearly you need to go through every element of your array. But maybe you are concerned that you are making multiple large objects and are looping over the array effectively three times. Which is fair enough, and well yes you can do it all in one loop and just making one object. Just go through the array and at each element add the appropriate thing and you have already had something of that type and date increment the counter. I don’t think lodash has a neat function which generalises this." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-29T20:42:53.983", "Id": "487067", "Score": "0", "body": "Why is your example output not derived from your example input? That's going to confuse people trying to help you. It also puts the burden of coming up with mock data on others." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-29T20:58:48.443", "Id": "487070", "Score": "0", "body": "It's also confusing how your example output could have objects with a `y` (count) value of zero." } ]
[ { "body": "<p>I don't see what lodash has to offer here. With modern JavaScript it can be written quite tersely thus:</p>\n<pre><code>const events = data.reduce((events, { log_type, date }) =&gt; {\n const event = (events[log_type] || (events[log_type] = []));\n const match = event.find(({ x }) =&gt; x == date);\n match ? match.y++ : event.push({ x: date, y: 1 });\n return events;\n}, { });\n</code></pre>\n<p>The first line inside the <code>.reduce</code> method creates the event array if it doesn't exist.</p>\n<p>The second line finds the element with a matching date.</p>\n<p>The third line, if a matching date was found, increments its <code>y</code> property. Else, it adds a new element with the date.</p>\n<p>For example:</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const data = [\n {\n log_type: 'eventOne',\n date: '2020-08-27T20:00:00+00:00'\n },\n {\n log_type: 'eventOne',\n date: '2020-08-27T20:00:00+00:00'\n },\n {\n log_type: 'eventTwo',\n date: '2020-08-27T00:00:00+00:00'\n },\n {\n log_type: 'eventTwo',\n date: '2020-08-27T00:00:00+00:00'\n },\n {\n log_type: 'eventTwo',\n date: '2020-08-27T40:00:00+00:00'\n },\n {\n log_type: 'eventOne',\n date: '2020-08-27T00:00:00+00:00'\n },\n];\n\nconst events = data.reduce((events, { log_type, date }) =&gt; {\n const event = (events[log_type] || (events[log_type] = []));\n const match = event.find(({ x }) =&gt; x == date);\n match ? match.y++ : event.push({ x: date, y: 1 });\n return events;\n}, { });\n\nconsole.log(events);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-29T20:56:17.140", "Id": "248637", "ParentId": "248525", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-27T23:31:00.667", "Id": "248525", "Score": "0", "Tags": [ "javascript", "performance", "ecmascript-6", "lodash.js" ], "Title": "Efficiently performing multiple nested grouping and mapping in Javascript" }
248525
<p>This is something I've done a few times, but I've found it to feel a bit error-prone with so many conditions, and am wondering if anyone can point me in the direction of a cleaner way. This is a PATCH route for editing a user. Super admin and admin users are both able to change other users (with some limitations) while other types of users can only edit themselves.</p> <pre><code>router.patch('/:userId', async (req, res) =&gt; { const patcher = (req as AuthRequest).user; const otherUser = await database.getUserById(req.params.userId); const requestedUpdate = req.body; // 404 if user is not found. if (!otherUser) { return sendCannotFind(res); } // Basic validation of requestedUpdate if (requestedUpdate.userType &amp;&amp; !isUserTypeValid(requestedUpdate.userType)) { return sendInvalidUserType(res); } if (patcher.userType === 'superAdmin') { // Super admin cannot demote self. if (otherUser.id === patcher.id &amp;&amp; requestedUpdate.userType) { return sendCannotSetUserType(res); } // Super admin cannot edit other super admins if (otherUser.userType === 'superAdmin' &amp;&amp; otherUser.id !== patcher.id) { return sendCannotEdit(res); } } else if (patcher.userType === 'admin') { // Admin cannot edit super admins if (otherUser.userType === 'superAdmin') { return sendCannotEdit(res); } // Admin cannot edit other admins if (otherUser.userType === 'admin' &amp;&amp; otherUser.id !== patcher.id) { return sendCannotEdit(res); } // Admin cannot promote or demote themselves if (otherUser.id === patcher.id &amp;&amp; requestedUpdate.userType) { return sendCannotSetUserType(res); } // Admin cannot promote anyone to admin or superAdmin if (requestedUpdate.userType === 'admin' || requestedUpdate.userType === 'superAdmin') { return sendCannotSetUserType(res); } } else { // Non-admins cannot edit anyone but themselves if (otherUser.id !== patcher.id) { return sendCannotEdit(res); } // Non-admins cannot promote or demote themselves if (requestedUpdate.userType &amp;&amp; requestedUpdate.userType !== otherUser.userType) { return sendCannotSetUserType(res); } } await doEdit(otherUser, requestedUpdate); return res.json(otherUser); }); <span class="math-container">```</span> </code></pre>
[]
[ { "body": "<p>I think I came up with a better and more declarative way using Joi schemas in nested dictionaries.</p>\n<p>The idea is that we first figure out these three things:</p>\n<ol>\n<li>Is the user editing themselves? (bool)</li>\n<li>What type of user is the editor? (admin, etc)</li>\n<li>What type of user is being edited? (admin, etc)</li>\n</ol>\n<p>And based on those three things, we can lookup the correct Joi schema to use.</p>\n<p>So the schema dictionary looks like this for the PATCH route:</p>\n<pre class=\"lang-js prettyprint-override\"><code>// No one is allowed to edit their own user type, everyone can edit their own name.\nconst selfEditSchemas: { [key in UserType]?: Joi.Schema } = {\n [UserType.superAdmin]: Joi.object({\n userType: Joi.forbidden(),\n name: Joi.string().pattern(/^[a-zA-Z0-9_\\-. ]{3,100}$/).optional(),\n }),\n [UserType.admin]: Joi.object({\n userType: Joi.forbidden(),\n name: Joi.string().pattern(/^[a-zA-Z0-9_\\-. ]{3,100}$/).optional(),\n }),\n [UserType.user]: Joi.object({\n userType: Joi.forbidden(),\n name: Joi.string().pattern(/^[a-zA-Z0-9_\\-. ]{3,100}$/).optional(),\n }),\n};\n\n// We only allow admins and super admins to edit others, and we use different schemas\n// depending on what type of user they are trying to edit.\nconst otherEditSchemas: { [key in UserType]: { [key in UserType]?: Joi.Schema } } = {\n [UserType.superAdmin]: {\n [UserType.admin]: Joi.object({ // (superAdmin can edit admins according to this schema)\n userType: Joi.string().valid(...Object.values(UserType)).optional(),\n name: Joi.string().pattern(/^[a-zA-Z0-9_\\-. ]{3,100}$/).optional(),\n }),\n [UserType.user]: Joi.object({ // (superAdmin can edit regular users according to this chema)\n userType: Joi.string().valid(...Object.values(UserType)).optional(),\n name: Joi.string().pattern(/^[a-zA-Z0-9_\\-. ]{3,100}$/).optional(),\n }),\n },\n [UserType.admin]: {\n [UserType.user]: Joi.object({ // (admin can edit regular users according to this schema)\n userType: Joi.forbidden(), // (admin cannot promote regular users)\n name: Joi.string().pattern(/^[a-zA-Z0-9_\\-. ]{3,100}$/).optional(),\n }),\n },\n [UserType.user]: {}, // (user is not allowed to edit anyone else)\n};\n</code></pre>\n<p>And now the logic for validating edits becomes a lot simpler and less error-prone IMO:</p>\n<pre class=\"lang-js prettyprint-override\"><code>function validateUserEdit(req: express.Request, res: express.Response, next: express.NextFunction) {\n const userReq = req as UserRequest;\n\n const isSelf = userReq.user.id === userReq.otherUser.id;\n const schema = isSelf\n ? selfEditSchemas[userReq.user.userType]\n : otherEditSchemas[userReq.user.userType][userReq.otherUser.userType];\n\n if (!schema) {\n return res.status(403).json({\n message: 'Not allowed to edit that user.',\n code: ErrorCodes.FORBIDDEN_TO_EDIT_USER,\n });\n }\n\n const validateRes = schema.validate(req.body, { stripUnknown: true });\n if (validateRes.error) {\n res.status(400).json({\n message: `Invalid arguments: ${validateRes.error}`,\n code: ErrorCodes.INVALID_ARGUMENTS,\n });\n } else {\n req.body = validateRes.value;\n next();\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-09-08T16:25:02.360", "Id": "249086", "ParentId": "248528", "Score": "0" } } ]
{ "AcceptedAnswerId": "249086", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-28T01:52:11.720", "Id": "248528", "Score": "2", "Tags": [ "javascript", "typescript", "express.js", "authorization" ], "Title": "Role based permissions in Express.js" }
248528
<p>I have a method which checks all of its surrounding squares and returns the number of bombs around it. But it's really long code and ugly, so can it be shorten?</p> <pre><code>final int MINE =10 for (int x = 0; x &lt; counts.length; x++) { for (int y = 0; y &lt; counts[0].length; y++) { if (counts[x][y] != MINE) { int Minesearch = 0; if (x &gt; 0 &amp;&amp; y &gt; 0 &amp;&amp; counts[x-1][y-1] == MINE) {//up left Minesearch++; } if (y &gt; 0 &amp;&amp; counts[x][y-1] == MINE) {//up Minesearch++; } if (x &lt; counts.length - 1 &amp;&amp; y &gt; 0 &amp;&amp; counts[x+1][y-1] == MINE) {//up right Minesearch++; } if (x &gt; 0 &amp;&amp; counts[x-1][y] == MINE) {//left Minesearch++; } if (x &lt; counts.length - 1 &amp;&amp; counts[x+1][y] == MINE) {//right Minesearch++; } if (x &gt; 0 &amp;&amp; y &lt; counts[0].length - 1 &amp;&amp; counts[x-1][y+1] == MINE) {//down left Minesearch++; } if (y &lt; counts[0].length - 1 &amp;&amp; counts[x][y+1] == MINE) {//down Minesearch++; } if (x &lt; counts.length - 1 &amp;&amp; y &lt; counts[0].length - 1 &amp;&amp; counts[x+1][y+1] == MINE) {//down right Minesearch++; } counts[x][y] = Minesearch; } } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-28T16:57:36.843", "Id": "486944", "Score": "0", "body": "What is ```MINE``` initialized to, or what is its value if it is a constant?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-29T14:34:29.853", "Id": "487037", "Score": "0", "body": "@bob final int MINE = 10; This is it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-31T13:05:52.273", "Id": "487243", "Score": "0", "body": "It might be helpful to include that info in the question." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-09-01T16:49:47.420", "Id": "487438", "Score": "1", "body": "@bob Thanks I'll add MINE initialized" } ]
[ { "body": "<p>It can be shortened and &quot;beautified&quot; by refactoring the bounds cyhecking and mine checking into internal method:</p>\n<pre><code>private boolean isWithinBounds(int x, int y) {\n return x &gt;= 0 &amp;&amp; y &gt;= 0 &amp;&amp; x &lt; width &amp;&amp; y &lt; height;\n}\n\nprivate boolean isMine(int x, int y) {\n return field[x][y] == MINE;\n}\n</code></pre>\n<p>Then the mine count becomes trivial (we can assume that the center of the 3x3 square does not have a mine, otherwise the player would have exploded and ended the game):</p>\n<pre><code>for (int x1 = x - 1; x1 &lt;= x + 1; x1++) {\n for (int y1 = y - 1; y1 &lt;= y + 1; y1++) {\n if (isWithinBounds(x1, y1) &amp;&amp; isMine(x1, y1) {\n mineCount++;\n }\n }\n}\n</code></pre>\n<p>What we have done is breaking code into methods, each of which implement a small and well defined function. Because each method does exactly one thing, they become easier to understand, maintain and test.</p>\n<p>You should check <a href=\"https://www.oracle.com/java/technologies/javase/codeconventions-namingconventions.html\" rel=\"noreferrer\">Java naming conventions</a>. Variable names should be in <code>camelCase</code>, <code>startingWithSmallLetter</code>.</p>\n<p>Variable and method names should describe the reason why the code exists. E.g. <code>mineSearch</code> is confusing as the variable does not search mines, it just keeps count of them. Thus <code>mineCount</code> is a better alternative.</p>\n<p><code>Counts</code> is also confusing as it contains a value named <code>MINE</code> which obviously is a marker for a cell containing mine but it also contains the surrounding mine counts. I did a minesweeper clone (or actually a minesweeper solver) once and I used an array containing Cell-objects. The Cell object provided methods for querying the status of the cell (stepped on, flagged, unknown) and the number of surrounding mines if it had been stepped on.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-28T06:15:18.487", "Id": "486870", "Score": "2", "body": "Why `isWithinBounds(-1, -1)` should return `true`? It will make `isMine` fail. The condition should be `x >= 0 && y >= 0 && x < mines.length && y < mines[0].length`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-28T06:26:30.677", "Id": "486873", "Score": "0", "body": "Good point @Marc. I had the condition exactly backwards!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-28T17:18:36.277", "Id": "486945", "Score": "0", "body": "Also, I would normally write `x >= 0 && x < width && y >= 0 && y < height`. The same variable together. However, that's a really minor point." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-28T20:05:35.940", "Id": "486965", "Score": "0", "body": "Why `x1`/`y1`? Also, that does check the current field, too, if I'm not mistaken." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-31T05:10:46.477", "Id": "487181", "Score": "0", "body": "@Bobby The assumption is that mine count is performed only after the user has stepped on the current field. If there is a mine, the game ends and a mine count is not needed. :)" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-28T05:28:43.013", "Id": "248531", "ParentId": "248530", "Score": "12" } }, { "body": "<p>While the Answer of @TorbenPutkonen is correct it is a <em>procedural</em> approach to the problem.</p>\n<p>There is nothing wrong with <em>procedural</em> approaches as such, but since Java is a <em>object oriented</em> language we might look out for OO-approaches instead...</p>\n<p>I would extract the neighbor check into an <code>enum</code> like this:</p>\n<pre><code>enum Direction {\n NORTH{\n boolean isBomb(inx x, int y, boolean[] field){\n if(0 &lt; x)\n return BOMB == field(x-1, y);\n else\n return false;\n }\n },\n NORTH_WEST{\n boolean isBomb(inx x, int y, boolean[] field){\n if(0 &lt; x &amp;&amp; 0 &lt; y)\n return BOMB == field(x-1, y-1);\n else\n return false;\n }\n },\n SOUTH{\n boolean isBomb(inx x, int y, boolean[] field){\n if(field.length-1 &gt; x)\n return BOMB == field(x+1, y);\n else\n return false;\n }\n },\n SOUTH_EAST{\n boolean isBomb(inx x, int y, boolean[] field){\n if(field.length-1 &gt; x &amp;&amp; field[0].length-1&gt;y)\n return BOMB == field(x+1, y+1);\n else\n return false;\n }\n }\n // other directions following same pattern\n\n abstract boolean isBomb(inx x, int y, boolean[] field);\n}\n</code></pre>\n<p>The benefit is that this enum could live in its own file and has a very limited responsibility. That means it is easy to understand what is does, isn't it?</p>\n<p>In your calculation method you can simply iterate over the <code>enum</code> constants like this:</p>\n<pre><code>for (int x = 0; x &lt; counts.length; x++) {\n for (int y = 0; y &lt; counts[0].length; y++) {\n int mineCount =0;\n for(Direction direction : Direction.values()) {\n if (direction.isBomb(x, y, counts) ) {\n mineCount++;\n }\n }\n }\n}\n</code></pre>\n<hr />\n<p>As a next step I'd apply the &quot;tell, don't ask&quot; principle by changing the method signature:</p>\n<pre><code>abstract int getBombValueOf(inx x, int y, boolean[] field);\n</code></pre>\n<p>the implementation in the <code>enum</code> would change like this:</p>\n<pre><code> int getBombValueOf(inx x, int y, boolean[] field){\n if(0 &lt; x &amp;&amp; BOMB == field(x-1, y))\n return 1;\n else\n return 0;\n },\n</code></pre>\n<p>That could be simplified to the &quot;elvis operator&quot;:</p>\n<pre><code> int getBombValueOf(inx x, int y, boolean[] field){\n return (0 &lt; x &amp;&amp; BOMB == field(x-1, y))\n ? 1 \n : 0;\n },\n</code></pre>\n<p>and the usage would change to this:</p>\n<pre><code>for (int x = 0; x &lt; counts.length; x++) {\n for (int y = 0; y &lt; counts[0].length; y++) {\n int mineCount =0;\n for(Direction direction : Direction.values()) {\n mineCount += \n direction.getBombValueOf(x, y, counts) );\n }\n }\n}\n</code></pre>\n<hr />\n<p>We could achief the same (exept moving the neighbor calculation to another file) by using a <code>FunctionalInterface</code> and a simple collection:</p>\n<pre><code>@FunctionalInterface\ninterface Direction{\n int getBombValueOf(inx x, int y, boolean[] field);\n}\n\nprivate final Collection&lt;Direction&gt; directions = new HashSet&lt;&gt;();\n\n// in constructor\n directions.add(new Direction() { // old style anonymous inner class\n int getBombValueOf(inx x, int y, boolean[] field){\n return (0 &lt; x &amp;&amp; BOMB == field(x-1, y))\n ? 1 \n : 0; \n }\n };\n directions.add((x, y, field)-&gt; { // Java8 Lambda \n return (0 &lt; x &amp;&amp; 0 &lt; y &amp;&amp;BOMB == field(x-1, y-1))\n ? 1 \n : 0;\n };\n // more following same pattern\n\n// in your method\n for (int x = 0; x &lt; counts.length; x++) {\n for (int y = 0; y &lt; counts[0].length; y++) {\n int mineCount =0;\n for(Direction direction : directions) {\n mineCount += \n direction.getBombValueOf(x, y, counts) );\n }\n }\n }\n</code></pre>\n<hr />\n<p>Of cause we could make much more benefit from OO principles if the game field would not be an <em>array of primitives</em> but a <em>Collection of Objects</em>. But that might be stuff for another answer... ;o)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-31T05:16:48.390", "Id": "487183", "Score": "0", "body": "Instead of copy-pasting the code in the enums, you could define an xy-offset for each direction and reuse the same code in each value. Personally I don't advocate for adding any functionality to enums. They're intended to be a tool for enumerating value sets and making them a container for code violates that intention and as such, always surprises the user. There are always better ways to implement the functionality." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-09-02T13:02:05.180", "Id": "487528", "Score": "0", "body": "@TorbenPutkonen `enum`s are *full featured* classes. Classes are used to provide different behavior. So I don't see any reason to use `enum`s as dump constants only, especially if in turn they are used to introduce *branching* by use of a `switch` block. But I agree that the code in the `enum`s could be cleaned a little more... And just vor the records: my second approach does what you suggest." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-29T13:29:23.773", "Id": "248619", "ParentId": "248530", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-28T02:07:58.733", "Id": "248530", "Score": "7", "Tags": [ "java", "minesweeper" ], "Title": "Minesweeper BombCounts" }
248530
<p>I have a bunch of JSON records, each record with a varying degree of completeness. In other words, record A may contain keys not in record B, and vice-versa. To get a better understanding of the data within, I have created a function to take N number of records and merge them together, creating one single frankenstein record containing all keys and a single value for each key.</p> <pre><code>import sys import json def frankenstein(out, in_dict, key=None): if isinstance(in_dict, dict): for k, v in in_dict.items(): if isinstance(in_dict[k], list) and v: out.setdefault(k, []) frankenstein(out[k], v, k) elif isinstance(in_dict[k], dict) and v: out.setdefault(k, {}) frankenstein(out[k], v, k) elif v: out[k] = v elif isinstance(in_dict, list): s = {} for item in in_dict: if isinstance(item, dict): frankenstein(s, item) elif not out: out.append(item) if s: if not out: out.append(s) else: frankenstein(s, out[0]) out[0] = s if __name__ == '__main__': l = [ { &quot;name&quot;: &quot;foo bar&quot;, &quot;experience&quot;: [ { &quot;company&quot;: { &quot;name&quot;: &quot;oracle&quot;, &quot;hq&quot;: &quot;123 main st&quot;, &quot;size&quot;: 100 }, &quot;function&quot;: [ { &quot;name&quot;: &quot;go getter&quot; } ], &quot;location&quot;: { &quot;doubleday&quot;: &quot;publisher&quot; }, &quot;animal&quot;: &quot;horse&quot; } ], &quot;skills&quot;: [&quot;programming&quot;, &quot;eating&quot;] }, { &quot;name&quot;: &quot;poo dar&quot;, &quot;experience&quot;: [ { &quot;company&quot;: { &quot;name&quot;: &quot;microsoft&quot;, &quot;url&quot;: &quot;foo.bar/com&quot; }, &quot;function&quot;: [ { &quot;name&quot;: &quot;bread&quot;, &quot;level&quot;: &quot;really high&quot; } ], &quot;solitary&quot;: { &quot;fat&quot;: &quot;cat&quot; }, &quot;health&quot;: &quot;no good&quot; } ], &quot;skills&quot;: [&quot;igz&quot;] }, { &quot;name&quot;: &quot;poo mar&quot;, &quot;experience&quot;: [ { &quot;function&quot;: [ { &quot;zoo&quot;: &quot;creature&quot; } ], &quot;location&quot;: { &quot;taste&quot;: &quot;food&quot; }, &quot;ping&quot;: { &quot;pong&quot;: &quot;bong&quot; } } ], &quot;skills&quot;: [&quot;woots own&quot;] } ] out = {} for item in l: frankenstein(out, item) print(json.dumps(out, indent=4)) </code></pre> <h3>This is the output from the code:</h3> <pre><code>{ &quot;name&quot;: &quot;poo mar&quot;, &quot;experience&quot;: [ { &quot;function&quot;: [ { &quot;name&quot;: &quot;bread&quot;, &quot;level&quot;: &quot;really high&quot;, &quot;zoo&quot;: &quot;creature&quot; } ], &quot;location&quot;: { &quot;taste&quot;: &quot;food&quot;, &quot;doubleday&quot;: &quot;publisher&quot; }, &quot;ping&quot;: { &quot;pong&quot;: &quot;bong&quot; }, &quot;company&quot;: { &quot;name&quot;: &quot;oracle&quot;, &quot;url&quot;: &quot;foo.bar/com&quot;, &quot;hq&quot;: &quot;123 main st&quot;, &quot;size&quot;: 100 }, &quot;solitary&quot;: { &quot;fat&quot;: &quot;cat&quot; }, &quot;health&quot;: &quot;no good&quot;, &quot;animal&quot;: &quot;horse&quot; } ], &quot;skills&quot;: [ &quot;programming&quot; ] } </code></pre> <p>I've tested the function and it does work. What I'd like is some feedback with regards to the code. Am I doing this in the most efficient way possible? Are there better ways to do it?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-28T11:04:11.953", "Id": "486897", "Score": "0", "body": "This question is probably answered by this https://stackoverflow.com/questions/38987/how-do-i-merge-two-dictionaries-in-a-single-expression-in-python-taking-union-o" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-28T11:13:59.033", "Id": "486899", "Score": "5", "body": "@user985366 None of the answers in the linked question on SO cover a deep merge, and none of them deal with nested lists of dicts like this code. Beyond that, I don't believe this question is asking how to do it, since they obviously achieved their desired goal; but rather, it's asking for a code review on their code, which seems to be the obvious intention of this community." } ]
[ { "body": "<p>The <code>key</code> parameter to <code>frankenstein()</code> does not appear to be used anywhere and can be eliminated.</p>\n<p>Use blank lines to split the code up into smaller logical chunks. It aides reading and understanding the code.</p>\n<p><code>in_dict</code> is a misleading name, because it can be a list, dict, or something else altogether.</p>\n<p>In the <code>for k, v in in_dict.items():</code> loop, <code>in_dict[k]</code> and <code>v</code> are the same thing, <code>v</code> is tested 3 times, and the return value of <code>setdefault()</code> is discarded then looked up on the next line. It can be rewritten it like so:</p>\n<pre><code> for k, v in in_dict.items():\n if not v:\n continue\n\n if isinstance(v, (list, dict)):\n out_k = out.setdefault(k, v.__class__())\n frankenstein(out_k, v)\n\n else:\n out[k] = v\n</code></pre>\n<p>The logic for handling <code>lists</code> seems convoluted. For example, it looks like <code>s</code> can get updated each time through the loop and also appended to <code>out[k]</code>. The question doesn't clearly state the rules for combining things, so maybe it's correct. A comment or doc-string explaining the purpose of the function and the rules for merging values would be helpful.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-31T05:16:57.837", "Id": "248683", "ParentId": "248538", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-28T08:50:48.473", "Id": "248538", "Score": "5", "Tags": [ "python", "python-3.x", "recursion", "hash-map" ], "Title": "python3 function to merge dictionaries" }
248538
<p>I'm trying to automate the CSS I write by developing SASS files I can reuse. I want to create a utility SASS file for padding and came up with the following.</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-html lang-html prettyprint-override"><code>// Variables to set the amount of padding $_1: 0.25rem !default; $_2: 0.5rem !default; $_3: 1rem !default; $_4: 1.5rem !default; $_5: 3rem !default; // Various Padding mixins // Padding on the Y-axis @mixin py($unit) { padding-top: $unit !important; padding-bottom: $unit !important; } // Padding on the X-axis @mixin px($unit) { padding-left: $unit !important; padding-right: $unit !important; } // Padding all around @mixin p($unit) { padding: $unit !important; } // Padding on top @mixin pt($unit) { padding-top: $unit !important; } // Padding on the right @mixin pr($unit) { padding-right: $unit !important; } // Padding on the bottom @mixin pb($unit) { padding-bottom: $unit !important; } // Padding on the left @mixin pl($unit) { padding-left: $unit !important; }</code></pre> </div> </div> </p> <p>Does it make any sense though? Im not too sure. Does it mean I can use it like this? If I want to set padding of a nav element?</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-html lang-html prettyprint-override"><code>nav ul { @include py(1); }</code></pre> </div> </div> </p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-28T09:27:26.650", "Id": "486891", "Score": "1", "body": "Does it do what you expect it to do?" } ]
[ { "body": "<p>No, it does not make sense; the goal of SASS is to make things dry and maintainable. There's no point in writing:</p>\n<pre><code>nav ul {\n @include py(1);\n}\n</code></pre>\n<p>instead of:</p>\n<pre><code>nav ul {\n padding-top: 1rem;\n padding-bottom: 1rem;\n}\n</code></pre>\n<p>or:</p>\n<pre><code>nav ul {\n padding: 1rem 0;\n}\n</code></pre>\n<p>With your mixing you are not writing less code and you make it sightly less readable.</p>\n<p>Furthermore you should note that the !important keyword should be avoided as much as possible, since it's very hard to override and, in most of the cases, that's not what you want.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-28T12:08:04.637", "Id": "248544", "ParentId": "248539", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-28T09:15:53.157", "Id": "248539", "Score": "-1", "Tags": [ "sass" ], "Title": "Does this SASS make sense?" }
248539
<p>I still write login system in Go(Golang) using cookies.But my system is still not secure enough.Can you review my code and provide some suggestions on how to improve the security?Previous <a href="https://codereview.stackexchange.com/questions/248362/cookie-authorization-golang">question</a>.</p> <p>Main file:</p> <pre><code>package main import ( &quot;crypto/rand&quot; &quot;encoding/base64&quot; &quot;fmt&quot; &quot;golang.org/x/crypto/bcrypt&quot; &quot;html/template&quot; &quot;log&quot; &quot;net/http&quot; &quot;strings&quot; &quot;time&quot; ) var ( t *template.Template ) func init() { t, _ = template.ParseFiles(&quot;main.html&quot;,&quot;signup.html&quot;,&quot;signin.html&quot;) } type User struct { Login, Email string } func genToken(n int) string { b := make([]byte, n) if _, err := rand.Read(b);err != nil{ log.Fatal(err) } return base64.URLEncoding.EncodeToString(b) } func setCookie(w http.ResponseWriter, name, value string,d int) { cookie := http.Cookie{ Name: name, Value: value, } if d != 0{ expires := time.Now().AddDate(0,0,d) cookie.Expires = expires } http.SetCookie(w, &amp;cookie) } func getCookie(r *http.Request, name string) string { c, err := r.Cookie(name) if err != nil { return &quot;&quot; } return c.Value } func deleteCookie(w http.ResponseWriter,name string){ cookie := http.Cookie{ Name: name, MaxAge: -1, } http.SetCookie(w, &amp;cookie) } func signup(w http.ResponseWriter, r *http.Request) { switch r.Method { case &quot;GET&quot;: t.ExecuteTemplate(w,&quot;signup.html&quot;,nil) case &quot;POST&quot;: r.ParseForm() data := r.Form var error string if data[&quot;login&quot;][0] == &quot;&quot;{ error = &quot;Login can't be empty&quot; } else if data[&quot;email&quot;][0] == &quot;&quot;{ error = &quot;Email can't be empty&quot; } else if data[&quot;password&quot;][0] == &quot;&quot;{ error = &quot;Password cant't be empty&quot; } else if len(data[&quot;login&quot;][0]) &lt; 4{ error = &quot;Login must be at least 4 characters&quot; } else if DB.checkLogin(data[&quot;login&quot;][0]){ error = &quot;User with such login already exists&quot; } else if !strings.ContainsRune(data[&quot;email&quot;][0],'@'){ error = &quot;Email must contain @&quot; } else if DB.checkEmail(data[&quot;email&quot;][0]) { error = &quot;User with such email already exists&quot; } else if len(data[&quot;password&quot;][0]) &lt; 8{ error = &quot;Password must be at least 8 characters&quot; } else if data[&quot;password2&quot;][0] != data[&quot;password&quot;][0]{ error = &quot;Passwords don't match&quot; } if error != &quot;&quot;{ values :=&amp;User{} values.Login = data[&quot;login&quot;][0] values.Email = data[&quot;email&quot;][0] t, err := template.ParseFiles(&quot;signup.html&quot;) if err != nil{ http.Error(w,&quot;Internal server error&quot;,500) } t.Execute(w,values) fmt.Fprintln(w,&quot;&lt;hr&gt;&lt;span style='color:red;'&gt;&quot; + error + &quot;&lt;/span&gt;&quot;) } else { hashedPassword, err := bcrypt.GenerateFromPassword([]byte(data[&quot;password&quot;][0]),10) if err != nil{ http.Error(w,&quot;Internal server error&quot;,500) } DB.newUser(data[&quot;login&quot;][0],data[&quot;email&quot;][0],string(hashedPassword)) http.Redirect(w,r,&quot;/login&quot;,http.StatusSeeOther) } } } func signin(w http.ResponseWriter, r *http.Request) { switch r.Method { case &quot;GET&quot;: t.ExecuteTemplate(w,&quot;signin.html&quot;,nil) case &quot;POST&quot;: r.ParseForm() data := r.Form var error string if !DB.checkLogin(data[&quot;login&quot;][0]){ error = &quot;User with such login doesn't exists&quot; } else { if !DB.checkPassword(data[&quot;login&quot;][0],data[&quot;password&quot;][0]){ error = &quot;Wrong password&quot; } } if error != &quot;&quot;{ values :=&amp;User{} values.Login = data[&quot;login&quot;][0] t, err := template.ParseFiles(&quot;signin.html&quot;) if err != nil{ http.Error(w,&quot;Internal server error&quot;,http.StatusInternalServerError) } t.Execute(w,values) fmt.Fprintln(w,&quot;&lt;hr&gt;&lt;span style='color:red;'&gt;&quot; + error + &quot;&lt;/span&gt;&quot;) } else { expiresAfter := 0 if r.FormValue(&quot;remember&quot;) == &quot;1&quot;{ expiresAfter = 30 } token := genToken(32) setCookie(w,&quot;login&quot;,data[&quot;login&quot;][0],expiresAfter) setCookie(w,&quot;session_token&quot;,token,expiresAfter) DB.newSession(data[&quot;login&quot;][0],token) http.Redirect(w,r,&quot;/&quot;,http.StatusSeeOther) } } } func mainPage(w http.ResponseWriter, r *http.Request) { login := getCookie(r,&quot;login&quot;) token := getCookie(r,&quot;session_token&quot;) if !DB.checkToken(login,token){ http.Redirect(w,r,&quot;/login&quot;,http.StatusSeeOther) } user := DB.getUser(login) t.ExecuteTemplate(w,&quot;main.html&quot;,user) } func logout(w http.ResponseWriter,r *http.Request){ login := getCookie(r,&quot;login&quot;) token := getCookie(r,&quot;session_token&quot;) deleteCookie(w,&quot;login&quot;) deleteCookie(w,&quot;session_token&quot;) DB.deleteSession(login,token) http.Redirect(w,r,&quot;/login&quot;,http.StatusSeeOther) } func main() { http.HandleFunc(&quot;/register&quot;, signup) http.HandleFunc(&quot;/login&quot;, signin) http.HandleFunc(&quot;/&quot;, mainPage) http.HandleFunc(&quot;/logout&quot;,logout) http.ListenAndServe(&quot;:8080&quot;, nil) } </code></pre> <p>Database file:</p> <pre><code>package main import ( &quot;database/sql&quot; &quot;golang.org/x/crypto/bcrypt&quot; &quot;log&quot; _ &quot;github.com/go-sql-driver/mysql&quot; ) var DB = newDB(&quot;root:root574@/signin&quot;) type db struct { DB *sql.DB } func newDB(name string) *db { conn, err := sql.Open(&quot;mysql&quot;, name) if err != nil { log.Fatal(err) } if err = conn.Ping(); err != nil { log.Fatal(err) } return &amp;db{DB: conn} } func (db db) newUser(login, email, password string) { db.DB.Exec(&quot;INSERT INTO users(login,email,password) VALUES (?,?,?)&quot;, login, email, password) } func (db db) newSession(login, token string) { db.DB.Exec(&quot;INSERT INTO sessions(login,token) VALUES (?,?)&quot;,login,token) } func (db db) deleteSession(login, token string) { db.DB.Exec(&quot;DELETE FROM sessions WHERE login = ? and token = ?&quot;,login,token) } func (db db) checkLogin(login string) bool { var rows, _ = db.DB.Query(&quot;SELECT id FROM users WHERE login = ?&quot;, login) if rows.Next() { return true } rows.Close() return false } func (db db) checkEmail(email string) bool { var rows, _ = db.DB.Query(&quot;SELECT id FROM users WHERE email = ?&quot;, email) if rows.Next() { return true } rows.Close() return false } func (db db) checkPassword(login, password string) bool{ var rows, _ = db.DB.Query(&quot;SELECT password FROM users WHERE login = ?&quot;, login) var dbpassword string rows.Next() rows.Scan(&amp;dbpassword) rows.Close() if bcrypt.CompareHashAndPassword([]byte(dbpassword),[]byte(password)) != nil{ return false } return true } func (db db) checkToken(login, token string) bool { var rows, _ = db.DB.Query(&quot;SELECT token FROM sessions WHERE login = ? and token = ?&quot;,login,token) if rows.Next(){ return true } rows.Close() return false } func (db db) getUser(login string) *User { var rows, _ = db.DB.Query(&quot;select email FROM users WHERE login = ?&quot;,login) user := &amp;User{} rows.Next() rows.Scan(&amp;user.Email) rows.Close() user.Login = login return user } </code></pre> <p>Database users table:</p> <pre><code>+----------+--------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +----------+--------------+------+-----+---------+----------------+ | id | int | NO | PRI | NULL | auto_increment | | login | varchar(255) | YES | | NULL | | | email | varchar(255) | YES | | NULL | | | password | varchar(255) | YES | | NULL | | +----------+--------------+------+-----+---------+----------------+ </code></pre> <p>Database sessions table:</p> <pre><code>+-------+--------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +-------+--------------+------+-----+---------+-------+ | login | varchar(255) | YES | | NULL | | | token | varchar(44) | YES | | NULL | | +-------+--------------+------+-----+---------+-------+ </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-09-12T07:36:04.200", "Id": "488493", "Score": "0", "body": "What are your concerns? I also don't quite understand what is \"cookie-based\" about your auth, looks like vanilla session-based auth to me." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-09-13T07:57:33.610", "Id": "488587", "Score": "0", "body": "@D.SM I think it looks like [this](https://astaxie.gitbooks.io/build-web-application-with-golang/content/en/images/6.1.cookie2.png?raw=true),isn't it?.Can you provide some suggestion on how to improve the security?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-09-14T09:05:07.423", "Id": "488694", "Score": "0", "body": "Cookies are used to implement sessions. Your auth uses sessions. You didn't say what your concerns were." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-09-14T12:08:44.593", "Id": "488711", "Score": "0", "body": "@D.SM I'm concerned about security" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-28T09:31:32.550", "Id": "248540", "Score": "5", "Tags": [ "go", "authentication", "authorization" ], "Title": "Security of cookie based authorization Golang" }
248540
<p>I have code that basically is the same, but depending on the number of arguments you provide (up to 5), it will operate with them in a very repetitive way. I have the feeling that this can be optimized in some way, since maintaining and creating all the overloads by hand is a tedious and error-prone task.</p> <p>The code is 5 versions (overloads) of the <code>Operate</code> method. As you can see, it increasingly deal with 2, 3, 4 and 5 arguments (each one is of a given type), so it can adapt from 2 to 5 type arguments.</p> <pre><code>public static Either&lt;ErrorList, TResult&gt; Operate&lt;T1, T2, TResult&gt;(Either&lt;ErrorList, T1&gt; a, Either&lt;ErrorList, T2&gt; b, Func&lt;T1, T2, Either&lt;ErrorList, TResult&gt;&gt; onSuccess) { var success = from av in a.RightValue from bv in b.RightValue select onSuccess(av, bv); var errorList = new[] { a.LeftValue, b.LeftValue, } .SelectMany(x =&gt; x.ToEnumerable()) .Aggregate((x, y) =&gt; new ErrorList(x.Concat(y))); return success.ValueOr(() =&gt; errorList); } public static Either&lt;ErrorList, TResult&gt; Operate&lt;T1, T2, T3, TResult&gt;(Either&lt;ErrorList, T1&gt; a, Either&lt;ErrorList, T2&gt; b, Either&lt;ErrorList, T3&gt; c, Func&lt;T1, T2, T3, Either&lt;ErrorList, TResult&gt;&gt; onSuccess) { var success = from av in a.RightValue from bv in b.RightValue from cv in c.RightValue select onSuccess(av, bv, cv); var errorList = new[] { a.LeftValue, b.LeftValue, c.LeftValue, } .SelectMany(x =&gt; x.ToEnumerable()) .Aggregate((x, y) =&gt; new ErrorList(x.Concat(y))); return success.ValueOr(() =&gt; errorList); } public static Either&lt;ErrorList, TResult&gt; Operate&lt;T1, T2, T3, T4, TResult&gt;(Either&lt;ErrorList, T1&gt; a, Either&lt;ErrorList, T2&gt; b, Either&lt;ErrorList, T3&gt; c, Either&lt;ErrorList, T4&gt; d, Func&lt;T1, T2, T3, T4, Either&lt;ErrorList, TResult&gt;&gt; onSuccess) { var success = from av in a.RightValue from bv in b.RightValue from cv in c.RightValue from dv in d.RightValue select onSuccess(av, bv, cv, dv); var errorList = new[] { a.LeftValue, b.LeftValue, c.LeftValue, d.LeftValue, } .SelectMany(x =&gt; x.ToEnumerable()) .Aggregate((x, y) =&gt; new ErrorList(x.Concat(y))); return success.ValueOr(() =&gt; errorList); } public static Either&lt;ErrorList, TResult&gt; Operate&lt;T1, T2, T3, T4, T5, TResult&gt;( Either&lt;ErrorList, T1&gt; a, Either&lt;ErrorList, T2&gt; b, Either&lt;ErrorList, T3&gt; c, Either&lt;ErrorList, T4&gt; d, Either&lt;ErrorList, T5&gt; e, Func&lt;T1, T2, T3, T4, T5, Either&lt;ErrorList, TResult&gt;&gt; onSuccess) { var success = from av in a.RightValue from bv in b.RightValue from cv in c.RightValue from dv in d.RightValue from ev in e.RightValue select onSuccess(av, bv, cv, dv, ev); var errorList = new[] { a.LeftValue, b.LeftValue, c.LeftValue, d.LeftValue, e.LeftValue, } .SelectMany(x =&gt; x.ToEnumerable()) .Aggregate((x, y) =&gt; new ErrorList(x.Concat(y))); return success.ValueOr(() =&gt; errorList); } </code></pre> <p>Is there a better way to do this without repeating almost the same code? Imagine that I would like to create another overload for 6, 7, 8... arguments. It can be really tricky and sub-optimal.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-28T11:05:56.373", "Id": "486898", "Score": "1", "body": "You may use the (generic) [Template Method](https://sourcemaking.com/design_patterns/template_method) design pattern, to concentrate the repeated algorithmic parts in a base class." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-28T11:57:17.523", "Id": "486904", "Score": "2", "body": "I'd suggest you use a T4 template (.tt file) to generate the overloads. You can have a for loop from 2 up to the number of arguments you need and generate each overload. The T4 template itself might be a bit of work but I think it should be straightforward." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-28T13:42:43.557", "Id": "486910", "Score": "0", "body": "How do you use this code right now?" } ]
[ { "body": "<p>You can try to extract the common piece of code into a helper method:</p>\n<pre class=\"lang-cs prettyprint-override\"><code>private static Either&lt;ErrorList, TResult&gt; Operate&lt;TResult&gt;(ErrorList[] errorLists, Either&lt;ErrorList, TResult&gt; success)\n{\n var errorList = errorLists\n .SelectMany(x =&gt; x.ToEnumerable())\n .Aggregate((x, y) =&gt; new ErrorList(x.Concat(y)));\n\n return success.ValueOr(() =&gt; errorList);\n}\n</code></pre>\n<p>Then you can reduce the overloads' body only to calculate the helpers inputs:</p>\n<pre class=\"lang-cs prettyprint-override\"><code>public static Either&lt;ErrorList, TResult&gt; Operate&lt;T1, T2, T3, T4, T5, TResult&gt;(\n Either&lt;ErrorList, T1&gt; a, Either&lt;ErrorList, T2&gt; b, Either&lt;ErrorList, T3&gt; c, Either&lt;ErrorList, T4&gt; d, Either&lt;ErrorList, T5&gt; e,\n Func&lt;T1, T2, T3, T4, T5, Either&lt;ErrorList, TResult&gt;&gt; onSuccess)\n =&gt; Operate&lt;TResult&gt;(\n new [] { a.LeftValue, b.LeftValue, c.LeftValue, d.LeftValue, e.LeftValue },\n onSuccess(a.RightValue, b.RightValue, c.RightValue, d.RightValue, e.RightValue));\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-28T11:44:17.240", "Id": "248543", "ParentId": "248542", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-28T11:01:56.433", "Id": "248542", "Score": "3", "Tags": [ "c#", ".net", "generics", "overloading" ], "Title": "Different versions of the Operate method" }
248542
<p>I wanted to know If there was a way to make it more versatile or shorter/simpler. Here's the code:</p> <pre><code>// Take only std::byte parameter and return an unsigned integral constexpr auto bytes_to_uint(std::same_as&lt;std::byte&gt; auto... bytes) -&gt; std::unsigned_integral auto { constexpr auto N = sizeof...(bytes); // Integral types large enough to hold N bytes using types = std::tuple&lt; std::uint8_t, std::uint16_t, std::uint32_t, std::uint32_t, std::uint64_t, std::uint64_t, std::uint64_t, std::uint64_t &gt;; using result = std::tuple_element_t&lt;N, types&gt;; return [&amp;]&lt;std::size_t... S&gt;(std::index_sequence&lt;S...&gt;) { // Accumulate the part of the number using the bitwise or operator for each bytes return ((static_cast&lt;result&gt;(bytes) &lt;&lt; CHAR_BIT * (N - S - 1)) | ... ); }(std::make_index_sequence&lt;N&gt;{}); } </code></pre> <p>It is meant to be used like this:</p> <pre><code>bytes_to_uint(std::byte{0xaa}, std::byte{0xbb}); // std::uint16_t: 0xaabb bytes_to_uint( std::byte{0x11}, std::byte{0x22}, std::byte{0x33}, std::byte{0x44} ); // std::uint32_t: 0x11223344 </code></pre>
[]
[ { "body": "<p>The function signature strikes me as difficult to read, thanks to the constraint <code>std::same_as&lt;std::byte&gt; auto...</code> and the trailing &quot;return type&quot; <code>std::unsigned_integral auto</code>. I might rather write something like</p>\n<pre><code>constexpr auto bytes_to_uint(std::initializer_list&lt;std::byte&gt; bytes) {\n</code></pre>\n<p>...Ah, but then you couldn't use <code>bytes.size()</code> as a constant expression; I see.\nSo I'd think about writing an overload set, like this:</p>\n<pre><code>constexpr std::uint8_t bytes_to_uint(std::byte a) {\n return a;\n}\nconstexpr std::uint16_t bytes_to_uint(std::byte a, std::byte b) {\n return (a &lt;&lt; 8) | b;\n}\nconstexpr std::uint32_t bytes_to_uint(std::byte a, std::byte b, std::byte c, std::byte d) {\n return (a &lt;&lt; 24) | (b &lt;&lt; 16) | (c &lt;&lt; 8) | d;\n}\n</code></pre>\n<p>But I guess this is messy because you need 16 different overloads. You can't even use default function arguments, because you want <code>bytes_to_uint(a,b,c)</code> to be equal to <code>bytes_to_uint(0,a,b,c)</code> and not <code>bytes_to_uint(a,b,c,0)</code>. Of course you could still write</p>\n<pre><code>#define B std::byte\nconstexpr std::uint8_t bytes_to_uint(B a)\n { return bytes_to_uint(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,a); }\nconstexpr std::uint16_t bytes_to_uint(B a, B b)\n { return bytes_to_uint(0,0,0,0,0,0,0,0,0,0,0,0,0,0,a,b); }\nconstexpr std::uint32_t bytes_to_uint(B a, B b, B c)\n { return bytes_to_uint(0,0,0,0,0,0,0,0,0,0,0,0,0,a,b,c); }\nconstexpr std::uint32_t bytes_to_uint(B a, B b, B c, B d)\n { return bytes_to_uint(0,0,0,0,0,0,0,0,0,0,0,0,a,b,c,d); }\nconstexpr std::uint64_t bytes_to_uint(B a, B b, B c, B d, B e)\n { return bytes_to_uint(0,0,0,0,0,0,0,0,0,0,0,a,b,c,d,e); }\n[...22 more lines...]\n#undef B\n</code></pre>\n<p>but I bet you don't want to do that. Okay, let's stick with the templatey thing you did.</p>\n<hr />\n<pre><code>using result = std::tuple_element_t&lt;N, types&gt;;\n</code></pre>\n<p>I'd rather see this dependent typedef use <code>CamelCase</code> (like a template parameter) or <code>suffixedwith_type</code> (like an STL member typedef). Calling it <code>result</code> makes it look too much like a variable, and makes it hard to pick out the one place where you use it.</p>\n<p>Instead of spending 13 lines and a <code>&lt;tuple&gt;</code> dependency, I'd rather just do</p>\n<pre><code>using ResultType = std::conditional_t&lt;\n (N == 1), std::uint8_t, std::conditional_t&lt;\n (N == 2), std::uint16_t, std::conditional_t&lt;\n (N &lt;= 4), std::uint32_t, std::uint64_t&gt;&gt;&gt;;\n</code></pre>\n<p>Which reminds me, you need something like</p>\n<pre><code>static_assert(N &lt;= 16);\n</code></pre>\n<p>to stop you from trying to handle an argument list of 17 bytes or more.</p>\n<p>And I didn't even notice until I tried it in Godbolt, but, you've got an off-by-one bug here! You meant <code>tuple_element_t&lt;N-1, types&gt;</code>. Remember that indexing always starts at zero (everywhere except <code>&lt;regex&gt;</code>).</p>\n<hr />\n<p>If you don't like <code>conditional_t</code>, another option is to use plain old <code>if</code>s. Factor out the computation while it's still parameterized on <code>ResultType</code>, and then use an <code>if-else</code> chain to decide on the right type to plug in for <code>ResultType</code> later:</p>\n<pre><code>auto do_it = [&amp;]&lt;class ResultType, std::size_t... S&gt;(ResultType, std::index_sequence&lt;S...&gt;) {\n return ((static_cast&lt;ResultType&gt;(bytes) &lt;&lt; CHAR_BIT * (N - S - 1)) | ... );\n};\nif constexpr (N == 1) {\n return do_it(std::uint8_t{}, std::make_index_sequence&lt;N&gt;{});\n} else if constexpr (N == 2) {\n return do_it(std::uint16_t{}, std::make_index_sequence&lt;N&gt;{});\n} else if constexpr (N &lt;= 4) {\n return do_it(std::uint32_t{}, std::make_index_sequence&lt;N&gt;{});\n} else if constexpr (N &lt;= 8) {\n return do_it(std::uint64_t{}, std::make_index_sequence&lt;N&gt;{});\n}\n</code></pre>\n<hr />\n<p>Even better, permit the compiler to do the math at its preferred bit-width (which is 64 bits on all the desktop platforms <em>I</em> care about) and then truncate it at the end. This produces similar codegen and reads nicer yet:</p>\n<pre><code>std::uint64_t result = [&amp;]&lt;std::size_t... S&gt;( std::index_sequence&lt;S...&gt;) {\n return ((static_cast&lt;std::uint64_t&gt;(bytes) &lt;&lt; CHAR_BIT * (N - S - 1)) | ... );\n}(std::make_index_sequence&lt;N&gt;{});\nif constexpr (N == 1) {\n return std::uint8_t(result);\n} else if constexpr (N == 2) {\n return std::uint16_t(result);\n} else if constexpr (N &lt;= 4) {\n return std::uint32_t(result);\n} else {\n return std::uint64_t(result);\n}\n</code></pre>\n<hr />\n<p>You have another bug when <code>N == 1</code> (besides the off-by-one bug). When <code>N == 1</code>, the fold-expression has no <code>|</code> operations at all, and so it's just a <code>uint8_t</code> shifted by zero. That shift expression has type <code>int</code>. Which is not an unsigned integral type. So your return-type-constraint fails!</p>\n<p>This is just another reason to do all the math <em>first</em> in <code>uint64_t</code>, and then cast down to <code>uint8_t</code> right before you return, as shown in my last example above.</p>\n<p>Writing any test cases would have caught both this bug and the off-by-one bug. Test cases are always important! Especially when you're planning to put the code up for public review. (Or for review by coworkers, for that matter.)</p>\n<hr />\n<p>Finally, I recommend parentheses to clarify the precedence of <code>x &lt;&lt; CHAR_BIT * y</code>. In context it's obvious what you <em>expected</em> the precedence to be; but as a reader, I'm not sure you're right. Put the parentheses so that I don't have to think about it even for a second.</p>\n<p>However, in this context, that's a very minor point, because you clearly aren't expecting anybody to <em>read</em> the expression <code>((static_cast&lt;result&gt;(bytes) &lt;&lt; CHAR_BIT * (N - S - 1)) | ... )</code>. It's a &quot;trust me&quot; line of code.</p>\n<p>It's also silly to pretend that <code>CHAR_BIT</code> is relevant here. This code explodes spectacularly if <code>CHAR_BIT</code> is anything other than <code>8</code>. So just write <code>8</code>; and if you are <em>compelled</em> to work in a reference to <code>CHAR_BIT</code>, do so by writing</p>\n<pre><code>static_assert(CHAR_BIT == 8);\n</code></pre>\n<p>at the top of the function.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-09-01T14:09:28.010", "Id": "248763", "ParentId": "248549", "Score": "3" } } ]
{ "AcceptedAnswerId": "248763", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-28T14:35:30.753", "Id": "248549", "Score": "4", "Tags": [ "c++", "bitwise", "c++20" ], "Title": "Generically convert bytes to integers" }
248549
<p>I have a longer Macro has sub functions opening many different Workbooks, takes the data, and pastes into a Destination Workbook through <code>arrays and .value</code>. There are also a few functions to bring over title and data value information.</p> <p>However, the macro seems to get stuck for a few seconds every time a source Workbook is opened.<br /> Would you please review the code to see if it can be any more efficient?</p> <pre><code>Option Explicit Public Const TemplatePath As String = &quot;C:\Users\cday\OneDrive - udfinc.com\M6 Scorecard\Data Pulls\&quot; Dim WbKrogerScorecard As Workbook Dim SourceWBPath As String Dim Data As Variant Sub M6Scorecard_DataPaste() 'Turn Off Screen Updates Application.ScreenUpdating = False Application.DisplayAlerts = False Application.Calculation = xlCalculationManual Set WbKrogerScorecard = Workbooks(&quot;KROGER M6 SCORECARD TEMPLATE.xlsm&quot;) WeeklyDivision_DataPaste Combine_DataPaste StoreSelling_DataPaste 'Save File as Template File ActiveWorkbook.Save 'Turn on Screen Updates Application.ScreenUpdating = True Application.DisplayAlerts = True Application.Calculation = xlCalculationAutomatic End Sub Sub WeeklyDivision_DataPaste() Set WbKrogerScorecard = Workbooks(&quot;KROGER M6 SCORECARD TEMPLATE.xlsm&quot;) Dim WsWeeklyDiv As Worksheet Set WsWeeklyDiv = WbKrogerScorecard.Worksheets(&quot;Weekly Division&quot;) With WsWeeklyDiv .Range(&quot;A15:W&quot; &amp; .Cells(.Rows.Count, &quot;A&quot;).End(xlUp).Offset(1).Row).ClearContents End With SourceWBPath = TemplatePath &amp; &quot;Weekly Data.csv&quot; With Workbooks.Open(SourceWBPath) With .Worksheets(&quot;Weekly Data&quot;) Dim Data(3) As Variant 'Title Information Data(0) = .Range(&quot;A1:A12&quot;).Value 'Data Cells Data(1) = .Range(.Cells(.Rows.Count, &quot;A&quot;).End(xlUp), &quot;I17&quot;).Value Data(2) = .Range(&quot;J17:N17&quot;).Resize(UBound(Data(1))).Value Data(3) = .Range(&quot;O17:P17&quot;).Resize(UBound(Data(1))).Value End With .Close SaveChanges:=False End With With WsWeeklyDiv 'Move Title Information from &quot;Weekly Data.csv&quot; to WbKrogerScorecard.Worksheets(&quot;Weekly Division&quot;).Range(&quot;A1:A12&quot;) .Range(&quot;A1:A12&quot;).Value = Data(0) 'Move Data Cells from &quot;Weekly Data.csv&quot; to WbKrogerScorecard.Worksheets(&quot;Weekly Division&quot;) 'Cells &quot;A17:I17&quot; With .Cells(.Rows.Count, &quot;A&quot;).End(xlUp).Offset(1).Resize(UBound(Data(1))) .Resize(ColumnSize:=UBound(Data(1), 2)).Value = Data(1) End With 'Cells L15:P15 .Cells(.Rows.Count, &quot;L&quot;).End(xlUp).Offset(1).Resize(UBound(Data(2)), UBound(Data(2), 2)).Value = Data(2) 'Cells V15:W15 .Cells(.Rows.Count, &quot;V&quot;).End(xlUp).Offset(1).Resize(UBound(Data(3)), UBound(Data(3), 2)).Value = Data(3) End With End Sub Sub Combine_DataPaste() Dim WsCombined As Worksheet Set WsCombined = WbKrogerScorecard.Worksheets(&quot;COMBINED&quot;) With WsCombined .Range(&quot;A5:U&quot; &amp; .Cells(.Rows.Count, &quot;A&quot;).End(xlUp).Offset(1).Row).ClearContents End With CombineWorksheets WbKrogerScorecard, &quot;52 Wk Data.csv&quot;, 52 CombineWorksheets WbKrogerScorecard, &quot;26 Wk Data.csv&quot;, 26 CombineWorksheets WbKrogerScorecard, &quot;13 Wk Data.csv&quot;, 13 CombineWorksheets WbKrogerScorecard, &quot;4 Wk Data.csv&quot;, 4 CombineWorksheets WbKrogerScorecard, &quot;YTD Data.csv&quot;, 0 End Sub Private Sub CombineWorksheets(WbKrogerScorecard As Workbook, FileName As String, FileIndex As Long) SourceWBPath = TemplatePath &amp; FileName Data = GetCombineData(SourceWBPath) With WbKrogerScorecard Dim DateValue As String With WbKrogerScorecard.Worksheets(&quot;Weekly Division&quot;) If FileIndex = 0 Then DateValue = &quot;Kroger YTD - Ending &quot; &amp; Left(Right(.Range(&quot;A4&quot;), 24), 23) Else DateValue = &quot;Latest &quot; &amp; FileIndex &amp; &quot; Wks - Ending &quot; &amp; Left(Right(.Range(&quot;A4&quot;), 24), 23) End If End With With WbKrogerScorecard.Worksheets(&quot;COMBINED&quot;) With .Cells(.Rows.Count, &quot;B&quot;).End(xlUp).Offset(1).Resize(UBound(Data(0))) .Offset(0, -1).Value = DateValue .Resize(ColumnSize:=UBound(Data(0), 2)).Value = Data(0) End With .Cells(.Rows.Count, &quot;L&quot;).End(xlUp).Offset(1).Resize(UBound(Data(1)), UBound(Data(1), 2)).Value = Data(1) End With End With End Sub Private Function GetCombineData(SourceWBPath As String) With Workbooks.Open(SourceWBPath) With .Worksheets(1) Dim Data(1) As Variant Data(0) = .Range(.Cells(.Rows.Count, &quot;A&quot;).End(xlUp), &quot;H18&quot;).Value Data(1) = .Range(&quot;I18:R18&quot;).Resize(UBound(Data(0))).Value End With .Close SaveChanges:=False End With GetCombineData = Data End Function Sub StoreSelling_DataPaste() Set WbKrogerScorecard = Workbooks(&quot;KROGER M6 SCORECARD TEMPLATE.xlsm&quot;) Dim WsStoreSelling As Worksheet Set WsStoreSelling = WbKrogerScorecard.Worksheets(&quot;Stores Selling Summary&quot;) With WsStoreSelling .Range(&quot;A6:N&quot; &amp; .Cells(.Rows.Count, &quot;A&quot;).End(xlUp).Offset(1).Row).ClearContents End With StoreSellingWorksheets WbKrogerScorecard, &quot;Stores Selling 52Wks_Frozen.csv&quot;, 52 StoreSellingWorksheets WbKrogerScorecard, &quot;Stores Selling 52Wks_Natural.csv&quot;, 52 StoreSellingWorksheets WbKrogerScorecard, &quot;Stores Selling 26Wks_Frozen.csv&quot;, 26 StoreSellingWorksheets WbKrogerScorecard, &quot;Stores Selling 26Wks_Natural.csv&quot;, 26 StoreSellingWorksheets WbKrogerScorecard, &quot;Stores Selling 13Wks_Frozen.csv&quot;, 13 StoreSellingWorksheets WbKrogerScorecard, &quot;Stores Selling 13Wks_Natural.csv&quot;, 13 StoreSellingWorksheets WbKrogerScorecard, &quot;Stores Selling 4Wks_Frozen.csv&quot;, 4 StoreSellingWorksheets WbKrogerScorecard, &quot;Stores Selling 4Wks_Natural.csv&quot;, 4 StoreSellingWorksheets WbKrogerScorecard, &quot;Stores Selling YTD_Frozen.csv&quot;, 0 StoreSellingWorksheets WbKrogerScorecard, &quot;Stores Selling YTD_Natural.csv&quot;, 0 End Sub Private Sub StoreSellingWorksheets(WbKrogerScorecard As Workbook, FileName As String, FileIndex As Long) SourceWBPath = TemplatePath &amp; FileName Data = GetStoreSellingData(SourceWBPath) With WbKrogerScorecard Dim DateValue As String With WbKrogerScorecard.Worksheets(&quot;Weekly Division&quot;) If FileIndex = 0 Then DateValue = &quot;Kroger YTD - Ending &quot; &amp; Left(Right(.Range(&quot;A4&quot;), 24), 23) Else DateValue = &quot;Latest &quot; &amp; FileIndex &amp; &quot; Wks - Ending &quot; &amp; Left(Right(.Range(&quot;A4&quot;), 24), 23) End If End With With WbKrogerScorecard.Worksheets(&quot;Stores Selling Summary&quot;) With .Cells(.Rows.Count, &quot;B&quot;).End(xlUp).Offset(1).Resize(UBound(Data(0))) .Offset(0, -1).Value = DateValue .Resize(ColumnSize:=UBound(Data(0), 2)).Value = Data(0) End With .Cells(.Rows.Count, &quot;G&quot;).End(xlUp).Offset(1).Resize(UBound(Data(1)), UBound(Data(1), 2)).Value = Data(1) .Cells(.Rows.Count, &quot;I&quot;).End(xlUp).Offset(1).Resize(UBound(Data(2)), UBound(Data(2), 2)).Value = Data(2) .Cells(.Rows.Count, &quot;M&quot;).End(xlUp).Offset(1).Resize(UBound(Data(3)), UBound(Data(3), 2)).Value = Data(3) End With UpdateStoresSellingSummaryAttributes End With End Sub Private Function GetStoreSellingData(SourceWBPath As String) With Workbooks.Open(SourceWBPath) With .Worksheets(1) Dim Data(3) As Variant Data(0) = .Range(.Cells(.Rows.Count, &quot;A&quot;).End(xlUp), &quot;B13&quot;).Value Data(1) = .Range(&quot;C13&quot;).Resize(UBound(Data(0))).Value Data(2) = .Range(&quot;F13:I13&quot;).Resize(UBound(Data(0))).Value Data(3) = .Range(&quot;D13:E13&quot;).Resize(UBound(Data(0))).Value End With .Close SaveChanges:=False End With GetStoreSellingData = Data End Function Private Sub UpdateStoresSellingSummaryAttributes() Const Formula As String = &quot;=INDEX(COMBINED!$C:$F,MATCH($C6,COMBINED!$H:$H,0),MATCH(D$5,COMBINED!$C$4:$F$4,0))&quot; Dim Target As Range With WbKrogerScorecard.Worksheets(&quot;Stores Selling Summary&quot;) Set Target = .Range(&quot;A6&quot;, .Range(&quot;A&quot; &amp; .Rows.Count).End(xlUp)) Set Target = Target.Offset(, 3) Set Target = Target.Resize(, 3) Target.Formula = Formula End With End Sub </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-28T15:27:08.683", "Id": "486930", "Score": "2", "body": "\"Is this normal?\" [probably](https://codereview.meta.stackexchange.com/q/8908). To be clear do you want a review of your code - do you want people to explain how you can make your code better?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-28T17:54:20.650", "Id": "486948", "Score": "1", "body": "In programming, input/output (I/O) work is the slowest thing that can be done; opening a file from disk or network *is* I/O work, and while VBA is waiting for the `Workbooks.Open` function to return, it cannot do anything other than *wait* for the I/O to complete. So yes, this is normal. Please [edit] your post to clarify what reviewers are looking at?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-28T18:12:15.787", "Id": "486951", "Score": "0", "body": "@Peilonrayz - Yes, sorry I updated my post. Is there a way to make the code better or more efficient?" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-28T14:59:20.773", "Id": "248551", "Score": "1", "Tags": [ "vba", "excel" ], "Title": "Longer Macro getting stuck when opening Workbooks" }
248551
<h3>Preliminary rant:</h3> <p><code>System.Collections.Generic.KeyNotFoundException : The given key was not present in the dictionary.</code></p> <p>Oh. My.</p> <p>So I finally got fed up with <a href="https://softwareengineering.stackexchange.com/questions/278949/why-do-many-exception-messages-not-contain-useful-details">how default exception information is beyond useless</a>.</p> <p>For a part of the project I will mostly no longer use the <code>this[TKey key]</code> property to access my <code>Dictionary</code>ies but will use a custom extension method that actually tries to tell me WTF went wrong.</p> <h3>Preliminary rationale:</h3> <p>The system I have has a large &quot;integration testing&quot; suite in addition to more easily debuggable Unit Tests, and if things go southwards, it is <em>hard</em> to grok what went wrong, if all you have is a rather unspecific stack trace and a message telling you:</p> <blockquote> <p><code>System.Collections.Generic.KeyNotFoundException : The given key was not present in the dictionary.</code></p> </blockquote> <p>I would note that this system heavily relies on (string) mappings, where some kind of configuration error can easily trigger such errors in unexpected places.</p> <p>Especially, there are quite a lot of places in the code, where <em>different dictionaries will be consulted in the same code part / line</em>, making the stacktrace basically worthless to pinpoint the exact problem. Think:</p> <pre><code>var attributeValue = model[Config.PartX].attributes[Config.Attribute42]; </code></pre> <p>I will also note that I started out with hand coding the <code>TryGetValue</code> stuff, but this got unreadable pretty fast, so I'm looking forward to trying a slightly less specific, but more hopefully usable, approach.</p> <h3>Requirements</h3> <ul> <li><p>&quot;Key Not Found&quot; Exception shall contain information pertaining to:</p> <ul> <li>local name of dictionary</li> <li>number of items in dictionary</li> <li>value of the key</li> </ul> </li> <li><p>The information shall be recorded by the logging framework (NLog) without further fiddling.</p> </li> <li><p>I feel I have to explicitly note this: <strong>The potential leaking of <code>key</code> value information is beyond irrelevant for this system.</strong> Please do not comment wrt. this aspect.</p> </li> </ul> <h3>Code</h3> <p>If applicable, all my snippets basically fall under <a href="https://opensource.org/licenses/unlicense" rel="nofollow noreferrer">https://opensource.org/licenses/unlicense</a> in the unlikely event anybody would like to copy this.</p> <pre><code>namespace MY.Project { public static class DictionaryHelper { /// &lt;summary&gt; /// Same as `TValue this[TKey key] { get; }`, but with a better exception message /// containing the dictionary &quot;name&quot; (needs to be provided), number of entries and key value /// &lt;/summary&gt; /// &lt;returns&gt;Value if found, throws KeyNotFoundException otherwise&lt;/returns&gt; public static TValue GetExistingValue&lt;TKey, TValue&gt;(this IDictionary&lt;TKey, TValue&gt; dict, string nameOfDict, TKey key) { if (!dict.TryGetValue(key, out var val)) { throw CreateKeyNotFoundException(dict, nameOfDict, dict.Count, key); } return val; } /// &lt;see cref=&quot;GetExistingValue&quot;/&gt; for `IDictionary` above. public static TValue GetExistingValue&lt;TKey, TValue&gt;(this IReadOnlyDictionary&lt;TKey, TValue&gt; dict, string nameOfDict, TKey key) { if (!dict.TryGetValue(key, out var val)) { throw CreateKeyNotFoundException(dict, nameOfDict, dict.Count, key); } return val; } /// &lt;summary&gt; /// Provide separate explicit overload for the `Dictionary` class because this class implements both /// the IDict and IReadOnlyDict interface, making the overload ambiguous otherwise /// &lt;/summary&gt; public static TValue GetExistingValue&lt;TKey, TValue&gt;(this Dictionary&lt;TKey, TValue&gt; dict, string nameOfDict, TKey key) { return GetExistingValue((IDictionary&lt;TKey, TValue&gt;)dict, nameOfDict, key); } private static KeyNotFoundException CreateKeyNotFoundException&lt;T, TCount, TKey&gt;(T dict, string nameOfDict, TCount count, TKey key) { return new KeyNotFoundException( $&quot;{nameOfDict} ({dict.GetType()}) (with #{count} entries) does not contain key &lt;{key}&gt;!&quot; ); } } </code></pre> <h3>Questions</h3> <p>Beyond general feedback:</p> <ul> <li>Is there any sane name for this extension method?</li> <li>Would <em>you</em> make this an extension method?</li> <li>Is there any other good way to capture the name of the dictionary variable?</li> <li>Order of parameters? How to prevent messing up order of <code>string nameOfDict</code> and <code>key</code>if <code>TKey == string</code>?</li> </ul>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-28T15:19:38.667", "Id": "486926", "Score": "3", "body": "_\"If applicable, all my snippets basically fall under https://opensource.org/licenses/unlicense ...\"_ This statement is futile. As soon you posted here your content gets owned by Stack Overflow Inc. and the license is _Creative Commons_ (check the [help] which one exactly)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-28T15:22:26.323", "Id": "486927", "Score": "1", "body": "Can't you just fix the places where multiple dictionaries are accessed on the same line to make the stack trace useful?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-31T08:51:18.847", "Id": "487201", "Score": "0", "body": "@πάνταῥεῖ - No. The Code is copyright *by me* and, yes, I license it (to S.O. and its users) under [CC](https://creativecommons.org/licenses/by-sa/4.0/), but there's no problem if I additionally also provide it under another license so that others can copy it without adhering to the CC license (which would require attribution and ShareAlike)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-31T08:54:39.173", "Id": "487202", "Score": "0", "body": "@sleptic - One could do this, but in release builds, the line number information often isn't fully accurate, so if the accesses are just a few lines apart, it still won't help." } ]
[ { "body": "<p>A different way to skin this cat is to wrap the dictionary. Something along the lines of this</p>\n<pre><code>public class DictionarWrapper&lt;TKey, TValue&gt; : IDictionary&lt;TKey, TValue&gt;\n{\n private readonly IDictionary&lt;TKey, TValue&gt; innerDictionary;\n private readonly string name;\n \n public DictionarWrapper(IDictionary&lt;TKey, TValue&gt; innerDictionary, string name)\n {\n // could throw if null or set to empty\n this.name = name ?? string.Empty;\n this.innerDictionary = innerDictionary;\n }\n\n public DictionarWrapper(string name) : this(new Dictionary&lt;TKey, TValue&gt;(), name)\n {\n }\n</code></pre>\n<p>Most of the methods you would just be chaining down back into the innerDictionary but the indexer function you would put your code</p>\n<pre><code>public TValue this[TKey key] \n{\n get {\n // either trap error or write own TryGetValue and skip calling the normal inner indexer \n try\n {\n return innerDictionary[key];\n }\n catch (KeyNotFoundException ex)\n { \n throw new KeyNotFoundException($&quot;{name} ({innerDictionary.GetType()}) (with #{Count} entries) does not contain key &lt;{key}&gt;!&quot;, ex);\n }\n }\n set =&gt; innerDictionary[key] = value;\n}\n</code></pre>\n<p>You wouldn't need to change your code that is accessing the dictionary and still get the exception info you want. Plus if you pass in the name in the constructor then you don't need to worry about continuing to pass it in each time.</p>\n<p>You could also add to the constructor(s) to make it like the normal Dictionary constructors then you just need to change where the code create the dictionary to be your wrapperr</p>\n<p>I also feel wrapping a class is pretty standard in programming, see Decorator Pattern, plus for future maintenance and someone coming after you they don't need to know about a new extension method.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-29T02:04:53.383", "Id": "248588", "ParentId": "248552", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-28T15:00:01.300", "Id": "248552", "Score": "4", "Tags": [ "c#", ".net" ], "Title": "C# KeyNotFoundException with more information" }
248552
<p>I have just started reading the GO4 book to learn the OOD concepts. In order to practice the Prototype pattern, I implemented a small example (the idea for colored shapes was taken from &quot;refactoring.guru&quot;). Following is my code with some questions beneath.</p> <p>Prototype definition:</p> <pre><code>enum class Shape { Circle, Rectangle, }; class ColoredShapePrototype { protected: std::string color_; public: ColoredShapePrototype() {} ColoredShapePrototype(std::string color) : color_(color) {} virtual ~ColoredShapePrototype() {} virtual ColoredShapePrototype* Clone() const = 0; virtual void ShapeDetails() { std::cout &lt;&lt; &quot;Color: &quot; &lt;&lt; color_ &lt;&lt; &quot;\n&quot;; } virtual void UpdateColor(int color) { color_ = color; } }; class ColoredCirclePrototype : public ColoredShapePrototype { private: int radius_; public: ColoredCirclePrototype(std::string color, int raduis) : ColoredShapePrototype(color), radius_(raduis) {} ColoredShapePrototype* Clone() const override { return new ColoredCirclePrototype(*this); } void ShapeDetails() { ColoredShapePrototype::ShapeDetails(); std::cout &lt;&lt; &quot;Radius: &quot; &lt;&lt; radius_ &lt;&lt; &quot;\n&quot;; } }; class ColoredRectanglePrototype : public ColoredShapePrototype { private: int height_; int width_; public: ColoredRectanglePrototype(std::string color, int height, int width) : ColoredShapePrototype(color), height_(height), width_(width) {} ColoredShapePrototype* Clone() const override { return new ColoredRectanglePrototype(*this); } void ShapeDetails() { ColoredShapePrototype::ShapeDetails(); std::cout &lt;&lt; &quot;Height: &quot; &lt;&lt; height_ &lt;&lt; &quot;\nWidth:&quot; &lt;&lt; width_ &lt;&lt; &quot;\n&quot;; } }; class ShapesPrototypeFactory { private: std::unordered_map&lt;Shape, ColoredShapePrototype*&gt; prototypes_; public: ShapesPrototypeFactory() { prototypes_[Shape::Circle] = new ColoredCirclePrototype(&quot;White&quot;, 5); prototypes_[Shape::Rectangle] = new ColoredRectanglePrototype(&quot;White&quot;, 2, 3); } ~ShapesPrototypeFactory() { delete prototypes_[Shape::Circle]; delete prototypes_[Shape::Rectangle]; } ColoredShapePrototype* CreatePrototype(Shape shape) { return prototypes_[shape]-&gt;Clone(); } }; </code></pre> <p>Usage in main:</p> <pre><code>ShapesPrototypeFactory prototype_factory; ColoredShapePrototype* circ = prototype_factory.CreatePrototype(Shape::Circle); circ-&gt;ShapeDetails(); ColoredShapePrototype* rect = prototype_factory.CreatePrototype(Shape::Rectangle); rect-&gt;ShapeDetails(); delete circ; delete rect; </code></pre> <p>Questions:</p> <ol> <li><p>Interfaces in general - pure virtual functions and other variables are declared, and derived classes should implement those. Suppose I want to add a specific capability (with unique data member and member function) to the derived - Does it contradict the interface idea? (Because, if I have a pointer from base to derived, this pointer will not recognize the specific method...). If it is OK, Is there a way to execute a derived function through the interface(who doesnt have this function..)?</p> </li> <li><p>while debugging and watching circ variable, I can see the variable in the memory window, and I see &quot;white&quot; color, but I cant find the radius there. Is there a way i can see specific data member address in the memory? (I have tried circ-&gt;radius_ etc. none was working..)</p> </li> <li><p>I have seen that most implementations are using &quot;unique_ptr&quot;. I know its basic usage, but how critical it is? and why not use it all the times rather than a regular pointer actually? and where are the places I should use it in the prototype pattern?</p> </li> <li><p>Implementing Copy Constructor in case of non-stack variables (shallow/deep copying) for the clone operation - Is a CCtor in the base class is sufficient or the derived is required as well?</p> </li> <li><p>Code review - better syntax/design/ideas/improvements?</p> </li> </ol> <p>Thanks in advance, I will highly appreciate your help!</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-28T19:15:21.993", "Id": "486955", "Score": "0", "body": "What's the GO4 book and who's \"refactoring.guru\"? What problem does this code solve? What prompted you to write this?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-29T07:00:55.917", "Id": "486994", "Score": "0", "body": "this is a design patterns book, and that website is a random website i encountered while looking for an example. I want to make sure I used the pattern correctly and if there are better ways to write it" } ]
[ { "body": "<p>Let's go through your questions.</p>\n<ol>\n<li><p>No, it does not contradict the idea.</p>\n<p>The base class should define the common functionality of the derived classes, that's needed by some system to operate on such objects. However, part of the code of that system, or a different part of the code base may be dedicated to working only with some of the derived classes, in which case the functions and variables should not be defined in the base class.</p>\n<p>Using your example, a rendering system may require a Render() method and variables defining the visual characteristics of a shape, which should be part of the colored shape interface. On the other hand, a system that works with shapes that have corners will not be expected to work on circles. In which case you would dynamic_cast a shape to the derived type in that system and call the methods specific to the derived class.</p>\n</li>\n<li><p>Depending on the debugger you're using, you are probably using a watch window to view the values of the circ variable. The watch window will display circ as a variable of type ColoredShapePrototype*, which only has a color variable.</p>\n<p>In Visual studio, for example, watch window will allow you to cast the variable to a ColoredCirclePrototype*, by typing (ColoredCirclePrototype*)circ. You will then see the radius member of circ.</p>\n</li>\n<li><p>Smart pointers avoid common problems with managing dynamically allocated memory. unique_ptr specifically avoids leaks by deallocating the memory at the end of the scope, unless it is moved to another unique_ptr. If the clone() function returns a unique_ptr, this means the user of your prototype pattern code won't need to bother remembering to dealocate the memory. However, you are enforcing him to use a specific implementation of a smart pointer, in this case the standard library's unique_ptr. If this prototype pattern is part of a library and used in a project that has a different implementation of unique_ptr, it can become more complicated to manage this difference than if you return a plain raw pointer.</p>\n</li>\n<li><p>If a derived class has members that need to be deep copied, then that class needs to define a copy constructor that performs the deep copy.</p>\n</li>\n<li><p>My feedback</p>\n</li>\n</ol>\n<ul>\n<li>The most significant issue I see is that someone else can further derive a class from your derived classes, and there's nothing to remind them that the clone method needs to be overriden. Let's consider creating a ColoredSquarePrototype that inherits ColoredRectanglePrototype. If we create a square object and try to clone it, we would call the ColoredRectanglePrototype::clone() which copy constructs a rectangle, not a square. This is not easy to solve, one option is to declare your derived classes final, so they cannot be further derived. If you wish to allow derivations, you could read further about the issue in this blog post: <a href=\"https://katyscode.wordpress.com/2013/08/22/c-polymorphic-cloning-and-the-crtp-curiously-recurring-template-pattern/\" rel=\"nofollow noreferrer\">https://katyscode.wordpress.com/2013/08/22/c-polymorphic-cloning-and-the-crtp-curiously-recurring-template-pattern/</a></li>\n<li>I don't see the benefit of providing a default constructor in\nColoredShapePrototype, it just allows the usage of shapes with an\nunitialized color (&quot;&quot;).</li>\n<li>You should pass a const string&amp; to the constructors to avoid copying.</li>\n<li>Removing &quot;Prototype&quot; from the name of the shape classes will convey better that these classes represent actual shapes instead of some auxiliary implementation.</li>\n<li>The virtual void UpdateColor(int color) incorrectly takes an integer parameter instead of a string. This compiles, because the integer is converted to a char for std::string::operator=(const char) to be invoked.</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-09-02T04:29:16.870", "Id": "248793", "ParentId": "248553", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-28T15:12:02.067", "Id": "248553", "Score": "1", "Tags": [ "c++", "design-patterns" ], "Title": "Prototype Design Pattern C++" }
248553
<pre><code>#include &lt;cstring&gt; #include &lt;map&gt; #include &lt;iostream&gt; #include &lt;fstream&gt; #include &lt;sstream&gt; #include &lt;string&gt; #include &lt;sys/types.h&gt; #include &lt;sys/wait.h&gt; #include &lt;unistd.h&gt; #include &lt;vector&gt; #include &lt;filesystem&gt; #include &lt;errno.h&gt; #include &lt;bits/stdc++.h&gt; std::string USERDIR = getenv(&quot;HOME&quot;); std::string ALIASFILE = USERDIR+&quot;/shell/.alias&quot;; std::vector&lt;std::string&gt; Split(std::string input, char delim); void Execute(const char *command, char *arglist[]); std::map&lt;std::string, std::string&gt; alias(std::string file); bool BuiltInCom(const char *command, char *arglist[],int arglist_size); char** conv(std::vector&lt;std::string&gt; source); bool createAlias(std::string first, std::string sec); std::string replaceAll(std::string data, std::map &lt;std::string, std::string&gt; dict); int main() { while (1) { char path[100]; getcwd(path, 100); char prompt[110] = &quot;$[&quot;; strcat(prompt, path); strcat(prompt,&quot;]: &quot;); std::cout &lt;&lt; prompt; // Takes input and splits it by space std::string input; getline(std::cin, input); if(input == &quot;&quot;) continue; std::map&lt;std::string, std::string&gt; aliasDict = alias(ALIASFILE); input = replaceAll(input, aliasDict); std::vector&lt;std::string&gt; parsed_string = Split(input, ' '); // Splits parsed_string into command and arglist const char * com = parsed_string.front().c_str(); char ** arglist = conv(parsed_string); // Checks if it is a built in command and if not, execute it if(BuiltInCom(com, arglist, parsed_string.size()) == 0){ Execute(com, arglist); } delete[] arglist; } } std::vector&lt;std::string&gt; Split(std::string input, char delim) { std::vector&lt;std::string&gt; ret; std::istringstream f(input); std::string s; while (getline(f, s, delim)) { ret.push_back(s); } return ret; } void Execute(const char *command, char *arglist[]) { pid_t pid; //Creates a new proccess if ((pid = fork()) &lt; 0) { std::cout &lt;&lt; &quot;Error: Cannot create new process&quot; &lt;&lt; std::endl; exit(-1); } else if (pid == 0) { //Executes the command if (execvp(command, arglist) &lt; 0) { std::cout &lt;&lt; &quot;Could not execute command&quot; &lt;&lt; std::endl; exit(-1); } else { sleep(2); } } //Waits for command to finish if (waitpid(pid, NULL, 0) != pid) { std::cout &lt;&lt; &quot;Error: waitpid()&quot;; exit(-1); } } bool BuiltInCom(const char *command, char ** arglist, int arglist_size){ if(strcmp(command, &quot;quit&quot;) == 0){ delete[] arglist; exit(0); } else if(strcmp(command, &quot;cd&quot;) == 0){ if(chdir(arglist[1]) &lt; 0){ switch(errno){ case EACCES: std::cout &lt;&lt; &quot;Search permission denied.&quot; &lt;&lt; std::endl; break; case EFAULT: std::cout &lt;&lt; &quot;Path points outside accesable adress space&quot; &lt;&lt; std::endl; break; case EIO: std::cout &lt;&lt; &quot;IO error&quot; &lt;&lt; std::endl; break; case ELOOP: std::cout &lt;&lt; &quot;Too many symbolic loops&quot; &lt;&lt; std::endl; break; case ENAMETOOLONG: std::cout &lt;&lt; &quot;Path is too long&quot; &lt;&lt; std::endl; break; case ENOENT: std::cout &lt;&lt; &quot;Path doesn't exist&quot; &lt;&lt; std::endl; break; case ENOTDIR: std::cout &lt;&lt; &quot;Path isn't a dir&quot; &lt;&lt; std::endl; break; default: std::cout &lt;&lt; &quot;Unknown error&quot; &lt;&lt; std::endl; break; } return 1; } return 1; } else if(strcmp(command, &quot;alias&quot;) == 0){ if(arglist_size &lt; 2){ std::cout &lt;&lt; &quot;[USAGE] Alias originalName:substituteName&quot; &lt;&lt; std::endl; return 1; } std::string strArg(arglist[1]); int numOfSpaces = std::count(strArg.begin(), strArg.end(), ':'); if(numOfSpaces){ std::vector&lt;std::string&gt; aliasPair = Split(strArg, ':'); createAlias(aliasPair.at(0), aliasPair.at(1)); return 1; } else { std::cout &lt;&lt; &quot;[USAGE] Alias originalName:substituteName&quot; &lt;&lt; std::endl; return 1; } } return 0; } char** conv(std::vector&lt;std::string&gt; source){ char ** dest = new char*[source.size() + 1]; for(int i = 0; i &lt; source.size(); i++) dest[i] = (char *)source.at(i).c_str(); dest[source.size()] = NULL; return dest; } std::map&lt;std::string, std::string&gt; alias(std::string file){ std::map&lt;std::string, std::string&gt; aliasPair; std::string line; std::ifstream aliasFile; aliasFile.open(file); if(aliasFile.is_open()){ while(getline(aliasFile, line)){ auto pair = Split(line, ':'); aliasPair.insert(std::make_pair(pair.at(0), pair.at(1))); } } else { std::cout &lt;&lt; &quot;Error: Cannot open alias file\n&quot;; } return aliasPair; } std::string replaceAll(std::string data, std::map &lt;std::string, std::string&gt; dict){ for(std::pair &lt;std::string, std::string&gt; entry : dict){ size_t start_pos = data.find(entry.first); while(start_pos != std::string::npos){ data.replace(start_pos, entry.first.length(),entry.second); start_pos = data.find(entry.first, start_pos + entry.second.size()); } } return data; } bool createAlias(std::string first, std::string second){ std::ofstream aliasFile; aliasFile.open(ALIASFILE, std::ios_base::app); if(aliasFile.is_open()){ aliasFile &lt;&lt; first &lt;&lt; &quot;:&quot;&lt;&lt; second &lt;&lt; std::endl; return true; } else return false; } </code></pre> <p>I have a shell that I've coded in c++ on a Fedora Linux distro. I would welcome general improvements on how to make the code better, but I'd especially welcome comments on the code's readability</p>
[]
[ { "body": "<p>There are several improvements you can do for this code using just c++ standard library classes and functions.</p>\n<h3>1. Don't use <code>#include &lt;bits/stdc++.h&gt;</code></h3>\n<p>It's not guaranteed that this header file exists, and is a compiler specific internal. Using such will make your code less portable.<br />\nOnly <code>#include</code> headers provided for the classes and functions you want to use from the c++ standard library.<br />\nYou can read more about the possible consequences and problems here: <a href=\"https://stackoverflow.com/questions/31816095/why-should-i-not-include-bits-stdc-h\">Why should I not #include &lt;bits/stdc++.h&gt;?</a></p>\n<p>As well don't <code>#include</code> header files where you don't use anything from them (e.g. <code>#include &lt;filesystem&gt;</code>).</p>\n<h3>2. Don't use c library functions for string manipulations</h3>\n<p>E.g. your code to build the <code>prompt</code> variable can be drastically simplified by just using <code>std::string</code> instead of <code>char*</code>:</p>\n<pre><code>char path[100];\ngetcwd(path,100);\nstd::string prompt = &quot;$[&quot; + std::string(path) + &quot;]:&quot;;\n</code></pre>\n<p>Also you can simply write</p>\n<pre><code>if(command == &quot;quit&quot;){\n</code></pre>\n<p>supposed you use <code>const std::string&amp;</code> as type for the <code>command</code> parameter.</p>\n<h3>3. You don't need to allocate arrays of <code>char*</code> variables to pass them to <code>execxy()</code> functions</h3>\n<p>Just built a <code>std::vector&lt;const char*&gt;</code> instead of your <code>conv()</code> function:</p>\n<pre><code>void Execute(const std::string&amp; command, const std::vector&lt;std::string&gt;&amp; args) {\n std::vector&lt;const char*&gt; cargs;\n pid_t pid;\n\n for(auto sarg : args) {\n cargs.append(sarg.data());\n }\n cargs.append(nullptr);\n\n //Creates a new proccess\n if ((pid = fork()) &lt; 0) {\n std::cout &lt;&lt; &quot;Error: Cannot create new process&quot; &lt;&lt; std::endl;\n exit(-1);\n } else if (pid == 0) {\n //Executes the command\n if (execvp(command.data(), cargs.data()) &lt; 0) {\n std::cout &lt;&lt; &quot;Could not execute command&quot; &lt;&lt; std::endl;\n exit(-1);\n } else {\n sleep(2);\n }\n }\n //Waits for command to finish\n if (waitpid(pid, NULL, 0) != pid) {\n std::cout &lt;&lt; &quot;Error: waitpid()&quot;;\n exit(-1);\n }\n}\n</code></pre>\n<p>In such case where you use raw data pointers obtained by e.g. <code>std::string::data()</code>, be sure that the lifetimes of the underlying variables last throughout their use in e.g. C library functions.</p>\n<p>As a general rule of thumb:<br />\nAvoid doing memory management yourself using <code>new</code> and <code>delete</code> explicitely.\nRather use a c++ <a href=\"https://en.cppreference.com/w/cpp/container\" rel=\"noreferrer\">standard container</a> or at least <a href=\"https://en.cppreference.com/w/cpp/memory\" rel=\"noreferrer\">smart pointers</a>.</p>\n<h3>4. You don't need explicit comparison for <code>bool</code> values</h3>\n<p>Change</p>\n<pre><code>if(BuiltInCom(com, arglist, parsed_string.size()) == 0){\n</code></pre>\n<p>to</p>\n<pre><code>if(!BuiltInCom(com, arglist, parsed_string.size())){\n</code></pre>\n<p>Also use <code>false</code> and <code>true</code> instead of the implicit conversions from <code>int</code> <code>0</code> and <code>1</code> literals.</p>\n<h3>5. Use <code>const</code> and pass by reference for parameters whenever possible</h3>\n<p>Use <code>const</code> if you don't need to change the parameter.<br />\nUse pass by reference (<code>&amp;</code>) if you want to avoid unnecessary copies made for non trivial types.</p>\n<p>You can see how in the example of <code>Execute()</code> I've given above.</p>\n<p>Same goes for example</p>\n<pre><code>std::string replaceAll(std::string data, std::map &lt;std::string, std::string&gt; dict);\n</code></pre>\n<p>this should be</p>\n<pre><code>std::string&amp; replaceAll(std::string&amp; data, const std::map &lt;std::string, std::string&gt;&amp; dict);\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-28T21:34:51.043", "Id": "486969", "Score": "2", "body": "Apart from not using C string functions, you can also avoid some C path functions by using `std::filesystem` functions, for example [`std::filesystem::current_path()`](https://en.cppreference.com/w/cpp/filesystem/current_path) instead of `getcwd()`. This requires C++17, if you cannot use that you can use [`boost::filesystem`](https://www.boost.org/libs/filesystem/) instead." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-28T18:18:09.537", "Id": "248564", "ParentId": "248555", "Score": "5" } }, { "body": "<h2>Formatting.</h2>\n<p>This is one large wall of text. You need to split things up into logical sections to make this easyier to read. Add some vertical space between section to make this easier to read.</p>\n<hr />\n<p>You have a bunch of #include. Its nice to order them. You can choose any way to order it as long as its logical and makes it easy for people to look through.</p>\n<p>I do most specific to most general.</p>\n<pre><code> #include &quot;HeaderFileForThisSource.h&quot;\n #include &quot;HeaderFileForOtherClassesInThisProject&quot;\n ...\n #include &lt;C++ Librries&gt;\n ...\n #include &lt;C Librries&gt;\n ...\n #include &lt;Standard C++ Header Files&gt;\n ..\n #include &lt;C standard Libraries&gt;\n ...\n</code></pre>\n<p>Others list them alphabetically.</p>\n<p>Not sure what is best but some logic to the ordering would be nice.</p>\n<hr />\n<p>This is really hard to read. I can't see the function names in the sea of text.</p>\n<pre><code>std::vector&lt;std::string&gt; Split(std::string input, char delim);\nvoid Execute(const char *command, char *arglist[]);\nstd::map&lt;std::string, std::string&gt; alias(std::string file);\nbool BuiltInCom(const char *command, char *arglist[],int arglist_size);\nchar** conv(std::vector&lt;std::string&gt; source);\nbool createAlias(std::string first, std::string sec);\nstd::string replaceAll(std::string data, std::map &lt;std::string, std::string&gt; dict);\n</code></pre>\n<p>With some judisious use of <code>using</code> and some tidying you can make that really easy to use.</p>\n<pre><code>using Store = std::vector&lt;std::string&gt;;\nusing Map = std::map&lt;std::string, std::string&gt;;\nusing CPPtr = char**;\n\nStore Split(std::string input, char delim);\nvoid Execute(const char *command, char *arglist[]);\nMap alias(std::string file);\nbool BuiltInCom(const char *command, char *arglist[],int arglist_size);\nCPPtr conv(std::vector&lt;std::string&gt; source);\nbool createAlias(std::string first, std::string sec);\nstd::string replaceAll(std::string data, std::map &lt;std::string, std::string&gt; dict);\n</code></pre>\n<h2>Code</h2>\n<p>Global &quot;Variables&quot; are a bad idea.</p>\n<pre><code>std::string USERDIR = getenv(&quot;HOME&quot;);\nstd::string ALIASFILE = USERDIR+&quot;/shell/.alias&quot;;\n</code></pre>\n<p>Set this up in <code>main()</code>. You can then either pass these around as parameters or add them to an object.</p>\n<p>You can have static immutable state in the global scope. This is for things like constants.</p>\n<hr />\n<p>Make it easy to read.</p>\n<pre><code> while (1) {\n</code></pre>\n<p>This would be better as:</p>\n<pre><code> while(true) {\n</code></pre>\n<hr />\n<p>Don't use fixed size buffers where the user could input arbitrary length strings. C++ has the <code>std::string</code> to handle this kind of situation.</p>\n<pre><code> char path[100];\n getcwd(path, 100);\n\n // Rather\n std::string path = std::filesystem::current_path().string();\n</code></pre>\n<hr />\n<p>Don't use magic numbers in your code:</p>\n<pre><code> char prompt[110] = &quot;$[&quot;;\n</code></pre>\n<p>Why a 110? Put the magic numbers into named constants</p>\n<pre><code> // Near the top of the programe with all other constants.\n // Then you can tune your program without having to search for the constants.\n static std::size_t constepxr bufferSize = 110;\n\n .....\n char buffer[bufferSize];\n</code></pre>\n<hr />\n<p>Should be using std::string here</p>\n<pre><code> strcat(prompt, path);\n strcat(prompt,&quot;]: &quot;);\n</code></pre>\n<p>The old C string functions are not safe.</p>\n<hr />\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-28T18:48:03.917", "Id": "248565", "ParentId": "248555", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-28T15:42:32.983", "Id": "248555", "Score": "5", "Tags": [ "c++", "linux", "shell" ], "Title": "c++ shell for linux" }
248555
<p>So i got an task from school. Which ask's me to write a program tad creates an 2d array with 11 rows and 5 columns. In which the first column starts with 2.0 and increments by 0.1 all the way up to 3.0. Then in next column it should be devided by 1 so if x is 2.0 then 1 / x and goes trough all 11 rows. then in next column it has to multiply by 2 so x^2 and repeat in every column up to x^4. So so far i got it to do what i need , but i know there should be a better way to achieve this. as if there would be a task to go up to x^50 for example i imagine it would be pain to do with my way. as its hardcoded.</p> <p>So here is my code:</p> <pre><code>#include&lt;iostream&gt; #include&lt;iomanip&gt; #include&lt;array&gt; using namespace std; int main() { const int rows = 11; const int columns = 5; double x = 2.0; array&lt;array&lt;double, columns&gt;,rows&gt; A{}; cout &lt;&lt; setprecision(2); cout &lt;&lt; fixed; cout &lt;&lt; setw(2) &lt;&lt;&quot;x&quot; &lt;&lt; setw(10) &lt;&lt; &quot;1/x&quot; &lt;&lt; setw(7) &lt;&lt; &quot;x^2&quot; &lt;&lt; setw(7) &lt;&lt; &quot;x^3&quot; &lt;&lt; setw(8)&lt;&lt; &quot;x^4\n&quot;; cout &lt;&lt; &quot;------ ------ ------ ------ ------\n&quot;; A[0][0] = x; for(int i = 0; i &lt; A.size(); i++) { A[i+1][0] = A[i][0] + 0.1; A[i][1] = 1 / A[i][0]; A[i][2] = A[i][0] * A[i][0] * A[i][0]; A[i][3] = A[i][0] * A[i][0] * A[i][0]* A[i][0]; A[i][4] = A[i][0] * A[i][0] * A[i][0]* A[i][0] * A[i][0] ; for(int j = 0; j &lt; A[0].size(); j++) { cout &lt;&lt; A[i][j] &lt;&lt; setw(4) &lt;&lt; &quot; &quot;; } cout &lt;&lt; endl; } return 0; } </code></pre> <p>and here is how it's supposed to look: <a href="https://i.stack.imgur.com/eXNP1.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/eXNP1.png" alt="enter image description here" /></a></p> <p>Looking for suggestions or tips. I am strugling here. And sorry for my english it's not my native.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-28T18:08:47.057", "Id": "486950", "Score": "0", "body": "You say \"devided by 1\" and \"multiply by 2\" but you do something different. And it's not x^2, either. Most of your table is obviously wrong." } ]
[ { "body": "<p>You're almost there, you just need to use <a href=\"https://en.cppreference.com/w/cpp/numeric/math/pow\" rel=\"nofollow noreferrer\"><code>std::pow()</code></a> to raise a value to an arbitrary power, and add another <code>for</code>-loop to handle the repetetive work of filling in all the remaining columns:</p>\n<pre><code>for(int i = 0; i &lt; A.size(); i++)\n{\n A[i][0] = 2.0 + 0.1 * i;\n A[i][1] = 1 / A[i][0];\n\n for(int j = 2; j &lt; A[i].size(); j++)\n {\n A[i][j] = std::pow(A[i][0], j);\n }\n ...\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-29T08:08:47.523", "Id": "487000", "Score": "0", "body": "Thanks man. I didn't even know about std::pow :D Learned something new today. Thanks man." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-29T08:19:34.747", "Id": "487004", "Score": "1", "body": "@DreamHacker It's a pretty basic function provided by the standard library. I suggest you browse through https://en.cppreference.com/w/ and see what other helpful functions there are. You don't have to remember everything, but just get a feel of what is out there, so next time you need something you know where to look." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-28T21:44:39.923", "Id": "248574", "ParentId": "248556", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-28T17:16:53.907", "Id": "248556", "Score": "2", "Tags": [ "c++", "homework" ], "Title": "c++ array. Looking for better solution" }
248556
<p>Posting my code for LeetCode's LRU Cache, if you'd like to review, please do so, thank you for your time!</p> <h3>Problem</h3> <blockquote> <ul> <li><p>Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get and put.</p> </li> <li><p>get(key) - Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1.</p> </li> <li><p>put(key, value) - Set or insert the value if the key is not already present. When the cache reached its capacity, it should invalidate the least recently used item before inserting a new item.</p> </li> <li><p>The cache is initialized with a positive capacity.</p> </li> </ul> <p>Follow up:</p> <ul> <li>Could you do both operations in O(1) time complexity?</li> </ul> <h3>Example:</h3> <pre><code>LRUCache cache = new LRUCache( 2 /* capacity */ ); cache.put(1, 1); cache.put(2, 2); cache.get(1); // returns 1 cache.put(3, 3); // evicts key 2 cache.get(2); // returns -1 (not found) cache.put(4, 4); // evicts key 1 cache.get(1); // returns -1 (not found) cache.get(3); // returns 3 cache.get(4); // returns 4 </code></pre> </blockquote> <h3>Code</h3> <pre><code>type LRUCache struct { head *Node tail *Node cache map[int]*Node capacity int } type Node struct { prev *Node next *Node key int val int } func Constructor(capacity int) LRUCache { return LRUCache{capacity: capacity, cache: make(map[int]*Node)} } func (this *LRUCache) Get(key int) int { node, stored := this.cache[key] if !stored { return -1 } this.Evict(node) this.Add(node) return node.val } func (this *LRUCache) Put(key int, val int) { node, stored := this.cache[key] if !stored { node = &amp;Node{val: val, key: key} this.cache[key] = node } else { node.val = val this.Evict(node) } this.Add(node) if len(this.cache) &gt; this.capacity { node = this.tail if node != nil { this.Evict(node) delete(this.cache, node.key) } } } func (this *LRUCache) Evict(node *Node) { if node == this.head { this.head = node.next } if node == this.tail { this.tail = node.prev } if node.next != nil { node.next.prev = node.prev } if node.prev != nil { node.prev.next = node.next } } func (this *LRUCache) Add(node *Node) { node.prev = nil node.next = this.head if node.next != nil { node.next.prev = node } this.head = node if this.tail == nil { this.tail = node } } </code></pre> <h3>Reference</h3> <p>Here is LeetCode's template:</p> <pre><code>type LRUCache struct { } func Constructor(capacity int) LRUCache { } func (this *LRUCache) Get(key int) int { } func (this *LRUCache) Put(key int, value int) { } /** * Your LRUCache object will be instantiated and called as such: * obj := Constructor(capacity); * param_1 := obj.Get(key); * obj.Put(key,value); */ </code></pre> <ul> <li><p><a href="https://leetcode.com/problems/lru-cache/" rel="nofollow noreferrer">146. LRU Cache - Problem</a></p> </li> <li><p><a href="https://leetcode.com/problems/lru-cache/discuss/" rel="nofollow noreferrer">146. LRU Cache - Discuss</a></p> </li> </ul>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-28T17:38:29.880", "Id": "248558", "Score": "1", "Tags": [ "beginner", "algorithm", "object-oriented", "programming-challenge", "go" ], "Title": "LeetCode 146: LRU Cache (Go)" }
248558
<p>This code review is presented in 3 questions due to the amount of code:</p> <ol> <li>Part A (this question) contains the Lexical Analyzer and the main portion of the unit test code.</li> <li><a href="https://codereview.stackexchange.com/questions/248560/hand-coded-state-driven-lexical-analyzer-in-c-with-unit-test-part-b">Part B</a> contains the lower level unit tests called in Part A</li> <li><a href="https://codereview.stackexchange.com/questions/248561/hand-coded-state-driven-lexical-analyzer-in-c-with-unit-test-part-c">Part C</a> contains common unit test code that is included in all of the unit tests to be written.</li> </ol> <h2>Background</h2> <p>Back in June I provided this <a href="https://codereview.stackexchange.com/questions/244566/an-attempt-at-a-toy-vm/244573#244573">answer</a> to a question here on code review. I advised the person that asked the question to use enums rather than numbers to represent the opcodes, but upon further consideration I thought that the virtual machine really needed an editor as the front end and I have been working on that. An editor will require a translator to convert text into the numbers the virtual machine uses for opcodes and operands. The translator is composed of a parser and a lexical analyzer. The lexical analyzer is complete, unit tested and debugged so I am presenting it here for code review with the unit tests.</p> <p>This program is written in C because the original question was written in C. I tried to stick to the C90 standard as much as possible, but I did include _strdup() which is in the latest standard (perhaps it is strdup() in the latest standard, but Visual Studio suggested _strdup()).</p> <h2>Why did I write unit tests for the lexical analyzer?</h2> <ol> <li>It is a best practice at many companies that do software development.</li> <li>The code was very complex, at the time it was not a state machine (unit testing convinced me to go that route). It was over 450 lines of un-commented code in the parser module and growing.</li> <li>I had gotten to the point where I wanted to test/debug the lexical analyzer and the parser wasn't working so I wanted a program that ran only the lexical analyzer.</li> <li>I wanted to test/debug the code in a bottom up manner to make sure the lowest level functions were working correctly before testing the higher level functions.</li> </ol> <p>The benefits of unit testing were that it forced me to create a more modular design and to redesign the lexical analyzer to use a state machine rather another method. The results are less code and a better working lexical analyzer. It will also force a redesign of the parser, but that is for another question.</p> <h2>The Language</h2> <p>The language is fairly simple.</p> <p>{OPCODE, OPERAND}, {OPCODE, OPERAND}</p> <p>Here is a working program (it is the example program in the original question):</p> <pre><code>{PUSH, 0x0A}, {PUSH, 0x43}, {PUSH, 0x42}, {PUSH, 0x41}, {OUTPUTCHAR, 0x00}, {POP, 0x00}, {OUTPUTCHAR, 0x00}, {POP, 0x00}, {OUTPUTCHAR, 0x00}, {POP, 0x00}, {HALT, 0x00} </code></pre> <p><a href="https://i.stack.imgur.com/LHm7G.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/LHm7G.gif" alt="enter image description here" /></a></p> <h2>Questions</h2> <p>I learned C a long time ago from K&amp;R “The C Programming Language” Version 1 (pre C89/C90).</p> <ol> <li>Other than compiling this –O3 what can I do to optimize this code?</li> <li>Are there any features in the more modern versions of C that could reduce the amount of code? There are currently more 1300 lines of commented code to test the 376 lines of commented code in lexical_analyzer.c and lexical_analyzer.h.</li> <li>Is there archaic C usage that is not customary to use anymore?</li> <li>Are the unit tests missing any test cases, especially edge cases?</li> <li>Are there any memory leaks?</li> <li>Is the code readable?</li> <li>I don’t like the fact that I need to include the unit test files in lexical_analyzer.c do you see any way around this?</li> <li>Is the language too complex?</li> </ol> <h2>Code Available:</h2> <p>Rather than copy and pasting this code it is available in my <a href="https://github.com/pacmaninbw/VMWithEditor" rel="nofollow noreferrer">GitHub Repository</a>. The code as presented in these 3 questions is on the branch <code>Before_First_Code_Review</code>, updates including those based on the review will be added to the master branch. <strong>Udate</strong> The code reviews have been added to the appropriate <a href="https://github.com/pacmaninbw/VMWithEditor/tree/Before_First_Code_Review/VMWithEditor/UnitTests/State_Machine_Unit_Test" rel="nofollow noreferrer">repository unit test directory</a> in the <code>Before_First_Code_Review</code> branch.</p> <p>The unit test ouput is always saved to a <code>.txt</code> file, a comparison text file is the <a href="https://github.com/pacmaninbw/VMWithEditor/tree/master/VMWithEditor/UnitTests/State_Machine_Unit_Test/State_Machine_Unit_Test" rel="nofollow noreferrer">unit test folder</a> in the repository. The unit test output is 1827 lines so it is not included here in the question.</p> <p>There is a CMakeLists.txt file in the unit test directory, but I'm not sure it works so it isn't posted here. If anyone would like to test it, let me know what to do or how to fix it. I could give you permission to update it in GitHub.</p> <p><a href="https://i.stack.imgur.com/HADnu.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/HADnu.gif" alt="Layout of the Repository" /></a></p> <h2>The code being tested</h2> <p><strong>lexical_analyzer.h</strong></p> <pre><code>/* * lexical_analyzer.h * * The Syntax State Machine is a simple lexical analiser. Given the current syntax * state and the new input character what is the new syntax state. State machines * can be represented as tables. Table implementation of a state machine uses * more memory but performs faster, the lexical analyser programs Flex and LEX * generate tables to implement lexical analysis. * * This module uses enums to make the states and transitions easier to understand. * */ #ifndef SYNTAX_STATE_MACHINE_H #define SYNTAX_STATE_MACHINE_H typedef enum syntax_checks_list_items { OPENBRACE = 0, CLOSEBRACE = 1, COMMA = 2, LEGALOPCODE = 3, LEGALOPERAND = 4, ILLEGALOPCODE = 5, ILLEGALOPERAND = 6, ILLEGALFIRSTCHAR = 7, MULTIPLESTATEMENTSONELINE = 8, ILLEGALCHAR = 9, MISSINGCOMMA = 10 #define SYNTAX_CHECK_COUNT 11 } Syntax_Check_List_Items; typedef enum syntax_state_enum { START_STATE = 0, // Start of a new line, only white space or open brace is really expected ENTER_OPCODE_STATE = 1, // Open brace encountered, waiting for opcode (first alpha character) white space or alpha is expected OPCODE_STATE = 2, // Open brace and first leter of opcode have been encoutered more alpha, white space or comma expected END_OPCODE_STATE = 3, // White space has been encountered only white space or comma expected ENTER_OPERAND_STATE = 4, // Comma has been encountered, waiting for first digit of operand white space allowed OPERAND_STATE = 5, // First digit of operand has been encountered, remain in this state until white space or close brace is encountered. END_OPERAND_STATE = 6, // White space has been encountered, waiting for close brace to end statement END_STATEMENT_STATE = 7, // Close brace has been encountered, comma or new line expected DONE_STATE = 8, // Comma has been encountered only legal input is white space or new line ERROR_STATE = 9 } Syntax_State; #define SYNTAX_STATE_ARRAY_SIZE 9 + 1 // (size_t) ERROR_STATE + 1 typedef enum legal_characters_that_cause_transitions { OPENBRACE_STATE_TRANSITION = 0, // This needs to be the same as OPENBRACE in Syntax_Check_List_Items CLOSEBRACE_STATE_TRANSITION = 1, // This needs to be the same as CLOSEBRACE in Syntax_Check_List_Items COMMA_STATE_TRANSITION = 2, // This needs to be the same as COMMA in Syntax_Check_List_Items ALPHA_STATE_TRANSITION = 3, DIGIT_STATE_TRANSITION = 4, WHITESPACE_STATE_TRANSITION = 5, EOL_STATE_TRANSITION = 6, // End of Line ILLEGAL_CHAR_TRANSITION = 7 } State_Transition_Characters; #define TRANSITION_ARRAY_SIZE 7 + 1 // ILLEGAL_CHAR_TRANSITION + 1 typedef struct syntax_state_transition { Syntax_State current_state; Syntax_State transition_on_char_type[TRANSITION_ARRAY_SIZE]; } Syntax_State_Transition; #define MAX_COMMA 2 #define MAX_OPEN_BRACE 1 #define MAX_CLOSE_BRACE 1 #define MAX_OPCODE 1 #define MAX_OPERAND 1 #define MAX_WHITE_SPACE 200 extern Syntax_State lexical_analyzer(Syntax_State current_state, unsigned char input, unsigned syntax_check_list[]); extern void deactivate_lexical_analyzer(void); #endif // SYNTAX_STATE_MACHINE_H </code></pre> <p><strong>lexical_analyzer.c</strong></p> <pre><code>/* * lexical_analyzer.c * * The Syntax State Machine is a simple lexical analyzer. Given the current syntax * state and the new input character what is the new syntax state. State machines * can be represented as tables. Table implementation of a state machine uses * more memory but performs faster, the lexical analyser programs Flex and LEX * generate tables to implement lexical analysis. * * This module uses enums to make the states and transitions easier to understand. * */ #include &quot;lexical_analyzer.h&quot; #ifdef UNIT_TESTING #include &quot;common_unit_test_logic.h&quot; #else #include &quot;common_program_logic.h&quot; #endif #include &lt;ctype.h&gt; #include &lt;stdbool.h&gt; #include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;string.h&gt; /* * This function returns the table that represents the current syntactic state * and the new state that each possible legal into can go to from the current * state. If this function is successful the function deallocate_next_states() * should be called when the lexical analisys is done. * * To allow the parser to report as many errors as possible per statement * not all errors result in ERROR_STATE, missing required items are reported * in a separate data structure. The decision to report the error is made * at the parser level. * * Columns in table below * OPENBRACE_STATE_TRANSITION = 0, * CLOSEBRACE_STATE_TRANSITION = 1, * COMMA_STATE_TRANSITION = 2, * ALPHA_STATE_TRANSITION = 3, * DIGIT_STATE_TRANSITION = 4, * WHITESPACE_STATE_TRANSITION = 5, * EOL_STATE_TRANSITION = 6 // End of Line * ILLEGAL_CHAR_TRANSITION = 7 * * Rows in table below * START_STATE = 0, Start of a new line, only white space or open brace is really expected * ENTER_OPCODE_STATE = 1, Open brace encountered, waiting for opcode (first alpha character) white space or alpha is expected * OPCODE_STATE = 2, Open brace and first leter of opcode have been encoutered more alpha, white space or comma expected * END_OPCODE_STATE = 3, White space has been encountered only white space or comma expected * ENTER_OPERAND_STATE = 4, Comma has been encountered, waiting for first digit of operand white space allowed * OPERAND_STATE = 5, First digit of operand has been encountered, remain in this state until white space or close brace is encountered. * END_OPERAND_STATE = 6, White space has been encountered, waiting for close brace to end statement * END_STATEMENT_STATE = 7, Close brace has been encountered, comma or new line expected * DONE_STATE = 8, Comma has been encountered only legal input is white space or new line * ERROR_STATE = 9 */ static Syntax_State_Transition* allocate_next_states_once = NULL; static Syntax_State_Transition* get_or_create_next_states(void) { if (allocate_next_states_once) { return allocate_next_states_once; } allocate_next_states_once = calloc(((size_t)ERROR_STATE) + 1, sizeof(*allocate_next_states_once)); if (!allocate_next_states_once) { report_error_generic(&quot;In create_next_states(), memory allocation for next_states failed\n&quot;); return allocate_next_states_once; } allocate_next_states_once[START_STATE] = (Syntax_State_Transition){ START_STATE, {ENTER_OPCODE_STATE, ERROR_STATE, ENTER_OPERAND_STATE, OPCODE_STATE, OPERAND_STATE, START_STATE, DONE_STATE, ERROR_STATE} }; allocate_next_states_once[ENTER_OPCODE_STATE] = (Syntax_State_Transition){ ENTER_OPCODE_STATE, {ENTER_OPCODE_STATE, END_STATEMENT_STATE, ENTER_OPERAND_STATE, OPCODE_STATE, OPERAND_STATE, ENTER_OPCODE_STATE, ERROR_STATE, ERROR_STATE} }; allocate_next_states_once[OPCODE_STATE] = (Syntax_State_Transition){OPCODE_STATE, {ERROR_STATE, END_STATEMENT_STATE, ENTER_OPERAND_STATE, OPCODE_STATE, OPERAND_STATE, END_OPCODE_STATE, ERROR_STATE, ERROR_STATE} }; allocate_next_states_once[END_OPCODE_STATE] = (Syntax_State_Transition){ END_OPCODE_STATE, {ERROR_STATE, END_STATEMENT_STATE, ENTER_OPERAND_STATE, ERROR_STATE, OPERAND_STATE, END_OPCODE_STATE, ERROR_STATE, ERROR_STATE} }; allocate_next_states_once[ENTER_OPERAND_STATE] = (Syntax_State_Transition){ ENTER_OPERAND_STATE, {ERROR_STATE, END_STATEMENT_STATE, DONE_STATE, ERROR_STATE, OPERAND_STATE, ENTER_OPERAND_STATE, ERROR_STATE} }; allocate_next_states_once[OPERAND_STATE] = (Syntax_State_Transition){ OPERAND_STATE, {ERROR_STATE, END_STATEMENT_STATE, DONE_STATE, ERROR_STATE, OPERAND_STATE, END_OPERAND_STATE, ERROR_STATE, ERROR_STATE} }; allocate_next_states_once[END_OPERAND_STATE] = (Syntax_State_Transition){ END_OPERAND_STATE, {ERROR_STATE, END_STATEMENT_STATE, DONE_STATE, ERROR_STATE, ERROR_STATE, END_OPERAND_STATE, ERROR_STATE, ERROR_STATE} }; allocate_next_states_once[END_STATEMENT_STATE] = (Syntax_State_Transition){ END_STATEMENT_STATE, {ERROR_STATE, END_STATEMENT_STATE, DONE_STATE, ERROR_STATE, ERROR_STATE, END_STATEMENT_STATE, DONE_STATE, ERROR_STATE} }; allocate_next_states_once[DONE_STATE] = (Syntax_State_Transition){ DONE_STATE, {ERROR_STATE, ERROR_STATE, DONE_STATE, ERROR_STATE, ERROR_STATE, DONE_STATE, DONE_STATE, ERROR_STATE} }; allocate_next_states_once[ERROR_STATE] = (Syntax_State_Transition){ ERROR_STATE, {ERROR_STATE, ERROR_STATE, ERROR_STATE, ERROR_STATE, ERROR_STATE, ERROR_STATE, ERROR_STATE, ERROR_STATE} }; return allocate_next_states_once; } void deactivate_lexical_analyzer(void) { free(allocate_next_states_once); } static bool is_legal_in_hex_number(unsigned char input) { bool is_legal = false; switch (toupper(input)) { case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'X': is_legal = true; break; default: is_legal = false; break; } return is_legal; } /* * The calling function has already gone through one filter so it is assured that * the input character is an alpha and not some other type of character. */ static State_Transition_Characters get_alpha_input_transition_character_type(unsigned char input, Syntax_State current_state) { State_Transition_Characters character_type = ILLEGAL_CHAR_TRANSITION; switch (current_state) { case ENTER_OPERAND_STATE: case OPERAND_STATE: case END_OPERAND_STATE: character_type = (is_legal_in_hex_number(input)) ? DIGIT_STATE_TRANSITION : ALPHA_STATE_TRANSITION; break; default: character_type = ALPHA_STATE_TRANSITION; break; } return character_type; } /* * The calling function has already gone through several filter so it is assured * that the input character is not an alpha, digit, white space or end of line. */ static State_Transition_Characters get_puctuation_transition_character_type(unsigned char input) { State_Transition_Characters character_type = ILLEGAL_CHAR_TRANSITION; switch (input) { case ',': character_type = COMMA_STATE_TRANSITION; break; case '{': character_type = OPENBRACE_STATE_TRANSITION; break; case '}': character_type = CLOSEBRACE_STATE_TRANSITION; break; default: character_type = ILLEGAL_CHAR_TRANSITION; break; } return character_type; } /* * The calling function has already gone through several filter so it is assured * that the input character is not an alpha, digit, white space or end of line. */ static State_Transition_Characters get_whitespace_transition_character_type(unsigned char input) { State_Transition_Characters character_type = ILLEGAL_CHAR_TRANSITION; switch (input) { case ' ': case '\t': character_type = WHITESPACE_STATE_TRANSITION; break; case '\n': case '\r': character_type = EOL_STATE_TRANSITION; break; default: character_type = ILLEGAL_CHAR_TRANSITION; break; } return character_type; } /* * Rather than create a table indexed by each and every character in the character * set save space using ctype functions for large ranges. Also save time on * implementation and debugging. */ static State_Transition_Characters get_transition_character_type(unsigned char input, Syntax_State current_state) { State_Transition_Characters character_type = ILLEGAL_CHAR_TRANSITION; if (isalpha(input)) { character_type = get_alpha_input_transition_character_type(input, current_state); } else if (isdigit(input)) { character_type = DIGIT_STATE_TRANSITION; } else if (isspace(input)) { character_type = get_whitespace_transition_character_type(input); } else { character_type = get_puctuation_transition_character_type(input); } return character_type; } /* * syntax_check_list provides additional error information for the parser. */ static void collect_error_reporting_data(Syntax_State current_state, State_Transition_Characters character_type, unsigned syntax_check_list[]) { switch (character_type) { case WHITESPACE_STATE_TRANSITION: // This section is for character types that case EOL_STATE_TRANSITION: // are a legal first character on a line break; case COMMA_STATE_TRANSITION: // Punctuation required by grammer on case OPENBRACE_STATE_TRANSITION: // every line case CLOSEBRACE_STATE_TRANSITION: { unsigned maximum_allowed[] = { MAX_OPEN_BRACE, MAX_CLOSE_BRACE, MAX_COMMA }; syntax_check_list[character_type]++; if (syntax_check_list[character_type] &gt; maximum_allowed[character_type]) { syntax_check_list[MULTIPLESTATEMENTSONELINE]++; } } // flow through so that punctuation is handeled like all other character default: if (current_state == START_STATE &amp;&amp; character_type != OPENBRACE_STATE_TRANSITION) { syntax_check_list[ILLEGALFIRSTCHAR]++; } break; } } /* * A design decision was made to allocate next_states only once to save overhead in * this function and to not force the parser to allocate the memory. * * This function performs the lexical analysis for the parser, it uses a state machine * implemented as a table to do this. That table is the next_states variable. */ Syntax_State lexical_analyzer(Syntax_State current_state, unsigned char input, unsigned syntax_check_list[]) { Syntax_State_Transition* next_states = get_or_create_next_states(); if (!next_states) { fprintf(error_out_file, &quot;In %s: Memory allocation error in get_or_create_next_states()\n&quot;, &quot;get_state_transition_collect_parser_error_data&quot;); fprintf(error_out_file, &quot;Unable to perform lexical analisys! Exiting program.&quot;); exit(EXIT_FAILURE); } State_Transition_Characters character_type = get_transition_character_type(input, current_state); collect_error_reporting_data(current_state, character_type, syntax_check_list); return next_states[current_state].transition_on_char_type[character_type]; } #ifdef UNIT_TESTING #include &quot;internal_sytax_state_tests.c&quot; #endif </code></pre> <h2>Unit Testing Code</h2> <p><strong>internal_sytax_state_tests.h</strong></p> <pre><code>#ifndef INTERNAL_SYNTAX_STATE_TEST_H #define INTERNAL_SYNTAX_STATE_TEST_H #include &lt;stdbool.h&gt; extern bool internal_tests_on_all_state_transitions(unsigned test_step); extern bool unit_test_lexical_analyzer(unsigned test_step); #endif // INTERNAL_SYNTAX_STATE_TEST_H </code></pre> <p><strong>internal_sytax_state_tests.c</strong></p> <pre><code>/* * internal_sytax_state_tests.c * * This file contains both internal syntax state machine unit tests, and unit tests * for the public interface of the lexitcal analyzer these test functions test the * very basic functions that are the building blocks of the public interface, they are * declared static so these tests must be included in the syntax_state_machine.c file * rather than externally. */ #ifndef INTERNAL_SYNTAX_STATE_TESTS_C #define INTERNAL_SYNTAX_STATE_TESTS_C #include &quot;internal_sytax_state_tests.h&quot; #include &quot;lexical_analyzer_test_data.h&quot; static char *state_name_for_printing(Syntax_State state) { char* state_names[SYNTAX_STATE_ARRAY_SIZE] = { &quot;START_STATE&quot;, &quot;ENTER_OPCODE_STATE&quot;, &quot;OPCODE_STATE&quot;, &quot;END_OPCODE_STATE&quot;, &quot;ENTER_OPERAND_STATE&quot;, &quot;OPERAND_STATE&quot;, &quot;END_OPERAND_STATE&quot;, &quot;END_STATEMENT_STATE&quot;, &quot;DONE_STATE&quot;, &quot;ERROR_STATE&quot; }; return state_names[(size_t)state]; } static char* transition_character[TRANSITION_ARRAY_SIZE] = { &quot;Transition on {&quot;, &quot;Transition on }&quot;, &quot;Transition on ,&quot;, &quot;Transition on Alpha&quot;, &quot;Transition on Digit&quot;, &quot;Transition on White Space&quot;, &quot;Transition on EOL&quot;, &quot;Transition on Illegal Character&quot;, }; #ifdef UNIT_TEST_DEBUG static bool unit_test_syntax_states(size_t test_step) { bool test_passed = true; bool stand_alone = test_step == 0; Syntax_State_Transition* test_transitions = get_or_create_next_states(); if (!test_transitions) { fprintf(error_out_file, &quot;Memory allocation error in get_create_next_states()\n&quot;); return false; } for (size_t state = 0; state &lt; SYNTAX_STATE_ARRAY_SIZE; state++) { char out_buffer[BUFSIZ]; if (stand_alone) { sprintf(out_buffer, &quot;current_state = %s\n&quot;, state_name_for_printing( test_transitions[state].current_state)); log_generic_message(out_buffer); } if (stand_alone) { for (size_t character_index = 0; character_index &lt; TRANSITION_ARRAY_SIZE; character_index++) { sprintf(out_buffer, &quot;\ttransition character = %s\t\tnew state %s\n&quot;, transition_character[character_index], state_name_for_printing( test_transitions[state].transition_on_char_type[character_index])); log_generic_message(out_buffer); } log_generic_message(&quot;\n&quot;); } } return test_passed; } #endif #include &quot;internal_character_transition_unit_tests.c&quot; typedef struct state_test_data { Syntax_State current_state; State_Transition_Characters input_character_state; unsigned syntax_items_checklist[SYNTAX_CHECK_COUNT]; Expected_Syntax_Errors expected_data; } Error_Reporting_Test_Data; static void print_syntax_error_checklist(unsigned syntax_checklist[], char *out_buffer) { for (size_t i = 0; i &lt; SYNTAX_CHECK_COUNT; i++) { char num_buff[8]; if (i &lt; SYNTAX_CHECK_COUNT - 1) { sprintf(num_buff, &quot;%d ,&quot;, syntax_checklist[i]); strcat(out_buffer, num_buff); } else { sprintf(num_buff, &quot;%d} &quot;, syntax_checklist[i]); strcat(out_buffer, num_buff); } } } static void log_all_failure_data_for_unit_test_collect_error_reporting_data( Test_Log_Data* log_data, Error_Reporting_Test_Data test_data, unsigned syntax_check_list[]) { log_test_status_each_step2(log_data); char out_buffer[BUFSIZ]; sprintf(out_buffer, &quot;\tcurrent_state = %s &quot;, state_name_for_printing(test_data.current_state)); strcat(out_buffer, &quot;expected Checklist Values {&quot;); print_syntax_error_checklist(test_data.expected_data.syntax_check_list, out_buffer); strcat(out_buffer, &quot;new checklist value {&quot;); print_syntax_error_checklist(syntax_check_list, out_buffer); strcat(out_buffer, &quot;\n&quot;); log_generic_message(out_buffer); } static bool errors_in_sync(unsigned syntax_check_list[], Expected_Syntax_Errors expected_errors) { bool syntax_check_list_in_sync = true; for (size_t i = 0; i &lt; SYNTAX_CHECK_COUNT; i++) { if (syntax_check_list[i] != expected_errors.syntax_check_list[i]) { syntax_check_list_in_sync = false; } } return syntax_check_list_in_sync; } static bool run_error_checking_unit_tests( Test_Log_Data *log_data, size_t positive_path_test_count, Error_Reporting_Test_Data test_data[], size_t test_runs) { bool test_passed = true; log_start_test_path(log_data); for (size_t test_count = 0; test_count &lt; test_runs; test_count++) { log_data-&gt;status = true; if (test_count == positive_path_test_count) { log_end_test_path(log_data); log_data-&gt;path = &quot;Negative&quot;; log_start_test_path(log_data); } unsigned syntax_check_list[SYNTAX_CHECK_COUNT]; memcpy(&amp;syntax_check_list[0], &amp;test_data[test_count].syntax_items_checklist[0], sizeof(syntax_check_list)); collect_error_reporting_data(test_data[test_count].current_state, test_data[test_count].input_character_state, syntax_check_list); if (!errors_in_sync(syntax_check_list, test_data[test_count].expected_data)) { log_data-&gt;status = false; log_all_failure_data_for_unit_test_collect_error_reporting_data( log_data, test_data[test_count], syntax_check_list); } else { log_test_status_each_step2(log_data); } if (!log_data-&gt;status &amp;&amp; test_passed) { test_passed = log_data-&gt;status; } } log_end_test_path(log_data); return test_passed; } static Error_Reporting_Test_Data* init_error_report_data(size_t *positive_path_test_count, size_t *test_data_size) { Error_Reporting_Test_Data static_global_test_data[] = { // Start with positive test path data {START_STATE, OPENBRACE_STATE_TRANSITION, {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, {0, {1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}}}, {OPERAND_STATE, CLOSEBRACE_STATE_TRANSITION, {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, {0, {0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0}}}, {END_STATEMENT_STATE, COMMA_STATE_TRANSITION, {0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0}, {0, {0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0}}}, {OPCODE_STATE, COMMA_STATE_TRANSITION, {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, {0, {0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0}}}, {END_OPCODE_STATE, COMMA_STATE_TRANSITION, {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, {0, {0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0}}}, {END_OPCODE_STATE, WHITESPACE_STATE_TRANSITION, {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, {0, {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}}}, {START_STATE, WHITESPACE_STATE_TRANSITION, {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, {0, {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}}}, {OPERAND_STATE, WHITESPACE_STATE_TRANSITION, {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, {0, {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}}}, {OPCODE_STATE, WHITESPACE_STATE_TRANSITION, {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, {0, {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}}}, {END_OPCODE_STATE, EOL_STATE_TRANSITION, {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, {0, {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}}}, {START_STATE, EOL_STATE_TRANSITION, {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, {0, {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}}}, {OPERAND_STATE, EOL_STATE_TRANSITION, {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, {0, {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}}}, {OPCODE_STATE, EOL_STATE_TRANSITION, {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, {0, {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}}}, // Negative test path data {DONE_STATE, OPENBRACE_STATE_TRANSITION, {1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, {0, {2, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0}}}, {DONE_STATE, COMMA_STATE_TRANSITION, {0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0}, {0, {0, 0, 3, 0, 0, 0, 0, 0, 1, 0, 0}}}, {DONE_STATE, CLOSEBRACE_STATE_TRANSITION, {0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0}, {0, {0, 2, 0, 0, 0, 0, 0, 0, 1, 0, 0}}}, }; *test_data_size = (sizeof(static_global_test_data) / sizeof(Error_Reporting_Test_Data)); *positive_path_test_count = 13; // Count the lines of test_data above between the comments above. Error_Reporting_Test_Data* test_data = calloc(*test_data_size, sizeof(*test_data)); for (size_t i = 0; i &lt; *test_data_size; i++) { memcpy(&amp;test_data[i], &amp;static_global_test_data[i], sizeof(*test_data)); } return test_data; } static bool unit_test_collect_error_reporting_data(unsigned test_step) { bool test_passed = true; char buffer[BUFSIZ]; Test_Log_Data* log_data = create_and_init_test_log_data( &quot;unit_test_collect_error_reporting_data&quot;, test_passed, &quot;Positive&quot;, test_step == 0); if (!log_data) { report_create_and_init_test_log_data_memory_failure( &quot;unit_test_collect_error_reporting_data&quot;); return false; } size_t positivie_path_count = 0; size_t test_count = 0; Error_Reporting_Test_Data* test_data = init_error_report_data(&amp;positivie_path_count, &amp;test_count); if (!test_data) { fprintf(error_out_file, &quot;Memory allocation of test_data failed in %s&quot;, log_data-&gt;function_name); return false; } if (log_data-&gt;stand_alone) { sprintf(buffer, &quot;STARTING internal unit test for %s()\n\n&quot;, &quot;collect_error_reporting_data&quot;); log_generic_message(buffer); } test_passed = run_error_checking_unit_tests(log_data, positivie_path_count, test_data, test_count); if (log_data-&gt;stand_alone) { sprintf(buffer, &quot;\nENDING internal unit test for %s(\n\n&quot;, &quot;collect_error_reporting_data&quot;); log_generic_message(buffer); } free(test_data); free(log_data); return test_passed; } typedef bool (*state_machine_unit_test_function)(size_t test_step); typedef struct unit_test_functions_and_args { char* test_name; state_machine_unit_test_function func; } State_Machine_Unit_Test_Functions; /* * This function unit tests all the internal functions that support the * function get_state_transition_collect_parser_error_data(). If any of * these unit tests fail the unit test for lexical_analyzer() will not * execute. */ bool internal_tests_on_all_state_transitions(unsigned test_step) { bool all_tests_passed = true; char buffer[BUFSIZ]; State_Machine_Unit_Test_Functions unit_tests[] = { #ifdef UNIT_TEST_DEBUG {&quot;unit_test_syntax_states&quot;, unit_test_syntax_states}, #endif {&quot;unit_test_get_alpha_input_transition_character_type&quot;, unit_test_get_alpha_input_transition_character_type}, {&quot;unit_test_get_transition_character_type&quot;, unit_test_get_transition_character_type}, {&quot;unit_test_collect_error_reporting_data&quot;, unit_test_collect_error_reporting_data}, }; size_t test_max = (sizeof(unit_tests) / sizeof(*unit_tests)); for (size_t test_count = 0; test_count &lt; test_max; test_count++) { bool test_passed = unit_tests[test_count].func(test_step); sprintf(buffer, &quot;\nSyntax Machine Internal Unit Test %zd: %s : %s\n\n&quot;, test_count + 1, unit_tests[test_count].test_name, (test_passed) ? &quot;Passed&quot; : &quot;Failed&quot;); log_generic_message(buffer); // if one test already failed we are good if (all_tests_passed) { all_tests_passed = test_passed; } } return all_tests_passed; } static void report_syntax_errors(unsigned necessary_items[]) { char* error_strings[SYNTAX_CHECK_COUNT]; error_strings[OPENBRACE] = &quot;Missing the opening brace.&quot;; error_strings[CLOSEBRACE] = &quot;Missing the closing brace.&quot;; error_strings[COMMA] = &quot;Missing comma(s)&quot;; error_strings[LEGALOPCODE] = &quot;Missing or unknow opcode&quot;; error_strings[LEGALOPERAND] = &quot;Missing operand or operand out of range&quot;; error_strings[ILLEGALOPCODE] = &quot;Unknown Opcode.&quot;; error_strings[ILLEGALFIRSTCHAR] = &quot;Illegal character in column 1 (are you missing the opening brace { )&quot;; error_strings[MULTIPLESTATEMENTSONELINE] = &quot;Only one program step per line&quot;; error_strings[ILLEGALCHAR] = &quot;Illegal Character&quot;; error_strings[MISSINGCOMMA] = &quot;Missing comma(s)&quot;; for (size_t i = 0; i &lt; SYNTAX_CHECK_COUNT; i++) { char buffer[BUFSIZ]; if (i &gt;= ILLEGALOPCODE &amp;&amp; necessary_items[i]) { sprintf(buffer, &quot;\t%s\n&quot;, error_strings[i]); log_generic_message(buffer); } else if (i &lt; ILLEGALOPCODE &amp;&amp; !necessary_items[i]) { sprintf(buffer, &quot;\t%s\n&quot;, error_strings[i]); log_generic_message(buffer); } } } static bool check_syntax_check_list_and_report_errors_as_parser_would( unsigned syntax_check_list[], Syntax_State state, unsigned char* text_line, size_t statement_number, Expected_Syntax_Errors* expected_errors, char *parser_generated_error) { unsigned error_count = 0; bool syntax_check_list_in_sync = true; for (size_t i = 0; i &lt; SYNTAX_CHECK_COUNT; i++) { error_count += (!syntax_check_list[i] &amp;&amp; i &lt; ILLEGALOPCODE) ? 1 : ((i &gt;= ILLEGALOPCODE &amp;&amp; syntax_check_list[i]) ? 1 : 0); if (syntax_check_list[i] != expected_errors-&gt;syntax_check_list[i] &amp;&amp; i != MULTIPLESTATEMENTSONELINE) { syntax_check_list_in_sync = false; } } if (error_count != expected_errors-&gt;error_count) { syntax_check_list_in_sync = false; } char* eol_p = strrchr((const char *)text_line, '\n'); if (eol_p) { *eol_p = '\0'; } char buffer[BUFSIZ]; if (state == ERROR_STATE || error_count) { sprintf(buffer, &quot;\n\nStatement %d (%s) has the following syntax errors\n&quot;, statement_number + 1, text_line); log_generic_message(buffer); if (parser_generated_error) { log_generic_message(parser_generated_error); } report_syntax_errors(syntax_check_list); } else { if (expected_errors-&gt;error_count) { sprintf(buffer, &quot;\n\nStatement %d (%s)\n&quot;, statement_number + 1, text_line); log_generic_message(buffer); sprintf(buffer, &quot;Expected syntax errors were:\n&quot;); log_generic_message(buffer); report_syntax_errors(expected_errors-&gt;syntax_check_list); } } return syntax_check_list_in_sync; } static char* error_state(unsigned char* text_line, size_t statement_number, unsigned char* current_character) { char* parser_generated_error; char buffer[BUFSIZ]; char* eol_p = strrchr((const char*)text_line, '\n'); if (eol_p) { *eol_p = '\0'; } sprintf(buffer, &quot;Syntax Error line %zd %s column %d unexpected character '%c' : skipping rest of line.\n&quot;, statement_number + 1, text_line, (int)(current_character - text_line), *current_character); parser_generated_error = _strdup(buffer); return parser_generated_error; } /* * Provides debug data when a unit test fails. */ static void report_lexical_analyzer_test_failure(Syntax_State current_state, unsigned syntax_check_list[], Expected_Syntax_Errors* expected_errors) { char out_buffer[BUFSIZ]; sprintf(out_buffer, &quot;\tcurrent_state = %s expected error count = %d &quot;, state_name_for_printing(current_state), expected_errors-&gt;error_count); strcat(out_buffer, &quot;expected Checklist Values {&quot;); print_syntax_error_checklist(expected_errors-&gt;syntax_check_list, out_buffer); strcat(out_buffer, &quot;new checklist values {&quot;); print_syntax_error_checklist(syntax_check_list, out_buffer); strcat(out_buffer, &quot;\n&quot;); log_generic_message(out_buffer); } /* * This test parses a signle statement as the parser would. It directly calls * the lexical analiyzer for each character. */ static bool unit_test_final_lexical_parse_statement(unsigned char* text_line, size_t statement_number, Test_Log_Data* log_data, Expected_Syntax_Errors *expected_errors) { bool test_passed = true; unsigned syntax_check_list[SYNTAX_CHECK_COUNT]; memset(&amp;syntax_check_list[0], 0, sizeof(syntax_check_list)); Syntax_State current_state = START_STATE; unsigned char* opcode_start = NULL; unsigned char* opcode_end = NULL; unsigned char* operand_start = NULL; char* parser_generated_error = NULL; unsigned char* current_character = text_line; while (*current_character &amp;&amp; current_state != ERROR_STATE) { Syntax_State new_state = lexical_analyzer(current_state, *current_character, syntax_check_list); if (new_state != current_state) { switch (new_state) { case ERROR_STATE: { parser_generated_error = error_state(text_line, statement_number, current_character); }; break; case OPCODE_STATE: opcode_start = current_character; syntax_check_list[LEGALOPCODE]++; break; case END_OPCODE_STATE: opcode_end = current_character; break; case OPERAND_STATE: operand_start = current_character; syntax_check_list[LEGALOPERAND]++; if (!syntax_check_list[COMMA]) { syntax_check_list[MISSINGCOMMA]++; } break; case END_OPERAND_STATE: opcode_end = current_character; break; default: break; } current_state = new_state; } current_character++; } bool syntax_check_list_in_sync = check_syntax_check_list_and_report_errors_as_parser_would( syntax_check_list, current_state, text_line, statement_number, expected_errors, parser_generated_error); if (!syntax_check_list_in_sync) { report_lexical_analyzer_test_failure(current_state, syntax_check_list, expected_errors); test_passed = false; log_data-&gt;status = false; } log_test_status_each_step2(log_data); free(parser_generated_error); return test_passed; } bool run_parse_program_loop(Test_Log_Data* log_data, Lexical_Analyzer_Test_Data* test_data) { bool test_passed = true; unsigned char** test_program = test_data-&gt;test_program; Expected_Syntax_Errors* expected_errors = test_data-&gt;expected_errors; for (size_t test_count = 0; test_count &lt; test_data-&gt;test_program_size; test_count++) { log_data-&gt;status = true; if (!unit_test_final_lexical_parse_statement(test_program[test_count], test_count, log_data, &amp;expected_errors[test_count])) { test_passed = log_data-&gt;status; } } return test_passed; } /* * This final test imitates the parser and parses an entire program. There are * 2 programs, one without syntax errors and one with syntax errors. The positive * test path is the one without syntax errors and the negative path is the one * with syntax errors. */ bool unit_test_parse_statements_for_lexical_analysis(unsigned test_step) { bool test_passed = true; Test_Log_Data* log_data = create_and_init_test_log_data( &quot;unit_test_parse_statements_for_lexical_analysis&quot;, test_passed, &quot;Positive&quot;, test_step == 0); Lexical_Analyzer_Test_Data* positive_path_data = init_positive_path_data_for_lexical_analysis(log_data); if (!positive_path_data) { return false; } log_start_test_path(log_data); if (!run_parse_program_loop(log_data, positive_path_data)) { test_passed = log_data-&gt;status; } log_end_test_path(log_data); Lexical_Analyzer_Test_Data* negative_path_data = init_negative_path_data_for_lexical_analysis(log_data); if (!negative_path_data) { return false; } log_data-&gt;path = &quot;Negative&quot;; log_start_test_path(log_data); char* explanation = &quot;Only statements with syntax errors are printed&quot; &quot; Statement 1 and statement 8 do not contain syntax errors\n\n&quot;; log_generic_message(explanation); if (!run_parse_program_loop(log_data, negative_path_data)) { test_passed = log_data-&gt;status; } log_end_test_path(log_data); deallocate_lexical_test_data(positive_path_data); deallocate_lexical_test_data(negative_path_data); free(log_data); return test_passed; } /* * Unit test the public interface in syntax_state_machine.c. This function * assumes that internal_tests_on_all_state_transitions has been previously * called and that all component functions have been unit tested first. The * public interface is tested in 2 ways, first with test data and then * parsing statements as the parser will. */ bool unit_test_lexical_analyzer(unsigned test_step) { bool test_passed = true; char buffer[BUFSIZ]; Test_Log_Data* log_data = create_and_init_test_log_data( &quot;unit_test_lexical_analyzer&quot;, test_passed, &quot;Positive&quot;, test_step == 0); if (!log_data) { report_create_and_init_test_log_data_memory_failure(&quot;unit_test_lexical_analyzer&quot;); return false; } if (log_data-&gt;stand_alone) { sprintf(buffer, &quot;STARTING unit test for %s\n\n&quot;, log_data-&gt;function_name); log_generic_message(buffer); } test_passed = unit_test_parse_statements_for_lexical_analysis(test_step); if (log_data-&gt;stand_alone) { sprintf(buffer, &quot;\nENDING unit test for %s\n\n&quot;, log_data-&gt;function_name); log_generic_message(buffer); } free(log_data); return test_passed; } #endif // INTERNAL_SYNTAX_STATE_TESTS_C </code></pre> <p><strong>state_machine_unit_test_main.h</strong></p> <pre><code>#ifndef SYNTAX_STATE_MACHINE_UNIT_TEST_MAIN_H #define SYNTAX_STATE_MACHINE_UNIT_TEST_MAIN_H extern bool run_all_syntax_state_machine_unit_tests(unsigned test_step); #endif // SYNTAX_STATE_MACHINE_UNIT_TEST_MAIN_H </code></pre> <p>Since this program is designed to be part of larger unit tests <code>main()</code> is contained within ifdef/endif. It will only be compiled if this is a stand alone test.</p> <p><strong>state_machine_unit_test_main.c</strong></p> <pre><code>// state_machine_unit_test.c : This file contains the 'main' function. Program execution begins and ends there. // #include &quot;common_unit_test_logic.h&quot; #include &quot;lexical_analyzer.h&quot; #include &quot;internal_sytax_state_tests.h&quot; #include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; bool run_all_syntax_state_machine_unit_tests(unsigned test_step) { bool all_unit_tests_passed = true; char buffer[BUFSIZ]; sprintf(buffer, &quot;Unit Test %zd: Starting Lexical Analizer Unit Tests \n\n&quot;, test_step); log_generic_message(buffer); all_unit_tests_passed = internal_tests_on_all_state_transitions(test_step); if (all_unit_tests_passed) { // test the public interface for the lexical analyzer all_unit_tests_passed = unit_test_lexical_analyzer(test_step); } sprintf(buffer, &quot;Unit Test %zd: run_all_syntax_state_machine_unit_tests(unsigned &quot; &quot;test_step) : %s\n\n&quot;, test_step, all_unit_tests_passed ? &quot;Passed&quot; : &quot;Failed&quot;); log_generic_message(buffer); deactivate_lexical_analyzer(); sprintf(buffer, &quot;Unit Test %zd: Ending Lexical Analizer Unit Tests \n\n&quot;, test_step); log_generic_message(buffer); return all_unit_tests_passed; } #ifdef LEXICAL_UNIT_TEST_ONLY int main() { error_out_file = stderr; int passed = EXIT_SUCCESS; if (!init_vm_error_reporting(NULL) || !init_unit_tests(&quot;syntax_state_machine_unit_test_log.txt&quot;)) { return EXIT_FAILURE; } if (!run_all_syntax_state_machine_unit_tests(0)) { passed = EXIT_FAILURE; } close_unit_tests(); disengage_error_reporting(); return passed; } #endif </code></pre>
[]
[ { "body": "<h1>Answers to your questions</h1>\n<blockquote>\n<p>I learned C a long time ago from K&amp;R “The C Programming Language” Version 1 (pre C89/C90).</p>\n</blockquote>\n<p>I started with K&amp;R C's second revision, but that doesn't mean I didn't keep up with the changes over time. C99 brought many useful improvements that I happily use every day. Your code looks C99 as well, since you are using <code>bool</code> and <code>//</code> comments.</p>\n<blockquote>\n<ol>\n<li>Other than compiling this <code>–O3</code> what can I do to optimize this code?</li>\n</ol>\n</blockquote>\n<p>Try to do as much as possible at compile time instead of run time. For example, instead of having <code>get_or_create_next_states()</code>, it seems to me you can create a static array, like so:</p>\n<pre><code>static Syntax_State_Transition next_states[] = {\n [START_STATE] = {START_STATE, {ENTER_OPCODE_STATE, ERROR_STATE, ENTER_OPERAND_STATE, OPCODE_STATE, OPERAND_STATE, START_STATE, DONE_STATE, ERROR_STATE}},\n [ENTER_OPCODE_STATE] = {...},\n ...\n};\n</code></pre>\n<p>The above uses C99 designated initializers. If you don't want to use C99, you can omit the designations, but then you have to remember the correct order.</p>\n<blockquote>\n<ol start=\"2\">\n<li>Are there any features in the more modern versions of C that could reduce the amount of code? There are currently more 1300 lines of commented code to test the 376 lines of commented code in lexical_analyzer.c and lexical_analyzer.h.</li>\n</ol>\n</blockquote>\n<p>There are a some things that could reduce a few lines of code. For example, when logging messages, you write:</p>\n<pre><code>sprintf(buffer, &quot;\\nSome message, %s\\n\\n&quot;, some_variable);\nlog_generic_message(buffer);\n</code></pre>\n<p>Apart from <code>sprintf()</code> being unsafe, you can make <code>log_generic_message()</code> a <a href=\"https://en.cppreference.com/w/c/variadic\" rel=\"nofollow noreferrer\">variadic function</a> that takes a format strings and a variable number of arguments, like so:</p>\n<pre><code>void log_generic_message(const char *format, ...)\n{\n char buffer[...];\n va_list args;\n\n va_start(args, format);\n vsnprintf(buffer, sizeof buffer, format, args);\n va_end(args);\n\n ...\n}\n</code></pre>\n<p>This way, you can just write:</p>\n<pre><code>log_generic_message(&quot;\\nSome message, %s\\n\\n&quot;, some_variable);\n</code></pre>\n<p>You can also use <a href=\"https://gcc.gnu.org/onlinedocs/gcc/Common-Function-Attributes.html#index-format-function-attribute\" rel=\"nofollow noreferrer\"><code>__attribute__((format(...)))</code></a> to tell the compiler that you expect a <code>printf</code>-like format string, and it can then give the same warnings it will give if you have mismatching conversion specifiers and arguments. Of course support for function attributes might vary between compilers and cannot be used portably, unless you add some checks for it and <code>#ifdef</code> it out when the compiler doesn't support it.</p>\n<p>There's a <code>memset()</code> that can be replaced using an array initializer:</p>\n<pre><code>unsigned syntax_check_list[SYNTAX_CHECK_COUNT];\nmemset(&amp;syntax_check_list[0], 0, sizeof(syntax_check_list));\n</code></pre>\n<p>Can be rewritten as:</p>\n<pre><code>unsigned syntax_check_list[SYNTAX_CHECK_COUNT] = {0};\n</code></pre>\n<blockquote>\n<ol start=\"3\">\n<li>Is there archaic C usage that is not customary to use anymore?</li>\n</ol>\n</blockquote>\n<p>Not that I see.</p>\n<blockquote>\n<ol start=\"4\">\n<li>Are the unit tests missing any test cases, especially edge cases?</li>\n</ol>\n</blockquote>\n<p>I'm not sure.</p>\n<blockquote>\n<ol start=\"5\">\n<li>Are there any memory leaks?</li>\n</ol>\n</blockquote>\n<p>Not that I see.</p>\n<blockquote>\n<ol start=\"6\">\n<li>Is the code readable?</li>\n</ol>\n</blockquote>\n<p>Well, mostly. But I would personally have used a lexer generator like <a href=\"https://en.wikipedia.org/wiki/Flex_lexical_analyser\" rel=\"nofollow noreferrer\">flex</a>, so I can write the lexer in a higher level language, and not have to deal with writing the code myself. Even though the language you are implementing is very simple, the lexer you wrote is already quite large, and if the language would get more complex, your lexer will quickly become unmaintainable, I'm afraid.</p>\n<blockquote>\n<ol start=\"7\">\n<li>I don’t like the fact that I need to include the unit test files in lexical_analyzer.c do you see any way around this?</li>\n</ol>\n</blockquote>\n<p>Yes, do it the other way around: in <code>internal_sytax_state_tests.c</code>, add <code>#include &quot;lexical_analyzer.c&quot;</code>. Alternatively, if you don't want to <code>#include</code> .c files into each other, then you have to find some way to remove the <code>static</code> from functions that you want to be able to unit test. A typical way to do that is:</p>\n<pre><code>#ifdef UNIT_TESTING\n#define STATIC\n#else\n#define STATIC static\n#endif\n\n...\n\nSTATIC bool is_legal_in_hex_number(unsigned char input) {\n ...\n}\n</code></pre>\n<p>Then when building the unit test, you can link the unit testing code with a version of <code>lexical_analyzer.c</code> built with <code>UNIT_TESTING</code> defined.</p>\n<blockquote>\n<ol start=\"8\">\n<li>Is the language too complex?</li>\n</ol>\n</blockquote>\n<p>The language is not complex at all, but as you see you already had to write a lot of code to parse it. That's why lexer and parser generators have been created.</p>\n<h1>Use of <code>_strdup()</code></h1>\n<p>The function <code>strdup()</code> is not in any C standard, but it is in POSIX.1-2001. As mentioned by @chux-ReinstateMonica, the C standard reserves identifiers starting with <code>str</code>, so Microsoft decided to not violate that rule and declare <code>_strdup()</code> instead. What I typically do in my own projects that need to be compatible with a certain standard, and where I want to use some commonly available convenience function that is not present in the standards I can safely use in my projects, is to add some check for the presence of the desired function, and if it's not present, either add an alias to a similar function or just write a drop-in replacement. So for example, you could write:</p>\n<pre><code>#ifndef HAVE_STRDUP\n#ifdef HAVE__STRDUP\n#define strdup(x) _strdup(x)\n#else\nstatic char *strdup(const char *x) {\n size_t len = strlen(x) + 1;\n char *s = malloc(len);\n if (s)\n memcpy(s, x, len);\n return s;\n}\n#endif\n</code></pre>\n<p>Then either have a build tool like autoconf figure out which functions are available and <code>#define HAVE_...</code> somewhere, or replace <code>#ifdef HAVE_STRDUP</code> by some other way to check for the availability of that function.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-29T00:26:20.297", "Id": "486977", "Score": "1", "body": "Thank you for the review. While I haven't used Bison and Flex I have used YACC and Lex (a lot actually). When I started this I wasn't even using a state driven array, I didn't think it was going to be that difficult. I don't see how including lexical_analyzer.c in the unit test is any different than the other way around other than it removes the` #ifdef UNIT_TESTING` from lexical_analyzer.c." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-29T05:05:00.003", "Id": "486989", "Score": "2", "body": "\" don't know why they felt the need to create a version with an underscore in front\" --> exactly to allow conditional code like `#define strdup(x) _strdup(x)` [See also](https://stackoverflow.com/a/7582741/2410359). Had they unconditional supplied `strdup()` it would have been non-compliant with C as it collides with reserved name space. In this case, MS is following the standard." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-29T05:29:49.833", "Id": "486991", "Score": "1", "body": "\" If you don't want to use C99\" --> Note: Lots of re-work then changing `//` into `/* */`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-29T07:44:41.637", "Id": "486998", "Score": "2", "body": "@pacmaninbw So what you really don't like is `#include`ing .c files? If you want to avoid that, but still want to unit test `static` functions, then you need to do something like `#ifdef UNIT_TESTING #define STATIC #else #define STATIC static #endif`, and replace all `static` with `STATIC` in lexical_analyzer.c Then you can just link the latter with your unit testing .c files." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-29T07:55:49.600", "Id": "486999", "Score": "2", "body": "@chux-ReinstateMonica Ah, I did not know about C reserving identifiers starting with `str`. I think that rule is violated a lot." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-29T15:55:26.187", "Id": "487047", "Score": "2", "body": "@G.Sliepen Detail: Its a lib thing under \"Future library directions\": \"7.31.13 String handling <string.h> 1 Function names that begin with str, mem, or wcs and a lowercase letter may be added to the declarations in the <string.h> header.\"" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-31T14:29:57.923", "Id": "487246", "Score": "0", "body": "The review has been copied into an md file and posted to the [repository](https://github.com/pacmaninbw/VMWithEditor/tree/Before_First_Code_Review/VMWithEditor/UnitTests/State_Machine_Unit_Test/State_Machine_Unit_Test). In the md file there is a link back to this answer." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-09-09T16:18:33.450", "Id": "488244", "Score": "0", "body": "@G.Sliepen I have linked to this answer from the [follow up question](https://codereview.stackexchange.com/questions/248817/common-unit-testing-code-follow-up/248883#248883). I implemented your suggestion about including the module being tested rather than the test modules, I replaced the usage of `sprintf()` mostly with 2 variadic functions but also with `snprintf()`. The updated code is in the [repository](https://github.com/pacmaninbw/VMWithEditor/tree/master/VMWithEditor)." } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-28T23:00:28.993", "Id": "248581", "ParentId": "248559", "Score": "2" } }, { "body": "<p><code>&quot;%z...&quot;</code></p>\n<p>Avoid UB.</p>\n<p>Codes use <a href=\"https://stackoverflow.com/q/32916575/2410359\"><code>&quot;%zd&quot;</code></a> with <code>size_t</code> and <code>unsigned</code>.</p>\n<p>Use <code>&quot;%zu&quot;</code> with <code>size_t</code> and <code>&quot;%u&quot;</code> with <code>unsigned</code>.</p>\n<p><strong>Name space</strong></p>\n<p>(Is the code readable?) <code>lexical_analyzer.h</code> introduces types and macros such as <code>SYNTAX_STATE_MACHINE_H</code>, <code>COMMA</code>, <code>State_Transition_Characters</code>, <code>MAX_OPCODE</code>, in a inconsistent manner.</p>\n<p>Name collision avoidance is difficult as naming covers too many naming styles.</p>\n<p>Consider a common prefix for all, perhaps <code>lapac_</code> in <code>lapac.h</code>.</p>\n<p><strong>Take care with failed data</strong></p>\n<p>Avoid UB. <code>report_lexical_analyzer_test_failure()</code></p>\n<p>When things fail, avoid assuming too much about <em>string</em> data.</p>\n<p>I recommend printing <em>string</em> with sentinels such as <code>&quot;&lt;&quot;</code>, <code>&quot;&gt;&quot;</code> for clarity as to the start/end of a string which may include <em>white space</em>..</p>\n<p>Take better string length care by using <code>snprintf()</code>, etc., than hoping <code>char out_buffer[BUFSIZ];</code> is big enough.</p>\n<p><strong>Simplify verbose code</strong></p>\n<p>(Are there any features in the more modern versions of C that could reduce the amount of code?)</p>\n<pre><code>// Instead of 22 line original, avoid locale dependencies and shorten.\nstatic bool is_legal_in_hex_number(unsigned char input) {\n return (isxdigit(input) &amp;&amp; !isdigit(input)) || (input == 'x' || input == 'X');\n}\n</code></pre>\n<p>It is unclear to me why original <code>is_legal_in_hex_number(some_0_to_9_digit)</code> returns <code>false</code>.</p>\n<p><strong>Minor</strong></p>\n<p><code>state_machine_unit_test_main.h</code> should include <code>&lt;stdbool.h&gt;</code></p>\n<p><code>()</code> around macro equations..</p>\n<pre><code>// #define SYNTAX_STATE_ARRAY_SIZE 9 + 1\n#define SYNTAX_STATE_ARRAY_SIZE (9 + 1)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-29T12:56:19.687", "Id": "487022", "Score": "0", "body": "`SYNTAX_STATE_MACHINE_H` is a problem, the `lexical_analyzer.*` files were originally named `syntax_state_machine.*` and I missed changing that macro when I changed the file name (the file name changes might be documented in the git change history, it was in the commit message). The enum COMMA is in the same set of enums as OPENBRACE, and CLOSEBRACE, what would you suggest for COMMA instead? Thank you for the review, I know it took lots of time. I see your point about `is_legal_in_hex_number()`, however I don't think opcodes will ever contain digit's, I should add that to the documentation." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-29T12:59:32.733", "Id": "487024", "Score": "0", "body": "I didn't know about `isxdigit()` thank you!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-29T16:03:32.527", "Id": "487048", "Score": "1", "body": "@pacmaninbw Pedantic detail about `isxdigit()` vs `switch(toupper(ch)) case 'A' ... case 'F': ...`. `isxdigit()` true for 10+6+6 characters - independent of locale.. `toupper(AE_with_a_diacritical_mark)` might map to `A` or `E` depending on locale. C's _locale_ features impose corner issues." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-29T16:44:07.077", "Id": "487052", "Score": "0", "body": "@pacmaninbw \"what would you suggest for COMMA instead?\" -->Example: I like the model of a `asdf.h` only declaring functions, vars, defines, types, macros, etc. all beginning with `asdf_` or macros with `ASDF_` or a type `asdf`. I tend to code like that even with `enum`s. I find that approach easier to maintain." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-31T14:30:41.457", "Id": "487247", "Score": "0", "body": "The review has been copied into an md file and posted to the [repository](https://github.com/pacmaninbw/VMWithEditor/tree/Before_First_Code_Review/VMWithEditor/UnitTests/State_Machine_Unit_Test/State_Machine_Unit_Test). In the md file there is a link back to this answer. Both of your answers are there." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-29T04:56:47.250", "Id": "248599", "ParentId": "248559", "Score": "2" } } ]
{ "AcceptedAnswerId": "248599", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-28T17:41:25.887", "Id": "248559", "Score": "8", "Tags": [ "performance", "c", "unit-testing", "cyclomatic-complexity", "lexical-analysis" ], "Title": "Hand Coded State Driven Lexical Analyzer in C With Unit Test Part A" }
248559
<p>This review is presented in 3 questions due to the amount of code:</p> <ol> <li><a href="https://codereview.stackexchange.com/questions/248559/hand-coded-state-driven-lexical-analyzer-in-c-with-unit-test-part-a">Part A</a> contains the Lexical Analyzer and the main portion of the unit test code.</li> <li>Part B (this question) contains the lower level unit tests called in Part A</li> <li><a href="https://codereview.stackexchange.com/questions/248561/hand-coded-state-driven-lexical-analyzer-in-c-with-unit-test-part-c">Part C</a> contains common unit test code that is included in all of the unit tests to be written.</li> </ol> <h2>Background</h2> <p>Back in June I provided this <a href="https://codereview.stackexchange.com/questions/244566/an-attempt-at-a-toy-vm/244573#244573">answer</a> to a question here on code review. I advised the person that asked the question to use enums rather than numbers to represent the opcodes, but upon further consideration I thought that the virtual machine really needed an editor as the front end and I have been working on that. An editor will require a translator to convert text into the numbers the virtual machine uses for opcodes and operands. The translator is composed of a parser and a lexical analyzer. The lexical analyzer is complete, unit tested and debugged so I am presenting it here for code review with the unit tests.</p> <p>This program is written in C because the original question was written in C. I tried to stick to the C90 standard as much as possible, but I did include _strdup() which is in the latest standard (perhaps it is strdup() in the latest standard, but Visual Studio suggested _strdup()).</p> <h2>Why did I write unit tests for the lexical analyzer?</h2> <ol> <li>It is a best practice at many companies that do software development.</li> <li>The code was very complex, at the time it was not a state machine (unit testing convinced me to go that route). It was over 450 lines of un-commented code in the parser module and growing.</li> <li>I had gotten to the point where I wanted to test/debug the lexical analyzer and the parser wasn't working so I wanted a program that ran only the lexical analyzer.</li> <li>I wanted to test/debug the code in a bottom up manner to make sure the lowest level functions were working correctly before testing the higher level functions.</li> </ol> <p>The benefits of unit testing were that it forced me to create a more modular design and to redesign the lexical analyzer to use a state machine rather another method. The results are less code and a better working lexical analyzer. It will also force a redesign of the parser, but that is for another question.</p> <h2>Questions</h2> <p>I learned C a long time ago from K&amp;R “The C Programming Language” Version 1 (pre C89/C90).</p> <ol> <li>Other than compiling this –O3 what can I do to optimize this code?</li> <li>Are there any features in the more modern versions of C that could reduce the amount of code?</li> <li>Is there archaic C usage that is not customary to use anymore?</li> <li>Are the unit tests missing any test cases, especially edge cases?</li> <li>Are there any memory leaks?</li> <li>Is the code readable?</li> <li>I don’t like the fact that I need to include some of the unit test files in internal_sytax_state_tests.c do you see any way around this?</li> </ol> <h2>Code Available:</h2> <p>Rather than copy and pasting this code it is available in my <a href="https://github.com/pacmaninbw/VMWithEditor" rel="nofollow noreferrer">GitHub Repository</a>. The code as presented in these 3 questions is on the branch <code>Before_First_Code_Review</code>, updates including those based on the review will be added to the master branch.</p> <p>The unit test ouput is always saved to a <code>.txt</code> file, a comparison text file is the <a href="https://github.com/pacmaninbw/VMWithEditor/tree/master/VMWithEditor/UnitTests/State_Machine_Unit_Test/State_Machine_Unit_Test" rel="nofollow noreferrer">unit test folder</a> in the repository. The unit test output is 1827 lines so it is not included here in the question.</p> <p>There is a CMakeLists.txt file in the unit test directory, but I'm not sure it works so it isn't posted here. If anyone would like to test it, let me know what to do or how to fix it. I could give you permission to update it in GitHub.</p> <p><strong>internal_character_transition_unit_tests.c</strong></p> <pre><code>/* * internal_character_transition_unit_tests.c * * This file contains the lowest level of unit testing for the lexical analyzer. * It tests the lexical state transitions for particular characters. While it * is a C source file rather than a header file it is included by static functions * internal_sytax_state_tests.c because it is testing within lexical_analyzer.c. * The file internal_sytax_state_tests.c is included by lexical_analyzer.c. as * well. This file was separated out of internal_sytax_state_tests.c because at * some point that file became too large and complex. */ #ifndef INTERNAL_CHARACTER_TRANSITION_UNIT_TEST_C #define INTERNAL_CHARACTER_TRANSITION_UNIT_TEST_C static void log_unit_test_get_transition_character_type_failure( Test_Log_Data* log_data, unsigned char candidate, Syntax_State current_state, State_Transition_Characters expected_type, State_Transition_Characters actual_type) { // Force failures to be reported bool stand_alone = log_data-&gt;stand_alone; log_test_status_each_step2(log_data); char out_buffer[BUFSIZ]; sprintf(out_buffer, &quot;\tcurrent_state = %s input character = %c\n&quot;, state_name_for_printing(current_state), candidate); log_generic_message(out_buffer); sprintf(out_buffer, &quot;\tExpected Transitiion %s Actual Transition %s\n\n&quot;, transition_character[expected_type], transition_character[actual_type]); log_generic_message(out_buffer); log_data-&gt;stand_alone = stand_alone; } typedef enum test_character_case { LOWER_CASE = 0, UPPER_CASE = 1 } TEST_CHARACTER_CASE; static State_Transition_Characters get_expected_alpha_transition_character_type( unsigned char input, Syntax_State current_state) { input = (unsigned char)toupper(input); switch (input) { case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'X': if (current_state == ENTER_OPERAND_STATE || current_state == OPERAND_STATE || current_state == END_OPERAND_STATE) { return DIGIT_STATE_TRANSITION; } else { return ALPHA_STATE_TRANSITION; } break; default: return ALPHA_STATE_TRANSITION; break; } } typedef State_Transition_Characters(*STFfunct)(unsigned char input, Syntax_State current_state); static bool core_alpha_character_transition_unit_test(Test_Log_Data* log_data, Syntax_State current_state, STFfunct transition_function) { bool test_passed = true; char buffer[BUFSIZ]; for (size_t alphabet = (size_t)LOWER_CASE; alphabet &lt;= (size_t)UPPER_CASE; alphabet++) { if (log_data-&gt;stand_alone) { sprintf(buffer, &quot;\tBegin Positive test path current_state = %s input character = %s\n\n&quot;, state_name_for_printing(current_state), (alphabet == LOWER_CASE) ? &quot;Lower Case&quot; : &quot;Upper case&quot;); log_generic_message(buffer); } unsigned char fist_character_to_test = (alphabet == LOWER_CASE) ? 'a' : 'A'; unsigned char last_character_to_test = (alphabet == LOWER_CASE) ? 'z' : 'Z'; for (unsigned char candidate_character = fist_character_to_test; candidate_character &lt;= last_character_to_test; candidate_character++) { log_data-&gt;status = true; State_Transition_Characters expected_type = get_expected_alpha_transition_character_type(candidate_character, current_state); State_Transition_Characters actual_type = transition_function(candidate_character, current_state); if (expected_type != actual_type) { log_data-&gt;status = false; test_passed = log_data-&gt;status; log_unit_test_get_transition_character_type_failure(log_data, candidate_character, current_state, expected_type, actual_type); } else { log_test_status_each_step2(log_data); } } if (log_data-&gt;stand_alone) { sprintf(buffer, &quot;\n\tEnd Positive test path current_state = %s input character = %s\n\n&quot;, state_name_for_printing(current_state), (alphabet == LOWER_CASE) ? &quot;Lower Case&quot; : &quot;Upper case&quot;); log_generic_message(buffer); } } return test_passed; } static bool core_non_alpha_character_transition_unit_test(Test_Log_Data* log_data, Syntax_State current_state, unsigned char* input, State_Transition_Characters expected_transition[], size_t positive_path_count, char* local_func_name) { bool test_passed = true; char* keep_old_path = log_data-&gt;path; log_data-&gt;path = &quot;Positive&quot;; size_t test_count = 0; for (unsigned char* test_input = input; *test_input; test_input++, test_count++) { if (positive_path_count == test_count) { log_end_positive_path(local_func_name); log_start_negative_path(local_func_name); log_data-&gt;path = &quot;Negative&quot;; } log_data-&gt;status = true; State_Transition_Characters actual_transistion = get_transition_character_type( *test_input, current_state); log_data-&gt;status = actual_transistion == expected_transition[test_count]; if (!log_data-&gt;status) { log_unit_test_get_transition_character_type_failure(log_data, *test_input, current_state, expected_transition[test_count], actual_transistion); test_passed = false; } else { log_test_status_each_step2(log_data); } } log_data-&gt;status = test_passed; log_data-&gt;path = keep_old_path; return test_passed; } /* * Tests limited number of states where alpha is important calls the lower level * function get_alpha_input_transition_character_type(). */ static bool unit_test_get_alpha_input_transition_character_type(unsigned test_step) { bool test_passed = true; Test_Log_Data log_data; init_test_log_data(&amp;log_data, &quot;unit_test_get_alpha_input_transition_character_type&quot;, test_passed, &quot;Positive&quot;, test_step == 0); if (log_data.stand_alone) { log_start_positive_path(log_data.function_name); } for (size_t state = (size_t)ENTER_OPCODE_STATE; state &lt;= (size_t)END_OPERAND_STATE; state++) { test_passed = core_alpha_character_transition_unit_test(&amp;log_data, state, get_alpha_input_transition_character_type); } if (log_data.stand_alone) { log_end_test_path(&amp;log_data); } return test_passed; } static bool unit_test_whitespace_transition(Test_Log_Data* log_data, Syntax_State current_state) { bool test_passed = true; unsigned char input[] = &quot; \t\n\r\v\f&quot;; State_Transition_Characters expected_transition[] = { // Positive test path WHITESPACE_STATE_TRANSITION, WHITESPACE_STATE_TRANSITION, EOL_STATE_TRANSITION, // Test the negatvie path as well. EOL_STATE_TRANSITION, ILLEGAL_CHAR_TRANSITION, ILLEGAL_CHAR_TRANSITION }; size_t positive_path_count = 4; // Change this if more positive path tests are added. char buffer[BUFSIZ]; sprintf(buffer, &quot;%s whitespace transition test&quot;, log_data-&gt;function_name); char* local_func_name = _strdup(buffer); log_start_positive_path(local_func_name); if (core_non_alpha_character_transition_unit_test(log_data, current_state, input, expected_transition, positive_path_count, local_func_name)) { test_passed = log_data-&gt;status; } log_end_negative_path(local_func_name); free(local_func_name); log_data-&gt;status = test_passed; return test_passed; } static void init_digit_test_data(unsigned char* input, State_Transition_Characters expected_transition[], size_t* positive_test_path, Syntax_State current_state) { State_Transition_Characters* expected_ptr = expected_transition; if (current_state == ENTER_OPERAND_STATE || current_state == OPERAND_STATE || current_state == END_OPERAND_STATE) { for (; *input; input++, expected_ptr++) { *expected_ptr = DIGIT_STATE_TRANSITION; } *positive_test_path = strlen((const char*)input); } else { for (; *input; input++, expected_ptr++) { if (isdigit(*input)) { *expected_ptr = DIGIT_STATE_TRANSITION; (*positive_test_path)++; } else { *expected_ptr = ALPHA_STATE_TRANSITION; // to force failures use this instead *expected_ptr = DIGIT_STATE_TRANSITION; } } } } static bool unit_test_digit_transition(Test_Log_Data* log_data, Syntax_State current_state) { bool test_passed = true; unsigned char* input = (unsigned char*)&quot;0123456789ABCDEFXabcdefx&quot;; // size is currently 24 #define MAX_INPUT_CHARACTERS 24 State_Transition_Characters expected_transition[MAX_INPUT_CHARACTERS]; size_t positive_path_count; // Change this if more positive path tests are added. init_digit_test_data(input, expected_transition, &amp;positive_path_count, current_state); char* local_func_name = NULL; if (log_data-&gt;stand_alone) { char buffer[BUFSIZ]; sprintf(buffer, &quot;%s digit transition test&quot;, log_data-&gt;function_name); local_func_name = _strdup(buffer); log_start_positive_path(local_func_name); } if (core_non_alpha_character_transition_unit_test(log_data, current_state, input, expected_transition, positive_path_count, local_func_name)) { test_passed = log_data-&gt;status; } if (log_data-&gt;stand_alone) { if (positive_path_count &gt; 10) { log_end_positive_path(local_func_name); } else { log_end_negative_path(local_func_name); } } #undef MAX_INPUT_CHARACTERS log_data-&gt;status = test_passed; return test_passed; } /* * test the state specified by the caller function. Calls the higher level function * get_transition_character_type(). */ static bool unit_test_alpha_transition(Test_Log_Data* log_data, Syntax_State current_state) { bool test_passed = true; char* local_func_name = NULL; if (log_data-&gt;stand_alone) { char buffer[BUFSIZ]; sprintf(buffer, &quot;%s alpha transition test&quot;, log_data-&gt;function_name); local_func_name = _strdup(buffer); log_start_positive_path(local_func_name); } test_passed = core_alpha_character_transition_unit_test(log_data, current_state, get_transition_character_type); if (log_data-&gt;stand_alone) { log_end_positive_path(local_func_name); } return test_passed; } static bool unit_test_punctuation_transition(Test_Log_Data* log_data, Syntax_State current_state) { bool test_passed = true; unsigned char input[] = &quot;{},+-/*=&amp;&quot;; State_Transition_Characters expected_transition[] = { // Positive test path OPENBRACE_STATE_TRANSITION, CLOSEBRACE_STATE_TRANSITION, COMMA_STATE_TRANSITION, // Test the negatvie path as well. ILLEGAL_CHAR_TRANSITION, ILLEGAL_CHAR_TRANSITION, ILLEGAL_CHAR_TRANSITION, ILLEGAL_CHAR_TRANSITION, ILLEGAL_CHAR_TRANSITION, ILLEGAL_CHAR_TRANSITION }; size_t positive_path_count = 3; // Change this if more positive path tests are added. char buffer[BUFSIZ]; sprintf(buffer, &quot;%s punctuation transition test&quot;, log_data-&gt;function_name); char* local_func_name = _strdup(buffer); log_start_positive_path(local_func_name); if (core_non_alpha_character_transition_unit_test(log_data, current_state, input, expected_transition, positive_path_count, local_func_name)) { test_passed = log_data-&gt;status; } log_end_negative_path(local_func_name); free(local_func_name); log_data-&gt;status = test_passed; return test_passed; } typedef bool (*character_transition_test_function)(Test_Log_Data* log_data, Syntax_State state); static bool unit_test_get_transition_character_type(size_t test_step) { bool test_passed = true; char buffer[BUFSIZ]; Test_Log_Data* log_data = create_and_init_test_log_data( &quot;unit_test_get_transition_character_type&quot;, test_passed, &quot;Positive&quot;, test_step == 0); if (!log_data) { report_create_and_init_test_log_data_memory_failure( &quot;unit_test_get_transition_character_type&quot;); return false; } if (log_data-&gt;stand_alone) { sprintf(buffer, &quot;STARTING internal unit test for get_transition_character_type(&quot; &quot;unsigned char input, Syntax_State current_state)&quot;); log_generic_message(buffer); } character_transition_test_function test_function[] = { unit_test_punctuation_transition, unit_test_alpha_transition, unit_test_digit_transition, unit_test_whitespace_transition }; for (size_t state = (size_t)START_STATE; state &lt;= (size_t)ERROR_STATE; state++) { for (size_t unit_test_count = 0; unit_test_count &lt; sizeof(test_function) / sizeof(*test_function); unit_test_count++) { if (!test_function[unit_test_count](log_data, (Syntax_State)state)) { test_passed = log_data-&gt;status; } } } if (log_data-&gt;stand_alone) { sprintf(buffer, &quot;\nENDING internal unit test for get_transition_character_type(&quot; &quot;unsigned char input, Syntax_State current_state)\n&quot;); log_generic_message(buffer); } free(log_data); return test_passed; } #endif // INTERNAL_CHARACTER_TRANSITION_UNIT_TEST_C </code></pre> <p><strong>lexical_analyzer_test_data.h</strong></p> <pre><code>#ifndef LEXICAL_ANALYZER_TEST_DATA_H #define LEXICAL_ANALYZER_TEST_DATA_H #include &quot;lexical_analyzer.h&quot; typedef struct expected_syntax_errors { unsigned error_count; unsigned syntax_check_list[SYNTAX_CHECK_COUNT]; } Expected_Syntax_Errors; typedef struct lexical_analyzer_test_data { unsigned char** test_program; size_t test_program_size; Expected_Syntax_Errors* expected_errors; } Lexical_Analyzer_Test_Data; extern void deallocate_lexical_test_data(Lexical_Analyzer_Test_Data* deletee); extern void lexical_analyzer_test_data_allocation_failed(Test_Log_Data* log_data, char* allocating_function, char* allocation_function); extern Lexical_Analyzer_Test_Data* init_positive_path_data_for_lexical_analysis(Test_Log_Data* log_data); extern Lexical_Analyzer_Test_Data* init_negative_path_data_for_lexical_analysis(Test_Log_Data* log_data); #endif // LEXICAL_ANALYZER_TEST_DATA_H </code></pre> <p><strong>lexical_analyzer_test_data.c</strong></p> <pre><code>#include &quot;common_unit_test_logic.h&quot; #include &quot;lexical_analyzer_test_data.h&quot; #include &lt;stdbool.h&gt; #include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;string.h&gt; static void deallocate_test_program(size_t test_program_size, unsigned char **test_program) { if (!test_program) { return; } for (size_t i = 0; i &lt; test_program_size; i++) { free(test_program[i]); } free(test_program); } static void deallocate_expected_data(Expected_Syntax_Errors* expected_errors) { if (!expected_errors) { return; } free(expected_errors); } void deallocate_lexical_test_data(Lexical_Analyzer_Test_Data* deletee) { if (!deletee) { return; } if (deletee-&gt;expected_errors) { deallocate_expected_data(deletee-&gt;expected_errors); deletee-&gt;expected_errors = NULL; } if (deletee-&gt;test_program) { deallocate_test_program(deletee-&gt;test_program_size, deletee-&gt;test_program); deletee-&gt;test_program = NULL; } free(deletee); } void lexical_analyzer_test_data_allocation_failed(Test_Log_Data* log_data, char* allocating_function, char* allocation_function) { fprintf(error_out_file, &quot;Memory Allocation Error in %s\n&quot;, allocating_function); fprintf(error_out_file, &quot;\t%s failed for allocation of test data\n&quot;, allocation_function); fprintf(error_out_file, &quot;\t Unable to continue %s\n&quot;, log_data-&gt;function_name); } static Lexical_Analyzer_Test_Data* create_and_init_lexical_test_data(unsigned char** test_program, size_t test_program_size, Expected_Syntax_Errors* expected_data, Test_Log_Data* log_data, char* allocating_function) { Expected_Syntax_Errors* expected_errors_dup = calloc(test_program_size, sizeof(*expected_errors_dup)); if (!expected_errors_dup) { lexical_analyzer_test_data_allocation_failed(log_data, &quot;init_positive_path_data_for_lexical_analysis&quot;, &quot;calloc&quot;); return NULL; } for (size_t step_count = 0; step_count &lt; test_program_size; step_count++) { expected_errors_dup[step_count].error_count = expected_data[step_count].error_count; for (size_t checklist_item = 0; checklist_item &lt; SYNTAX_CHECK_COUNT; checklist_item++) { expected_errors_dup[step_count].syntax_check_list[checklist_item] = expected_data[step_count].syntax_check_list[checklist_item]; } } unsigned char** test_program_dupe = calloc(test_program_size, sizeof(*test_program_dupe)); if (!test_program_dupe) { lexical_analyzer_test_data_allocation_failed(log_data, &quot;init_positive_path_data_for_lexical_analysis&quot;, &quot;calloc&quot;); deallocate_expected_data(expected_errors_dup); return NULL; } for (size_t step_count = 0; step_count &lt; test_program_size; step_count++) { test_program_dupe[step_count] = (unsigned char*) _strdup((char *)test_program[step_count]); if (!test_program_dupe[step_count]) { lexical_analyzer_test_data_allocation_failed(log_data, &quot;init_positive_path_data_for_lexical_analysis&quot;, &quot;_strdup&quot;); deallocate_test_program(step_count, test_program_dupe); deallocate_expected_data(expected_errors_dup); return NULL; } } Lexical_Analyzer_Test_Data* new_lexical_test_data = calloc(1, sizeof(*new_lexical_test_data)); if (!new_lexical_test_data) { lexical_analyzer_test_data_allocation_failed(log_data, allocating_function, &quot;calloc&quot;); return NULL; } new_lexical_test_data-&gt;test_program_size = test_program_size; new_lexical_test_data-&gt;test_program = test_program_dupe; new_lexical_test_data-&gt;expected_errors = expected_errors_dup; return new_lexical_test_data; } Lexical_Analyzer_Test_Data* init_positive_path_data_for_lexical_analysis(Test_Log_Data* log_data) { unsigned char* test_program[] = { (unsigned char*)&quot; {PUSH, 0x0A},\n&quot;, (unsigned char*)&quot; {PUSH, 0x43},\n&quot;, (unsigned char*)&quot;{ PUSH, 0x42 },\n&quot;, (unsigned char*)&quot;{ PUSH, 0x41 },\n&quot;, (unsigned char*)&quot;{ OUTPUTCHAR, 0x00 }, \n&quot;, (unsigned char*)&quot;{ POP, 0x00 }, \n&quot;, (unsigned char*)&quot;{ OUTPUTCHAR, 0x00 },\n&quot;, (unsigned char*)&quot;{ POP, 0x00 },\n&quot;, (unsigned char*)&quot;{OUTPUTCHAR, 0x00},\n&quot;, (unsigned char*)&quot;{POP, 0x00},\n&quot;, (unsigned char*)&quot;{HALT, 0x00}&quot; }; size_t test_size = sizeof(test_program) / sizeof(*test_program); Expected_Syntax_Errors* expected_errors = calloc(test_size, sizeof(*expected_errors)); if (!expected_errors) { lexical_analyzer_test_data_allocation_failed(log_data, &quot;init_positive_path_data_for_lexical_analysis&quot;, &quot;calloc&quot;); return NULL; } Expected_Syntax_Errors sample_expect_data = { 0, {1, 1, 2, 1, 1, 0, 0, 0, 0, 0, 0} }; for (size_t test = 0; test &lt; test_size; test++) { expected_errors[test].error_count = sample_expect_data.error_count; for (size_t checklist_item = 0; checklist_item &lt; SYNTAX_CHECK_COUNT; checklist_item++) { expected_errors[test].syntax_check_list[checklist_item] = sample_expect_data.syntax_check_list[checklist_item]; } } expected_errors[test_size - 1].syntax_check_list[COMMA] = 1; Lexical_Analyzer_Test_Data* positive_test_data = create_and_init_lexical_test_data( test_program, test_size, expected_errors, log_data, &quot;init_positive_path_data_for_lexical_analysis&quot;); return positive_test_data; } Lexical_Analyzer_Test_Data* init_negative_path_data_for_lexical_analysis(Test_Log_Data* log_data) { unsigned char* test_program[] = { (unsigned char*)&quot; {PUSH, 0x0A},\n&quot;, // No problem (unsigned char*)&quot; PUSH, 0x43},\n&quot;, // Missing open brace (unsigned char*)&quot;{ PUSH, 0x42 ,\n&quot;, // Missing close brace (unsigned char*)&quot; { PUSH, 0x41 }, { OUTPUTCHAR 0x00 }, \n&quot;, // Multiple statements on one line missing comma in second statement (unsigned char*)&quot;{ , 0x00 }, \n&quot;, // Missibg opcode (unsigned char*)&quot;{ OUTPUTCHAR 0x00 },&quot;, // Missing comma between opcode and operand (unsigned char*)&quot;{ POP, },&quot;, // Missing OPERAND (unsigned char*)&quot;{OUTPUTCHAR, 0x00}\n&quot;, // Missing last comma (unsigned char*)&quot;{POP, 0x00 POP},\n&quot;, // Illegal characters after operand (unsigned char*)&quot;HALT&quot; // Missing open brace, commas, operand, close brace }; size_t test_size = sizeof(test_program) / sizeof(*test_program) ; Expected_Syntax_Errors expected_errors[] = { {0, {1, 1, 2, 1, 1, 0, 0, 0, 0, 0, 0}}, // {PUSH, 0x0A}, No problem {2, {0, 1, 2, 1, 1, 0, 0, 1, 0, 0, 0}}, // PUSH, 0x43}, Missing open brace and Illegal character in first column {1, {1, 0, 2, 1, 1, 0, 0, 0, 0, 0, 0}}, // { PUSH, 0x42 , Missing close brace {1, {2, 1, 2, 1, 1, 0, 0, 0, 1, 0, 0}}, // { PUSH, 0x41 }, { OUTPUTCHAR 0x00 }, Multiple statements on one line missing comma in second statement {1, {1, 1, 2, 0, 1, 0, 0, 0, 0, 0, 0}}, // { , 0x00 }, Missibg opcode {1, {1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1}}, // { OUTPUTCHAR 0x00 }, Missing comma between opcode and operand {1, {1, 1, 2, 1, 0, 0, 0, 0, 0, 0, 0}}, // { POP, }, Missing OPERAND {0, {1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0}}, // {OUTPUTCHAR, 0x00}, Missing last comma {1, {1, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0}}, // {POP, 0x00 POP}, Illegal characters after operand {5, {0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0}} // HALT Missing open brace, commas, operand, close brace }; Lexical_Analyzer_Test_Data* negative_test_data = create_and_init_lexical_test_data( test_program, test_size, expected_errors, log_data, &quot;init_negative_path_data_for_lexical_analysis&quot;); return negative_test_data; } </code></pre>
[]
[ { "body": "<p>Small review.</p>\n<p><strong>Minor</strong></p>\n<p>Simplify. Instead of</p>\n<pre><code>unsigned char* input = (unsigned char*)&quot;0123456789ABCDEFXabcdefx&quot;; // size is currently 24\n#define MAX_INPUT_CHARACTERS 24\nState_Transition_Characters expected_transition[MAX_INPUT_CHARACTERS];\n...\n#undef MAX_INPUT_CHARACTERS\n</code></pre>\n<p>Consider</p>\n<pre><code>unsigned char input[] = &quot;0123456789ABCDEFXabcdefx&quot;;\nState_Transition_Characters expected_transition[sizeof input - 1];\n</code></pre>\n<p><strong>Is the code readable?</strong></p>\n<p>I'd make more use of pointers to <code>const</code> to help convey the idea referenced data does not change.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-29T06:13:42.863", "Id": "248604", "ParentId": "248560", "Score": "2" } } ]
{ "AcceptedAnswerId": "248604", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-28T17:45:22.803", "Id": "248560", "Score": "4", "Tags": [ "performance", "c", "unit-testing", "cyclomatic-complexity", "lexical-analysis" ], "Title": "Hand Coded State Driven Lexical Analyzer in C With Unit Test Part B" }
248560
<p>This review is presented in 3 questions due to the amount of code:</p> <ol> <li><a href="https://codereview.stackexchange.com/questions/248559/hand-coded-state-driven-lexical-analyzer-in-c-with-unit-test-part-a">Part A</a> contains the Lexical Analyzer and the main portion of the unit test code.</li> <li><a href="https://codereview.stackexchange.com/questions/248560/hand-coded-state-driven-lexical-analyzer-in-c-with-unit-test-part-b">Part</a> B contains the lower level unit tests called in Part A</li> <li>Part C (this question) contains common unit test code that is included in all of the unit tests to be written.</li> </ol> <h2>The Need for Common Unit Test Code</h2> <p>Since I am planning at least 5 unit tests and possibly up to 7 there is a real need to have common code that the unit tests can share, especially unit test logging and error reporting. The functions provided here are used extensively in the unit test code in the other questions.</p> <h2>Questions</h2> <p>I learned C a long time ago from K&amp;R “The C Programming Language” Version 1 (pre C89/C90).</p> <ol> <li>Other than compiling this –O3 what can I do to optimize this code?</li> <li>Is there archaic C usage that is not customary to use anymore?</li> <li>Is the code readable?</li> </ol> <h2>Code Available:</h2> <p>Rather than copy and pasting this code it is available in my <a href="https://github.com/pacmaninbw/VMWithEditor/tree/master/VMWithEditor/UnitTests/Common_UnitTest_Code" rel="nofollow noreferrer">GitHub Repository</a>. The code as presented in these 3 questions is on the branch <code>Before_First_Code_Review</code>, updates including those based on the review will be added to the master branch.</p> <p>The repository structure. <a href="https://i.stack.imgur.com/nUGwN.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/nUGwN.gif" alt="visual map of the GitHub repository." /></a></p> <p><strong>common_unit_test_logic.h</strong></p> <pre><code>#ifndef COMMON_UNIT_TEST_LOGIC_H #define COMMON_UNIT_TEST_LOGIC_H #include &lt;stdio.h&gt; #include &lt;stdbool.h&gt; #ifndef REDUCED_VM_AND_HRF_DEPENDENCIES #include &quot;human_readable_program_format.h&quot; #endif typedef struct test_log_data { char* function_name; bool status; char* path; bool stand_alone; } Test_Log_Data; extern FILE* error_out_file; extern FILE* unit_test_log_file; extern bool init_vm_error_reporting(char* error_log_file_name); #ifndef REDUCED_VM_AND_HRF_DEPENDENCIES extern Human_Readable_Program_Format* default_program(size_t* program_size); #endif extern void disengage_error_reporting(void); extern bool init_unit_tests(char* log_file_name); extern void report_error_generic(char* error_message); extern void report_create_and_init_test_log_data_memory_failure(char* function_name); extern void log_test_status_each_step(char* function_name, bool status, char* path, bool stand_alone); extern void init_test_log_data(Test_Log_Data* log_data, char* function_name, bool status, char* path, bool stand_alone); extern Test_Log_Data* create_and_init_test_log_data(char* function_name, bool status, char* path, bool stand_alone); extern void log_test_status_each_step2(Test_Log_Data* test_data_to_log); extern void log_start_positive_path(char* function_name); extern void log_start_positive_path2(Test_Log_Data* log_data); extern void log_start_test_path(Test_Log_Data* log_data); extern void log_end_test_path(Test_Log_Data* log_data); extern void log_end_positive_path(char* function_name); extern void log_end_positive_path2(Test_Log_Data* log_data); extern void log_start_negative_path(char* function_name); extern void log_end_negative_path(char* function_name); extern void log_generic_message(char *log_message); extern void close_unit_tests(void); #endif // !COMMON_UNIT_TEST_LOGIC_H </code></pre> <p><strong>common_unit_test_logic.c</strong></p> <pre><code>#include &quot;common_unit_test_logic.h&quot; #ifndef REDUCED_VM_AND_HRF_DEPENDENCIES #include &quot;virtual_machine.h&quot; #endif #include &lt;ctype.h&gt; #include &lt;stdbool.h&gt; #include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;string.h&gt; FILE* error_out_file = NULL; FILE* unit_test_log_file = NULL; bool init_vm_error_reporting(char* error_log_file_name) { bool status_is_good = true; if (error_log_file_name) { error_out_file = fopen(error_log_file_name, &quot;w&quot;); if (!error_out_file) { error_out_file = stderr; fprintf(error_out_file, &quot;Can't open error output file, %s&quot;, &quot;error_log_file_name&quot;); status_is_good = false; } } else { error_out_file = stderr; } return status_is_good; } void disengage_error_reporting(void) { if (error_out_file != stderr) { fclose(error_out_file); } } bool init_unit_tests(char* log_file_name) { if (log_file_name) { unit_test_log_file = fopen(log_file_name, &quot;w&quot;); if (!unit_test_log_file) { fprintf(error_out_file, &quot;Can't open %s for output\n&quot;, log_file_name); return false; } error_out_file = unit_test_log_file; } else { unit_test_log_file = stdout; error_out_file = stderr; } return true; } void report_error_generic(char *error_message) { fprintf(error_out_file, &quot;%s\n&quot;, error_message); } void close_unit_tests(void) { if (unit_test_log_file != stdout) { fclose(unit_test_log_file); } } static bool log_test_is_positive_path(Test_Log_Data* log_data) { bool is_positive = true; if (!log_data-&gt;path) { fprintf(error_out_file, &quot;Programmer error: log_data-&gt;path is NULL in log_test_is_positive_path()\n&quot;); return false; } char* string_to_test = _strdup(log_data-&gt;path); if (!string_to_test) { fprintf(error_out_file, &quot;Memory Allocation error: _strdup() failed in log_test_is_positive_path()\n&quot;); fprintf(error_out_file, &quot;Exiting program.\n&quot;); exit(EXIT_FAILURE); } char* stt_ptr = string_to_test; while (*stt_ptr) { *stt_ptr = (char) toupper(*stt_ptr); stt_ptr++; } is_positive = (strcmp(string_to_test, &quot;POSITIVE&quot;) == 0); return is_positive; } void log_test_status_each_step(char* function_name, bool status, char* path, bool stand_alone) { if (stand_alone) { fprintf(unit_test_log_file, &quot;%s(): %s Path %s\n&quot;, function_name, path, (status) ? &quot;Passed&quot; : &quot;Failed&quot;); } } void log_test_status_each_step2(Test_Log_Data *test_data_to_log) { if (test_data_to_log-&gt;stand_alone) { fprintf(unit_test_log_file, &quot;%s(): %s Path %s\n&quot;, test_data_to_log-&gt;function_name, test_data_to_log-&gt;path, (test_data_to_log-&gt;status) ? &quot;Passed&quot; : &quot;Failed&quot;); } } void log_start_positive_path(char* function_name) { fprintf(unit_test_log_file, &quot;\nStarting POSITIVE PATH testing for %s\n\n&quot;, function_name); } void log_start_positive_path2(Test_Log_Data *log_data) { fprintf(unit_test_log_file, &quot;\nStarting POSITIVE PATH testing for %s\n\n&quot;, log_data-&gt;function_name); } void log_end_positive_path(char* function_name) { fprintf(unit_test_log_file, &quot;\nEnding POSITIVE PATH testing for %s\n&quot;, function_name); } void log_end_positive_path2(Test_Log_Data* log_data) { fprintf(unit_test_log_file, &quot;\nEnding POSITIVE PATH testing for %s, POSITIVE PATH %s \n&quot;, log_data-&gt;function_name, log_data-&gt;status? &quot;PASSED&quot; : &quot;FAILED&quot;); } void log_start_negative_path(char* function_name) { fprintf(unit_test_log_file, &quot;\nStarting NEGATIVE PATH testing for %s\n\n&quot;, function_name); } void log_end_negative_path(char* function_name) { fprintf(unit_test_log_file, &quot;\nEnding NEGATIVE PATH testing for %s\n&quot;, function_name); fflush(unit_test_log_file); // Current unit test is done flush the output. } void log_start_test_path(Test_Log_Data* log_data) { bool is_positive = log_test_is_positive_path(log_data); fprintf(unit_test_log_file, &quot;\nStarting %s PATH testing for %s\n\n&quot;, is_positive ? &quot;POSITIVE&quot; : &quot;NEGATIVE&quot;, log_data-&gt;function_name); } void log_end_test_path(Test_Log_Data *log_data) { bool is_positive = log_test_is_positive_path(log_data); fprintf(unit_test_log_file, &quot;\nEnding %s PATH testing for %s, Path %s\n&quot;, is_positive ? &quot;POSITIVE&quot; : &quot;NEGATIVE&quot;, log_data-&gt;function_name, log_data-&gt;status ? &quot;PASSED&quot; : &quot;FAILED&quot;); if (!is_positive) { fflush(unit_test_log_file); // Current unit test is done flush the output. } } void log_generic_message(char* log_message) { fprintf(unit_test_log_file, log_message); } void init_test_log_data(Test_Log_Data* log_data, char *function_name, bool status, char *path, bool stand_alone) { log_data-&gt;function_name = function_name; log_data-&gt;status = status; log_data-&gt;path = path; log_data-&gt;stand_alone = stand_alone; } Test_Log_Data *create_and_init_test_log_data(char* function_name, bool status, char* path, bool stand_alone) { Test_Log_Data* log_data = calloc(1, sizeof(*log_data)); if (log_data) { init_test_log_data(log_data, function_name, status, path, stand_alone); } else { fprintf(error_out_file, &quot;In %s calloc() failed\n&quot;, &quot;create_and_init_test_log_data&quot;); } return log_data; } // provides common error report for memory allocation error. void report_create_and_init_test_log_data_memory_failure(char *function_name) { fprintf(error_out_file, &quot;In function %s, Memory allocation failed in create_and_init_test_log_data\n&quot;, function_name); } </code></pre>
[]
[ { "body": "<h1><code>typedef struct</code> can reuse the name of struct</h1>\n<p>I see you often do something like:</p>\n<pre><code>typedef struct foo_bar {\n ...\n} Foo_Bar;\n</code></pre>\n<p>It's a bit weird to use lower_case for the struct name and Upper_Case for the typedef. You can reuse the same name as the struct:</p>\n<pre><code>typedef struct foo_bar {\n ...\n} foo_bar;\n</code></pre>\n<p>It's also common to append <code>_t</code> to the typedef'ed name so it is easier to identify it as a type name instead of a variable or function name, although the <code>_t</code> suffix is reserved by at least POSIX 1003.1.</p>\n<h1>No need to use <code>extern</code> for function declarations</h1>\n<p>The keyword <code>extern</code> is only necessary to declare variables without defining them, for function declarations there is no need, you can write for example the following in a header file:</p>\n<pre><code>bool init_vm_error_reporting(char* error_log_file_name);\n</code></pre>\n<h1>Use <code>const</code> where appropriate</h1>\n<p>It seems like you avoided using <code>const</code> everywhere. Using it might allow the compiler to better optimize your code, and it will be able to report an error if you ever accidentily do write to a variable that shouldn't be changed. So for example:</p>\n<pre><code>bool init_vm_error_reporting(const char* error_log_file_name);\n</code></pre>\n<p>You can also use it for struct members:</p>\n<pre><code>typedef struct test_log_data\n{\n const char* function_name;\n bool status;\n const char* path;\n bool stand_alone;\n} test_log_data;\n</code></pre>\n<h1>Optimize struct layout</h1>\n<p>The C standard mandates that the members of a struct appear in the same order in memory as they are declared. But this can result into gaps because of alignment restrictions. The above struct can be better layed out as follows:</p>\n<pre><code>typedef struct test_log_data\n{\n const char* function_name;\n const char* path;\n bool status;\n bool stand_alone;\n} test_log_data;\n</code></pre>\n<p>This saves 8 bytes on 64-bit architectures. In this particular case, it probably won't have a significant impact, but if structs get larger or you use a lot of them, you will reduce the amount of memory (bandwidth) used, and will less likely cause cache misses.</p>\n<h1>You can close <code>stderr</code> and <code>stdout</code></h1>\n<p>It is perfectly fine to call <code>fclose(stdout)</code> and <code>fclose(stderr)</code>, so the checks in <code>disengage_error_reporting()</code> and <code>close_unit_tests()</code> are not necessary.</p>\n<h1>Simplify <code>log_test_is_positive_path()</code></h1>\n<p>It looks like you can replace this whole function with:</p>\n<pre><code>static bool log_test_is_positive_path(Test_Log_Data* log_data)\n{\n return !strcasecmp(log_data, &quot;POSITIVE&quot;);\n}\n</code></pre>\n<p>Or if you can't use the POSIX <a href=\"https://linux.die.net/man/3/strcasecmp\" rel=\"nofollow noreferrer\"><code>strcasecmp()</code></a> function, Windows provides <a href=\"https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/stricmp-wcsicmp-mbsicmp-stricmp-l-wcsicmp-l-mbsicmp-l?view=vs-2019\" rel=\"nofollow noreferrer\"><code>_stricmp()</code></a>.</p>\n<p>But maybe it is better to ensure the filename itself is always upper case, so you can just use <code>strcmp()</code>?</p>\n<h1>Avoid spending too much code on error handling unrelated to the unit tests</h1>\n<p>When there is an error internally in the unit tests, like when allocating memory for some string, don't waste lots of lines of code producing nice error messages and exitting gracefully. I particular like the BSD functions like <a href=\"https://linux.die.net/man/3/err\" rel=\"nofollow noreferrer\"><code>err()</code></a> for this, but to stay within the C standard, I recommend handling errors using <a href=\"https://en.cppreference.com/w/c/io/perror\" rel=\"nofollow noreferrer\"><code>perror()</code></a> and <code>abort()</code> like so:</p>\n<pre><code>test_log_data *create_and_init_test_log_data(const char* function_name, bool status, const char* path, bool stand_alone)\n{\n test_log_data* log_data = calloc(1, sizeof(*log_data));\n if (!log_data)\n perror(&quot;calloc()&quot;), abort();\n\n init_test_log_data(log_data, function_name, status, path, stand_alone);\n return log_data;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-29T12:35:13.927", "Id": "487021", "Score": "1", "body": "You found `extern` which was the basis for the archaic question, it used to be required for functions as well. I trying to stick to the C Standard rather than POSIX or any windows implementations, I included strdup because it finally made it into the C Standard sometime in the last year. In a unit_test it is probably fine to call `exit()` or abort(), but I've written device drivers and extended operating systems in other ways where that really isn't a good idea." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-29T13:10:38.230", "Id": "487025", "Score": "2", "body": "Sure, in a device driver or in kernel code, `exit()` and `abort()` are not options, but you would have something similar to stop everything in case of an *unrecoverable* error. Unless you are specifically testing whether your code is robust against out-of-memory conditions, OOM is normally considered unrecoverable, so calling `abort()` is totally fine. Note that `strcmp()` is C89, so if you ensure consistent capitalization of the filenames, then you don't need to use or reimplement `strcasecmp()`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-29T13:20:40.443", "Id": "487026", "Score": "1", "body": "If I use `abort()` I think I need to add `setjmp` to `main()` and `longjmp()` to everyplace where the error is possible and then call `abort()` from `main()` after doing any clean up." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-29T13:23:15.740", "Id": "487027", "Score": "1", "body": "No, don't try to do cleanup after an unrecoverable error, just `abort()` immediately. This will terminate the program, and will help a debugger see exactly where the error happened and what state your program was in. Trying to do any cleanup is not helpful, and will make debugging harder." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-30T13:57:14.080", "Id": "487133", "Score": "0", "body": "\" perfectly fine to call fclose(stdout) and fclose(stderr),\" --> except that closes those stream for all other code uses as well. OP conditional is a useful idea." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-30T14:01:06.707", "Id": "487135", "Score": "0", "body": "@pacmaninbw \"strdup because it finally made it into the C Standard sometime in the last year\" --> I do not think so (C17/18). Perhaps you are thinking of the next C2x?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-30T14:06:13.070", "Id": "487136", "Score": "0", "body": "Interesting code avoids `{}` in `if (!log_data) perror(\"calloc()\"), abort();`, yet uses unneeded `()` in `sizeof(*log_data)`. Hmmm." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-30T14:10:38.227", "Id": "487139", "Score": "0", "body": "@chux-ReinstateMonica I copied the `sizeof()` line verbatim from the question. Anyway, maybe even shorter is just calling `assert(log_data)`, and assuming the test suite is not compiled with `-DNDEBUG`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-30T14:39:56.607", "Id": "487143", "Score": "0", "body": "@chux-ReinstateMonica I found that out yesterday when I was trying to update files to test for the existence of `strdup()` and provide a declaration and definition when it didn't exist." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-31T13:26:33.240", "Id": "487244", "Score": "0", "body": "@G.Sliepen Let me know if you want me to remove [this](https://github.com/pacmaninbw/VMWithEditor/blob/Before_First_Code_Review/VMWithEditor/UnitTests/Common_UnitTest_Code/CodeReview.md) from the repository." } ], "meta_data": { "CommentCount": "10", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-29T11:11:37.863", "Id": "248611", "ParentId": "248561", "Score": "2" } } ]
{ "AcceptedAnswerId": "248611", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-28T17:50:57.613", "Id": "248561", "Score": "5", "Tags": [ "performance", "c", "unit-testing", "cyclomatic-complexity" ], "Title": "Hand Coded State Driven Lexical Analyzer in C With Unit Test Part C" }
248561
<p>I am new assembly programming in Linux (x86_64) and I want to make sure that I am programing in a correct way. I wrote a program that just takes an input from the user and then writes his input to stdout</p> <pre><code>SYS_WRITE equ 1 ; write text to stdout SYS_READ equ 0 ; read text from stdin SYS_EXIT equ 60 ; terminate the program STDOUT equ 1 ; stdout section .bss uinput resb 24 ; 24 bytes for user string uinput_len equ $ - uinput ; get length of user input section .data text db &quot;You wroted: &quot; text_len equ $ - text section .text global _start _start: mov rax, SYS_READ mov rdi, STDOUT mov rsi, uinput mov rdx, uinput_len syscall mov rax, SYS_WRITE mov rdi, STDOUT mov rsi, text mov rdx, text_len syscall mov rax, SYS_WRITE mov rdi, STDOUT mov rsi, uinput mov rdx, uinput_len syscall mov rax, SYS_EXIT mov rsi, 0 ; successful exit syscall </code></pre> <p>Am I doing this experiment correctly? Which suggestions do you find to improve this code? Could you please provide some resources to deepen in good practices (and if posible more features or effective techniques)?</p> <p>Thank you.</p>
[]
[ { "body": "\n<h3>Three small errors</h3>\n<blockquote>\n<pre class=\"lang-none prettyprint-override\"><code>section .data\n text db &quot;You wroted: &quot;\n text_len equ $ - text\n</code></pre>\n</blockquote>\n<p>A small spelling error (typo). Correct is: &quot;You wrote: &quot; without the <strong>d</strong>.</p>\n<hr />\n<blockquote>\n<pre class=\"lang-none prettyprint-override\"><code>mov rax, SYS_READ\nmov rdi, STDOUT\nmov rsi, uinput\nmov rdx, uinput_len\nsyscall\n</code></pre>\n</blockquote>\n<p>For <em>SYS_READ</em> you need to use <em>STDIN</em> instead of <em>STDOUT</em>.</p>\n<hr />\n<blockquote>\n<pre class=\"lang-none prettyprint-override\"><code>mov rax, SYS_EXIT\nmov rsi, 0 ; successful exit\nsyscall\n</code></pre>\n</blockquote>\n<p>The first parameter goes in the <code>RDI</code> register instead of <code>RSI</code>.</p>\n<h3>Three small improvements</h3>\n<blockquote>\n<pre class=\"lang-none prettyprint-override\"><code>section .bss\n uinput resb 24 ; 24 bytes for user string\n uinput_len equ $ - uinput ; get length of user input\n</code></pre>\n</blockquote>\n<p>It's strange to see a calculation for the <em>uinput_len</em> variable given that the length is a hardcoded 24. What you can write is:</p>\n<pre class=\"lang-none prettyprint-override\"><code>section .bss\n uinput_len equ 24 ; 24 bytes for user input\n uinput resb uinput_len\n</code></pre>\n<hr />\n<p>Be nice for the person that uses your program and show a prompt of some kind before expecting an input.</p>\n<hr />\n<p>For the final result you currently show the whole inputbuffer. What if the user didn't input that much characters? Best to only show the characters that were effectively inputted. You obtain this count in the <code>RAX</code> register upon returning from <em>SYS_READ</em>. e.g. If the user inputs 5 characters then <code>RAX</code> will hold 6. Those 5 characters plus the terminating newline character (0Ah).</p>\n<h3>Same code, different style</h3>\n<p>You should offset you tail comments so that they all start in the same column. This will improve readability.<br />\nAnd because <strong>readability is very very important</strong>, I've applied the same rule to the labels, mnemonics, and operands.</p>\n<pre class=\"lang-none prettyprint-override\"><code> SYS_READ equ 0 ; read text from stdin\n SYS_WRITE equ 1 ; write text to stdout\n SYS_EXIT equ 60 ; terminate the program\n STDIN equ 0 ; standard input\n STDOUT equ 1 ; standard output\n; --------------------------------\nsection .bss\n uinput_len equ 24 ; 24 bytes for user input\n uinput resb uinput_len ; buffer for user input\n; --------------------------------\nsection .data\n prompt db &quot;Please input some text: &quot;\n prompt_len equ $ - prompt\n text db 10, &quot;You wrote: &quot;\n text_len equ $ - text\n; --------------------------------\nsection .text\n global _start\n\n_start:\n mov rdx, prompt_len\n mov rsi, prompt\n mov rdi, STDOUT\n mov rax, SYS_WRITE\n syscall\n\n mov rdx, uinput_len\n mov rsi, uinput\n mov rdi, STDIN\n mov rax, SYS_READ\n syscall ; -&gt; RAX\n push rax ; (1)\n\n mov rdx, text_len\n mov rsi, text\n mov rdi, STDOUT\n mov rax, SYS_WRITE\n syscall\n\n pop rdx ; (1)\n mov rsi, uinput\n mov rdi, STDOUT\n mov rax, SYS_WRITE\n syscall\n\n xor edi, edi ; successful exit\n mov rax, SYS_EXIT\n syscall\n</code></pre>\n<p>Instead of <code>mov rdi, 0</code>, I've used <code>xor edi, edi</code> which is shorter and faster and leaves the same result (0) in the <code>RDI</code> register.</p>\n<p>I always prefer to write the function number directly above the <code>syscall</code> instruction. I find this clearer. As a consequence I've also inversed the order of the other parameters, again for clarity.</p>\n<hr />\n<hr />\n<p>You can learn a lot about 64-bit Linux programming from the .PDF that you can <a href=\"http://www.egr.unlv.edu/%7Eed/assembly64.pdf\" rel=\"nofollow noreferrer\">download here</a><br />\nIt provides good examples that deal with console input and console output and more.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-09-26T22:37:40.553", "Id": "490064", "Score": "1", "body": "Awesome, thank you very much. I learned a lot (:" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-30T18:22:10.407", "Id": "248664", "ParentId": "248569", "Score": "1" } } ]
{ "AcceptedAnswerId": "248664", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-28T21:01:31.693", "Id": "248569", "Score": "3", "Tags": [ "linux", "assembly", "x86" ], "Title": "Simple input and output in assembly x86_64" }
248569
<p>I wrote some code to get 3 integers from the user. The code then prints the sum of the 3 integers. The code works as expected. I want to validate all input before doing the calculation. However, the code just doesn't feel right. Is there another approach I should be taking? It seems.. redundant. I am looking into nested try/except, but so far no luck.</p> <pre><code>msg = &quot;Invalid Input&quot; while True: try: a = int(input(&quot;Enter 1st number: &quot;)) break except: print(msg) while True: try: b = int(input(&quot;Enter 2nd number: &quot;)) break except: print(msg) while True: try: c = int(input(&quot;Enter 3rd number: &quot;)) break except: print(msg) print(a + b + c) </code></pre> <p><a href="https://i.stack.imgur.com/NOzEB.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/NOzEB.png" alt="output" /></a></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-28T21:21:18.983", "Id": "486968", "Score": "1", "body": "You could create a function and include on it the while loop and if needed a numerical range (interval) to validate the input so that your code be more cleaner." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-28T22:55:16.550", "Id": "486973", "Score": "0", "body": "@MiguelAvila thanks for the suggestion. I made some edits above. Is that what you were talking about?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-29T01:49:37.140", "Id": "486983", "Score": "0", "body": "Yes, I was referring to that. Btw this video https://www.youtube.com/watch?v=C-gEQdGVXbk&t=1781s is really useful, the dude mentions pretty efficient python features to be more expressive with less code. (I would recommend his channel)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-29T02:18:28.927", "Id": "486986", "Score": "0", "body": "Thanks! I will check it out." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-29T06:50:50.273", "Id": "486993", "Score": "0", "body": "Please do not update the code in your question after receiving answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-29T22:28:52.390", "Id": "487076", "Score": "0", "body": "my apologies. i will keep that in mind." } ]
[ { "body": "<p>When you have three intimately related variables like this it would be natural to see whether this can be done as a <code>list</code> instead. Some tips to do that:</p>\n<ol>\n<li>You can use a loop to collect all the items you want.</li>\n<li><code>range(N)</code> gives you a generator to iterate over numbers 0 through N.</li>\n<li>You can either initialize an empty list inside the loop to avoid keeping old results, or continue from the last successfully gathered index to avoid asking the same question twice.</li>\n<li>You can use the <a href=\"https://pypi.org/project/inflect/\" rel=\"nofollow noreferrer\">inflect library</a> to generate ordinals.</li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-28T21:32:12.010", "Id": "248572", "ParentId": "248570", "Score": "2" } }, { "body": "<p>Your revised code in on the right track. You can simplify the function a fair bit:</p>\n<pre><code>def get_integer_input(prompt):\n while True:\n try:\n # Just return directly. No need for an invalid_input flag.\n return int(input(prompt))\n except ValueError:\n print('Invalid input')\n\n# Where you see repetition in your code, consider using a data structure to\n# address it. There are libraries that will give you the ordinals. Personally,\n# I would just rephrase the input() prompt so that the ordinals are not needed.\nORDINALS = ('1st', '2nd', '3rd')\n\n# Get the integers.\nfmt = 'Enter {} number: '\na, b, c = [get_integer_input(fmt.format(o)) for o in ORDINALS]\nprint(a + b + c)\n\n# Or if you care only about the total, just get it directly.\ntot = sum(get_integer_input(fmt.format(o)) for o in ORDINALS)\nprint(tot)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-28T23:12:03.140", "Id": "248582", "ParentId": "248570", "Score": "4" } } ]
{ "AcceptedAnswerId": "248582", "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-28T21:06:08.887", "Id": "248570", "Score": "4", "Tags": [ "python", "python-3.x" ], "Title": "How to create a validation loop for multiple inputs" }
248570
<p>It is my first program in Javascript. Is there any lack or a thing to be improved? It simply increases, decreases, or reset the counter either by buttons or arrow keys.</p> <p>HTML,</p> <pre><code>&lt;h1 id=&quot;number&quot;&gt;&lt;/h1&gt; &lt;button class=&quot;btn&quot; id=&quot;incr&quot;&gt;Increase&lt;/button&gt; &lt;button class=&quot;btn&quot; id=&quot;reset&quot;&gt;Reset&lt;/button&gt; &lt;button class=&quot;btn&quot; id=&quot;decr&quot;&gt;Decrease&lt;/button&gt; </code></pre> <p>JS,</p> <pre><code>let number = 0 const getNumber = document.getElementById(`number`) const incrButton = document.getElementById(`incr`) const decrButton = document.getElementById(`decr`) const resetButton = document.getElementById(`reset`) getNumber.textContent = number const incrFunc = function () { ++number getNumber.textContent = number if (number &gt; 0) { getNumber.style.color = `green` } } const resetFunc = function () { number = 0 getNumber.textContent = number getNumber.style.color = `gray` } const decrFunc = function () { --number getNumber.textContent = number if (number &lt; 0) { getNumber.style.color = `red` } } incrButton.addEventListener(`keyup`, function (e) { e.stopPropagation() //console.log(e.target === document.body) if (e.code === `ArrowUp`) { incrFunc() } }) document.addEventListener(`keyup`, function (e) { //console.log(e.target === document.body) if (e.code === `ArrowUp`) { incrFunc() } }) document.addEventListener(`keyup`, function (e) { if (e.code === `ArrowRight` || e.code === `ArrowLeft`) { resetFunc() } }) resetButton.addEventListener(`keyup`, function (e) { if (e.code === `ArrowRight` || e.code === `ArrowLeft`) { resetFunc() } }) document.addEventListener(`keyup`, function (e) { if (e.code === `ArrowDown`) { decrFunc() } }) decr.addEventListener(`keyup`, function (e) { if (e.code === `ArrowDown`) { decrFunc() } }) incrButton.addEventListener(`click`, incrFunc) resetButton.addEventListener(`click`, resetFunc) decrButton.addEventListener(`click`, decrFunc) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-29T05:54:37.617", "Id": "486992", "Score": "0", "body": "May just be a copy/paste typo, but `decr.addEventListener(`keyup`, ...` looks like it should probably be `decrButton.addEventListener(`keyup`, ...`." } ]
[ { "body": "<p>My first advice would be to reformat your code with a linter. I won't go into this in more detail because I assume you're mostly after implementation advice, but as it is it's quite jarring to read, similar to text written in your own language but with foreign capitalization and punctuation.</p>\n<p>Some of your functions could use destructuring to make their bodies more terse.</p>\n<p>For instance, this:</p>\n<pre><code>document.addEventListener(`keyup`, function (e) {\n if (e.code === `ArrowRight` || e.code === `ArrowLeft`) {\n resetFunc()\n }\n})\n</code></pre>\n<p>Could be rewritten as this, since you're only using the <code>code</code> property of the argument:</p>\n<pre><code>document.addEventListener(`keyup`, function ({ code }) {\n if (code === `ArrowRight` || code === `ArrowLeft`) {\n resetFunc()\n }\n})\n</code></pre>\n<p>A more controversial bit of advice might be to write this at the top of your script:</p>\n<pre><code>const $ = document.querySelector.bind(document);\n</code></pre>\n<p>This allows you to replace this:</p>\n<pre><code>const getNumber = document.getElementById(`number`)\nconst incrButton = document.getElementById(`incr`)\nconst decrButton = document.getElementById(`decr`)\nconst resetButton = document.getElementById(`reset`)\n</code></pre>\n<p>With something much less verbose:</p>\n<pre><code>const getNumber = $(`#number`)\nconst incrButton = $(`#incr`)\nconst decrButton = $(`#decr`)\nconst resetButton = $(`#reset`)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-29T20:27:19.480", "Id": "248636", "ParentId": "248575", "Score": "3" } }, { "body": "<p>You should be using a semicolon at the end of lines.</p>\n<p>There is no need to have keyup event on the buttons, the document will catch the event. You also only need a single event listener on the document.</p>\n<pre><code>document.addEventListener(`keyup`, function (e) {\n if (e.code === `ArrowUp`) {\n incrFunc();\n }\n else if (e.code === `ArrowDown`) {\n decrFunc();\n }\n else if (e.code === `ArrowRight` || e.code === `ArrowLeft`) {\n resetFunc();\n }\n})\n</code></pre>\n<p>Your functions for increasing, deceasing, and resetting are similar enough that they can be combined, so you don't have to repeat the same code. This way you also have a way set the number to any value or change it by any amount if you need that later.</p>\n<pre><code>function setNumber(value) {\n number = value;\n getNumber.textContent = number\n if (number &lt; 0) {\n getNumber.style.color = `red`\n }\n else if (number &gt; 0) {\n getNumber.style.color = `green`\n }\n else {\n getNumber.style.color = `gray`\n }\n}\n\nfunction changeNumber(change) {\n setNumber(number + change);\n}\n</code></pre>\n<p>You can set the event listeners with pre-set arguments with <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind\" rel=\"nofollow noreferrer\">bind</a>. The first argument is to set the <code>this</code> keyword, which we don't use, so we can just set it to <code>null</code>.</p>\n<pre><code>incr.addEventListener(`click`, changeNumber.bind(null, 1));\nreset.addEventListener(`click`, setNumber.bind(null, 0));\ndecr.addEventListener(`click`, changeNumber.bind(null, -1));\n</code></pre>\n<p>While saving an element to a variable when it's reference multiple times is a good practice, there's no need to when it's only used once.</p>\n<p>Lastly, <code>getNumber</code> is not a good descriptive name.</p>\n<p>The final code.</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const numberDisplay = document.getElementById(`number`);\nlet number = 0;\nsetNumber(number);\n\nfunction setNumber(value) {\n number = value;\n numberDisplay.textContent = number;\n if (number &lt; 0) {\n numberDisplay.style.color = `red`;\n }\n else if (number &gt; 0) {\n numberDisplay.style.color = `green`;\n }\n else {\n numberDisplay.style.color = `gray`;\n }\n}\n\nfunction changeNumber(change) {\n setNumber(number + change);\n}\n\ndocument.addEventListener(`keyup`, function (e) {\n if (e.code === `ArrowUp`) {\n changeNumber(1);\n }\n else if (e.code === `ArrowDown`) {\n changeNumber(-1);\n }\n else if (e.code === `ArrowRight` || e.code === `ArrowLeft`) {\n setNumber(0);\n }\n})\n\ndocument.getElementById(`incr`).addEventListener(`click`, changeNumber.bind(null, 1));\ndocument.getElementById(`reset`).addEventListener(`click`, setNumber.bind(null, 0));\ndocument.getElementById(`decr`).addEventListener(`click`, changeNumber.bind(null, -1));</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;h1 id=\"number\"&gt;&lt;/h1&gt;\n&lt;button class=\"btn\" id=\"incr\"&gt;Increase&lt;/button&gt;\n&lt;button class=\"btn\" id=\"reset\"&gt;Reset&lt;/button&gt;\n&lt;button class=\"btn\" id=\"decr\"&gt;Decrease&lt;/button&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-31T11:49:20.503", "Id": "248696", "ParentId": "248575", "Score": "3" } }, { "body": "<p>Maybe you could map every key code with a function and avoid to check the keyCode multiple times</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"true\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const map = {\n 'ArrowUp': incrFunc,\n 'ArrowRight': resetFunc,\n 'ArrowLeft': resetFunc,\n 'ArrowDown': decrFunc,\n}\n\ndocument.addEventListener(`keyup`, function (e) {\n if(map[e.code]) {\n map[e.code]();\n }\n})</code></pre>\r\n</div>\r\n</div>\r\n</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-09-03T02:19:40.890", "Id": "248839", "ParentId": "248575", "Score": "1" } }, { "body": "<p>Don't use template strings (<code>`number`</code>) if you are not actually using templates. Use normal single or double quotes: <code>'number'</code> or <code>&quot;number&quot;</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-09-04T08:38:24.073", "Id": "487735", "Score": "0", "body": "My favourite style guide agrees with you, but why though?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-09-04T08:49:26.690", "Id": "487737", "Score": "1", "body": "Performance: The JS engine will try to find placeholders where there are none. Readability: The reader may expect that something special is happening here when there is nothing. Writability(?): On some keyboard layouts the back tick can be tricky to type. (These are all my personal thoughts, not based on any style guide)." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-09-04T08:14:14.517", "Id": "248909", "ParentId": "248575", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-28T21:46:33.567", "Id": "248575", "Score": "6", "Tags": [ "javascript" ], "Title": "Simple Counter Program" }
248575
<p>I implemented a multi-producer single consumer class, with an important restriction that once the consumer started working, it <strong>must</strong> continue its work on the same thread (the reasoning behind this is to allocate and free COM objects from a third party library, and these actions must be on the same thread according to that library).</p> <p>Here's the code, followed by an example:</p> <pre><code>interface WorkerLogic&lt;T&gt; { void Work(T item); } class ThreadedWorker&lt;T&gt; where T : class { private readonly object locker = new object(); private readonly Queue&lt;T&gt; queue = new Queue&lt;T&gt;(); private readonly WorkerLogic&lt;T&gt; logic; private readonly Thread actualThread; private bool started = false; private readonly ManualResetEvent resetEvent = new ManualResetEvent(false); private volatile bool shouldWork = true; public ThreadedWorker(WorkerLogic&lt;T&gt; logic) { this.logic = logic; actualThread = new Thread(Spin); } private void Spin() { while (shouldWork) { resetEvent.WaitOne(); while (shouldWork) { T item; lock (locker) { if (queue.Count == 0) break; // back to main loop and WaitOne item = queue.Dequeue(); resetEvent.Reset(); } try { logic.Work(item); } catch (Exception ex) { // log } } } } public void Stop() { Stop(TimeSpan.FromMilliseconds(500)); } public void Stop(TimeSpan timeout) { shouldWork = false; lock (locker) { resetEvent.Set(); } bool joined = actualThread.Join(timeout); if (!joined) { try { actualThread.Abort(); } catch (ThreadStateException) { // swallow } } } public void Push(T item) { lock (locker) { queue.Enqueue(item); if (!started) { started = true; actualThread.Start(); } resetEvent.Set(); } } } </code></pre> <p>Usage example for the code above:</p> <pre><code>public class UsageExample { public class MyLogic : WorkerLogic&lt;string&gt; { public void Work(string s) { Console.WriteLine(&quot;working on '{0}', thread id = {1}&quot;, s, Thread.CurrentThread.ManagedThreadId); } } public static void Main() { ThreadedWorker&lt;string&gt; threadedWorker = new ThreadedWorker&lt;string&gt;(new MyLogic()); threadedWorker.Push(&quot;My&quot;); threadedWorker.Push(&quot;name&quot;); threadedWorker.Push(&quot;is&quot;); threadedWorker.Push(&quot;Luca&quot;); threadedWorker.Stop(); } } </code></pre> <p>Example output:</p> <pre><code>working on 'My', thread id = 3 working on 'name', thread id = 3 working on 'is', thread id = 3 working on 'Luca', thread id = 3 </code></pre> <p>I created a <a href="https://repl.it/@ronklein/MyNameIsLuca#main.cs" rel="nofollow noreferrer">repl</a> for this, feel free to play with it.</p> <p>I'd like to have a peer review focused on <strong>correctness</strong>: is it thread safe? Am I missing an edge case?</p> <p>Thanks!</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-29T09:17:59.807", "Id": "487010", "Score": "1", "body": "Not sure if this is the kind of feedback you're after, but it looks like you could simplify your `ThreadedWorker<T>` considerably by using a [`BlockingCollection<T>`](https://docs.microsoft.com/en-us/dotnet/api/system.collections.concurrent.blockingcollection-1?view=netcore-3.1)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-29T12:56:52.993", "Id": "487023", "Score": "1", "body": "In case of .NET Core [`System.Threading.Channels`](https://devblogs.microsoft.com/dotnet/an-introduction-to-system-threading-channels/) may also help." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-09-03T14:37:54.703", "Id": "487677", "Score": "0", "body": "Please do not update the original code in your question. The comments and the code might be out of sync. Instead post as an answer or if you wish to receive further review suggestions then please open a new question." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-09-03T15:18:58.267", "Id": "487682", "Score": "1", "body": "@PeterCsala I made changes according to your suggestions." } ]
[ { "body": "<p>I took <a href=\"https://codereview.stackexchange.com/users/206953/rob-earwaker\">rob.earwaker</a>'s advice (thanks!), and I implemented it using a BlockingCollection. The code is much simpler now :)</p>\n<pre><code>class ThreadedWorker&lt;T&gt; where T : class\n{\n private readonly object locker = new object();\n BlockingCollection&lt;T&gt; queue = new BlockingCollection&lt;T&gt;(new ConcurrentQueue&lt;T&gt;());\n private readonly WorkerLogic&lt;T&gt; logic;\n private readonly Thread actualThread;\n private bool started = false;\n private volatile bool shouldWork = true;\n\n public ThreadedWorker(WorkerLogic&lt;T&gt; logic)\n {\n\n this.logic = logic;\n actualThread = new Thread(Spin);\n \n }\n\n private void Spin()\n {\n while (shouldWork)\n {\n T item;\n var dequeued = queue.TryTake(out item, TimeSpan.FromMilliseconds(100));\n if (!dequeued) continue;\n try\n {\n logic.Work(item);\n }\n catch (Exception ex)\n {\n // log\n }\n\n } \n }\n\n public void Stop()\n {\n Stop(TimeSpan.FromMilliseconds(500));\n }\n\n public void Stop(TimeSpan timeout)\n {\n shouldWork = false; \n bool joined = actualThread.Join(timeout);\n if (!joined)\n {\n try\n {\n actualThread.Abort();\n }\n catch (ThreadStateException)\n {\n // swallow\n }\n }\n }\n\n\n public void Push(T item)\n {\n if (!started)\n {\n lock (locker)\n {\n if (!started)\n {\n started = true;\n actualThread.Start();\n }\n }\n }\n queue.Add(item);\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-09-03T15:17:55.107", "Id": "248875", "ParentId": "248576", "Score": "0" } } ]
{ "AcceptedAnswerId": "248875", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-28T22:09:03.867", "Id": "248576", "Score": "2", "Tags": [ "c#", "multithreading", "thread-safety", "queue" ], "Title": "Multiple producer single consumer on the same thread" }
248576
<p>I am using SignalR to send notifications to clients. I use <code>IClientProxy</code> which is a proxy for invoking hub methods.</p> <p>It has 10 overload methods for <code>SendAsync</code> that takes parameters one by one as you see below, however, to handle this situation I have written a spagetti style method which is really weird to me.</p> <p>Could you please give some suggestion?</p> <pre class="lang-cs prettyprint-override"><code>private async Task InvokeNotification(string userName, string methodName, params object[] parameters) { if (connections.ContainsKey(userName)) { var proxy = Clients.Clients(connections[userName]); switch (parameters.Length) { case 0: await proxy.SendAsync(methodName); break; case 1: await proxy.SendAsync(methodName, parameters[0]); break; case 2: await proxy.SendAsync(methodName, parameters[0], parameters[1]); break; default: throw new HubException($&quot;No method was defined with {parameters.Length} parameters in Hub&quot;); } } } </code></pre> <p>The following code block is the definition of SendAsync which is coming from SignalR</p> <pre class="lang-cs prettyprint-override"><code>public static class ClientProxyExtensions { public static Task SendAsync(this IClientProxy clientProxy, string method, object arg1, object arg2, object arg3, object arg4, object arg5, object arg6, object arg7, object arg8, object arg9, object arg10, CancellationToken cancellationToken = default); public static Task SendAsync(this IClientProxy clientProxy, string method, object arg1, object arg2, object arg3, object arg4, object arg5, object arg6, object arg7, object arg8, object arg9, CancellationToken cancellationToken = default); public static Task SendAsync(this IClientProxy clientProxy, string method, object arg1, object arg2, object arg3, object arg4, object arg5, object arg6, object arg7, object arg8, CancellationToken cancellationToken = default); public static Task SendAsync(this IClientProxy clientProxy, string method, object arg1, object arg2, object arg3, object arg4, object arg5, object arg6, object arg7, CancellationToken cancellationToken = default); public static Task SendAsync(this IClientProxy clientProxy, string method, object arg1, object arg2, object arg3, object arg4, object arg5, object arg6, CancellationToken cancellationToken = default); public static Task SendAsync(this IClientProxy clientProxy, string method, object arg1, object arg2, object arg3, object arg4, object arg5, CancellationToken cancellationToken = default); public static Task SendAsync(this IClientProxy clientProxy, string method, object arg1, object arg2, object arg3, object arg4, CancellationToken cancellationToken = default); public static Task SendAsync(this IClientProxy clientProxy, string method, object arg1, object arg2, object arg3, CancellationToken cancellationToken = default); public static Task SendAsync(this IClientProxy clientProxy, string method, object arg1, object arg2, CancellationToken cancellationToken = default); public static Task SendAsync(this IClientProxy clientProxy, string method, object arg1, CancellationToken cancellationToken = default); public static Task SendAsync(this IClientProxy clientProxy, string method, CancellationToken cancellationToken = default); } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-29T13:44:44.853", "Id": "487030", "Score": "0", "body": "Can you show the `SendAsync` method overloads? Does it apply `params` too? If it is, you may pass parameters as array there." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-29T14:43:21.943", "Id": "487038", "Score": "1", "body": "@aepot , I updated the code" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-30T14:27:38.773", "Id": "487142", "Score": "0", "body": "Is `connections` a kind of `Dictionary`? I can suggest one more improvement then." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-30T17:04:23.647", "Id": "487149", "Score": "1", "body": "Yes it is, please shot!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-30T17:34:00.767", "Id": "487152", "Score": "0", "body": "Updated the answer." } ]
[ { "body": "<p>As for me, this code is fine. Maybe there's some <code>Reflection</code> dark magic available but this one will be anyway faster.</p>\n<p>The only thing I can suggest here is optimizing out an <code>async</code> State Machine because there's no code after <code>await</code> and the only await in the method can be executed.</p>\n<p>Also note that you lookup through the <code>Dictionary</code> twice, first time when you check key with <code>.ContainsKey</code>, second time when you get the value with the same key. It can be done with single lookup using <code>Dictionary.TryGetValue()</code> method.</p>\n<p>Also I suggest to follow <code>async</code> naming policy suggested by Microsoft, and rename the method to <code>InvokeNotificationAsync</code>.</p>\n<pre class=\"lang-csharp prettyprint-override\"><code>private Task InvokeNotificationAsync(string userName, string methodName, params object[] parameters)\n{\n if (connections.TryGetValue(userName, out var connection))\n {\n var proxy = Clients.Clients(connection);\n switch (parameters.Length)\n {\n case 0:\n return proxy.SendAsync(methodName);\n break;\n\n case 1:\n return proxy.SendAsync(methodName, parameters[0]);\n break;\n\n case 2:\n return proxy.SendAsync(methodName, parameters[0], parameters[1]);\n break;\n\n default:\n throw new HubException($&quot;No method was defined with {parameters.Length} parameters in Hub&quot;);\n }\n }\n}\n</code></pre>\n<p>Also it can look a bit better with C# 8.0 syntax</p>\n<pre class=\"lang-csharp prettyprint-override\"><code>private Task InvokeNotificationAsync(string userName, string methodName, params object[] parameters)\n{\n if (connections.TryGetValue(userName, out var connection))\n {\n var proxy = Clients.Clients(connection);\n return parameters.Length switch\n {\n 0 =&gt; proxy.SendAsync(methodName),\n 1 =&gt; proxy.SendAsync(methodName, parameters[0]),\n 2 =&gt; proxy.SendAsync(methodName, parameters[0], parameters[1]),\n _ =&gt; throw new HubException($&quot;No method was defined with {parameters.Length} parameters in Hub&quot;)\n };\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-29T15:54:28.410", "Id": "248626", "ParentId": "248577", "Score": "3" } } ]
{ "AcceptedAnswerId": "248626", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-28T22:14:44.687", "Id": "248577", "Score": "3", "Tags": [ "c#", "overloading", "signalr" ], "Title": "Over overloaded method" }
248577
<p>Below is the implementation for the Floyd-Warshall algorithm, which finds all-pairs shortest paths for a given weighted graph.</p> <p>The function <code>floyd_warshall</code> takes a graph as an input, which is represented by an edge list in the form of [<em>source</em>, <em>destination</em>, <em>weight</em>]</p> <p>The <code>path_reconstruction</code> function outputs the shortest paths from each vertex that is connected to every other vertex.</p> <p>Please provide suggestions for improvements of any sort.</p> <pre><code>import sys INF = sys.maxsize def floyd_warshall(graph): source_vertices = [column[0] for column in graph] destination_vertices = [column[1] for column in graph] vertices = list(set(source_vertices) | set(destination_vertices)) distance = [[INF] * len(vertices) for i in range(len(vertices))] next_vertices = [[0] * len(vertices) for i in range(len(vertices))] for i in range(len(vertices)): distance[i][i] = 0 for source, destination, weight in graph: distance[source-1][destination-1] = weight next_vertices[source-1][destination-1] = destination-1 for k in range(len(vertices)): for i in range(len(vertices)): for j in range(len(vertices)): if distance[i][j] &gt; distance[i][k] + distance[k][j]: distance[i][j] = distance[i][k] + distance[k][j] next_vertices[i][j] = next_vertices[i][k] path_reconstruction(distance, next_vertices) def path_reconstruction(dist, nxt): print(&quot;Edge \t\t Distance \t Shortest Path&quot;) for i in range(len(dist)): for j in range(len(dist)): if i != j: path = [i] while path[-1] != j: path.append(nxt[path[-1]][j]) print(&quot;(%d, %d) \t\t %2d \t\t %s&quot; % (i + 1, j + 1, dist[i][j], ' - '.join(str(p + 1) for p in path))) print() def main(): edge_list1 = [ [1, 3, -2], [2, 1, 4], [2, 3, 3], [3, 4, 2], [4, 2, -1] ] edge_list2 = [ [1, 2, 10], [1, 3, 20], [1, 4, 30], [2, 6, 7], [3, 6, 5], [4, 5, 10], [5, 1, 2], [5, 6, 4], [6, 2, 5], [6, 3, 7], [6, 5, 6] ] floyd_warshall(edge_list1) floyd_warshall(edge_list2) if __name__ == '__main__': main() </code></pre>
[]
[ { "body": "<p>Your program provides a good example for seeing how one can increase code readability through some common techniques: (1) convenience variables to avoid verbose repetition; (2) code organized as small commented &quot;paragraphs&quot; or blocks; and (3) the use of <strong>shorter</strong> variables names to lighten the visual weight of the code, thus enhancing ease of reading and visual scanning. Note that short names must be used judiciously: because they can be cryptic, short vars typically\nderive their meaning either from a consistently used convention in the program\nor from other contextual clues (eg, from nearby functions or collections having more explicit names and from well-placed comments). Here's a heavily edited version of <code>floyd_warshall()</code> along those lines. Because I'm lazy, I will assume that you implemented Floyd-Warshall correctly.</p>\n<pre><code>def floyd_warshall(graph):\n # Collect all vertices.\n vertices = set(\n col[i]\n for col in graph\n for i in (0, 1)\n )\n n = len(vertices)\n rng = range(n)\n\n # Initialize the distance and next-vertex matrix.\n dists = [\n [0 if i == j else INF for j in rng]\n for i in rng\n ]\n next_vertices = [\n [0 for j in rng]\n for i in rng\n ]\n\n # Populate the matrixes.\n for src, dst, weight in graph:\n i = src - 1\n j = dst - 1\n dists[i][j] = weight\n next_vertices[i][j] = j\n\n # Do that Floyd-Warshall thing.\n for k in rng:\n for i in rng:\n for j in rng:\n ikj = dists[i][k] + dists[k][j]\n if dists[i][j] &gt; ikj:\n dists[i][j] = ikj\n next_vertices[i][j] = next_vertices[i][k]\n\n return path_reconstruction(dists, next_vertices)\n</code></pre>\n<p>A bigger issue is that your <code>floyd_warshall()</code> function should not be calling a\nfunction that prints. Rather it should return some kind of meaningful data.\nThat approach makes your function more readily testable. For example,\n<code>path_reconstruction()</code> could return a list of declarative dicts.</p>\n<pre><code>def path_reconstruction(dists, next_vertices):\n # Same ideas here: return data, don't print; use convenience\n # vars where they help with readability.\n rng = range(len(dists))\n paths = []\n for i in rng:\n for j in rng:\n if i != j:\n path = [i]\n while path[-1] != j:\n path.append(next_vertices[path[-1]][j])\n paths.append(dict(\n i = i,\n j = j,\n dist = dists[i][j],\n path = path,\n ))\n return paths\n</code></pre>\n<p>Then do your printing outside of the algorithmic code.</p>\n<pre><code>def main():\n edge_lists = [\n [\n [1, 3, -2],\n [2, 1, 4],\n [2, 3, 3],\n [3, 4, 2],\n [4, 2, -1],\n ],\n [\n [1, 2, 10],\n [1, 3, 20],\n [1, 4, 30],\n [2, 6, 7],\n [3, 6, 5],\n [4, 5, 10],\n [5, 1, 2],\n [5, 6, 4],\n [6, 2, 5],\n [6, 3, 7],\n [6, 5, 6],\n ],\n ]\n for el in edge_lists:\n paths = floyd_warshall(el)\n for p in paths:\n print(p)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-29T18:32:49.850", "Id": "487056", "Score": "0", "body": "In python 3 ‘range’ is an iterator, so rng will be exhausted after the first use." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-29T19:31:42.137", "Id": "487061", "Score": "0", "body": "@MaartenFabré Try it in a Python REPL and I think you'll be surprised. For example: `rng = range(3) ; print(list(rng)) ; print(list(rng)) ; print(rng[1])`. Or `next(rng)`, which will fail, because a range is not an iterator. There's probably a more authoritative way to prove the point, but those practical usages convince me." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-29T20:03:58.383", "Id": "487062", "Score": "0", "body": "@MaartenFabré A `range()` is an iterable, not an iterator. It is reusable in exactly the same way a `list` is reusable; you can iterate over them multiple times, even simultaneously in parallel threads." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-29T20:15:01.650", "Id": "487064", "Score": "1", "body": ":facepalm: that's what you get by replying on your phone without checking..." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-29T00:24:31.807", "Id": "248584", "ParentId": "248578", "Score": "6" } }, { "body": "<p><a href=\"https://codereview.stackexchange.com/a/248584/100620\">FMc</a> has made some excellent points. I'll try not to repeat those.</p>\n<h1>Vertices</h1>\n<p>You determine the list of vertices using:</p>\n<pre><code> source_vertices = [column[0] for column in graph]\n destination_vertices = [column[1] for column in graph]\n vertices = list(set(source_vertices) | set(destination_vertices))\n</code></pre>\n<p>and then repeatedly use <code>len(vertices)</code> through-out your code.</p>\n<p>FMc suggests using:</p>\n<pre><code> vertices = set(col[i] for col in graph for i in (0, 1))\n n = len(vertices)\n</code></pre>\n<p>Both implementations use sets to form a cover of all vertices. But this doesn't really make any sense. You're using <code>range(len(vertices))</code> to determine the indices. What if the graphs used the vertices 1, 2, 4, &amp; 5? Your sets would be <code>{1, 2, 4, 5}</code>, the length of the set is <code>4</code>, and <code>range(4)</code> produces the indices <code>0</code>, <code>1</code>, <code>2</code>, and <code>3</code>. But you execute:</p>\n<pre><code> for source, destination, weight in graph:\n distance[source-1][destination-1] = weight\n</code></pre>\n<p>you'd find <code>source</code> or <code>destination</code> is <code>5</code>, compute subtract 1, to get the index 4, and find you've fallen off the end of the matrix!</p>\n<p>Clearly, there is a requirement that all indices from <code>1</code> to <code>N</code> must be used, with no gaps allowed. But then, you don't need a set. You just need to find the maximum index.</p>\n<pre><code> n = max(edge[col] for edge in graph for col in (0, 1))\n</code></pre>\n<h1>Indexing is slow</h1>\n<p>In this code, for 100 vertices, how many times is <code>distance[i]</code> evaluated? How about <code>distance[k]</code>?</p>\n<pre><code> for k in range(len(vertices)):\n for i in range(len(vertices)):\n for j in range(len(vertices)):\n if distance[i][j] &gt; distance[i][k] + distance[k][j]:\n distance[i][j] = distance[i][k] + distance[k][j]\n next_vertices[i][j] = next_vertices[i][k]\n</code></pre>\n<p><code>distance[i]</code> is looked up somewhere between 2000000 and 4000000 times? Seems excessive, perhaps? <code>distance[k]</code> is looked up between 1000000 and 2000000 times. A wee bit less, but still quite a few.</p>\n<p>Once you've entered the first <code>for</code> loop <code>k</code> is a constant for that iteration. You could lookup <code>distance[k]</code> once. Similarly, once you've entered the second <code>for</code> loop, <code>i</code> is a constant for that iteration. You could lookup <code>distance[i]</code> once.</p>\n<pre><code> for k in range(len(vertices)):\n distance_k = distance[k]\n for i in range(len(vertices)):\n distance_i = distance[i]\n for j in range(len(vertices)):\n if distance_i[j] &gt; distance_i[k] + distance_k[j]:\n distance_i[j] = distance_i[k] + distance_k[j]\n next_vertices[i][j] = next_vertices[i][k]\n</code></pre>\n<p>Now, were looking up distance[k] only 100 times, and distance[i] only 10000 times. This will be a speed improvement.</p>\n<p>We can do the for loops better: getting the indices and looking up the values together, using <code>enumerate</code>, and looping over the rows of the <code>distance</code> matrix:</p>\n<pre><code> for k, distance_k in enumerate(distance):\n for i, distance_i in enumerate(distance):\n for j in range(len(vertices)):\n if distance_i[j] &gt; distance_i[k] + distance_k[j]:\n distance_i[j] = distance_i[k] + distance_k[j]\n next_vertices[i][j] = next_vertices[i][k]\n</code></pre>\n<p>Again, <code>distance_i[k]</code> does not change in the inner loop, so we can look it up once in the middle loop:</p>\n<pre><code> for k, distance_k in enumerate(distance):\n for i, distance_i in enumerate(distance):\n dist_ik = distance_i[k]\n for j in range(len(vertices)):\n dist_ik_kj = dist_ik + distance_k[j]\n if distance_i[j] &gt; dist_ik_kj:\n distance_i[j] = dist_ik_kj \n next_vertices[i][j] = next_vertices[i][k]\n</code></pre>\n<p>Finally, we can iterate over the <code>distance_k</code> row of the matrix, to avoid addition lookup overheads:</p>\n<pre><code> for k, distance_k in enumerate(distance):\n for i, distance_i in enumerate(distance):\n dist_ik = distance_i[k]\n for j, dist_kj in enumerate(distance_k):\n dist_ik_kj = dist_ik + dist_kj\n if distance_i[j] &gt; dist_ik_kj:\n distance_i[j] = dist_ik_kj \n next_vertices[i][j] = next_vertices[i][k]\n</code></pre>\n<p>Both <code>next_vertices[i]</code> and <code>next_vertices[i][k]</code> are constant in the inner loop; we could look them up once in the middle loop, for additional savings. You could even <code>zip</code> <code>distance</code> and <code>next_vertices</code> together in the <code>for i, ...</code> statement and look up both <code>distance_i</code> and <code>next_vertices_i</code> simultaneously. But perhaps that is getting a little too advanced.</p>\n<h1>Memory</h1>\n<p>Python lists are memory hogs. This doesn't matter if your graphs don't have more than a few hundred vertices. But if you want to support larger graphs (thousands of vertices? hundreds of thousands of vertices?), you'll want to use memory efficient structures.</p>\n<p>You could use <code>numpy</code> to create your NxN <code>distance</code> and <code>next_vertices</code> matrices. But if you don't have <code>numpy</code> installed, we don't have to use that sledgehammer. Python does come with more memory efficient <code>array</code> objects, which can only store scalar information (integers, floats, characters) instead of the Jack-of-all-Trade heterogeneous lists of lists.</p>\n<p><code>next_vertices</code> hold integer vertex values. Instead of:</p>\n<pre><code>next_vertices = [[0] * len(vertices) for i in range(len(vertices))]\n</code></pre>\n<p>consider:</p>\n<pre><code>zeros = [0] * len(vertices)\nnext_vertices = [array.array('I', zeros) for _ in range(len(vertices))]\n</code></pre>\n<p>The rest of the code wouldn't need to change. You still access the data like <code>next_vertices[i][j]</code>.</p>\n<p>This creates a <code>list</code> of <code>array</code> integers, where the array takes a mere 2 bytes per value, instead of 8 bytes per element, plus the storage requirement of each integer (around 28 bytes each).</p>\n<p>You can do something similar for the <code>distance</code> matrix. But now we need to know: are the weights always integer values, or are they floating point? You might want to use the the <code>'d'</code> type code, if weights can be fractional. See the <a href=\"https://docs.python.org/3/library/array.html#module-array\" rel=\"noreferrer\">array</a> for details.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-29T14:18:28.433", "Id": "487034", "Score": "1", "body": "Another point: when constructing the `distance` matrix, you should not use `INF = sys.maxsize`. That was valid in python 2 but not in 3. It is not guaranteed to return the largest int size. Try replacing `INF` with `float('inf')` instead. See https://stackoverflow.com/questions/7604966/maximum-and-minimum-values-for-ints" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-29T15:03:42.243", "Id": "487042", "Score": "1", "body": "@Joe A good point. Good enough that it should be it's own independent answer that you can gain reputation from, instead of a comment where you don't. But `math.inf` is preferable to `float('inf')`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-29T17:01:17.520", "Id": "487054", "Score": "1", "body": "@Joe I went through the link and `sys.maxsize` is valid in python 3, and `sys.maxint` is valid in python 2. Since I'm on python3.x, I used the former. Strongly agree on `math.inf`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-09-05T03:30:18.257", "Id": "487816", "Score": "1", "body": "@Saurabh you're right I was thinking of `sys.maxint`. Still a good practice to use `float('inf')`." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-29T02:58:10.710", "Id": "248594", "ParentId": "248578", "Score": "5" } } ]
{ "AcceptedAnswerId": "248594", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-28T22:24:01.210", "Id": "248578", "Score": "4", "Tags": [ "python", "algorithm", "python-3.x", "graph" ], "Title": "Floyd-Warshall Path Reconstruction" }
248578
<p>In an effort to learn Java's support for concurrency I solved a self-imposed exercise to write a Game of Life simulator in Java, running a separate thread for each cell.</p> <p>Here is my code:</p> <pre class="lang-java prettyprint-override"><code>import java.util.*; import java.lang.*; interface ICell extends Runnable { boolean retrieveGeneration(int generation); void setNeighborGeneration(int x, int y, int gen); } class AlwaysDead implements ICell { private List&lt;List&lt;ICell&gt;&gt; grid; private int xPos, yPos; AlwaysDead(List&lt;List&lt;ICell&gt;&gt; grid, int xPos, int yPos) { this.grid = grid; this.xPos = xPos; this.yPos = yPos; } public boolean retrieveGeneration(int generation) { return false; } public void setNeighborGeneration(int x, int y, int gen) {} public void run() { for(int y = yPos-1; y &lt;= yPos+1; y++) { for(int x = xPos-1; x &lt;= xPos+1; x++) { if(y &lt; grid.size() &amp;&amp; y &gt;= 0) { if(x &lt; grid.get(y).size() &amp;&amp; x &gt;= 0) { if(x != xPos || y != yPos) { ICell c = grid.get(y).get(x); int maxv = Integer.MAX_VALUE; c.setNeighborGeneration(xPos, yPos, maxv); } } } } } } } class Cell implements ICell { private List&lt;Boolean&gt; isPopulated; private int generationOffset; private List&lt;List&lt;ICell&gt;&gt; grid; private int generationNumber; private int xPos, yPos; private List&lt;List&lt;Integer&gt;&gt; neighborGeneration; private int steps; Cell(List&lt;List&lt;ICell&gt;&gt; grid, int xPos, int yPos, boolean val, int steps) { isPopulated = new ArrayList&lt;Boolean&gt;(); isPopulated.add(val); generationOffset = 0; this.grid = grid; generationNumber = 0; this.xPos = xPos; this.yPos = yPos; neighborGeneration = new ArrayList&lt;List&lt;Integer&gt;&gt;(); for(int y = 0; y &lt; 3; y++) { neighborGeneration.add(new ArrayList&lt;Integer&gt;()); for(int x = 0; x &lt; 3; x++) { // This means that neighborGeneration[1][1] points at this cell // and will have a spurious value forever and will be ignored. // No matter - I leave this for the sake of simplicity neighborGeneration.get(y).add(0); } } this.steps = steps; } private synchronized int addGeneration(boolean populated) { isPopulated.add(populated); generationNumber++; return generationNumber; } private synchronized void removeOldGeneration() { isPopulated.remove(0); generationOffset++; } public synchronized boolean retrieveGeneration(int generation) { return isPopulated.get(generation-generationOffset); } private Collection&lt;ICell&gt; neighbors() { Collection&lt;ICell&gt; ret = new ArrayList&lt;ICell&gt;(); for(int x = xPos-1; x &lt;= xPos+1; x++) { for(int y = yPos-1; y &lt;= yPos+1; y++) { if(xPos != x || yPos != y) { ret.add(grid.get(y).get(x)); } } } return ret; } private boolean willBeAlive(boolean isAlive, int neighboringAlive) { if(isAlive &amp;&amp; neighboringAlive &gt;= 2 &amp;&amp; neighboringAlive &lt;= 3) { return true; } else if(!isAlive &amp;&amp; neighboringAlive == 3) { return true; } else { return false; } } private int step() { int neighboringAlive = 0; for(ICell c : neighbors()) { if(c.retrieveGeneration(generationNumber)) { neighboringAlive++; } } boolean isAlive = retrieveGeneration(generationNumber); return addGeneration(willBeAlive(isAlive, neighboringAlive)); } public synchronized void setNeighborGeneration(int x, int y, int gen) { neighborGeneration.get(y-yPos+1).set(x-xPos+1, gen); if(canProgress()) { notify(); } } private synchronized int getMinimalNeighboursGeneration() { int ret = Integer.MAX_VALUE; for(int y = 0; y &lt; 3; y++) { for(int x = 0; x &lt; 3; x++) { if(x != 1 || y != 1) { ret = Math.min(ret, neighborGeneration.get(y).get(x)); } } } return ret; } private synchronized boolean canProgress() { return getMinimalNeighboursGeneration() &gt;= generationNumber; } private synchronized void clearUnneededGenerations() { while(isPopulated.size() &gt; 2) { removeOldGeneration(); } } private void notifyNeighbors(int currentGeneration) { for(ICell c : neighbors()) { c.setNeighborGeneration(xPos, yPos, currentGeneration); } } private synchronized void waitUntilCanProgress() throws InterruptedException { while(!canProgress()) { wait(); } } public void run() { for(int i = 0; i &lt; steps; i++) { int newGeneration = step(); notifyNeighbors(newGeneration); clearUnneededGenerations(); try { waitUntilCanProgress(); } catch(InterruptedException e) { // What am I supposed to do here?? // I can't make run() throw InterruptedException } } } } public class GameOfLife { static int steps = 10000; public static void main(String[] args) throws InterruptedException { List&lt;List&lt;ICell&gt;&gt; grid = inputToGrid(initialData()); List&lt;Thread&gt; threads = new ArrayList&lt;Thread&gt;(); for(int y = 0; y &lt; grid.size(); y++) { for(int x = 0; x &lt; grid.get(y).size(); x++) { Thread cell = new Thread(grid.get(y).get(x)); threads.add(cell); cell.start(); } } for(Thread cell: threads) { cell.join(); } printGrid(grid); return; } public static void printGrid(List&lt;List&lt;ICell&gt;&gt; grid) { for(int y = 1; y &lt; grid.size()-1; y++) { for(int x = 1; x &lt; grid.get(y).size()-1; x++) { if(grid.get(y).get(x).retrieveGeneration(steps)) { System.out.print(&quot;▒&quot;); } else { System.out.print(&quot; &quot;); } } System.out.println(&quot;&quot;); } } public static List&lt;List&lt;ICell&gt;&gt; inputToGrid(int[][] input) { List&lt;List&lt;ICell&gt;&gt; ret = new ArrayList&lt;List&lt;ICell&gt;&gt;(); int ySiz = input.length; int xSiz = input[0].length; ret.add(new ArrayList&lt;ICell&gt;()); for(int x = 0; x &lt; xSiz+2; x++) { ret.get(0).add(new AlwaysDead(ret, x, 0)); } for(int y = 0; y &lt; ySiz; y++) { ret.add(new ArrayList&lt;ICell&gt;()); ret.get(y+1).add(new AlwaysDead(ret, 0, y+1)); for(int x = 0; x &lt; xSiz; x++) { boolean val = input[y][x]==1; ret.get(y+1).add(new Cell(ret, x+1, y+1, val, steps)); } ret.get(y+1).add(new AlwaysDead(ret, xSiz+1, y+1)); } ret.add(new ArrayList&lt;ICell&gt;()); for(int x = 0; x &lt; xSiz+2; x++) { ret.get(ySiz+1).add(new AlwaysDead(ret, x, ySiz+1)); } return ret; } public static int[][] initialData() { int ret[][] = { {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,1,0,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, {1,1,0,0,0,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, {1,1,0,0,0,0,0,0,0,0,1,0,0,0,1,0,1,1,0,0,0,0,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0} }; return ret; } } </code></pre> <p>Since I'm trying to learn concurrency (preparing for an exam...) I would be especially interested to know if there is any obscure interleaving that could lead to a deadlock, or to two concurrent writes and subsequently to data corruption, and the likes. (Of course I tried to design the program to make this not possible) In practice I don't observe such problems, but this doesn't mean there can be none in theory.</p> <p>I understand that in this particular case concurrency doesn't help performance-wise, but still I'm kind of surprised that program is <em>so</em> slow. Running 10k steps of simulation on an 80x23 grid takes <em>minutes</em> on my laptop. (If I ditch concurrency, have only a single thread and run the simulation sequentially, 10k steps on the same board takes only a few seconds).</p> <p>(The sample input is just a <a href="https://en.wikipedia.org/wiki/Gun_(cellular_automaton)" rel="nofollow noreferrer">Gosper gun</a>)</p> <p>Comments?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-29T01:25:26.810", "Id": "486980", "Score": "0", "body": "On my phone (late night), but just want to point out that, as you mentioned, using a single thread for each cell is not viable for even a 4x2 grid (I assume a processor with 8 logical threads) because you encounter a problem with 1. cache locality (how close data is together in memory for cache optimization), and 2. the context switches between threads (these are relatively expensive as you are essentially saving the state of one thread, and reloading another state over and over). I hope you will get a good review on this, seems interesting." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-29T08:50:01.090", "Id": "487009", "Score": "1", "body": "What you're seeing is why multi-threading beyond the (physical) CPU cores is not feasible. Hyperthreading and similar technologies *do* help, but nothing beats physical cores. With that grid you have 1840 threads trying to get one of, in the best case, 8 cores. That means you're looking at 230 threads per core. Swapping threads or processes in the CPU is *expensive*. Not \"expensive\" in the sense of \"you know, my calculator app should receive highest process priority\", but expensive in the sense you're seeing here. You're basically stalling the CPU with all the context swaps it has to perform." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-29T14:55:32.680", "Id": "487039", "Score": "0", "body": "Ironically, you might get better performance on something like a 1995 Java 1.0 Sun JVM with Green Threads. I don't know how context switches are implemented in that JVM, but Green Threads *can* have many orders of magnitude more efficient context switching than native threads. If you try the same exercise with a language with a saner concurrency model, e.g. make each cell a Clojure Agent, you'd probably also see better performance." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-28T22:47:02.150", "Id": "248579", "Score": "4", "Tags": [ "java", "multithreading", "thread-safety", "concurrency", "game-of-life" ], "Title": "Game of Life, thread per cell" }
248579
<p>This is an implementation of a Color class, primarily targetting the web to be used in a Blazor app.</p> <p><strong>Color.cs</strong></p> <pre><code>using System; using System.Globalization; namespace Color { /// &lt;summary&gt; /// Represents a Color with Red, Green, Blue and Alpha channels, packed into an integer. Also contains utilities to convert between color spaces. /// &lt;/summary&gt; /// /// Since the colors are stored in ARGB, if you create a Color from other color spaces you might lose precision. /// This means that converting back and forth between color spaces does not guarantee you getting the original value. /// All percentage values are within [0.0, 1.0] and the smallest possible delta is 1 / 255. So an alpha of 0.001 and 0.002 are the same. /// Static constructors take tuples and constructors take each value separately. /// /// Currently supported color spaces conversion: RGB, HSL, CMYK. public struct Color : IEquatable&lt;Color&gt;, ICloneable { /// &lt;summary&gt; /// Represents ARGB as a densely packed integer. /// &lt;/summary&gt; public uint Value { get; private set; } #region Checks private static bool NotInPctRange(double v) { return v &lt; 0.0 || v &gt; 1.0; } private static bool NotInByteRange(uint v) { return v &gt; 255; } private static bool NotInRgbRange(double r, double g, double b) { return NotInPctRange(r) || NotInPctRange(g) || NotInPctRange(b); } private static bool NotInRgbRange(uint r, uint g, uint b) { return NotInByteRange(r) || NotInByteRange(g) || NotInByteRange(b); } private static bool NotInHslRange(double h, double s, double v) { return h &lt; 0.0 || h &gt; 359.0 || NotInPctRange(s) || NotInPctRange(v); } private static bool NotInCmykRange(double c, double m, double y, double k) { return NotInPctRange(c) || NotInPctRange(m) || NotInPctRange(y) || NotInPctRange(k); } #endregion #region Getters /// &lt;summary&gt; /// The value of Alpha within [0, 255] /// &lt;/summary&gt; public uint A =&gt; Value &gt;&gt; 24; /// &lt;summary&gt; /// The value of Red within [0, 255] /// &lt;/summary&gt; public uint R =&gt; (Value &gt;&gt; 16) &amp; 0xFF; /// &lt;summary&gt; /// The value of Green within [0, 255] /// &lt;/summary&gt; public uint G =&gt; (Value &gt;&gt; 8) &amp; 0xFF; /// &lt;summary&gt; /// The value of Blue within [0, 255] /// &lt;/summary&gt; public uint B =&gt; Value &amp; 0xFF; /// &lt;summary&gt; /// Masks off the Alpha value, returning only RGB /// &lt;/summary&gt; public uint RGB =&gt; Value &amp; 0xFFFFFF; /// &lt;summary&gt; /// Returns value of Alpha within [0.0, 1.0] /// &lt;/summary&gt; public double Alpha =&gt; A / 255.0; /// &lt;summary&gt; /// Returns value of Red within [0.0, 1.0] /// &lt;/summary&gt; public double Red =&gt; R / 255.0; /// &lt;summary&gt; /// Returns value of Green within [0.0, 1.0] /// &lt;/summary&gt; public double Green =&gt; G / 255.0; /// &lt;summary&gt; /// Returns value of Blue within [0.0, 1.0] /// &lt;/summary&gt; public double Blue =&gt; B / 255.0; /// &lt;summary&gt; /// Returns value of Hue within [0.0, 359.0] /// &lt;/summary&gt; public double Hue { get { var r = Red; var g = Green; var b = Blue; var max = Math.Max(Math.Max(r, g), b); var min = Math.Min(Math.Min(r, g), b); var c = max - min; if (c != 0) { if (max == r) { var segment = (g - b) / c; var shift = 0 / 60; if (segment &lt; 0) shift = 360 / 60; return (segment + shift) * 60; } else if (max == g) { var segment = (b - r) / c; var shift = 120 / 60; return (segment + shift) * 60; } else if (max == b) { var segment = (r - g) / c; var shift = 240 / 60; return (segment + shift) * 60; } } return 0; } } /// &lt;summary&gt; /// Returns value of Saturation within [0.0, 1.0] /// &lt;/summary&gt; public double Saturation { get { var r = Red; var g = Green; var b = Blue; var max = Math.Max(Math.Max(r, g), b); var min = Math.Min(Math.Min(r, g), b); var l = (max + min) / 2; // Lightness if (min != max) { if (l &lt; 0.5) return (max - min) / (max + min); return (max - min) / (2 - max - min); } return 0; } } /// &lt;summary&gt; /// Returns value of Lightness within [0.0, 1.0] /// &lt;/summary&gt; public double Lightness { get { var r = Red; var g = Green; var b = Blue; var max = Math.Max(Math.Max(r, g), b); var min = Math.Min(Math.Min(r, g), b); return (max + min) / 2; } } /// &lt;summary&gt; /// Returns value of Cyan within [0.0, 1.0] /// &lt;/summary&gt; public double Cyan { get { var k = Black; return k == 1.0 ? 0.0 : (1.0 - Red - k) / (1.0 - k); } } /// &lt;summary&gt; /// Returns value of Magenta within [0.0, 1.0] /// &lt;/summary&gt; public double Magenta { get { var k = Black; return k == 1.0 ? 0.0 : (1.0 - Green - k) / (1.0 - k); } } /// &lt;summary&gt; /// Returns value of Yellow within [0.0, 1.0] /// &lt;/summary&gt; public double Yellow { get { var k = Black; return k == 1.0 ? 0.0 : (1.0 - Blue - k) / (1.0 - k); } } /// &lt;summary&gt; /// Returns value of Black within [0.0, 1.0] /// &lt;/summary&gt; public double Black =&gt; 1.0 - Math.Max(Math.Max(Red, Green), Blue); /// &lt;summary&gt; /// Returns the relative Luminance (how bright to the human eye the color is) according to ITU BT.601. /// &lt;/summary&gt; public double Luminance =&gt; (0.299 * R + 0.587 * G + 0.114 * B) / 255.0; #endregion #region Value Tuples /// &lt;summary&gt; /// A tuple with RGB values as integers within [0, 255]. /// &lt;/summary&gt; public (uint, uint, uint)RGBValuesInt() { return (R, G, B); } /// &lt;summary&gt; /// A tuple with RGB values within [0.0, 1.0]. /// &lt;/summary&gt; public (double, double, double)RGBValues() { return (Red, Green, Blue); } /// &lt;summary&gt; /// A tuple with HSL values within [0.0, 1.0]. /// &lt;/summary&gt; public (double, double, double)HSLValues() { return RgbToHslInt((R, G, B)); } /// &lt;summary&gt; /// A tuple with CMYK values within [0.0, 1.0]. /// &lt;/summary&gt; public (double, double, double, double)CMYKValues() { return RgbToCmykInt((R, G, B)); } #endregion #region Ctors /// &lt;summary&gt; /// Creates a new Color from an integer value. /// &lt;/summary&gt; public Color(uint value) { Value = value; } /// &lt;summary&gt; /// Creates a Color from a hexadecimal string, converting it to an integer and assigning to Value. /// &lt;/summary&gt; /// &lt;param name=&quot;hexa&quot;&gt;A string as a hexadecimal number&lt;/param&gt; public Color(string hexa) { Value = Convert.ToUInt32(hexa, 16); } /// &lt;summary&gt; /// Creates a Color from Red, Green and Blue channels with 100% Alpha, ranging from [0, 255]. /// &lt;/summary&gt; /// &lt;param name=&quot;r&quot;&gt;Red value&lt;/param&gt; /// &lt;param name=&quot;g&quot;&gt;Green value&lt;/param&gt; /// &lt;param name=&quot;b&quot;&gt;Blue value&lt;/param&gt; public Color(uint r, uint g, uint b) { if (NotInRgbRange(r, g, b)) throw new ArgumentOutOfRangeException(&quot;&quot;, $&quot;R, G, B and A need to be within [0, 255]. Instead got r: {r}, g: {g}, b: {b}&quot;); Value = ((uint)0xFF &lt;&lt; 24) | (r &lt;&lt; 16) | (g &lt;&lt; 8) | b; } /// &lt;summary&gt; /// Creates a Color from Red, Green, Blue and Alpha channels, ranging from [0, 255]. /// &lt;/summary&gt; /// &lt;param name=&quot;r&quot;&gt;Red value&lt;/param&gt; /// &lt;param name=&quot;g&quot;&gt;Green value&lt;/param&gt; /// &lt;param name=&quot;b&quot;&gt;Blue value&lt;/param&gt; /// &lt;param name=&quot;a&quot;&gt;Alpha value&lt;/param&gt; public Color(uint r, uint g, uint b, uint a) { if (NotInRgbRange(r, g, b) || a &gt; 255) throw new ArgumentOutOfRangeException(&quot;&quot;, $&quot;R, G, B and A need to be within [0, 255]. Instead got r: {r}, g: {g}, b: {b}, a: {a}&quot;); Value = (a &lt;&lt; 24) | (r &lt;&lt; 16) | (g &lt;&lt; 8) | b; } /// &lt;summary&gt; /// Creates a Color from Red, Green, Blue and Alpha channels, with RGB ranging from [0, 255], and Alpha, from [0.0, 1.0]. /// &lt;/summary&gt; /// &lt;param name=&quot;r&quot;&gt;Red value&lt;/param&gt; /// &lt;param name=&quot;g&quot;&gt;Green value&lt;/param&gt; /// &lt;param name=&quot;b&quot;&gt;Blue value&lt;/param&gt; /// &lt;param name=&quot;a&quot;&gt;Alpha value&lt;/param&gt; public Color(uint r, uint g, uint b, double a) { if (NotInRgbRange(r, g, b) || a &gt; 1.0 || a &lt; 0.0) throw new ArgumentOutOfRangeException(&quot;&quot;, $&quot;R, G, B need to be within [0, 255] and A within [0.0, 1.0]. Instead got r: {r}, g: {g}, b: {b}, a: {a}&quot;); var a_ = (uint)Math.Round(a * 255.0, 0); Value = (a_ &lt;&lt; 24) | (r &lt;&lt; 16) | (g &lt;&lt; 8) | b; } /// &lt;summary&gt; /// Creates a Color from Red, Green and Blue channels with 100% Alpha, ranging from [0.0, 1.0]. /// &lt;/summary&gt; /// &lt;param name=&quot;r&quot;&gt;Red value&lt;/param&gt; /// &lt;param name=&quot;g&quot;&gt;Green value&lt;/param&gt; /// &lt;param name=&quot;b&quot;&gt;Blue value&lt;/param&gt; public Color(double r, double g, double b) { if (NotInRgbRange(r, g, b)) throw new ArgumentOutOfRangeException(&quot;&quot;, $&quot;R, G and B need to be within [0.0, 1.0]. Instead got r: {r}, g: {g}, b: {b}&quot;); var (r_, g_, b_) = PctToRgb(r, g, b); Value = ((uint)0xFF &lt;&lt; 24) | (r_ &lt;&lt; 16) | (g_ &lt;&lt; 8) | b_; } /// &lt;summary&gt; /// Creates a Color from Red, Green, Blue and Alpha channels, ranging from [0.0, 1.0]. /// &lt;/summary&gt; /// &lt;param name=&quot;r&quot;&gt;Red value&lt;/param&gt; /// &lt;param name=&quot;g&quot;&gt;Green value&lt;/param&gt; /// &lt;param name=&quot;a&quot;&gt;Alpha value&lt;/param&gt; public Color(double r, double g, double b, double a) { if (NotInRgbRange(r, g, b) || a &gt; 1.0 || a &lt; 0.0) throw new ArgumentOutOfRangeException(&quot;&quot;, $&quot;R, G, B and A need to be within [0.0, 1.0]. Instead got r: {r}, g: {g}, b: {b}, a: {a}&quot;); var (r_, g_, b_) = PctToRgb(r, g, b); var a_ = (uint)Math.Round(a * 255.0, 0); Value = (a_ &lt;&lt; 24) | (r_ &lt;&lt; 16) | (g_ &lt;&lt; 8) | b_; } #endregion #region Static Ctors /// &lt;summary&gt; /// Creates a Color from a string, converting it to an integer and assigning to Value. /// &lt;/summary&gt; /// &lt;param name=&quot;hexa&quot;&gt;A string as a hexadecimal number&lt;/param&gt; public static Color FromHexa(string hexa) { return new Color(hexa); } /// &lt;summary&gt; /// Creates a Color from Red, Green, Blue and Alpha channels. All numbers ranging from 0 to 255. /// &lt;/summary&gt; /// &lt;param name=&quot;rgb&quot;&gt;A tuple of form (R, G, B)&lt;/param&gt; /// &lt;param name=&quot;a&quot;&gt;Alpha value&lt;/param&gt; public static Color FromRGBA((uint, uint, uint) rgb, uint a) { var (r, g, b) = rgb; return new Color(r, g, b, a); } /// &lt;summary&gt; /// Creates a Color from Red, Green, Blue and Alpha channels. RGB ranging from 0 to 255, and Alpha, from 0.0 to 1.0. /// &lt;/summary&gt; /// &lt;param name=&quot;rgb&quot;&gt;A tuple of form (R, G, B)&lt;/param&gt; /// &lt;param name=&quot;a&quot;&gt;Alpha value&lt;/param&gt; public static Color FromRGBA((uint, uint, uint) rgb, double a) { var (r, g, b) = rgb; return new Color(r, g, b, a); } /// &lt;summary&gt; /// Creates a Color from Red, Green, Blue and Alpha components. All numbers ranging from 0.0 to 1.0. /// &lt;/summary&gt; /// &lt;param name=&quot;rgb&quot;&gt;A tuple of form (R, G, B)&lt;/param&gt; /// &lt;param name=&quot;a&quot;&gt;Alpha value&lt;/param&gt; public static Color FromRGBA((double, double, double) rgb, double a) { var (r, g, b) = rgb; return new Color(r, g, b, a); } /// &lt;summary&gt; /// Creates a Color from Red, Green and Blue channels with 100% Alpha and values within [0, 255]. /// &lt;/summary&gt; /// &lt;param name=&quot;rgb&quot;&gt;A tuple of form (R, G, B)&lt;/param&gt; public static Color FromRGB((uint, uint, uint) rgb) { return FromRGBA(rgb, 255); } /// &lt;summary&gt; /// Creates a Color from Red, Green and Blue channels with 100% Alpha and values within [0.0, 1.0]. /// &lt;/summary&gt; /// &lt;param name=&quot;rgb&quot;&gt;A tuple of form (R, G, B)&lt;/param&gt; public static Color FromRGB((double, double, double) rgb) { return FromRGBA(rgb, 1.0); } /// &lt;summary&gt; /// Creates a Color from Hue, Saturation and Value, with Hue within [0.0, 359.0], and the others, within [0.0, 1.0]. Alpha is at 100%. /// &lt;/summary&gt; /// &lt;param name=&quot;hsl&quot;&gt;A tuple of form (H, S, L)&lt;/param&gt; public static Color FromHSL((double, double, double) hsl) { return FromRGBA(HslToRgb(hsl), 1.0); } /// &lt;summary&gt; /// Creates a Color from Hue, Saturation, Value, and Alpha, with Hue within [0.0, 359.0], and the others, within [0.0, 1.0]. /// &lt;/summary&gt; /// &lt;param name=&quot;hsl&quot;&gt;A tuple of form (H, S, L)&lt;/param&gt; /// &lt;param name=&quot;a&quot;&gt;Alpha value&lt;/param&gt; public static Color FromHSLA((double, double, double) hsl, double a) { return FromRGBA(HslToRgb(hsl), a); } /// &lt;summary&gt; /// Creates a Color from Cyan, Magenta, Yellow and Black, with values within [0.0, 1.0]. /// &lt;/summary&gt; /// &lt;param name=&quot;hsl&quot;&gt;A tuple of form (C, M, Y, K)&lt;/param&gt; public static Color FromCMYK((double, double, double, double) cmyk) { return FromRGBA(CmykToRgb(cmyk), 1.0); } /// &lt;summary&gt; /// Creates a Color from Cyan, Magenta, Yellow, Black and Alpha, with values within [0.0, 1.0]. /// &lt;/summary&gt; /// &lt;param name=&quot;hsl&quot;&gt;A tuple of form (C, M, Y, K)&lt;/param&gt; /// &lt;param name=&quot;a&quot;&gt;Alpha value&lt;/param&gt; /// &lt;returns&gt;&lt;/returns&gt; public static Color FromCMYKA((double, double, double, double) cmyk, double a) { return FromRGBA(CmykToRgb(cmyk), a); } #endregion #region Conversions /// &lt;summary&gt; /// Transforms RGB color space to HSL. /// &lt;/summary&gt; /// /// RGB values must be in range [0.0, 1.0]. /// /// &lt;param name=&quot;rgb&quot;&gt;A tuple of form (Red, Green, Blue)&lt;/param&gt; /// &lt;returns&gt;A tuple of form Tuple of form (Hue, Saturation, Lightness)&lt;/returns&gt; public static (double, double, double) RgbToHsl((double, double, double) rgb) { double hue = 0.0, sat = 0.0, light; (double r, double g, double b) = rgb; if (NotInRgbRange(r, g, b)) throw new ArgumentOutOfRangeException(&quot;rbg&quot;, $&quot;R, G and B must be in range [0.0, 1.0]. Instead got r: {r}, g: {g}, b: {b}&quot;); var max = Math.Max(Math.Max(r, g), b); var min = Math.Min(Math.Min(r, g), b); var c = max - min; if (c != 0) { if (max == r) { var segment = (g - b) / c; var shift = 0 / 60; if (segment &lt; 0) shift = 360 / 60; hue = (segment + shift) * 60; } else if (max == g) { var segment = (b - r) / c; var shift = 120 / 60; hue = (segment + shift) * 60; } else if (max == b) { var segment = (r - g) / c; var shift = 240 / 60; hue = (segment + shift) * 60; } } light = (max + min) / 2; if (min != max) { if (light &lt; 0.5) sat = (max - min) / (max + min); else sat = (max - min) / (2 - max - min); } return (hue, sat, light); } /// &lt;summary&gt; /// Transforms RGB color space to HSL. /// &lt;/summary&gt; /// /// RGB values must be in range [0, 255]. /// /// &lt;param name=&quot;rgb&quot;&gt;A tuple of form (Red, Green, Blue)&lt;/param&gt; /// &lt;returns&gt;A tuple of form (Hue, Saturation, Lightness) within [0.0, 1.0]&lt;/returns&gt; public static (double, double, double) RgbToHslInt((uint, uint, uint) rgb) { (uint r_, uint g_, uint b_) = rgb; if (NotInRgbRange(r_, g_, b_)) throw new ArgumentOutOfRangeException(&quot;rbg&quot;, $&quot;R, G and B must be in range [0, 255]. Instead got r: {r_}, g: {g_}, b: {b_}&quot;); (double r, double g, double b) = RgbToPct(r_, g_, b_); return RgbToHsl((r, g, b)); } /// &lt;summary&gt; /// Transforms RGB color space to CMYK. /// &lt;/summary&gt; /// /// RGB values must be in range [0.0, 1.0]. /// /// &lt;param name=&quot;rgb&quot;&gt;A tuple of form (Red, Green, Blue)&lt;/param&gt; /// &lt;returns&gt;A tuple of form (Cyan, Magenta, Yellow, Black) within [0.0, 1.0]&lt;/returns&gt; public static (double, double, double, double) RgbToCmyk((double, double, double) rgb) { double c, m, y, k; (double r, double g, double b) = rgb; if (NotInRgbRange(r, g, b)) throw new ArgumentOutOfRangeException(&quot;rbg&quot;, $&quot;R, G and B must be in range [0.0, 1.0]. Instead got r: {r}, g: {g}, b: {b}&quot;); var max = Math.Max(Math.Max(r, g), b); k = 1 - max; if (k == 1) { c = m = y = 0; } else { c = (1 - r - k) / (1 - k); m = (1 - g - k) / (1 - k); y = (1 - b - k) / (1 - k); } return (c, m, y, k); } /// &lt;summary&gt; /// Transforms RGB color space to CMYK. /// &lt;/summary&gt; /// /// RGB values must be in range [0, 255]. /// /// &lt;param name=&quot;rgb&quot;&gt;A tuple of form (Red, Green, Blue)&lt;/param&gt; /// &lt;returns&gt;A tuple of form (Cyan, Magenta, Yellow, Black) within [0.0, 1.0]&lt;/returns&gt; public static (double, double, double, double) RgbToCmykInt((uint, uint, uint) rgb) { (uint r_, uint g_, uint b_) = rgb; if (NotInRgbRange(r_, g_, b_)) throw new ArgumentOutOfRangeException(&quot;rbg&quot;, $&quot;R, G and B must be in range [0, 255]. Instead got r: {r_}, g: {g_}, b: {b_}&quot;); (double r, double g, double b) = RgbToPct(r_, g_, b_); return RgbToCmyk((r, g, b)); } /// &lt;summary&gt; /// Transforms HSL color space to RGB. /// &lt;/summary&gt; /// /// H value must be in range [0.0, 359.0] and SL values must be in range [0.0, 1.0]. /// /// &lt;param name=&quot;hsl&quot;&gt;A tuple of form (Hue, Saturation, Lightness)&lt;/param&gt; /// &lt;returns&gt;A tuple of form (Red, Green, Blue) within [0.0, 1.0]&lt;/returns&gt; public static (double, double, double) HslToRgb((double, double, double) hsl) { (double hue, double sat, double light) = hsl; if (NotInHslRange(hue, sat, light)) throw new ArgumentOutOfRangeException(&quot;hsl&quot;, $&quot;H must be in range [0.0, 359.0], and S and L must be in range [0.0, 1.0]. Instead got h: {hue}, s: {sat}, l: {light}&quot;); hue /= 60; double t2; if (light &lt;= 0.5) { t2 = light * (sat + 1); } else { t2 = light + sat - (light * sat); } double t1 = light * 2 - t2; return (HueToRgb(t1, t2, hue + 2.0), HueToRgb(t1, t2, hue), HueToRgb(t1, t2, hue - 2)); } /// &lt;summary&gt; /// Transforms HSL color space to RGB. /// &lt;/summary&gt; /// /// H value must be in range [0.0, 359.0] and SL values must be in range [0.0, 1.0]. /// /// &lt;param name=&quot;hsl&quot;&gt;A tuple of form (Hue, Saturation, Lightness)&lt;/param&gt; /// &lt;returns&gt;A tuple of form (Red, Green, Blue)&lt;/returns&gt; public static (uint, uint, uint) HslToRgbInt((double, double, double) hsl) { var (r, g, b) = HslToRgb(hsl); return PctToRgb(r, g, b); } public static double HueToRgb(double t1, double t2, double hue) { if (hue &lt; 0.0) hue += 6.0; if (hue &gt;= 6.0) hue -= 6.0; if (hue &lt; 1.0) return (t2 - t1) * hue + t1; else if (hue &lt; 3.0) return t2; else if (hue &lt; 4.0) return (t2 - t1) * (4.0 - hue) + t1; return t1; } /// &lt;summary&gt; /// Transforms CMYK color space to RGB. /// &lt;/summary&gt; /// /// CMYK values must be in range [0.0, 1.0]. /// /// &lt;param name=&quot;cmyk&quot;&gt;A tuple of form (Cyan, Magenta, Yellow, Black)&lt;/param&gt; /// &lt;returns&gt;A tuple of form (Red, Green, Blue) within [0.0, 1.0]&lt;/returns&gt; public static (double, double, double) CmykToRgb((double c, double m, double y, double k) cmyk) { var (c, m, y, k) = cmyk; if (NotInCmykRange(c, m, y, k)) throw new ArgumentOutOfRangeException(&quot;cmyk&quot;, $&quot;CMYK must be in range [0.0, 1.0]. Instead got c: {c}, m: {m}, y: {y}, k: {k}&quot;); var r = 1 - (Math.Min(1, c * (1 - k) + k)); var g = 1 - (Math.Min(1, m * (1 - k) + k)); var b = 1 - (Math.Min(1, y * (1 - k) + k)); return (r, g, b); } /// &lt;summary&gt; /// Transforms CMYK color space to RGB. /// &lt;/summary&gt; /// /// CMYK values must be in range [0.0, 1.0]. /// /// &lt;param name=&quot;cmyk&quot;&gt;A tuple of form (Cyan, Magenta, Yellow, Black)&lt;/param&gt; /// &lt;returns&gt;A tuple of form (Red, Green, Blue)&lt;/returns&gt; public static (uint, uint, uint) CmykToRgbInt((double c, double m, double y, double k) cmyk) { var (r, g, b) = CmykToRgb(cmyk); return PctToRgb(r, g, b); } #endregion #region ToCSS /// &lt;summary&gt; /// Returns the Color to fit into an rgba CSS function, with form rbga(R, G, B, A). /// &lt;/summary&gt; public string ToCssRgba() { return $&quot;rgba({R}, {G}, {B}, {DefaultFormat(A / 255.0)})&quot;; } /// &lt;summary&gt; /// Returns the Color to fit into an hsla CSS function, with form hsl(H, S%, L%, A) /// &lt;/summary&gt; public string ToCssHsla() { var (h, s, l) = RgbToHsl((Red, Green, Blue)); return $&quot;hsla({DefaultFormat(h)}, {DefaultFormat(s * 100)}%, {DefaultFormat(l * 100)}%, {DefaultFormat(A / 255.0)})&quot;; } /// &lt;summary&gt; /// Returns the Color with a format of #RRGGBB. /// &lt;/summary&gt; public string ToCssColor() { return $&quot;#{Convert.ToString(RGB, 16).PadLeft(6, '0')}&quot;; } #endregion #region Misc /// &lt;summary&gt; /// [0, 255] -&gt; [0.0, 1.0] /// &lt;/summary&gt; private static (double, double, double) RgbToPct(uint r, uint g, uint b) { return (r / 255.0, g / 255.0, b / 255.0); } /// &lt;summary&gt; /// [0.0, 1.0] -&gt; [0, 255] /// &lt;/summary&gt; private static (uint, uint, uint) PctToRgb(double r, double g, double b) { return ((uint)Math.Round(r * 255.0, 0), (uint)Math.Round(g * 255.0, 0), (uint)Math.Round(b * 255.0, 0)); } private static string DefaultFormat(double value) { return value.ToString(&quot;0.##&quot;, CultureInfo.InvariantCulture); } #endregion #region Overrides + Impls public static bool operator ==(Color lhs, Color rhs) { return lhs.Value == rhs.Value; } public static bool operator !=(Color lhs, Color rhs) { return lhs.Value != rhs.Value; } public override bool Equals(object obj) { if (obj is Color c) return Value == c.Value; return false; } public override int GetHashCode() =&gt; Value.GetHashCode(); public override string ToString() { return Value.ToString(&quot;X&quot;); } public bool Equals(Color other) { return Value == other.Value; } public object Clone() { return new Color(Value); } #endregion } } </code></pre> <p>Here is an example of using it on a console application:</p> <p><strong>Program.cs</strong></p> <pre><code>using System; public class Program { public static void Main() { var color1 = new Color(49, 100, 200); var color2 = Color.FromHSL(color1.HSLValues()); if (color1 == color2) Console.WriteLine(&quot;yay!&quot;); var color3 = new Color(color2.ToString()); if (color1 == color3 &amp;&amp; color2 == color3 &amp;&amp; color3 == color3) Console.WriteLine(&quot;yay!&quot;); Console.WriteLine(color1); Console.WriteLine(color2); Console.WriteLine(color3); } } </code></pre> <p>I've taken all the named colors from <a href="https://www.w3schools.com/colors/colors_names.asp" rel="nofollow noreferrer">here</a> and added to a separate static class that can be very usefull:</p> <p><strong>Colors.cs</strong></p> <pre><code>using System.Collections.Generic; namespace Color { /// &lt;summary&gt; /// https://www.w3schools.com/colors/colors_names.asp /// &lt;/summary&gt; public static class Colors { public static Color AliceBlue =&gt; new Color(0xFFF0F8FF); public static Color AntiqueWhite =&gt; new Color(0xFFFAEBD7); public static Color Aqua =&gt; new Color(0xFF00FFFF); public static Color Aquamarine =&gt; new Color(0xFF7FFFD4); public static Color Azure =&gt; new Color(0xFFF0FFFF); public static Color Beige =&gt; new Color(0xFFF5F5DC); public static Color Bisque =&gt; new Color(0xFFFFE4C4); public static Color Black =&gt; new Color(0xFF000000); public static Color BlanchedAlmond =&gt; new Color(0xFFFFEBCD); public static Color Blue =&gt; new Color(0xFF0000FF); public static Color BlueViolet =&gt; new Color(0xFF8A2BE2); public static Color Brown =&gt; new Color(0xFFA52A2A); public static Color BurlyWood =&gt; new Color(0xFFDEB887); public static Color CadetBlue =&gt; new Color(0xFF5F9EA0); public static Color Chartreuse =&gt; new Color(0xFF7FFF00); public static Color Chocolate =&gt; new Color(0xFFD2691E); public static Color Coral =&gt; new Color(0xFFFF7F50); public static Color CornflowerBlue =&gt; new Color(0xFF6495ED); public static Color Cornsilk =&gt; new Color(0xFFFFF8DC); public static Color Crimson =&gt; new Color(0xFFDC143C); public static Color Cyan =&gt; new Color(0xFF00FFFF); public static Color DarkBlue =&gt; new Color(0xFF00008B); public static Color DarkCyan =&gt; new Color(0xFF008B8B); public static Color DarkGoldenRod =&gt; new Color(0xFFB8860B); public static Color DarkGray =&gt; new Color(0xFFA9A9A9); public static Color DarkGrey =&gt; new Color(0xFFA9A9A9); public static Color DarkGreen =&gt; new Color(0xFF006400); public static Color DarkKhaki =&gt; new Color(0xFFBDB76B); public static Color DarkMagenta =&gt; new Color(0xFF8B008B); public static Color DarkOliveGreen =&gt; new Color(0xFF556B2F); public static Color DarkOrange =&gt; new Color(0xFFFF8C00); public static Color DarkOrchid =&gt; new Color(0xFF9932CC); public static Color DarkRed =&gt; new Color(0xFF8B0000); public static Color DarkSalmon =&gt; new Color(0xFFE9967A); public static Color DarkSeaGreen =&gt; new Color(0xFF8FBC8F); public static Color DarkSlateBlue =&gt; new Color(0xFF483D8B); public static Color DarkSlateGray =&gt; new Color(0xFF2F4F4F); public static Color DarkSlateGrey =&gt; new Color(0xFF2F4F4F); public static Color DarkTurquoise =&gt; new Color(0xFF00CED1); public static Color DarkViolet =&gt; new Color(0xFF9400D3); public static Color DeepPink =&gt; new Color(0xFFFF1493); public static Color DeepSkyBlue =&gt; new Color(0xFF00BFFF); public static Color DimGray =&gt; new Color(0xFF696969); public static Color DimGrey =&gt; new Color(0xFF696969); public static Color DodgerBlue =&gt; new Color(0xFF1E90FF); public static Color FireBrick =&gt; new Color(0xFFB22222); public static Color FloralWhite =&gt; new Color(0xFFFFFAF0); public static Color ForestGreen =&gt; new Color(0xFF228B22); public static Color Fuchsia =&gt; new Color(0xFFFF00FF); public static Color Gainsboro =&gt; new Color(0xFFDCDCDC); public static Color GhostWhite =&gt; new Color(0xFFF8F8FF); public static Color Gold =&gt; new Color(0xFFFFD700); public static Color GoldenRod =&gt; new Color(0xFFDAA520); public static Color Gray =&gt; new Color(0xFF808080); public static Color Grey =&gt; new Color(0xFF808080); public static Color Green =&gt; new Color(0xFF008000); public static Color GreenYellow =&gt; new Color(0xFFADFF2F); public static Color HoneyDew =&gt; new Color(0xFFF0FFF0); public static Color HotPink =&gt; new Color(0xFFFF69B4); public static Color IndianRed =&gt; new Color(0xFFCD5C5C); public static Color Indigo =&gt; new Color(0xFF4B0082); public static Color Ivory =&gt; new Color(0xFFFFFFF0); public static Color Khaki =&gt; new Color(0xFFF0E68C); public static Color Lavender =&gt; new Color(0xFFE6E6FA); public static Color LavenderBlush =&gt; new Color(0xFFFFF0F5); public static Color LawnGreen =&gt; new Color(0xFF7CFC00); public static Color LemonChiffon =&gt; new Color(0xFFFFFACD); public static Color LightBlue =&gt; new Color(0xFFADD8E6); public static Color LightCoral =&gt; new Color(0xFFF08080); public static Color LightCyan =&gt; new Color(0xFFE0FFFF); public static Color LightGoldenRodYellow =&gt; new Color(0xFFFAFAD2); public static Color LightGray =&gt; new Color(0xFFD3D3D3); public static Color LightGrey =&gt; new Color(0xFFD3D3D3); public static Color LightGreen =&gt; new Color(0xFF90EE90); public static Color LightPink =&gt; new Color(0xFFFFB6C1); public static Color LightSalmon =&gt; new Color(0xFFFFA07A); public static Color LightSeaGreen =&gt; new Color(0xFF20B2AA); public static Color LightSkyBlue =&gt; new Color(0xFF87CEFA); public static Color LightSlateGray =&gt; new Color(0xFF778899); public static Color LightSlateGrey =&gt; new Color(0xFF778899); public static Color LightSteelBlue =&gt; new Color(0xFFB0C4DE); public static Color LightYellow =&gt; new Color(0xFFFFFFE0); public static Color Lime =&gt; new Color(0xFF00FF00); public static Color LimeGreen =&gt; new Color(0xFF32CD32); public static Color Linen =&gt; new Color(0xFFFAF0E6); public static Color Magenta =&gt; new Color(0xFFFF00FF); public static Color Maroon =&gt; new Color(0xFF800000); public static Color MediumAquaMarine =&gt; new Color(0xFF66CDAA); public static Color MediumBlue =&gt; new Color(0xFF0000CD); public static Color MediumOrchid =&gt; new Color(0xFFBA55D3); public static Color MediumPurple =&gt; new Color(0xFF9370DB); public static Color MediumSeaGreen =&gt; new Color(0xFF3CB371); public static Color MediumSlateBlue =&gt; new Color(0xFF7B68EE); public static Color MediumSpringGreen =&gt; new Color(0xFF00FA9A); public static Color MediumTurquoise =&gt; new Color(0xFF48D1CC); public static Color MediumVioletRed =&gt; new Color(0xFFC71585); public static Color MidnightBlue =&gt; new Color(0xFF191970); public static Color MintCream =&gt; new Color(0xFFF5FFFA); public static Color MistyRose =&gt; new Color(0xFFFFE4E1); public static Color Moccasin =&gt; new Color(0xFFFFE4B5); public static Color NavajoWhite =&gt; new Color(0xFFFFDEAD); public static Color Navy =&gt; new Color(0xFF000080); public static Color OldLace =&gt; new Color(0xFFFDF5E6); public static Color Olive =&gt; new Color(0xFF808000); public static Color OliveDrab =&gt; new Color(0xFF6B8E23); public static Color Orange =&gt; new Color(0xFFFFA500); public static Color OrangeRed =&gt; new Color(0xFFFF4500); public static Color Orchid =&gt; new Color(0xFFDA70D6); public static Color PaleGoldenRod =&gt; new Color(0xFFEEE8AA); public static Color PaleGreen =&gt; new Color(0xFF98FB98); public static Color PaleTurquoise =&gt; new Color(0xFFAFEEEE); public static Color PaleVioletRed =&gt; new Color(0xFFDB7093); public static Color PapayaWhip =&gt; new Color(0xFFFFEFD5); public static Color PeachPuff =&gt; new Color(0xFFFFDAB9); public static Color Peru =&gt; new Color(0xFFCD853F); public static Color Pink =&gt; new Color(0xFFFFC0CB); public static Color Plum =&gt; new Color(0xFFDDA0DD); public static Color PowderBlue =&gt; new Color(0xFFB0E0E6); public static Color Purple =&gt; new Color(0xFF800080); public static Color RebeccaPurple =&gt; new Color(0xFF663399); public static Color Red =&gt; new Color(0xFFFF0000); public static Color RosyBrown =&gt; new Color(0xFFBC8F8F); public static Color RoyalBlue =&gt; new Color(0xFF4169E1); public static Color SaddleBrown =&gt; new Color(0xFF8B4513); public static Color Salmon =&gt; new Color(0xFFFA8072); public static Color SandyBrown =&gt; new Color(0xFFF4A460); public static Color SeaGreen =&gt; new Color(0xFF2E8B57); public static Color SeaShell =&gt; new Color(0xFFFFF5EE); public static Color Sienna =&gt; new Color(0xFFA0522D); public static Color Silver =&gt; new Color(0xFFC0C0C0); public static Color SkyBlue =&gt; new Color(0xFF87CEEB); public static Color SlateBlue =&gt; new Color(0xFF6A5ACD); public static Color SlateGray =&gt; new Color(0xFF708090); public static Color SlateGrey =&gt; new Color(0xFF708090); public static Color Snow =&gt; new Color(0xFFFFFAFA); public static Color SpringGreen =&gt; new Color(0xFF00FF7F); public static Color SteelBlue =&gt; new Color(0xFF4682B4); public static Color Tan =&gt; new Color(0xFFD2B48C); public static Color Teal =&gt; new Color(0xFF008080); public static Color Thistle =&gt; new Color(0xFFD8BFD8); public static Color Tomato =&gt; new Color(0xFFFF6347); public static Color Turquoise =&gt; new Color(0xFF40E0D0); public static Color Violet =&gt; new Color(0xFFEE82EE); public static Color Wheat =&gt; new Color(0xFFF5DEB3); public static Color White =&gt; new Color(0xFFFFFFFF); public static Color WhiteSmoke =&gt; new Color(0xFFF5F5F5); public static Color Yellow =&gt; new Color(0xFFFFFF00); public static Color YellowGreen =&gt; new Color(0xFF9ACD32); public static readonly Dictionary&lt;string, Color&gt; ByName = new Dictionary&lt;string, Color&gt; { { &quot;AliceBlue&quot;, AliceBlue }, { &quot;AntiqueWhite&quot;, AntiqueWhite }, { &quot;Aqua&quot;, Aqua }, { &quot;Aquamarine&quot;, Aquamarine }, { &quot;Azure&quot;, Azure }, { &quot;Beige&quot;, Beige }, { &quot;Bisque&quot;, Bisque }, { &quot;Black&quot;, Black }, { &quot;BlanchedAlmond&quot;, BlanchedAlmond }, { &quot;Blue&quot;, Blue }, { &quot;BlueViolet&quot;, BlueViolet }, { &quot;Brown&quot;, Brown }, { &quot;BurlyWood&quot;, BurlyWood }, { &quot;CadetBlue&quot;, CadetBlue }, { &quot;Chartreuse&quot;, Chartreuse }, { &quot;Chocolate&quot;, Chocolate }, { &quot;Coral&quot;, Coral }, { &quot;CornflowerBlue&quot;, CornflowerBlue }, { &quot;Cornsilk&quot;, Cornsilk }, { &quot;Crimson&quot;, Crimson }, { &quot;Cyan&quot;, Cyan }, { &quot;DarkBlue&quot;, DarkBlue }, { &quot;DarkCyan&quot;, DarkCyan }, { &quot;DarkGoldenRod&quot;, DarkGoldenRod }, { &quot;DarkGray&quot;, DarkGray }, { &quot;DarkGrey&quot;, DarkGrey }, { &quot;DarkGreen&quot;, DarkGreen }, { &quot;DarkKhaki&quot;, DarkKhaki }, { &quot;DarkMagenta&quot;, DarkMagenta }, { &quot;DarkOliveGreen&quot;, DarkOliveGreen }, { &quot;DarkOrange&quot;, DarkOrange }, { &quot;DarkOrchid&quot;, DarkOrchid }, { &quot;DarkRed&quot;, DarkRed }, { &quot;DarkSalmon&quot;, DarkSalmon }, { &quot;DarkSeaGreen&quot;, DarkSeaGreen }, { &quot;DarkSlateBlue&quot;, DarkSlateBlue }, { &quot;DarkSlateGray&quot;, DarkSlateGray }, { &quot;DarkSlateGrey&quot;, DarkSlateGrey }, { &quot;DarkTurquoise&quot;, DarkTurquoise }, { &quot;DarkViolet&quot;, DarkViolet }, { &quot;DeepPink&quot;, DeepPink }, { &quot;DeepSkyBlue&quot;, DeepSkyBlue }, { &quot;DimGray&quot;, DimGray }, { &quot;DimGrey&quot;, DimGrey }, { &quot;DodgerBlue&quot;, DodgerBlue }, { &quot;FireBrick&quot;, FireBrick }, { &quot;FloralWhite&quot;, FloralWhite }, { &quot;ForestGreen&quot;, ForestGreen }, { &quot;Fuchsia&quot;, Fuchsia }, { &quot;Gainsboro&quot;, Gainsboro }, { &quot;GhostWhite&quot;, GhostWhite }, { &quot;Gold&quot;, Gold }, { &quot;GoldenRod&quot;, GoldenRod }, { &quot;Gray&quot;, Gray }, { &quot;Grey&quot;, Grey }, { &quot;Green&quot;, Green }, { &quot;GreenYellow&quot;, GreenYellow }, { &quot;HoneyDew&quot;, HoneyDew }, { &quot;HotPink&quot;, HotPink }, { &quot;IndianRed&quot;, IndianRed }, { &quot;Indigo&quot;, Indigo }, { &quot;Ivory&quot;, Ivory }, { &quot;Khaki&quot;, Khaki }, { &quot;Lavender&quot;, Lavender }, { &quot;LavenderBlush&quot;, LavenderBlush }, { &quot;LawnGreen&quot;, LawnGreen }, { &quot;LemonChiffon&quot;, LemonChiffon }, { &quot;LightBlue&quot;, LightBlue }, { &quot;LightCoral&quot;, LightCoral }, { &quot;LightCyan&quot;, LightCyan }, { &quot;LightGoldenRodYellow&quot;, LightGoldenRodYellow }, { &quot;LightGray&quot;, LightGray }, { &quot;LightGrey&quot;, LightGrey }, { &quot;LightGreen&quot;, LightGreen }, { &quot;LightPink&quot;, LightPink }, { &quot;LightSalmon&quot;, LightSalmon }, { &quot;LightSeaGreen&quot;, LightSeaGreen }, { &quot;LightSkyBlue&quot;, LightSkyBlue }, { &quot;LightSlateGray&quot;, LightSlateGray }, { &quot;LightSlateGrey&quot;, LightSlateGrey }, { &quot;LightSteelBlue&quot;, LightSteelBlue }, { &quot;LightYellow&quot;, LightYellow }, { &quot;Lime&quot;, Lime }, { &quot;LimeGreen&quot;, LimeGreen }, { &quot;Linen&quot;, Linen }, { &quot;Magenta&quot;, Magenta }, { &quot;Maroon&quot;, Maroon }, { &quot;MediumAquaMarine&quot;, MediumAquaMarine }, { &quot;MediumBlue&quot;, MediumBlue }, { &quot;MediumOrchid&quot;, MediumOrchid }, { &quot;MediumPurple&quot;, MediumPurple }, { &quot;MediumSeaGreen&quot;, MediumSeaGreen }, { &quot;MediumSlateBlue&quot;, MediumSlateBlue }, { &quot;MediumSpringGreen&quot;, MediumSpringGreen }, { &quot;MediumTurquoise&quot;, MediumTurquoise }, { &quot;MediumVioletRed&quot;, MediumVioletRed }, { &quot;MidnightBlue&quot;, MidnightBlue }, { &quot;MintCream&quot;, MintCream }, { &quot;MistyRose&quot;, MistyRose }, { &quot;Moccasin&quot;, Moccasin }, { &quot;NavajoWhite&quot;, NavajoWhite }, { &quot;Navy&quot;, Navy }, { &quot;OldLace&quot;, OldLace }, { &quot;Olive&quot;, Olive }, { &quot;OliveDrab&quot;, OliveDrab }, { &quot;Orange&quot;, Orange }, { &quot;OrangeRed&quot;, OrangeRed }, { &quot;Orchid&quot;, Orchid }, { &quot;PaleGoldenRod&quot;, PaleGoldenRod }, { &quot;PaleGreen&quot;, PaleGreen }, { &quot;PaleTurquoise&quot;, PaleTurquoise }, { &quot;PaleVioletRed&quot;, PaleVioletRed }, { &quot;PapayaWhip&quot;, PapayaWhip }, { &quot;PeachPuff&quot;, PeachPuff }, { &quot;Peru&quot;, Peru }, { &quot;Pink&quot;, Pink }, { &quot;Plum&quot;, Plum }, { &quot;PowderBlue&quot;, PowderBlue }, { &quot;Purple&quot;, Purple }, { &quot;RebeccaPurple&quot;, RebeccaPurple }, { &quot;Red&quot;, Red }, { &quot;RosyBrown&quot;, RosyBrown }, { &quot;RoyalBlue&quot;, RoyalBlue }, { &quot;SaddleBrown&quot;, SaddleBrown }, { &quot;Salmon&quot;, Salmon }, { &quot;SandyBrown&quot;, SandyBrown }, { &quot;SeaGreen&quot;, SeaGreen }, { &quot;SeaShell&quot;, SeaShell }, { &quot;Sienna&quot;, Sienna }, { &quot;Silver&quot;, Silver }, { &quot;SkyBlue&quot;, SkyBlue }, { &quot;SlateBlue&quot;, SlateBlue }, { &quot;SlateGray&quot;, SlateGray }, { &quot;SlateGrey&quot;, SlateGrey }, { &quot;Snow&quot;, Snow }, { &quot;SpringGreen&quot;, SpringGreen }, { &quot;SteelBlue&quot;, SteelBlue }, { &quot;Tan&quot;, Tan }, { &quot;Teal&quot;, Teal }, { &quot;Thistle&quot;, Thistle }, { &quot;Tomato&quot;, Tomato }, { &quot;Turquoise&quot;, Turquoise }, { &quot;Violet&quot;, Violet }, { &quot;Wheat&quot;, Wheat }, { &quot;White&quot;, White }, { &quot;WhiteSmoke&quot;, WhiteSmoke }, { &quot;Yellow&quot;, Yellow }, { &quot;YellowGreen&quot;, YellowGreen } }; } } </code></pre> <p>And then made a pretty cool page showcasing all colors:</p> <p><strong>Colors.razor</strong></p> <pre><code>@page &quot;/color&quot; @using Color &lt;h3&gt;Colors&lt;/h3&gt; &lt;style&gt; .square-container { display: flex; justify-content: space-around; flex-wrap: wrap; } .square { display: flex; flex-direction: column; justify-content: center; align-items: center; width: 400px; height: 300px; margin: 20px; } &lt;/style&gt; &lt;div class=&quot;square-container&quot;&gt; @foreach ((string name, Color color) in Colors.ByName) { &lt;div class=&quot;square&quot; style=&quot;@($&quot;background-color: {color.ToCssRgba()}; color: {(color.Luminance &gt; 0.5 ? &quot;black&quot; : &quot;white&quot;)}&quot;)&quot;&gt; &lt;p&gt;@name&lt;/p&gt; &lt;p&gt;@color.ToCssColor()&lt;/p&gt; &lt;p&gt;@color.ToCssRgba()&lt;/p&gt; &lt;p&gt;@color.ToCssHsla()&lt;/p&gt; &lt;/div&gt; } &lt;/div&gt; </code></pre> <p><strong>Concerns</strong>:</p> <ul> <li>It really feels like the <code>Color</code> struct should be a struct indeed. I've read about structs vs classes in C# but can't quite get to a conclusion;</li> <li>Should I store ARGB into a 64 bit integer for higher precision? It doesn't feels like it is necessary;</li> <li>Should all parameters be <code>double</code>?</li> <li>Shoudl all <code>uint</code> parameters by <code>byte</code>?</li> <li>The use of tuples...? Is there a better way of doing it? It doesn't feel right.</li> </ul>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-09-02T10:01:17.053", "Id": "487506", "Score": "0", "body": "Tip: refer to [`Color.cs`](https://github.com/dotnet/runtime/blob/master/src/libraries/System.Drawing.Primitives/src/System/Drawing/Color.cs) implementation. It can be useful." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-09-02T11:22:59.133", "Id": "487514", "Score": "1", "body": "@aepot I based this class mostly on Flutter's [Color](https://github.com/flutter/engine/blob/master/lib/ui/painting.dart) which is a much more modern one" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-29T00:16:04.460", "Id": "248583", "Score": "2", "Tags": [ "c#", "css", "color", "blazor" ], "Title": "C# Color implementation with conversions from RGB to HSL and CMYK and vice versa, targetting Blazor and CSS" }
248583
<p>This is my first ever python project finished from start to end. This is the third iteration after posting twice before and using the feed back. This time I decided to add tkinter. Just seeing if there code in my program that could have been done better. Also I lots of code uses self and <strong>init</strong> and I can never seem to understand it and when to use it. Also I don't really like using python = sys.executable os.execl(python, python, * sys.argv) Just wondering their a better way to reset program without actual restarting the program.</p> <pre><code>from tkinter import * import os import sys import requests import tkinter as tk from getId import idcollect from games import GAME from wins import win_calc # Variables global Key Key = '***********************************' global num_game num_game = 20 stat_list = [1, 2, 3, 4, 5, 6] truth = ' ' # Making objects for other classes ids = idcollect() game = GAME() wins = win_calc() # Restart new def restart_program(): python = sys.executable os.execl(python, python, * sys.argv) # Switching frames def raise_frame(frame): frame.tkraise() # Collecting the data from riot api def collecting_data(): name = entry_1.get() accId = ids.ID_collected(name, Key) if accId != 'NO': game_list = [] game_list = game.find_game_ids(accId, Key, num_game) global stat_list stat_list = game.game_data(game_list, Key, name, num_game) global truth truth = wins.is_he_good(stat_list[5]) label_kill.configure(text = stat_list[1]) label_death.configure(text = stat_list[0]) label_cs.configure(text = stat_list[4]) label_honest.configure(text = truth) else: restart_program() # Making main frame window = Tk() window.geometry('500x500') window.title(&quot;Riot Skills Evaluator&quot;) # kill avg frame kill_frame = Frame(window) kill_frame.place(x = 0, y = 0, width = 500, height = 500) # death avg frame death_frame = Frame(window) death_frame.place(x = 0, y = 0, width = 500, height = 500) # cs avg frame cs_frame = Frame(window) cs_frame.place(x = 0, y = 0, width = 500, height = 500) # being honest frame honest_frame = Frame(window) honest_frame.place(x = 0, y = 0, width = 500, height = 500) # Multiple options frame second_frame = Frame(window) second_frame.place(x = 0, y = 0, width = 500, height = 500) # Main menu first_frame = Frame(window) first_frame.place(x = 0, y = 0, width = 500, height = 500) # First frame widgets label_0 = Label(first_frame, text = &quot;Enter summoner name:&quot;, width = 20, font = (&quot;bold&quot;, 20)) label_0.place(x=90,y=53) entry_1 = Entry(first_frame) entry_1.place(x=190,y=130) Button(first_frame, text = 'Search', width = 20, bg = 'brown', fg = 'white', command = lambda:[raise_frame(second_frame), collecting_data()]).place(x=180,y=200) # Second frame widgets Button(second_frame, text = 'Kills average',width = 20, bg ='brown', fg = 'white', command = lambda:raise_frame(kill_frame)).place(x=180,y=100) Button(second_frame, text = 'Death average',width = 20, bg ='brown', fg = 'white', command = lambda:raise_frame(death_frame)).place(x=180,y=150) Button(second_frame, text = 'Cs average',width = 20, bg ='brown', fg = 'white', command = lambda:raise_frame(cs_frame)).place(x=180,y=200) Button(second_frame, text = 'Honest truth',width = 20, bg = 'brown', fg = 'white', command = lambda:raise_frame(honest_frame)).place(x=180,y=250) Button(second_frame, text = 'Back',width = 20,bg = 'brown', fg='white', command = restart_program).place(x=180,y=300) # KillAvg frame label_kill = Label(kill_frame, text = stat_list[1], width=20,font=(&quot;bold&quot;, 20)) label_kill.place(x=90,y=53) Button(kill_frame, text = 'Back',width = 20,bg = 'brown', fg='white', command = lambda:raise_frame(second_frame)).place(x=180,y=300) # DeathAvg frame label_death = Label(death_frame, text = stat_list[0], width=20,font=(&quot;bold&quot;, 20)) label_death.place(x=90,y=53) Button(death_frame, text = 'Back',width = 20,bg = 'brown', fg='white', command = lambda:raise_frame(second_frame)).place(x=180,y=300) # Cs Average label_cs = Label(cs_frame, text = stat_list[4], width=20,font=(&quot;bold&quot;, 20)) label_cs.place(x=90,y=53) Button(cs_frame, text = 'Back',width = 20,bg = 'brown', fg='white', command = lambda:raise_frame(second_frame)).place(x=180,y=300) # Honest Truth label_honest = Label(honest_frame, text = truth, width=20,font=(&quot;bold&quot;, 20)) label_honest.place(x=90,y=53) Button(honest_frame, text = 'Back',width = 20,bg = 'brown', fg='white', command = lambda:raise_frame(second_frame)).place(x=180,y=300) window.mainloop() </code></pre> <p>games file</p> <pre><code>import requests class GAME: def find_game_ids(self, accId, key, num_games): i = 0 GAMEID = [] num_games = 20 url_match_list = ('https://na1.api.riotgames.com/lol/match/v4/matchlists/by-account/' + (accId) + '?queue=420&amp;endIndex=20&amp;api_key=' + (key)) response2 = requests.get(url_match_list) # Adding 20 games into the list while num_games &gt; 0: GAMEID.append('https://na1.api.riotgames.com/lol/match/v4/matches/'+str(response2.json()['matches'][i]['gameId']) + '?api_key=' + (key)) i = i + 1 num_games = num_games - 1 return GAMEID def game_data(self, game_list, key, sumName, num_games): wins = [] deaths = [] deaths = [] kills = [] assists = [] visions = [] csTotal = [] # Finding the data of said summoner in each game id for urls in game_list: response = requests.get(urls) resp_json = response.json() Loop = 0 index = 0 while Loop &lt;= 10: if resp_json['participantIdentities'][index]['player']['summonerName'] != sumName: Loop = Loop+1 index = index+1 elif resp_json['participantIdentities'][index]['player']['summonerName'] == sumName: deaths.append(resp_json['participants'][index]['stats']['deaths']) kills.append(resp_json['participants'][index]['stats']['kills']) assists.append(resp_json['participants'][index]['stats']['assists']) visions.append(resp_json['participants'][index]['stats']['visionScore']) csTotal.append(resp_json['participants'][index]['stats']['totalMinionsKilled']) wins.append(resp_json['participants'][index]['stats']['win']) break # Finding avg of each stat deaths = sum(deaths)/num_games kills = sum(kills)/num_games assists = sum(assists)/num_games visions = sum(visions)/num_games csTotal = sum(csTotal)/num_games wins = sum(wins)/num_games stat_list = [] stat_list.append(deaths) #0 stat_list.append(kills) #1 stat_list.append(assists) #2 stat_list.append(visions) #3 stat_list.append(csTotal) #4 stat_list.append(wins) #5 return stat_list </code></pre> <p>getid file</p> <pre><code>import requests class idcollect: def ID_collected(self, sumName, key): # COLLECTING DATA TO BE INSERTING FOR MATCHLIST DATABASE url = ('https://na1.api.riotgames.com/lol/summoner/v4/summoners/by-name/'+(sumName)+'?api_key='+(key)) response = requests.get(url) if response.status_code == 200: accId = (response.json()['accountId']) return accId else: accId = 'NO' return accId </code></pre> <p>wins file</p> <pre><code>import random class win_calc: def is_he_good(self, winlist): if (winlist &lt; 0.33): trash = ['DIS MANE STINKS', 'run while you can', 'I repeat, YOU ARE NOT WINNING THIS', 'I predict a fat L', 'Have fun trying to carry this person', 'He is a walking trash can', 'He needs to find a new game', 'BAD LUCK!!!'] return (random.choice(trash)) elif (winlist &gt; 0.33 and winlist &lt;= 0.5): notgood = ['Losing a bit', 'Not very good', 'He needs lots of help', 'Your back might hurt a little', 'Does not win much'] return (random.choice(notgood)) elif (winlist &gt; 0.5 and winlist &lt;= 0.65): ight = ['He is ight', 'He can win a lil', 'You guys have a decent chance to win', 'Serviceable', 'Should be a dub'] return (random.choice(ight)) elif (winlist &gt; 0.65): good = ['DUB!', 'You getting carried', 'His back gonna hurt a bit', 'winner winner chicken dinner', 'Dude wins TOO MUCH', 'You aint even gotta try', 'GODLIKE'] return (random.choice(good)) </code></pre>
[]
[ { "body": "<p>Note: below is just my opinion, do not treat it as a single source of truth. Also, I am assuming that the code works as it is expected, I will not mention functionality or any errors in logic.</p>\n<h1>General remarks:</h1>\n<ul>\n<li>I like that you have split the code to multiple files. One of my favorite points of python's zen is 'Namespaces are one honking great idea -- let's do more of those!'</li>\n<li>Try to employ some linter and formatter to keep your code consistent, otherwise the code might be hard to read. I am personally using <a href=\"https://github.com/psf/black\" rel=\"nofollow noreferrer\">black</a> and <a href=\"https://www.pylint.org/\" rel=\"nofollow noreferrer\">pylint</a>, I would suggest to take a look.</li>\n</ul>\n<h1>First file</h1>\n<ul>\n<li>Do not use global variables as much as it is possible, do not treat them as a convinient way of storing state. This will cause a lot of problems in the future.\nFor example, what if you want to run two identical things in parallel? They will have to share this state.</li>\n<li>Do not use star imports (import *) it might cause names clash and is a bad practice.</li>\n<li><code>os.execl(python, python, * sys.argv)</code> as you mention, this is not great solution. The question here is WHY do you want to restart it?\nYou should never have to restart the whole script. Instead, try to reset the state, if you remove the global variables and wrap the whole state in a couple of objects, it should be fairly easy.</li>\n<li>Use <code>if __name__ == &quot;__main__&quot;</code> instead putting all the code directly into the script.</li>\n<li>Extract different initializations to their own functions instead of adding comments.</li>\n<li>There seems to be a lot of duplication, try to extract commonalities (e.g. button initialization).</li>\n<li>Many buttons seem to have identical setup - you can extract those to a constant, then if you would like to resize it will be one change instead of many</li>\n<li>In the first file you can keep the main initialization, but I would move out all things related to tinker to other file, wrap it with a class and import and create the window here.</li>\n</ul>\n<h1>Second file</h1>\n<p>Overall, I'd suggest to extract a <code>RiotClient</code> that would do the calls for you, this way you can extract the responsibility to other place. Also, currently the class is untestable (via unit tests) without 'hacking' the requests package</p>\n<ul>\n<li>Extract the endpoint to a provider, this way the user can switch between different riot servers.</li>\n<li>Use string interpolation instead of concatenation</li>\n<li>You might want to do a builder for queries - this way you don't have to copy paste<code>api_key=</code> and the url in so many places. Something like <code>builder.withServer(&quot;na1&quot;).withEndpoint(&quot;matchlist/by-account&quot;).withToken(token)</code> or something similar.</li>\n<li><code>find_game_ids</code> can be split, currently it has two responsibilities - calling the API and</li>\n<li><code>GAMEID</code> should be lowercase, capital case is should be reserved for (global) constants (see <a href=\"https://realpython.com/python-pep8/\" rel=\"nofollow noreferrer\">here</a>)</li>\n<li>Try to use <code>typing</code> package, for example, <code>game_list</code> does not say anything about strings so it might be hard to figure out.</li>\n<li>Try to name your variables by what they are storing, for example I think <code>game_list</code> should be <code>game_url_list</code>, right? Without context it might seem that this is a list of Game objects.\nAlso, try to keep consistent with variable style <code>Loop</code> vs <code>resp_json</code> vs <code>csTotal</code>.</li>\n<li>Try to name the functions by what they are doing, <code>game_data</code> does not indicate what this function does.</li>\n<li>Consider adding error handling - what if API call fails for some reason (e.g. rate exceeded or some 5XX?). Such logic could be stored in before mentioned <code>RiotClient</code>.</li>\n<li>Create a 'typed' return type from <code>game_data</code>, returning array will require the consumer to either know the internal implementation (which field goes to whcih array element) or negotiate a contract which is impractical if you can just create an object with names for properties.</li>\n<li>Try to split your functions into multiple smaller ones and name them by what they are doing. For example, whenever you feel that you want to write a comment (<code># Finding avg of each stat</code>), extract it to a function (<code>get_avg_of_stats</code>).</li>\n</ul>\n<h1>Third file</h1>\n<ul>\n<li>Class name should be CamelCase</li>\n<li>Function name should be lower_case</li>\n<li>Here you have error handling - very good. This could be still abstracted to <code>RiotClient</code> though.</li>\n<li>You can have a single return - no need to have it for both <code>if</code> and <code>else</code>.</li>\n<li>I like that the file is small and has only one class which has a single responsibiliy - this is a pattern that you should apply to other functionalities.\nHowever, I don't think this should be a class - maybe just a function? You never use <code>self</code>.</li>\n</ul>\n<h1>Fourth file</h1>\n<ul>\n<li>Class name should be CamelCase</li>\n<li>Maybe better name for the method would be <code>is_player_good</code> ?</li>\n<li>For if statements you can use chaining syntax - <code>if 0.33 &lt; winlist &lt;= 0.5</code></li>\n<li>No need for parenthesis in <code>if</code>, <code>elif</code>, <code>return</code> statements</li>\n<li>You could have a single return here but I personally wouldn't mind the current solution</li>\n<li>This should be a function, not a class</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-29T20:18:14.120", "Id": "248634", "ParentId": "248586", "Score": "3" } } ]
{ "AcceptedAnswerId": "248634", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-29T01:47:20.277", "Id": "248586", "Score": "1", "Tags": [ "python", "api", "tkinter" ], "Title": "Fully finished my first ever python program" }
248586
<p>Rather embarrassingly, I have been coding for some years now, however I feel that I still write code in a very basic way. It is hard to be certain, when many companies often give coding interviews for free labour, and the internet rarely sees software development from a business side but treats it too academically fussing over details that an ordinary company would not waste resources on for productivity.</p> <p>I was given a task to write in Python by a fraud prevention company, which I completed and confirmed worked correctly, within their four to five hour deadline. They gave me a list of dummy transactions within a CSV file, and the following instructions:</p> <blockquote> <ol> <li><p>Using Flask + any other python libraries design a simple API service that would be able to serve information in this CSV file.</p> </li> <li><p>Assume this service will be part of an additional BI + ML pipeline, so propose a number of aggregates that each API could provide when queried.</p> </li> <li><p>This is quite an open-ended task, so feel free to take the approach you feel is right and make some assumptions if they simplify the job.</p> </li> </ol> </blockquote> <p><strong>Question:</strong> How could I improve my code and solution?</p> <p><strong>Question:</strong> Without worrying about my feelings, was this good work for 4 to 5 hours? I have a university degree in Computer Science, a paid industry year where I did software development (but I learnt very little as the company used a difficult to understand framework), and have tried hard to code since I was a young child.</p> <p><strong>I assume:</strong> The answers will vary from using a framework to reduce boilerplate code, dependency injection, test cases, using several py files, more comments, use switch instead of the numerous elif statements, error handling, proper logging rather than using print for status information, and better named variables. I guess the algorithm part of the code is poor, for example it would not search the BINs very efficiently, and a RAM database might have been a faster implementation given the high traffic this could potentially receive.</p> <p>Please be harsh, because after so many years I am always doing the same basic things, I want to finally code the way industries, or startup companies, expect.</p> <p><strong>Here is the source code:</strong></p> <pre><code>################################################################################################# # Created by XXXXX YYYYY for ZZZZZ, use at your own risk # Test the API with Post Man by sending JSON data: # { # &quot;auth&quot;: &quot;amazingHorse&quot;, # &quot;action&quot;: &quot;suseptibleBINs&quot; # &quot;term&quot;: &quot;additional information like search terms, else write 'empty'&quot; # } # Setup instructions for first time users: # Visual Studio Code # pip3 install virtualenv # .\env\Scripts\activate.bat # pip3 flask flask-sqlalchemy # pip3 install pandas # python app.py # !!! Warning: delete the xtransactions.sqlite file before each new deployment!!!! ################################################################################################# from flask import Flask, request, jsonify import sqlalchemy as db import pandas as pd from itertools import islice import collections import csv import time app = Flask(__name__) adminPassword = &quot;cyberExpert333&quot; # Admin API password userPassword = &quot;amazingHorse&quot; # User API password suseptibleBINs = [&quot;111&quot;,&quot;222&quot;,&quot;2a6f738d9ce1a8a9381aa775620fe5f0&quot;] req_data = &quot;&quot; # Stores the JSON received from API # For ordinary visitors @app.route('/') def hello_world(): return 'Welcome, this is a private nonproduction system and provides API access to authorised users only' # TODO admin access with special privs to drop tables etc... @app.route('/api/admin', methods=['POST']) def adminAccess(): req_data = request.get_json() password = req_data['password'] if(password != adminPassword): return &quot;Authentication failure&quot; else: return &quot;Welcome administrator, please finish coding this...&quot; # Normal API access @app.route('/api/user', methods=['POST']) def userAccess(): req_data = request.get_json() password = req_data['password'] # This function only checks for user password, admins have a seperate path at /api/admin if(password != userPassword): return &quot;Authentication failure&quot; else: action = req_data['action'] # What user would like to do term = req_data['term'] # Optional information, such as text to search for if(action == &quot;BIN&quot;): return binsFraudRisk() elif (action == &quot;search&quot;): return searchDatabase(term) elif (action == &quot;mean&quot;): return meanMaths(term) elif (action == &quot;mode&quot;): return modeMaths(term) elif (action == &quot;median&quot;): return medianMaths(term) elif (action == &quot;max&quot;): return maxMaths(term) elif (action == &quot;min&quot;): return minMaths(term) else: return &quot;Error in your JSON data, please resend request&quot; # Boiler plate database code def boilerPlateDatabase(): engine = db.create_engine('sqlite:///xtransactions.sqlite') connection = engine.connect() metadata = db.MetaData() census = db.Table('trans', metadata, autoload=True, autoload_with=engine) query = db.select([census]) ResultProxy = connection.execute(query) ResultSet = ResultProxy.fetchall() return ResultSet # BINs suseptible to fraud def binsFraudRisk(): ResultSet = boilerPlateDatabase() foundRow = list() for row in ResultSet: for badBIN in suseptibleBINs: if badBIN == row[4]: foundRow.append(row) # Add into foundRow array return str(foundRow) # All discovered rows which have suseptible BINs # Search string - case sensitive! def searchDatabase(searchTerm): ResultSet = boilerPlateDatabase() foundRow = list() for row in ResultSet: if (searchTerm == row[1] or searchTerm == row[2] or searchTerm == row[3] or searchTerm == row[4] or searchTerm == row[5] or searchTerm == row[6] or searchTerm == row[7] or searchTerm == row[8] or searchTerm == row[9]): foundRow.append(row) return str(foundRow) # All rows which match the query # Mean is the average def meanMaths(searchTerm): ResultSet = boilerPlateDatabase() searchNumber = 0 # 7 if(searchTerm == &quot;amount&quot;): searchNumber = 7 # 8 elif(searchTerm == &quot;currency&quot;): searchNumber = 8 else: return &quot;Error in your JSON&quot; # New array with just with numbers from amount or currency num = [] for number in ResultSet: num.append(number[searchNumber]) # Calculate the mean sum_num = 0 for t in num: sum_num = sum_num + t avg = sum_num / len(num) return str(avg) # Mode is number that appears the most def modeMaths(searchTerm): ResultSet = boilerPlateDatabase() searchNumber = 0 # 7 if(searchTerm == &quot;amount&quot;): searchNumber = 7 # 8 elif(searchTerm == &quot;currency&quot;): searchNumber = 8 else: return &quot;Error in your JSON&quot; # New array with just with numbers from amount or currency num_list = [] for number in ResultSet: num_list.append(number[searchNumber]) # calculate the frequency of each item data = collections.Counter(num_list) data_list = dict(data) max_value = max(list(data.values())) mode_val = [num for num, freq in data_list.items() if freq == max_value] if len(mode_val) == len(num_list): return &quot;Mode not found!&quot; else: return(&quot;The Mode of the list is : &quot; + ', '.join(map(str, mode_val))) # Median is middle value def medianMaths(searchTerm): ResultSet = boilerPlateDatabase() searchNumber = 0 # 7 if(searchTerm == &quot;amount&quot;): searchNumber = 7 # 8 elif(searchTerm == &quot;currency&quot;): searchNumber = 8 else: return &quot;Error in your JSON&quot; # New array with just with numbers from amount or currency num_list = [] for number in ResultSet: num_list.append(number[searchNumber]) # Sort the list num_list.sort() # Finding the position of the median if len(num_list) % 2 == 0: first_median = num_list[len(num_list) // 2] second_median = num_list[len(num_list) // 2 - 1] median = (first_median + second_median) / 2 else: median = num_list[len(num_list) // 2] return(&quot;The median is: &quot; + str(median)) # Max is highest number def maxMaths(searchTerm): ResultSet = boilerPlateDatabase() searchNumber = 0 # 7 if(searchTerm == &quot;amount&quot;): searchNumber = 7 # 8 elif(searchTerm == &quot;currency&quot;): searchNumber = 8 else: return &quot;Error in your JSON&quot; # New array with just with numbers from amount or currency num_list = [] for number in ResultSet: num_list.append(number[searchNumber]) return 'Maximum: '+str(max(num_list)) # Min is smallest number def minMaths(searchTerm): ResultSet = boilerPlateDatabase() searchNumber = 0 # 7 if(searchTerm == &quot;amount&quot;): searchNumber = 7 # 8 elif(searchTerm == &quot;currency&quot;): searchNumber = 8 else: return &quot;Error in your JSON&quot; # New array with just with numbers from amount or currency num_list = [] for number in ResultSet: num_list.append(number[searchNumber]) return 'Minimum: '+str(min(num_list)) def databaseManagement(): print(&quot;Creating new database&quot;) engine = db.create_engine('sqlite:///xtransactions.sqlite') # Create test.sqlite automatically connection = engine.connect() metadata = db.MetaData() trans = db.Table('trans', metadata, db.Column('Id', db.Integer(), unique=True), # Not in CSV file but makes life easier db.Column('t', db.String(), nullable=False), db.Column('tx_id', db.String(), nullable=False), db.Column('src_card', db.String(), nullable=False), db.Column('src_BIN', db.String(), nullable=False), db.Column('dst_card', db.String(), nullable=False), db.Column('dst_BIN', db.String(), nullable=False), db.Column('amount', db.Integer(), nullable=False), db.Column('currency', db.Integer(), nullable=False), db.Column('status', db.String(), nullable=False), ) metadata.create_all(engine) # Creates the table # Inserting record one by one with a FOR loop print(&quot;Loading CSV into database&quot;) theIDCounter = 0 # Counter variable to assign a unique ID for DB with open('trx_sample.csv') as fd: for row in islice(csv.reader(fd), 2, None): # Skip line 0 (the disclaimer) and 1 (which is stuff like t, tx_id) query = db.insert(trans).values(Id=theIDCounter, t=row[0], tx_id=row[1], src_card=row[2], src_BIN=row[3], dst_card=row[4], dst_BIN=row[5], amount=row[6], currency=row[7], status=row[8]) ResultProxy = connection.execute(query) theIDCounter = theIDCounter + 1 results = connection.execute(db.select([trans])).fetchall() if __name__ == '__main__': databaseManagement() # Loads CSV and puts everything into the DB app.run(debug=False) # If true then it causes server to restart which upsets DB </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-29T02:25:19.817", "Id": "486987", "Score": "8", "body": "Were you familiar with Python before this?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-29T17:39:16.113", "Id": "487055", "Score": "17", "body": "Hardcoding passwords in a readable script is a Well Known Blunder." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-31T15:46:54.837", "Id": "487258", "Score": "0", "body": "I think you don't need this: `db.Column('Id', db.Integer(), unique=True),`. SQLite has a special `rowid` column: https://www.sqlite.org/lang_createtable.html#rowid. (In your case, it seems that the `Id` column is an alias to `rowid`.)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-31T20:13:00.840", "Id": "487315", "Score": "0", "body": "were you asked to use sqlite? (or any database at all, for that matters?)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-09-01T07:59:44.113", "Id": "487377", "Score": "0", "body": "`when many companies often give coding interviews for free labour` I don't think this has ever been true. I can't imagine a situation where I would ever get anything useful from a few hours work from someone with no knowledge of the company or current code base. Integrating and using some random persons code would probably take as long as just writing it in house to begin with." } ]
[ { "body": "<p>These observations are just about the code itself and not about your implementation</p>\n<p>The vast majority of Python code bases adhere to the <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"noreferrer\">PEP8</a> style guide, this helps Python developers parse and understand each others code. Your code does not follow PEP8 guidelines for function and variable names. Function and variable names should be <code>lowercase_with_underscores</code>:</p>\n<pre><code>def bins_fraud_risk():\n result_set = boiler_plate_database()\n</code></pre>\n<p>You are wrapping expressions in your &quot;if&quot; statements with unnecessary parenthesis, remove them:</p>\n<pre><code>if search_term == &quot;amount&quot;:\n</code></pre>\n<p>Concatenating strings with the &quot;+&quot; operator is frowned upon as it creates a new string every time which can lead to poor performance. String formatting is generally preferred</p>\n<pre><code># Using an f-string\nreturn f'The median is: {median}'\n\n# Using .format()\nreturn 'The median is: {}'.format(median)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-29T02:36:49.913", "Id": "248590", "ParentId": "248587", "Score": "7" } }, { "body": "<p>The code can be much simpler. It sounds like you already have a lot of ideas on potential improvements, so I would recommend trying those out more often and comparing the result of each one to how the code was before in order to learn from it.</p>\n<ul>\n<li><p>Your only database query is a query to fetch all rows. If you’re going to load a CSV into an SQLite database, it should be to run queries against.</p>\n</li>\n<li><p>Python has <a href=\"https://docs.python.org/3/library/statistics.html#statistics.median\" rel=\"noreferrer\">built-in median calculation</a>.</p>\n</li>\n<li><p><code>if(searchTerm == &quot;amount&quot;): searchNumber = 7</code> <code>elif(searchTerm == &quot;currency&quot;): searchNumber = 8</code> and the column extraction that follows is some very factor-out-able common logic.</p>\n</li>\n<li><p>It’s probably better API design to give each operation its own route. Doing this will also force you to factor out authentication, which also improves the code.</p>\n</li>\n<li><p>If the statistics aren’t changing at runtime, you can precompute them.</p>\n</li>\n<li><p>Comparing passwords with <code>==</code> isn’t safe because of timing attacks, but it’s a toy example, and your interviewers probably won’t care/know about that.</p>\n</li>\n<li><p>Pandas is unused.</p>\n</li>\n<li><p>There are a lot of Python standard library, language features, and formatting expectations you should learn if you’re going to be using Python. (Of course, some of that can be on the job. But other things, like checking if an element is in a list, you should know can be done better no matter which language you’re familiar with.)</p>\n</li>\n</ul>\n<p>I hope to update this answer with more detail tomorrow. Anyway, here’s an idea of what the code can look like in the meantime:</p>\n<pre class=\"lang-py prettyprint-override\"><code>import statistics\nfrom dataclasses import dataclass\n\n\n@dataclass\nclass Transaction:\n t: str\n tx_id: str\n src_card: str\n src_bin: str\n dst_card: str\n dst_bin: str\n amount: int\n currency: int # you sure?\n status: str # enum?\n\n\n@app.route(&quot;/amounts/median&quot;)\ndef median():\n return {&quot;median&quot;: statistics.median(t.amount for t in transactions)}\n\n\n# ... (every route is that short) ...\n\n\n# libraries can do this\ndef transaction_from_row(row):\n return Transaction(\n t=row[0],\n tx_id=row[1],\n src_card=row[2],\n src_bin=row[3],\n dst_card=row[4],\n dst_bin=row[5],\n amount=int(row[6]),\n currency=int(row[7]),\n status=row[8],\n )\n\n\nif __name__ == &quot;__main__&quot;:\n with open(&quot;trx_sample.csv&quot;) as f:\n # Skip line 0 (the disclaimer) and 1 (which is stuff like t, tx_id)\n transactions = [transaction_from_row(row) for row in islice(csv.reader(fd), 2)]\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-29T02:41:54.943", "Id": "248591", "ParentId": "248587", "Score": "9" } }, { "body": "<p>Your code doesn't look Pythonic as your code does not follow <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP 8</a>.</p>\n<ul>\n<li>A lot of PEP 8 is to do with whitespace; two newlines above and below top level class and function definitions, two spaces in front of an inline comment, a space always after a comma, a single space either side of operators.</li>\n<li>You're using <code>camelCase</code> rather than <code>snake_case</code> for functions and variable names.</li>\n<li>You have a lot of unneeded parentheses making your code more dense.</li>\n<li>You're inconsistent in your string delimiters.</li>\n</ul>\n<p>A couple of these issues and given that you have a function named <code>hello_world</code> makes me think you've clearly taken the Flask code from the web.</p>\n<p>You have also used comments rather than docstrings, <a href=\"https://www.python.org/dev/peps/pep-0257/\" rel=\"nofollow noreferrer\">PEP 257</a>, to document your code.</p>\n<hr />\n<p>Your server API doesn't seem too great:</p>\n<ul>\n<li><p>All responses are 200 OK even in failure where some 400 codes would make sense.</p>\n</li>\n<li><p>Your API doesn't have a common format to easily identify if a response was successful whether or not you're not using HTTP codes.</p>\n<p>Your error messages don't even have a common format or word.</p>\n</li>\n</ul>\n<hr />\n<p>In all your code at a short glance has a few red flags.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-29T21:46:18.970", "Id": "487074", "Score": "1", "body": "This is a much better answer than the currently top voted one, as they're issues I'd actually fail a PR for, rather than just merge with comments." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-30T07:51:39.793", "Id": "487109", "Score": "2", "body": "I think on balance this is a good answer, but I can't quite endorse the emphasis on the PEP 8 whitespace guidelines. As much as they are a widely held convention, I don't think it's reasonable to dismiss code as non-Pythonic because it skipped the occasional newline or didn't use two spaces before a comment. (The other things are more legitimate complaints, but you did choose to mention whitespace _first_...)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-30T15:20:25.933", "Id": "487146", "Score": "2", "body": "@DavidZ I write answers in the order I see them. Additionally the code doesn't look Pythenic due to the assortment of the PEP 8 issues, not just the whitespace." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-31T04:49:59.520", "Id": "487179", "Score": "1", "body": "@DavidZ I don't have the space in a comment to explain, but strict adherence to PEP8 is actually very important, (including the line length limit of 79), because it indirectly encourages harder to define good practices. Things like code nested to 30 levels deep and giant `if` statements are not a thing with four space indents and 79 character limits." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-31T06:28:28.347", "Id": "487189", "Score": "0", "body": "Re: 2 comments up: I totally agree that there are a wide variety of PEP 8 issues, all of which put together make the code look unpythonic. I was just noting that the fact that you listed the whitespace issues first may give the impression (whether intended or not) that you view those as the most important ones, and I was suggesting that you edit your answer to change the order (unless you really do believe that the whitespace issues are the most critical)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-31T06:29:56.147", "Id": "487190", "Score": "0", "body": "@AdamBarnes I quite strongly disagree with that. Things like high nesting levels and giant if statements are not a thing with well structured code, regardless of whether line length limits are in force. Good developers don't need an artificial line length limit to make their code readable." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-31T11:06:10.107", "Id": "487227", "Score": "0", "body": "@DavidZ If I follow through with your suggestion then I'll annoy people that don't think whatever I replace it with should come first. No matter the order I chose some group of users will be annoyed with my placement. The only way I can give a uniform experience for the first point is to write some absolute tosh first so everyone is united in their distaste for my answer." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-31T19:00:29.527", "Id": "487293", "Score": "0", "body": "@DavidZ Not everyone writes well-structured code by default though, especially not in a rush, or when the PR has been bounced for the fourth time and they're sick of it. Following PEP8 rigidly is something that can be done thoughtlessly, and doing so provokes thoughts that encourage good structure. I repeat that there's not enough space here, though." } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-29T02:44:04.433", "Id": "248592", "ParentId": "248587", "Score": "34" } }, { "body": "<p>a long block of <code>elif</code>-s can be simplified by using a dictionary lookup. So instead of this:</p>\n<pre><code>if(action == &quot;BIN&quot;):\n return binsFraudRisk()\nelif (action == &quot;search&quot;):\n return searchDatabase(term)\nelif (action == &quot;mean&quot;):\n return meanMaths(term)\nelif (action == &quot;mode&quot;):\n return modeMaths(term)\nelif (action == &quot;median&quot;):\n return medianMaths(term)\nelif (action == &quot;max&quot;):\n return maxMaths(term)\nelif (action == &quot;min&quot;):\n return minMaths(term)\nelse:\n return &quot;Error in your JSON data, please resend request&quot;\n</code></pre>\n<p>you can define a dictionary with condition as a key + result as a value, assuming all functions expect the same parameters (ie. add <code>term</code> parameter to <code>binsFraudRisk()</code> even if it will be unused there)</p>\n<pre><code>action_resolver = {\n &quot;BIN&quot;: binsFraudRisk,\n &quot;search&quot;: searchDatabase,\n # ...keep adding other functions\n}\n\n# all if-elifs will shrink into this:\nif action in action_resolver:\n return action_resolver[action](term)\nelse:\n return &quot;Error in your JSON data, please resend request&quot;\n \n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-30T01:58:54.440", "Id": "487101", "Score": "5", "body": "This is a great tip and I do this often myself. I would add one thing: creating the `action_resolver` dictionary should be done _outside_ the function where it is used, so it is only done once. If you create the dictionary every time the `userAccess` function is called, then it is less efficient than the series of `if`/`elif` tests." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-31T01:50:26.223", "Id": "487177", "Score": "0", "body": "Adding an unused `term` parameter to `binsFraudRisk()` does not seem great to me since it leads to unnecessary dependencies between functions. Had there been one more function that needs, say, 5 parameters, you would need to change definitions of all other functions. A better approach is to construct a `kwargs` dictionary and call the functions by `func(**kwargs)`." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-29T03:11:45.693", "Id": "248596", "ParentId": "248587", "Score": "17" } }, { "body": "<p>The other answers already address topics like code formatting or other things which are maybe not idiomatic. In this review, I want to focus on what I would expect if I was the interviewer and would review your solution.</p>\n<h2>1. Design a simple API</h2>\n<p>The first task ask you to design a simple API which serves some data from a CSV file. As an interviewer, I would want to see the following things:</p>\n<ul>\n<li>the API uses a common data format to provide the data to the end user, most likely JSON.</li>\n<li>The API is well behaved, e.g. it sets the correct <code>Content-Type</code> headers, and meaningful status codes.</li>\n<li>the <em>interface</em> of the API makes sense in the context of the application and is consistent.</li>\n<li>the API is well documented.</li>\n</ul>\n<p>So a good first approach would be to look at the data you have at hand. From your database schema in the <code>databaseManagement</code> function, I assume you have a list of transactions in the CSV file. So the minimum API I would like to see is:</p>\n<p><code>GET /transactions</code> - returns all transactions in the CSV file in a JSON format.<br />\n<code>GET /transactions/:id</code> - returns the transaction with the given <code>tx_id</code>.</p>\n<p>Bonus points, if you'd use something like <a href=\"https://swagger.io/specification/\" rel=\"noreferrer\">openapi</a> to specify the data types and operations of your API with this standard. This standard also allows you to provide the API documentation in an easy way.</p>\n<p>Other functionalities that could be implemented on top would be for example filtering down the list of transactions using query parameters:</p>\n<p><code>GET /transactions?currency=EUR</code> - returns all transactions with currency equal to EUR.</p>\n<p>Or you could add other resources to index by, which would be helpful for the second task:</p>\n<p><code>GET /accounts</code> - assuming a BIN is some sort of account ID, return all existing src_BINs.<br />\n<code>GET /accounts/:src_bin</code> - return some info about the given account (e.g. a balance).</p>\n<h3>Why?</h3>\n<p>In a professional environment it is extremely important to carefully design your APIs, because once they are out in the wild, you can (almost) never change them. Other tools will depend on the endpoints to behave in the documented way. I would want to see that the candidate takes this into consideration.</p>\n<h2>2. Propose a number of aggregates that each API could provide when queried</h2>\n<p>I think for this task it is mostly about the context of the interview you are in. This is a fraud detection company, and I think this should be reflected in your answer to this task.</p>\n<p>I am not from this business, so no idea what would make sense, but if I were to do something, I'd do something like:</p>\n<p><code>GET /accounts/:src_bin/statistics</code> - returns <code>min</code>, <code>max</code>, <code>mean</code> of outgoing transactions of the given <code>:src_bin</code>.</p>\n<p>or even something of higher level like:</p>\n<p><code>GET /accounts/:src_bin/outliers</code>- returns out of the ordinary transactions for the given <code>:src_bin</code></p>\n<p>Where you implement any outlier detection algorithm you find on the internet, to allow API users to find &quot;suspicious&quot; transactions.</p>\n<h3>Why?</h3>\n<p>This shows that you are not just another coding monkey, but instead that you are able to think in the business domain of the company you're going to work with, which is a very important skill for any software engineer.</p>\n<h2>Topics to learn about</h2>\n<p>You explicitly ask about advice on how to</p>\n<blockquote>\n<p>[...] finally code the way industries, or startup companies, expect.</p>\n</blockquote>\n<p>And I think there are a few skills you should acquire which will help you tackle tasks like this more easily:</p>\n<ul>\n<li>know the well-established standards. Other answers mentioned the <code>pep8</code> code formatting convention, but also you should know about openapi and REST when you're working in any web related engineering position.</li>\n<li>if you introduce additional dependencies, there should be a good reason for it. I'm thinking about using SQLite as a database. I think it technically is a good choice, but you don't really use any of its features in your code. All the aggregates that you provide don't use any of <a href=\"https://www.sqlitetutorial.net/sqlite-aggregate-functions/\" rel=\"noreferrer\">SQL's aggregation functionality</a>.</li>\n<li>know how to do <a href=\"https://cheatsheetseries.owasp.org/cheatsheets/REST_Security_Cheat_Sheet.html\" rel=\"noreferrer\">API authentication</a>. The task didn't ask for authentication, so I think the choice was to either don't do it at all, or do it right. Hardcoding a password and sending it in the request body is not a right way of doing it.</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-29T18:09:32.813", "Id": "248629", "ParentId": "248587", "Score": "17" } }, { "body": "<p>Personally there is one thing that puts me off: the use of index values instead of field names. Consider this example:</p>\n<pre><code># BINs suseptible to fraud\ndef binsFraudRisk():\n ResultSet = boilerPlateDatabase()\n foundRow = list()\n for row in ResultSet:\n for badBIN in suseptibleBINs:\n if badBIN == row[4]: \n foundRow.append(row) # Add into foundRow array\n return str(foundRow) # All discovered rows which have suseptible BINs\n</code></pre>\n<p>If you have a SQL database then I don't understand why you do this stuff (row by row iteration to find bad BINs) when a simple SQL query would do the job. This is not efficient.</p>\n<p>But the other problem is the reference to field #4. What if your table structure changes ? It is perfectly conceivable that a few more fields may be added/inserted in the future, and that the position of other fields will shift as a result. So you'll have to make plenty of adjustments in your code and there is always a risk that you will forget one line (or more). Then your code will probably continue to work but some conditions will no longer evaluate the way you intended. This is a good way to introduce bugs.</p>\n<p>And using columns number is not <strong>intuitive</strong> at all.</p>\n<p>Your code is full of hardcoded magic numbers too. If you can't avoid them, use <strong>constants</strong>.</p>\n<p>You make repeated calls to <code>boilerPlateDatabase()</code> which in turns does this: <code>ResultSet = ResultProxy.fetchall()</code>, which is terribly inefficient and unnecessary. Just do regular SQL queries. I think that you didn't take the time yet to read up about SQLAlchemy (since it's the platform you've chosen). Python also supports SQLite out of the box so you could make queries easily, even without SQLAlchemy.</p>\n<p>Or if you are going to load all records to memory do it once only, on startup. Because you are working on a static sample of data that is not going to change anyway. No need to reload it all every time.</p>\n<p>My advice would be:</p>\n<ul>\n<li>if you are dealing with a SQL database, learn to use proper SQL</li>\n<li>make it a habit to measure the <strong>execution time</strong> of your code, here is a useful pointer: <a href=\"https://realpython.com/python-timer/\" rel=\"noreferrer\">https://realpython.com/python-timer/</a>\nYou can achieve massive gains by improving your code. The impact may not be very noticeable right now but when you run expensive code in a loop your users will be getting impatient behind their screens.</li>\n</ul>\n<p>Pandas could have been an option but in the present case regular SQL should be more than enough.</p>\n<p>But think of what would happen with a very large dataset. Your application will not scale and become slower (or crash) and loading the whole thing to memory could lead to performance issues. Just for kicks I would have a look at memory usage and CPU levels while the application is running. I found flaws in my own applications just by doing that. Like, a command-line application taking up 25% CPU or 50 Mb RAM =&gt; not looking hood.</p>\n<p>In one word you need to learn how to write <strong>efficient</strong> code and not just code that does the work.</p>\n<p>Last but not least: seems to me that the API should be implemented as a standalone class, thus in a separate file. It is distinct than the interface.</p>\n<p>The comments in your code are not really helpful: I learn nothing about the functions by looking at them. What would help is two or three line explaining the logic and showing a data sample perhaps.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-29T23:16:54.550", "Id": "248639", "ParentId": "248587", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-29T02:02:11.603", "Id": "248587", "Score": "18", "Tags": [ "python" ], "Title": "Fraud detection database API server" }
248587
<p>I have this function which calculates how many seconds, mins, hours etc ago a specific time string was.</p> <p>However, the way I have done it consists of a massive if statement block, and it goes through each specific time that it can reach.</p> <p>Is there a better way of writing this code where it's more efficient and doesn't have a massive if statement block?</p> <pre><code>define('SECS_IN_MIN', 60); define('SECS_IN_HR', 3600); define('SECS_IN_DAY', 86400); define('SECS_IN_WEEK', 604800); // 7 days define('SECS_IN_MONTH', 2592000); // 30 days define('SECS_IN_YEAR', 31536000); // 365 days // Determines if a number is a plural // Input: Takes in a number // Output: Outputs a string which is either &quot;s&quot;, if plural // OR &quot;&quot; if not plural function is_plural($num) { if ($num != 1) return &quot;s&quot;; else return &quot;&quot;; } // Gets a string line x minutes ago // Input a date // Output: a string which matches its time ago function date_to_str($time) { $currTime = time(); $pastTime = strtotime($time); $diff = $currTime - $pastTime; // Seconds Ago if ($diff &lt; SECS_IN_MIN) { $plural = is_plural($diff); return &quot;$ans few second$plural ago&quot;; // Minutes Ago } else if($diff &lt; SECS_IN_HR) { $ans = floor($diff / SECS_IN_MIN); $plural = is_plural($ans); return &quot;$ans minute$plural ago&quot;; // Hours Ago } else if ($diff &lt; SECS_IN_DAY) { $ans = floor($diff / SECS_IN_HR); $plural = is_plural($ans); return &quot;$ans hour$plural ago&quot;; // Days Ago } else if ($diff &lt; SECS_IN_WEEK) { $ans = floor($diff / SECS_IN_DAY); $plural = is_plural($ans); return &quot;$ans day$plural ago&quot;; // Weeks ago } else if ($diff &lt; SECS_IN_MONTH) { $ans = floor($diff / SECS_IN_WEEK); $plural = is_plural($ans); return &quot;$ans week$plural ago&quot;; // Months Ago } else if ($diff &lt; SECS_IN_YEAR) { $ans = floor($diff / SECS_IN_MONTH); $plural = is_plural($ans); return &quot;$ans month$plural ago&quot;; // Years Ago } else if ($diff &gt; SECS_IN_YEAR * 10) { $ans = floor($diff / SECS_IN_YEAR); $plural = is_plural($ans); return &quot;$ans year$plural ago&quot;; } return &quot;-1&quot;; } $time = &quot;2020-08-25 13:02:32&quot; echo( date_to_str($time) ); // Outputs 4 days ago </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-29T05:14:42.577", "Id": "486990", "Score": "0", "body": "We must not extend the functionality of your code in our review. We are only supposed to offer insights on how to refine your working code. After having a red hot go yourself, if you are unable to extend the functionality as required, then you should probably ask on Stack Overflow. The title of your question must uniquely describe what your script does -- not describe your concerns for the code." } ]
[ { "body": "<p>First, here is my recommended replacement for your script (inspired by <a href=\"https://stackoverflow.com/a/19680778/2943403\">this SO post</a>) and some test cases:</p>\n<p>Code: (<a href=\"https://3v4l.org/CNq7v\" rel=\"nofollow noreferrer\">Demo</a>)</p>\n<pre><code>function secondsToTime($seconds) {\n $dtF = new DateTime('@0');\n $dtT = new DateTime(&quot;@$seconds&quot;);\n $diff = $dtF-&gt;diff($dtT);\n $units = [\n 'y' =&gt; 'year',\n 'm' =&gt; 'month',\n 'd' =&gt; 'day',\n 'h' =&gt; 'hour',\n 'i' =&gt; 'minute',\n 's' =&gt; 'second'\n ];\n foreach ($units as $char =&gt; $unit) {\n if ($diff-&gt;$char) {\n if ($char === 'd' &amp;&amp; $diff-&gt;$char &gt;= 7) {\n $diff-&gt;$char = floor($diff-&gt;$char / 7);\n $unit = 'week';\n }\n return sprintf(\n '%d %s%s ago',\n $diff-&gt;$char,\n $unit,\n $diff-&gt;$char !== 1 ? 's' : ''\n );\n }\n }\n}\n\n$tests = [\n 53 =&gt; 53, // y=0, m=0, d=0, h=0, i=0, s=53\n 365 =&gt; 365, // y=0, m=0, d=0, h=0, i=6, s=5\n 7200 =&gt; 7200, // y=0, m=0, d=0, h=2, i=0, s=0\n 176455 =&gt; 176455, // y=0, m=0, d=2, h=1, i=0, s=55\n 2002000 =&gt; 2002000, // y=0, m=0, d=23, h=4, i=6, s=40\n 4592000 =&gt; 4592000, // y=0, m=1, d=22, h=3, i=33, s=20\n 66536000 =&gt; 66536000 // y=2, m=1, d=9, h=2, i=13, s=20\n];\n\nvar_export(\n array_map('secondsToTime', $tests)\n);\n</code></pre>\n<p>Output:</p>\n<pre><code>array (\n 53 =&gt; '53 seconds ago',\n 365 =&gt; '6 minutes ago',\n 7200 =&gt; '2 hours ago',\n 176455 =&gt; '2 days ago',\n 2002000 =&gt; '3 weeks ago',\n 4592000 =&gt; '1 month ago',\n 66536000 =&gt; '2 years ago',\n)\n</code></pre>\n<p>By leveraging the beauty of a PHP DateTime object, you can pick out the largest non-zero unit from the <code>diff()</code> evaluation and do a quick return from the loop/function. As a bonus, you won't need to worry about daylight savings or leap years or anything -- trust the <code>diff()</code> method.</p>\n<p>If you call <code>var_export($diff)</code>, you will see that there are additional properties populated, but you only need 6 of them.</p>\n<p>I don't think I'd bother with the overhead of a pluralizing function, just write the condition as an inline condition (ternary).</p>\n<p>If you want to make <code>$unit</code> a constant, okay, because it won't be mutated.</p>\n<p>The only special handling that is necessary is the week calculation because that is not an instantly available property in the object. Do the simple arithmetic and change the unit to be presented and proceed with returning the desired string.</p>\n<hr />\n<p>As for critiquing your code:</p>\n<ul>\n<li><code>$ans</code> is always returned but it is not always declared; I assuming this is a typo that you overlooked.</li>\n<li>Your <code>is_plural()</code> condition block is missing its curly braces.</li>\n<li><code>else if</code> as two words in php is a violation of PSR-12 coding standards. You should form one word as <code>elseif</code>.</li>\n<li>I hope that your <code>-1</code> return is never reached, but if it does then that would suggest that you need to validate your incoming seconds value.</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-29T06:07:59.733", "Id": "248603", "ParentId": "248595", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-29T02:59:47.940", "Id": "248595", "Score": "4", "Tags": [ "php", "datetime", "formatting" ], "Title": "Creating formatted \"[time] [unit] ago\" messages from a seconds value" }
248595
<p>In the process of learning JavaScript, I built a Google Chrome extension. It works but as I am adding more features the code is quickly getting duplicated, so I'm looking for ways to improve it.</p> <p>This is the code (other parts of the extension are omitted for brevity):</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>let createProject = document.getElementById('cproject'); var errorMessage = document.getElementById('error_message'); const cprojectRipple = new mdc.ripple.MDCRipple(document.getElementById('cproject')); const pLanguageElement = new mdc.select.MDCSelect(document.getElementById('planguage')); const buildtoolElement = new mdc.select.MDCSelect(document.getElementById('buildtool')); const frameworkElement = new mdc.select.MDCSelect(document.getElementById('framework')); const buildtooljsElement = new mdc.select.MDCSelect(document.getElementById('buildtool-js')); const frameworkjsElement = new mdc.select.MDCSelect(document.getElementById('framework-js')); const isPrivateSwitch = new mdc.switchControl.MDCSwitch(document.querySelector('.mdc-switch')); const pnameElement = new mdc.textField.MDCTextField(document.querySelector('.mdc-text-field')); frameworkElement.listen('MDCSelect:change', () =&gt; { // Set build tool to Maven if a framework is selected if (frameworkElement.value !== 'none' &amp;&amp; buildtoolElement.value === 'none') { buildtoolElement.selectedIndex = 1; } }); buildtoolElement.listen('MDCSelect:change', () =&gt; { // Reset framework if build tool is none if (buildtoolElement.value === 'none' &amp;&amp; frameworkElement.value !== 'none') { frameworkElement.selectedIndex = 0; } }); frameworkjsElement.listen('MDCSelect:change', () =&gt; { if (frameworkjsElement.selectedIndex !== buildtooljsElement.selectedIndex) { buildtooljsElement.selectedIndex = frameworkjsElement.selectedIndex; } }); buildtooljsElement.listen('MDCSelect:change', () =&gt; { if (frameworkjsElement.selectedIndex !== buildtooljsElement.selectedIndex) { frameworkjsElement.selectedIndex = buildtooljsElement.selectedIndex; } }); pLanguageElement.listen('MDCSelect:change', () =&gt; { console.log(`Selected language at index ${pLanguageElement.selectedIndex} with value "${pLanguageElement.value}"`); const javaConfig = document.getElementById('java-configurator'); const pyConfig = document.getElementById('python-configurator'); const jsConfig = document.getElementById('javascript-configurator'); if (pLanguageElement.value === 'java') { javaConfig.style.display = 'inline'; pyConfig.style.display = 'none'; jsConfig.style.display = 'none'; } else if (pLanguageElement.value === 'python') { javaConfig.style.display = 'none'; jsConfig.style.display = 'none'; pyConfig.style.display = 'inline'; } else if(pLanguageElement.value === 'javascript'){ javaConfig.style.display = 'none'; jsConfig.style.display = 'inline'; pyConfig.style.display = 'node'; } buildtoolElement.selectedIndex=0; frameworkElement.selectedIndex=0; buildtooljsElement.selectedIndex=0; frameworkjsElement.selectedIndex=0; }); createProject.onclick = function () { errorMessage.innerHTML = ''; // Validate project name if (!pnameElement.valid) { errorMessage.innerHTML = 'Please provide the project name'; return false; } var projectName = pnameElement.value; console.log('Project name: ', projectName); // Get language const language = pLanguageElement.value; console.log('Language selected: ', language); // Get Build Tool const buildtool = buildtoolElement.value; console.log('Build tool selected: ', buildtool); const buildtooljs = buildtooljsElement.value; const frameworkjs = frameworkjsElement.value; //Get Framework const framework = frameworkElement.value; console.log('Framework selected: ', framework); // build project type var ptype = language; if (buildtool !== 'none') { ptype = ptype + '-' + buildtool; } if (framework !== 'none') { ptype = ptype + '-' + framework; } if(buildtooljs !== 'none'){ ptype = ptype + '-' + buildtooljs; } if(frameworkjs !== 'none'){ ptype = ptype + '-' + frameworkjs; } console.log('Project type: ', ptype); var isPrivate = isPrivateSwitch.checked; alert(JSON.stringify({project_type:ptype,project_name:projectName,is_private:isPrivate})); return true; };</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;link href="https://unpkg.com/material-components-web@latest/dist/material-components-web.min.css" rel="stylesheet"&gt; &lt;script src="https://unpkg.com/material-components-web@latest/dist/material-components-web.min.js"&gt;&lt;/script&gt; &lt;div id="pconfig"&gt; &lt;!-- PROJECT LANGUAGE --&gt; &lt;div id="planguage" class="mdc-select mdc-select--filled"&gt; &lt;div class="mdc-select__anchor"&gt; &lt;span class="mdc-select__ripple"&gt;&lt;/span&gt; &lt;span class="mdc-select__selected-text"&gt;&lt;/span&gt; &lt;span class="mdc-select__dropdown-icon"&gt; &lt;svg class="mdc-select__dropdown-icon-graphic" viewBox="7 10 10 5"&gt; &lt;polygon class="mdc-select__dropdown-icon-inactive" stroke="none" fill-rule="evenodd" points="7 10 12 15 17 10"&gt; &lt;/polygon&gt; &lt;polygon class="mdc-select__dropdown-icon-active" stroke="none" fill-rule="evenodd" points="7 15 12 10 17 15"&gt; &lt;/polygon&gt; &lt;/svg&gt; &lt;/span&gt; &lt;span class="mdc-floating-label"&gt;Language&lt;/span&gt; &lt;span class="mdc-line-ripple"&gt;&lt;/span&gt; &lt;/div&gt; &lt;div class="mdc-select__menu mdc-menu mdc-menu-surface mdc-menu-surface--fullwidth"&gt; &lt;ul class="mdc-list"&gt; &lt;li class="mdc-list-item mdc-list-item--selected" data-value="java" aria-selected="true"&gt; &lt;span class="mdc-list-item__ripple"&gt;&lt;/span&gt; &lt;span class="mdc-list-item__text"&gt;Java&lt;/span&gt; &lt;/li&gt; &lt;li class="mdc-list-item" data-value="python"&gt; &lt;span class="mdc-list-item__ripple"&gt;&lt;/span&gt; &lt;span class="mdc-list-item__text"&gt;Python&lt;/span&gt; &lt;/li&gt; &lt;li class="mdc-list-item" data-value="javascript"&gt; &lt;span class="mdc-list-item__ripple"&gt;&lt;/span&gt; &lt;span class="mdc-list-item__text"&gt;Javascript&lt;/span&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;/div&gt; &lt;br&gt;&lt;br&gt; &lt;!-- JAVA CONFIGURATOR --&gt; &lt;div id="java-configurator"&gt; &lt;!-- BUILD TOOLS --&gt; &lt;div id="buildtool" class="mdc-select mdc-select--filled demo-width-class"&gt; &lt;div class="mdc-select__anchor"&gt; &lt;span class="mdc-select__ripple"&gt;&lt;/span&gt; &lt;span class="mdc-select__selected-text"&gt;&lt;/span&gt; &lt;span class="mdc-select__dropdown-icon"&gt; &lt;svg class="mdc-select__dropdown-icon-graphic" viewBox="7 10 10 5"&gt; &lt;polygon class="mdc-select__dropdown-icon-inactive" stroke="none" fill-rule="evenodd" points="7 10 12 15 17 10"&gt; &lt;/polygon&gt; &lt;polygon class="mdc-select__dropdown-icon-active" stroke="none" fill-rule="evenodd" points="7 15 12 10 17 15"&gt; &lt;/polygon&gt; &lt;/svg&gt; &lt;/span&gt; &lt;span class="mdc-floating-label"&gt;Build tool&lt;/span&gt; &lt;span class="mdc-line-ripple"&gt;&lt;/span&gt; &lt;/div&gt; &lt;div class="mdc-select__menu mdc-menu mdc-menu-surface mdc-menu-surface--fullwidth"&gt; &lt;ul class="mdc-list"&gt; &lt;li class="mdc-list-item mdc-list-item--selected" data-value="none" aria-selected="true"&gt; &lt;span class="mdc-list-item__ripple"&gt;&lt;/span&gt; &lt;span class="mdc-list-item__text"&gt;None&lt;/span&gt; &lt;/li&gt; &lt;li class="mdc-list-item" data-value="maven"&gt; &lt;span class="mdc-list-item__ripple"&gt;&lt;/span&gt; &lt;span class="mdc-list-item__text"&gt;Maven&lt;/span&gt; &lt;/li&gt; &lt;li class="mdc-list-item" data-value="gradle"&gt; &lt;span class="mdc-list-item__ripple"&gt;&lt;/span&gt; &lt;span class="mdc-list-item__text"&gt;Gradle&lt;/span&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;/div&gt; &lt;br&gt;&lt;br&gt; &lt;!-- FRAMEWORK --&gt; &lt;div id="framework" class="mdc-select mdc-select--filled demo-width-class"&gt; &lt;div class="mdc-select__anchor"&gt; &lt;span class="mdc-select__ripple"&gt;&lt;/span&gt; &lt;span class="mdc-select__selected-text"&gt;&lt;/span&gt; &lt;span class="mdc-select__dropdown-icon"&gt; &lt;svg class="mdc-select__dropdown-icon-graphic" viewBox="7 10 10 5"&gt; &lt;polygon class="mdc-select__dropdown-icon-inactive" stroke="none" fill-rule="evenodd" points="7 10 12 15 17 10"&gt; &lt;/polygon&gt; &lt;polygon class="mdc-select__dropdown-icon-active" stroke="none" fill-rule="evenodd" points="7 15 12 10 17 15"&gt; &lt;/polygon&gt; &lt;/svg&gt; &lt;/span&gt; &lt;span class="mdc-floating-label"&gt;Framework&lt;/span&gt; &lt;span class="mdc-line-ripple"&gt;&lt;/span&gt; &lt;/div&gt; &lt;div class="mdc-select__menu mdc-menu mdc-menu-surface mdc-menu-surface--fullwidth"&gt; &lt;ul class="mdc-list"&gt; &lt;li class="mdc-list-item mdc-list-item--selected" data-value="none" aria-selected="true"&gt; &lt;span class="mdc-list-item__ripple"&gt;&lt;/span&gt; &lt;span class="mdc-list-item__text"&gt;None&lt;/span&gt; &lt;/li&gt; &lt;li class="mdc-list-item" data-value="springboot"&gt; &lt;span class="mdc-list-item__ripple"&gt;&lt;/span&gt; &lt;span class="mdc-list-item__text"&gt;Spring Boot&lt;/span&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;/div&gt; &lt;br&gt;&lt;br&gt; &lt;/div&gt; &lt;!-- PYTHON CONFIGURATOR --&gt; &lt;div id="python-configurator" style="display:none"&gt; &lt;/div&gt; &lt;!-- JAVASCRIPT CONFIGURATOR --&gt; &lt;div id="javascript-configurator" style="display:none"&gt; &lt;!-- BUILD TOOLS --&gt; &lt;div id="buildtool-js" class="mdc-select mdc-select--filled demo-width-class"&gt; &lt;div class="mdc-select__anchor"&gt; &lt;span class="mdc-select__ripple"&gt;&lt;/span&gt; &lt;span class="mdc-select__selected-text"&gt;&lt;/span&gt; &lt;span class="mdc-select__dropdown-icon"&gt; &lt;svg class="mdc-select__dropdown-icon-graphic" viewBox="7 10 10 5"&gt; &lt;polygon class="mdc-select__dropdown-icon-inactive" stroke="none" fill-rule="evenodd" points="7 10 12 15 17 10"&gt; &lt;/polygon&gt; &lt;polygon class="mdc-select__dropdown-icon-active" stroke="none" fill-rule="evenodd" points="7 15 12 10 17 15"&gt; &lt;/polygon&gt; &lt;/svg&gt; &lt;/span&gt; &lt;span class="mdc-floating-label"&gt;Build tool&lt;/span&gt; &lt;span class="mdc-line-ripple"&gt;&lt;/span&gt; &lt;/div&gt; &lt;div class="mdc-select__menu mdc-menu mdc-menu-surface mdc-menu-surface--fullwidth"&gt; &lt;ul class="mdc-list"&gt; &lt;li class="mdc-list-item mdc-list-item--selected" data-value="none" aria-selected="true"&gt; &lt;span class="mdc-list-item__ripple"&gt;&lt;/span&gt; &lt;span class="mdc-list-item__text"&gt;None&lt;/span&gt; &lt;/li&gt; &lt;li class="mdc-list-item" data-value="npm"&gt; &lt;span class="mdc-list-item__ripple"&gt;&lt;/span&gt; &lt;span class="mdc-list-item__text"&gt;npm&lt;/span&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;/div&gt; &lt;br&gt;&lt;br&gt; &lt;!-- FRAMEWORK --&gt; &lt;div id="framework-js" class="mdc-select mdc-select--filled demo-width-class"&gt; &lt;div class="mdc-select__anchor"&gt; &lt;span class="mdc-select__ripple"&gt;&lt;/span&gt; &lt;span class="mdc-select__selected-text"&gt;&lt;/span&gt; &lt;span class="mdc-select__dropdown-icon"&gt; &lt;svg class="mdc-select__dropdown-icon-graphic" viewBox="7 10 10 5"&gt; &lt;polygon class="mdc-select__dropdown-icon-inactive" stroke="none" fill-rule="evenodd" points="7 10 12 15 17 10"&gt; &lt;/polygon&gt; &lt;polygon class="mdc-select__dropdown-icon-active" stroke="none" fill-rule="evenodd" points="7 15 12 10 17 15"&gt; &lt;/polygon&gt; &lt;/svg&gt; &lt;/span&gt; &lt;span class="mdc-floating-label"&gt;Framework&lt;/span&gt; &lt;span class="mdc-line-ripple"&gt;&lt;/span&gt; &lt;/div&gt; &lt;div class="mdc-select__menu mdc-menu mdc-menu-surface mdc-menu-surface--fullwidth"&gt; &lt;ul class="mdc-list"&gt; &lt;li class="mdc-list-item mdc-list-item--selected" data-value="none" aria-selected="true"&gt; &lt;span class="mdc-list-item__ripple"&gt;&lt;/span&gt; &lt;span class="mdc-list-item__text"&gt;None&lt;/span&gt; &lt;/li&gt; &lt;li class="mdc-list-item" data-value="nodejs"&gt; &lt;span class="mdc-list-item__ripple"&gt;&lt;/span&gt; &lt;span class="mdc-list-item__text"&gt;Node.js&lt;/span&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;/div&gt; &lt;br&gt;&lt;br&gt; &lt;/div&gt; &lt;!-- PROJECT NAME --&gt; &lt;label class="mdc-text-field mdc-text-field--filled mdc-text-field--label-floating"&gt; &lt;span class="mdc-text-field__ripple"&gt;&lt;/span&gt; &lt;input class="mdc-text-field__input" type="text" aria-labelledby="my-label-id" value="my-new-project" required&gt; &lt;span class="mdc-floating-label mdc-floating-label--float-above" id="my-label-id"&gt;Project name&lt;/span&gt; &lt;span class="mdc-line-ripple"&gt;&lt;/span&gt; &lt;/label&gt; &lt;br&gt;&lt;br&gt; &lt;!-- IS PRIVATE --&gt; &lt;label for="basic-switch"&gt;Private project&lt;/label&gt; &lt;div class="mdc-switch mdc-switch--checked"&gt; &lt;div class="mdc-switch__track"&gt;&lt;/div&gt; &lt;div class="mdc-switch__thumb-underlay"&gt; &lt;div class="mdc-switch__thumb"&gt;&lt;/div&gt; &lt;input type="checkbox" id="basic-switch" class="mdc-switch__native-control" role="switch" aria-checked="true" checked&gt; &lt;/div&gt; &lt;/div&gt; &lt;br&gt;&lt;br&gt; &lt;!-- CREATE BUTTON--&gt; &lt;button id="cproject" class="mdc-button mdc-button--outlined"&gt; &lt;div class="mdc-button__ripple"&gt;&lt;/div&gt; &lt;span class="mdc-button__label"&gt;Create&lt;/span&gt; &lt;/button&gt; &lt;p id="error_message" style="color:red;"&gt;&lt;/p&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <p>If you run the code snippet and click <code>CREATE</code>, an alert shows the JSON that will be sent to the backend.</p> <p>The JSON represents a <strong>project</strong> containing: a name, a type, and a boolean &quot;isPrivate&quot;. The <code>project_type</code> is a lowercase string with this format: language-[build tool]-[framework]. For example: <code>java-gradle-springboot</code> or simply <code>java</code>. Depending on the language, a project can have additional fields.</p> <ul> <li>How can I reduce the duplicated code and have a more flexible solution?</li> </ul> <p>My plan is to add more languages and configurations. Any comments are welcome.</p> <p>The complete extension is available <a href="https://chrome.google.com/webstore/detail/codestrap/mbnccmhnjeokeihamhbhnlacdcdimflg?hl=en" rel="nofollow noreferrer">here</a>. It creates a project in your GitHub repo and opens it in Gitpod.</p>
[]
[ { "body": "<p>You can rewrite the HTML in JavaScript so that you may add an array of all supported languages that you plan on adding and then just loop through each element in the array to generate a new &quot;language&quot; block. You can also nest that code in. something like this</p>\n<pre><code>(function () {\n\n})();\n</code></pre>\n<p>So that it will run when everything boots up.</p>\n<p>As for the JavaScript side, it is already really condensed and clean. You do not need to do many edits for that file. Although you can look into JS Array Prototypes to try making a list of *Elements then you iterate through each one and call the same code on it.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-30T03:18:07.197", "Id": "254073", "ParentId": "248597", "Score": "3" } }, { "body": "<h1>Javascript feedback</h1>\n<h2>Redundant code</h2>\n<p>There is some redundant code - take the first three lines:</p>\n<blockquote>\n<pre><code>let createProject = document.getElementById('cproject');\nvar errorMessage = document.getElementById('error_message');\n\nconst cprojectRipple = new mdc.ripple.MDCRipple(document.getElementById('cproject'));\n</code></pre>\n</blockquote>\n<p>There are two places where document.getElementById('cproject') appears. While users often have a lot more resources these days and browsers have come along way in the past couple decades, bear in mind that <a href=\"https://stackoverflow.com/a/11785684/1575353\">DOM access is not cheap</a>.</p>\n<p><code>createProject</code> could be passed on the third line:</p>\n<pre><code>const cprojectRipple = new mdc.ripple.MDCRipple(createProject);\n</code></pre>\n<h2>prefer using <code>const</code></h2>\n<p>The variable <code>createProject</code> is never re-assigned so it can be declared using <code>const</code> instead of <code>let</code>. Getting in the habit of this can help avoid <a href=\"https://softwareengineering.stackexchange.com/a/278653/244085\">accidental re-assignment and other bugs</a>. Many users also believe <code>var</code> should not be used with ES6 code - refer to the <a href=\"https://eslint.org/docs/rules/no-var\" rel=\"nofollow noreferrer\">ES lint rule <code>no-var</code></a>.</p>\n<h2>click handler registration</h2>\n<p>The click handler for <code>createProject</code> is assigned to the <code>onclick</code> property. This isn't wrong and it may never be required but if there was a need to have multiple click handlers then a different registration mechanism would be needed - e.g. using <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener\" rel=\"nofollow noreferrer\"><code>addEventListener()</code></a> - similar to the <code>.listen()</code> method on the mdc elements.</p>\n<h2>using <code>alert()</code></h2>\n<p>The end of that click handler for the <code>createProject</code> button calls <code>alert()</code>. While the functionality may just be test code for demonstration, know that using <code>alert()</code> can be an issue because 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> (And seemingly Chrome on iOS) but <a href=\"https://github.com/GoogleChrome/dialog-polyfill\" rel=\"nofollow noreferrer\">there is a polyfill</a></p>\n<h1>Question</h1>\n<blockquote>\n<p>How can I reduce the duplicated code and have a more flexible solution?</p>\n</blockquote>\n<p>I'm honestly not very familiar with the material design framework but there may be components that lend themselves to conditional display. Also, there maybe some mechanism similar to using <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/FormData\" rel=\"nofollow noreferrer\"><code>FormData</code></a> that can be used to simplify the serialization code in the click handler function.</p>\n<p>One approach to simplifying the code is to add a single event listener for all elements - e.g. observe all changes on a parent element and use <a href=\"https://davidwalsh.name/event-delegate\" rel=\"nofollow noreferrer\">event delegation</a>:</p>\n<pre><code>const pconfig = document.getElementById('pconfig');\npconfig.addEventListener('MDCSelect:change', { target } =&gt; {\n //delegate functionality based on target.id to other functions\n})\n</code></pre>\n<p>And perhaps a way to reduce redundancy is to only have one list for framework and one list for build tool, with options that are only displayed based on the selected language - e.g. using data attributes. If no options are applicable - e.g. for python- then hide the list.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-07T10:39:55.093", "Id": "501738", "Score": "0", "body": "Ping: https://codereview.meta.stackexchange.com/q/10611/141885" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-30T21:18:34.923", "Id": "254106", "ParentId": "248597", "Score": "3" } } ]
{ "AcceptedAnswerId": "254106", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-29T04:37:30.080", "Id": "248597", "Score": "3", "Tags": [ "javascript", "html", "ecmascript-6", "google-chrome" ], "Title": "Project builder Google Chrome Extension" }
248597
<p>I'm a chemistry student working on a research team and part of my job is to produce simple computational scripts that can be understood and used by members unfamiliar with Python or other languages. I was recently tasked with producing a script for creating crystal lattices of any desired 3-dimensional permutation of AxBxC in reduced coordinates (aka fractional coordinates) using a dictionary of the primitive cell, which is essentially a minimum volume unit cell. The user sets their desired parameters, which are found in the beginning of the original script and in the userParam function of the second script, and runs the script.</p> <p>Example of output:</p> <pre><code> ******************************************************* 1 x 1 x 2 PbCO3 14 supercell x-shift: 0.000 y-shift: 0.000 z-shift: 0.000 Sorting priority: z-y-x ******************************************************* x y z 1: O | 0.010000000 | -0.800000000 | -0.195000000 2: Pb | -0.251000000 | -0.574000000 | -0.113500000 3: O | -0.440000000 | -0.310000000 | -0.055000000 4: O | -0.230000000 | -0.060000000 | -0.055000000 5: C | -0.210000000 | -0.220000000 | -0.044000000 6: C | 0.210000000 | 0.220000000 | 0.044000000 7: O | 0.010000000 | 1.300000000 | 0.045500000 8: O | 0.230000000 | 0.060000000 | 0.055000000 9: O | 0.440000000 | 0.310000000 | 0.055000000 10: Pb | 0.251000000 | 0.574000000 | 0.113500000 11: Pb | -0.251000000 | 1.074000000 | 0.136500000 12: O | -0.230000000 | 0.560000000 | 0.195000000 13: C | -0.210000000 | 0.720000000 | 0.195000000 14: O | -0.010000000 | 0.800000000 | 0.195000000 15: O | -0.440000000 | 0.810000000 | 0.195000000 16: O | 0.010000000 | -0.800000000 | 0.305000000 17: O | 0.440000000 | 0.190000000 | 0.305000000 18: C | 0.210000000 | 0.280000000 | 0.305000000 19: O | 0.230000000 | 0.440000000 | 0.305000000 20: Pb | 0.251000000 | -0.074000000 | 0.363500000 21: Pb | -0.251000000 | -0.574000000 | 0.386500000 22: O | -0.440000000 | -0.310000000 | 0.445000000 23: O | -0.010000000 | -0.300000000 | 0.445000000 24: O | -0.230000000 | -0.060000000 | 0.445000000 25: C | -0.210000000 | -0.220000000 | 0.456000000 26: C | 0.210000000 | 0.220000000 | 0.544000000 27: O | 0.010000000 | 1.300000000 | 0.545500000 28: O | 0.230000000 | 0.060000000 | 0.555000000 29: O | 0.440000000 | 0.310000000 | 0.555000000 30: Pb | 0.251000000 | 0.574000000 | 0.613500000 31: Pb | -0.251000000 | 1.074000000 | 0.636500000 32: O | -0.230000000 | 0.560000000 | 0.695000000 33: C | -0.210000000 | 0.720000000 | 0.695000000 34: O | -0.010000000 | 0.800000000 | 0.695000000 35: O | -0.440000000 | 0.810000000 | 0.695000000 36: O | 0.440000000 | 0.190000000 | 0.805000000 37: C | 0.210000000 | 0.280000000 | 0.805000000 38: O | 0.230000000 | 0.440000000 | 0.805000000 39: Pb | 0.251000000 | -0.074000000 | 0.863500000 40: O | -0.010000000 | -0.300000000 | 0.945000000 ***Possible inversion center found at 5-6*** Enter two numbers e.g. &quot;10-20&quot; corresponding to the atomic positions you would like to cleave a surface between: 1-20 O 0.010000000 -0.800000000 -0.195000000 Pb -0.251000000 -0.574000000 -0.113500000 O -0.440000000 -0.310000000 -0.055000000 O -0.230000000 -0.060000000 -0.055000000 C -0.210000000 -0.220000000 -0.044000000 C 0.210000000 0.220000000 0.044000000 O 0.010000000 1.300000000 0.045500000 O 0.230000000 0.060000000 0.055000000 O 0.440000000 0.310000000 0.055000000 Pb 0.251000000 0.574000000 0.113500000 Pb -0.251000000 1.074000000 0.136500000 O -0.230000000 0.560000000 0.195000000 C -0.210000000 0.720000000 0.195000000 O -0.010000000 0.800000000 0.195000000 O -0.440000000 0.810000000 0.195000000 O 0.010000000 -0.800000000 0.305000000 O 0.440000000 0.190000000 0.305000000 C 0.210000000 0.280000000 0.305000000 O 0.230000000 0.440000000 0.305000000 Pb 0.251000000 -0.074000000 0.363500000 Net charge of cleaved surface: 0 </code></pre> <p>Here is the original script:</p> <pre><code>#!/usr/bin/python3 x=1; y=2; z=3; #------------------------------------------------------------------------------------------- #enter input dictionaries here PbCO3_14 = { 1 : ['Pb',(0.251, 0.574, 0.227)], 2 : [ 'Pb',(-0.251, 1.074, 0.273)], 3 : ['Pb',(-0.251, -0.574, -0.227)], 4 : [ 'Pb',(0.251, -0.074, 0.727)], 5 : ['C',(0.21, 0.22, 0.088)], 6 : [ 'C',(-0.21, 0.72, 0.39)], 7 : ['C',( -0.21, -0.22, -0.088)], 8 : [ 'C',(0.21, 0.28, 0.61)], 9 : ['O',(0.23, 0.06, 0.11)], 10 : [ 'O',(-0.23, 0.56, 0.39)], 11 : ['O',(-0.23, -0.06, -0.11)], 12 : [ 'O',(0.23, 0.44, 0.61)], 13 : ['O',(-0.01, 0.8, 0.39)], 14 : [ 'O',(0.01, 1.3, 0.091)], 15 : ['O',(0.01, -0.8, -0.39)], 16 : [ 'O',(-0.01, -0.30, 0.89)], 17 : ['O',( 0.44, 0.31, 0.11)], 18 : [ 'O',(-0.44, 0.81, 0.39)], 19 : ['O',(-0.44, -0.31, -0.11)], 20 : [ 'O',(0.44, 0.19, 0.61)] } #END OF DICTIONARIES #*****************************************************USER-PARAMETERS***************************************************** Name = ['PbCO3 #14'] #enter string corresponding to name of structure output_key = ['Quantum'] #enter either 'Abinit' or 'Quantum' for desired output format of cleaved surface, default is Quantum Espresso format #dimensions of supercell, 1x1x1 returns the primitive cell X = 1 Y = 1 Z = 2 Sort_by = [z,y,x] #sorting priority for supercell coordinates - must be some permutation of x, y, and z charges = { 'H' : +1, 'Pb' : +2, 'O' : -2, 'C' : +4 } #shifts for x y and z coordinates of the cell - use to find inversion plane x_shift = 0 y_shift = 0 z_shift = 0 STRUCTURE = PbCO3_14 #name of input dictionary for primitive cell atoms and coordinates #****************************************************END-OF-PARAMETERS**************************************************** def Expand(prim_cell,Atoms,prim,X,Y,Z,x_shift,y_shift,z_shift): Atom = [ prim[1][0]/X, prim[1][1]/Y, prim[1][2]/Z ] L_X = [ [ Atom[0] + i/X, Atom[1], Atom[2] ] for i in range(X) ]; L_XY = [ [ Coord[0], Coord[1] + i/Y, Coord[2] ] for Coord in L_X for i in range(Y) ] L_XYZ = [ [ prim[0], round(Coord[0] + x_shift,9), round(Coord[1] + y_shift,9), round(Coord[2] + i/Z + z_shift, 9) ] for Coord in L_XY for i in range(Z) ] for i in range(len(L_XYZ)): Atoms = { max( Atoms, key=int ) + 1 : L_XYZ[i], **Atoms } return Atoms #------------------------------------------------------------------------------------------- def Layer(prim_cell,Atoms,Layers): inversion = False; origin = False; k_inv = False; k_zero = False; Layered_Atoms = sorted(Atoms.items(), key = lambda x:(x[1][Sort_by[0]],x[1][Sort_by[1]],x[1][Sort_by[2]])) for i in range(len(Layered_Atoms)):[ Layers.update( { i + 1 : Layered_Atoms[i][1] } ) for i in range(len(Layered_Atoms)) ] for key, value in Layers.items(): if (key != list(Layers)[-1]) and (Layers[key+1] == [ value[0],-value[1],-value[2],-value[3] ]):inversion = True; k_inv = key if value[1] == value[2] == value[3] == 0.0: origin = True; k_zero = key print('{:4} {:2} {:^12} {:^12} {:^12}\n'.format('','','x','y','z')) for key, value in Layers.items(): if ((inversion == True ) and (key in [k_inv,k_inv+1])):print(fmt.inversion.format(key,*value)); if ((inversion == True) and (key not in [k_inv,k_inv+1])) or inversion == False: print(fmt.main.format(key,*value)) if inversion == True: print((color.BOLD + '\n***Possible inversion center found at {}-{}***\n' + color.END).format(k_inv,k_inv+1)) if origin == True: print('\n***Possible inversion center found at {}**\n'.format(k_zero)) return Layers #------------------------------------------------------------------------------------------- def Supercell(prim_cell,Atoms,Layers,X,Y,Z,x_shift,y_shift,z_shift): for i in range(len(prim_cell)): Atoms = Expand(prim_cell,Atoms,prim_cell[i+1],*params()[1],*params()[2]) del Atoms[0] Layers = Layer(prim_cell,Atoms,Layers) print('\nEnter two numbers e.g. &quot;10-20&quot; corresponding to the atomic positions you would like to cleave a surface between') Surface = input('\n: ').split('-');print('\n'); if Surface != [''] and (len(Surface) == 2): [ Cleaved_Surface.update( { i + 1 : [ *Layers[i] ] } ) for i in range(int(Surface[0]),int(Surface[1])+1) ] for i in range(len(Cleaved_Surface)): if output_key[0] == 'Abinit': Atom_Sort = sorted(Cleaved_Surface.items(), key = lambda x: (x[1][0],x[1][Sort_by[0]])); print(fmt.abinit.format(Atom_Sort[i][1][1],Atom_Sort[i][1][2],Atom_Sort[i][1][3],Atom_Sort[i][1][0])) if output_key[0] in ['','Quantum'] : Atom_Sort = sorted(Cleaved_Surface.items(), key = lambda x: (x[1][Sort_by[0]],x[1][Sort_by[1]],x[1][Sort_by[2]])) print(fmt.quantum.format(*Atom_Sort[i][1])) Net_charge(charges,Cleaved_Surface) #------------------------------------------------------------------------------------------- def params(): Dim = [X,Y,Z] if [(isinstance(dim,int)) for dim in Dim] != [True]*3: print('\nCheck supercell dimension parameters.\n');raise SystemExit; Shift = [x_shift,y_shift,z_shift] for shift in Shift: if isinstance(shift,float) == False and shift != 0: print('\nInvalid shift parameters.\n'); raise SystemExit key_map = { 1: 'x', 2: 'y', 3: 'z' }; Sorter = [key_map.get(key, 'Null') for key in Sort_by] if [Sort_by.count(sort) for sort in Sort_by] != [1]*3: print('Check Sort_by parameters.'); raise SystemExit; if output_key[0] not in ['','Quantum','Abinit']: print('Check output_key.'); raise SystemExit return Sorter,Dim,Shift #------------------------------------------------------------------------------------------- def Net_charge(charge,cleaved_surface): net_charge = int(sum([charge.get(v[0], 'Null') for k,v in cleaved_surface.items()])); def colorize(col,net_charge): print(fmt.charge.format(color.BOLD,col,net_charge,color.END)) if net_charge &gt; 0: colorize(color.GREEN,'+'+str(net_charge)) elif net_charge == 0: colorize(color.CYAN,net_charge) else: colorize(color.RED,net_charge) #------------------------------------------------------------------------------------------- class color: CYAN ='\033[96m';BOLD ='\033[1m';END ='\033[0m';HIGHLIGHT ='\033[01;97;105m'; FLASH ='\033[5m';PINK ='\033[95m';GREEN ='\033[32m';RED ='\033[31m'; class fmt: main = '{:4}: {:2} | {:12.9f} | {:12.9f} | {:12.9f}';abinit = ' {:12.9f} {:12.9f} {:12.9f} #{:3}'; quantum = '{:2} {:12.9f} {:12.9f} {:12.9f}';charge = '\nNet charge of cleaved surface: {}{}{}{}\n'; inversion = color.HIGHLIGHT + '{:4}: {:2} | {:12.9f} | {:12.9f} | {:12.9f}' + color.END; #------------------------------------------------------------------------------------------- if __name__ == &quot;__main__&quot;: Atoms = { 0 : 'Null' }; Layers = {}; Cleaved_Surface = {}; if X == Y == Z == 1: print('{}\n{} unaltered cell\n'.format('\n'+'*'*55+'\n',Name[0])) else: print('{}\n{} x {} x {} {} supercell\n'.format('\n'+'*'*55+'\n',*params()[1],Name[0])) print('x-shift: {} \ny-shift: {} \nz-shift: {} \n\nSorting priority: {}-{}-{}\n{}'.format(*params()[2],*params()[0],'\n'+'*'*55+'\n')) Supercell(STRUCTURE,Atoms,Layers,*params()[1],*params()[2]) </code></pre> <p>I'm inexperienced at programming and wanted to teach myself about classes and basic methods by incorporating them into this script in a meaningful way, and so this is how I updated it:</p> <pre><code>#!/usr/bin/python3 def userParam(x,y,z): #USER DICTIONARIES PbCO3_14 = { 1 : ['Pb',(0.251, 0.574, 0.227)], 2 : [ 'Pb',(-0.251, 1.074, 0.273)], 3 : ['Pb',(-0.251, -0.574, -0.227)], 4 : [ 'Pb',(0.251, -0.074, 0.727)], 5 : ['C',(0.21, 0.22, 0.088)], 6 : [ 'C',(-0.21, 0.72, 0.39)], 7 : ['C',( -0.21, -0.22, -0.088)], 8 : [ 'C',(0.21, 0.28, 0.61)], 9 : ['O',(0.23, 0.06, 0.11)], 10 : [ 'O',(-0.23, 0.56, 0.39)], 11 : ['O',(-0.23, -0.06, -0.11)], 12 : [ 'O',(0.23, 0.44, 0.61)], 13 : ['O',(-0.01, 0.8, 0.39)], 14 : [ 'O',(0.01, 1.3, 0.091)], 15 : ['O',(0.01, -0.8, -0.39)], 16 : [ 'O',(-0.01, -0.30, 0.89)], 17 : ['O',( 0.44, 0.31, 0.11)], 18 : [ 'O',(-0.44, 0.81, 0.39)], 19 : ['O',(-0.44, -0.31, -0.11)], 20 : [ 'O',(0.44, 0.19, 0.61)] } #END OF DICTIONARIES #*****************************************************USER-PARAMETERS***************************************************** STRUCTURE = PbCO3_14 # name of input dictionary for primitive cell atoms and coordinates Name = ['PbCO3 #14'] # enter string corresponding to name of structure # dimensions of supercell, 1x1x1 returns the primitive cell X = 1 Y = 1 Z = 2 sortBy = [z,y,x] #sorting priority for supercell coordinates - must be some permutation of x, y, and z charges = { 'H' : +1, 'Pb' : +2, 'O' : -2, 'C' : +4 } # shifts for x y and z coordinates of the cell - use to find inversion plane x_shift = 0 y_shift = 0 z_shift = 0 outputKey = ['Quantum'] # enter either 'Abinit' or 'Quantum' for desired output format of cleaved surface, default is Quantum Espresso format #****************************************************END-OF-PARAMETERS**************************************************** return [STRUCTURE,Name,outputKey,[X,Y,Z],sortBy,[x_shift,y_shift,z_shift],charges] #------------------------------------------------------------------------------------------- class color: CYAN ='\033[96m';BOLD ='\033[1m';END ='\033[0m';HIGHLIGHT ='\033[01;97;105m'; FLASH ='\033[5m';PINK ='\033[95m';GREEN ='\033[32m';RED ='\033[31m'; class fmt: main = '{:4}: {:2} | {:12.9f} | {:12.9f} | {:12.9f}'; abinit = ' {:12.9f} {:12.9f} {:12.9f} #{:3}'; quantum = '{:2} {:12.9f} {:12.9f} {:12.9f}'; charge = '\nNet charge of cleaved surface: {}{}{}{}\n'; inversion = color.HIGHLIGHT + '{:4}: {:2} | {:12.9f} | {:12.9f} | {:12.9f}' + color.END; header = '{:4} {:2} {:^12} {:^12} {:^12}\n' showParam = 'x-shift: {:4.3f} \ny-shift: {:4.3f} \nz-shift: {:4.3f} \n\nSorting priority: {}-{}-{}\n{}' class Supercell: def __init__(self,structure,name,outputKey,dim,sortBy,shift,charges): self.primitive = structure; self.name = name[0] self.format = outputKey[0] self.sortBy = sortBy self.dim = dim self.X = dim[0]; self.Y = dim[1]; self.Z = dim[2]; self.shift = shift self.x_shift = shift[0]; self.y_shift = shift[1]; self.z_shift = shift[2] self.charges = charges self.inversion = False; self.inversionKey = False self.origin = False; self.zeroKey = False self.layers = {} self.cleaved = {} #------------------------------------------------------------------------------------------- def checkParam(self): if [(isinstance(dim,int)) for dim in self.dim] != [True]*3: print('\nCheck supercell dimension parameters.\n');raise SystemExit; for shift in self.shift: if isinstance(shift,float) == False and shift != 0: print('\nInvalid shift parameters.\n'); raise SystemExit if [self.sortBy.count(sort) for sort in self.sortBy] != [1]*3: print('Check sortBy parameters.'); raise SystemExit; keyMap = { 1: 'x', 2: 'y', 3: 'z' }; sortKeys = [keyMap.get(key, 'Null') for key in self.sortBy] if self.format not in ['','Quantum','Abinit']: print('Check outputKey.'); raise SystemExit return sortKeys #------------------------------------------------------------------------------------------- def constructCell(self): emptyCell = { 0 : 'Null' } for i in range(len(self.primitive)): atom = self.primitive[i+1][0] basis = [ self.primitive[i+1][1][0]/self.X, self.primitive[i+1][1][1]/self.Y, self.primitive[i+1][1][2]/self.Z ] X_RED = [ [ basis[0] + i/self.X, basis[1], basis[2] ] for i in range(self.X) ]; XY_RED = [ [ xred[0], xred[1] + i/self.Y, xred[2] ] for xred in X_RED for i in range(self.Y) ] XYZ_RED = [ [ atom, round(xred[0] + self.x_shift,9), round(xred[1] + self.y_shift,9), round(xred[2] + i/self.Z + self.z_shift, 9) ] for xred in XY_RED for i in range(self.Z) ] for i in range(len(XYZ_RED)): emptyCell = { max( emptyCell, key=int ) + 1 : XYZ_RED[i], **emptyCell } del emptyCell[0]; return emptyCell #------------------------------------------------------------------------------------------- def layerCell(self): cell = self.constructCell() layeredCell = sorted(cell.items(), key = lambda x:(x[1][self.sortBy[0]],x[1][self.sortBy[1]],x[1][self.sortBy[2]])) for i in range(len(layeredCell)):[ self.layers.update( { i + 1 : layeredCell[i][1] } ) for i in range(len(layeredCell)) ] return self.layers #------------------------------------------------------------------------------------------- def displayParam(self): sortKeys = self.checkParam() if self.X == self.Y == self.Z == 1: print('{}\n{} unaltered cell\n'.format('\n'+'*'*55+'\n',self.name)) else: print('{}\n{} x {} x {} {} supercell\n'.format('\n'+'*'*55+'\n',*self.dim,self.name)) print(fmt.showParam.format(*self.shift,*sortKeys,'\n'+'*'*55+'\n')) #------------------------------------------------------------------------------------------- def displayCell(self): self.displayParam() layers = self.layerCell() for key, value in layers.items(): if (key != list(layers)[-1]) and (layers[key+1] == [value[0],-value[1],-value[2],-value[3]]): self.inversion = True; self.inversionKey = key if value[1] == value[2] == value[3] == 0.0: self.origin = True; self.zeroKey = key print(fmt.header.format('','','x','y','z')) for key, value in layers.items(): if ((self.inversion == True ) and (key in [self.inversionKey,self.inversionKey+1])):print(fmt.inversion.format(key,*value)); if ((self.inversion == True) and (key not in [self.inversionKey,self.inversionKey+1])) or self.inversion == False: print(fmt.main.format(key,*value)) if self.inversion == True: print((color.BOLD + '\n***Possible inversion center found at {}-{}***\n' + color.END).format(self.inversionKey,self.inversionKey+1)) if self.origin == True: print('\n***Possible inversion center found at {}**\n'.format(self.zeroKey)) while True: Surface = input('\nEnter two numbers e.g. &quot;10-20&quot; corresponding to the atomic positions you would like to cleave a surface between:\n\n').split('-');print('\n') if Surface != [''] and (len(Surface) == 2): [ self.cleaved.update( { i + 1 : [ *layers[i] ] } ) for i in range(int(Surface[0]),int(Surface[1])+1) ] else: print('Exiting...\n'); raise SystemExit for i in range(len(self.cleaved)): if self.format == 'Abinit': cellSort = sorted(self.cleaved.items(), key = lambda x: (x[1][0],x[1][self.sortBy[0]])); print(fmt.abinit.format(cellSort[i][1][1],cellSort[i][1][2],cellSort[i][1][3],cellSort[i][1][0])) if self.format in ['','Quantum']: cellSort = sorted(self.cleaved.items(), key = lambda x: (x[1][self.sortBy[0]],x[1][self.sortBy[1]],x[1][self.sortBy[2]])) print(fmt.quantum.format(*cellSort[i][1])) netCharge = int(sum([self.charges.get(data[0], 'Null') for data in self.cleaved.values()])); if netCharge &gt; 0: print(fmt.charge.format(color.BOLD,color.GREEN,'+'+str(netCharge),color.END)) elif netCharge == 0: print(fmt.charge.format(color.BOLD,color.CYAN,netCharge,color.END)) else: print(fmt.charge.format(color.BOLD,color.RED,netCharge,color.END)) print('Press enter to exit') self.cleaved = {} #------------------------------------------------------------------------------------------- if __name__ == &quot;__main__&quot;: Supercell(*userParam(1,2,3)).displayCell() </code></pre> <p>Was this an improvement? Any criticisms are welcome.</p>
[]
[ { "body": "<p>Unfortunately, I know <em>nothing</em> of crystal lattices, so I won't be able to touch on any aspect of them.</p>\n<p>And it seems from your phrasing that you wrote all of the code here. I'm also not well versed in OOP, and I rarely use classes, so I'll just comment on what I can in the code shown here.</p>\n<hr />\n<hr />\n<p>I consider your spacing and indentation in general to be off.</p>\n<p>Things like:</p>\n<pre><code>PbCO3_14 = {\n\n . . .\n\n }\n</code></pre>\n<p><a href=\"https://www.python.org/dev/peps/pep-0008/#code-lay-out\" rel=\"noreferrer\">PEP8 says</a> that the closing brace should either be flush to the left, or in-line with the first piece of data from the left. It doesn't recommend lining up with the opening brace.</p>\n<p>You also have an odd mix of far too much spacing in some places, and not enough spacing in others. For example, your first part of that same dictionary looks like:</p>\n<pre><code>PbCO3_14 = {\n\n 1 : ['Pb',(0.251, 0.574, 0.227)], 2 : [ 'Pb',(-0.251, 1.074, 0.273)], \n . . .\n</code></pre>\n<p>I don't think that initial empty line is helping readability. Also, I wouldn't put multiple keys on one line. If you're searching for a certain key, you now need to look over two columns, once you realize that it's spread out over two columns. It's longer as one column, but there are other ways around that.</p>\n<p>Your entire <code>Layer</code> function is also a good example of too much spacing. Having an extra empty line between <em>every</em> line of code doesn't help readability. <a href=\"https://www.python.org/dev/peps/pep-0008/#blank-lines\" rel=\"noreferrer\">Empty lines should be used to group like-code together.</a> Spacing everything out just forces your reader to scroll more to see code, and contributes to preventing the whole function from fitting on the screen at once.</p>\n<p>Then at the opposite end of the spectrum, you have lines like:</p>\n<pre><code>def Expand(prim_cell,Atoms,prim,X,Y,Z,x_shift,y_shift,z_shift):\n</code></pre>\n<p>Where you have no spacing between parameters. In general, commas should be followed by a space if anything else comes after the comma. Smooshing everything together just makes it more difficult to tell the parameters apart at a glance.</p>\n<p>This is also far too compressed:</p>\n<pre><code>class color:\n CYAN ='\\033[96m';BOLD ='\\033[1m';END ='\\033[0m';HIGHLIGHT ='\\033[01;97;105m'; \n FLASH ='\\033[5m';PINK ='\\033[95m';GREEN ='\\033[32m';RED ='\\033[31m';\n</code></pre>\n<p>Each member should be on its own line. You're also inconsistent with spacing around <code>=</code>. You have a space on the left, but no space on the right.</p>\n<p>Also on lines like this:</p>\n<pre><code>L_X = [ [ Atom[0] + i/X, Atom[1], Atom[2] ] for i in range(X) ];\n</code></pre>\n<p><a href=\"https://www.python.org/dev/peps/pep-0008/#pet-peeves\" rel=\"noreferrer\">PEP8 discourages that extra space inside of parenthesis</a>.</p>\n<hr />\n<pre><code>x=1; y=2; z=3;\n</code></pre>\n<p>Please don't do this. In almost every language and style guide, multiple declarations on a single line are discouraged. It generally makes it more difficult to find the source of a variable while scanning over the file. Each &quot;declaration&quot; should be on its own line, and without semicolons (semicolons are very rarely used in Python). You're using semicolons all over, even though they're unnecessary. In every case I can see in this code, semicolons are just adding noise to the lines. Don't use them like you would in Java or C++.</p>\n<hr />\n<p>Names should be in &quot;snake_case&quot;: lowercase, separated by underscores. Uppercase is reserved for things like class names, which are in &quot;UpperCamelCase&quot;.</p>\n<hr />\n<pre><code> for i in range(len(L_XYZ)): Atoms = { max( Atoms\n</code></pre>\n<p>Putting an entire <code>for</code> loop on a single line is not a good idea. Trying to force everything on to a single line just forces your users to scroll left and right to read your code. Code that is shorter vertically is not necessarily more readable if that bulk was just moved across horizontally.</p>\n<hr />\n<p>Your <code>color</code> class (which should be <code>Color</code>) is defining an enum; a closed set of options to be chosen from. Python has a <a href=\"https://docs.python.org/3/library/enum.html\" rel=\"noreferrer\">built-in for that</a> that adds some extra features:</p>\n<pre><code>from enum import Enum\n\n. . .\n\nclass Color(Enum):\n CYAN = '\\033[96m'\n BOLD = '\\033[1m'\n END = '\\033[0m'\n HIGHLIGHT = '\\033[01;97;105m'\n FLASH = '\\033[5m'\n PINK = '\\033[95m'\n GREEN = '\\033[32m'\n RED = '\\033[31m'\n</code></pre>\n<p>You likely don't need any of its special features, but by having the class inherit from <code>Enum</code>, you're indicating to your reader that that's what the intent of the class is. That could be inferred, but explicit is always good.</p>\n<p>I'd also consider renaming that class to <code>AnsiiCodes</code> or something. You have elements in there line <code>END</code> and <code>FLASH</code> that aren't themselves colors.</p>\n<hr />\n<p>In a few places you're using a list as a tuple:</p>\n<pre><code>Atom = [ prim[1][0]/X, prim[1][1]/Y, prim[1][2]/Z ]\n</code></pre>\n<p>Lists are for when you want to be able to alter the structure later. You're only using it as a read-only storage container though, so a tuple would be better:</p>\n<pre><code>atom = (prim[1][0]/X, prim[1][1]/Y, prim[1][2]/Z)\n# or even\natom = prim[1][0]/X, prim[1][1]/Y, prim[1][2]/Z # Parenthesis aren't necessary, although I'd still use them here\n</code></pre>\n<p>Tuples are generally faster and require less memory than lists. Again, they also indicate <em>intent</em>, which is important.</p>\n<hr />\n<p>In a few places you compare agains't <code>True</code>/<code>False</code>:</p>\n<pre><code>if isinstance(shift,float) == False\nif ((inversion == True )\nor inversion == False:\n</code></pre>\n<p>That's not necessary though. <code>==</code> already evaluates to a <code>True</code>/<code>False</code>, so comparing against them again is redundant. A line like:</p>\n<pre><code>if ((inversion == True) and (key not in [k_inv,k_inv+1])) or inversion == False:\n</code></pre>\n<p>Would be better written as:</p>\n<pre><code>if (inversion and (key not in [k_inv,k_inv+1])) or not inversion:\n</code></pre>\n<p>I'd have to double check precedence, but I believe all those parenthesis are superfluous as well.</p>\n<hr />\n<hr />\n<hr />\n<h1>Summary</h1>\n<ul>\n<li>Use less empty lines.</li>\n<li>Don't try to shove multiple independent things onto a single line.</li>\n<li>Don't use semicolons where they aren't necessary (and the places they are necessary should usually be rewritten anyways).</li>\n<li>Abide by proper naming standards</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-30T14:24:45.750", "Id": "487141", "Score": "0", "body": "Thanks for such a thorough and descriptive critique. I've only just started coding in the last 6 months so now is the time to establish better practices." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-29T14:51:04.487", "Id": "248624", "ParentId": "248598", "Score": "5" } }, { "body": "<p>Just a few comments.</p>\n<p><strong>Standard input techniques</strong>. Do not design a process that will require users to edit your Python code. It\nwill be a hassle for you – at a minimum. If a program needs information\nfrom users, use one or more of the standard methods: (1) command-line arguments\n(eg <a href=\"https://docs.python.org/3/library/argparse.html\" rel=\"nofollow noreferrer\">argparse</a>); (2) a JSON,\nYAML, or some other type of configuration file that either resides in a default\nlocation for the user or that the user supplies, via a path, on the command\nline; and (3) only as a last resort, real-time <code>input()</code> (avoid, avoid, avoid,\nif you can).</p>\n<p><strong>Compute or print</strong>. If possible, reorganize your code to make it more testable. Highly algorithmic\nfunctions or methods should not print or get user input, both of which make\ntesting harder and more annoying. Rather, they should take data as input and\nreturn data as output. Do the printing and user-interacting in the &quot;outer\nshell&quot; of your program, not its algorithmic guts.</p>\n<p><strong>Functions</strong>. Don't put substantive code in the <code>__name__</code> conditional. It's not testable,\nextensible, or flexible going forward. Putting all code in functions/methods is\na <strong>great idea</strong> that has survived the test of time: do it and you'll be\nstanding on the shoulders of giants!</p>\n<pre><code># No.\n\nif __name__ == &quot;__main__&quot;:\n Supercell(*userParam(1,2,3)).displayCell()\n\n# Yes.\n\nimport sys\n\ndef main(args):\n nums = [int(a) for a in args] or [1, 2, 3]\n Supercell(*userParam(*nums)).displayCell()\n\nif __name__ == '__main__':\n main(sys.argv[1:])\n</code></pre>\n<p><strong>Readability</strong>. Pay a lot more attention to code readability and scanability. You might have\nto maintain this beast in the future. I promise that you will forget – much\nmore quickly and thoroughly than you expect in your youth – how it works.\nHere's a purely stylistic edit of one function with that in mind:</p>\n<pre><code>def constructCell(self):\n # Blah, blah, blah.\n emptyCell = {0: 'Null'}\n\n # Blah, blah, blah.\n # Organize your code in commented paragraphs.\n # Blank lines between meaningful paragraphs, but not within them.\n for i in range(len(self.primitive)):\n\n # Use convenience variables to reduce repetition and the code's visual mass.\n prim1 = self.primitive[i + 1]\n atom = prim1[0]\n\n # Prefer &quot;more short lines&quot; over &quot;fewer long lines&quot;. Among other\n # things, this approach allows readers to understand logical structure\n # and perceive similarities, differences, and errors more readily.\n # Also, let your operators breathe.\n basis = [\n prim1[1][0] / self.X,\n prim1[1][1] / self.Y,\n prim1[1][2] / self.Z, # Include terminal comma for better maintainability.\n ]\n\n # Organize long list/dict comprehensions like a data structure to\n # convey the logical hierarchy. One could argue that the inner comprehensions\n # for X_RED and XY_RED could be put into a single line. Perhaps, but\n # I would rather maintain the code in this fully multi-line format.\n X_RED = [\n [\n basis[0] + i / self.X,\n basis[1],\n basis[2],\n ]\n for i in range(self.X)\n ]\n XY_RED = [\n [\n xred[0],\n xred[1] + i / self.Y,\n xred[2],\n ]\n for xred in X_RED\n for i in range(self.Y)\n ]\n XYZ_RED = [\n [\n atom,\n round(xred[0] + self.x_shift, 9),\n round(xred[1] + self.y_shift, 9),\n round(xred[2] + i / self.Z + self.z_shift, 9),\n ]\n for xred in XY_RED for i in range(self.Z)\n ]\n\n # Same thing: help your reader (including your future self).\n for i in range(len(XYZ_RED)):\n emptyCell = {\n max(emptyCell, key = int) + 1: XYZ_RED[i],\n **emptyCell,\n }\n\n del emptyCell[0];\n return emptyCell\n</code></pre>\n<p><strong>Puzzling data structure</strong>. Why is <code>self.primitive</code> a <code>dict</code> with keys <code>1..20</code> rather than just a <code>list</code> of 20 things? There could be an excellent reason (I don't know chemistry), but it seems an odd choice on the surface.</p>\n<hr />\n<p>Response to OP's question about how to get large-ish user inputs for a Python\nscript:</p>\n<p>In my experience working with a lot of technically-minded non-programmers\n(chemists in your case, social scientists in mine), people almost never have\nproblems reading and editing pretty-printed JSON files. YAML has some nice\nfeatures (aesthetically better, less line noise, files can include comments),\nbut it also includes some edge-case gotchas that can trip people up if the data\ncontains a wider range of characters. If your data is simple (the primitive\ncells look like nothing more than ASCII and numbers), YAML could be nice for\nthe aesthetics. But JSON is more edge-case-proof. Either one would be a reasonable choice.</p>\n<p>Either way, a few approaches come to mind, depending on work\nprocess details. (1) A shared, team-wide file is some known location.\nUsers can add their primitive definitions in that file.\nThis requires that team members not edit the file at the same\ntime or use some other coordination mechanism, such as a Git or an equivalent.\n(2) Each user has their own JSON file, in a default location like\n<code>$HOME/magic-crystals/primitives.json</code> or whatever. (3) Primitive definitions\nare stored in the script itself, and you control which ones get added, based on\nthe team's input.</p>\n<p>Those approaches are not mutually exclusive and can be combined in various ways\n(but start simple). Once the primitive file(s) are in place, users can provide the\nneeded inputs, including a primitive name like <code>PbCO3_14</code>, directly on the\ncommand-line and, only if truly necessary, via <code>input()</code>. If you write and\nmaintain enough command-line scripts, you will growth to hate <code>input()</code> --\ntruly, a source of much evil and computer-science mis-education.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-30T14:10:43.967", "Id": "487140", "Score": "0", "body": "Thanks for pointing all these issues out. My goal is to become a competent coder and these are the things I need to hear. This script is a part of a series of modules I've written and I use the self.primitive dictionary format universally. A list would have probably been a better choice, but I would have to gut some other modules to reintegrate everything." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-30T14:46:22.227", "Id": "487144", "Score": "0", "body": "The other team members need to add their own primitive cell which could be of length 4 or 100. What would be an effective way to allow users to enter large primitive cells, even if it's not in dictionary format?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-30T18:14:26.120", "Id": "487154", "Score": "1", "body": "@R.T I added a reply to your follow-up question. I don't know if it truly addresses what you're asking, but it might give you some options to consider." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-29T23:52:14.957", "Id": "248641", "ParentId": "248598", "Score": "5" } } ]
{ "AcceptedAnswerId": "248641", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-29T04:42:47.017", "Id": "248598", "Score": "5", "Tags": [ "python", "python-3.x" ], "Title": "Is this an improvement or did I over-complicate this script for producing crystal lattices?" }
248598
<p>I have a problem with my code, because his is required a long time to be done(only when I put big numbers like 2000)... I am trying to do the <a href="https://www.codewars.com/kata/526d84b98f428f14a60008da" rel="nofollow noreferrer"><em>Hamming Numbers</em> kata on codewars.com</a>:</p> <blockquote> <p>A Hamming number is a positive integer of the form 2<sup>i</sup>3<sup>j</sup>5<sup>k</sup>, for some non-negative integers i, j, and k.</p> <p>Write a function that computes the nth smallest Hamming number.</p> <p>Specifically:</p> <ul> <li>The first smallest Hamming number is 1 = 2<sup>0</sup>3<sup>0</sup>5<sup>0</sup></li> <li>The second smallest Hamming number is 2 = 2<sup>1</sup>3<sup>0</sup>5<sup>0</sup></li> <li>The third smallest Hamming number is 3 = 2<sup>0</sup>3<sup>1</sup>5<sup>0</sup></li> <li>The fourth smallest Hamming number is 4 = 2<sup>2</sup>3<sup>0</sup>5<sup>0</sup></li> <li>The fifth smallest Hamming number is 5 = 2<sup>0</sup>3<sup>0</sup>5<sup>1</sup></li> </ul> <p>The 20 smallest Hamming numbers are given in example test fixture.</p> <p>Your code should be able to compute all of the smallest 5,000 (Clojure: 2000, NASM: 13282) Hamming numbers without timing out.</p> </blockquote> <p>And my code is:</p> <pre><code>function isHumming(x){ while(x % 2 === 0) x /= 2; while(x % 3 === 0) x /= 3; while(x % 5 === 0) x /= 5; return x == 1; } function hamming (n){ let duzina = 1; let trenutni = 2; let poslednji = 1; while(duzina &lt; n){ if(isHumming(trenutni)){ if(trenutni &gt;= n){ poslednji = trenutni; } duzina++; } trenutni++ } return poslednji; } console.log(hamming(100)); </code></pre> <p>The problem arises when I try to put a large number like 5000, because the code seems stuck...Can anyone help me to create code which can do that in max 12 sec?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-29T07:25:06.973", "Id": "486996", "Score": "4", "body": "Welcome to CodeReview@SE. You check each \"positive integer\" for being a *Hamming number*. An alternative approach is to consider (first idea: generate) Hamming numbers only and find a way to handle *nth smallest*." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-29T13:42:53.630", "Id": "487029", "Score": "2", "body": "It would help a lot if you translated your variable names into English." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-29T06:47:38.723", "Id": "248605", "Score": "1", "Tags": [ "javascript", "mathematics" ], "Title": "Code is timeout - Hamming Number" }
248605
<p>This class works as a single instance of a worker, a worker reads from a bank of queue items from a MySQL database table, although that logic is abstracted into <code>ScraperQueueDao</code> class. One process runs only one worker, although many processes are spread across multiple servers.</p> <p>This code is only used by me for personal projects, so the usability side of things doesn't matter as much as they would usually. I would like to primarily focus on improving my code, specifically the 70 line method <code>ProcessQueueItem</code>.</p> <pre><code>public class ScraperWorker { private readonly ScraperQueue _scraperQueue; private readonly Dictionary&lt;string, ISocialEventHandler&gt; _eventHandlers; private readonly ScraperWorkerDao _scraperWorkerDao; private readonly ScraperQueueDao _scraperQueueDao; private bool _isProcessing; public ScraperWorker( ScraperQueue scraperQueue, Dictionary&lt;string, ISocialEventHandler&gt; eventHandlers, ScraperWorkerDao scraperWorkerDao, ScraperQueueDao scraperQueueDao) { _scraperQueue = scraperQueue; _eventHandlers = eventHandlers; _scraperWorkerDao = scraperWorkerDao; _scraperQueueDao = scraperQueueDao; Process(); } public void Start() { _isProcessing = true; } public void Stop() { _isProcessing = false; } public void Process() { new Thread(() =&gt; { while (true) { RenewWorkerStatus(); // Checks if we have paused the worker via an external service. if (!_isProcessing || !_scraperQueue.TryGetItem(out var item)) { Console.WriteLine(&quot;Either the worker is paused, or the queue is empty.&quot;); Thread.Sleep(TimeSpan.FromSeconds(30)); continue; } _scraperWorkerDao.UpdateWorkerLastSeen(StaticState.WorkerId); var eventHandler = ResolveEventHandlerFromItem(item.Item); eventHandler.SetCurrentItem(item.Item); var result = ProcessQueueItem(item, eventHandler); _scraperQueueDao.StoreItemResultInDatabase(result); item.MarkAsComplete(); Thread.Sleep(500); } }).Start(); } private void RenewWorkerStatus() { _isProcessing = _scraperWorkerDao.IsWorkerRunning(StaticState.WorkerId); } private ScraperQueueItemResult ProcessQueueItem(ScraperQueueItem item, ISocialEventHandler eventHandler) { try { Console.WriteLine(&quot;Started processing queue item: &quot; + item.Item); if (eventHandler.IsLoginNeeded()) { eventHandler.Login(); } eventHandler.NavigateToProfile(item.Item); if (!eventHandler.TryWaitForProfileToLoad()) { return new ScraperQueueItemResult( item.Id, &quot;Method 'TryWaitForProfileToLoad' returned false.&quot;, eventHandler.GetPageSource(), false ); } var profile = eventHandler.CreateProfile(); if (!profile.ShouldScrape()) { return new ScraperQueueItemResult( item.Id, &quot;Method 'ShouldScrape' returned false.&quot;, eventHandler.GetPageSource(), false ); } if (profile.ShouldCollectConnections()) { profile.Connections = eventHandler.GetConnections(); var filteredConnections = eventHandler.GetFilteredConnections(profile.Connections); _scraperQueue.AddItems(eventHandler.ConvertConnectionsToQueueItems(filteredConnections)); } if (profile.ShouldSave()) { if (!profile.IsPrivate) { profile.Posts = eventHandler.GetPosts(profile.Username); } profile.Save(); Console.WriteLine(&quot;We successfully saved - &quot; + profile.Url); return new ScraperQueueItemResult( item.Id, &quot;success&quot;, eventHandler.GetPageSource(), true ); } else { return new ScraperQueueItemResult( item.Id, &quot;Method 'ShouldSave' returned false.&quot;, eventHandler.GetPageSource(), false ); } } catch (Exception e) { new Client(new Configuration(StaticState.BugSnagApiKey)).Notify(e); return new ScraperQueueItemResult( item.Id, e.Message, eventHandler.GetPageSource(), false ); } } private ISocialEventHandler ResolveEventHandlerFromItem(string item) { var domain = new Uri(item).Host.Replace(&quot;www.&quot;, &quot;&quot;); if (_eventHandlers.ContainsKey(domain)) { return _eventHandlers[domain]; } throw new Exception($&quot;Failed to resolve event handler for domain {domain}&quot;); } public bool IsProcessing() { return _isProcessing; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-29T14:32:02.917", "Id": "487036", "Score": "0", "body": "I'm not sure why this has 2 downvotes or close votes for being broken, as the description doesn't say it's broken anywhere. And asking for a refactor is inline with what Code Review deems is on-topic." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-29T15:17:07.120", "Id": "487043", "Score": "1", "body": "Hey whilst I changed \"refactor\" to \"improving my code\" it would be great if you could clarify what you want refactored and why." } ]
[ { "body": "<p>All <code>try</code> / <code>catch</code> blocks have a tendency to add more code to a function.</p>\n<p>I see 2 ways to improve(decrease the code) the specified function, both include applying 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>This means taking the contents of the more complicated <code>if</code> statements and putting them into their own member functions. You can then either reference these functions directly or have a dictionary of functions to call in particular cases.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-29T14:55:29.703", "Id": "248625", "ParentId": "248613", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-29T12:04:32.530", "Id": "248613", "Score": "1", "Tags": [ "c#" ], "Title": "ScraperWorker: Refactoring large method?" }
248613
<p>Here is my little snake game which I made in c++ using the SFML library. The game is very simple. I have also included a screenshot of how the GUI looks. The files which I am loading are 30x30 colored squares. Yellow is the background. Red represents the snake. White is the cherry/fruit/prize to increase the size of the snake</p> <pre><code> #include&lt;SFML/graphics.hpp&gt; #include&lt;windows.h&gt; using namespace sf; struct position{ int x; int y; }snake[200]; char direction = 'r'; int length = 2; void update(){ for(int i = length-1;i &gt; 0;i--){ snake[i].x = snake[i-1].x; snake[i].y = snake[i-1].y; } if (direction == 'u') snake[0].y-=1; else if (direction == 'd') snake[0].y+=1; else if (direction == 'r') snake[0].x+=1; else if (direction == 'l') snake[0].x-=1; } int fruitx = 5; int fruity = 5; void genrand(){ int rx = rand() % 20; int ry = rand() % 20; fruitx = rx; fruity = ry; } int main(){ snake[0].x = 5; snake[0].y = 5; RenderWindow window(VideoMode(620,620),&quot;Snake c++&quot;); Texture t; Texture t2; Texture t3; t3.loadFromFile(&quot;images/green.png&quot;); t2.loadFromFile(&quot;images/red.png&quot;); t.loadFromFile(&quot;images/yellow.png&quot;); Sprite bg(t); Sprite sn(t2); Sprite fruit(t3); const int size = 31; while(window.isOpen()){ Event e; while(window.pollEvent(e)){ if(e.type == Event::Closed) window.close(); if(e.type == Event::KeyPressed){ if(e.key.code == Keyboard::Key::Up &amp;&amp; direction != 'd') direction = 'u'; else if(e.key.code == Keyboard::Key::Down &amp;&amp; direction != 'u') direction = 'd'; else if(e.key.code == Keyboard::Key::Left &amp;&amp; direction != 'r') direction = 'l'; else if(e.key.code == Keyboard::Key::Right &amp;&amp; direction != 'l') direction = 'r'; } } Sleep(60); update(); window.clear(); for(int i = 0;i &lt; 20;i++){ for(int j = 0;j &lt; 20;j++){ bg.setPosition(i*size,j*size); window.draw(bg); } } for(int i = 0;i &lt; length;i++) { if (snake[i].x &lt; 0) snake[i].x+=20; if (snake[i].x &gt; 19) snake[i].x-=20; if (snake[i].y &lt; 0) snake[i].y+=20; if (snake[i].y &gt; 19) snake[i].y-=20; sn.setPosition(snake[i].x*size,snake[i].y*size); if (i != 0){ if(snake[i].x == snake[0].x &amp;&amp; snake[i].y == snake[0].y) length = 2; } if (snake[i].x == fruitx &amp;&amp; snake[i].y == fruity){ length+=1; genrand(); fruit.setPosition(fruitx*size,fruity*size); } window.draw(sn); } window.draw(fruit); window.display(); } return 0; } </code></pre> <p>The snake is represented by an array of <code>position</code> objects. When I detect any collision I just reset the length of the snake. <a href="https://i.stack.imgur.com/wfpUs.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/wfpUs.png" alt="enter image description here" /></a></p>
[]
[ { "body": "<h1>Use correct capitalization of file names</h1>\n<p>Be careful with upper case and lower case in filenames. While Windows might not treat filenames case sensitively, other operating systems might. The correct <code>#include</code> is:</p>\n<pre><code>#include &lt;SFML/Graphics.hpp&gt;\n</code></pre>\n<h1>Avoid operating specific functions</h1>\n<p>You use <code>Sleep()</code>, which is not a standard C function, but rather Windows specific. Since you are using SFML, you can use <a href=\"https://www.sfml-dev.org/documentation/2.5.1/group__system.php#gab8c0d1f966b4e5110fd370b662d8c11b\" rel=\"nofollow noreferrer\"><code>sf::sleep()</code></a> instead, like so:</p>\n<pre><code>sf::sleep(sf::milliseconds(60));\n</code></pre>\n<p>You can then also remove <code>#include &lt;windows.h&gt;</code>, and then your code compiles and runs on other platforms without errors.</p>\n<h1>Add error checking</h1>\n<p>Your code ignores errors trying to open the texture files. Make sure you report an error and exit if any of the required files cannot be found.</p>\n<h1>Split off more functionality into their own functions</h1>\n<p>You already created a function <code>update()</code> to handle moving the snake one frame. However, it would be nice to move more functionality out of <code>main()</code> into their own functions, so that the game loop in <code>main()</code> becomes something simple like:</p>\n<pre><code>while (window.isOpen()) {\n handle_input();\n update();\n draw();\n sleep(milliseconds(60));\n}\n</code></pre>\n<h1>Avoid moving the whole body each frame</h1>\n<p>Instead of moving the position of every element of <code>snake[]</code>, use a <a href=\"https://en.cppreference.com/w/cpp/container/deque\" rel=\"nofollow noreferrer\"><code>std::deque</code></a> to hold the positions, and inside <code>update()</code>, just pop the tail and add a new head:</p>\n<pre><code>#include &lt;deque&gt;\n\nstruct position {\n int x;\n int y;\n};\n\nstd::deque&lt;position&gt; snake;\n\nvoid update() {\n // Calculate the new head position\n position new_head = snake.front();\n if (direction == 'u') new_head.y--;\n else if ...;\n\n // Handle wraparounds here\n if (new_head.x &lt; 0) new_head.x += ...;\n if (...) ...;\n\n // Remove the tail and add a new head\n snake.pop_back();\n snake.push_front(new_head);\n}\n</code></pre>\n<p>Using <code>std::deque</code>, the container knows its own length, and this makes it easy to use range-for loops. For example, to draw the snake:</p>\n<pre><code>for (auto position: snake) {\n sn.setPosition(position.x * size, position.y * size);\n window.draw(sn);\n}\n</code></pre>\n<h1>Use <code>struct position</code> for all positions</h1>\n<p>You can also use <code>struct position</code> to store the coordinates of the fruit:</p>\n<pre><code>position fruit;\n</code></pre>\n<p>This makes the code more consistent, and if <code>position</code> would have added comparison operators, it would save you from manually comparing the <code>x</code> and <code>y</code> coordinates separately. Which brings me to:</p>\n<h1>Use <code>sf::Vector2&lt;int&gt;</code> for the positions</h1>\n<p>SFML has a handy class to store coordinates for you, so you can write:</p>\n<pre><code>std::deque&lt;sf::Vector2&lt;int&gt;&gt; snake;\nsf::Vector2&lt;int&gt; fruit;\n</code></pre>\n<p>This type also has <code>x</code> and <code>y</code> member variables. But, it also overloads things like <code>operator=()</code>, so instead of comparing <code>x</code> and <code>y</code> coordinates manually, you can write:</p>\n<pre><code>if (snake.front() == fruit) {\n // Handle the snake eating the fruit\n}\n</code></pre>\n<h1>Code formatting</h1>\n<p>Your code has inconsistent formatting, sometimes there are spaces between operators and around braces, sometimes not. It doesn't really matter that much which code style you use, as long as you are consistent. Instead of manually fixing style issues, consider using a code formatting tool (either an external one like <a href=\"http://astyle.sourceforge.net/\" rel=\"nofollow noreferrer\">Artistic Style</a>, or your editor's built-in code formatting functions) to keep your code looking tidy.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-29T13:04:03.120", "Id": "248617", "ParentId": "248615", "Score": "4" } } ]
{ "AcceptedAnswerId": "248617", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-29T12:11:15.987", "Id": "248615", "Score": "3", "Tags": [ "c++", "snake-game", "sfml" ], "Title": "C++ Snake game using SFML libraby" }
248615
<p>Since I am trying to learn many programming languages, I created this simple Android app. What it does basically is taking a sentence <code>phrase</code> from an EditText <code>ed</code> and translate it to speech when you click the start button.</p> <p>I used <code>onActivityResult</code> to prevent app from crashing when the <code>EditText</code> becomes empty.</p> <p>I am sensing that this code, while working perfectly, is far from perfect.</p> <pre><code>import android.support.v7.app.AppCompatActivity; import java.util.Locale; import android.content.Intent; import android.os.Bundle; import android.speech.tts.TextToSpeech; import android.speech.tts.TextToSpeech.OnInitListener; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; public class MainActivity extends AppCompatActivity implements OnInitListener { private TextToSpeech myTTS; private EditText ed; private String phrase; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ed = findViewById(R.id.editText); Button startButton = findViewById(R.id.start_button); startButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { Intent checkIntent = new Intent(); checkIntent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA); startActivityForResult(checkIntent, 1); phrase = ed.getText().toString(); } }); } protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == 1) { if (resultCode == TextToSpeech.Engine.CHECK_VOICE_DATA_PASS) { myTTS = new TextToSpeech(this, this); myTTS.setLanguage(Locale.US); } else { // TTS data not yet loaded, try to install it Intent ttsLoadIntent = new Intent(); ttsLoadIntent.setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA); startActivity(ttsLoadIntent); } } } public void onInit(int status) { if (status == TextToSpeech.SUCCESS) { myTTS.speak(phrase, TextToSpeech.QUEUE_FLUSH, null); } else if (status == TextToSpeech.ERROR) { myTTS.shutdown(); } } </code></pre> <p>}</p>
[]
[ { "body": "<p>First of all better use clear variable names.\nComing from android I can guess what an 'ed' is. But for everybody it is always better to name it properly like :</p>\n<pre><code>private EditText editText;\neditText = findViewById(R.id.editText);\n</code></pre>\n<p>or in this case maybe even</p>\n<pre><code>editTextTTS;\n</code></pre>\n<p>or something similar.\nSame with myTTS, I personally would also name that :</p>\n<pre><code>private TextToSpeech textToSpeech;\n</code></pre>\n<p>You are creating a TextToSpeech Object on every click, which is absolutely unneccessary, create it once when starting the application, and reuse it. So this piece of code belongs in your onCreate() not your onClick() :</p>\n<pre><code>Intent checkIntent = new Intent();\ncheckIntent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);\nstartActivityForResult(checkIntent, 1);\n</code></pre>\n<p>That way the TTS will be ready before the user can click the button and is only initialised once.</p>\n<p>You are getting the value of your editText AFTER you startActivityForResult().\nThis does not seem to be the logical order, although if you remove the code above from your onClick(), that also solves this problem.</p>\n<p>You have a magic number 1 in your startActivityForResult() method, better use a final value with a proper name like :</p>\n<pre><code>private final int TTS_REQUEST_CODE = 1;\n</code></pre>\n<p>makes this also look way better :</p>\n<pre><code>startActivityForResult(checkIntent, TTS_REQUEST_CODE);\n\nif (requestCode == TTS_REQUEST_CODE) \n</code></pre>\n<p>In case the application becomes larger and more complex this will be way more secure and readable since the value is final and cannot be tampered with.</p>\n<p>There is no information to the user wether the TextToSpeech is installed and ready or not, I would suggest showing a Toast or a Snackbar to let the user know what is happening, especially in case of</p>\n<pre><code>status == TextToSpeech.ERROR\n</code></pre>\n<p>You might even want to smooth exit the application in this case.</p>\n<p>This app will only please Users with US English language. Why not make it get the Locale from the Users device, to set the proper language dynamically :</p>\n<pre><code>myTTS.setLanguage(Locale.getDefault());\n</code></pre>\n<p>The onInit() method should only be called once when initialising the TTS Object, so your</p>\n<pre><code>myTTS.speak(phrase, TextToSpeech.QUEUE_FLUSH, null);\n</code></pre>\n<p>is misplaced there. This code should go into your onClick() method along with a check that the editText is not empty :</p>\n<pre><code>public void onClick(View arg0) {\n\n final String phrase = ed.getText().toString();\n if(!phrase.isEmpty()) {\n myTTS.speak(phrase, TextToSpeech.QUEUE_FLUSH, null);\n } else {\n // Toast or Snackbar to tell the user Edittext is empty\n }\n</code></pre>\n<p>This will also convert</p>\n<pre><code>private String phrase;\n</code></pre>\n<p>to a local final variable, which is always better than having an unneccessary global variable.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-06T09:53:10.310", "Id": "253118", "ParentId": "248620", "Score": "2" } } ]
{ "AcceptedAnswerId": "253118", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-29T13:45:39.853", "Id": "248620", "Score": "2", "Tags": [ "beginner", "android" ], "Title": "Android text to speech app" }
248620
<p>I'm trying to implement a <code>Priority Search Tree(PST)</code> following this note: <a href="http://cs.brown.edu/courses/cs252/misc/resources/lectures/pdf/notes07.pdf" rel="noreferrer">http://cs.brown.edu/courses/cs252/misc/resources/lectures/pdf/notes07.pdf</a>. For convenience, I copied the related peuso-code here: <a href="https://i.stack.imgur.com/IFEU5.png" rel="noreferrer"><img src="https://i.stack.imgur.com/IFEU5.png" alt="creating PST" /></a></p> <p>and the note has also provided an example for creating a PST, I just copied the final tree here:</p> <p><a href="https://i.stack.imgur.com/hqYaY.png" rel="noreferrer"><img src="https://i.stack.imgur.com/hqYaY.png" alt="PST_example" /></a></p> <p>The following is my code.</p> <pre><code>#include &lt;iostream&gt; #include &lt;vector&gt; #include &lt;algorithm&gt; #include &lt;set&gt; #include &lt;queue&gt; template &lt;typename E&gt; struct Point2D { static int used_count; E _x; E _y; Point2D() : _x(0), _y(0) { used_count++; std::cout &lt;&lt; &quot;Point2D(), used_count = &quot; &lt;&lt; used_count &lt;&lt; &quot;\n&quot;; } Point2D(const E&amp; x, const E&amp; y) : _x(x), _y(y) { used_count++; std::cout &lt;&lt; &quot;Point2D(const E&amp; x, const E&amp; y), used_count = &quot; &lt;&lt; used_count &lt;&lt; &quot;\n&quot;; } Point2D(int arr[]) : _x(arr[0]), _y(arr[1]) { used_count++; std::cout &lt;&lt; &quot;Point2D(int arr[]), used_count = &quot; &lt;&lt; used_count &lt;&lt; &quot;\n&quot;; } Point2D(const Point2D&amp; other) { // copy constructor used_count++; std::cout &lt;&lt; &quot;Point2D(const Point2D&amp; other), used_count = &quot; &lt;&lt; used_count &lt;&lt; &quot;\n&quot;; _x = other._x; _y = other._y; } Point2D(Point2D&amp; other) { // copy constructor used_count++; std::cout &lt;&lt; &quot;Point2D(Point2D&amp; other), used_count = &quot; &lt;&lt; used_count &lt;&lt; &quot;\n&quot;; _x = other._x; _y = other._y; } Point2D&amp; operator=(const Point2D&amp; other) { // assignment operator _x = other._x; _y = other._y; return *this; } Point2D&amp; operator=(Point2D&amp; other) { // assignment operator _x = other._x; _y = other._y; return *this; } Point2D(Point2D&amp;&amp; other) { // move constructor if (this != &amp;other) { used_count++; std::cout &lt;&lt; &quot;Point2D(Point2D&amp;&amp; other), used_count = &quot; &lt;&lt; used_count &lt;&lt; &quot;\n&quot;; _x = other._x; _y = other._y; } } virtual ~Point2D() { used_count--; std::cout &lt;&lt; &quot;~Point2D(), used_count = &quot; &lt;&lt; used_count &lt;&lt; &quot;\n&quot;; } Point2D operator-(const Point2D&amp; other) { return Point2D(_x - other._x, _y - other._y); } Point2D operator-(Point2D&amp; other) { return Point2D(_x - other._x, _y - other._y); } bool operator&lt;(const Point2D&amp; other) { return (_y &lt; other._y) || (_y == other._y &amp;&amp; _x &lt; other._x); } }; template &lt;typename E&gt; class PSTMultiset { public: struct Element { std::string _name; Point2D&lt;E&gt; _point; Element(const std::string&amp; name, int arr[]) : _name(name), _point(arr) {} }; struct ElementComparatorY { bool operator()(const Element&amp; l, const Element&amp; r) { return (l._point._y &gt; r._point._y) || (l._point._y == r._point._y &amp;&amp; l._point._x &gt; r._point._x); } }; struct ElementComparatorX { bool operator()(const Element&amp; l, const Element&amp; r) { return (l._point._x &lt; r._point._x) || (l._point._x == r._point._x &amp;&amp; l._point._y &lt; r._point._y); } }; std::multiset&lt;Element, ElementComparatorY&gt; _points; typedef typename std::multiset&lt;Element, ElementComparatorY&gt;::iterator Iterator; int _size; PSTMultiset(int size) : _size(size) { std::cout &lt;&lt; &quot;PSTMultiset(int size)\n&quot;; } PSTMultiset(std::string names[], E points[][2], int size) : PSTMultiset(size) { // Nx2 points for (int i = 0; i &lt; _size; i++) { _points.insert(Element(names[i], points[i])); } std::cout &lt;&lt; &quot;PSTMultiset(std::string names[], E points[][2])\n&quot;; } virtual ~PSTMultiset() { Clear(); std::cout &lt;&lt; &quot;~PSTMultiset()\n&quot;; } void Print(const std::string&amp; title) { std::cout &lt;&lt; title &lt;&lt; &quot;\n&quot;; for (auto iter = _points.begin(); iter != _points.end(); iter++) { const Element&amp; p = *iter; std::cout &lt;&lt; p._name &lt;&lt; &quot;: (&quot; &lt;&lt; p._point._x &lt;&lt; &quot;, &quot; &lt;&lt; p._point._y &lt;&lt; &quot;)\n&quot;; } } class Node { public: Element _element; Node *_parent; Node *_left; Node *_right; Node(const Element&amp; element, Node* parent) : _element(element), _parent(parent), _left(nullptr), _right(nullptr) { } friend std::ostream&amp; operator&lt;&lt;(std::ostream&amp; out, Node* node) { if (node == nullptr) { return out; } if (node-&gt;_left != nullptr) { out &lt;&lt; &quot;L(&quot; &lt;&lt; node-&gt;_left-&gt;_element._name &lt;&lt; &quot;)_&quot;; } out &lt;&lt; node-&gt;_element._name &lt;&lt; &quot;: (&quot; &lt;&lt; node-&gt;_element._point._x &lt;&lt; &quot;, &quot; &lt;&lt; node-&gt;_element._point._y &lt;&lt; &quot;)&quot;; if (node-&gt;_right != nullptr) { out &lt;&lt; &quot;_R(&quot; &lt;&lt; node-&gt;_right-&gt;_element._name &lt;&lt; &quot;)&quot;; } return out; } }; Node *_root; Node* Build(Node* parent, std::multiset&lt;Element, ElementComparatorY&gt;&amp; points) { if (points.size() == 0) return nullptr; if (points.size() == 1) { Node *node = new Node(*(points.begin()), parent); return node; } auto first = points.begin(); std::multiset&lt;Element, ElementComparatorX&gt; remainPoints; auto iter = points.begin(); iter++; // remove the first point (the point with greatest Y) for (; iter != points.end(); iter++) { remainPoints.insert(*iter); } auto mid_iter = remainPoints.begin(); std::advance(mid_iter, remainPoints.size() / 2); std::multiset&lt;Element, ElementComparatorY&gt; leftPoints(remainPoints.begin(), mid_iter); std::multiset&lt;Element, ElementComparatorY&gt; rightPoints(mid_iter, remainPoints.end()); Node *node = new Node(*first, parent); node-&gt;_left = Build(node, leftPoints); node-&gt;_right = Build(node, rightPoints); return node; } void Build() { _root = Build(nullptr, _points); } void Clear() { // clear the tree by level-order traverse if (_root == nullptr) return; std::queue&lt;Node*&gt; q; q.push(_root); int height = 1; int levelSize = q.size(); while (!q.empty()) { Node *node = q.front(); std::cout &lt;&lt; node &lt;&lt; &quot; &quot;; if (node-&gt;_left != nullptr) { q.push(node-&gt;_left); } if (node-&gt;_right != nullptr) { q.push(node-&gt;_right); } delete node; q.pop(); levelSize--; if (levelSize == 0) { height++; levelSize = q.size(); std::cout &lt;&lt; &quot;\n&quot;; } } std::cout &lt;&lt; &quot;Height: &quot; &lt;&lt; height &lt;&lt; &quot;\n&quot;; } }; template&lt;&gt; int Point2D&lt;int&gt;::used_count = 0; int main() { std::string names[] = {&quot;A&quot;, &quot;B&quot;, &quot;C&quot;, &quot;D&quot;, &quot;E&quot;, &quot;F&quot;, &quot;G&quot;, &quot;H&quot;, &quot;I&quot;, &quot;J&quot;, &quot;K&quot;, &quot;M&quot;, &quot;N&quot;}; int arr[][2] = {{15, 7}, {16, 2}, {12, 1}, {14, -1}, {10, -2}, {-1, 9}, {6, 4}, {7, 6}, {-2, 5}, {2, 3}, {4, 0}, {9, -3}, {1, 8}}; int size = sizeof(arr) / sizeof(arr[0]); PSTMultiset&lt;int&gt; *t = new PSTMultiset&lt;int&gt;(names, arr, size); // print the multiset { t-&gt;Print(&quot;before&quot;); } // build PST { t-&gt;Build(); } delete t; } </code></pre> <p>The output is as follows:</p> <pre><code>PSTMultiset(int size) Point2D(int arr[]), used_count = 1 Point2D(Point2D&amp;&amp; other), used_count = 2 ~Point2D(), used_count = 1 Point2D(int arr[]), used_count = 2 Point2D(Point2D&amp;&amp; other), used_count = 3 ~Point2D(), used_count = 2 Point2D(int arr[]), used_count = 3 Point2D(Point2D&amp;&amp; other), used_count = 4 ~Point2D(), used_count = 3 Point2D(int arr[]), used_count = 4 Point2D(Point2D&amp;&amp; other), used_count = 5 ~Point2D(), used_count = 4 Point2D(int arr[]), used_count = 5 Point2D(Point2D&amp;&amp; other), used_count = 6 ~Point2D(), used_count = 5 Point2D(int arr[]), used_count = 6 Point2D(Point2D&amp;&amp; other), used_count = 7 ~Point2D(), used_count = 6 Point2D(int arr[]), used_count = 7 Point2D(Point2D&amp;&amp; other), used_count = 8 ~Point2D(), used_count = 7 Point2D(int arr[]), used_count = 8 Point2D(Point2D&amp;&amp; other), used_count = 9 ~Point2D(), used_count = 8 Point2D(int arr[]), used_count = 9 Point2D(Point2D&amp;&amp; other), used_count = 10 ~Point2D(), used_count = 9 Point2D(int arr[]), used_count = 10 Point2D(Point2D&amp;&amp; other), used_count = 11 ~Point2D(), used_count = 10 Point2D(int arr[]), used_count = 11 Point2D(Point2D&amp;&amp; other), used_count = 12 ~Point2D(), used_count = 11 Point2D(int arr[]), used_count = 12 Point2D(Point2D&amp;&amp; other), used_count = 13 ~Point2D(), used_count = 12 Point2D(int arr[]), used_count = 13 Point2D(Point2D&amp;&amp; other), used_count = 14 ~Point2D(), used_count = 13 PSTMultiset(std::string names[], E points[][2]) before F: (-1, 9) N: (1, 8) A: (15, 7) H: (7, 6) I: (-2, 5) G: (6, 4) J: (2, 3) B: (16, 2) C: (12, 1) K: (4, 0) D: (14, -1) E: (10, -2) M: (9, -3) Point2D(const Point2D&amp; other), used_count = 14 Point2D(const Point2D&amp; other), used_count = 15 Point2D(const Point2D&amp; other), used_count = 16 Point2D(const Point2D&amp; other), used_count = 17 Point2D(const Point2D&amp; other), used_count = 18 Point2D(const Point2D&amp; other), used_count = 19 Point2D(const Point2D&amp; other), used_count = 20 Point2D(const Point2D&amp; other), used_count = 21 Point2D(const Point2D&amp; other), used_count = 22 Point2D(const Point2D&amp; other), used_count = 23 Point2D(const Point2D&amp; other), used_count = 24 Point2D(const Point2D&amp; other), used_count = 25 Point2D(const Point2D&amp; other), used_count = 26 Point2D(const Point2D&amp; other), used_count = 27 Point2D(const Point2D&amp; other), used_count = 28 Point2D(const Point2D&amp; other), used_count = 29 Point2D(const Point2D&amp; other), used_count = 30 Point2D(const Point2D&amp; other), used_count = 31 Point2D(const Point2D&amp; other), used_count = 32 Point2D(const Point2D&amp; other), used_count = 33 Point2D(const Point2D&amp; other), used_count = 34 Point2D(const Point2D&amp; other), used_count = 35 Point2D(const Point2D&amp; other), used_count = 36 Point2D(const Point2D&amp; other), used_count = 37 Point2D(const Point2D&amp; other), used_count = 38 Point2D(const Point2D&amp; other), used_count = 39 Point2D(const Point2D&amp; other), used_count = 40 Point2D(const Point2D&amp; other), used_count = 41 Point2D(const Point2D&amp; other), used_count = 42 Point2D(const Point2D&amp; other), used_count = 43 Point2D(const Point2D&amp; other), used_count = 44 Point2D(const Point2D&amp; other), used_count = 45 Point2D(const Point2D&amp; other), used_count = 46 Point2D(const Point2D&amp; other), used_count = 47 Point2D(const Point2D&amp; other), used_count = 48 Point2D(const Point2D&amp; other), used_count = 49 Point2D(const Point2D&amp; other), used_count = 50 Point2D(const Point2D&amp; other), used_count = 51 Point2D(const Point2D&amp; other), used_count = 52 Point2D(const Point2D&amp; other), used_count = 53 ~Point2D(), used_count = 52 ~Point2D(), used_count = 51 Point2D(const Point2D&amp; other), used_count = 52 Point2D(const Point2D&amp; other), used_count = 53 Point2D(const Point2D&amp; other), used_count = 54 Point2D(const Point2D&amp; other), used_count = 55 Point2D(const Point2D&amp; other), used_count = 56 Point2D(const Point2D&amp; other), used_count = 57 Point2D(const Point2D&amp; other), used_count = 58 ~Point2D(), used_count = 57 ~Point2D(), used_count = 56 ~Point2D(), used_count = 55 ~Point2D(), used_count = 54 ~Point2D(), used_count = 53 ~Point2D(), used_count = 52 ~Point2D(), used_count = 51 ~Point2D(), used_count = 50 ~Point2D(), used_count = 49 ~Point2D(), used_count = 48 ~Point2D(), used_count = 47 ~Point2D(), used_count = 46 ~Point2D(), used_count = 45 ~Point2D(), used_count = 44 Point2D(const Point2D&amp; other), used_count = 45 Point2D(const Point2D&amp; other), used_count = 46 Point2D(const Point2D&amp; other), used_count = 47 Point2D(const Point2D&amp; other), used_count = 48 Point2D(const Point2D&amp; other), used_count = 49 Point2D(const Point2D&amp; other), used_count = 50 Point2D(const Point2D&amp; other), used_count = 51 Point2D(const Point2D&amp; other), used_count = 52 Point2D(const Point2D&amp; other), used_count = 53 Point2D(const Point2D&amp; other), used_count = 54 Point2D(const Point2D&amp; other), used_count = 55 Point2D(const Point2D&amp; other), used_count = 56 Point2D(const Point2D&amp; other), used_count = 57 Point2D(const Point2D&amp; other), used_count = 58 Point2D(const Point2D&amp; other), used_count = 59 ~Point2D(), used_count = 58 ~Point2D(), used_count = 57 Point2D(const Point2D&amp; other), used_count = 58 Point2D(const Point2D&amp; other), used_count = 59 Point2D(const Point2D&amp; other), used_count = 60 Point2D(const Point2D&amp; other), used_count = 61 Point2D(const Point2D&amp; other), used_count = 62 Point2D(const Point2D&amp; other), used_count = 63 Point2D(const Point2D&amp; other), used_count = 64 ~Point2D(), used_count = 63 ~Point2D(), used_count = 62 ~Point2D(), used_count = 61 ~Point2D(), used_count = 60 ~Point2D(), used_count = 59 ~Point2D(), used_count = 58 ~Point2D(), used_count = 57 ~Point2D(), used_count = 56 ~Point2D(), used_count = 55 ~Point2D(), used_count = 54 ~Point2D(), used_count = 53 ~Point2D(), used_count = 52 ~Point2D(), used_count = 51 ~Point2D(), used_count = 50 ~Point2D(), used_count = 49 ~Point2D(), used_count = 48 ~Point2D(), used_count = 47 ~Point2D(), used_count = 46 ~Point2D(), used_count = 45 ~Point2D(), used_count = 44 ~Point2D(), used_count = 43 ~Point2D(), used_count = 42 ~Point2D(), used_count = 41 ~Point2D(), used_count = 40 ~Point2D(), used_count = 39 ~Point2D(), used_count = 38 ~Point2D(), used_count = 37 ~Point2D(), used_count = 36 ~Point2D(), used_count = 35 ~Point2D(), used_count = 34 ~Point2D(), used_count = 33 ~Point2D(), used_count = 32 ~Point2D(), used_count = 31 ~Point2D(), used_count = 30 ~Point2D(), used_count = 29 ~Point2D(), used_count = 28 ~Point2D(), used_count = 27 ~Point2D(), used_count = 26 L(N)_F: (-1, 9)_R(A) ~Point2D(), used_count = 25 L(I)_N: (1, 8)_R(H) ~Point2D(), used_count = 24 L(E)_A: (15, 7)_R(B) ~Point2D(), used_count = 23 I: (-2, 5)_R(J) ~Point2D(), used_count = 22 L(K)_H: (7, 6)_R(G) ~Point2D(), used_count = 21 E: (10, -2)_R(M) ~Point2D(), used_count = 20 L(C)_B: (16, 2)_R(D) ~Point2D(), used_count = 19 J: (2, 3) ~Point2D(), used_count = 18 K: (4, 0) ~Point2D(), used_count = 17 G: (6, 4) ~Point2D(), used_count = 16 M: (9, -3) ~Point2D(), used_count = 15 C: (12, 1) ~Point2D(), used_count = 14 D: (14, -1) ~Point2D(), used_count = 13 Height: 5 ~PSTMultiset() ~Point2D(), used_count = 12 ~Point2D(), used_count = 11 ~Point2D(), used_count = 10 ~Point2D(), used_count = 9 ~Point2D(), used_count = 8 ~Point2D(), used_count = 7 ~Point2D(), used_count = 6 ~Point2D(), used_count = 5 ~Point2D(), used_count = 4 ~Point2D(), used_count = 3 ~Point2D(), used_count = 2 ~Point2D(), used_count = 1 ~Point2D(), used_count = 0 </code></pre> <p>From this result, It seems the PST tree has correctly built with the code. But I'm not sure if the code is efficiency. <strong>If you had time and convenient, could you please check the code? I greatly appreciate for any suggestions and comments</strong>. Thanks in advance.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-30T01:05:53.450", "Id": "487097", "Score": "3", "body": "@pacmaninbw, thanks for your kind comment! This is not a homework. These days I'm learning the basic data structures and algorithms, so I'm trying to implement them. I eager to learn more about C++ and write elegant code and beautiful design and solutions." } ]
[ { "body": "<h1>About using underscores</h1>\n<p>Avoid starting identifiers with an underscore, or using double underscores. Some uses of underscores are reserved, see <a href=\"https://stackoverflow.com/questions/228783/what-are-the-rules-about-using-an-underscore-in-a-c-identifier\">this question</a>.</p>\n<p>If you really want to use some way to distinguish private and public member variables, consider prefixing using <code>m_</code> or adding a single underscore at the end.</p>\n<h1>Useless overloads</h1>\n<p>I see you often have two overloads for member functions, such as:</p>\n<pre><code>Point2D&amp; operator=(const Point2D&amp; other) {...}\nPoint2D&amp; operator=(Point2D&amp; other) {...}\n</code></pre>\n<p>Unless you plan to modify <code>other</code>, there is no need for the second version.</p>\n<h1>Make member functions <code>const</code> if they do not modify the object</h1>\n<p>You should mark functions themselves as <code>const</code> if they do not make any modifications. For example:</p>\n<pre><code>bool operator&lt;(const Point2D&amp; other) const {\n return (m_y &lt; other.m_y) || (m_y == other.m_y &amp;&amp; m_x &lt; other.m_x);\n}\n</code></pre>\n<h1>Your set is actually a map</h1>\n<p>Your class name is <code>PSTMultiset</code>, but instead of a set you actually implement a map from a <code>Point2D&lt;E&gt;</code> to a <code>std::string</code>. And your internal use of <code>std::multiset</code> can thus be replaced with <code>std::multimap</code>, and you then also no longer need to declare a <code>struct Element</code>:</p>\n<pre><code>template &lt;typename E&gt;\nclass PSTMultimap {\n std::multimap&lt;Point2D&lt;E&gt;, std::string&gt; m_points;\n\n class Node {\n ...\n Point2D&lt;E&gt; m_key;\n std::string m_value;\n ...\n };\n\n ...\n};\n</code></pre>\n<p>Inside <code>Build()</code> you want to create a <code>std::multimap</code> with a custom comparison function to sort on the <code>x</code> coordinate first:</p>\n<pre><code>struct Point2DComparatorX {\n bool operator()(const Point2D&lt;E&gt;&amp; l, const Point2D&lt;E&gt;&amp; r) {\n return (l.m_x &lt; r.m_x) || (l.m_x == r.m_x &amp;&amp; l.m_y &lt; r.m_y);\n }\n};\n\nNode* Build(Node* parent, std::multimap&lt;Point2D&lt;E&gt;, std::string&gt;&amp; points) {\n ...\n std::multimap&lt;Point2D&lt;E&gt;, std::string, Point2DComparatorX&gt; remainPoints;\n ...\n};\n</code></pre>\n<h1>Consider not hardcoding the use of <code>Point2D</code> inside your PST</h1>\n<p>The only thing <code>PSTMultimap</code> needs to know about the type of keys is how to order them in two ways. It doesn't need to know you are sorting two-dimensional points. So it might be nicer if you could do something like:</p>\n<pre><code>template&lt;typename Key, typename Value, typename Compare1 = std::less&lt;&gt;, typename Compare2 = std::less&lt;&gt;&gt;\nclass PSTMultimap {\n std::multimap&lt;Key, Value, Compare1&gt; m_points;\npublic:\n PSTMultimap(Key keys[], Value values[], int size) ...\n\n class Node {\n ...\n Key m_key;\n Value m_value;\n ...\n };\n\n Node* Build(Node* parent, std::multimap&lt;Key, Value&gt;&amp; points) {\n ...\n std::multimap&lt;Key, Value, Compare2&gt; remainPoints;\n ...\n }\n \n ...\n};\n</code></pre>\n<p>And then let the caller worry about providing the right comparison functions:</p>\n<pre><code>std::string names[] = {&quot;A&quot;, &quot;B&quot;, ...};\nPoint2D&lt;int&gt; points[] = {{15, 7}, {16, 2}, ...};\nint size = ...;\n\ntemplate&lt;typename E&gt;\nstruct Point2DComparatorX {\n bool operator()(const Point2D&lt;E&gt;&amp; l, const Point2D&lt;E&gt;&amp; r) {\n return (l.m_x &lt; r.m_x) || (l.m_x == r.m_x &amp;&amp; l.m_y &lt; r.m_y);\n }\n};\n\nPSTMultimap&lt;Point2D&lt;int&gt;, std::string, std::less&lt;Point2D&gt;, Point2DComparatorX&lt;int&gt;&gt; t(names, points, size);\n</code></pre>\n<h1>Alternative constructors</h1>\n<p>Your constructor requires you to store the keys and values in two arrays. But what if you have the information in a different container? It might make sense to provide a constructor that takes two iterators to key/value <code>std::pair</code>s, like so:</p>\n<pre><code>template&lt;typename Iterator&gt;\nPSTMultimap(const Iterator &amp;begin, const Iterator &amp;end) {\n for (Iterator it = begin; it != end; ++it) {\n m_points[it-&gt;first] = it-&gt;second;\n }\n}\n</code></pre>\n<p>And then use it, for example, like so:</p>\n<pre><code>std::vector&lt;std::pair&lt;Point2D&lt;int&gt;, std::string&gt;&gt; points = {\n {{15, 7}, &quot;A&quot;},\n {{16, 2}, &quot;B&quot;},\n ...\n};\n\nPSTMultimap&lt;...&gt; t(points.begin(), points.end());\n</code></pre>\n<h1>Consider allowing points to be added and removed from an existing PST</h1>\n<p>Just like regular STL contains, it would be nice to be able to <code>insert()</code> and <code>erase()</code> elements. Even better would be to make it look like a regular STL container.</p>\n<h1>Make <code>Build()</code> automatic</h1>\n<p>I understand that you want to be able to print the situation before and after ordering the elements, but in production use, you don't need that, and it is much nicer if your class builds the PST automatically without having to manually call <code>Build()</code>.</p>\n<p>Also, this will remove the need to temporarily store all the elements in a <code>std::multimap&lt;&gt;</code> member variable until <code>Build()</code> is called.</p>\n<h1>Use <code>std::unique_ptr</code> to manage memory</h1>\n<p>Instead of having raw pointer variables and calling <code>new</code> and <code>delete</code> manually, consider using <a href=\"https://en.cppreference.com/w/cpp/memory/unique_ptr\" rel=\"noreferrer\"><code>std::unique_ptr</code></a>. Use this for <code>PSTMultimap</code>'s <code>root</code> and <code>Node</code>'s <code>left</code> and <code>right</code> member variables.</p>\n<h1>Improving efficiency</h1>\n<p>A major issue with your code is that you build a lot of temporary maps, and even do some unnecessary sorting. When building the PST, what you want to do at each recursive step is:</p>\n<ol>\n<li>Get the max element using <code>Compare1</code>, this becomes the root.</li>\n<li>Sort the remaining elements using <code>Compare2</code>.</li>\n<li>Split the remaining elements in two, recurse each half, and add those as children.</li>\n<li>Return the root.</li>\n</ol>\n<p>Consider storing all the elements in a <code>std::vector</code> instead, and for each call to <code>Build()</code>, give it the <code>begin</code> and <code>end</code> position in this vector to use. Then the above steps become more concretely:</p>\n<ol>\n<li>Use <a href=\"https://en.cppreference.com/w/cpp/algorithm/max_element\" rel=\"noreferrer\"><code>std::max_element()</code></a> using <code>Compare1</code> on the given range, then <code>std::swap()</code> it to the start of the range. Alternatively, you could use <a href=\"https://en.cppreference.com/w/cpp/algorithm/partial_sort\" rel=\"noreferrer\"><code>std::partial_sort(begin, begin + 1, end)</code></a>.</li>\n<li>Use <a href=\"https://en.cppreference.com/w/cpp/algorithm/sort\" rel=\"noreferrer\"><code>std::sort()</code></a> from <code>begin + 1</code> to <code>end</code> using <code>Compare2</code>.</li>\n<li>Find the midpoint, and recurse each half (<code>being + 1</code> to <code>mid_iter</code> and <code>mid_iter</code> to <code>end</code>)</li>\n</ol>\n<p>So there's just one vector throughout the whole building process, of which smaller and smaller parts get sorted, without needing to allocate more and more maps. It also avoids full sorts just to get the maximum element.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-29T19:01:58.093", "Id": "487058", "Score": "4", "body": "`h3` (`###`) weight is fairly enough emphasis for section titles (and saves some vertical space). Good c++ reviews from your side otherwise" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-30T00:27:05.827", "Id": "487086", "Score": "0", "body": "I greatly appreciate for your so detail answer! So many valuable suggestions and improvements! The most important I learnt from your answer is the valuable design experience using `C++`! I think I'm still in the kindergarden of `C++`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-30T00:28:09.697", "Id": "487087", "Score": "0", "body": "1. For the naming of private variables within the class, I'll follow your kind suggestion by using `m_`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-30T00:29:30.930", "Id": "487088", "Score": "0", "body": "2. For the useless copy constructor, I'll remove that. In fact another expert also suggest me this. I forgot to remove that overload." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-30T00:32:30.703", "Id": "487089", "Score": "0", "body": "3. For the usage of `const`, I'll do more exercises. In fact, I encountered some `const`-related compiler errors before. I remembered that when I remove the `const` after the function, the errors were solved. I think I should do more study for the `const`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-30T00:37:50.117", "Id": "487090", "Score": "0", "body": "4. using `multiset` or `multimap`? I think I didn't have much opinion. In general, I think the `set` is suitable for no duplicate items, and the `map` is suitable for quick find usage. With my limited understanding of `set` and `map`, it seems the `set` is just a `subset` of the `map`. When equipping with some carefully designed hash functions and comparators, the `map` can be used as a `set`. I think the hash function and the comparators used in a `map` is the most important thing. But I didn't have much practical experiences." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-30T00:41:57.680", "Id": "487091", "Score": "0", "body": "5. Thanks for your suggestion of designing the PST for general purpose. That would be much better. In fact, I didn't have these thoughts when I faced this new problems. This means a lot to me. I should do more practice!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-30T00:45:02.610", "Id": "487092", "Score": "0", "body": "6. For the suggestion of `alternative constructors`, your solution is much smarter than that in my code. I didn't have the practical experience using the iterator for constructor. This is novel for me." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-30T00:47:20.803", "Id": "487093", "Score": "0", "body": "7. For the `insert()` and `erase()` like other `STL` containers, I also want to add these operations. In fact, those operations are described in another note, http://cs.brown.edu/courses/cs252/misc/resources/lectures/pdf/notes18.pdf, where the red-black tree is used for the basic data structure of PST. Currently that is difficult to me." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-30T00:50:08.860", "Id": "487094", "Score": "0", "body": "8. For the automatically `Build` suggestion, yeah, understood. In the second note, http://cs.brown.edu/courses/cs252/misc/resources/lectures/pdf/notes18.pdf, the PST will be constructed similar as a heap and the new elements will be inserted dynamically. This mechanism is more general and productive." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-30T00:56:45.460", "Id": "487095", "Score": "0", "body": "9. For the `std::unique_ptr` suggestion, I'll try that. In fact, I'm not familiar with the new memory management, like the `shared_ptr` or `unique_ptr`. With my limited understanding of these new features, they implemented the strategy like the garbage-collection (GC)? So we don't need to manage the memory. Thanks a lot for your suggestion, but I don't know why I'm always prone to reject to use `*_ptr`, I always want to know when the objects are constructed and when they are destroyed. That's why I always add a `used_count` into the class definition. Despite this, I'll follow your suggestion." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-30T01:02:44.333", "Id": "487096", "Score": "0", "body": "10. Your last valuable suggestion of `improving efficienty` is my initial expectation when I post this question. In fact, I have the same concerns, in the original code, I used the `multiset`. Now I think that is truly unnecessary. With your suggested `vector`, the thing is getting more simpler and more elegant. You are an expert, thanks a lot for your so many valuable suggestions! So many words!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-30T08:24:42.460", "Id": "487110", "Score": "1", "body": "@mining Good luck with improving your class and your C++ skills, I'm glad you find the review helpful! About `set` and `map`: there really is no difference except `map` stores keys and values, whereas `set` only stores keys. As for `unique_ptr`: it is not garbage collected, it uses [RAII](https://en.cppreference.com/w/cpp/language/raii). But `shared_ptr` can be considered garbage collecting, although a simple form using reference counting." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-30T08:49:11.090", "Id": "487111", "Score": "1", "body": "@G.Sliepen, very grateful for your kind suggestions and detail explainations, which is very helpful and valuable! Thank you!" } ], "meta_data": { "CommentCount": "14", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-29T18:41:34.373", "Id": "248631", "ParentId": "248622", "Score": "7" } } ]
{ "AcceptedAnswerId": "248631", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-29T14:19:22.900", "Id": "248622", "Score": "5", "Tags": [ "c++", "stl" ], "Title": "C++ code for Priority Search Tree" }
248622
<p>After not programming in c++ for some time, I decided to write an AVL tree implementation to get back in shape (I wasn't that good anyway. Still an amateur).</p> <h1>Header File</h1> <p><em><strong>bst.hpp</strong></em></p> <pre class="lang-cpp prettyprint-override"><code>#pragma once #include &lt;iostream&gt; #include &lt;utility&gt; namespace bst { template &lt;typename T&gt; class BstNode { public: explicit BstNode(T key, BstNode&lt;T&gt; *parent = nullptr); BstNode(const BstNode&lt;T&gt; &amp;other); BstNode&lt;T&gt; &amp;operator=(BstNode&lt;T&gt; &amp;other); ~BstNode(); BstNode&lt;T&gt; *insert(T key); BstNode&lt;T&gt; *getNode(const T &amp;key); const BstNode&lt;T&gt; *search(const T &amp;key) const; BstNode&lt;T&gt; *findMin(); BstNode&lt;T&gt; *findMax(); BstNode&lt;T&gt; *nextLarger(); void printInOrder() const; int placeInOrder(T array[], int begin) const; int findHeight() const; void deleteChildren(); T key; BstNode&lt;T&gt; *left = nullptr, *right = nullptr, *parent; private: int height = 0; int updateHeight(); template &lt;typename U&gt; friend int getHeight(BstNode&lt;U&gt; *node); template &lt;typename U&gt; friend class BST; template &lt;typename U&gt; friend class AvlTree; }; template &lt;typename T&gt; class BST { public: BST(); explicit BST(T root_key); BST(const BST&lt;T&gt; &amp;other); BST&lt;T&gt; &amp;operator=(const BST&lt;T&gt; &amp;other); ~BST(); virtual BstNode&lt;T&gt; *insert(T key); BstNode&lt;T&gt; *getNode(const T &amp;key); const BstNode&lt;T&gt; *search(const T &amp;key) const; BstNode&lt;T&gt; *minNode(); BstNode&lt;T&gt; *maxNode(); T min(); T max(); virtual int height() const; int placeInOrder(T array[], int begin) const; void printInOrder() const; void deleteNode(BstNode&lt;T&gt; *node); static void deleteSubtree(BstNode&lt;T&gt; *node); protected: BstNode&lt;T&gt; *root; }; template &lt;typename T&gt; class AvlTree : public BST&lt;T&gt; { public: AvlTree(); explicit AvlTree(T key); BstNode&lt;T&gt; *insert(T key); int height() const; private: void rightRotate(BstNode&lt;T&gt; *node); void leftRotate(BstNode&lt;T&gt; *node); void rebalance(BstNode&lt;T&gt; *node); }; template &lt;typename T&gt; int getHeight(BstNode&lt;T&gt; *node) { // if a node is null, we define its height as -1 return node != nullptr ? node-&gt;height : -1; } template &lt;typename T&gt; T max(T a, T b) { return a &gt; b ? a : b; } template &lt;typename T&gt; void swap(T &amp;a, T &amp;b) { T c = a; a = b; b = c; } template &lt;typename T&gt; BstNode&lt;T&gt;::BstNode(T key, BstNode&lt;T&gt; *parent) : key{std::move(key)}, parent{parent} {} template &lt;typename T&gt; BstNode&lt;T&gt;::BstNode(const BstNode&lt;T&gt; &amp;other) : key{other.key}, height{other.height}, parent{nullptr} { if (other.left != nullptr) { left = new BstNode&lt;T&gt;{*(other.left)}; left-&gt;parent = this; } if (other.right != nullptr) { right = new BstNode&lt;T&gt;{*(other.right)}; right-&gt;parent = this; } } template &lt;typename T&gt; BstNode&lt;T&gt; &amp;BstNode&lt;T&gt;::operator=(BstNode&lt;T&gt; &amp;other) { key = other.key; height = other.height; deleteChildren(); if (other.left != nullptr) { left = new BstNode&lt;T&gt;{other.right-&gt;key}; left-&gt;parent = this; } if (other.right != nullptr) { right = new BstNode&lt;T&gt;{*(other.right)}; right-&gt;parent = this; } return *this; } template &lt;typename T&gt; BstNode&lt;T&gt;::~BstNode() { deleteChildren(); if (parent != nullptr) { if (parent-&gt;left == this) parent-&gt;left = nullptr; else parent-&gt;right = nullptr; } } template &lt;typename T&gt; void BstNode&lt;T&gt;::deleteChildren() { if (left != nullptr) { left-&gt;deleteChildren(); delete left; left = nullptr; } if (right != nullptr) { right-&gt;deleteChildren(); delete right; right = nullptr; } } template &lt;typename T&gt; BstNode&lt;T&gt; *BstNode&lt;T&gt;::insert(T key) { if (key &lt; this-&gt;key) { if (left == nullptr) { left = new BstNode&lt;T&gt;{std::move(key), this}; return left; } else return left-&gt;insert(std::move(key)); } else { if (right == nullptr) { right = new BstNode&lt;T&gt;{std::move(key), this}; return right; } else return right-&gt;insert(std::move(key)); } } template &lt;typename T&gt; BstNode&lt;T&gt; *BstNode&lt;T&gt;::getNode(const T &amp;key) { if (key &lt; this-&gt;key) { if (left == nullptr) return nullptr; return left-&gt;getNode(key); } else if (key &gt; this-&gt;key) { if (right == nullptr) return nullptr; return right-&gt;getNode(key); } else // key == this-&gt;key return this; } template &lt;typename T&gt; const BstNode&lt;T&gt; *BstNode&lt;T&gt;::search(const T &amp;key) const { if (key &lt; this-&gt;key) { if (left == nullptr) return nullptr; return left-&gt;search(key); } else if (key &gt; this-&gt;key) { if (right == nullptr) return nullptr; return right-&gt;search(key); } else // key == this-&gt;key return this; } template &lt;typename T&gt; BstNode&lt;T&gt; *BstNode&lt;T&gt;::findMin() { auto *node = this; while (node-&gt;left != nullptr) node = node-&gt;left; return node; } template &lt;typename T&gt; BstNode&lt;T&gt; *BstNode&lt;T&gt;::findMax() { auto *node = this; while (node-&gt;right != nullptr) node = node-&gt;right; return node; } template &lt;typename T&gt; BstNode&lt;T&gt; *BstNode&lt;T&gt;::nextLarger() { if (right != nullptr) return right-&gt;findMin(); auto *node = this; while ((node-&gt;parent != nullptr) &amp;&amp; (node == node-&gt;parent-&gt;right)) node = node-&gt;parent; return node-&gt;parent; } template &lt;typename T&gt; void BstNode&lt;T&gt;::printInOrder() const { if (left != nullptr) left-&gt;printInOrder(); std::cout &lt;&lt; key &lt;&lt; ' '; if (right != nullptr) right-&gt;printInOrder(); } template &lt;typename T&gt; int BstNode&lt;T&gt;::placeInOrder(T array[], int begin) const { if (left != nullptr) begin = left-&gt;placeInOrder(array, begin); array[begin++] = key; if (right != nullptr) begin = right-&gt;placeInOrder(array, begin); return begin; } template &lt;typename T&gt; int BstNode&lt;T&gt;::findHeight() const { int left_height = -1; int right_height = -1; if (left != nullptr) left_height = left-&gt;findHeight(); if (right != nullptr) right_height = right-&gt;findHeight(); return max(left_height, right_height) + 1; } template &lt;typename T&gt; int BstNode&lt;T&gt;::updateHeight() { height = max(getHeight(this-&gt;left), getHeight(this-&gt;right)) + 1; return height; } template &lt;typename T&gt; BST&lt;T&gt;::BST() : root{nullptr} {} template &lt;typename T&gt; BST&lt;T&gt;::BST(T root_key) { root = new BstNode&lt;T&gt;{root_key}; } template &lt;typename T&gt; BST&lt;T&gt;::BST(const BST&lt;T&gt; &amp;other) { root = new BstNode&lt;T&gt;{*(other.root)}; } template &lt;typename T&gt; BST&lt;T&gt; &amp;BST&lt;T&gt;::operator=(const BST&lt;T&gt; &amp;other) { deleteSubtree(root); root = new BstNode&lt;T&gt;{*(other.root)}; return *this; } template &lt;typename T&gt; BST&lt;T&gt;::~BST() { deleteSubtree(root); } template &lt;typename T&gt; void BST&lt;T&gt;::deleteSubtree(BstNode&lt;T&gt; *node) { if (node-&gt;parent != nullptr) { if (node-&gt;parent-&gt;left == node) node-&gt;parent-&gt;left = nullptr; else node-&gt;parent-&gt;right = nullptr; } delete node; } template &lt;typename T&gt; BstNode&lt;T&gt; *BST&lt;T&gt;::insert(T key) { return root-&gt;insert(std::move(key)); } template &lt;typename T&gt; BstNode&lt;T&gt; *BST&lt;T&gt;::getNode(const T &amp;key) { return root-&gt;getNode(key); } template &lt;typename T&gt; const BstNode&lt;T&gt; *BST&lt;T&gt;::search(const T &amp;key) const { return root-&gt;search(key); } template &lt;typename T&gt; BstNode&lt;T&gt; *BST&lt;T&gt;::minNode() { return root-&gt;findMin(); } template &lt;typename T&gt; BstNode&lt;T&gt; *BST&lt;T&gt;::maxNode() { return root-&gt;findMax(); } template &lt;typename T&gt; T BST&lt;T&gt;::min() { return minNode()-&gt;key; } template &lt;typename T&gt; T BST&lt;T&gt;::max() { return maxNode()-&gt;key; } template &lt;typename T&gt; int BST&lt;T&gt;::height() const { return root-&gt;findHeight(); } template &lt;typename T&gt; int BST&lt;T&gt;::placeInOrder(T array[], int begin) const { return root-&gt;placeInOrder(array, begin); } template &lt;typename T&gt; void BST&lt;T&gt;::printInOrder() const { root-&gt;printInOrder(); } template &lt;typename T&gt; void BST&lt;T&gt;::deleteNode(BstNode&lt;T&gt; *node) { BstNode&lt;T&gt; *new_node; if ((node-&gt;left != nullptr) &amp;&amp; (node-&gt;right == nullptr)) new_node = node-&gt;left; else if ((node-&gt;left == nullptr) &amp;&amp; (node-&gt;right != nullptr)) new_node = node-&gt;right; else if ((node-&gt;left == nullptr) &amp;&amp; (node-&gt;right == nullptr)) { deleteSubtree(node); return; } else { new_node = node-&gt;nextLarger(); swap(node-&gt;key, new_node-&gt;key); deleteNode(new_node); return; } new_node-&gt;parent = node-&gt;parent; if (new_node-&gt;parent != nullptr) { if (node-&gt;parent-&gt;left == node) new_node-&gt;parent-&gt;left = new_node; else new_node-&gt;parent-&gt;right = new_node; } else root = new_node; node-&gt;parent = nullptr; node-&gt;left = nullptr; node-&gt;right = nullptr; delete node; } template &lt;typename T&gt; AvlTree&lt;T&gt;::AvlTree() {} template &lt;typename T&gt; AvlTree&lt;T&gt;::AvlTree(T key) : BST&lt;T&gt;{std::move(key)} {} template &lt;typename T&gt; BstNode&lt;T&gt; *AvlTree&lt;T&gt;::insert(T key) { if (this-&gt;root == nullptr) { this-&gt;root = new BstNode&lt;T&gt;{std::move(key)}; return this-&gt;root; } auto *node = this-&gt;root-&gt;insert(std::move(key)); rebalance(node); return node; } template &lt;typename T&gt; void AvlTree&lt;T&gt;::leftRotate(BstNode&lt;T&gt; *node) { auto *temp = node-&gt;right; temp-&gt;parent = node-&gt;parent; if (node-&gt;parent == nullptr) this-&gt;root = temp; else { if (node-&gt;parent-&gt;left == node) node-&gt;parent-&gt;left = temp; else node-&gt;parent-&gt;right = temp; } node-&gt;right = temp-&gt;left; if (node-&gt;right != nullptr) node-&gt;right-&gt;parent = node; temp-&gt;left = node; node-&gt;parent = temp; node-&gt;updateHeight(); temp-&gt;updateHeight(); } template &lt;typename T&gt; void AvlTree&lt;T&gt;::rightRotate(BstNode&lt;T&gt; *node) { auto *temp = node-&gt;left; temp-&gt;parent = node-&gt;parent; if (node-&gt;parent == nullptr) this-&gt;root = temp; else { if (node-&gt;parent-&gt;left == node) node-&gt;parent-&gt;left = temp; else node-&gt;parent-&gt;right = temp; } node-&gt;left = temp-&gt;right; if (node-&gt;left != nullptr) node-&gt;left-&gt;parent = node; temp-&gt;right = node; node-&gt;parent = temp; node-&gt;updateHeight(); temp-&gt;updateHeight(); } template &lt;typename T&gt; void AvlTree&lt;T&gt;::rebalance(BstNode&lt;T&gt; *node) { do { node-&gt;updateHeight(); if (getHeight(node-&gt;left) &gt; getHeight(node-&gt;right) + 1) { if (getHeight(node-&gt;left-&gt;left) &gt;= getHeight(node-&gt;left-&gt;right)) rightRotate(node); else { leftRotate(node-&gt;left); rightRotate(node); } } else if (getHeight(node-&gt;right) &gt; getHeight(node-&gt;left) + 1) { if (getHeight(node-&gt;right-&gt;right) &gt;= getHeight(node-&gt;right-&gt;left)) leftRotate(node); else { rightRotate(node-&gt;right); leftRotate(node); } } node = node-&gt;parent; } while(node != nullptr); } template &lt;typename T&gt; int AvlTree&lt;T&gt;::height() const { return getHeight(this-&gt;root); } } // namespace bst </code></pre> <h1>Unit Tests</h1> <pre class="lang-cpp prettyprint-override"><code>#include &lt;iostream&gt; #include &lt;cassert&gt; #include &quot;bst.hpp&quot; void insertionTest() { auto *node = new bst::BstNode&lt;int&gt;{4}; assert(node-&gt;insert(2) == node-&gt;left); assert(node-&gt;insert(3) == node-&gt;left-&gt;right); assert(node-&gt;insert(1) == node-&gt;left-&gt;left); assert(node-&gt;insert(6) == node-&gt;right); assert(node-&gt;insert(7) == node-&gt;right-&gt;right); assert(node-&gt;insert(5) == node-&gt;right-&gt;left); delete node; } bst::BST&lt;int&gt; makeBst() { auto tree = bst::BST&lt;int&gt;{1}; tree.insert(2); tree.insert(3); tree.insert(4); tree.insert(5); tree.insert(6); tree.insert(7); tree.insert(8); tree.insert(9); return tree; } bst::AvlTree&lt;int&gt; makeAvl() { auto tree = bst::AvlTree&lt;int&gt;{1}; tree.insert(2); tree.insert(3); tree.insert(4); tree.insert(5); tree.insert(6); tree.insert(7); tree.insert(8); tree.insert(9); return tree; } void testHeight(const bst::BST&lt;int&gt; &amp;tree1, const bst::AvlTree&lt;int&gt; &amp;tree2) { assert(tree1.height() == 8); assert(tree2.height() == 3); } void testMin(bst::BST&lt;int&gt; &amp;tree1, bst::AvlTree&lt;int&gt; &amp;tree2) { assert(tree1.min() == 1); assert(tree2.min() == 1); } void testMax(bst::BST&lt;int&gt; &amp;tree1, bst::AvlTree&lt;int&gt; &amp;tree2) { assert(tree1.max() == 9); assert(tree2.max() == 9); } void testSearch(const bst::AvlTree&lt;int&gt; &amp;tree) { assert(tree.search(3)-&gt;key == 3); assert(tree.search(10) == nullptr); } void testCopy(const bst::BST&lt;int&gt; &amp;tree1, const bst::AvlTree&lt;int&gt; &amp;tree2) { auto tree3 = tree1; auto tree4 = tree2; assert(tree1.search(8)-&gt;key == tree3.search(8)-&gt;key); assert(tree1.search(8) != tree3.search(8)); assert(tree2.search(8)-&gt;key == tree4.search(8)-&gt;key); assert(tree2.search(8) != tree4.search(8)); } void testAssignment(const bst::BST&lt;int&gt; &amp;tree1, const bst::AvlTree&lt;int&gt; &amp;tree2) { auto tree3 = bst::BST&lt;int&gt;{0}; auto tree4 = bst::AvlTree&lt;int&gt;{0}; tree3 = tree1; tree4 = tree2; assert(tree1.search(8)-&gt;key == tree3.search(8)-&gt;key); assert(tree1.search(8) != tree3.search(8)); assert(tree2.search(8)-&gt;key == tree4.search(8)-&gt;key); assert(tree2.search(8) != tree4.search(8)); } void testInOrderTraversal(const bst::AvlTree&lt;int&gt; &amp;tree) { int a[9]; tree.placeInOrder(a, 0); for (int i = 0; i &lt; 9; ++i) assert(a[i] == i + 1); } void testNextLarger(bst::AvlTree&lt;int&gt; &amp;tree) { assert(tree.getNode(4)-&gt;nextLarger()-&gt;key == 5); } void testDelete(bst::BST&lt;int&gt; tree1, bst::AvlTree&lt;int&gt; tree2) { tree1.deleteNode(tree1.getNode(4)); assert(tree1.search(4) == nullptr); assert(tree1.search(1)-&gt;key == 1); tree2.deleteNode(tree2.getNode(4)); assert(tree2.search(4) == nullptr); assert(tree2.search(1)-&gt;key == 1); } void testBundle() { insertionTest(); auto tree1 = makeBst(); auto tree2 = makeAvl(); testHeight(tree1, tree2); testMin(tree1, tree2); testMax(tree1, tree2); testSearch(tree2); testCopy(tree1, tree2); testAssignment(tree1, tree2); testInOrderTraversal(tree2); testNextLarger(tree2); testDelete(tree1, tree2); } int main() { testBundle(); } </code></pre> <h1>Example Use Case</h1> <pre class="lang-cpp prettyprint-override"><code>#include &lt;iostream&gt; #include &lt;random&gt; #include &lt;chrono&gt; #include &quot;bst.hpp&quot; static std::mt19937 random_engine( std::chrono::high_resolution_clock::now().time_since_epoch().count()); void fillRandomly(int array[], int begin, int end) { std::uniform_int_distribution&lt;int&gt; range(0, 99); for (int i = begin; i &lt;= end; ++i) array[i] = range(random_engine); } void avlSort(int array[], int begin, int end) { bst::AvlTree&lt;int&gt; tree; for (int i = begin; i &lt;= end; ++i) tree.insert(array[i]); tree.placeInOrder(array, begin); } void printArray(int array[], int begin, int end) { for (int i = begin; i &lt;= end; ++i) std::cout &lt;&lt; array[i] &lt;&lt; ' '; } int main() { int array[100]; fillRandomly(array, 0, 99); printArray(array, 0, 99); std::cout &lt;&lt; &quot;\n\n&quot;; avlSort(array, 0, 99); printArray(array, 0, 99); } </code></pre> <p>Notes:</p> <ol> <li><p>I didn't use smart pointers for two reasons; First, I wanted to practice using raw pointers. Second, since I'm using parent pointers, I had to use <code>std::shared_ptr</code> for smart pointers which adds some overhead. (I heard it's possible to implement AVL trees without parent pointers, but I can't even imagine how deleting a node is possible without using parent pointers)</p> </li> <li><p><code>BST::min</code>, <code>BST::max</code> and <code>BstNode::nextLarger</code> should be <code>const</code>, but I couldn't find an elegant way to define them that way while not messing up <code>BST::deleteNode</code>.</p> </li> </ol> <p>Any suggestion for additional functionality and improving readability (e.g. using modern features of c++) are welcome.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-30T11:46:30.080", "Id": "487124", "Score": "0", "body": "For future reference, my ```deleteNode``` function has some problems. My tests weren't rigorous enough to catch the errors." } ]
[ { "body": "<h1>About inheritance</h1>\n<p>I would advice against using (public) inheritance of <code>BST</code> for <code>AvlTree</code>. Consider that with your code, the following is valid:</p>\n<pre><code>bst::AvlTree&lt;int&gt; tree{...};\nbst::BST *base_ptr = &amp;tree;\nbase_ptr-&gt;deleteNode(base_ptr-&gt;getNode(42));\n</code></pre>\n<p>Without any compiler error or warning, I deleted a node from the AVL tree without it being rebalanced. This might cause the AVL tree to lose its balance, and even worse, it might cause subsequent operations on <code>tree</code> to fail if they depend on the properties being held.</p>\n<p>You could make more functions <code>virtual</code>, but it's easy to forget something here. It is better if you make it so you can't access the base class at all.</p>\n<p>One way to achieve that is to use private inheritance, and selectively bring features from the base class into the public API of the derived class, like so:</p>\n<pre><code>template&lt;typename T&gt;\nclass AvlTree: private BST&lt;T&gt;\n{\npublic:\n ...\n using BST::getNode;\n using BST::findMin;\n ...\n};\n</code></pre>\n<p>Or use composition instead of inheritance:</p>\n<pre><code>template&lt;typename T&gt;\nclass AvlTree&gt;\n{\n BST&lt;T&gt; bst;\npublic:\n ...\n BstNode&lt;T&gt; *getNode(const T &amp;key) {return bst.getNode(key);}\n BstNode&lt;T&gt; *findMin(const T &amp;key) {return bst.findMin(key);}\n ...\n};\n</code></pre>\n<p>Once you get rid of the base class, it doesn't make sense to have <code>virtual</code> functions anymore. It also gets rid of the overhead of a vtable.</p>\n<p>Alternatively just don't use <code>BST</code> at all inside <code>AvlTree</code>, just rely on <code>BstNode</code> and its member functions. But here also, you want to prevent the ability to do the following:</p>\n<pre><code>bst::AvlTree&lt;int&gt; tree{...};\nbst::BstNode *node = tree.getNode(...);\nnode-&gt;insert(42);\n</code></pre>\n<p>You can do that by making the member functions of <code>BstNode</code> private, and using a <code>friend</code> declaration to allow <code>AvlTree</code> access to the private members of <code>BstNode</code>. But that's also more complicated than necessary. Personally, I would get rid of the generic <code>BstNode</code> and <code>BST</code>, and just have a <code>class AvlTree</code> which inside declares a <code>class Node</code>, like so:</p>\n<pre><code>template &lt;typename T&gt;\nclass AvlTree {\n class Node {\n T key;\n int height;\n Node *left{};\n Node *right{};\n Node *parent{};\n };\n\n Node *root;\n\npublic:\n ...\n};\n</code></pre>\n<p>And instead of having member functions like <code>search()</code> return a pointer to a node, return a pointer to the key itself. This will ensure the implementation of your nodes is completely hidden.</p>\n<h1>Use the same name for <code>getNode()</code> and <code>search()</code></h1>\n<p>These two functions do exactly the same thing. The only difference is that <code>search()</code> operates on a <code>const</code> instance of a tree, and returns a <code>const</code> pointer to a node. You can just use the same name for those functions, the compiler is able to distinguish between the two cases. You can keep your code exactly as it is, just replace <code>getNode</code> with <code>search</code>, or the other way around as you like.</p>\n<h1>Avoid writing specialized convenience functions</h1>\n<p>I see functions like <code>printInOrder()</code> and <code>placeInOrder()</code>. While that might be convenient, they are quite specialized. What if instead of printing to <code>std::cout</code> I want to write to a file? Or instead of placing the items into an array, I want it in a <code>std::vector</code>? It is better to add something <em>generic</em> that makes it easy to do those things. For example, add an iterator class, and add <code>begin()</code> and <code>end()</code> member functions to <code>AvlTree</code>. This will allow you to then do the following:</p>\n<pre><code>bst:AvlTree&lt;int&gt; tree{...};\n\n// Print all elements of the tree\nfor (auto key: tree)\n std::cout &lt;&lt; key &lt;&lt; ' ';\n\n// Copy the elements into a vector\nstd::vector&lt;int&gt; vec(tree.begin(), tree.end());\n</code></pre>\n<p>Once you have iterators for your class, there is a whole slew of STL algorithms that can operator on your AVL tree, without you having to make custom implementations. This also brings me to:</p>\n<h1>Try to emulate other STL containers</h1>\n<p>Have a good look at other STL containers such as <a href=\"https://en.cppreference.com/w/cpp/container/map\" rel=\"noreferrer\"><code>std::map</code></a>, and try to mimic their interface as much as possible. Not only try to use the same names as STL for similar functions (for example, <code>find()</code> instead of <code>search()</code> or <code>getNode()</code>), but you can also find a lot of functions that you are missing, that might be very useful to have in a tree, like <code>size()</code>, <code>empty()</code>, <code>erase()</code>, and so on. If you keep the API the same as STL containers, there is less cognitive overhead, and makes it easier to swap an STL container for your AVL tree, and vice versa.</p>\n<p>You'll also notice that a <code>std::map</code> has a key and a value type. Your <code>AvlTree</code> is more like a <a href=\"https://en.cppreference.com/w/cpp/container/set\" rel=\"noreferrer\"><code>std::set</code></a>. Both have their uses. Maybe you could make an <code>AvlMap</code> and an <code>AvlSet</code>?</p>\n<p>Finally, the ordered STL containers allow you to specify a custom comparison operator. This is nice to have if the type of keys you want to store do not have a proper ordering of their own, or if I want to sort them in a different way than their natural order (consider for example wanting to store <code>std::string</code>s, but use case-insensitive comparison to order them).</p>\n<h1>Make use of standard library functions instead of reinventing them</h1>\n<p>You implemented <code>bst::max()</code> and <code>bst::swap()</code>, but those functions are already part of <a href=\"https://en.cppreference.com/w/cpp/algorithm\" rel=\"noreferrer\"><code>&lt;algorithm&gt;</code></a>. Why not use the ones that come with the standard library?</p>\n<h1>Making more functions <code>const</code></h1>\n<p>To ensure <code>BST::min()</code> and <code>BST::max()</code> and can be <code>const</code>, just make variants of <code>findMin()</code> and <code>findMax()</code> that are <code>const</code> (they can overload the non-const versions). For <code>nextLarger()</code>, you would indeed need to make two versions of it, one regular and the other <code>const</code>. Then again, <code>nextLarger()</code> is only used inside <code>deleteNode()</code>, so does it really need to be a separate, public function? I would make it private, and then it doesn't matter it doesn't have a <code>const</code> version. If you do want to keep it public, then you have to make a <code>const</code> and non-<code>const</code> version of <code>nextLarger</code>.</p>\n<p>Note that you don't have to two full implementations of each function that you want to have a <code>const</code> and non-<code>const</code> version for. You can do something like:</p>\n<pre><code>const Node *AvlTree::Node::nextLarger() const {\n // full implementation here\n ...\n}\n\nNode *AvlTree::Node::nextLarger() {\n return const_cast&lt;Node *&gt;(const_cast&lt;const Node *&gt;(this)-&gt;nextLarger());\n}\n</code></pre>\n<p>Even though it might look a bit shady, the above is valid C++: since the original objects were not <code>const</code>, const-casting them to <code>const</code> and then back again is allowed.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-29T17:19:58.270", "Id": "248628", "ParentId": "248623", "Score": "6" } } ]
{ "AcceptedAnswerId": "248628", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-29T14:45:16.813", "Id": "248623", "Score": "7", "Tags": [ "c++", "object-oriented", "binary-search-tree" ], "Title": "AVL Tree in C++" }
248623
<p>I am writing an Express.js middleware function in a TypeScript NodeJS project that uses a function from a third-party module to perform a small workload. When writing unit tests, I want to mock this third-party function. In the following code, the <code>decodeFunction</code> parameter is what I used as a seam to inject the dependency (or, when writing unit tests, a mock). Here it is:</p> <pre><code>/** * Returns a middleware function that performs authentication using a JSON Web * Token (JWT). * * @remarks * This middleware is intended to be used during test mode only and should not * be considered secure. * * @param - decodeFunction - A function that decodes a JWT. * * @returns An Express-compatible middleware function that authenticates a JWT. */ export function getJwtAuthMiddleware( decodeFunction: DecodeFunction = decode ): (req: Request, res: Response, next: NextFunction) =&gt; Promise&lt;void&gt; { return async (req, res, next) =&gt; { const { authorization } = req.headers || &quot;&quot;; if (!authorization) { next(new HttpException(401, &quot;An authorization header is required.&quot;)); return; } const [authType, token] = authorization.trim().split(&quot; &quot;); if (authType !== &quot;Bearer&quot;) { next(new HttpException(401, &quot;The specified authentication scheme is not supported.&quot;)); return; } try { const result = await decodeFunction(token, config.testModeJwtSecret, false, &quot;HS256&quot;); req.user = { id: result.sub }; next(); } catch (error) { next(new HttpException(401, &quot;Authorization is required.&quot;, error)); } }; } </code></pre> <p>This seems to work just fine, but I'm relatively inexperienced with TypeScript/JavaScript and would love to hear from the community here as to whether there are alternative approaches I should consider or best practices I've ignored.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-29T18:24:43.467", "Id": "248630", "Score": "2", "Tags": [ "javascript", "unit-testing", "node.js", "typescript", "express.js" ], "Title": "Express compatible JSON Web Token authentication middleware" }
248630
<h3>Description</h3> <p>I've created simple SBT plugin which enables creating Helm Charts</p> <p>The main reasons:</p> <ul> <li>in Helm it is impossible to 'fetch' external files: <a href="https://github.com/helm/helm/issues/3276" rel="nofollow noreferrer">https://github.com/helm/helm/issues/3276</a> which is very cumbersome when dealing with applications that are packaged multiple times with different configurations.</li> <li>want to package my application from one tool: SBT (I'm using sbt-native-packager to create the Docker image)</li> <li>didn't find already existing SBT plugin that enables Helm Charts creation</li> </ul> <p>The description and usage can be found in the <a href="https://github.com/kiemlicz/shelm" rel="nofollow noreferrer">Github repository README.md</a></p> <p>The main plugin source: <a href="https://github.com/kiemlicz/shelm/blob/master/src/main/scala/com/shelm/HelmPlugin.scala" rel="nofollow noreferrer">https://github.com/kiemlicz/shelm/blob/master/src/main/scala/com/shelm/HelmPlugin.scala</a></p> <pre class="lang-scala prettyprint-override"><code>package com.shelm import java.io.FileReader import java.security.SecureRandom import java.util.concurrent.TimeUnit import com.shelm.ChartPackagingSettings.{ChartYaml, ValuesYaml} import com.shelm.exception.HelmCommandException import io.circe.syntax._ import io.circe.{yaml, Json} import sbt.Keys._ import sbt._ import scala.annotation.tailrec import scala.concurrent.duration.{FiniteDuration, SECONDS} import scala.util.control.NonFatal import scala.util.{Failure, Success, Try} object HelmPlugin extends AutoPlugin { override def trigger = noTrigger object autoImport { val Helm: Configuration = config(&quot;helm&quot;) // format: off lazy val chartSettings = settingKey[Seq[ChartPackagingSettings]](&quot;All per-Chart settings&quot;) lazy val prepare = taskKey[Seq[File]](&quot;Download Chart if not present locally, copy all includes into Chart directory, return Chart directory&quot;) lazy val lint = taskKey[Seq[File]](&quot;Lint Helm Chart&quot;) lazy val packagesBin = taskKey[Seq[File]](&quot;Create Helm Charts&quot;) // format: on lazy val baseHelmSettings: Seq[Setting[_]] = Seq( chartSettings := Seq.empty[ChartPackagingSettings], prepare := { val log = streams.value.log chartSettings.value.map { settings =&gt; val tempChartDir = ChartDownloader.download(settings.chartLocation, target.value, log) val chartYaml = readChart(tempChartDir / ChartYaml) val updatedChartYaml = settings.chartUpdate(chartYaml) settings.includeFiles.foreach { case (src, d) =&gt; val dst = tempChartDir / d if (src.isDirectory) IO.copyDirectory(src, dst, overwrite = true) else IO.copyFile(src, dst) } settings.yamlsToMerge.foreach { case (overrides, onto) =&gt; val dst = tempChartDir / onto if (dst.exists()) IO.write( dst, resultOrThrow(for { overrides &lt;- yaml.parser.parse(new FileReader(overrides)) onto &lt;- yaml.parser.parse(new FileReader(dst)) } yield yaml.printer.print(onto.deepMerge(overrides))), ) else IO.copyFile(overrides, dst) } val valuesFile = tempChartDir / ValuesYaml val valuesJson = if (valuesFile.exists()) yaml.parser.parse(new FileReader(valuesFile)).toOption else None val overrides = mergeOverrides(settings.valueOverrides(valuesJson)) overrides.foreach { valuesOverride =&gt; IO.write( valuesFile, if (valuesFile.exists()) resultOrThrow( yaml.parser .parse(new FileReader(valuesFile)) .map(onto =&gt; yaml.printer.print(onto.deepMerge(valuesOverride))) ) else yaml.printer.print(valuesOverride), ) } IO.write(tempChartDir / ChartYaml, yaml.printer.print(updatedChartYaml.asJson)) cleanFiles ++= Seq(tempChartDir) tempChartDir } }, lint := { val log = streams.value.log prepare.value.zip(chartSettings.value).map { case (chartDir, settings) =&gt; lintChart(chartDir, settings.fatalLint, log) } }, packagesBin := { lint.value.zip(chartSettings.value).map { case (linted, settings) =&gt; val chartYaml = readChart(linted / ChartYaml) buildChart( linted, chartYaml.name, chartYaml.version, settings.destination, settings.dependencyUpdate, streams.value.log, ) } }, ) } val random = new SecureRandom import autoImport._ private[this] def lintChart(chartDir: File, fatalLint: Boolean, log: Logger): File = { log.info(&quot;Linting Helm Package&quot;) val cmd = s&quot;helm lint $chartDir&quot; val logger = new BufferingProcessLogger try { startProcess(cmd, logger) } catch { case NonFatal(e) if fatalLint =&gt; throw new HelmCommandException(s&quot;$cmd has failed: ${e.getMessage}, full output:\n${logger.buf.toString}&quot;, e) case NonFatal(e) =&gt; log.error(s&quot;$cmd has failed: ${e.getMessage}, full output:\n${logger.buf.toString}continuing&quot;) } chartDir } private[this] def buildChart( chartDir: File, chartName: String, chartVersion: String, targetDir: File, dependencyUpdate: Boolean, log: Logger, ): File = { val opts = s&quot;${if (dependencyUpdate) &quot; -u&quot; else &quot;&quot;}&quot; val dest = s&quot; -d $targetDir&quot; val cmd = s&quot;helm package$opts$dest $chartDir&quot; val output = targetDir / s&quot;$chartName-$chartVersion.tgz&quot; log.info(s&quot;Creating Helm Package: $cmd&quot;) retrying(cmd, log) output } /** * Retry given command * That method exists only due to: https://github.com/helm/helm/issues/2258 * @param cmd * @param sbtLogger * @param n number of tries * @return */ private[shelm] def retrying(cmd: String, sbtLogger: Logger, n: Int = 3): Try[Unit] = { val logger = new BufferingProcessLogger() val sleepTime = FiniteDuration(1, SECONDS) val backOff = 2 @tailrec def go(n: Int, result: Try[Unit], sleep: FiniteDuration): Try[Unit] = result match { case s @ Success(_) =&gt; sbtLogger.info(s&quot;Helm command success, output:\n${logger.buf.toString}&quot;) s case Failure(e) if n &gt; 0 =&gt; sbtLogger.warn(s&quot;Couldn't perform: $cmd, failed with: ${e.getMessage}, retrying in: $sleep&quot;) Thread.sleep(sleep.toMillis) val nextSleep = (sleep * backOff) + FiniteDuration(random.nextInt() % 1000, TimeUnit.MILLISECONDS) go(n - 1, Try(startProcess(cmd, logger)), nextSleep) case Failure(exception) =&gt; val msg = s&quot;Couldn't perform: $cmd, retries limit reached.\nProcess stderr and stdout:\n${logger.buf.toString}&quot; sbtLogger.err(msg) throw new HelmCommandException(msg, exception) } go(n, Try(startProcess(cmd, logger)), sleepTime) } private[shelm] def startProcess(cmd: String, log: BufferingProcessLogger): Unit = sys.process.Process(command = cmd) ! log match { case 0 =&gt; () case exitCode =&gt; sys.error(s&quot;The command: $cmd, failed with: $exitCode&quot;) } private[this] def readChart(file: File) = resultOrThrow( yaml.parser.parse(new FileReader(file)).flatMap(_.as[Chart]) ) private[this] def mergeOverrides(overrides: Seq[Json]): Option[Json] = { val merged = overrides.foldLeft(Json.Null)(_.deepMerge(_)) if (overrides.isEmpty) None else Some(merged) } override lazy val projectSettings: Seq[Setting[_]] = inConfig(Helm)(baseHelmSettings) override def projectConfigurations: Seq[Configuration] = Seq(Helm) } </code></pre> <p>SBT plugins tests: <a href="https://github.com/kiemlicz/shelm/tree/master/src/sbt-test/shelm" rel="nofollow noreferrer">https://github.com/kiemlicz/shelm/tree/master/src/sbt-test/shelm</a></p> <h3>Questions</h3> <p>First and foremost: I would gladly receive any input and thoughts about this project</p> <p>Open question: what do you think about plugin rationale?</p> Technical questions <ol> <li>Do you think that <code>task</code>s and <code>settings</code> are properly split?</li> <li>When running plugin in parallel for multiple projects (the SBT parallelizes tasks by default) sometimes I encountered: <a href="https://github.com/helm/helm/issues/2258#issuecomment-306498450" rel="nofollow noreferrer">https://github.com/helm/helm/issues/2258#issuecomment-306498450</a>. The linked ticket somehow suggests it is an issue with Helm. Yet I've <a href="https://github.com/kiemlicz/shelm/blob/master/src/main/scala/com/shelm/HelmPlugin.scala#L147" rel="nofollow noreferrer">created a workaround</a> which simply retries the <code>helm</code> commands. I'm unsure if it is indeed issue with Helm or my code wrongly spawning the <code>helm</code> process</li> <li>I've created dedicated SBT <code>Configuration</code> for my tasks, is it created and used properly?</li> </ol> <pre class="lang-scala prettyprint-override"><code>object autoImport { val Helm: Configuration = config(&quot;helm&quot;) ... } </code></pre> <ol start="4"> <li>Should I implement dedicated <code>clean</code> task or appending any artifacts to <code>cleanFiles</code> is sufficient?</li> </ol> <pre class="lang-scala prettyprint-override"><code>cleanFiles ++= Seq(tempChartDir) </code></pre> <p>Thank you</p> <p>EDIT: I've provided the missing main plugin source as a snippet</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-29T21:12:10.213", "Id": "487071", "Score": "1", "body": "For anyone in the close vote queue, the code is now included, that is not a reason to down vote or vote to close." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-29T21:20:58.393", "Id": "487072", "Score": "0", "body": "What is a helm chart supposed to convey?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-30T14:55:13.830", "Id": "487145", "Score": "0", "body": "K8s deployment yamls mainly. Helm provides nice versioning system, 'standarized' deplyoment procedures, templating engine. I consider Helm Chart as a complementary artifact to Docker images" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-31T06:00:25.253", "Id": "487187", "Score": "0", "body": "Why in the code presented don't I find what it is good for?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-31T08:35:25.440", "Id": "487200", "Score": "0", "body": "Isn't the: https://github.com/kiemlicz/shelm#example what you are after? Or Should I elaborate more here in this post?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-31T09:57:30.967", "Id": "487210", "Score": "0", "body": "You can address whoever you want in a comment using @whoever: only the post/question owner gets notified by default. I, for one, review code presented *here*. And I commented I didn't find a raison d'être in the code presented above: I don't believe in separate documentation." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-29T19:09:39.530", "Id": "248632", "Score": "3", "Tags": [ "scala", "plugin" ], "Title": "SBT Helm plugin" }
248632
<p>i have made simple python login nothing impressive but i have the feeling that i could have done it differently.</p> <p>I saw some people saying that i should use text files but i tried and i didn't quite work out with iteration .</p> <p>How would you approach it using a text file ?</p> <pre><code>print('WELCOME USER , Please Enter Your Login Information') class Login: def __init__(self): self.data = {} self.username = input('Username : ') self.password = input('Password : ') def login_check(self): key1, value1 = self.username , self.password if key1 in self.data and value1 == self.data[key1]: print(f'\nWelcome Back {self.username}') else: print(&quot;\nWrong Username Or Password&quot;) ask = input(&quot;\nAre You A New User? Y/N : &quot;) if ask == &quot;y&quot;: self.new_user() if ask == 'n': check_username = input(&quot;\nUsername : &quot;) check_password = input(&quot;Password : &quot;) key, value = check_username , check_password if key in self.data and value == self.data[key]: print(f&quot;\nWELCOME {check_username}!!&quot;) def new_user(self): new_username = input('\nPlease Enter A New Username : ') new_password = input('Please Enter A New Password : ') self.data[new_username] = new_password check_username = input(&quot;\nUsername : &quot;) check_password = input(&quot;Password : &quot;) key , value = check_username , check_password if key in self.data and value == self.data[key] : print(f&quot;\nWELCOME {check_username}!!&quot;) else: self.login_check() main = Login() main.login_check() </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-30T01:19:50.327", "Id": "487098", "Score": "0", "body": "What is the program supposed to do? Where will the user names and passwords be stored? Even if this script exists purely for educational purposes, at least declare some kind of a basic plan (it's ok to adjust the plan as you learn more): for example, \"Passwords will be in a text file, a JSON file, a database, whatever. Script will support 3 actions: add user, delete user, or login\". Some clarity about the goal will help you and any people willing to review your code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-30T07:05:47.687", "Id": "487108", "Score": "0", "body": "@FMc , this isn't the full project . This is actually just a test one that is why it has a few holes like that it doesn't save permanently . But that is why i am asking how you would approach this with a text file. Sorry for the misunderstanding." } ]
[ { "body": "<p>First of all I recommend you to separate your class to two classes. Each class must have only one responsibility. Now your class make two different things - store and validate passwords, and working with user input/output.</p>\n<p>Let's try to fix it and separate your code to two classes:</p>\n<pre><code>class LoginStore:\n def __init__(self):\n self.data = {}\n\n def add_user(self, login, password):\n if login in self.data:\n raise AssertionError('User already exists')\n\n self.data[login] = password\n\n def check_user(self, login, password):\n if not login in self.data:\n return False\n\n if self.data[login] != password:\n return False\n\n return True\n\n\nclass LoginManager:\n def __init__(self):\n self.store = LoginStore()\n\n def _ask_input_and_password(self):\n username = input(&quot;username: &quot;)\n password = input(&quot;password: &quot;)\n return username, password\n\n def login_check(self):\n username, password = self._ask_input_and_password()\n\n while not self.store.check_user(username, password):\n print(&quot;Wrong username or password&quot;)\n if input(&quot;Are you a new user?&quot;) == &quot;y&quot;:\n print(&quot;Starting registration process&quot;)\n username, password = self._ask_input_and_password()\n self.store.add_user(username, password)\n print(&quot;Done. Try to login.&quot;)\n username, password = self._ask_input_and_password()\n\nmanager = LoginManager()\nmanager.login_check()\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-29T20:39:08.323", "Id": "487066", "Score": "0", "body": "is that a prefered methode or is that a personal chose. I previously made a guessing game and i heard none say anything. But if it is i will gladly implement it into to my other projects. THANKS FOR THE ADVIES." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-29T20:56:19.500", "Id": "487069", "Score": "1", "body": "@bliboy, it is one of five principles intended to make a code more understandable en.wikipedia.org/wiki/Single-responsibility_principle" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-29T22:23:01.807", "Id": "487075", "Score": "0", "body": "i get it now. It would be a bad design to couple two things that change for different reasons at different times and should, therefore, be in separate classes or modules. THANKS FOR THAT , YOU ARE A BIGGG HELP!!" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-29T20:24:33.717", "Id": "248635", "ParentId": "248633", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-29T19:59:12.723", "Id": "248633", "Score": "1", "Tags": [ "python", "beginner", "file" ], "Title": "Simple Python Login" }
248633
<p>This is exercise 2.3.24. from the book <em>Computer Science An Interdisciplinary Approach</em> by Sedgewick &amp; Wayne:</p> <p>Modify Beckett to print the Gray code.</p> <p>Beckett refers to the following program within the text:</p> <pre><code>public class Beckett { public static void moves(int n, boolean enter) { if (n == 0) return; moves(n-1, true); if (enter) System.out.println(&quot;enter &quot; + n); else System.out.println(&quot;exit &quot; + n); moves(n-1, false); } public static void main(String[] args) { int n = Integer.parseInt(args[0]); moves(n, true); } } </code></pre> <p>As stated in the text:</p> <blockquote> <p>The playwright Samuel Beckett wrote a play called Quad that had the following property: starting with an empty stage, characters enter and exit one at a time so that each subset of characters on the stage appears exactly once.</p> </blockquote> <p>The above program tries to simulate the above-explained stage instructions. Here is my attempt at turning Beckett into a program that produces Gray code:</p> <pre><code>public class exercise2_3_24 { public static String swap(String s, String t, int n) { n = n-1; return s.substring(0,n) + t + s.substring(n+1); } public static void beckett(String s, int n) { if (n == 0) return; beckett(s, n-1); System.out.println(swap(s, &quot;1&quot;, n)); s = swap(s, &quot;1&quot;, n); beckett(s, n-1); } public static void graycodes(int n) { String s = &quot;&quot;; for (int i = 0; i &lt; n; i++) s += &quot;0&quot;; System.out.println(s); beckett(s, n); } public static void main(String[] args) { int n = Integer.parseInt(args[0]); graycodes(n); } } </code></pre> <p>Is there any way that I can improve my program?</p> <p>Thanks for your attention.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-30T21:15:45.383", "Id": "487162", "Score": "0", "body": "This _does not_ produce Gray codes. It produces something completely different." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-30T21:55:28.593", "Id": "487163", "Score": "0", "body": "@vnp On page 273 of the aforementioned book, the author considers sequences like 00 01 10 11 (for n=2 for instance) Gray code and has a picture of these saying Gray code representations. I actually like to learn more about Gray code and its applications. I appreciate your guidance. Thank you. :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-30T22:00:20.693", "Id": "487164", "Score": "0", "body": "By definition of Gray code, successive numbers differ in exactly one bit. When I run your program (with `n = 4`), I see that the generated sequence starts with `0000, 1000, 0100`. The second and third numbers differ in _two_ positions. And there are more violations." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-30T22:39:16.823", "Id": "487166", "Score": "0", "body": "Thank you very much. I see now. These are not in accordance with the stage instructions. My code only produces all possible combinations but with the wrong order. I try to fix my code and edit my post. :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-31T08:59:37.247", "Id": "487203", "Score": "0", "body": "@vnp I corrected my code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-31T09:02:44.820", "Id": "487204", "Score": "2", "body": "Please do not update the code in your question after receiving answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*. Having multiple versions of the same program in the same question is very confusing and the original code can't be removed or it would possibly invalidate the answers. Please, check your code is correct next time *before* posting." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-31T09:04:30.190", "Id": "487205", "Score": "0", "body": "@Mast I wasn't aware of that. Thank you very much for informing me. I'll do my best." } ]
[ { "body": "<p>I have some suggestions for your code.</p>\n<h2>Always add curly braces to <code>loop</code> &amp; <code>if</code></h2>\n<p>In my opinion, it's a bad practice to have a block of code not surrounded by curly braces; I saw so many bugs in my career related to that, if you forget to add the braces when adding code, you break the logic / semantic of the code.</p>\n<h2>Use <code>java.lang.StringBuilder</code> to concatenate String in a loop.</h2>\n<p>It's generally more efficient to use the builder in a loop, since the compiler is unable to make it efficient in a loop; since it creates a new String each iteration. There are lots of good explanations with more details on the subject.</p>\n<p><strong>before</strong></p>\n<pre class=\"lang-java prettyprint-override\"><code>String s = &quot;&quot;;\nfor (int i = 0; i &lt; n; i++) {\n s += &quot;0&quot;;\n}\n</code></pre>\n<p><strong>after</strong></p>\n<pre class=\"lang-java prettyprint-override\"><code>StringBuilder s = new StringBuilder();\nfor (int i = 0; i &lt; n; i++) {\n s.append(&quot;0&quot;);\n}\n</code></pre>\n<h2>Don’t use a loop when you want to repeat a string of x elements</h2>\n<p>The API that java give you offer a method to repeat the character x times; you can use <a href=\"https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/String.html#repeat(int)\" rel=\"nofollow noreferrer\"><code>java.lang.String#repeat</code></a> (Java 11+)</p>\n<p><strong>before</strong></p>\n<pre class=\"lang-java prettyprint-override\"><code>StringBuilder s = new StringBuilder();\nfor (int i = 0; i &lt; n; i++) {\n s.append(&quot;0&quot;);\n}\n</code></pre>\n<p><strong>after</strong></p>\n<pre class=\"lang-java prettyprint-override\"><code>String s = &quot;0&quot;.repeat(n);\n</code></pre>\n<h2>Extract the expression to variables when used multiple times.</h2>\n<p>In your code, you can extract the similar expressions into variables; this will make the code shorter and easier to read.</p>\n<p><strong>before</strong></p>\n<pre class=\"lang-java prettyprint-override\"><code>beckett(s, n - 1);\nSystem.out.println(swap(s, &quot;1&quot;, n));\ns = swap(s, &quot;1&quot;, n);\nbeckett(s, n - 1);\n</code></pre>\n<p><strong>after</strong></p>\n<pre class=\"lang-java prettyprint-override\"><code>int previousNumber = n - 1;\nbeckett(s, previousNumber);\nSystem.out.println(swap(s, &quot;1&quot;, n));\ns = swap(s, &quot;1&quot;, n);\nbeckett(s, previousNumber);\n</code></pre>\n<h2>Uses the <a href=\"https://docs.oracle.com/javase/tutorial/java/nutsandbolts/opsummary.html\" rel=\"nofollow noreferrer\">increment and decrement operators</a> when possible</h2>\n<p>Try to use the <code>x++</code> / <code>++x</code>, <code>x--</code> or <code>--x</code> instead of <code>x = x + 1</code> since they are more widely used and make the code easier to read.</p>\n<p><strong>before</strong></p>\n<pre class=\"lang-java prettyprint-override\"><code>n = n - 1;\n</code></pre>\n<p><strong>after</strong></p>\n<pre class=\"lang-java prettyprint-override\"><code>n--;\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-30T12:42:53.503", "Id": "487127", "Score": "0", "body": "Thank you very much for your time. :)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-30T12:20:22.850", "Id": "248658", "ParentId": "248642", "Score": "3" } } ]
{ "AcceptedAnswerId": "248658", "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-30T00:35:19.853", "Id": "248642", "Score": "4", "Tags": [ "java", "beginner", "recursion" ], "Title": "Printing Gray code through modifying Samuel Beckett's stage instructions" }
248642
<p>I'm trying to add students to Google Classrooms ('Courses') from a Google Sheet with code below (function AddStudents).</p> <p>It's very slow and, if I do too many, it exceeds allowed execution time. Is there anything that I can do to speed it up?</p> <pre><code>function AddStudent(argStudent, argCourseCode) { Classroom.Courses.Students.create({ userId: argStudent, }, argCourseCode); } function AddStudents() { var ss = SpreadsheetApp.getActiveSpreadsheet(); var shtStudents = ss.getSheetByName('Students'); var rngStudentCourses = shtStudents.getRange(2,6,645,2); var arrStudentCourses = rngStudentCourses.getValues(); for (var i = 0; i &lt; arrStudentCourses.length; i++) { AddStudent(arrStudentCourses[i][0], arrStudentCourses[i][1]); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-30T20:37:43.917", "Id": "487160", "Score": "0", "body": "the `Classroom.Courses.Students.create` is most likely what is slowing it down as the rest of the code seems as efficient as it can be. If it is this https://developers.google.com/classroom/reference/rest/v1/courses.students/create, then maybe there is a way to make an POST request asynchronously (without waiting for result)" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-30T00:47:41.500", "Id": "248643", "Score": "2", "Tags": [ "google-apps-script" ], "Title": "Google Script is slow. Using arrays. Anything else I'm missing?" }
248643
<p>The following source code is a solution to the <a href="https://en.wikipedia.org/wiki/Marching_squares" rel="nofollow noreferrer">Marching Square</a> problem.</p> <p>The explanation of using random numbers in ambiguous cases <a href="https://stackoverflow.com/q/62868990/159072">can be found here</a>.</p> <pre><code>using System; using System.Collections.Generic; using System.Drawing; using System.Text; namespace G__Marching_Sqaure { public static class StaticRandomNumber { private static Random rnd = new Random(); public static int GetRandom(int min, int max) { return rnd.Next(min, max); } } public class Point { public int X { get; set; } public int Y { get; set; } public Point(int x, int y) { X = x; Y = y; } } public class Line { public Point Start { get; set; } public Point End { get; set; } public Line(int x1, int y1, int x2, int y2) { Start = new Point(x1, y1); End = new Point(x2, y2); } public Line(Point start, Point end) { Start = start; End = end; } } public class LinesRectangle { public Graphics Graphics { get; set; } public Color Color { get; set; } public Pen Pen { get; set; } public int Thickness { get; set; } public LinesRectangle() { Color = Color.Blue; Thickness = 2; Pen = new Pen(Color, Thickness); } public void DrawLine(Line line) { Graphics.DrawLine(Pen, line.Start.X, line.Start.Y, line.End.X, line.End.Y); } } public partial class DrawingForm : System.Windows.Forms.Form { public DrawingForm() { InitializeComponent(); } public int [,] Data { get; set; } public void Print(int[,] data, int xn, int yn) { for (int j = 0; j &lt; yn; j++) { for (int i = 0; i &lt; xn; i++) { Console.Write(data[j, i] + &quot;, &quot;); } Console.WriteLine(); } } public int[,] ToBinary(int[,] data, int xn, int yn) { for (int j = 0; j &lt; yn; j++) { for (int i = 0; i &lt; xn; i++) { if (data[j, i] &gt; 1) { data[j, i] = 0; } else { data[j, i] = 1; } } } int xWidth = data.GetLength(1); int yHeight = data.GetLength(0); for (int j = 0; j &lt; yHeight; j++) { for (int i = 0; i &lt; xWidth; i++) { Console.Write(data[j, i] + &quot;, &quot;); } Console.WriteLine(); } return data; } public Point GetMidPoint(Point thisp, Point other) { int xHalf = (thisp.X + other.X) / 2; int yHalf = (thisp.Y + other.Y) / 2; return new Point(xHalf, yHalf); } private IEnumerable&lt;Line&gt; GetLines(int casevalue, int[] xVector, int[] yVector, int i, int j) { List&lt;Line&gt; linesList = new List&lt;Line&gt;(); Point topLeft = new Point(xVector[i], yVector[j]); Point topRight = new Point(xVector[i+1], yVector[j]); Point bottomLeft = new Point(xVector[i], yVector[j+1]); Point bottomRight= new Point(xVector[i+1], yVector[j+1]); if (casevalue == 0) {/*do nothing*/ } if (casevalue == 15) {/*do nothing*/ } if ((casevalue == 1) || (casevalue == 14)) { Point start = GetMidPoint(topLeft, bottomLeft); Point end = GetMidPoint(bottomLeft, bottomRight); } /*2==13*/ if ((casevalue == 2) || (casevalue == 13)) { Point start = GetMidPoint(bottomLeft, bottomRight); Point end = GetMidPoint(topRight, bottomRight); } /*3==12*/ if ((casevalue == 3) || (casevalue == 12)) { Point start = GetMidPoint(topLeft, bottomLeft); Point end = GetMidPoint(topRight, bottomRight); } /*4==11*/ if ((casevalue == 4) || (casevalue == 11)) { Point start = GetMidPoint(topLeft, topRight); Point end = GetMidPoint(topRight, bottomRight); } /*6==9*/ if ((casevalue == 6) || (casevalue == 9)) { Point start = GetMidPoint(topLeft, topRight); Point end = GetMidPoint(bottomLeft, bottomRight); } /*7==8*/ if ((casevalue == 7) || (casevalue == 8)) { Point start = GetMidPoint(topLeft, topRight); Point end = GetMidPoint(bottomLeft, bottomRight); } if ((casevalue == 5) || (casevalue == 10)) { int caseValueTemp = 0; int randVal = StaticRandomNumber.GetRandom(1,11); if (randVal % 2 == 0) { caseValueTemp = 5; } else { caseValueTemp = 10; } /*ambiguous case*/ if (caseValueTemp == 5) { Point start1 = GetMidPoint(topLeft, bottomLeft); Point end1 = GetMidPoint(topLeft, topRight); Line line1 = new Line(start1, end1); Point start2 = GetMidPoint(bottomLeft, bottomRight); Point end2 = GetMidPoint(topRight, bottomRight); Line line2 = new Line(start2, end2); linesList.Add(line1); linesList.Add(line2); } if (caseValueTemp == 10) { Point start1 = GetMidPoint(topLeft, topRight); Point end1 = GetMidPoint(topRight, bottomRight); Line line1 = new Line(start1, end1); Point start2 = GetMidPoint(topLeft, bottomLeft); Point end2 = GetMidPoint(bottomLeft, bottomRight); Line line2 = new Line(start2, end2); linesList.Add(line1); linesList.Add(line2); } } return linesList; } public List&lt;Line&gt; marching_square(int[] xVector, int[] yVector, int[,] imageData, int isovalue) { List&lt;Line&gt; linesList = new List&lt;Line&gt;(); int dataWidth = imageData.GetLength(1); int dataHeight = imageData.GetLength(0); if (dataWidth == xVector.Length &amp;&amp; dataHeight == yVector.Length) { imageData = ToBinary(imageData, dataWidth, dataHeight); for (int j = 0; j &lt; dataHeight - 1; j++) { for (int i = 0; i &lt; dataWidth - 1; i++) { StringBuilder sb = new StringBuilder(); sb.Append(imageData[j, i]); sb.Append(imageData[j, i + 1]); sb.Append(imageData[j + 1, i + 1]); sb.Append(imageData[j + 1, i]); int casevalue = Convert.ToInt32(sb.ToString(), 2); IEnumerable&lt;Line&gt; list = GetLines(casevalue, xVector, yVector, i, j); linesList.AddRange(list); } } } else { throw new Exception(&quot;dimension mismatch!&quot;); } return linesList; } private void MainForm_Paint(object sender, System.Windows.Forms.PaintEventArgs e) { int[,] data = new int[,] { { 2,1,2,1,2,2,2 }, { 1,2,1,2,1,2,2 }, { 2,1,2,1,2,2,2 }, { 1,2,1,2,1,2,2 }, { 2,1,2,1,2,2,2 } }; int width = data.GetLength(1); int height = data.GetLength(0); int[] x = new int[] {0, 100, 200, 300, 400, 500, 600}; int[] y = new int[] {0, 100, 200, 300, 400}; int xMaxCoord = x[6]; int yMaxCoord = y[4]; int[,] adjacencyMatrix = new int[xMaxCoord, yMaxCoord]; List&lt;Line&gt; collection = marching_square(x, y, data, 0); Graphics g = this.CreateGraphics(); LinesRectangle rect = new LinesRectangle(); rect.Graphics = g; foreach (var item in collection) { rect.DrawLine(item); } } } } </code></pre> <p>Can someone kindly review this?</p> <hr /> <p><strong>N.B.</strong> Kindly, only focus on the algorithm, not class-arrangement.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-09-02T21:34:58.263", "Id": "487596", "Score": "1", "body": "TL;DR but few tips: I suggest to use `switch-case` statement instead of `if-if-if`. Also you may use [`yield return`](https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/yield) to build an `IEnumerable<T>` instead of creating `List` inside. Also `Console.WriteLine` in Winforms app looks odd, for debuggong purpose try `Debug.WriteLine` instead. Also looks like `GetLines()` do nothing for all cases except `5` and `10`." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-30T03:16:36.070", "Id": "248645", "Score": "2", "Tags": [ "c#", "algorithm" ], "Title": "Marching Square algorithm" }
248645
<p><strong>Brief introduction:</strong> so the point of the question is that the author doesn't really talk about good or bad code quality and I really wanted some feedback to have a grasp of how the code for others to read should look like. I mean, for the very first solution of the task I would check different parameters manually just to finish it and the function looked really bulky, so I took some time to make it neat.</p> <p><strong>Task:</strong> the dictionary value represent a chess board, for example {'1h': 'bking', '6c': 'wqueen', '2g': 'bbishop', '5h': 'bqueen', '3e': 'wking'}. Write a function named that takes a dictionary argument and returns True or False depending on if the board is valid.</p> <p>A valid board will have exactly one black king and exactly one white king. Each player can only have at most 16 pieces, at most 8 pawns, and all pieces must be on a valid space from '1a' to '8h'; that is, a piece can’t be on space '9z'. The piece names begin with either a 'w' or 'b' to represent white or black, followed by 'pawn', 'knight', 'bishop', 'rook', 'queen', or 'king'. This function should detect when a bug has resulted in an improper chess board.</p> <p><strong>My solution:</strong></p> <pre><code>def chessboardCheck(board): piecesDict={'pawn':8,'knight':2,'bishop':2,'rook':2,'queen':1,'king':1} #to count pieces on the board if list(board.values()).count('wking')!=1 or list(board.values()).count('bking')!=1: #kings check print('The board is invalid: kings requirement not met.') return False for piece in board.values(): if piece[0] not in 'wb': #piece color print('The board is invalid: improper color reference.') return False elif piece[1:] not in piecesDict.keys(): #piece type print('The board is invalid: improper piece reference.') return False elif list(board.values()).count(piece) &gt; piecesDict.get(piece[1:]): #pieces count print('The board is invalid: improper pieces count.') return False for cell in board: #axis correctness if cell[0] not in '12345678' or cell[1] not in 'abcdefgh': print('The board is invalid: improper cell reference.') return False print('All checks are clear: the board is valid.') return True </code></pre> <p>This is the least lines I could come up with, but if there are more shortcuts to take, please do not hesitate to point! Also I would like to hear opinions on introducing variables: I tried to avoid them wherever I knew how, but maybe it's not always the way to go? Thanks!</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-30T08:57:10.877", "Id": "487112", "Score": "1", "body": "(The are more restrictions on the count of each type of piece, placement of bishops, number of kings in check.)" } ]
[ { "body": "<p>As you may know already, your validation rules are both incomplete and too strict. For example, a black bishop must be on a black square, and there can be more-than-expected numbers of the pieces after a pawn is advanced and promoted (usually, but not always, to a queen). I'll ignore those issues and focus on the code.</p>\n<p>Get the so-called magic strings and numbers out of the code and into named\nconstants and/or data structures. Here's a draft of some constants that might\nbe handy for your task. As you add more validation checks, you might need to\naugment or adjust these.</p>\n<pre><code>import sys\nfrom collections import namedtuple\n\nBLACK = 'b'\nWHITE = 'w'\n\nKING = 'king'\nQUEEN = 'queen'\nROOK = 'rook'\nBISHOP = 'bishop'\nKNIGHT = 'knight'\nPAWN = 'pawn'\n\nCOLORS = {BLACK, WHITE}\nPIECES = {KING, QUEEN, ROOK, BISHOP, KNIGHT, PAWN}\n\nRANKS = set('12345678')\nCOLUMNS = set('abcdefgh')\n\nVALID_COUNTS = {\n PAWN: range(0, 9),\n KNIGHT: range(0, 3),\n BISHOP: range(0, 3),\n ROOK: range(0, 3),\n QUEEN: range(0, 2),\n KNIGHT: range(1, 2),\n}\n</code></pre>\n<p>Set up a simple data structure to facilitate testing and debugging\nas you write the script. For example, we have the board you gave us\nand an invalid board I added.</p>\n<pre><code>INPUT_BOARDS = {\n 'orig': {\n '1h': 'bking',\n '6c': 'wqueen',\n '2g': 'bbishop',\n '5h': 'bqueen',\n '3e': 'wking',\n },\n 'bad1': {\n '9h': 'bking',\n '9x': 'wking',\n },\n}\n</code></pre>\n<p>The input format for a board is not convenient for validation because it\nglues together rank-plus-column and color-plus-piece. Do parsing first, validation\nsecond. There are various ways to arrange the parsing, but an easy, low-tech\nway is with a <a href=\"https://docs.python.org/3/library/collections.html#collections.namedtuple\" rel=\"nofollow noreferrer\">namedtuple</a> -- an immutable container that behaves like a tuple\nbut also allows one to access the attributes via their names.\nBy parsing the input board immediately, you can simplify the rest of the code.</p>\n<p>The validation function should take and return data (e.g. the first\nerror or, even better, all errors). It should not print.\nPrint only in the simple, outer-shell of the program (e.g. a <code>main()</code> function), not it\nits more complex, algorithmic center (where you are doing validation).</p>\n<pre><code>ParsedCell = namedtuple('ParsedCell', 'cell color_piece rank column color piece')\n\ndef main(args):\n board = parse_input_board(INPUT_BOARDS[args[0]])\n errors = check_board(board)\n if errors:\n for e in errors:\n print(e)\n else:\n print('OK')\n\ndef parse_input_board(input_board):\n return tuple(\n ParsedCell(\n cell,\n color_piece,\n cell[0:1], # A safe technique even if cell is an empty string.\n cell[1:],\n color_piece[0:1],\n color_piece[1:],\n )\n for cell, color_piece in input_board.items()\n )\n</code></pre>\n<p>Now sitting on a more solid foundation, the program's validation\ncode becomes (1) simpler to write and (2) easier to read\nbecause it is more declarative or self-documenting.</p>\n<pre><code>def check_board(board):\n errors = []\n for pcell in board:\n if pcell.rank not in RANKS:\n msg = emsg('Invalid rank', pcell.cell)\n errors.append(msg)\n\n if pcell.color not in COLORS:\n msg = emsg('Invalid color', pcell.cell)\n errors.append(msg)\n\n # Etc.\n\n return errors\n\ndef emsg(msg, item):\n return f'{msg}: {item}'\n\nif __name__ == '__main__':\n main(sys.argv[1:])\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-31T09:20:46.397", "Id": "487206", "Score": "0", "body": "aha, so if i get it correctly, the main point is to arrange an efficient data structure, then break a function down into smaller ones and at the end make the one bringing it all together. this helps figuring out the fundamental approach to a task, thanks!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-30T22:47:45.280", "Id": "248672", "ParentId": "248648", "Score": "1" } } ]
{ "AcceptedAnswerId": "248672", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-30T08:30:01.143", "Id": "248648", "Score": "3", "Tags": [ "python", "performance", "beginner" ], "Title": "Automate the Boring Stuff – Chess Dictionary Validator – Optimal Solution" }
248648
<p>I have the following Ruby method.</p> <pre><code>def get_status(creds) client = create_client(creds) status = client.account_status client.close_session status end </code></pre> <p>Usually I optimize this kind of code by using <code>tap</code> or <code>yield_self</code>. I have come up with a way to use these, but it doesn't seem like the nicest way to optimize it.</p> <pre><code>def get_status(creds) create_client(creds).yeild_self do |client| [client, client.account_status] end.yield_self do |client, status| client.close_session status end end </code></pre> <p>Is my new solution better than the original solution?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-30T11:20:14.743", "Id": "487120", "Score": "2", "body": "Define _better_ and _optimization_ please. Your review request lacks context." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-30T11:51:35.093", "Id": "487125", "Score": "0", "body": "[I did encourage you to read the guide](https://stackoverflow.com/questions/63656026/how-to-optimize-ruby-method#comment112565788_63656026), and not to post it as-is. Should I have been more clear?" } ]
[ { "body": "<p>First of all I also agree with the questions asked that you should define first why you want to optimize this method? With 4 lines of code I think this method is still readable and also your suggested refactoring would more obfuscate this method.</p>\n<p>Anyway, here are some suggestions to improve the readability a little bit.</p>\n<p>This is just a small refactoring but I think it makes it more clear that you create a 'session' and makes it more reusable. Basically it is just extracting a <code>with_session</code> method.</p>\n<pre class=\"lang-rb prettyprint-override\"><code>def get_status(creds)\n with_session(creds) do |session|\n session.account_status\n end\nend\n\ndef with_session(creds)\n client = create_client(creds)\n result = yield(client)\n client.close_session\n result\nend\n</code></pre>\n<p>Now the next step could be to adapt the client class (or extract a session class) and move this method in there instead.</p>\n<pre class=\"lang-rb prettyprint-override\"><code>class Session\n def initialize(credentials)\n @credentials = credentials\n end\n\n def execute\n client = create_client(credentials)\n result = yield(client)\n client.close_session\n result\n end\n\n private\n\n attr_reader :credentials\nend\n\ndef get_status(creds)\n Session.new(creds).execute do |session|\n session.account_status\n end\nend\n</code></pre>\n<p>In the end your method did not change much but giving it proper names, splitting concerns and moving it to the right place improved in my opinion the code.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-30T15:09:14.633", "Id": "248660", "ParentId": "248653", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-30T10:43:06.693", "Id": "248653", "Score": "-2", "Tags": [ "ruby" ], "Title": "Getting account status from a client" }
248653
<p>I'm new to react and am building a basic react app and have just built a basic area where navigation links render on a page but wonder whether my current start could be optimised - for example, I wonder whether an area like this:</p> <pre><code>render() { return ( &lt;Root navLinks={this.state.navLinks}&gt;&lt;/Root&gt; ); } </code></pre> <p>Could be changed to something like this:</p> <pre><code>render() { return ( &lt;Root&gt; &lt;NavLinks navLinks={this.state.navLinks} /&gt; &lt;/Root&gt; ); } </code></pre> <p>And I wonder about other aspects of the app such as do I need an App.js file or index.js file and could have one rather than the other?</p> <p>Any quick basic beginner advice would be much appreciated. The code can be better found in this <a href="https://stackblitz.com/edit/react-1dhizf?file=src%2FApp.js" rel="nofollow noreferrer">Stackblitz</a> demo or below:</p> <p>App.js:</p> <pre><code>import React, {Component} from &quot;react&quot;; import {navLinks} from &quot;./components/nav-links&quot;; import Root from &quot;./components/Root&quot;; export default class App extends Component { constructor() { super(); this.state = { navLinks: navLinks } } render() { return ( &lt;Root navLinks={this.state.navLinks}&gt;&lt;/Root&gt; ); } } </code></pre> <p>index.js:</p> <pre><code>import React from 'react'; import ReactDOM from 'react-dom'; import App from './App'; ReactDOM.render( &lt;App /&gt;, document.getElementById('root') ); </code></pre> <p>/components/Root.js:</p> <pre><code>import React from &quot;react&quot;; import NavMenu from &quot;./nav-menu&quot;; import BodyCode from &quot;./body-code&quot;; export default class Root extends React.Component { render() { return ( &lt;div id=&quot;container&quot;&gt; &lt;div id=&quot;header&quot;&gt; &lt;NavMenu navLinks={this.props.navLinks} /&gt; &lt;/div&gt; &lt;div id=&quot;body&quot;&gt; &lt;BodyCode /&gt; &lt;/div&gt; &lt;/div&gt; ) } } </code></pre> <p>/components/body-code.js:</p> <pre><code>import React from &quot;react&quot;; export default class bodyCode extends React.Component { constructor(props) { super(props); this.state = {isToggleOn: true}; // boolean for event listener alternative // This binding is necessary to make `this` work in the callback this.handleClick = this.handleClick.bind(this); } // bind is saying make the ‘this’ keyword bind(this), where the 2nd ‘this’ is the ‘this’ of the constructor handleClick() { this.setState(state =&gt; ({ isToggleOn: !state.isToggleOn // sets state to the opposite of whatever it is })); } render() { return ( &lt;div&gt; &lt;p&gt;some body text&lt;/p&gt; &lt;button onClick={this.handleClick}&gt; {this.state.isToggleOn ? 'ON' : 'OFF'} &lt;/button&gt; &lt;/div&gt; ) } } </code></pre> <p>/components/nav-links.js:</p> <pre><code>export const navLinks = [ { name: &quot;home&quot;, href: &quot;/&quot; }, { name: &quot;subs&quot;, href: &quot;/subs&quot; } ]; </code></pre> <p>/components/nav-menu.js:</p> <pre><code>import React from &quot;react&quot;; export default class navBar extends React.Component { render() { return ( this.props.navLinks.map((link) =&gt; &lt;a href={link.href} key = {link.href} &gt; {link.name} &lt;/a&gt;) ) } } </code></pre>
[]
[ { "body": "<h1>Questions</h1>\n<blockquote>\n<p>Should <code>Root</code> take props or wrap children components?</p>\n</blockquote>\n<pre><code>&lt;Root navLinks={this.state.navLinks}&gt;&lt;/Root&gt;\n</code></pre>\n<p>vs</p>\n<pre><code>&lt;Root&gt;\n &lt;NavLinks navLinks={this.state.navLinks} /&gt;\n&lt;/Root&gt;\n</code></pre>\n<p>I think this primarily comes down to the purpose of <code>Root</code>. If it is a general purpose wrapper container component, then the latter pattern makes sense. I.E. it is providing the layout but no actual UI, this works well. If on the other hand it isn't very generalizable, i.e. it is more single purpose, then passing it props is preferred. I understand this doesn't sound like an answer, but like many things in javascript, there's no clear, hard line between them and this could also simply come down to personal preference/opinion.</p>\n<blockquote>\n<p>Do I need an App.js file or index.js file and could have one rather than the other?</p>\n</blockquote>\n<p>Again, these both exist by convention, but you could easily merge the two if you so desired. The distinction basically comes down to separation of concerns. <code>index.js</code> is primarily concerned with rendering the application into the DOM whereas <code>App.js</code> is primarily concerned with being the root application container. This is typically where redux stores &amp; providers, react contexts &amp; providers (<em>well, all &quot;providers&quot; in general</em>), root routers/navigation, theming, etc, etc... would/could reside and provide functionality to the app.</p>\n<h1>Code Review</h1>\n<p>App.js</p>\n<ul>\n<li>For such simple components (no state updates or no state, no lifecycle functions, etc..) it is recommended to instead use functional components</li>\n<li>There is no compelling reason to store the static link data in react state, just pass it directly to props</li>\n<li><code>navLinks</code> isn't a component so it <em>probably</em> shouldn't be stored in that directory, better suited for a utility directory or similar</li>\n<li><code>Root</code> doesn't wrap any children components so it can be self-closed</li>\n</ul>\n<p>Suggestion</p>\n<pre><code>import React from &quot;react&quot;;\nimport { navLinks } from &quot;./components/nav-links&quot;;\nimport Root from &quot;./components/Root&quot;;\n\nexport const App = () =&gt; &lt;Root navLinks={navLinks} /&gt;;\n</code></pre>\n<p>/components/Root.js</p>\n<ul>\n<li>Many of the same comments as for <code>App.js</code></li>\n<li>If the element <code>id</code>s are <em>actually</em> used (CSS, testing) then keep them, otherwise they just clutter the JSX</li>\n<li><code>BodyCode</code> is already wrapped in a div, so the div here is extraneous and helps increase clutter in the DOM</li>\n</ul>\n<p>Suggestion</p>\n<pre><code>import React from &quot;react&quot;;\nimport NavMenu from &quot;./nav-menu&quot;;\nimport BodyCode from &quot;./body-code&quot;;\n\nexport const Root = ({ navLinks }) =&gt; (\n &lt;div&gt;\n &lt;div&gt;\n &lt;NavMenu navLinks={navLinks} /&gt;\n &lt;/div&gt;\n &lt;BodyCode /&gt;\n &lt;/div&gt;\n);\n</code></pre>\n<p>/components/body-code.js</p>\n<ul>\n<li>By convention react component names are PascalCased</li>\n<li><code>handleClick</code> <em>can</em> be defined as an arrow function, which would make binding <code>this</code> to it in the constructor unnecessary</li>\n<li>Great job on using a functional state update to toggle the <code>isToggleOn</code> state value</li>\n<li>While not a necessity, the constructor can be removed and state defined as a class property</li>\n<li>Also not a necessity, this component is still simple enough and doesn't utilize any lifecycle functions that it is also a good candidate for conversion to functional component</li>\n</ul>\n<p>Class-based suggestion</p>\n<pre><code>import React, { Component } from &quot;react&quot;;\n\nexport class BodyCode extends Component {\n state = {\n isToggleOn: true,\n };\n\n handleClick = () =&gt; this.setState(\n prevState =&gt; ({ isToggleOn: !prevState.isToggleOn })\n );\n\n render() {\n return (\n &lt;div&gt;\n &lt;p&gt;some body text&lt;/p&gt;\n &lt;button onClick={this.handleClick}&gt;\n {this.state.isToggleOn ? 'ON' : 'OFF'}\n &lt;/button&gt;\n &lt;/div&gt;\n )\n }\n}\n</code></pre>\n<p>Functional component suggestion</p>\n<pre><code>import React, { useState } from &quot;react&quot;;\n\nexport const BodyCode = () =&gt; {\n const [isToggleOn, setIsToggleOn] = useState(true);\n\n const handleClick = () =&gt; setIsToggleOn(on =&gt; !on);\n\n return (\n &lt;div&gt;\n &lt;p&gt;some body text&lt;/p&gt;\n &lt;button onClick={handleClick}&gt;\n {isToggleOn ? 'ON' : 'OFF'}\n &lt;/button&gt;\n &lt;/div&gt;\n );\n};\n</code></pre>\n<p>/components/nav-menu.js</p>\n<ul>\n<li>Should follow react component naming convention</li>\n<li>Simple and should probably be converted to functional component</li>\n</ul>\n<p>Suggestion</p>\n<pre><code>import React from &quot;react&quot;;\n\nexport const NavBar = ({ navLinks }) =&gt; navLinks.map(link =&gt; (\n &lt;a key={link.href} href={link.href}&gt;\n {link.name}\n &lt;/a&gt;\n));\n</code></pre>\n<h1>Other Suggestions</h1>\n<p>Use a routing/navigation solution versus using anchor (<code>&lt;a /&gt;</code>) tags as these <em><strong>actually reload the app</strong></em>. These typically provide all the functionality of links and navigating around your app by manipulating the browser's history stack but won't reload the page between navigations.</p>\n<p><a href=\"https://reactrouter.com/web/guides/quick-start\" rel=\"nofollow noreferrer\">react-router/react-router-dom</a> is a common routing solution. The idea being you define <code>Route</code>s, wrapped in a <code>Router</code>/<code>Switch</code>, to render each &quot;page&quot; of your app, and instead of anchor tags a <code>Link</code> is used to go to a specified path.</p>\n<p>A sample router in <code>BodyCode</code></p>\n<pre><code>import { BrowserRouter as Router, Route } from 'react-router-dom';\n\n...\n\n&lt;div&gt;\n &lt;p&gt;some body text&lt;/p&gt;\n &lt;button onClick={this.handleClick}&gt;\n {isToggleOn ? 'ON' : 'OFF'}\n &lt;/button&gt;\n &lt;Router&gt;\n &lt;Route path=&quot;/subs&quot; component={Subs} /&gt;\n &lt;Route path=&quot;/&quot; component={Home} /&gt;\n &lt;/Router&gt;\n&lt;/div&gt;\n</code></pre>\n<p>NavMenu</p>\n<pre><code>import { Link } from 'react-router-dom';\n\n...\n\nnavLinks.map(link =&gt; (\n &lt;Link key={link.href} to={link.href}&gt;\n {link.name}\n &lt;/Link&gt;\n))\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-09-01T19:39:00.957", "Id": "487455", "Score": "1", "body": "wow, thank you so much! excellent and VERY helpful response. I think a key takeaway as a beginner is knowing when to use functional vs class components as you seem logically correct. And using arrow functions for brevity seems like another nice touch. Thank you very much :)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-09-01T07:37:33.513", "Id": "248754", "ParentId": "248657", "Score": "3" } } ]
{ "AcceptedAnswerId": "248754", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-30T12:07:41.080", "Id": "248657", "Score": "4", "Tags": [ "react.js" ], "Title": "Basic Start of a React App" }
248657
<p><strong>Assessment Question:</strong> Print an array of size n*n, with border as 1's and rest of the element as 0's.</p> <p><strong>Sample Input:</strong> 5</p> <p><strong>Sample Output:</strong></p> <pre><code>[[1 1 1 1 1] [1 0 0 0 1] [1 0 0 0 1] [1 0 0 0 1] [1 1 1 1 1]] </code></pre> <p>Here is my solution:</p> <pre><code>import numpy as np n = int(input(&quot;Enter a number:&quot;)) np_box = np.zeros([n, n], dtype='int') np_box[:, 0] = np_box[:, -1] = np_box[0] = np_box[-1] = 1 print(np_box) </code></pre> <p>Can this code be still optimised (using numpy, considering space and time complexity)?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-31T00:05:25.177", "Id": "487174", "Score": "0", "body": "Because printing is involved, the problem cannot be large scale. And you've delegated the work to numpy. In light of those things, why is memory/speed optimization an issue here at all?" } ]
[ { "body": "<p>Have you alread checked out np.pad?</p>\n<pre><code>import numpy as np\nn = int(input(&quot;Enter a number:&quot;))\nnp_box = np.pad(np.zeros((n-1,n-1)), 1, constant_values=1)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-09-07T22:34:43.767", "Id": "249059", "ParentId": "248659", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-30T12:30:41.560", "Id": "248659", "Score": "1", "Tags": [ "python", "numpy" ], "Title": "Print a array of size n*n, with borders as 1's and fill rest of element with 0's" }
248659
<p>I built a quite simple webpage to display a random quote from an array of quotes.</p> <p>I would love to have some feedback on the JS, CSS, and HTML, for example, feedback about best practices, maintainability, readability, accessibility, semantic markup, performance, or anything you can spot that could be improved.</p> <p>This is it:</p> <pre class="lang-html prettyprint-override"><code>&lt;!DOCTYPE html&gt; &lt;html lang=&quot;en&quot;&gt; &lt;head&gt; &lt;meta charset=&quot;UTF-8&quot; /&gt; &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot; /&gt; &lt;title&gt;Quotes to Live By&lt;/title&gt; &lt;link href=&quot;https://fonts.googleapis.com/css2?family=Montserrat:wght@700;900&amp;display=swap&quot; rel=&quot;stylesheet&quot; /&gt; &lt;style&gt; body { margin: 0; background-color: hsl(24, 100%, 50%); font-family: &quot;Montserrat&quot;, sans-serif; min-height: 100vh; text-align: center; display: flex; flex-direction: column; align-items: center; justify-content: center; } figure { margin: 2rem 0; display: flex; justify-content: center; flex-direction: column; flex: 1; cursor: pointer; } blockquote { margin: 0 auto 2rem; font-weight: 900; font-size: clamp(2rem, 8vw, 4rem); color: white; max-width: min(1400px, 90%); } figcaption { font-weight: 700; color: hsl(0, 0%, 20%); font-size: clamp(1rem, 4vw, 2rem); } figcaption::after, figcaption::before { content: &quot;〰&quot;; margin: 0.5rem; } footer { font-size: 0.85rem; padding: 1rem; color: hsl(0, 0%, 20%); text-transform: uppercase; } footer a { color: inherit; text-decoration: none; padding: 0.5rem; } footer a:hover { text-decoration: underline wavy currentColor; } /* loader https://loading.io/css/ */ .lds-ripple { display: inline-block; position: relative; width: 80px; height: 80px; } .lds-ripple div { position: absolute; border: 4px solid #fff; opacity: 1; border-radius: 50%; animation: lds-ripple 1s cubic-bezier(0, 0.2, 0.8, 1) infinite; } .lds-ripple div:nth-child(2) { animation-delay: -0.5s; } @keyframes lds-ripple { 0% { top: 36px; left: 36px; width: 0; height: 0; opacity: 1; } 100% { top: 0px; left: 0px; width: 72px; height: 72px; opacity: 0; } } /* end loader */ &lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;figure&gt; &lt;div id=&quot;loader&quot; class=&quot;lds-ripple&quot;&gt; &lt;div&gt;&lt;/div&gt; &lt;div&gt;&lt;/div&gt; &lt;/div&gt; &lt;/figure&gt; &lt;footer&gt; &lt;a href=&quot;https://github.com/MauricioRobayo/quotes-to-live-by&quot; &gt;Source code&lt;/a &gt; &lt;/footer&gt; &lt;script&gt; (function () { function createElement(type, textContent) { const el = document.createElement(type); el.textContent = textContent; return el; } function createQuoteElement({ quote, author = &quot;&quot;, cite = &quot;&quot; }) { const blockquote = createElement(&quot;blockquote&quot;, quote); if (cite.trim()) { blockquote.setAttribute(&quot;cite&quot;, cite); } return blockquote } async function getQuotes() { const SESSION_STORAGE_KEY = &quot;quotes&quot;; const sessionStorageQuotes = sessionStorage.getItem( SESSION_STORAGE_KEY ); if (sessionStorageQuotes) { return JSON.parse(sessionStorageQuotes); } const response = await fetch( &quot;https://raw.githubusercontent.com/MauricioRobayo/quotes-to-live-by/master/quotes-to-live-by.json&quot; ); if (!response.ok) { throw new Error( `Error fetching quotes: ${response.status} ${response.statusText}` ); } const quotes = await response.json(); sessionStorage.setItem(SESSION_STORAGE_KEY, JSON.stringify(quotes)); return quotes; } function shuffle(quotes) { return quotes.sort(() =&gt; Math.random() - 0.5); } function render(container, ...children) { container.innerHTML = &quot;&quot;; container.append(...children); } function renderQuote(container, quote) { const blockquote = createQuoteElement(quote) if (quote.author.trim()) { render(container, blockquote, createElement(&quot;figcaption&quot;, quote.author)); } else { render(container, blockquote); } } function renderError(container, error) { render(container, createElement(&quot;div&quot;, error)); } function loadQuote(container) { getQuotes() .then((quotes) =&gt; { renderQuote(container, shuffle(quotes)[0]); }) .catch((error) =&gt; { renderError(container, error); }); } const container = document.querySelector(&quot;figure&quot;); loadQuote(container); container.addEventListener(&quot;click&quot;, function() { loadQuote(container) }); })(); &lt;/script&gt; &lt;/body&gt; &lt;/html&gt; <span class="math-container">```</span> </code></pre>
[]
[ { "body": "<p>This naive shuffle function is biased.</p>\n<pre><code>function shuffle(quotes) {\n return quotes.sort(() =&gt; Math.random() - 0.5);\n}\n</code></pre>\n<p>There's an interesting account of a real-life example of the problem <a href=\"https://www.robweir.com/blog/2010/02/microsoft-random-browser-ballot.html\" rel=\"nofollow noreferrer\">here</a>. The correct algorithm is called the Fisher–Yates Shuffle:</p>\n<pre><code>function shuffle(quotes) {\n for (let i = quotes.length - 1; i &gt; 0; i--) {\n const j = ~~(Math.random() * (i + 1));\n [quotes[i], quotes[j]] = [quotes[j], quotes[i]];\n }\n return quotes;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-31T15:55:43.040", "Id": "487261", "Score": "1", "body": "The was an interesting read, thanks for the feedback, I was not aware of this." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-31T16:09:38.740", "Id": "487264", "Score": "2", "body": "What about choosing just a single quote from the array every time: `quotes[Math.floor(Math.random() * quotes.length)]`. We just need one quote every time so might be better just to choose a random one every time... do you see any issues on that approach instead of shuffling the array?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-09-03T02:41:35.073", "Id": "487613", "Score": "1", "body": "I agree it's a better idea to pick a random element instead of shuffling the entire array unnecessarily." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-30T22:17:26.540", "Id": "248670", "ParentId": "248663", "Score": "3" } } ]
{ "AcceptedAnswerId": "248670", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-30T16:07:56.633", "Id": "248663", "Score": "2", "Tags": [ "javascript", "html", "css" ], "Title": "Vanilla JS random quote webpage" }
248663
<p>Amateur c++ programmer here, working my way through the Project Euler problems (problem 4). I would love for someone to take a look at my ~40 lines of code and give suggestions on improving the effectiveness of the code, and how/what to change to better follow the general guidelines for the flow of a c++ program.</p> <p>The <a href="https://projecteuler.net/problem=4" rel="noreferrer">task</a> states as such: &quot;A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99. Find the largest palindrome made from the product of two 3-digit numbers.&quot;</p> <pre class="lang-cpp prettyprint-override"><code>// Largest palindrome product (4) #include &lt;iostream&gt; #include &lt;time.h&gt; bool is_palindrome(int &amp;num) { // Determine if a given number is a palindrome or not int reverse=0, copy=num, digit; do { digit = copy % 10; reverse = reverse*10 + digit; copy /= 10; } while (copy != 0); return (reverse == num); } int main(void) { double time_spent = 0.0; clock_t begin = clock(); int largest_palindrome = 0; for (int i=999; i&gt;99; i--) { for (int j=999; j&gt;99; j--) { if (i &lt; largest_palindrome/1000) { // Optimalization // std::cout &lt;&lt; &quot;Any value lower than &quot; &lt;&lt; i &lt;&lt; &quot; will, when multiplied by 999, never exceed the largest palindrome (&quot; &lt;&lt; largest_palindrome &lt;&lt; &quot;).&quot;&lt;&lt; '\n'; std::cout &lt;&lt; &quot;No larger palindromes possible.&quot; &lt;&lt; '\n'; i = 0; j = 0; } else { int product = i*j; if (is_palindrome(product) &amp;&amp; product&gt;largest_palindrome) { std::cout &lt;&lt; &quot;Found palindrome! &quot; &lt;&lt; i &lt;&lt; &quot; * &quot; &lt;&lt; j &lt;&lt; &quot; == &quot; &lt;&lt; product &lt;&lt; '\n'; largest_palindrome = product; // More optimalization (no product of the current iteration of i can be larger than the current palindrome, so skip to next iteration) j = 0; } } } } // Program execution time clock_t end = clock(); time_spent += (double)(end - begin) / CLOCKS_PER_SEC; std::cout &lt;&lt; &quot;Elapsed time is &quot; &lt;&lt; time_spent &lt;&lt; &quot; seconds.&quot; &lt;&lt; std::endl; return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-30T19:46:49.490", "Id": "487156", "Score": "2", "body": "FYI, a lot of the Euler projects have mathematical solutions that do not require any iteration. Most of the questions are designed so that you can attempt to figure out the mathematical \"trick\" involved." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-31T14:37:38.590", "Id": "487248", "Score": "1", "body": "@PaulMcKenzie Would you figure out and explain to simpler folks the mathematical trick involved, in this special case? Thank you!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-31T18:53:31.123", "Id": "487292", "Score": "0", "body": "@ProfessorVector Paul may have one in mind, but it seems a little out of scope. I hate to be \"that guy,\" but you can Google this to see if anyone else has found \"tricks\" to it rather than brute force attempts. I only mention it because A) This is a very well known set of problems, others probably have discussed it B) The poster of this question may want to avoid \"spoilers\" for better solutions. I see they included a timer so they may be trying to optimize it for speed (again, maybe not, but they didn't explicitly ask to help make it *faster* is why I say this)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-09-01T16:30:52.717", "Id": "487437", "Score": "0", "body": "Note: A followup question appears [here](https://codereview.stackexchange.com/a/248772/100620)" } ]
[ { "body": "<p>Why is the parameter to <code>is_palindrome</code> a reference? It should just be <code>int n</code> since it is a built in type (i.e., not large) and you don't want to change the value passed from the caller.</p>\n<p>The declaration of <code>time_spent</code> can be at near the end of <code>main</code> since that's the only place you use it. Initializing it to 0 then adding a single value to it is just an assignment, and you should declare variables as close to the point of first use as possible.</p>\n<pre><code>auto time_spent = double(end - begin) / CLOCKS_PER_SEC;\n</code></pre>\n<p>Note that I've also changed the cast from a C-style cast to a constructor style.</p>\n<p>In far as the big double loops, there is no point in testing values of <code>i * j</code> that have already been tested (if <code>j &gt; i</code> you've already tried that case when the two values were swapped). So <code>j</code> should start at <code>i</code> and decrease. However, since the goal is the largest palindrome, you should start <code>j</code> at <code>999</code> and end that loop when it is less than <code>i</code>. This will quickly work thru multiples of the larger numbers.</p>\n<p>The check for no larger palindromes possible should be lifted out of the inner loop, and performed before you run the <code>j</code> loop. Its value does not need to be checked on every iteration of the <code>j</code> loop because it won't change. When you do change <code>largest_palindrome</code> you break out of the inner loop and won't execute the check. The <code>'\\n'</code> character used in this message can be included in the message string.</p>\n<p>Instead of ending a loop by setting the index to 0 (<code>j = 0;</code>), use a <code>break;</code> statement. With the optimization check made in the outer loop, you don't need to break out of two loops.</p>\n<p>In the &quot;found palindrome&quot; message, consider replacing the <code>'\\n'</code> with <code>std::endl()</code>. This will flush the output and let you see the message immediately. It will increase the execution time, but depending on how long this runs and how frequent palindromes are found having the faster feedback displayed on a console may be useful. But when running on the challenge site using it could be detrimental.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-30T20:39:55.507", "Id": "487161", "Score": "0", "body": "This is *exactly* the kind of answer I was hoping for! Thank you for taking the time to review my code, kind stranger. You make some excellent points (tweaks that completely went over my head but make so much sense in hindsight), and I thank you. Regarding the execution time, this program takes about 0.005 seconds to execute (not counting command line output), so flushing the output stream (buffer? I'm can't quite remember which is which) so palindromes are shown immediately wouldn't really matter. Again, thank you!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-30T20:21:54.647", "Id": "248666", "ParentId": "248665", "Score": "9" } }, { "body": "<p>You have a brute force solution as 90% of 3 digit number are not palindromes.</p>\n<p>More optimal is to first generate a list of 3 digit palindromic numbers and then check their products, starting with the high numbers.</p>\n<p>Of note is that a 3 digit palindromic number has the form ABA which is much easier to generate than to check every number.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-31T16:43:01.210", "Id": "487270", "Score": "0", "body": "The 3-digit numbers don't have to be palindromes; only the product of the two 3-digit numbers needs to be a palindrome. Moreover, if you just use 3-digit palindrome numbers, you will not find the correct answer. Furthermore, this answer does not provide any review of the OP's actual code, which is a requirement for answers on this Code Review site." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-30T20:27:03.987", "Id": "248667", "ParentId": "248665", "Score": "0" } }, { "body": "<p>Much of this comes from what 1201ProgramAlarm mentioned.</p>\n<p>Notably, changing:</p>\n<pre><code>if (is_palindrome(product) &amp;&amp; product &gt; largest_palindrome)\n</code></pre>\n<p>Into:</p>\n<pre><code>if ((product &gt; largest_palindrome) &amp;&amp; is_palindrome(product))\n</code></pre>\n<p>produces an 8x speedup!</p>\n<p>This is because, now, the &quot;lightweight&quot; test is performed first, and, due to &quot;short circuit&quot; evaluation of the <code>if</code>, the [heavyweight] <code>is_palindrome</code> call is suppressed.</p>\n<hr />\n<p>To minimize the effects of outputing to <code>std::cout</code>, I've added a &quot;solution&quot; struct that remembers <code>i</code>, <code>j</code>, and <code>product</code> and prints all results at the end of a given test. (i.e.) We're timing <em>just</em> the algorithm and <em>not</em> the algorithm plus the I/O time.</p>\n<p>I've also added a <code>timeit</code> function and moved the actual code into functions so multiple algorithms can be compared. <code>timeit</code> also runs the test algorithm multiple times and takes the shortest time to minimize the effects of timeslicing.</p>\n<p>I've shown a progression of improvements.</p>\n<p>Anyway, here's the refactored code:</p>\n<pre><code>// Largest palindrome product (4)\n#include &lt;iostream&gt;\n#include &lt;time.h&gt;\n\nstruct sol {\n int i;\n int j;\n int product;\n};\n\nint solcnt;\nsol solvec[100];\n\n#define SAVE \\\n do { \\\n sol *sp = &amp;solvec[solcnt++]; \\\n sp-&gt;i = i; \\\n sp-&gt;j = j; \\\n sp-&gt;product = product; \\\n } while (0)\n\n// Determine if a given number is a palindrome or not\nbool\nis_palindrome(int num)\n{\n int reverse = 0,\n copy = num,\n digit;\n\n do {\n digit = copy % 10;\n reverse = reverse * 10 + digit;\n copy /= 10;\n } while (copy != 0);\n\n return (reverse == num);\n}\n\nvoid\ntimeit(void (*fnc)(void),const char *reason)\n{\n clock_t best = 0;\n\n for (int iter = 0; iter &lt;= 100; ++iter) {\n clock_t begin = clock();\n\n solcnt = 0;\n fnc();\n\n clock_t end = clock();\n clock_t dif = end - begin;\n\n if (iter == 0)\n best = dif;\n\n if (dif &lt; best)\n best = dif;\n }\n\n std::cout &lt;&lt; '\\n';\n std::cout &lt;&lt; reason &lt;&lt; ':' &lt;&lt; '\\n';\n\n for (sol *sp = solvec; sp &lt; &amp;solvec[solcnt]; ++sp) {\n std::cout &lt;&lt; &quot;Found palindrome! &quot; &lt;&lt; sp-&gt;i &lt;&lt; &quot; * &quot; &lt;&lt; sp-&gt;j &lt;&lt; &quot; == &quot;\n &lt;&lt; sp-&gt;product &lt;&lt; '\\n';\n }\n\n double time_spent = double(best) / CLOCKS_PER_SEC;\n std::cout &lt;&lt; &quot;Elapsed time is &quot; &lt;&lt; time_spent &lt;&lt; &quot; seconds.&quot; &lt;&lt; std::endl;\n}\n\nvoid\nfix1(void)\n{\n int largest_palindrome = 0;\n\n for (int i = 999; i &gt; 99; i--) {\n for (int j = 999; j &gt; 99; j--) {\n // Optimalization\n if (i &lt; largest_palindrome / 1000) {\n //std::cout &lt;&lt; &quot;No larger palindromes possible.&quot; &lt;&lt; '\\n';\n i = 0;\n j = 0;\n }\n else {\n int product = i * j;\n\n if (is_palindrome(product) &amp;&amp; product &gt; largest_palindrome) {\n SAVE;\n\n largest_palindrome = product;\n\n // More optimalization (no product of the current iteration\n // of i can be larger than the current palindrome,\n // so skip to next iteration)\n j = 0;\n }\n }\n }\n }\n}\n\nvoid\nfix2(void)\n{\n int largest_palindrome = 0;\n\n for (int i = 999; i &gt; 99; i--) {\n // Optimalization\n if (i &lt; largest_palindrome / 1000) {\n //std::cout &lt;&lt; &quot;No larger palindromes possible.&quot; &lt;&lt; '\\n';\n break;\n }\n\n for (int j = 999; j &gt; 99; j--) {\n int product = i * j;\n\n if (is_palindrome(product) &amp;&amp; product &gt; largest_palindrome) {\n SAVE;\n\n largest_palindrome = product;\n\n // More optimalization (no product of the current iteration\n // of i can be larger than the current palindrome,\n // so skip to next iteration)\n j = 0;\n }\n }\n }\n}\n\nvoid\nfix3(void)\n{\n int largest_palindrome = 0;\n\n for (int i = 999; i &gt; 99; i--) {\n // Optimalization\n if (i &lt; largest_palindrome / 1000) {\n //std::cout &lt;&lt; &quot;No larger palindromes possible.&quot; &lt;&lt; '\\n';\n break;\n }\n\n for (int j = 999; j &gt; 99; j--) {\n int product = i * j;\n\n if ((product &gt; largest_palindrome) &amp;&amp; is_palindrome(product)) {\n SAVE;\n\n largest_palindrome = product;\n\n // More optimalization (no product of the current iteration\n // of i can be larger than the current palindrome,\n // so skip to next iteration)\n j = 0;\n }\n }\n }\n}\n\nvoid\nfix4(void)\n{\n int largest_palindrome = 0;\n int largest_div1000 = 0;\n\n for (int i = 999; i &gt; 99; i--) {\n // Optimalization\n if (i &lt; largest_div1000) {\n //std::cout &lt;&lt; &quot;No larger palindromes possible.&quot; &lt;&lt; '\\n';\n break;\n }\n\n for (int j = 999; j &gt; 99; j--) {\n int product = i * j;\n\n if ((product &gt; largest_palindrome) &amp;&amp; is_palindrome(product)) {\n SAVE;\n\n largest_palindrome = product;\n largest_div1000 = product / 1000;\n\n // More optimalization (no product of the current iteration\n // of i can be larger than the current palindrome,\n // so skip to next iteration)\n j = 0;\n }\n }\n }\n}\n\nint\nmain(void)\n{\n\n timeit(fix1,&quot;fix1 -- original&quot;);\n timeit(fix2,&quot;fix2 -- moved i &lt; largest_palidrome out of j loop&quot;);\n timeit(fix3,&quot;fix3 -- reversed order of inner if&quot;);\n timeit(fix4,&quot;fix4 -- removed divide by 1000 in loop&quot;);\n\n return 0;\n}\n</code></pre>\n<p>Note that <code>solvec</code> is a simple array. It <em>might</em> be replaced with <code>std::vector</code> [or <code>std::array</code>], but since it's just test jig code, I didn't bother.</p>\n<hr />\n<p>Here's the program output:</p>\n<pre><code>fix1 -- original:\nFound palindrome! 995 * 583 == 580085\nFound palindrome! 993 * 913 == 906609\nElapsed time is 0.001755 seconds.\n\nfix2 -- moved i &lt; largest_palidrome out of j loop:\nFound palindrome! 995 * 583 == 580085\nFound palindrome! 993 * 913 == 906609\nElapsed time is 0.001668 seconds.\n\nfix3 -- reversed order of inner if:\nFound palindrome! 995 * 583 == 580085\nFound palindrome! 993 * 913 == 906609\nElapsed time is 0.000219 seconds.\n\nfix4 -- removed divide by 1000 in loop:\nFound palindrome! 995 * 583 == 580085\nFound palindrome! 993 * 913 == 906609\nElapsed time is 0.000222 seconds.\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-31T06:35:14.113", "Id": "487192", "Score": "1", "body": "I would try to get rid of the macro. You can use a `std::vector<sol>` with a large enough reserved capactiy, and instead of `SAVE` you can then write `solvec.push_back({i, j, product})`, which should then be almost as efficient." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-30T22:08:29.177", "Id": "248669", "ParentId": "248665", "Score": "7" } }, { "body": "<p>Here are some suggestions in addition to the existing answers.</p>\n<h1><code>&lt;chrono&gt;</code></h1>\n<p>In general, the C++ <a href=\"https://en.cppreference.com/w/cpp/header/chrono\" rel=\"nofollow noreferrer\"><code>std::chrono</code></a> API is more flexible and\ntype-safe than the C functions in <code>&lt;ctime&gt;</code>, so consider using\n<code>std::chrono</code> to time the function.</p>\n<h1><code>is_palindrome</code></h1>\n<p>In C++, it is usually not advised to declare multiple variables on one\nline. Taking small types like <code>int</code> by value is more efficient than\nby reference and gives you a free copy to use. To prevent errors, I\nwould also add an assertion to ensure that the input is a nonnegative\ninteger:</p>\n<pre><code>bool is_palindrome(int number) {\n assert(number &gt;= 0);\n\n int original = number;\n int reversed = 0;\n\n while (number &gt; 0) {\n reversed *= 10;\n reversed += number % 10;\n number /= 10;\n }\n\n return reversed == original;\n}\n</code></pre>\n<p>Note that your version suffers from overflow problems for certain\nlarge values of <code>number</code>, which this version does not fix.</p>\n<h1>Mathematical optimizations</h1>\n<p>By analyzing the problem mathematically, some optimizations can be\nachieved. The largest product of two 3-digit numbers is <span class=\"math-container\">\\$ 999 \\times\n999 = 998001 \\$</span>, so the answer will be at most a six-digit number.\nFor now, let's just assume that the answer is <span class=\"math-container\">\\$ \\ge 900000 \\$</span>. Thus,\nthe palindromes are restricted to the form <span class=\"math-container\">\\$ 9abba9 \\$</span>, where <span class=\"math-container\">\\$a\\$</span>\nand <span class=\"math-container\">\\$b\\$</span> are single-digit numbers.</p>\n<p>By applying the <a href=\"https://en.wikipedia.org/wiki/Divisibility_rule\" rel=\"nofollow noreferrer\">divisibility rule</a> for <span class=\"math-container\">\\$11\\$</span>, we see that <span class=\"math-container\">\\$\n9abba9 \\$</span> is a multiple of <span class=\"math-container\">\\$11\\$</span>. Therefore, at least one of the\n3-digit factors is a multiple of <span class=\"math-container\">\\$11\\$</span> — we'll call this factor\nthe <em>primary factor</em>. Since the product is an odd number, the primary\nfactor is odd as well, so we can start from <span class=\"math-container\">\\$979\\$</span>, the largest odd\n3-digit multiple of <span class=\"math-container\">\\$11\\$</span>, and subtract <span class=\"math-container\">\\$22\\$</span> at a time. Our search\nwould stop if the primary factor becomes lower than <span class=\"math-container\">\\$900\\$</span>, since\n<span class=\"math-container\">\\$899 \\times 999 = 898101 &lt; 900000\\$</span>, meaning our assumption would be\ninvalid.</p>\n<p>Here's my result:</p>\n<pre><code>#include &lt;algorithm&gt;\n#include &lt;cassert&gt;\n#include &lt;climits&gt;\n#include &lt;iostream&gt;\n\nbool is_palindrome(int number) {\n assert(number &gt;= 0);\n\n int original = number;\n int reversed = 0;\n\n while (number &gt; 0) {\n reversed *= 10;\n reversed += number % 10;\n number /= 10;\n }\n\n return reversed == original;\n}\n\nint main() {\n int max_product = INT_MIN;\n\n for (int primary = 979; primary &gt;= 900; primary -= 22) {\n for (int secondary = 999; secondary &gt;= 900; secondary -= 2) {\n int product = primary * secondary;\n\n if (is_palindrome(product)) {\n max_product = std::max(product, max_product);\n break; // break out of the inner loop\n }\n }\n }\n\n if (max_product &lt; 900000) {\n std::cout &lt;&lt; &quot;No result &gt;= 900000\\n&quot;;\n } else {\n std::cout &lt;&lt; &quot;Found: &quot; &lt;&lt; max_product &lt;&lt; '\\n';\n }\n}\n</code></pre>\n<p>(<a href=\"https://wandbox.org/permlink/8JGq1xFaxoU7iGrR\" rel=\"nofollow noreferrer\">wandbox</a>)</p>\n<p>The result is <code>906609</code>, which is correct.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-31T06:06:19.667", "Id": "487188", "Score": "1", "body": "Also the one's digits for the two multiplicands must multiply to a number ending in 9. That is (1,9), (9,1), (3,3), (7,7)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-31T17:53:07.213", "Id": "487278", "Score": "0", "body": "\"meaning our assumption would be invalid.\" - Well, a priori that assumption *is* unjustified and *might* miss the solution. In the end, you are \"lucky\"" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-31T18:44:14.497", "Id": "487290", "Score": "3", "body": "@HagenvonEitzen: If we change the message from \"No result found\" to \"Assumption that there is an answer above 900000 is incorrect\", would you be satisfied?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-09-01T02:15:54.247", "Id": "487343", "Score": "0", "body": "@HagenvonEitzen Indeed, if the assumption turns out to be invalid, we need to perform another search with different optimization methods. A better phrasing might state that this search finds solutions above 900000. I've modified the output message." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-31T04:50:04.980", "Id": "248682", "ParentId": "248665", "Score": "11" } }, { "body": "<p>The <code>is_palindrome</code> function is nice. The long main is not so nice. It's doing 3 things:</p>\n<ul>\n<li>computing the desired value</li>\n<li>printing out the result</li>\n<li>timing the algorithm.</li>\n</ul>\n<p>I think it's best if you can keep your functions to do just one thing. Extracting a function that just returns the answer you want could be a good first step.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-31T14:33:43.790", "Id": "248703", "ParentId": "248665", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-30T19:34:42.133", "Id": "248665", "Score": "10", "Tags": [ "c++", "programming-challenge" ], "Title": "Project Euler #4: Finding the largest palindrome that is a product of two 3-digit numbers" }
248665
<p>For this graph and its <a href="https://en.wikipedia.org/wiki/Vertex_cover" rel="nofollow noreferrer">vertex cover</a> I try to compare the LP solution with the optimal and the rounded solution.</p> <p><a href="https://i.stack.imgur.com/dwRv9.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/dwRv9.png" alt="enter image description here" /></a></p> <pre><code>from scipy.optimize import linprog obj = [1, 1, 1, 1, 1, 1, 1, 1] lhs_ineq = [[ -1, -1, 0, 0, 0, 0, 0, 0],[ -1, 0, 0, -1, 0, 0, 0, 0],[ 0, -1, -1, 0, 0, 0, 0, 0],[ 0, -1, 0, 0, -1, 0, 0, 0],[ 0, 0, -1, -1, 0, 0, 0, 0],[ 0, 0, 0, -1, 0, 0, 0, -1],[ 0, 0, 0, -1, 0, 0, -1, 0],[ 0, 0, 0, 0, -1, -1, 0, 0],[ 0, 0, 0, 0, 0, -1, -1, 0],[ 0, 0, 0, 0, 0, -1, 0, -1]] rhs_ineq = [-1, -1, -1, -1, -1, -1, -1, -1, -1, -1] bnd = [(0, float(&quot;inf&quot;)),(0, float(&quot;inf&quot;)),(0, float(&quot;inf&quot;)),(0, float(&quot;inf&quot;)),(0, float(&quot;inf&quot;)),(0, float(&quot;inf&quot;)),(0, float(&quot;inf&quot;)),(0, float(&quot;inf&quot;))] opt = linprog(c=obj, A_ub=lhs_ineq, b_ub=rhs_ineq, bounds=bnd, method=&quot;revised simplex&quot;) print(opt) </code></pre> <p>What comes out is the following, which looks like the optimal solution even though it was done with LP.</p> <pre><code> con: array([], dtype=float64) fun: 3.0 message: 'Optimization terminated successfully.' nit: 11 slack: array([0., 0., 0., 0., 0., 0., 0., 0., 0., 0.]) status: 0 success: True x: array([0., 1., 0., 1., 0., 1., 0., 0.]) </code></pre> <p>The array in the output [0,1,0,1,0,1,0,0] represents a vertex cover with the nodes 2,4,6 which is also the optimal solution (the digit is 0 for a node not in the solution and 1 otherwise).</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-30T21:09:57.227", "Id": "248668", "Score": "1", "Tags": [ "graph", "scipy" ], "Title": "LP constraint problem with scipy" }
248668
<p>The function below passes most test cases:</p> <pre><code>function numOfSquares(a, b) { const isSquare = function (n) { return n &gt; 0 &amp;&amp; Math.sqrt(n) % 1 === 0; }; let squareCount = 0; for (let i = a; i &lt;= b; i++){ if (isSquare(i)) { squareCount++; } } return squareCount } </code></pre> <p><code>numOfSquares(3, 9) //out: 2</code> <code>numOfSquares(17, 24) //out: 0</code></p> <p>The time complexity of this is O(n)... right?</p> <p>The problem is that this function does not pass the test cases being provided due to the time complexity. For example, in one case, the input could be <code>numOfSquares(465868129, 988379794)</code> (expected out: 9855). In my case, using the function above, it seems to run... forever.</p> <p>How can I make this function more efficient, and thus faster?</p>
[]
[ { "body": "<p>You are correct that your solution is <code>O(n)</code>. However, there is a possible solution for <code>O(1)</code>. If you find the root of the first square (<code>first</code>) and the last square (<code>last</code>), then all of the numbers between <code>first</code> and <code>last</code> will yield squares in the range.</p>\n<pre><code>function numSquares(min,max) {\n const first = Math.ceil(Math.sqrt(min));\n const last = Math.floor(Math.sqrt(max));\n return last-first+1;\n}\n\nconsole.log(numSquares(465868129, 988379794));\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-31T01:31:50.383", "Id": "248677", "ParentId": "248671", "Score": "4" } } ]
{ "AcceptedAnswerId": "248677", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-30T22:25:52.003", "Id": "248671", "Score": "3", "Tags": [ "javascript", "time-limit-exceeded", "complexity" ], "Title": "Count number of square integers in a given range of ints (faster function?)" }
248671
<p><strong>Background</strong></p> <p>I have a code that basically caches file. The way it works is it will first check if the file exists on the local drive and if it does if there is a flag passed called validate_file_size then it will do another check to see if the size of the file on local drive equals the size of the file on S3. if they equal we assume the local file is the most recent version and if they don't then we need to download the latest version.</p> <p><strong>CODE</strong></p> <pre><code> def cache_file(self, s3_path_of_file: str, local_path: Path, file_name: str, validate_file_size: bool = True) -&gt; None: bucket, key = s3.deconstruct_s3_url(f&quot;{s3_path_of_file}/{file_name}&quot;) is_file_size_valid = True if not (local_path / file_name).exists(): os.makedirs(local_path, exist_ok=True) try: s3_client().download_file(bucket, key, f&quot;{local_path}/{file_name}&quot;) os.chmod(local_path / file_name, S_IREAD | S_IRGRP | S_IROTH) except botocore.exceptions.ClientError as e: if e.response[&quot;Error&quot;][&quot;Code&quot;] == &quot;404&quot;: raise FileNotFoundError elif validate_file_size: is_file_size_valid = self._is_file_size_equal( s3_path_of_file, local_path, file_name ) if not is_file_size_valid: try: s3_client().download_file(bucket, key, f&quot;{local_path}/{file_name}&quot;) os.chmod(local_path / file_name, S_IREAD | S_IRGRP | S_IROTH) except botocore.exceptions.ClientError as e: if e.response[&quot;Error&quot;][&quot;Code&quot;] == &quot;404&quot;: raise FileNotFoundError else: logger.info(&quot;Cached File is Valid!&quot;) </code></pre> <p><strong>ISSUE</strong></p> <p>I am wondering if there is a better way to organize my if else statements so my code is cleaner and less redundant. I am not particularly happy about this block in particular that is repeated twice.</p> <pre><code> try: s3_client().download_file(bucket, key, f&quot;{local_path}/{file_name}&quot;) os.chmod(local_path / file_name, S_IREAD | S_IRGRP | S_IROTH) except botocore.exceptions.ClientError as e: if e.response[&quot;Error&quot;][&quot;Code&quot;] == &quot;404&quot;: raise FileNotFoundError </code></pre> <p>One obvious choice is to take it out as a separate function but I am almost wondering if i can avoid that and organize my if else statement in a way where i don't really repeat this try except block twice.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-06T18:41:59.797", "Id": "501708", "Score": "0", "body": "The current question title, which states your concerns about the code, is too general to be useful here. Please [edit] to the site standard, which is for the title to simply state the task accomplished by the code. Please see [How do I ask a good question?](https://codereview.stackexchange.com/help/how-to-ask), as well as [How to get the best value out of Code Review: Asking Questions](https://codereview.meta.stackexchange.com/q/2436/120114) for guidance on writing good question titles." } ]
[ { "body": "<p>Perhaps this does what you need:</p>\n<pre><code>exists_locally = (local_path / file_name).exists()\nsizes_agree = (\n validate_file_size is False or\n (\n exists_locally and\n self._is_file_size_equal(s3_path_of_file, local_path, file_name)\n )\n)\nif exists_locally and sizes_agree:\n logger.info('All is well')\nelse:\n os.makedirs(local_path, exist_ok=True)\n self.download_file(...)\n logger.info('Blah blah')\n</code></pre>\n<p>The code could be further simplified if <code>self._is_file_size_equal()</code> will\nhappily return <code>False</code> when the local file is absent.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-31T15:48:59.210", "Id": "487259", "Score": "0", "body": "You have unbalanced parentheses in the `exists_locally` assignment. You're also missing concatenation of the `/`, although it would be better to use `os.path.join()`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-31T15:50:56.030", "Id": "487260", "Score": "0", "body": "@Barmar \"You're also missing concatenation of the `/`\" isn't that what `local_path / file_name` is doing?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-31T16:00:19.023", "Id": "487262", "Score": "0", "body": "I didn't notice that `local_path` was a class that redefines the `/` operator." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-31T16:08:22.127", "Id": "487263", "Score": "0", "body": "@Barmar Thanks, fixed." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-30T23:49:13.350", "Id": "248674", "ParentId": "248673", "Score": "6" } }, { "body": "<p>I'm not a Python programmer, but the way to not repeat the code without creating a function is to do the download checking first have flags set by that checking one for creating a new file path and one for doing the download. Figure out everything that needs to be done first and then do the download and path creation as necessary.</p>\n<p>pseudo code:</p>\n<pre><code>if not local path or file:\n create_local_path_flag = True\n\nif file size not valid:\n file_out_of_date_flag = True\n\nif create_local_path_flag or file_out_of_date_flag:\n if create_local_path_flag:\n create_local_path()\n download_file()\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-31T10:50:52.807", "Id": "487224", "Score": "2", "body": "IMO this is not a very pythonic approach, setting multiple boolean flags to avoid function calls doesn't seem like the way I would go. I think OP is on the right track with extracting a function." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-31T12:06:52.910", "Id": "487236", "Score": "2", "body": "You missed the last paragraph, the OP doesn't want to extract the function, or that was the way the last paragraph was originally phrased." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-31T12:21:46.597", "Id": "487239", "Score": "4", "body": "-fair enough, I think we had different readings of the question. I read it as \"is using a function a good way or is there better?\", to which my answer is \"using a function is the better way\"." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-30T23:53:20.757", "Id": "248675", "ParentId": "248673", "Score": "7" } }, { "body": "<p>Why avoid extracting it to a separate function? I'd argue that extracting it would make the <code>cache_file</code> function easier to read (with good function naming).</p>\n<p>Similarly, checking whether or not the file should be downloaded can be extracted to a function, say, <code>is_latest_version_cached</code>. The <code>cache_file</code> function would then look something like this:</p>\n<pre class=\"lang-py prettyprint-override\"><code> def cache_file(self, s3_path_of_file: str, local_path: Path, file_name: str, validate_file_size: bool = True) -&gt; None:\n if not _is_latest_version_cached(): # input arguments not shown\n try:\n s3_client().download_file(bucket, key, f&quot;{local_path}/{file_name}&quot;)\n os.chmod(local_path / file_name, S_IREAD | S_IRGRP | S_IROTH)\n except botocore.exceptions.ClientError as e:\n if e.response[&quot;Error&quot;][&quot;Code&quot;] == &quot;404&quot;:\n raise FileNotFoundError\n else:\n logger.info(&quot;Cached File is Valid!&quot;)\n</code></pre>\n<p>This removes the repetition.</p>\n<p>In addition to that, I'd extract a function that does the actual caching. The result is then:</p>\n<pre class=\"lang-py prettyprint-override\"><code> def cache_file(self, s3_path_of_file: str, local_path: Path, file_name: str, validate_file_size: bool = True) -&gt; None:\n if not _is_latest_version_cached(): # input arguments not shown\n _cache_file() # input arguments not shown\n else:\n logger.info(&quot;Cached File is Valid!&quot;)\n</code></pre>\n<p>That said, the code does become a bit less neat when you add the required inputs for <code>_is_lastest_version_cached</code> and <code>_cache_file</code> that I omitted in the snippets above.</p>\n<p>It's been a while since I programmed in python, so I'm not sure how pythonic it is to use private methods here and for <code>cache_file</code> and <code>_cache_file</code> to basically have the same name.</p>\n<p>Perhaps it's worth considering renaming the original method to something that indicates that caching is only done if necessary, e.g. <code>ensure_file_is_cached</code>, if this is valuable info to the caller.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-31T10:28:29.370", "Id": "248691", "ParentId": "248673", "Score": "4" } }, { "body": "<p>You're natural response to separate it out into a function is the right one.</p>\n<p>Even if you do re-organise your code such that you only need this block once and its not repeated, splitting it out into it's own function is still a good idea as it is much easier to test standalone, and would be cleaner to refactor if you want to use a different storage provider/access library in future.</p>\n<p>Further things to add:</p>\n<ul>\n<li>If you make the function standalone, then you could pull in the <code>bucket, key = s3...</code> to the new <code>download_s3_file(s3_path, local_filepath)</code> function</li>\n<li>You should add a <code>raise</code> at the end of the exception if you want to catch errors other than 404 (currently e.g. 500 would pass silently)</li>\n<li>You should add the paths to the logs/raises to help yourself later</li>\n<li>You only log on &quot;Cache is valid&quot;, I would either log on everything (&quot;Downloading file&quot;, &quot;Validating cache&quot;) or nothing; everything is probably better!</li>\n<li>You can use <code>Path.mkdir()</code> rather than <code>os.makedir()</code></li>\n<li>You don't use the <code>is_file_size_valid</code> variable after setting it</li>\n<li>As a matter of personal taste, I would combine the <code>local_path</code> and <code>file_name</code> as early as possible (probably before this function!)</li>\n<li>As a matter of personal taste, I would return the local_filepath from this function</li>\n</ul>\n<pre><code>def cache_file(self, s3_path_of_file: str, local_path: Path, file_name: str, validate_file_size: bool = True) -&gt; Path:\n s3_path = f&quot;{s3_path_of_file}/{file_name}&quot;\n local_filepath = f&quot;{local_path}/{file_name}&quot;\n \n if not local_filepath.exists():\n logger.info(f&quot;File does not exist locally, downloading from s3: {s3_path} -&gt; {local_filepath}&quot;)\n local_filepath.parent.mkdir(exist_ok=True, parents=True)\n download_s3_file(s3_path, local_filepath) \n elif validate_file_size and not self._is_file_size_equal(s3_path, local_filepath):\n logger.info(f&quot;Cache file is invalid, re-downloading: {local_filepath}&quot;)\n download_s3_file(s3_path, local_filepath)\n else: \n logger.info(f&quot;Cache file exists locally: {local_filepath}&quot;)\n\n return local_filepath\n\n \ndef download_s3_file(s3_path, local_path)\n bucket, key = s3.deconstruct_s3_url(s3_path)\n try:\n s3_client().download_file(bucket, key, local_path)\n os.chmod(local_path / file_name, S_IREAD | S_IRGRP | S_IROTH)\n except botocore.exceptions.ClientError as e:\n if e.response[&quot;Error&quot;][&quot;Code&quot;] == &quot;404&quot;:\n raise FileNotFoundError(&quot;File not found on S3: {s3_path}&quot;)\n raise\n<span class=\"math-container\">```</span>\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-31T10:41:12.903", "Id": "248692", "ParentId": "248673", "Score": "4" } }, { "body": "<p>Invert the logic of the <code>if</code> statements and return early if the file doesn't need to be downloaded. <code>makedirs()</code> is probably much faster than downloading the file, so calling it every time a file is downloaded won't affect run time.</p>\n<pre><code>def cache_file(self, s3_path_of_file: str, \n local_path: Path,\n file_name: str,\n validate_file_size: bool = True) -&gt; None:\n\n if ( (local_path / file_name).exists()\n and ( validate_file_size == False \n or self._is_file_size_equal(s3_path_of_file, \n local_path, file_name)\n )\n ):\n return\n\n os.makedirs(local_path, exist_ok=True)\n bucket, key = s3.deconstruct_s3_url(f&quot;{s3_path_of_file}/{file_name}&quot;)\n\n try:\n s3_client().download_file(bucket, key, f&quot;{local_path}/{file_name}&quot;)\n os.chmod(local_path / file_name, S_IREAD | S_IRGRP | S_IROTH)\n\n except botocore.exceptions.ClientError as e:\n if e.response[&quot;Error&quot;][&quot;Code&quot;] == &quot;404&quot;:\n raise FileNotFoundError\n else:\n logger.info(&quot;Cached File is Valid!&quot;)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-31T15:50:48.787", "Id": "248710", "ParentId": "248673", "Score": "0" } } ]
{ "AcceptedAnswerId": "248675", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-30T23:01:02.487", "Id": "248673", "Score": "6", "Tags": [ "python" ], "Title": "Organize if else block" }
248673
<p>This code is utilized within a platform that has strict limitations on script execution time, occasionally being exceeded if there is a very large number of lines within the CSV input that is passed into this script. The script then outputs JSON by capturing the necessary data from each CSV line, and grouping data based upon a few columns. Are there any obvious optimizations that could or should be made here?</p> <pre><code>function prepData (options) { // CSV data is passed in on options.data[0]._ if (options.data[0]) { var reportStream = options.data[0]._; var reportData = base64Decode(reportStream); var testData = &quot;Amount Allocated,Base Segment Code,Code,Code Description (All),Company Code,Company,Employee Name,Employee No.,GL Account No.,GL Account Type Code,GL Account Type,GL Code Type Code,GL Code Type,Hours Allocated,Job Code,Job,Location Code,Location,Org Level 1 Code,Org Level 1,Org 1 Segment,Org Level 2 Code,Org Level 2,Org 2 Segment,Org Level 3 Code,Org Level 3,Org 3 Segment,Org Level 4 Code,Org Level 4,Org 4 Segment,Pay Group Code,Pay Group,Period Control,Period Control Date,Project Code,Project,Suspense Account&quot; +&quot;\r\n\&quot;$123.00\&quot;,123,12345,Net Cash,ABC,ABC Inc,\&quot;Smith, John\&quot;,0001,11-11-11,C,Credit,ND,Net pay,0.0000,ABC,A/P Clerk,ABCINC,ABC HQ,1,Administration,1,123,N/A,123,123,N/A,123,1234,Headquarters,1,1,ABC Inc,20190101,01/01/2019,Z,&lt;None&gt;,N&quot;; //var preImportData = prepDataForImport(reportData); var preImportData = prepDataForImport(testData); options.data[0].report = []; options.data[0].report = preImportData options.data[0].report[0].csvData = []; options.data[0].report[0].csvData = reportData; } return { data: options.data, errors: options.errors } function base64Decode(data) { var b64 = &quot;ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=&quot;; var o1, o2, o3, h1, h2, h3, h4, bits, i = 0, ac = 0, dec = &quot;&quot;, tmp_arr = []; if (!data) { return data; } data += ''; do { // unpack four hexets into three octets using index points in b64 h1 = b64.indexOf(data.charAt(i++)); h2 = b64.indexOf(data.charAt(i++)); h3 = b64.indexOf(data.charAt(i++)); h4 = b64.indexOf(data.charAt(i++)); bits = h1 &lt;&lt; 18 | h2 &lt;&lt; 12 | h3 &lt;&lt; 6 | h4; o1 = bits &gt;&gt; 16 &amp; 0xff; o2 = bits &gt;&gt; 8 &amp; 0xff; o3 = bits &amp; 0xff; if (h3 == 64) { tmp_arr[ac++] = String.fromCharCode(o1); } else if (h4 == 64) { tmp_arr[ac++] = String.fromCharCode(o1, o2); } else { tmp_arr[ac++] = String.fromCharCode(o1, o2, o3); } } while (i &lt; data.length); dec = tmp_arr.join(''); return dec; } // Is there any way I can optimize this function to be more efficient? function prepDataForImport(data) { var columnNum = 11; var allTextLines = data.split(/\r\n|\n/); var entries = allTextLines[0].match(/(&quot;.*?&quot;|[^&quot;,]+)(?=\s*,|\s*$)/g); var lines = []; var locationIndex; var glAccountTypeIndex; var accountIndex; var employeeColumnIndex; var payGroupIndex; var summaryAmountIndex; var headings = entries.splice(0, columnNum); for (var i = 0; i &lt; columnNum; i++) { if (headings[i].toLowerCase() == 'location') { headings[i] = 'LOC'; locationIndex = i; } else if (headings[i].toLowerCase() == 'gl account type') { headings[i] = 'GAT'; glAccountTypeIndex = i; } else if (headings[i].toLowerCase() == 'base segment code') { headings[i] = 'BSC'; accountIndex = i; } else if (headings[i].toLowerCase().indexOf('employee name') &gt; -1) { headings[i] = 'EN'; employeeColumnIndex = i; } else if (headings[i].toLowerCase().indexOf('pay group') &gt; -1) { headings[i] = 'PG'; payGroupIndex = i; } else if (headings[i].toLowerCase().indexOf('ee number') &gt; -1) { headings[i] = 'EE'; } else if (headings[i].toLowerCase().indexOf('summary(amount allocated)') &gt; -1) { headings[i] = 'SAA'; summaryAmountIndex = i; } else if (headings[i].toLowerCase() == 'amount allocated') { headings[i] = 'AA'; } else if (headings[i].toLowerCase().indexOf('org 4 segment') &gt; -1) { headings[i] = 'O4S'; } } var employeeObj; var employeeName; var finalArray = []; for (var i = 1; i &lt; allTextLines.length; i++) { var values = {}; var creditAmount = 0; var debitAmount = 0; var skipLine = false; employeeObj = {}; employeeName = ''; var columns = allTextLines[i].match(/(&quot;.*?&quot;|[^&quot;,]+)(?=\s*,|\s*$)/g); if (columns) { // Pay group + location used to group journal entry lines var concatIndexString = columns[locationIndex] + '|' + columns[payGroupIndex]; var glAccountType = columns[glAccountTypeIndex]; var accountId = columns[accountIndex]; employeeName = columns[employeeColumnIndex]; if (accountId == &quot;NOGL&quot; || !accountId) skipLine = true; for (var j = 0; j &lt; columnNum; j++) { if (headings[j].toLowerCase() === &quot;aa&quot;) { columns[j] = columns[j].replace(&quot;$&quot;, &quot;&quot;); columns[j] = columns[j].replace(/,/g, &quot;&quot;); columns[j] = columns[j].replace(/\&quot;/g, &quot;&quot;); if (glAccountType.toLowerCase() == 'debit') debitAmount = columns[j]; else creditAmount = columns[j]; } values[headings[j]] = columns[j]; delete values['SAA']; } var outerObj = { 'outerPayroll': [], 'csvData': [] }; if (!skipLine) { values['creditAmount'] = creditAmount; values['debitAmount'] = debitAmount; var groupObject = { key: concatIndexString, entries: [] }; var groupedIndex = lines.map(function(e){ return e.key; }).indexOf(concatIndexString); var employeeIndex = -1; if (groupedIndex == -1) { lines.push(groupObject); groupedIndex = (lines.length - 1); lines[groupedIndex].entries = []; } lines[groupedIndex].entries.push(values) } // End of skip line check } // split sub-reports when 750 lines reached if (i % 750 == 0 || i == (allTextLines.length-1)) { outerObj['outerPayroll'] = lines; finalArray.push(outerObj); lines = []; } } return finalArray; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-09-03T01:28:41.747", "Id": "487609", "Score": "0", "body": "Hey, Jordan, what if you put a simple example of input and the expected output? I think that's easier to understand what problem you're trying to solve :)" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-31T01:26:46.440", "Id": "248676", "Score": "1", "Tags": [ "javascript", "json", "csv" ], "Title": "How can this JavaScript CSV to JSON hook code be optimized to prevent timeouts?" }
248676
<pre class="lang-py prettyprint-override"><code> def merge_arrays(list1, list2): len_list1 = len(list1); len_list2 = len(list2) merge_len = len_list1 + len_list2 merge_list = [] l1_ptr = 0 l2_ptr = 0 # import pdb; pdb.set_trace() while(l1_ptr &lt;= len_list1-1 and l2_ptr &lt;= len_list2-1): if (list1[l1_ptr] &lt;= list2[l2_ptr]): merge_list.append(list1[l1_ptr]) l1_ptr += 1 elif (list1[l1_ptr] &gt; list2[l2_ptr]): merge_list.append(list2[l2_ptr]) l2_ptr += 1 if l1_ptr &gt; len_list1-1: #list1 exhausted for item in list2[l2_ptr:]: merge_list.append(item) else: for item in list1[l1_ptr:]: merge_list.append(item) return merge_list </code></pre> <p>I am trying to merge sorted arrays in python. How can I improve this? Honestly it looks like I've written this in C and not in Python</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-31T04:34:19.193", "Id": "487178", "Score": "1", "body": "There's a builtin function for this `from heapq import merge`... was this intentionally reinventing the wheel?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-31T10:10:38.167", "Id": "487212", "Score": "1", "body": "@Gerrit0 Or just `sorted(list1 + list2)`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-31T10:25:03.680", "Id": "487218", "Score": "2", "body": "@superbrain that doesn't take into account that both lists have been sorted already" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-31T10:27:06.420", "Id": "487220", "Score": "3", "body": "@MaartenFabré It does. I guess you're not familiar with Timsort?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-31T11:08:09.593", "Id": "487229", "Score": "0", "body": "The `elif:` seems not necessary, an `else:` is enough: once `list1[l1_ptr] <= list2[l2_ptr]` turned out false, `list1[l1_ptr] > list2[l2_ptr]` is true and doesn't need checking." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-31T11:12:44.590", "Id": "487230", "Score": "1", "body": "@MaartenFabré In particular, it also only takes linear time. And in some tests I just did, it was about 18 times faster than `list(merge(list1, list2))`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-31T11:14:21.407", "Id": "487231", "Score": "0", "body": "I seem to be learning something new every day" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-31T20:04:31.593", "Id": "487314", "Score": "0", "body": "@superbrain as much as I agree that this is the simplest solution, and as much as I love Timsort, relying on an implementation detail is never ideal." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-31T21:37:05.293", "Id": "487331", "Score": "0", "body": "@njzk2 Hmm, I'd say it's more than just an ordinary implementation detail. [`sorted`'s documentation](https://docs.python.org/3/library/functions.html#sorted) refers to [Sorting HOW TO](https://docs.python.org/3/howto/sorting.html#sortinghowto), which says *\"The Timsort algorithm used in Python does multiple sorts efficiently because it can take advantage of any ordering already present in a dataset\"*. So it's at least also in the documentaton, and without a *\"CPython implementation detail\"* warning." } ]
[ { "body": "<p>Use a <a href=\"https://www.python.org/dev/peps/pep-0008/#indentation\" rel=\"nofollow noreferrer\">4-space indent</a>.</p>\n<p>Don't repeatedly subtract 1 from the same unchanging value.</p>\n<p>Simplify the compare conditional: just use <code>else</code>.</p>\n<p>Take advantage of <a href=\"https://docs.python.org/3/tutorial/datastructures.html#more-on-lists\" rel=\"nofollow noreferrer\">list.extend()</a>.</p>\n<p>Drop the wrap-up conditionals: they aren't actually needed. Code like <code>zs.extend(xs[xi:])</code> will work fine even if <code>xi</code> exceeds the list\nbounds.</p>\n<p>Shorten the variable names to lighten the code weight and increase readability. There's no loss of meaning here, because all of the short names are quite conventional and make sense in a generic function like this.</p>\n<pre><code>def merge_arrays(xs, ys):\n # Setup.\n xmax = len(xs) - 1\n ymax = len(ys) - 1\n xi = 0\n yi = 0\n zs = []\n\n # Compare and merge.\n while xi &lt;= xmax and yi &lt;= ymax:\n if xs[xi] &lt;= ys[yi]:\n zs.append(xs[xi])\n xi += 1\n else:\n zs.append(ys[yi])\n yi += 1\n\n # Merge any remainders and return.\n zs.extend(ys[yi:])\n zs.extend(xs[xi:])\n return zs\n</code></pre>\n<p>Last night I wrote an iterator-base solution but somehow forgot that <code>next()</code>\nsupports a handy <code>default</code> argument: the code was awkward and <a href=\"https://codereview.stackexchange.com/a/248690/4612\">Maarten\nFabré</a> did a nicer\nimplementation. But if your willing to use\n<a href=\"https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.peekable\" rel=\"nofollow noreferrer\">more_itertools.peekable()</a>\nyou can achieve a simple, readable implementation. Thanks to\n<a href=\"https://codereview.stackexchange.com/users/228314/superb-rain\">superb-rain</a>\nfor an idea in the comments that helped me simplify further.</p>\n<pre><code>from more_itertools import peekable\n\ndef merge(xs, ys):\n xit = peekable(xs)\n yit = peekable(ys)\n while xit and yit:\n it = xit if xit.peek() &lt;= yit.peek() else yit\n yield next(it)\n yield from (xit or yit)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-31T18:46:21.117", "Id": "487291", "Score": "1", "body": "How about [this](https://repl.it/repls/KaleidoscopicMammothPcboard#main.py)?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-31T19:35:36.933", "Id": "487305", "Score": "0", "body": "@superbrain Cool: good to know a peekable iterator can be checked for exhaustion in a simple `if`-test. I simplified my version even more." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-31T05:57:03.757", "Id": "248684", "ParentId": "248679", "Score": "7" } }, { "body": "<h1>various</h1>\n<ul>\n<li><code>merge_len</code> is unused</li>\n<li>the extra parentheses around the simple checks are unnecessary</li>\n<li><code>l1_ptr &lt;= len_list1-1</code> can be made more clearer as <code>l1_ptr &lt; len_list1</code></li>\n<li>using the variable name <code>l1_ptr</code> to save a few characters while making it harder to guess from the name what it does is not useful</li>\n</ul>\n<p>Working with the indices directly is not really pythonic indeed. You can make this more generic, using <code>iter</code> and <code>next</code>, and work for all iterables.</p>\n<h1>typing</h1>\n<p>add typing information:</p>\n<pre><code>import typing\n\nT = typing.TypeVar(&quot;T&quot;)\n\n\ndef merge_sorted_iterables(\n iterable1: typing.Iterable[T], iterable2: typing.Iterable[T]\n) -&gt; typing.Iterable[T]:\n</code></pre>\n<p>This is extra explanation for the user of this function (and his IDE).</p>\n<h1>docstring</h1>\n<p>Add some explanation on what the method does, expects from the caller, and returns.</p>\n<pre><code>def merge_sorted_iterables(\n iterable1: typing.Iterable[T], iterable2: typing.Iterable[T]\n) -&gt; typing.Iterable[T]:\n &quot;&quot;&quot;Merge 2 sorted iterables.\n \n The items in the iterables need to be comparable (and support `&lt;=`).\n ...\n &quot;&quot;&quot;\n</code></pre>\n<h1>iterator</h1>\n<p>Instead of keeping track of the index you can use <code>iter</code> and <code>next</code>. You don't even need to add the items to a list, you can <a href=\"https://wiki.python.org/moin/Generators\" rel=\"noreferrer\"><code>yield</code></a> them, so the caller of the method can decide in what way he wants to use this.</p>\n<pre><code>done = object()\n\niterator1 = iter(iterable1)\niterator2 = iter(iterable2)\n\nitem1 = next(iterator1, done)\nitem2 = next(iterator2, done)\nwhile item1 is not done and item2 is not done:\n if item1 &lt;= item2:\n yield item1\n item1 = next(iterator1, done)\n else:\n yield item2\n item2 = next(iterator2, done)\n</code></pre>\n<p>Then all that needs to be done is continue the iterator that is not finished</p>\n<pre><code> if item1 is not done:\n yield item1\n yield from iterator1\n if item2 is not done:\n yield item2\n yield from iterator2\n</code></pre>\n<hr />\n<pre><code>import typing\n\nT = typing.TypeVar(&quot;T&quot;)\n\n\ndef merge_sorted_iterables(\n iterable1: typing.Iterable[T], iterable2: typing.Iterable[T]\n) -&gt; typing.Iterable[T]:\n &quot;&quot;&quot;Merge 2 sorted iterables.\n \n The items in the iterables need to be comparable (and support `&lt;=`).\n ...\n &quot;&quot;&quot;\n done = object()\n \n iterator1 = iter(iterable1)\n iterator2 = iter(iterable2)\n \n item1 = next(iterator1, done)\n item2 = next(iterator2, done)\n \n while item1 is not done and item2 is not done:\n if item1 &lt;= item2:\n yield item1\n item1 = next(iterator1, done)\n else:\n yield item2\n item2 = next(iterator2, done)\n\n if item1 is not done:\n yield item1\n yield from iterator1\n if item2 is not done:\n yield item2\n yield from iterator2\n</code></pre>\n<h1>testing</h1>\n<p>You can test the behaviour, starting with the simplest cases:</p>\n<pre><code>import pytest\n\ndef test_empty():\n expected = []\n result = list(merge_sorted_iterables([], []))\n assert result == expected\n\ndef test_single():\n expected = [0, 1, 2]\n result = list(merge_sorted_iterables([], range(3)))\n assert expected == result\n result = list(merge_sorted_iterables(range(3), [],))\n assert expected == result\n\ndef test_simple():\n expected = [0, 1, 2, 3, 4, 5]\n result = list(merge_sorted_iterables([0, 1, 2], [3, 4, 5]))\n assert result == expected\n result = list(merge_sorted_iterables([0, 2, 4], [1, 3, 5]))\n assert result == expected\n result = list(merge_sorted_iterables([3, 4, 5], [0, 1, 2],))\n assert result == expected\n\ndef test_string():\n expected = list(&quot;abcdef&quot;)\n\n result = list(merge_sorted_iterables(&quot;abc&quot;, &quot;def&quot;))\n assert result == expected\n result = list(merge_sorted_iterables(&quot;ace&quot;, &quot;bdf&quot;))\n assert result == expected\n result = list(merge_sorted_iterables(&quot;def&quot;, &quot;abc&quot;,))\n assert result == expected\n\ndef test_iterable():\n \n expected = [0, 1, 2, 3, 4, 5]\n result = list(merge_sorted_iterables(iter([0, 1, 2]), iter([3, 4, 5])))\n assert result == expected\n result = list(merge_sorted_iterables(iter([0, 2, 4]), iter([1, 3, 5])))\n assert result == expected\n result = list(merge_sorted_iterables(iter([3, 4, 5]), iter([0, 1, 2]),))\n assert result == expected\n\ndef test_comparable():\n with pytest.raises(TypeError, match=&quot;not supported between instances of&quot;):\n list(merge_sorted_iterables([0, 1, 2], [&quot;a&quot;, &quot;b&quot;, &quot;c&quot;]))\n</code></pre>\n<h1>descending</h1>\n<p>Once you have these test in place, you can easily expand the behaviour to also take descending iterables:</p>\n<pre><code>import operator\n\ndef merge_sorted_iterables(\n iterable1: typing.Iterable[T],\n iterable2: typing.Iterable[T],\n *,\n ascending: bool = True,\n) -&gt; typing.Iterable[T]:\n &quot;&quot;&quot;Merge 2 sorted iterables.\n \n The items in the iterables need to be comparable.\n ...\n &quot;&quot;&quot;\n done = object()\n\n iterator1 = iter(iterable1)\n iterator2 = iter(iterable2)\n\n item1 = next(iterator1, done)\n item2 = next(iterator2, done)\n\n comparison = operator.le if ascending else operator.ge\n\n while item1 is not done and item2 is not done:\n if comparison(item1, item2):\n yield item1\n item1 = next(iterator1, done)\n else:\n yield item2\n item2 = next(iterator2, done)\n\n if item1 is not done:\n yield item1\n yield from iterator1\n if item2 is not done:\n yield item2\n yield from iterator2\n</code></pre>\n<p>I added the <code>ascending</code> keyword as a keyword-only argument to avoid confusion and keep backwards compatibility</p>\n<p>One of its tests:</p>\n<pre><code>def test_descending():\n expected = [5, 4, 3, 2, 1, 0]\n result = list(\n merge_sorted_iterables([2, 1, 0], [5, 4, 3], ascending=False)\n )\n assert result == expected\n result = list(\n merge_sorted_iterables([4, 2, 0], [5, 3, 1], ascending=False)\n )\n assert result == expected\n result = list(\n merge_sorted_iterables([5, 4, 3], [2, 1, 0], ascending=False)\n )\n assert result == expected\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-31T12:58:29.143", "Id": "487241", "Score": "0", "body": "wow this is great, thank you so much. you have no idea how much more i have learnt from your explanation and just this small example. thank you for taking the time, truly!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-31T21:49:44.873", "Id": "487334", "Score": "0", "body": "Thanks for the tests, have been useful :-). Twice you wrote `expected == result` instead of `result == expected`, though. For consistency I think it would be better if all were the same." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-31T22:57:12.403", "Id": "487338", "Score": "0", "body": "I disagree 100% with the \"typing\" section. The function is called \"merge_sorted_iterables\" and takes two arguments \"iterable1\" and \"iterable2\". Of course they're iterables, and of course it returns an iterable. You've added zero useful information, and broken the function signature over three lines, and completely counterfeit the beauty of Python's indentation." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-09-01T04:57:47.303", "Id": "487361", "Score": "0", "body": "In this case the typing information is a bit superfluous. But it helps the IDE, and in other, less trivial cases it can have a lot of value" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-31T10:07:56.113", "Id": "248690", "ParentId": "248679", "Score": "7" } } ]
{ "AcceptedAnswerId": "248690", "CommentCount": "9", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-31T03:35:55.080", "Id": "248679", "Score": "4", "Tags": [ "python" ], "Title": "Merging sorted arrays in Python" }
248679
<p>I wrote the following x86 program to make sure I'm following the correct practices in calling a function and then exiting to the OS:</p> <pre><code>.globl _start _start: # Calculate 2*3 + 7*9 = 6 + 63 = 69 # The multiplication will be done with a separate function call # Parameters passed in System V ABI # The first 6 integer/pointer arguments are passed in: # %rdi, %rsi, %rdx, %rcx, %r8, and %r9 # The return value is passed in %rax # multiply(2, 3) # Part 1 --&gt; Call the parameters mov $2, %rdi mov $3, %rsi # Part 2 --&gt; Call the function (`push` return address onto stack and `jmp` to function label) call multiply # Part 3 --&gt; Handle the return value from %rax (here we'll just push it to the stack as a test) push %rax # multiply(7, 9) mov $7, %rdi mov $9, %rsi call multiply # Add the two together # Restore from stack onto rdi for the first function pop %rdi # The previous value from multiply(7,9) is already in rax, so just add to rbx add %rax, %rdi # for the 64-bit calling convention, do syscall instead of int 0x80 # use %rdi instead of %rbx for the exit arg # use $60 instead of 1 for the exit code movq $60, %rax # use the `_exit` [fast] syscall # rdi contains out exit code syscall # make syscall multiply: mov %rdi, %rax imul %rsi, %rax ret </code></pre> <p>Does the above follow the x86-64 conventions properly? I know it is probably as basic as it comes, but what can be improved here?</p>
[]
[ { "body": "<p>To elaborate on some comments you got on the SO version of this question, the main thing you're missing is <a href=\"https://stackoverflow.com/questions/49391001/why-does-the-x86-64-amd64-system-v-abi-mandate-a-16-byte-stack-alignment\">stack alignment</a>, a requirement of the <a href=\"https://gitlab.com/x86-psABIs/x86-64-ABI\" rel=\"nofollow noreferrer\">SysV ABI</a> calling conventions that's often overlooked by beginners.</p>\n<p>The requirement is (ABI 3.2.2):</p>\n<blockquote>\n<p>The end of the input argument area shall be aligned on a 16 (32 or 64, if\n<code>__m256</code> or <code>__m512</code> is passed on stack) byte boundary.</p>\n</blockquote>\n<p>So that means that, at the instant before you execute a <code>call</code> instruction, the stack pointer <code>%rsp</code> needs to be a multiple of 16. In your case you have a <code>push</code> of 8 bytes without a <code>pop</code> in between your two calls to <code>multiply</code>, so they can't both have correct alignment.</p>\n<p>Some wrinkles are introduced here by the fact that your parent function is <code>_start</code> instead of <code>main</code> or another function called by C code:</p>\n<ul>\n<li><p>The conditions on entry to <code>_start</code> are described in 3.4 of the ABI. In particular, the stack is aligned to 16 bytes at the instant <code>_start</code> gets control. Also, since you cannot return from <code>_start</code> (there is no return address on the stack), you have to exit with a system call as you do, and so there is no need to save any registers for the caller.</p>\n</li>\n<li><p>For <code>main</code> or any other function, the stack would have been aligned to 16 bytes <em>before</em> your function was called, so the extra 8 bytes for the return address mean that on entry to your function, the stack is now &quot;misaligned&quot;, i.e. the value of <code>rsp</code> is 8 more or less than a multiple of 16. (Since one would normally only manipulate the stack in 8-byte increments, it's only really ever in two possible states, which I'll call &quot;aligned&quot; and &quot;misaligned&quot;.) Also, in such functions, you would need to preserve the contents of the callee-saved registers <code>%rbx, %rbp, %r12-r15</code>.</p>\n</li>\n</ul>\n<p>So as it stands, your first call to <code>multiply</code> has correct stack alignment, but your second does not. Of course, it's only of academic interest in this case, because <code>multiply</code> doesn't do anything that needs stack alignment (it doesn't even use the stack at all), but it's good practice to do it right.</p>\n<p>One way to fix it would be to subtract another 8 bytes from the stack pointer before the second call, either with <code>sub $8, %rsp</code> or (more efficiently) by simply <code>push</code>ing any random 64-bit register. But why should we bother to use the stack at all to save this value? We could simply put it in one of the callee-saved registers, say <code>%rbx</code>, which we know <code>multiply</code> must preserve. Normally this would require us to save and restore the contents of this register, but since we are in the special case of being <code>_start</code>, we don't have to.</p>\n<hr />\n<p>A separate comment is that you have a lot of instructions like <code>mov $7, %rdi</code> where you operate on 64-bit registers. This would be better to write as <code>mov $7, %edi</code>. Recall that <a href=\"https://stackoverflow.com/questions/11177137/why-do-x86-64-instructions-on-32-bit-registers-zero-the-upper-part-of-the-full-6\">every write to a 32-bit register will zero the upper half of the corresponding 64-bit register</a>, so the effect is the same as long as your constant is unsigned 32 bits, and the encoding of <code>mov $7, %edi</code> is one byte shorter as it doesn't need a REX prefix.</p>\n<p>So I'd revise your code as</p>\n<pre><code>.globl _start\n\n_start:\n\n # Calculate 2*3 + 7*9 = 6 + 63 = 69\n # The multiplication will be done with a separate function call\n\n # Parameters passed in System V ABI\n # The first 6 integer/pointer arguments are passed in:\n # %rdi, %rsi, %rdx, %rcx, %r8, and %r9\n # The return value is passed in %rax\n\n # multiply(2, 3)\n # Part 1 --&gt; Load the parameters\n mov $2, %edi\n mov $3, %esi\n # Part 2 --&gt; Call the function (`push` return address onto stack and `jmp` to function label)\n call multiply\n # Part 3 --&gt; Save the return value\n mov %rax, %rbx # could also do mov %ebx, %eax if you know the result fits in 32 bits\n\n # multiply(7, 9)\n mov $7, %edi\n mov $9, %esi\n call multiply\n\n # Add the two together\n add %rbx, %rax\n mov %rax, %rdi\n\n # for the 64-bit calling convention, do syscall instead of int 0x80\n # use %rdi instead of %rbx for the exit arg\n # use $60 instead of 1 for the exit code\n\n mov $60, %eax # use the `_exit` [fast] syscall\n # rdi contains out exit code\n syscall # make syscall\n\n\nmultiply:\n mov %rdi, %rax\n imul %rsi, %rax\n ret\n</code></pre>\n<p>If you want to rely on the result of <code>multiply</code> fitting in 32 bits, you could replace <code>mov %rax, %rbx</code> with <code>mov %eax, %ebx</code> to save one byte. And likewise, the &quot;Add the two together&quot; could use 32-bit instructions instead to save two more bytes.</p>\n<p>Finally, there's a stylistic point on whether to use the AT&amp;T-syntax operand size suffixes, like <code>addq</code> versus <code>add</code>. They are optional when one operand is a register, since the operand size can be deduced from the size of that register (e.g. 32 bits for <code>%eax</code>, 64 bits for <code>%rax</code>, etc). My personal preference is to always use them, as a little extra verification that you're really writing what you mean, but omitting them as you (mostly) did is also common and fine; just be consistent. You did have one instance of <code>movq $60, %rax</code> where it wasn't needed, so for consistency I omitted the suffix there. (I also changed it to <code>%eax</code> for the reasons noted above.)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-09-01T03:36:36.787", "Id": "487347", "Score": "0", "body": "thanks for your thorough response and all the suggestions. A few questions: (1) what is the main reason for the 16-byte alignment requirement: is it mainly to support packed types? You mentioned that my code doesn't need that, but where might a function need stack-alignment? (2) Is there another place to view the ABI for example as a saved pdf (that github link requires me to build the latex files with a few additional libraries I don't have) ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-09-01T03:43:16.690", "Id": "487349", "Score": "1", "body": "(2) There's a copy [here](https://github.com/hjl-tools/x86-psABI/wiki/x86-64-psABI-1.0.pdf) which is not the latest but should be close enough. https://stackoverflow.com/questions/18133812/where-is-the-x86-64-system-v-abi-documented may eventually have better links." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-09-01T03:47:29.193", "Id": "487351", "Score": "0", "body": "(1) Sort of. There are SSE and later instructions which require aligned data and fault otherwise. Most of them are intended for packed data but are often used for other purposes, e.g. fast memory copying. But in order to use with stack data, you need to know how the stack is aligned. See also https://stackoverflow.com/questions/63440410/why-linux-nasm-working-even-without-16-bytes-stack-alignment/63440549#63440549." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-09-11T05:24:25.710", "Id": "488387", "Score": "0", "body": "if interested, I posted a continuation question from the above: https://codereview.stackexchange.com/questions/249198/x86-program-to-do-an-exponent" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-31T14:40:38.500", "Id": "248705", "ParentId": "248680", "Score": "3" } } ]
{ "AcceptedAnswerId": "248705", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-31T03:56:05.153", "Id": "248680", "Score": "3", "Tags": [ "assembly", "x86" ], "Title": "Example x86-64 program" }
248680
<p>I'm still new to coding and self-taught. If anyone could take a look at my code for my Ruby Hangman game and give any tips or advice whatsoever, it would be greatly appreciated. I'm trying to improve!</p> <p>The game is completely functional right now, and has a save/load feature. Repli link: <a href="https://repl.it/@MaBuCode/hangman" rel="nofollow noreferrer">https://repl.it/@MaBuCode/hangman</a></p> <pre><code>require 'json' class Hangman def initialize instructions @miss_array = [] random_word_picker word_spaces_creators @chance = 7 if (File.exist?(&quot;saved_game.json&quot;)) game_loader end turn end def to_json @save_game = JSON.dump ({ :secret_word =&gt; @secret_word, :spaces =&gt; @spaces, :chance =&gt; @chance }) end def game_loader puts &quot;Load previously saved game? Y/N?&quot; until @load_response == &quot;Y&quot; || @load_response == &quot;N&quot; @load_response = gets.chomp.upcase end if @load_response == &quot;Y&quot; from_json(&quot;saved_game.json&quot;) end end def from_json(file) data = JSON.load File.new(file) @secret_word = data['secret_word'] @spaces = data['spaces'] @chance = data['chance'] end def save_game(file) game_file = File.new(&quot;saved_game.json&quot;, &quot;w&quot;) game_file.write(file) game_file.close end def random_word_picker @secret_word = File.readlines(&quot;5desk.txt&quot;).sample.split(/[\r\n]+/).join.split(&quot;&quot;) end def word_spaces_creators @spaces = [] i = 0 until i == @secret_word.length @spaces.push(&quot;_ &quot;) i += 1 end end def letter_guess @letter_guess = &quot;&quot; puts &quot;Enter a single letter guess or type \&quot;save\&quot;to save&quot; @letter_guess = gets.downcase.chomp if @letter_guess == &quot;save&quot; to_json save_game(@save_game) exit end until (@letter_guess.is_a? String) &amp;&amp; (@letter_guess.length == 1) &amp;&amp; (('a'..'z').include?(@letter_guess)) puts &quot;Enter a single letter&quot; @letter_guess = gets.downcase.chomp end end def guess_checker(guess) @first_confirm = true @secret_word.each_with_index do |letter, index| if letter == guess || letter == guess.upcase @spaces[index] = &quot;#{letter} &quot; if @first_confirm == true puts &quot;Nice! You guessed a letter correctly&quot; @first_confirm = false end end end if @first_confirm == true chances @miss_array.push(&quot;#{guess} &quot;) puts &quot;Missed letters: #{@miss_array.join}&quot; end end def victory_check if @spaces.include?(&quot;_ &quot;) == false print @spaces.join puts &quot;&quot; puts &quot;Congratulations, you've guessed the word!&quot; elsif @chance == 0 puts &quot;Game Over! You didn't guess the word, it's #{@secret_word.join}&quot; else puts &quot;----------------------&quot; turn end end def turn puts &quot;#{@chance} chance(s) left&quot; puts @spaces.join letter_guess guess_checker(@letter_guess) victory_check end def chances puts &quot;Miss!&quot; @chance -= 1 end def instructions puts &quot;Welcome to Hangman. At the beginning of each game a randomly selected word will be chosen,&quot; puts &quot;you'll be allowed to guess letters until you miss 7 times. If you solve the word correctly you win.&quot; puts &quot;At the beginning you will be given the option to load a previously saved game and before each guess&quot; puts &quot;you will be presented with an opportunity to save your game&quot; puts &quot;---------&quot; end end newgame = Hangman.new </code></pre> <p>edit: Fixed a formatting error</p>
[]
[ { "body": "<p>As you say, the game is fully functional. But from a design perspective, it could use a little work.</p>\n<ol>\n<li>My number one issue is that the whole game is all in one class, and the whole game is run through the <code>initialize</code> method, which only finishes at the end of the game</li>\n<li>The <code>turn</code> method calls <code>victory_check</code>, which then recursively calls <code>turn</code> until the end of the game is reached</li>\n<li>Each method call requires Ruby to put its current context on the stack so that it can be restored when the method returns. But your methods don't return; they just call another method. Because the game has a finite length (words can only be so long, you only get seven guesses) this doesn't cause a problem. But if you were processing a file of a million records, or processing a stream of thousands of tweets, eventually the stack would fill up and your program would fail.</li>\n<li>The class has way too many responsibilities; generating the random word, printing the instructions, maintaining the game state, loading and saving, and interacting with the user. It makes it hard to test the individual parts of it in isolation.</li>\n</ol>\n<p>The idea of objects is that they represent some real-world items and encapsulates their state and provide methods to allow you to interact with them.\nLet's break it down a bit. Here's a sample class that just looks after the game state. It doesn't do much apart from keeping track of the secret word, the number of guesses taken and maintains a printable string showing which letters you've guessed.\nIt also has some convenience methods that allow you to see if you've been hanged or not.</p>\n<p>It doesn't interact with the user, generate the random word, or print the instructions, as these are presentation issues that can be dealt with by another program.</p>\n<pre class=\"lang-rb prettyprint-override\"><code>class Hangword\n attr_reader :guesses\n def initialize(word)\n @word = word.downcase.chars\n @display = @word.map { '_' }\n @charmap = Hash.new { |h, k| h[k] = [] }\n @word.each_with_index { |char, index| @charmap[char].append index }\n @guesses = 7\n end\n\n def guess(char)\n raise 'Hanged' if hanged?\n\n if @charmap.include? char\n @charmap[char].each { |i| @display[i] = char }\n else\n @guesses -= 1\n end\n end\n\n def secret\n @word.join\n end\n\n def display\n @display.join\n end\n\n def hanged?\n @guesses.zero?\n end\n\n def reprieved?\n !hanged? &amp;&amp; !@display.include?('_')\n end\nend\n</code></pre>\n<p>You can create a new <code>Hangword</code> and then interact with it:</p>\n<pre class=\"lang-rb prettyprint-override\"><code>a = Hangword.new 'puzzle'\na.guess('z')\nputs a.display\n7.times { a.guess 'x' }\nputs a.guesses\nputs a.hanged?\nputs a.reprieved?\n\nb = Hangword.new 'puzzle'\n'puzle'.chars.each { |i| b.guess i }\nputs a.reprieved?\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-09-15T04:30:55.363", "Id": "488801", "Score": "0", "body": "Appreciate the feedback! You explanation made a lot of sense to me and I THINK it conceptually helped me understand the fundamental issues I had in my code. I took your advice and rewrote the code from the beginning, I used part of the sample class you used above as a template for one of my classes. If you're interested in taking a quick look to see if it looks like I've gotten the hang of things it would mean a lot, cheers! https://repl.it/@MaBuCode/hangmanrefactored" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-09-03T09:02:14.200", "Id": "248850", "ParentId": "248681", "Score": "2" } }, { "body": "<h1>Consistency</h1>\n<p>Sometimes you are using 1 space for indentation, sometimes you are using 2. Sometimes you are using parentheses around the arguments of a message send, sometimes you don't. Sometimes you are using parentheses around the condition of a conditional, sometimes you don't. Sometimes you are using new-style hash syntax, sometimes you are using old-style.</p>\n<p>You should choose one style and stick with it. If you are editing some existing code, you should adapt your style to be the same as the existing code. If you are part of a team, you should adapt your style to match the rest of the team.</p>\n<p>Most communities have developed standardized community style guides. In Ruby, there are multiple such style guides. They all agree on the basics (e.g. indentation is 2 spaces), but they might disagree on more specific points (single quotes or double quotes).</p>\n<h1>Indentation</h1>\n<p>The standard indentation style in Ruby is two spaces. You mostly use 2 spaces, but there is one place where you use 1 space. Stick with two.</p>\n<h1>Single-quoted strings</h1>\n<p>If you don't use string interpolation, it is helpful if you use single quotes for your strings. That way, it is immediately obvious that no string interpolation is taking place.</p>\n<p>In particular, this would also remove the escaping you need to do here:</p>\n<pre class=\"lang-rb prettyprint-override\"><code>puts 'Enter a single letter guess or type &quot;save&quot;to save'\n</code></pre>\n<p>Note that it is perfectly fine use double quoted strings if you otherwise needed to use escapes, e.g. here:</p>\n<pre class=\"lang-rb prettyprint-override\"><code>puts &quot;Congratulations, you've guessed the word!&quot;\n</code></pre>\n<h1>Frozen string literals</h1>\n<p>Immutable data structures and purely functional code are always preferred, unless mutability and side-effects are required for clarity or performance. In Ruby, strings are always mutable, but there is a magic comment you can add to your files (also available as a command-line option for the Ruby engine), which will automatically make all literal strings immutable:</p>\n<pre class=\"lang-rb prettyprint-override\"><code># frozen_string_literal: true\n</code></pre>\n<p>It is generally preferred to add this comment to all your files.</p>\n<h1>Conditional modifiers</h1>\n<p>When you have a conditional that executes only one expression, you should use the modifier form instead, e.g. this:</p>\n<pre class=\"lang-rb prettyprint-override\"><code>if (File.exist?(&quot;saved_game.json&quot;))\n game_loader\nend\n</code></pre>\n<p>should be</p>\n<pre class=\"lang-rb prettyprint-override\"><code>game_loader if File.exist?('saved_game.json')\n</code></pre>\n<h1>Unnecessary parentheses around a condition</h1>\n<pre class=\"lang-rb prettyprint-override\"><code>if (File.exist?(&quot;saved_game.json&quot;))\n game_loader\nend\n</code></pre>\n<p>The parentheses around <code>File.exist?(&quot;saved_game.json&quot;)</code> are unnecessary.</p>\n<h1>Unnecessary parentheses around a message send</h1>\n<pre class=\"lang-rb prettyprint-override\"><code>(('a'..'z').include?(@letter_guess))\n</code></pre>\n<p>The parentheses around <code>('a'..'z').include?(@letter_guess)</code> are unnecessary.</p>\n<h1>No whitespace between message and argument list</h1>\n<pre class=\"lang-rb prettyprint-override\"><code>JSON.dump ({\n :secret_word =&gt; @secret_word,\n :spaces =&gt; @spaces,\n :chance =&gt; @chance\n})\n</code></pre>\n<p>You have whitespace between the message and the argument list. This means that the parentheses will <em>not</em> be parsed as the parentheses around an argument list, but they will be parsed as the grouping operator. With a single argument, that doesn't make a difference, but if you look at this case:</p>\n<pre class=\"lang-rb prettyprint-override\"><code>foo (1, 2)\n</code></pre>\n<p>This is interpreted as sending the message <code>foo</code> with a <em>single argument</em> <code>(1, 2)</code> which is not a legal expression, and therefore an error.</p>\n<p>The correct way is to not use whitespace between the message and a parenthesized argument list:</p>\n<pre class=\"lang-rb prettyprint-override\"><code>JSON.dump({\n :secret_word =&gt; @secret_word,\n :spaces =&gt; @spaces,\n :chance =&gt; @chance\n})\n</code></pre>\n<h1>New-style hash syntax</h1>\n<p>In 2007, an alternative syntax for hash literals with <code>Symbol</code> keys was added to Ruby. Instead of <code>:symbol =&gt; value</code>, you can now write <code>symbol: value</code>. It is generally preferred to use the new-style hash syntax for hashes that only contain <code>Symbol</code> keys:</p>\n<pre class=\"lang-rb prettyprint-override\"><code>JSON.dump({\n secret_word: @secret_word,\n spaces: @spaces,\n chance: @chance\n})\n</code></pre>\n<h1>Numeric predicates</h1>\n<pre class=\"lang-rb prettyprint-override\"><code>@chance.zero?\n</code></pre>\n<p>reads more fluently than</p>\n<pre class=\"lang-rb prettyprint-override\"><code>@chance == 0\n</code></pre>\n<h1><code>to_json</code> argument</h1>\n<p>It is unfortunately not well-documented, but <code>to_json</code> should take an argument. You can ignore the argument for now, but you should add a splat parameter to your parameter list:</p>\n<pre class=\"lang-rb prettyprint-override\"><code>def to_json(*)\n</code></pre>\n<h1>Linting</h1>\n<p>You should run some sort of linter or static analyzer on your code. <a href=\"https://www.rubocop.org/\" rel=\"nofollow noreferrer\">Rubocop</a> is a popular one, but there are others.</p>\n<p>Rubocop was able to detect all of the style violations I pointed out, and also was able to autocorrect all of them.</p>\n<p>Let me repeat that: I have just spent two pages pointing out how to correct tons of stuff that you can <em>actually</em> correct within milliseconds at the push of a button. I have set up my editor such that it automatically runs Rubocop with auto-fix as soon as I hit &quot;save&quot;.</p>\n<p>In particular, running Rubocop on your code, it detects 82 offenses, of which it can automatically correct 75. This leaves you with 7 offenses, of which 3 are very simple.</p>\n<p>Here's what the result of the auto-fix looks like:</p>\n<pre class=\"lang-rb prettyprint-override\"><code># frozen_string_literal: true\n\nrequire 'json'\n\nclass Hangman\n def initialize\n instructions\n @miss_array = []\n random_word_picker\n word_spaces_creators\n @chance = 7\n game_loader if File.exist?('saved_game.json')\n turn\n end\n\n def to_json(*_args)\n @save_game = JSON.dump({\n secret_word: @secret_word,\n spaces: @spaces,\n chance: @chance\n })\n end\n\n def game_loader\n puts 'Load previously saved game? Y/N?'\n @load_response = gets.chomp.upcase until @load_response == 'Y' || @load_response == 'N'\n from_json('saved_game.json') if @load_response == 'Y'\n end\n\n def from_json(file)\n data = JSON.load File.new(file)\n @secret_word = data['secret_word']\n @spaces = data['spaces']\n @chance = data['chance']\n end\n\n def save_game(file)\n game_file = File.new('saved_game.json', 'w')\n game_file.write(file)\n game_file.close\n end\n\n def random_word_picker\n @secret_word = File.readlines('5desk.txt').sample.split(/[\\r\\n]+/).join.split('')\n end\n\n def word_spaces_creators\n @spaces = []\n i = 0\n until i == @secret_word.length\n @spaces.push('_ ')\n i += 1\n end\n end\n\n def letter_guess\n @letter_guess = ''\n puts 'Enter a single letter guess or type &quot;save&quot;to save'\n @letter_guess = gets.downcase.chomp\n if @letter_guess == 'save'\n to_json\n save_game(@save_game)\n exit\n end\n until (@letter_guess.is_a? String) &amp;&amp;\n (@letter_guess.length == 1) &amp;&amp; ('a'..'z').include?(@letter_guess)\n puts 'Enter a single letter'\n @letter_guess = gets.downcase.chomp\n end\n end\n\n def guess_checker(guess)\n @first_confirm = true\n @secret_word.each_with_index do |letter, index|\n next unless letter == guess || letter == guess.upcase\n\n @spaces[index] = &quot;#{letter} &quot;\n if @first_confirm == true\n puts 'Nice! You guessed a letter correctly'\n @first_confirm = false\n end\n end\n if @first_confirm == true\n chances\n @miss_array.push(&quot;#{guess} &quot;)\n puts &quot;Missed letters: #{@miss_array.join}&quot;\n end\n end\n\n def victory_check\n if @spaces.include?('_ ') == false\n print @spaces.join\n puts ''\n puts &quot;Congratulations, you've guessed the word!&quot;\n elsif @chance.zero?\n puts &quot;Game Over! You didn't guess the word, it's #{@secret_word.join}&quot;\n else\n puts '----------------------'\n turn\n end\n end\n\n def turn\n puts &quot;#{@chance} chance(s) left&quot;\n puts @spaces.join\n letter_guess\n guess_checker(@letter_guess)\n victory_check\n end\n\n def chances\n puts 'Miss!'\n @chance -= 1\n end\n\n def instructions\n puts 'Welcome to Hangman. At the beginning of each game a randomly selected word will be chosen,'\n puts &quot;you'll be allowed to guess letters until you miss 7 times. If you solve the word correctly you win.&quot;\n puts 'At the beginning you will be given the option to load a previously saved game and before each guess'\n puts 'you will be presented with an opportunity to save your game'\n puts '---------'\n end\nend\n\nnewgame = Hangman.new\n</code></pre>\n<p>And here are the offenses that Rubocop could not automatically correct:</p>\n<pre class=\"lang-none prettyprint-override\"><code>Offenses:\n\nhangman.rb:5:1: C: Metrics/ClassLength: Class has too many lines. [104/100]\nclass Hangman ...\n^^^^^^^^^^^^^\nhangman.rb:5:1: C: Style/Documentation: Missing top-level class documentation comment.\nclass Hangman\n^^^^^\nhangman.rb:31:17: C: Security/JSONLoad: Prefer JSON.parse over JSON.load.\n data = JSON.load File.new(file)\n ^^^^\nhangman.rb:56:3: C: Metrics/MethodLength: Method has too many lines. [13/10]\n def letter_guess ...\n ^^^^^^^^^^^^^^^^\nhangman.rb:72:3: C: Metrics/MethodLength: Method has too many lines. [14/10]\n def guess_checker(guess) ...\n ^^^^^^^^^^^^^^^^^^^^^^^^\nhangman.rb:83:5: C: Style/GuardClause: Use a guard clause (return unless @first_confirm == true) instead of wrapping the code inside a conditional expression.\n if @first_confirm == true\n ^^\nhangman.rb:125:1: W: Lint/UselessAssignment: Useless assignment to variable - newgame.\nnewgame = Hangman.new\n^^^^^^^\n\n1 file inspected, 7 offenses detected, 1 offense auto-correctable\n</code></pre>\n<p>Let's look at the simple ones first.</p>\n<h1>Unused local variable</h1>\n<pre class=\"lang-rb prettyprint-override\"><code>newgame = Hangman.new\n</code></pre>\n<p><code>newgame</code> is never used anywhere. Just remove it:</p>\n<pre class=\"lang-rb prettyprint-override\"><code>Hangman.new\n</code></pre>\n<h1>Guard clauses</h1>\n<p>If you have a case where an entire method or block is wrapped in a conditional, you can replace that with a &quot;guard clause&quot; and reduce the level of nesting.</p>\n<p>E.g. this:</p>\n<pre class=\"lang-rb prettyprint-override\"><code>def something\n if foo\n bar\n baz\n quux\n else\n 42\n end\nend\n</code></pre>\n<p>can become this:</p>\n<pre class=\"lang-rb prettyprint-override\"><code>def something\n return 42 unless foo\n\n bar\n baz\n quux\nend\n</code></pre>\n<p>There are a couple of opportunities to do this in your code, and a couple more are created by following the Rubocop advice.</p>\n<p>Here is one example:</p>\n<pre class=\"lang-rb prettyprint-override\"><code>if @first_confirm == true\n chances\n @miss_array.push(&quot;#{guess} &quot;)\n puts &quot;Missed letters: #{@miss_array.join}&quot;\nend\n</code></pre>\n<pre class=\"lang-rb prettyprint-override\"><code>return unless @first_confirm == true\n\nchances\n@miss_array.push(&quot;#{guess} &quot;)\nputs &quot;Missed letters: #{@miss_array.join}&quot;\n</code></pre>\n<h1>Parentheses around argument list</h1>\n<p>In general, you should use the message sending form with parentheses around the argument list, so this:</p>\n<pre class=\"lang-rb prettyprint-override\"><code>@letter_guess.is_a? String\n</code></pre>\n<p>should be</p>\n<pre class=\"lang-rb prettyprint-override\"><code>@letter_guess.is_a?(String)\n</code></pre>\n<p>We only use the whitespace form for methods of <code>Kernel</code> that approximate global procedures, e.g. <code>puts</code>, <code>require</code>, or methods that approximate &quot;language extensions&quot; such as <code>attr_reader</code>.</p>\n<h1>Redundant checks</h1>\n<p>Here, you are checking whether the object referenced by the <code>@letter_guess</code> instance variable is an instance of the <code>String</code> class:</p>\n<pre class=\"lang-rb prettyprint-override\"><code>@letter_guess.is_a? String\n</code></pre>\n<p>But, this comes from user input on the terminal, so it will <em>always</em> be a <code>String</code>. That is <em>literally</em> what <code>gets</code> means: <strong>get</strong> a <strong>s</strong>tring.</p>\n<p>You can just delete this check, since it will always be true.</p>\n<h1>Equality with booleans</h1>\n<pre class=\"lang-rb prettyprint-override\"><code>if @first_confirm == true\n</code></pre>\n<p><code>@first_confirm</code> is already a boolean, there is no need to check for equality to <code>true</code>. This is just</p>\n<pre class=\"lang-rb prettyprint-override\"><code>if @first_confirm\n</code></pre>\n<p>Same here:</p>\n<pre class=\"lang-rb prettyprint-override\"><code>if @spaces.include?('_ ') == false\n</code></pre>\n<p>should just be</p>\n<pre class=\"lang-rb prettyprint-override\"><code>if !@spaces.include?('_ ')\n</code></pre>\n<h1>Unnecessary instance variables</h1>\n<p>The instance variables <code>@load_response</code>, and <code>@first_confirm</code> are only ever used in one method. They should be local variables instead.</p>\n<h1>Prefer the block form of <code>File</code> methods</h1>\n<p>Several methods of <code>File</code> and <code>IO</code> take blocks as arguments, and automatically make sure to close the file handle at the end of the block. For example, this:</p>\n<pre class=\"lang-rb prettyprint-override\"><code>game_file = File.new('saved_game.json', 'w')\ngame_file.write(file)\ngame_file.close\n</code></pre>\n<p>could leak a file handle if some exception gets raised during the <code>write</code>. If you use the block form of <code>File::open</code> instead, the method will take care to ensure the file handle is always closed:</p>\n<pre class=\"lang-rb prettyprint-override\"><code>File.open('saved_game.json', 'w') do |game_file|\n game_file.write(file)\nend\n</code></pre>\n<p>For example, in your <code>json_load</code> method, you create a file handle but never close it!</p>\n<h1>Redundant expression</h1>\n<p>In <code>letter_guess</code>, you assign the empty string to <code>@letter_guess</code>:</p>\n<pre class=\"lang-rb prettyprint-override\"><code>@letter_guess = &quot;&quot;\n</code></pre>\n<p>but then you immediately re-assign it without ever using it in between:</p>\n<pre class=\"lang-rb prettyprint-override\"><code>@letter_guess = gets.downcase.chomp\n</code></pre>\n<p>The first assignment is useless, just remove it.</p>\n<h1>Loops</h1>\n<p>In Ruby, you almost never need loops. In fact, I would go so far and say that if you are using a loop in Ruby, you are doing it wrong.</p>\n<p>Here's an example:</p>\n<pre class=\"lang-rb prettyprint-override\"><code>i = 0\nuntil i == @secret_word.length\n @spaces.push('_ ')\n i += 1\nend\n</code></pre>\n<p>would be much better written as</p>\n<pre class=\"lang-rb prettyprint-override\"><code>@secret_word.length.times do\n @spaces.push('_ ')\nend\n</code></pre>\n<h1>Array initialization</h1>\n<p>But actually, the above could much better be written using the <code>Array::new</code> method with a block argument:</p>\n<pre class=\"lang-rb prettyprint-override\"><code>@spaces = Array.new(@secret_word.size) { '_ ' }\n</code></pre>\n<p>And actually, since you never mutate an element of the array, and we are using frozen string literals anyway, it is safe to just do</p>\n<pre class=\"lang-rb prettyprint-override\"><code>@spaces = Array.new(@secret_word.size, '_ ')\n</code></pre>\n<h1><code>length</code> vs. <code>size</code></h1>\n<p>Many Ruby collections have both <code>length</code> and <code>size</code> methods, but some have only one. In general, <em>IFF</em> a collection has a <code>size</code> method, then that method is guaranteed to be &quot;efficient&quot; (usually constant time), whereas <code>length</code> may or may not be efficient (linear time for iterating through the collection and counting all the elements), depending on the collection.</p>\n<p>In your case, you are using arrays and strings, for which both are constant time, but if you want to guarantee efficiency, then it is better to explicitly use <code>size</code> instead.</p>\n<h1>Print empty lines</h1>\n<p>It is more idiomatic to just use</p>\n<pre class=\"lang-rb prettyprint-override\"><code>puts\n</code></pre>\n<p>to print an empty line instead of</p>\n<pre class=\"lang-rb prettyprint-override\"><code>puts ''\n</code></pre>\n<h1><code>String#chars</code> over <code>String#split</code></h1>\n<p>If you want to get the individual characters of a <code>String</code>, there is the <code>String#chars</code> method for that. No need to use <code>String#split</code> with an empty <code>String</code> as the delimiter.</p>\n<h1><code>Array#include?</code> over multiple comparisons</h1>\n<p>If you have a pattern like this:</p>\n<pre class=\"lang-rb prettyprint-override\"><code>load_response == 'Y' || load_response == 'N'\n</code></pre>\n<p>It is more idiomatic to use</p>\n<pre class=\"lang-rb prettyprint-override\"><code>%w[Y N].include?(load_response)\n</code></pre>\n<h1>The Elephant in the room</h1>\n<p>One thing I have not addressed so far, and that I unfortunately do not have to time to address, is the fundamental design of the code. Everything I mentioned so far is just cosmetics.</p>\n<p>All work is done in the initializer. All an initializer should do is initialize the object. It shouldn't ask for user input, it shouldn't print anything, it shouldn't play a game.</p>\n<p>Also, you are mixing I/O and logic everywhere. A method should either print something or do something. Your design makes it impossible to test the code without actually playing the game. I cannot prepare a file with guesses and feed it to a test runner, I actually have to manually play the game.</p>\n<p>It is also strange that you have only one &quot;object&quot;, namely the game, which is doing something. If you think about how the game is typically played, aren't the objects that are actively doing something the players and not the game? Where are the players in your design?</p>\n<p>Unfortunately, I do not have time to dive into this.</p>\n<p>The flow of your code is extremely convoluted. For example, I cannot figure out whether this check is redundant:</p>\n<pre class=\"lang-rb prettyprint-override\"><code>letter == guess || letter == guess.upcase\n</code></pre>\n<p><code>letter</code> and <code>guess</code> come from different places, they are carried around as hidden state, and it is hard to figure out whether <code>letter</code> even <em>can</em> be upper case at all! And if it can, then it would be much easier to just check like this:</p>\n<pre class=\"lang-rb prettyprint-override\"><code>letter.upcase == guess.upcase\n</code></pre>\n<p>Here is another example:</p>\n<pre class=\"lang-rb prettyprint-override\"><code>File.readlines('5desk.txt').sample.split(/[\\r\\n]+/)\n</code></pre>\n<p>I cannot even figure out what this is supposed to do, so it should probably be extracted into a separate method with a descriptive intention-revealing name and proper documentation. <code>readlines</code> will return an array of lines, <code>sample</code> will randomly return one of those lines, so I am not sure what the <code>split</code> is for. You only have one line, so what are you splitting here?</p>\n<p>Here is where the code currently stands:</p>\n<pre class=\"lang-rb prettyprint-override\"><code># frozen_string_literal: true\n\nrequire 'json'\n\nclass Hangman\n def initialize\n instructions\n @miss_array = []\n random_word_picker\n word_spaces_creators\n @chance = 7\n game_loader if File.exist?('saved_game.json')\n turn\n end\n\n def to_json(*)\n @save_game = JSON.dump({\n secret_word: @secret_word,\n spaces: @spaces,\n chance: @chance\n })\n end\n\n def game_loader\n puts 'Load previously saved game? Y/N?'\n load_response = gets.chomp.upcase until %w[Y N].include?(load_response)\n from_json('saved_game.json') if load_response == 'Y'\n end\n\n def from_json(file)\n data = JSON.parse(File.read(file))\n @secret_word = data['secret_word']\n @spaces = data['spaces']\n @chance = data['chance']\n end\n\n def save_game(file)\n File.open('saved_game.json', 'w') do |game_file|\n game_file.write(file)\n end\n end\n\n def random_word_picker\n @secret_word = File.readlines('5desk.txt').sample.split(/[\\r\\n]+/).join.chars\n end\n\n def word_spaces_creators\n @spaces = Array.new(@secret_word.size, '_ ')\n end\n\n def letter_guess\n puts 'Enter a single letter guess or type &quot;save&quot; to save'\n @letter_guess = gets.downcase.chomp\n if @letter_guess == 'save'\n to_json\n save_game(@save_game)\n exit\n end\n until (@letter_guess.size == 1) &amp;&amp; ('a'..'z').include?(@letter_guess)\n puts 'Enter a single letter'\n @letter_guess = gets.downcase.chomp\n end\n end\n\n def guess_checker(guess)\n first_confirm = true\n @secret_word.each_with_index do |letter, index|\n next unless letter.upcase == guess.upcase\n\n @spaces[index] = &quot;#{letter} &quot;\n\n next unless first_confirm\n\n puts 'Nice! You guessed a letter correctly'\n first_confirm = false\n end\n\n return unless first_confirm\n\n chances\n @miss_array.push(&quot;#{guess} &quot;)\n puts &quot;Missed letters: #{@miss_array.join}&quot;\n end\n\n def victory_check\n if !@spaces.include?('_ ')\n print @spaces.join\n puts\n puts &quot;Congratulations, you've guessed the word!&quot;\n elsif @chance.zero?\n puts &quot;Game Over! You didn't guess the word, it's #{@secret_word.join}&quot;\n else\n puts '----------------------'\n turn\n end\n end\n\n def turn\n puts &quot;#{@chance} chance(s) left&quot;\n puts @spaces.join\n letter_guess\n guess_checker(@letter_guess)\n victory_check\n end\n\n def chances\n puts 'Miss!'\n @chance -= 1\n end\n\n def instructions\n puts 'Welcome to Hangman. At the beginning of each game a randomly selected word will be chosen,'\n puts &quot;you'll be allowed to guess letters until you miss 7 times. If you solve the word correctly you win.&quot;\n puts 'At the beginning you will be given the option to load a previously saved game and before each guess'\n puts 'you will be presented with an opportunity to save your game'\n puts '---------'\n end\nend\n\nHangman.new\n<span class=\"math-container\">```</span>\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-09-15T04:37:28.613", "Id": "488802", "Score": "0", "body": "Thanks for the extensive feedback. I rewrote my code addressing all stylistic issues you identified, ran Rubocop, and I think I fixed the fundamental initialize problem I had in my code. If you're interested in taking a look to see if it seems improved, I'd greatly appreciate it. https://repl.it/@MaBuCode/hangmanrefactored" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-09-04T21:05:18.053", "Id": "248932", "ParentId": "248681", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-31T04:37:44.393", "Id": "248681", "Score": "1", "Tags": [ "beginner", "game", "ruby", "classes" ], "Title": "Ruby Hangman Game" }
248681
<p>I was told my code contains a lot of force unwrapping. I thought it's okay to do that if I am sure that the value operated won't be nil:</p> <pre><code>private var x: Int? private var y: Int? @IBAction func startButtonPressed(_ sender: UIButton) { guard let numberOfRooms = selectedRooms.text, !numberOfRooms.isEmpty else { return selectedRooms.placeholder = &quot;type it, dude&quot; } //if user typed something let rooms = Int(numberOfRooms) x = Int(ceil(sqrt(Double(rooms!)))) y = x //grab some values from user input maze = MazeGenerator(x!, y!) //generate a maze hp = 2 * (x! * y!) //get hp value depending on user input hpLabel.text = &quot;hp: \(hp)&quot; currentX = getRandomX(x!) //get random value in 0...x currentY = getRandomY(y!) currentCell = maze?.maze[currentX!][currentY!] //game starts in a random part of the maze for item in items.indices { //create and show some imageViews items[item].location = (getRandomX(x!), getRandomX(y!)) createItems(imageName: items[item].imageName) if items[item].location == (currentX!, currentY!) { reveal(index: item) } else { hide(index: item) } } refreshButtons() //refresh UI maze!.display() //print maze scheme in debug console } </code></pre> <p>Does it look fine? If not, what should be done?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-31T07:00:46.203", "Id": "487196", "Score": "0", "body": "Ok, but what's the *goal* of the code? What prompted you to write this? What's its purpose? When is this function called?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-31T07:03:00.690", "Id": "487197", "Score": "0", "body": "app opens, user types in number of rooms, clicks \"startButton\" and this function gets called" } ]
[ { "body": "<p>Yes, force unwrapping is ok if you're 100% sure the value won't be nil, <em>but</em> this should only be used when, for code structure reasons, you can't do otherwise. The thing is, most of the times, you can do otherwise, so using force-unwrapping should rarely happen. In your case, I think most of it can be refactored.</p>\n<p>For example: why are your variables <code>x</code> and <code>y</code> declared as Optionals in the first place? Do they <em>have to</em> be?</p>\n<p>If they are only used in this method, they should not be declared as Optional, and they should be declared inside the method, not outside.</p>\n<p>If they are used elsewhere, they should be declared as Optional <em>only</em> if you know they will be nil at some point (which means that they should not be force unwrapped when used, but instead properly validated with error handling).</p>\n<p>If they are used elsewhere and won't be nil when used, but you declared them as Optional for structural reasons, then you could use an implicitly unwrapped Optional instead.</p>\n<pre><code>private var x: Int!\nprivate var y: Int!\n</code></pre>\n<p>This way you won't have to force unwrap them each time you use them.</p>\n<p>Also, if this is acceptable in your context, you could make them non-optional and have an initial value.</p>\n<pre><code>private var x: Int = 0\nprivate var y: Int = 0\n</code></pre>\n<p>But let's say that you have a good reason to declare them as Optionals. In this case, you still can improve your code by safely unwrapping the variables <em>before</em> using them.</p>\n<pre><code>guard let x = Int(ceil(sqrt(Double(rooms!)))) else {\n // show some message\n return\n}\n</code></pre>\n<p>That way, if the user types a letter, space or non-numeric character, instead of a number, the app won't crash.</p>\n<p>Maybe you're making sure elsewhere that the user can only input a number? In this case, force unwrap <code>x</code> before using it:</p>\n<pre><code>x = Int(ceil(sqrt(Double(rooms!))))!\n</code></pre>\n<p>Now, actually, the issue might only happen if <code>numberOfRooms</code> is not a number, so this unwrapping should happen earlier.</p>\n<pre><code>guard let numberOfRooms = selectedRooms.text, !numberOfRooms.isEmpty, let rooms = Int(numberOfRooms) else {\n // error message 'please input a number'\n return\n}\n</code></pre>\n<p>Same idea about <code>currentX</code> and <code>currentY</code>: why are these declared as Optionals? Can the <code>getRandom</code> method return nil? Maybe that can be changed?</p>\n<p>Same for <code>maze</code>: if <code>MazeGenerator</code> can return nil, the shouldn't you handle possible errors instead of force unwrapping? And if it won't ever return nil, then why does it return an Optional instead of a normal value? (or maybe it doesn't return an Optional and the issue is that <code>maze</code> was declared as an Optional but shouldn't have been).</p>\n<hr />\n<p>These are the issues you should address.</p>\n<p>While force unwrapping is indeed not bad if you can guarantee the value won't be nil when you use it, most of the times it's better to make sure <em>earlier</em> in the code flow that the value won't be nil, which will allow you to not having to use Optionals.</p>\n<p>In short: validate the values before use, abort and show an error message if the content is incorrect at the validation step, and then proceed to use the values without having to use Optionals and unwrapping.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-09-04T06:19:44.893", "Id": "248903", "ParentId": "248685", "Score": "2" } }, { "body": "<p><strong>Code review:</strong></p>\n<p><strong>1. use a guard statements to transform optional values to values.</strong></p>\n<pre><code>private var x: Int?\nprivate var y: Int?\n\n@IBAction func startButtonPressed(_ sender: UIButton) {\n \n guard let numberOfRooms = selectedRooms.text, !numberOfRooms.isEmpty else {\n return selectedRooms.placeholder = &quot;type it, dude&quot;\n } //if user typed something\n let rooms = Int(numberOfRooms)\n \n x = Int(ceil(sqrt(Double(rooms!))))\n y = x //grab some values from user input\n \n guard let x = x, y = y else {\n return\n }\n guard let maze = MazeGenerator(x, y) else { //generate a maze\n return\n }\n hp = 2 * (x * y) //get hp value depending on user input\n hpLabel.text = &quot;hp: \\(hp)&quot;\n \n guard let currentX = getRandomX(x), let currentY = getRandomY(y) else {\n return\n }\n currentCell = maze.maze[currentX][currentY] //game starts in a random part of the maze\n \n for item in items.indices { //create and show some imageViews\n items[item].location = (getRandomX(x!), getRandomX(y!))\n createItems(imageName: items[item].imageName)\n if items[item].location == (currentX!, currentY!) {\n reveal(index: item)\n } else {\n hide(index: item)\n }\n }\n refreshButtons() //refresh UI\n maze.display() //print maze scheme in debug console\n}\n</code></pre>\n<p><strong>2. If possible, define a properties as non optional</strong></p>\n<pre><code>private var x: Int = 0\nprivate var y: Int = 0\n\n@IBAction func startButtonPressed(_ sender: UIButton) {\n \n guard let numberOfRooms = selectedRooms.text, !numberOfRooms.isEmpty else {\n return selectedRooms.placeholder = &quot;type it, dude&quot;\n } //if user typed something\n let rooms = Int(numberOfRooms)\n \n x = Int(ceil(sqrt(Double(rooms!))))\n y = x //grab some values from user input\n \n guard let maze = MazeGenerator(x, y) else { //generate a maze\n return\n }\n hp = 2 * (x * y) //get hp value depending on user input\n hpLabel.text = &quot;hp: \\(hp)&quot;\n \n guard let currentX = getRandomX(x), let currentY = getRandomY(y) else {\n return\n }\n currentCell = maze.maze[currentX][currentY] //game starts in a random part of the maze\n \n for item in items.indices { //create and show some imageViews\n items[item].location = (getRandomX(x!), getRandomX(y!))\n createItems(imageName: items[item].imageName)\n if items[item].location == (currentX!, currentY!) {\n reveal(index: item)\n } else {\n hide(index: item)\n }\n }\n refreshButtons() //refresh UI\n maze.display() //print maze scheme in debug console\n}\n</code></pre>\n<p><strong>3. @IBAction should call other methods instead executing a logic code. Example: One would trigger a game start method and an analytics event once a button tapped.</strong></p>\n<pre><code>private var x: Int?\nprivate var y: Int?\n\n@IBAction func startButtonPressed(_ sender: UIButton) {\n gameStartButtonPressed()\n Analytics.logAction(&quot;startButtonPressed&quot;)\n}\n\nprivate func gameStartButtonPressed() {\n guard let numberOfRooms = selectedRooms.text, !numberOfRooms.isEmpty else {\n return selectedRooms.placeholder = &quot;type it, dude&quot;\n } //if user typed something\n let rooms = Int(numberOfRooms)\n \n x = Int(ceil(sqrt(Double(rooms!))))\n y = x //grab some values from user input\n \n guard let x = x, y = y else {\n return\n }\n guard let maze = MazeGenerator(x, y) else { //generate a maze\n return\n }\n hp = 2 * (x * y) //get hp value depending on user input\n hpLabel.text = &quot;hp: \\(hp)&quot;\n \n guard let currentX = getRandomX(x), let currentY = getRandomY(y) else {\n return\n }\n currentCell = maze.maze[currentX][currentY] //game starts in a random part of the maze\n \n for item in items.indices { //create and show some imageViews\n items[item].location = (getRandomX(x!), getRandomX(y!))\n createItems(imageName: items[item].imageName)\n if items[item].location == (currentX!, currentY!) {\n reveal(index: item)\n } else {\n hide(index: item)\n }\n }\n refreshButtons() //refresh UI\n maze.display() //print maze scheme in debug console\n}\n</code></pre>\n<p><strong>4. Separate a model from a controller</strong></p>\n<pre><code>struct Model {\n var x: Int\n var y: Int\n}\n\nprivate var position: Model = .init(x: 0, y: 0)\n\n// instead of:\n\nprivate var x: Int?\nprivate var y: Int?\n</code></pre>\n<p><strong>Additional insights:</strong></p>\n<p><strong>Force unwrapping is useful in following cases (this list is not exhaustive):</strong></p>\n<ul>\n<li>failable initializers</li>\n<li>functions or methods returning optional type instead throwing an error</li>\n<li>IBOutlet attribute</li>\n</ul>\n<p><strong>Example of a failable initializers:</strong></p>\n<p>URL type has a failable initialiser init?(string:) which return optional URL object. In case of a string &quot;https://www.google.pl&quot; one can be sure that the string results in correct url object and not nil. In that case force unwrap is the way to express this having confidence that instead obtaining optional URL, one expects an URL object.</p>\n<pre><code>//failable initializer creates an optional URL object\nlet url: URL? = URL(string: &quot;https://www.google.pl&quot;)\n\n//force unwrapping leads to a non optional URL object\nlet url: URL = URL(string: &quot;https://www.google.pl&quot;)!\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-09-05T13:51:22.397", "Id": "248960", "ParentId": "248685", "Score": "2" } } ]
{ "AcceptedAnswerId": "248960", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-31T06:24:42.987", "Id": "248685", "Score": "3", "Tags": [ "swift", "optional" ], "Title": "A Start button handler" }
248685
<p>I want to wrap NSCache in a Singleton in order to use dependency injection in my code. This has resulted, rather unfortunately, in passing the type through a function parameter, and I even need two mocks for success and failure since it is a singleton instance.</p> <p>I think there might be a better way, but any comments appreciated!</p> <p>ImageCache and protocol</p> <pre><code>protocol ImageCacheProtocol { static var shared: Self { get } func getCache() -&gt; NSCache&lt;AnyObject, UIImage&gt; } final class ImageCache: ImageCacheProtocol { var cache: NSCache&lt;AnyObject, UIImage&gt; = NSCache&lt;AnyObject, UIImage&gt;() public static let shared = ImageCache() private init() {} func getCache() -&gt; NSCache&lt;AnyObject, UIImage&gt; { return cache } } </code></pre> <p>MockImageCache &amp; MockImageCacheFailure</p> <pre><code>final class MockImageCache: ImageCacheProtocol { var cache: NSCache&lt;AnyObject, UIImage&gt; = MockNSCache(shouldReturnImage: true) public static let shared = MockImageCache() private init() {} func getCache() -&gt; NSCache&lt;AnyObject, UIImage&gt; { return cache } } final class MockImageCacheFailure: ImageCacheProtocol { var cache: NSCache&lt;AnyObject, UIImage&gt; = MockNSCache(shouldReturnImage: false) public static let shared = MockImageCacheFailure() private init() {} func getCache() -&gt; NSCache&lt;AnyObject, UIImage&gt; { return cache } } </code></pre> <p>Instantiating my view model (snippet)</p> <pre><code>class ViewModel&lt;U: ImageCacheProtocol&gt; { private var cache: U.Type init&lt;T: NetworkManagerProtocol&gt;(networkManager: T, data: DisplayContent, imageCache: U.Type) { self.networkManager = AnyNetworkManager(manager: networkManager) cache = imageCache </code></pre>
[]
[ { "body": "<p>Yes, this isn't the canonical way. My solution is to not use <code>Self</code> and to instead focus on shared.</p>\n<p>That is:</p>\n<pre><code>protocol ImageCacheProtocol {\n func getCache() -&gt; NSCache&lt;AnyObject, UIImage&gt;\n}\n\nfinal class ImageCache: ImageCacheProtocol {\n var cache: NSCache&lt;AnyObject, UIImage&gt; = NSCache&lt;AnyObject, UIImage&gt;()\n static var shared = ImageCache()\n \n private init() {}\n \n func getCache() -&gt; NSCache&lt;AnyObject, UIImage&gt; {\n return cache\n }\n}\n</code></pre>\n<p>Then the mocks can be altered:</p>\n<pre><code>final class MockImageCache: ImageCacheProtocol {\n var cache: NSCache&lt;AnyObject, UIImage&gt; = MockNSCache(shouldReturnImage: true)\n public static var shared: ImageCacheProtocol! = MockImageCache()\n func getCache() -&gt; NSCache&lt;AnyObject, UIImage&gt; {\n return cache\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-09-02T07:29:45.880", "Id": "248799", "ParentId": "248687", "Score": "0" } } ]
{ "AcceptedAnswerId": "248799", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-31T07:33:41.897", "Id": "248687", "Score": "1", "Tags": [ "swift" ], "Title": "Swift NSCache Singleton" }
248687
<p><strong>Category Service:</strong></p> <pre><code> public Boolean deleteCategory(int id) { try { Category category = categoryDao.getCategoryById(id).orElseThrow(NoSuchElementException::new); categoryDao.deleteCategory(id); categoryDao.moveCategoriesUp(category.getUserid(), category.getPosition()); return true; } catch (DataAccessException | IllegalArgumentException | NoSuchElementException ex) { logger.error(&quot;Error log message&quot; + ex.getMessage()); return false; } } </code></pre> <p>Explanation of what this does:</p> <ol> <li>It deletes the category</li> <li>It pushes all the other above categories down (by down I mean further closer to 0)</li> <li>Then I return to the controller &quot;false&quot; or &quot;true&quot; regarding the success status of the operation.</li> </ol> <p>Here is the controller:</p> <p><strong>Delete Category API:</strong></p> <pre><code>@DeleteMapping(path = &quot;/deleteCat/{id}&quot;) @ResponseBody public Map&lt;String, Boolean&gt; deleteCategory(@PathVariable(&quot;id&quot;) int id) { return Collections.singletonMap(&quot;status&quot;, categoryService.deleteCategory(id)); } </code></pre> <p><strong>What I want to achieve</strong> When the user deletes a category of tasks, I want that category to be deleted and push all the other relevant ones above one &quot;position&quot;. What I am not sure about though is whether I am handling the errors correctly. If for some reason, the id is null, should I let the client know that the IllegalArgumentException was caught? Is it enough if I send back that the operation wasn't successful, for security reasons.</p> <p><strong>So, my questions are</strong>:</p> <ol> <li>Is it ok if I return just &quot;false&quot; or &quot;true&quot; to the controller and NOT let the client know what went wrong?</li> <li>Does my code break any other conventions or best practices?</li> <li>Would it be better if when I caught an exception I would respond with a response entity, let's say, a 400 Error code? So, the client would just receive the error from the http call and then perhaps just display the error message.</li> </ol> <hr /> <p>The reason I put Spring in the title is because I'm using the Spring framework now in this project. But I am asking about the most acceptable practice generally, for other frameworks or no frameworks too.</p> <p><strong>EDIT:</strong> My RequesFilter class:</p> <pre><code>@Component public class JwtRequestFilter extends OncePerRequestFilter { @Qualifier(&quot;handlerExceptionResolver&quot;) private final HandlerExceptionResolver resolver; private final UserDetailsServiceImpl userService; private final ExceptionTranslator exceptionTranslator; private final JwtUtil jwtUtil; @Autowired public JwtRequestFilter(@Qualifier(&quot;handlerExceptionResolver&quot;) HandlerExceptionResolver resolver, UserDetailsServiceImpl userService, ExceptionTranslator exceptionTranslator, JwtUtil jwtUtil) { this.resolver = resolver; this.userService = userService; this.exceptionTranslator = exceptionTranslator; this.jwtUtil = jwtUtil; } @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException, ExpiredJwtException, MalformedJwtException { try { final String authorizationHeader = request.getHeader(&quot;Authorization&quot;); String username = null; String jwt = null; if (authorizationHeader != null &amp;&amp; authorizationHeader.startsWith(&quot;Bearer &quot;)) { jwt = authorizationHeader.substring(7); username = jwtUtil.extractUsername(jwt); } if (username != null &amp;&amp; SecurityContextHolder.getContext().getAuthentication() == null) { UserDetails userDetails = userService.loadUserByUsername(username); boolean correct = jwtUtil.validateToken(jwt, userDetails); if (correct) { UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken( userDetails, null, userDetails.getAuthorities()); usernamePasswordAuthenticationToken .setDetails(new WebAuthenticationDetailsSource().buildDetails(request)); SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken); } } chain.doFilter(request, response); } catch (ExpiredJwtException | MalformedJwtException | AccessDeniedException | IOException ex) { ErrorDTO errorDto = exceptionTranslator.handleException(ex.getClass().getCanonicalName(), ex.getMessage().); response.getWriter().write(errorDto.getHandle()); response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); resolver.resolveException(request, response, null, ex); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-31T10:15:45.790", "Id": "487214", "Score": "2", "body": "Welcome to CodeReview@SE. Heed [How do I ask a Good Question?](https://codereview.stackexchange.com/help/how-to-ask): some code&context is necessary to give a useful review." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-31T10:44:42.410", "Id": "487223", "Score": "0", "body": "@greybeard I read the link and improved the question. Is it better now? Can anyone give me feedback instead of just downvoting please?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-31T12:05:14.423", "Id": "487235", "Score": "3", "body": "I find the question improved, especially the title. I wouldn't down-vote it in its current state. I probably would have down-voted it if you left it in its initial state. My mayor current worry: Java has no notion of *controller * that I know of, or annotations `@DeleteMapping()` and `@ResponseBody` ([Spring Framework](https://spring.io/projects/spring-framework)(?)) - you ask `In Java …`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-09-02T22:39:10.753", "Id": "487600", "Score": "1", "body": "Instead of adding revised code to your post, perhaps a better action would be Posting a new question. - see the section under heading **I improved my code based on the reviews. What next?** on [_What should I do when someone answers my question?_](https://codereview.stackexchange.com/help/someone-answers) as well as [_what you may and may not do after receiving answers_](http://meta.codereview.stackexchange.com/a/1765)." } ]
[ { "body": "<p>It depends on your context, but generally speaking it's good to return as much information as you can about the error to your caller. Unless it discloses security information (e.g., avoid returning error messages that contain names of DB tables or columns.)</p>\n<p>The way I like to code in Spring MVC is to let the business logic throw an appropriate exception when something goes wrong. Then I use a <code>@ControllerAdvice</code>-annotated class that handles the exception by returning an appropriate error response to the client.</p>\n<p>Getting to your questions:</p>\n<ol>\n<li><p>When you perform a business operation, the business logic should return nothing, or throw an appropriate exception to signal that something went wrong.</p>\n</li>\n<li><p>The CategoryDao could treat the two operations, of deleting and &quot;moving up&quot;, as a single operation and offer a method to do that. In any case, the two operations should be wrapped in a transaction</p>\n</li>\n<li><p>On <code>NoSuchElementException</code> the usual thing is to either return 400 or 404, with an appropriate message in the entity body. I prefer 400 because 404 would be generated also in the case when, say, the path of the HTTP request is wrong. It's nice to be able to tell that the error was generated by your code, not by Spring. I know others disagree on this.</p>\n</li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-31T15:01:00.917", "Id": "487257", "Score": "0", "body": "So in my request filter I try to catch the exceptions that are thrown there? should I remove the try/catch blocks and the \"throws\" from my code?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-09-02T06:52:22.440", "Id": "487486", "Score": "1", "body": "Sometimes you want to keep the try-catch to transform a \"technical\" exception such as SQLException to a business exception. Other than that, I think that in your example the try-catch can be removed. Let the exception happen and use a @ControllerAdvice class to handle it. Shameless plug: http://matteo.vaccari.name/blog/archives/875" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-31T14:46:45.000", "Id": "248706", "ParentId": "248688", "Score": "3" } } ]
{ "AcceptedAnswerId": "248706", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-31T09:10:30.707", "Id": "248688", "Score": "1", "Tags": [ "java", "security", "error-handling", "spring", "spring-mvc" ], "Title": "In Spring framework, should the controller let the client know that something went wrong by returning a response entity with the proper error code?" }
248688
<p>I wrote a script to reorder the columns in a CSV file in descending order and then write to another CSV file. My script needs to be able to handle several tens of millions of records, and I would like it to be as performant as possible.</p> <p>This is basically a mockup of a more complex CSV transformation I would be working on for work (I don't yet know the nature of the transformation I would be performing). To clarify, I was directed to write this at work, and it would be tested/scrutinised to see if its performant enough, but it's also not the final script we would eventually run.</p> <p><strong>CSV-Transform.py</strong></p> <pre class="lang-py prettyprint-override"><code>import pandas as pd import csv chunksize = 10 ** 6 # Or whatever value the memory permits source_file = &quot;&quot; # Change to desired source file destination_file = &quot;&quot; # Change to desired destination file def process(chunk, headers, dest): df = pd.DataFrame(chunk, columns=headers) df.to_csv(dest, header=False, index=False) def transform_csv(source_file, destination_file): with open(source_file) as infile: reader = csv.DictReader(infile) new_headers = reader.fieldnames[::-1] with open(destination_file, &quot;w+&quot;) as outfile: outfile.write(&quot;,&quot;.join(new_headers)) outfile.write(&quot;\n&quot;) with open(destination_file, 'a') as outfile: for chunk in pd.read_csv(source_file, chunksize=chunksize): process(chunk, new_headers, outfile) transform_csv(source_file, destination_file) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-31T10:19:55.860", "Id": "487215", "Score": "1", "body": "Welcome to CodeReview@SE. `mockup of a more complex CSV transformation I would be working on` does not comply with [actual code from a project rather than … hypothetical code](https://codereview.stackexchange.com/help/on-topic)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-31T10:22:06.393", "Id": "487216", "Score": "2", "body": "I’m voting to close this question because a *mockup of would-be code* is not the *concrete code from a project, with enough code and / or context* required here." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-31T10:24:31.730", "Id": "487217", "Score": "0", "body": "@greybeard: to clarify, I was directed by my boss to write this mockup first ahead of the task. So it's not just hypothetical code. It is actual code I wrote at work. The script would also be scrutinised to see if its performant enough.\n\nWe just don't yet have the schema from our client." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-31T10:32:55.017", "Id": "487222", "Score": "0", "body": "I have added the elaboration. I don't actually know if this script would be tested against 80 million records, but when my boss mentioned the task of transforming a CSV file of 80 million records, I pitched the approach of using a Pandas dataframe and he asked me to write this mockup first so he could check my approach and see if it would scale." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-31T12:12:55.967", "Id": "487238", "Score": "0", "body": "(I'm mildly interested in benchmark results of using the `10 ** 6` chunksize vs. max. `memory permits`. Plan you measurement, and put your best guess in writing before getting first figures.)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-31T14:40:03.510", "Id": "487249", "Score": "0", "body": "If your boss ordered you to make the mock-up, it's still a mock-up. Is it at least a *functional* mock-up? As in, is it actually more a prototype perhaps? \"and it would be tested/scrutinised to see if its performant enough\" is this something that will eventually be done or has already been done? As in, has this already been tested?" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-31T09:52:57.030", "Id": "248689", "Score": "3", "Tags": [ "python", "performance", "beginner", "csv", "pandas" ], "Title": "Reorder the Columns in a CSV File in Descending Order" }
248689
<p>I used the Bootstrap v4.0.0 accordion to display my business services. Further, I created a custom post type &quot;service&quot; for my services (Each service is a post).</p> <p>To display my services dynamically and not hardcode them, I implemented a for-loop within the WordPress while-loop which uses an enumeration to provide the number of the collapsible.</p> <p>I don't like my solution, especially the enumeration - Is there a better way to solve this? If you see any other improvement, I would be glad to hear also.</p> <p>See my code below:</p> <pre><code>&lt;div class=&quot;wv-archive-container wv-boxed-wrapper&quot;&gt; &lt;div class=&quot;container&quot;&gt; &lt;div class=&quot;row&quot;&gt; &lt;div class=&quot;col-sm&quot;&gt; &lt;h1 id=&quot;wv-archive-header-h1&quot;&gt;All Services&lt;/h1&gt; &lt;div id=&quot;wv-accordion&quot; class=&quot;wv-accordion&quot;&gt; &lt;div class=&quot;card mb-0&quot;&gt; &lt;?php $wv_services = new WP_Query( array( 'posts_per_page' =&gt; -1, 'post_type' =&gt; 'service', 'orderby' =&gt; 'date', 'order' =&gt; 'ASC' ) ); while ( $wv_services-&gt;have_posts() ) { $enum_of_collapsible_str_numbers = [ &quot;One&quot;, &quot;Two&quot;, &quot;Three&quot;, &quot;Four&quot;, &quot;Five&quot;, &quot;Six&quot;, &quot;Seven&quot;, &quot;Eight&quot;, &quot;Nine&quot;, &quot;Ten&quot;, &quot;Eleven&quot;, &quot;Twelve&quot;, &quot;Thirtenn&quot;, &quot;Fourteen&quot;, &quot;Fivteen&quot;, &quot;Sixteen&quot;, &quot;Seventeen&quot;, &quot;Eighteen&quot;, &quot;Nineteen&quot;, &quot;Twenty&quot; ]; $total_number_of_service_posts = wp_count_posts('service')-&gt;publish; for ($collapsible_str_number = 0; $collapsible_str_number &lt; $total_number_of_service_posts; $collapsible_str_number++) { $wv_services-&gt;the_post(); ?&gt; &lt;div class=&quot;card-header collapsed&quot; style=&quot;cursor:pointer;&quot; data-toggle=&quot;collapse&quot; href=&quot;#collapse&lt;?php echo $enum_of_collapsible_str_numbers[$collapsible_str_number] ?&gt;&quot; rel=”nofollow”&gt; &lt;a class=&quot;card-title&quot;&gt;&lt;h2&gt;&lt;?php the_title(); ?&gt;&lt;/h2&gt;&lt;/a&gt; &lt;/div&gt; &lt;div id=&quot;collapse&lt;?php echo $enum_of_collapsible_str_numbers[$collapsible_str_number] ?&gt;&quot; class=&quot;card-body collapse&quot; data-parent=&quot;#accordion&quot;&gt; &lt;p&gt;&lt;?php the_content(); ?&gt;&lt;/p&gt; &lt;/div&gt; &lt;?php } } wp_reset_postdata(); ?&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; </code></pre>
[]
[ { "body": "<p>Not sure what you are trying to achieve, but you can use numerical values for <code>enum_of_collapsible_numbers</code> and you can generate them like this</p>\n<pre><code>$enum_of_collapsible_numbers = range(1, 20);\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-09-02T09:36:22.647", "Id": "248805", "ParentId": "248693", "Score": "1" } }, { "body": "<p>I personally do not prefer the mixing of data collection with data printing, but I understand that this is common on simple Wordpress pages (I am not a Wordpress developer).</p>\n<p><code>id</code> values do not need to be purely comprised of letters to be valid, so I would use a counter and scrap the idea of having a limited-length lookup array of words.</p>\n<p>Using <code>printf()</code> will help to clean up your code by removing string concatenation/interpolation; it also allows you to reuse the same variable in the same expression. Generally, I don't enjoy trying to read a bunch of <code>&lt;?php ... ?&gt;</code> declarations bouncing in and out of php in script -- it just feels too noisy.</p>\n<p>Move your <code>cursor:pointer;</code> inline declaration to an external stylesheet inside <code>.collapsed{}</code> to reduce some of the eye strain on this script.</p>\n<p>Consider declaring your <code>&lt;div&gt;</code> attributes on multiple lines to prevent excessively long lines of code.</p>\n<p>Do not use (multibyte) curly quotes to encapsulate attribute values.</p>\n<p>I think I recommend writing <code>&lt;a&gt;</code> inside of <code>&lt;h2&gt;</code> instead of the inverse.</p>\n<p>Untested suggestion:</p>\n<pre><code>$wv_services = new WP_Query([\n 'posts_per_page' =&gt; -1,\n 'post_type' =&gt; 'service',\n 'orderby' =&gt; 'date',\n 'order' =&gt; 'ASC'\n]);\n\nwhile ($wv_services-&gt;have_posts()) {\n $post_count = wp_count_posts('service')-&gt;publish;\n for ($i = 0; $i &lt; $post_count; ++$i) {\n $wv_services-&gt;the_post();\n sprintf('\n &lt;div class=&quot;card-header collapsed&quot;\n data-toggle=&quot;collapse&quot;\n href=&quot;#collapse%1$d&quot;\n rel=&quot;nofollow&quot;\n &gt;\n &lt;h2&gt;\n &lt;a class=&quot;card-title&quot;&gt;%2$s&lt;/a&gt;\n &lt;/h2&gt;\n &lt;/div&gt;\n &lt;div id=&quot;collapse%1$d&quot;\n class=&quot;card-body collapse&quot;\n data-parent=&quot;#accordion&quot;\n &gt;\n &lt;p&gt;%3$s&lt;/p&gt;\n &lt;/div&gt;',\n $i, // referenced by %1$d\n the_title(), // referenced by %2$s\n the_content() // referenced by %3$s\n );\n }\n}\nwp_reset_postdata();\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-09-03T22:06:44.233", "Id": "248889", "ParentId": "248693", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-31T10:49:26.747", "Id": "248693", "Score": "1", "Tags": [ "php", "html", "wordpress", "twitter-bootstrap" ], "Title": "Dynamic Accordion in WordPress" }
248693
<h3>Idea</h3> <p>After a handfull of small javascript-projects, I also wanted to work a bit with php now. I decided to create a simple contact-form. Of course, I wanted it to be as spam-save as possible, so I used some of the ideas I found online (honeypott and some sort of CAPTCHA).</p> <p>I realized the CAPTCHA-idea in the following way: Every time the user loads the contact-page a simple math-problem is created randomly and the user has to enter the correct solution to submit the form.</p> <h3>The Code</h3> <p><strong>Minimal working example</strong></p> <pre class="lang-html prettyprint-override"><code>&lt;!DOCTYPE html&gt; &lt;html lang='en'&gt; &lt;!-- Head --&gt; &lt;head&gt; &lt;meta charset='utf-8'&gt; &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1&quot;&gt; &lt;title&gt;Contact&lt;/title&gt; &lt;link rel='stylesheet' type='text/css' href='style.css'&gt; &lt;/head&gt; &lt;body&gt; &lt;main&gt; &lt;div style='margin:30px; margin-top: 50px'&gt; &lt;h2&gt;Contact&lt;/h2&gt; &lt;div&gt; &lt;form method=&quot;POST&quot; action=&quot;send.php&quot; class='input'&gt; &lt;label&gt;Your Name:&lt;/label&gt;&lt;br&gt; &lt;input type=&quot;text&quot; name=&quot;myName&quot; placeholder=&quot;Name&quot; required/&gt;&lt;br&gt;&lt;br&gt; &lt;label&gt;Your Email:&lt;/label&gt;&lt;br&gt; &lt;input type=&quot;text&quot; name=&quot;myEmail&quot; placeholder=&quot;E-Mail&quot; required/&gt;&lt;br&gt;&lt;br&gt; &lt;!-- Honeypott --&gt; &lt;input type=&quot;text&quot; id=&quot;website&quot; name=&quot;website&quot;/&gt; &lt;label&gt;Message:&lt;/label&gt;&lt;br&gt; &lt;textarea rows=&quot;8&quot; name=&quot;myMessage&quot; style='width: 100%; resize: none; border: 1px solid Gray; border-radius: 4px; box-sizing: border-box; padding: 10px 10px;' placeholder=&quot;Message&quot; required&gt;&lt;/textarea&gt;&lt;br&gt;&lt;br&gt; &lt;!-- For sending the simple math-exercise to the server --&gt; &lt;input id='read' name='read' value='read' style='display: none;'/&gt; &lt;label id='exercise'&gt;&lt;/label&gt;&lt;br&gt; &lt;input type='number' id='solution' name='solution' placeholder=&quot;Solution&quot; required/&gt; &lt;div style='display: inline-block; text-align: left;'&gt; &lt;input type=&quot;checkbox&quot; id=&quot;consent&quot; name=&quot;consent&quot; value=&quot;consent&quot; required=&quot;&quot;&gt; &lt;label&gt;I agree with saving and sending this message according to the privacy policy. &lt;/label&gt; &lt;/div&gt; &lt;input style='' type=&quot;submit&quot; value=&quot;Send&quot;/&gt; &lt;/form&gt; &lt;/div&gt; &lt;/div&gt; &lt;!-- End main-div --&gt; &lt;script&gt; //Two random numbers for simple math-problem (spam-prevention) let array = [&quot;one&quot;, &quot;two&quot;, &quot;three&quot;, &quot;four&quot;, &quot;five&quot;, &quot;six&quot;, &quot;seven&quot;, &quot;eight&quot;, &quot;nine&quot;, &quot;ten&quot;]; let item1 = array[Math.floor(Math.random() * array.length)]; let item2 = array[Math.floor(Math.random() * array.length)]; document.getElementById('exercise').innerHTML = item1 + &quot; + &quot; + item2 + &quot; = ?&quot;; document.getElementById(&quot;read&quot;).value = item1 + &quot; + &quot; + item2; &lt;/script&gt; &lt;/main&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <pre class="lang-css prettyprint-override"><code>@media (max-width: 1000px) { .input { width: 100%; padding: 10px 20px; margin: 10px 0; display: inline-block; border: 1px solid black; border-radius: 5px; box-sizing: border-box; background: LightGray; } } @media (min-width: 1001px) { .input { width: 30%; padding: 10px 20px; margin: 10px 0; display: inline-block; border: 1px solid black; border-radius: 5px; box-sizing: border-box; background: LightGray; } } input[type=text] { width: 100%; padding: 10px 10px; margin: 10px 0; display: inline; border: 1px solid Gray; border-radius: 5px; box-sizing: border-box; } input[type=submit] { width: 100%; padding: 10px 10px; margin: 10px 0; display: inline; border: 1px solid Gray; border-radius: 5px; box-sizing: border-box; } input[type=number] { width: 100%; padding: 10px 10px; margin: 10px 0; display: inline; border: 1px solid Gray; border-radius: 5px; box-sizing: border-box; } #website { display: none; } </code></pre> <p><strong>PHP-Code</strong></p> <pre class="lang-php prettyprint-override"><code>&lt;?php //Get simple math-problem (e.g. four + six) $str = $_REQUEST['read']; $first = strpos($str, &quot; &quot;); //Get first number (e.g. four) $substr1 = substr($str, 0, $first); //Get second number (e.g. six) $substr2 = substr($str, $first + 3, strlen($str) - $first - 3); $arr = array(&quot;zero&quot;, &quot;one&quot;, &quot;two&quot;, &quot;three&quot;, &quot;four&quot;, &quot;five&quot;, &quot;six&quot;, &quot;seven&quot;, &quot;eight&quot;, &quot;nine&quot;, &quot;ten&quot;); /* * Convertring strings to numbers, e.g. * four -&gt; 4 * six -&gt; 6 */ $x = 0; $y = 0; for($i = 0; $i &lt;= 10; $i++) { if(strcmp($substr1, $arr[$i]) == 0) { $x = $i; break; } } for($i = 0; $i &lt;= 10; $i++) { if(strcmp($substr2, $arr[$i]) == 0) { $y = $i; break; } } $z = intval($_POST['solution']); //Did user enter right solution? if($z == ($x + $y)) { //Bot filled the honeypott-tree if(!empty($_POST['website'])) { echo &quot;Something went wrong&quot;; die(); } $userName = $_POST['myName']; $userEmail = $_POST['myEmail']; $userMessage = $_POST['myMessage']; //Did user enter a valid email-adress? if(!filter_var($userEmail, FILTER_VALIDATE_EMAIL)) { echo &quot;Something went wrong&quot;; die(); } //Creating message $to = &quot;mail@domain.com&quot;; $subject = &quot;New Contact-form message&quot;; $body = &quot;Content:&quot;; $body .= &quot;\n\n Name: &quot; . $userName; $body .= &quot;\n\n Email: &quot; . $userEmail; $body .= &quot;\n\n Message: &quot; . $userMessage; //Trying to send message if(mail($to, $subject, $body)){ echo &quot;Thank you for your message&quot;; die(); } else{ echo &quot;Something went wrong&quot;; die(); } } echo &quot;Something went wrong&quot;; ?&gt; </code></pre> <h3>Question(s)</h3> <p>I am especially interested in suggestions to improve the php-code.</p> <ul> <li>Did I follow best-practices?</li> <li>Is anything in the code a really <em>bad</em> idea?</li> </ul> <p>Another thing I am interested in is the safety of this approach. How can it improved further?</p> <p>Of course all other suggestions are appreciated as well.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-09-01T22:34:12.603", "Id": "487464", "Score": "1", "body": "I fully support Certain's advice because putting a 24-inch-high fence around a swimming pool is only going to keep just-crawling toddlers from getting in -- the naughty teenagers next door will chuckle to themselves as they step right over it. Here's my take on your 2-foot fence: https://3v4l.org/vMdJf" } ]
[ { "body": "<p><strong>JS and front-end style</strong></p>\n<ul>\n<li>If you aren't going to reassign a variable, <a href=\"https://softwareengineering.stackexchange.com/questions/278652/how-much-should-i-be-using-let-vs-const-in-es6\">always use <code>const</code> instead of <code>let</code></a>.</li>\n<li>Or, since this sounds like it's on a public facing website, if you wish to support ancient obsolete browsers that some users unfortunately still use (such as IE11), either write in ES5, or (recommended for anything more than a handful of lines) use <a href=\"https://babeljs.io/\" rel=\"nofollow noreferrer\">Babel</a> to transpile your ES6+ source code to ES5 automatically for production.</li>\n<li>Better to only use <code>.innerHTML</code> when deliberately inserting or retrieving HTML markup. If you aren't dealing with HTML markup, using <code>textContent</code> is faster and safer. (setting <code>.innerHTML</code> with untrusted input is a security risk. The input happens to be trusted here, but it's better to get into the habit of only using <code>.innerHTML</code> when necessary)</li>\n<li>This is somewhat opinion-based, but I'd prefer to avoid creating elements with IDs, because the ID of the element will <a href=\"https://stackoverflow.com/questions/3434278/do-dom-tree-elements-with-ids-become-global-variables\">implicitly become a global variable</a>, and variable names that happen to be unexpectedly globally defined can be an easy source of bugs, especially in larger projects (unless you're using a <a href=\"https://eslint.org/docs/rules/no-undef\" rel=\"nofollow noreferrer\">linter</a> or Typescript to protect yourself). I'd use <code>class=&quot;foo&quot;</code> instead of <code>id=&quot;foo&quot;</code>.</li>\n</ul>\n<p><strong>Security</strong></p>\n<p>The random numbers are being generated on the front-end, and as a result are very simple for any interested abuser with a bit of understanding of JS to bypass. (Admittedly, this is unlikely for a small-time website, but it's still something that would be good to fix.) All they'd need to do would be to send a request with a pre-set <code>read</code> property of <code>one + one</code> and a solution of <code>2</code>, along with whatever spam messages they'd want to send, and they could send you 1000 of them.</p>\n<p>I would recommend generating the random numbers on the <em>server</em>, and sending them to the client to verify in such a format that the random numbers could not be programatically extracted from payload easily.</p>\n<p>If I were creating a home-spun solution rather than something tried-and-trusted like Recaptcha, I would have the client request an image from the server, have the server create the background image with <a href=\"https://www.php.net/manual/en/function.imagecreatefrompng.php\" rel=\"nofollow noreferrer\"><code>imagecreatefrompng</code></a>, draw random text onto it with <a href=\"https://www.php.net/manual/en/function.imagettftext.php\" rel=\"nofollow noreferrer\"><code>imagettftext</code></a>, save the text in a session variable, and send the image to the client for verification. It wouldn't be perfect, but it would dramatically raise the bar for successful abuse.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-31T20:05:37.213", "Id": "248726", "ParentId": "248695", "Score": "3" } } ]
{ "AcceptedAnswerId": "248726", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-31T11:47:28.763", "Id": "248695", "Score": "3", "Tags": [ "javascript", "beginner", "php", "html", "css" ], "Title": "Contact form with spam-prevention" }
248695
<p>This is web exercise 2.3.20. from the book <em>Computer Science An Interdisciplinary Approach</em> by Sedgewick &amp; Wayne:</p> <blockquote> <p>Write a recursive program that takes a command-line argument n and plots an N-by-N Hadamard pattern where N = 2^n. Do not use an array. A 1-by-1 Hadamard pattern is a single black square. In general a 2N-by-2N Hadamard pattern is obtained by aligning 4 copies of the N-by-N pattern in the form of a 2-by-2 grid, and then inverting the colors of all the squares in the lower right N-by-N copy. The N-by-N Hadamard H(N) matrix is a boolean matrix with the remarkable property that any two rows differ in exactly N/2 bits. Here are the first few Hadamard matrices.</p> <p><a href="https://i.stack.imgur.com/gcChN.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/gcChN.png" alt="enter image description here" /></a></p> </blockquote> <p>Here is my program:</p> <pre><code>public class wexercise2_3_20 { public static void hadamard(int n, double x, double y, double size, boolean color) { double x1 = x - size/2, x2 = x + size/2; double y1 = y - size/2, y2 = y + size/2; if (n == 0) return; if (color) { StdDraw.setPenColor(StdDraw.BLACK); StdDraw.filledSquare(x,y,size); } else { StdDraw.setPenColor(StdDraw.WHITE); StdDraw.filledSquare(x,y,size); } hadamard(n-1, x1, y1, size/2, color); hadamard(n-1, x1, y2, size/2, color); hadamard(n-1, x2, y2, size/2, color); hadamard(n-1, x2, y1, size/2, !color); } public static void main(String[] args) { int n = Integer.parseInt(args[0]); hadamard(n, 0.5, 0.5, 0.5, true); } } </code></pre> <p><a href="https://introcs.cs.princeton.edu/java/stdlib/javadoc/StdDraw.html" rel="nofollow noreferrer">StdDraw</a> is a simple API written by the authors of the book.</p> <p>Is there any way that I can improve my program?</p> <p>Thanks for your attention.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-31T16:18:05.707", "Id": "487265", "Score": "0", "body": "I would put the `if (n == 0) return;` at the beginning." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-31T16:19:56.150", "Id": "487266", "Score": "0", "body": "@MiguelAvila May I ask why?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-31T16:21:13.187", "Id": "487267", "Score": "1", "body": "Because even if it is a bit, it saves four operations (the initialization of `x1, x2, y1, y2`)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-31T16:37:36.547", "Id": "487268", "Score": "0", "body": "Are you sure you have to use `double` arguments for your function ? Because it seems me you have a matrix N x N where N is a power of 2." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-31T16:40:02.750", "Id": "487269", "Score": "0", "body": "@dariosicily I understand. But I think this is because of the StdDraw library. It creates a 1.0 by 1.0 square and only accepts double values." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-31T16:43:50.073", "Id": "487271", "Score": "0", "body": "I thought about this but if you pass ints to StdDraw they will automatically converted to doubles." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-31T16:45:22.197", "Id": "487272", "Score": "0", "body": "Yes but in that case you should manually scale the drawing window to fit those bigger than 1.0 integers." } ]
[ { "body": "<p>Class names in Java should start with a capital letter.</p>\n<p>Avoid initializing two variables in the same line.</p>\n<p>The <code>filledSquare</code> call is the same in the two <code>if</code> branches, it could be moved out of the <code>if</code>. Now the two <code>if</code> branches only change in the argument to the <code>setPenColor</code> call, and you could replace it by</p>\n<pre><code>Color theColor = color ? WHITE : BLACK;\n</code></pre>\n<p>Now it seems like you could drop the boolean argument altogether (boolean arguments suck) and pass a Color; all you need is a function that inverts the color.</p>\n<p>This criticism has nothing to do with recursion; I have no idea if this works correctly or not :)</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-31T14:58:39.743", "Id": "248708", "ParentId": "248698", "Score": "2" } }, { "body": "<p>In your code is present the following exit condition :</p>\n<pre><code>if (n == 0) return;\n</code></pre>\n<p>You can rewrite your code executing it just when <code>n &gt; 0</code> starting from the assumption that <code>n</code> is always positive from the problem description, so your function can be rewritten like below :</p>\n<pre><code>public static void hadamard(int n, double x, double y, double size,\n boolean color) {\n if (n &gt; 0) { \n //your code \n }\n}\n</code></pre>\n<p><em><strong>Note</strong></em>: as @RoToRa noticed in his comment below my answer, wrapping the full code function in a <code>if</code> branch is not a good practice code, so better to use the old <code>if (n == 0) return;</code> at the beginning of the function followed by the body of the function.</p>\n<p>At the beginning of the code there are the following declarations:</p>\n<pre><code>double x1 = x - size/2, x2 = x + size/2;\ndouble y1 = y - size/2, y2 = y + size/2;\n</code></pre>\n<p>You can rewrite them like below:</p>\n<pre><code>final halfSize = size / 2;\nfinal double x1 = x - halfSize;\nfinal double y1 = y - halfSize;\n</code></pre>\n<p>Then the recursive calls to your function can be rewritten like below:</p>\n<pre><code>--n; //&lt;-- decrementing n here for clarity\nhadamard(n, x1, y1, halfSize, color);\nhadamard(n, x1, y1 + size, halfSize, color);\nhadamard(n, x1 + size, y1 + size, halfSize, color);\nhadamard(n, x1 + size, y1, halfSize, !color);\n</code></pre>\n<p>Your method can be rewritten like this:</p>\n<pre><code>public static void hadamard(int n, double x, double y, double size,\n boolean color) {\n\n if (n &gt; 0) {\n\n final double halfSize = size / 2;\n final double x1 = x - halfSize;\n final double y1 = y - halfSize;\n Color c = color ? StdDraw.BLACK : StdDraw.WHITE;\n\n StdDraw.setPenColor(c);\n StdDraw.filledSquare(x, y, size);\n\n --n; //put here for clarity\n hadamard(n, x1, y1, halfSize, color);\n hadamard(n, x1, y1 + size, halfSize, color);\n hadamard(n, x1 + size, y1 + size, halfSize, color);\n hadamard(n, x1 + size, y1, halfSize, !color);\n\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-31T20:49:38.233", "Id": "487321", "Score": "0", "body": "Thank you very much for your time. :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-31T21:04:15.410", "Id": "487327", "Score": "0", "body": "@KhashayarBaghizadeh You are welcome." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-09-01T10:05:56.150", "Id": "487385", "Score": "1", "body": "Generally an early return as in the original code is prefered over wrapping the whole function in an `if` block. See for example: https://softwareengineering.stackexchange.com/questions/18454/should-i-return-from-a-function-early-or-use-an-if-statement" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-09-01T10:38:54.483", "Id": "487390", "Score": "0", "body": "@RoToRa Probably I was too greedy to write less code lines, rethinking about it although there is no return value it is more readable the code with the old check `if (n == 0) return` at the beginning of the code. I will add a note with a reference to your comment, thanks for the advice." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-31T20:40:08.397", "Id": "248730", "ParentId": "248698", "Score": "2" } } ]
{ "AcceptedAnswerId": "248730", "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-31T13:00:21.450", "Id": "248698", "Score": "2", "Tags": [ "java", "beginner", "recursion" ], "Title": "Write a recursive function that takes a positive integer n and plots an N-by-N Hadamard pattern where N = 2^n" }
248698
<p>I'm drawing a square on a window using an implementation of <code>Xlib</code>. I put a colored pixel with <code>my_pixel_put</code> at a specific (<code>x</code>,<code>y</code>) coordinate.</p> <h2>Code to review</h2> <pre><code>#define LWST_VAL 200 #define HGHST_VAL 400 int main() { t_data img; //image data int x = LWST_VAL, y = LWST_VAL; // steps creating a window, creating an image while (x &gt;= LWST_VAL &amp;&amp; x &lt;= HGHST_VAL) { while ((y &gt; LWST_VAL &amp;&amp; y &lt; HGHST_VAL &amp;&amp; (x == LWST_VAL || x == HGHST_VAL)) || y == LWST_VAL || y == HGHST_VAL) { my_pixel_put(&amp;img, x, y, 456); y++; } if (x &gt; LWST_VAL &amp;&amp; x &lt; HGHST_VAL &amp;&amp; y == (LWST_VAL + 1)) y = HGHST_VAL; else { y = LWST_VAL; x++; } } // steps pushing image to the window, keep the window open } </code></pre> <h2>Output</h2> <p><a href="https://i.stack.imgur.com/LLbup.png" rel="noreferrer"><img src="https://i.stack.imgur.com/LLbup.png" alt="Square output" /></a></p> <h2>Question</h2> <p>Could anything improve the performance of my code ? Or its readability ?</p> <p>Any feedback appreciated.</p> <h1>Edit</h1> <p>This is the prototype of <code>my_pixel_put</code> :</p> <pre><code>void my_pixel_put(t_data *img, int x, int y, int colour) </code></pre> <p><code>img</code> is a structure containing data about the image such endiannes, bits per pixel, ... <code>x</code> and <code>y</code> are the width and height of the window. <code>colour</code> is the RGB colour of the pixel. (0,0) is actually the top left corner of the window (<em>I know don't ask me why</em>).</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-09-01T06:34:26.453", "Id": "487366", "Score": "2", "body": "Does your Xlib not expose *line* drawing functions that the GPU could accelerate, or that would only result in one message per line from the X client to the X server, rather than 1 per pixel? Or does `my_pixel_put` actually build a pixmap locally and then sync it in one big operation?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-09-01T14:47:51.230", "Id": "487430", "Score": "2", "body": "The canvas image is normally visualised as a 2-D pixel array `Pix[row,col]` so the top left will be (0,0). Due to a mix-up with porting a geographic info system to a power analysis system, I once ran a customer presentation where we drew the network for the whole of Wales upside down. I got an email from my boss with subject: `umop ap:sdn w,I :dlaH`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-09-02T13:35:00.503", "Id": "487541", "Score": "0", "body": "Is this the same Xlib? https://tronche.com/gui/x/xlib/graphics/drawing/XDrawLine.html" } ]
[ { "body": "<h3>Disclaimer</h3>\n<p>I don't have a working C compiler on my work computer, nor do I have Xlib available to me (I'm also not familiar with it, at all). That being said, given that we know our image is a square, you can do this with a single loop.</p>\n<h3>Use a simpler algorithm</h3>\n<p>The basic idea is that we know each corner of our square, and then by stepping through the length of a side, we can draw a pixel on each side of the square per iteration. This way, instead of nested looping, you do it all at once.</p>\n<pre><code>// assuming a coordinate system where 0,0 is the bottom-left corner of the image\n// starting at each corner, draw the corresponding clock-wise line\nfor (int pos = LWST_VAL; pos &lt;= HGHST_VAL++pos)\n{\n // The bottom line\n my_pixel_put(&amp;img, pos, LWST_VAL, 456);\n // The top line\n my_pixel_put(&amp;img, pos, HGHST_VAL, 456);\n // The left line\n my_pixel_put(&amp;img, LWST_VAL, pos, 456);\n // The right line\n my_pixel_put(&amp;img, HGHST_VAL, pos, 456);\n}\n</code></pre>\n<h3>Cache behavior</h3>\n<p>The one thing that occurs to me about this implementation is that you might not do quite as well from a caching perspective - the one benefit of doing things on a side-by-side basis is that you're more likely to be operating on data from the cache instead of from memory. I don't know how <code>&amp;img</code> is actually stored or what <code>my_pixel_put</code> is doing, so its hard to give more concrete advice about this.</p>\n<p>If you did encounter caching issues, short of changing things to process side-by-side (or maybe top + bottom in one loop, and left + right in another), there isn't a whole lot to do. A normal technique to handle cache churn is to use blocking to break up the loop. That won't help here, unfortunately - see below for why.</p>\n<p>Suppose we know the following (these numbers are made up):</p>\n<ul>\n<li>16 lines of data can be held in the cache</li>\n<li>4 integers can be held in the cache at the same time</li>\n<li><code>img</code> is a matrix stored as a row-wise vector, and <code>my_pixel_put</code> effectively becomes <code>img[WIDTH * y + x] = 456</code></li>\n<li><code>img</code> is aligned such that the left-most side of the square represents the start of a cache line (there will be many cache lines to get to the right side)</li>\n</ul>\n<p>Each iteration of our loop grabs 4 cache lines - one for each side of the square. The top and bottom will be able to re-use the cache line for the next three values, while the right and left will have to get a new cache line. We then have the following sequence for how many cache lines we get at a time:</p>\n<ol>\n<li>4</li>\n<li>6</li>\n<li>8</li>\n<li>10</li>\n<li>14</li>\n<li>16</li>\n<li>etc</li>\n</ol>\n<p>The 7th loop iteration would force some of the old data out of the cache. If we were going to be using data besides the border of the square (e.g. by filling it somehow) then it would be worthwhile to operate on 6x6 &quot;blocks&quot; of data, because then everything is in-cache instead of in-memory. Because we aren't using the interior of the square, however, we'll never actually get a benefit to blocking up the operation - most of those cache lines will always go to waste</p>\n<h3>Parallelization</h3>\n<p>Another benefit of this is that, if you wanted to parallelize this on a CPU or port it to a GPU, it'll be more straightforward. On a CPU, this is an embarrassingly parallel problem - assuming that <code>my_pixel_put</code> is thread-safe as long as you aren't modifying the same pixel, threading it should be trivial. On a GPU, the lack of conditional operations makes it a breeze as well.</p>\n<p>You may want to change your memory access patterns if you go parallel, but additional detail is left as an exercise for the reader. As a hint, for CPU-based parallelism each thread should generally be working on distinct pieces of work to avoid ruining cache coherence.</p>\n<h3>Looking at your code as written, without algorithm changes</h3>\n<p>Reviewing your actual code, there are some simple ways that you can improve readability &amp; maintainability without changing the algorithm much.</p>\n<ol>\n<li>I don't like your outer <code>while</code> loop - you basically just have a <code>for</code> loop, with some extra weirdness about the top vs bottom line.</li>\n<li>I have a very similar beef with your inner <code>while</code> loop - this one is even more obviously just a <code>for</code> loop.</li>\n<li>Some of your conditions that you pack into your <code>while</code> should be separate, if only for readability's sake. Several of them are obviously removed by switching to a <code>for</code> loop, while others are better suited as an <code>if</code> statement wrapping your loop.</li>\n<li>Your macro names are unnecessarily mangled - its okay to have vowels in your macros</li>\n<li>Is it really necessary to have these be macros?</li>\n</ol>\n<pre><code>for (int x_position = LWST_VAL; x_position &lt;= HGHST_VAL; ++x_position) \n{\n if (x_position == LWST_VAL || x_position == HGHST_VAL) {\n for (int y_position = LWST_VAL; y_position &lt;= HGHST_VAL; ++y_position) \n {\n my_pixel_put(&amp;img, x_position, y_position, 456);\n } \n } else {\n my_pixel_put(&amp;img, x_position, LWST_VAL, 456);\n my_pixel_put(&amp;img, x_position, HGHST_VAL, 456);\n }\n}\n</code></pre>\n<p>Whoops, I ended up rewriting it more than I meant to - I just couldn't make myself add another loop just because. To keep an equivalent number of loops, you could do something like this:</p>\n<pre><code>for (int side_count = 0; side_count &lt; 2; ++side_count) {\n for (int x_position = LWST_VAL; x_position &lt;= HGHST_VAL; ++x_position) \n {\n if (side_count == 0 &amp;&amp; (x_position == LWST_VAL || x_position == HGHST_VAL)) {\n for (int y_position = LWST_VAL; y_position &lt;= HGHST_VAL; ++x_position) \n {\n my_pixel_put(&amp;img, x_position, y_position, 456);\n } \n } else {\n my_pixel_put(&amp;img, x_position, side_count == 0 ? LWST_VAL : HGHST_VAL, 456);\n }\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-31T22:52:41.097", "Id": "487337", "Score": "0", "body": "They don't have to be macros, I thought it'd make my code more readable not to have numbers but rather macros." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-09-01T07:44:53.260", "Id": "487376", "Score": "2", "body": "Note nearby parallel pixel calls will devastate cache coherence (parallel threads must run 'away from each other' in CPU). Don't do that." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-09-01T13:23:38.677", "Id": "487402", "Score": "1", "body": "@MaxDZ8 Sure - when going parallel if your threads have poor work distribution you're going to have a bad time, but I already went into more detail than I intended/needed to on caching. I put a little caveat into there that MAPs need to change when going parallel" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-31T14:38:33.693", "Id": "248704", "ParentId": "248699", "Score": "10" } }, { "body": "<p>The real performance issue here is fairly simple: good performance is obtained by not repeating steps. The big step that you are doing repeatedly is to figure out where the pixel goes in the output space.</p>\n<p>If we consider @Dannano's</p>\n<pre><code>img[WIDTH * y + x] = 456;\n</code></pre>\n<p>We wind up doing that currently for every point. Multiplication is hard (at least classically, and still on simple machines), so the fewer times we do it, the better. Consider this function:</p>\n<pre><code>static void my_primitive_line_draw(pixel_t *ptr, size_t stride, unsigned count, pixel_t color)\n{\n while (count--) {\n *ptr = color;\n ptr = (pixel_t*) ( ((char *)ptr) + stride );\n /* or maybe:\n ptr += stride;\n */\n }\n}\n</code></pre>\n<p>Given a starting location and an appropriate stride, this can draw a vertical, horizontal, or 45 degree diagonal. Note that this should not be publicly accessible. It is too screwy if given the wrong parameters. But called from\n<code>my_line_draw(image_t, int x0, int y0, int x1, int y1, pixel_t color)</code>\nit provides a high performance implementation. FYI: Good values for stride are ((-WIDTH, 0, or +WIDTH) + (-1, 0, or +1)) * sizeof(pixel_t) (and omit the sizeof if you use the &quot;or maybe&quot; clause).</p>\n<p>The other thing that tends to be pricy is all the validation needed. For instance, your <code>my_pixel_put()</code> must validate: the image is valid, the x is in a legal range, the y is in a legal range, and the color is valid. But an internal function like my <code>my_primitive_line_draw()</code> can be called with known good parameters. So <code>my_line_draw()</code> must still do it, but only once per line.</p>\n<p>There are a number of similar tricks for high performance rendering of more complex shapes, though they tend to only work on well conditioned shapes.</p>\n<hr>\n<p>Having said all that, one other performance issue in your code is that convoluted looping structure. Just write two independent loops, one on x, in which you draw at x,LWST_VAL and x,HGHST_VAL, and a similar one on y.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-31T22:49:56.620", "Id": "248735", "ParentId": "248699", "Score": "8" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-31T13:25:06.997", "Id": "248699", "Score": "9", "Tags": [ "performance", "algorithm", "c", "image", "graphics" ], "Title": "Can I draw a square with pixels more efficiently?" }
248699
<p>I want to move two element of my array to the beginning. This solution works but I would like to know a better approach since using sort() twice is probably not the best.</p> <p>Array Input:</p> <pre><code>colors = [{name: yellow}, {name: blue}, {name: green}, {name: red}, {name: orange}] </code></pre> <p>JS Function:</p> <pre><code>sort(){ let green= colors.find(color=&gt; color.name === &quot;green&quot;) let red= colors.find(color=&gt; color.name === &quot;red&quot;) colors.sort(function(x,y){ return x == red? -1 : y == red? 1 : 0; }); colors.sort(function(x,y){ return x == green? -1 : y == green? 1 : 0; }); } </code></pre> <p>Output:</p> <pre><code>colors = [{name: green}, {name: red}, {name: yellow}, {name: blue}, {name: orange}] </code></pre> <p>PS: I want green to always the above red</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-31T14:54:17.937", "Id": "487254", "Score": "0", "body": "Do you care about the ordering of the other colors?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-31T14:56:17.093", "Id": "487256", "Score": "2", "body": "@TedBrownlow yes, the rest of the elements have to maintain the same order as they where before" } ]
[ { "body": "<p>Find the index of the <code>green</code> and <code>red</code> items, then remove them from the array with <code>splice</code>. Then you can make a properly ordered array by combining the removed items with the rest of the items in the original array:</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const colors = [{name: 'yellow'}, {name: 'blue'}, {name: 'green'}, {name: 'red'}, {name: 'orange'}]\nconst removeColor = colorToRemove =&gt; (\n colors.splice(\n colors.findIndex(({ name }) =&gt; name === colorToRemove),\n 1\n )[0]\n);\nconst green = removeColor('green');\nconst red = removeColor('red');\nconst newColors = [green, red, ...colors];\nconsole.log(newColors);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>Or, without mutation (it's good to avoid mutation when not necessary, it can make code a bit more predictable in most cases):</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const colors = [{name: 'yellow'}, {name: 'blue'}, {name: 'green'}, {name: 'red'}, {name: 'orange'}]\nconst getColor = colorToRemove =&gt; colors.find(({ name }) =&gt; name === colorToRemove);\nconst green = getColor('green');\nconst red = getColor('red');\nconst newColors = [green, red, ...colors.filter(({ name }) =&gt; name !== 'green' &amp;&amp; name !== 'red')];\nconsole.log(newColors);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>Also note:</p>\n<ul>\n<li>String literals require delimiters. <code>{name: yellow}</code> won't work - you want <code>{name: 'yellow'}</code>.</li>\n<li>If you aren't going to reassign a variable name (<em>most</em> of the time you should be able to avoid reassignment), <a href=\"https://softwareengineering.stackexchange.com/questions/278652/how-much-should-i-be-using-let-vs-const-in-es6\">always use <code>const</code></a>. Only use <code>let</code> when you must reassign.</li>\n<li>For readability, better to indent your code when entering a new block (such as a function).</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-31T19:32:44.987", "Id": "248722", "ParentId": "248700", "Score": "2" } }, { "body": "<p>I liked the @CertainPerformance solution, because you just need to find what you need(green and red), put in the order that you want to and just concat with the rest :) This was a good answer, in my humble opinion</p>\n<p>But another way to do the same is using an <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object\" rel=\"nofollow noreferrer\">Object</a> with <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment\" rel=\"nofollow noreferrer\">destructuring assigment</a></p>\n<p>That is:</p>\n<ol>\n<li>map every object with the color name</li>\n<li>find the colors with the key(color name) that you already know and want to order(green and red)</li>\n<li>put the others colors in one object with a <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters\" rel=\"nofollow noreferrer\">rest operator</a></li>\n<li>put in the order that you want to</li>\n</ol>\n<p>This way, you can avoid to iterate twice every time you want to search for a color</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const colors = [{name: 'yellow'}, {name: 'blue'}, {name: 'green'}, {name: 'red'}, {name: 'orange'}]\n\nconst sort = colors =&gt; {\n const obj = Object.assign(...colors.map(o =&gt; ({ [o.name]: o }) ))\n const { green, red, ...others } = obj;\n\n return [green, red, ...Object.values(others)];\n}\n\nconsole.log(sort(colors));</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>Notice that I followed the advice of use imutability that @CertainPerformance told, which I agree; in another words, for the same input that this function receive, it will always produce the same result</p>\n<p>Useful links:</p>\n<ul>\n<li><a href=\"https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/Array/map\" rel=\"nofollow noreferrer\">Array.prototype.map</a></li>\n<li><a href=\"https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/Object/assign\" rel=\"nofollow noreferrer\">Object.assign</a></li>\n<li><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/values\" rel=\"nofollow noreferrer\">Object.values</a></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-09-03T01:18:03.623", "Id": "248837", "ParentId": "248700", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-31T14:11:29.677", "Id": "248700", "Score": "4", "Tags": [ "javascript", "performance", "array", "sorting" ], "Title": "Move two element of an array to the front - Javascript" }
248700
<p>Two parties communicate over a network sending back and forth up to 100 messages. Each message sent is a response to the last received message and depends on it. This means that both parties have to wait idly for the response to arrive before they can carry on with computations. Speed is quite critical and deteriorates very quickly when the network has moderate latency (due to the many messages and unavoidable waiting for the response). The messages are not very large, hence bandwidth does not seem to matter much.</p> <p>Probably what I want to do can be achieved by using some library. If so, please point this out to me, preferably together with a demo or link to sources on how to use it. For lack of better alternatives I'm using (POSIX-API) TCP sockets here. I decided to use TCP rather than UDP because all data must be received in the correct order and the packet header size is not a relevant overhead, especially since latency is the issue.</p> <p>This was my first time using sockets and I surely made many mistakes, both specific to sockets as well as pure C++ (I'm using C++17 although the code also compiles with C++11). My problem seems very standard and most of the code is puzzled together from some tutorials on sockets but I was struggling to find detailed sources on best practices.</p> <p>Below is a simplified demo code that illustrates the way I handle the TCP logic. I tried to shorten it as much as possible but it is still quite long. Some comments:</p> <ul> <li><code>tcp_helpers.h</code> declares (AND defines for brevity of this post) functions containing all the TCP logic. The other two code files are an example application (main methods to run server and client). In my real code I encapsulate the TCP logic in classes, which internally call the functions shown here.</li> <li>My messages can be variable size and have custom-defined headers specifying the length. The contents of a message is an array of custom-defined C-structs. Aside from these structs only having fixed-size primitive-type fields and no further structure, I would like my network code to work with any such user-defined struct-type. This leads to a big problem with portability: my code will probably not work if the two communicating systems use different byte order or different struct alignment. I am currently postponing this issue unless there is a straightforward way to take care of it.</li> <li>I disable Nagle's algorithm to ensure the TCP packets are sent as soon as the message is ready. I learned about this from asking a <a href="https://stackoverflow.com/q/62691251/9988487">Stackoverflow question</a>.</li> </ul> <p>Some questions I have already:</p> <ol> <li>The first version of my <code>send_full_message</code> function (see linked Stackoverflow question) was making two sys-calls to <code>send</code>, once for the (custom) header (8 byte struct) and once for the actual message (array of structs). In this version I reduced it to a single sys-call by copying header and data into a buffer (using perhaps ugly C-style memory manipulation). I did not notice a difference in performance compared to the original (sending the header as a separate packet). Which method is perferable? Can this be achieved more elegantly?</li> <li>The pointer arithmetic in the <code>receive_structs</code> function seems ugly. What would be the best-practice solution here?</li> <li>Is there anything else I could do to make this faster (just as I had not known about Nagle's algorithm before asking)?</li> </ol> <pre><code>// tcp_helpers.h. // NOTE: Requires C++11, tested also with C++17. Using this code in the present form may be ill-advised. // This is not a true header file (contains all method definitions for brevity). #include &lt;vector&gt; #include &lt;iostream&gt; #include &lt;string&gt; #include &lt;sstream&gt; #include &lt;cerrno&gt; // for checking socket error messages #include &lt;cstdint&gt; // for fixed length integer types #include &lt;cstring&gt; // for memcpy #include &lt;unistd.h&gt; // POSIX specific #include &lt;sys/socket.h&gt; // POSIX specific #include &lt;netinet/in.h&gt; // POSIX specific #include &lt;netinet/tcp.h&gt; // POSIX specific #include &lt;arpa/inet.h&gt; // POSIX specific //////////////////// PROFILING /////////////////// #include &lt;chrono&gt; static auto start = std::chrono::high_resolution_clock::now(); // print a message with timestamp for rudimentary profiling. (I don't actually use this in my code) void print_now(const std::string &amp;message) { auto t2 = std::chrono::high_resolution_clock::now(); std::chrono::duration&lt;double&gt; time_span = t2 - start; std::cout &lt;&lt; time_span.count() &lt;&lt; &quot;: &quot; &lt;&lt; message &lt;&lt; std::endl; } //////////////////// PROFILING /////////////////// struct TCPMessageHeader { // Header for each message (I really use this). uint8_t protocol_name[4]; uint32_t message_bytes; }; struct ServerSends { // The server sends messages that are arrays of this struct (just an example). uint16_t a; uint32_t b; uint32_t c; }; typedef uint8_t ClientSends; // The client sends messages that are arrays of this (just an example). namespace TCP_Helpers { void disable_nagles_algorithm(int socket_fd) { const int enable_no_delay = 1; // Disable Nagle's algorithm for TCP socket to improve performance if (setsockopt(socket_fd, IPPROTO_TCP, TCP_NODELAY, &amp;enable_no_delay, sizeof(enable_no_delay))) { throw std::runtime_error(&quot;Failed to disble Nagle's algorithm by setting socket options&quot;); } } int init_client(const std::string &amp;ip_address, int port) { int sock_fd; struct sockaddr_in serv_addr{}; if ((sock_fd = socket(AF_INET, SOCK_STREAM, 0)) &lt; 0) { throw std::runtime_error(&quot;TCP Socket creation failed\n&quot;); } serv_addr.sin_family = AF_INET; serv_addr.sin_port = htons(port); // Convert IPv4 address from text to binary form if (inet_pton(AF_INET, ip_address.c_str(), &amp;serv_addr.sin_addr) &lt;= 0) { throw std::runtime_error(&quot;Invalid address/ Address not supported for TCP connection\n&quot;); } if (connect(sock_fd, (struct sockaddr *) &amp;serv_addr, sizeof(serv_addr)) &lt; 0) { throw std::runtime_error(&quot;Failed to connect to server.\n&quot;); } disable_nagles_algorithm(sock_fd); return sock_fd; } int init_server(int port) { int server_fd; int new_socket; struct sockaddr_in address{}; int opt = 1; int addrlen = sizeof(address); // Creating socket file descriptor if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == 0) { throw std::runtime_error(&quot;socket creation failed\n&quot;); } if (setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT, &amp;opt, sizeof(opt))) { throw std::runtime_error(&quot;failed to set socket options&quot;); } address.sin_family = AF_INET; address.sin_addr.s_addr = INADDR_ANY; address.sin_port = htons(port); // Forcefully attaching socket to the port if (bind(server_fd, (struct sockaddr *) &amp;address, sizeof(address)) &lt; 0) { throw std::runtime_error(&quot;bind failed&quot;); } if (listen(server_fd, 3) &lt; 0) { throw std::runtime_error(&quot;listen failed&quot;); } if ((new_socket = accept(server_fd, (struct sockaddr *) &amp;address, (socklen_t *) &amp;addrlen)) &lt; 0) { throw std::runtime_error(&quot;accept failed&quot;); } if (close(server_fd)) // don't need to listen for any more tcp connections (PvP connection). throw std::runtime_error(&quot;closing server socket failed&quot;); disable_nagles_algorithm(new_socket); return new_socket; } template&lt;typename NakedStruct&gt; void send_full_message(int fd, TCPMessageHeader header_to_send, const std::vector&lt;NakedStruct&gt; &amp;structs_to_send) { const size_t num_message_bytes = sizeof(NakedStruct) * structs_to_send.size(); if (header_to_send.message_bytes != num_message_bytes) { throw std::runtime_error(&quot;Trying to send struct vector whose size does not&quot; &quot; match the size claimed by message header&quot;); } print_now(&quot;Begin send_full_message&quot;); // copy header and structs vector contents to new vector (buffer) of bytes and sent via TCP. // Does not seem to be faster than sending two separate packets for header/message. Can the copy be avoided? std::vector&lt;uint8_t&gt; full_msg_packet(sizeof(header_to_send) + num_message_bytes); memcpy(full_msg_packet.data(), &amp;header_to_send, sizeof(header_to_send)); memcpy(full_msg_packet.data() + sizeof(header_to_send), structs_to_send.data(), num_message_bytes); // maybe need timeout and more error handling? size_t bytes_to_send = full_msg_packet.size() * sizeof(uint8_t); int send_retval; while (bytes_to_send != 0) { send_retval = send(fd, full_msg_packet.data(), sizeof(uint8_t) * full_msg_packet.size(), 0); if (send_retval == -1) { int errsv = errno; // from errno.h std::stringstream s; s &lt;&lt; &quot;Sending data failed (locally). Errno:&quot; &lt;&lt; errsv &lt;&lt; &quot; while sending header of size&quot; &lt;&lt; sizeof(header_to_send) &lt;&lt; &quot; and data of size &quot; &lt;&lt; header_to_send.message_bytes &lt;&lt; &quot;.&quot;; throw std::runtime_error(s.str()); } bytes_to_send -= send_retval; } print_now(&quot;end send_full_message.&quot;); } template&lt;typename NakedStruct&gt; std::vector&lt;NakedStruct&gt; receive_structs(int fd, uint32_t bytes_to_read) { print_now(&quot;Begin receive_structs&quot;); unsigned long num_structs_to_read; // ensure expected message is non-zero length and a multiple of the SingleBlockParityRequest struct if (bytes_to_read &gt; 0 &amp;&amp; bytes_to_read % sizeof(NakedStruct) == 0) { num_structs_to_read = bytes_to_read / sizeof(NakedStruct); } else { std::stringstream s; s &lt;&lt; &quot;Message length (bytes_to_read = &quot; &lt;&lt; bytes_to_read &lt;&lt; &quot; ) specified in header does not divide into required stuct size (&quot; &lt;&lt; sizeof(NakedStruct) &lt;&lt; &quot;).&quot;; throw std::runtime_error(s.str()); } // vector must have size &gt; 0 for the following pointer arithmetic to work // (this method must check this in above code). std::vector&lt;NakedStruct&gt; received_data(num_structs_to_read); int valread; while (bytes_to_read &gt; 0) // need to include some sort of timeout?! { valread = read(fd, ((uint8_t *) (&amp;received_data[0])) + (num_structs_to_read * sizeof(NakedStruct) - bytes_to_read), bytes_to_read); if (valread == -1) { throw std::runtime_error(&quot;Reading from socket file descriptor failed&quot;); } else { bytes_to_read -= valread; } } print_now(&quot;End receive_structs&quot;); return received_data; } void send_header(int fd, TCPMessageHeader header_to_send) { print_now(&quot;Start send_header&quot;); int bytes_to_send = sizeof(header_to_send); int send_retval; while (bytes_to_send != 0) { send_retval = send(fd, &amp;header_to_send, sizeof(header_to_send), 0); if (send_retval == -1) { int errsv = errno; // from errno.h std::stringstream s; s &lt;&lt; &quot;Sending data failed (locally). Errno:&quot; &lt;&lt; errsv &lt;&lt; &quot; while sending (lone) header.&quot;; throw std::runtime_error(s.str()); } bytes_to_send -= send_retval; } print_now(&quot;End send_header&quot;); } TCPMessageHeader receive_header(int fd) { print_now(&quot;Start receive_header (calls receive_structs)&quot;); TCPMessageHeader retval = receive_structs&lt;TCPMessageHeader&gt;(fd, sizeof(TCPMessageHeader)).at(0); print_now(&quot;End receive_header (calls receive_structs)&quot;); return retval; } } </code></pre> <pre><code>// main_server.cpp #include &quot;tcp_helpers.h&quot; int main() { int port = 20000; int socket_fd = TCP_Helpers::init_server(port); while (true) { // server main loop TCPMessageHeader rcv_header = TCP_Helpers::receive_header(socket_fd); if (rcv_header.protocol_name[0] == 0) // using first byte of header name as signal to end break; // receive message auto rcv_message = TCP_Helpers::receive_structs&lt;ClientSends&gt;(socket_fd, rcv_header.message_bytes); // for (ClientSends ex : rcv_message) // example &quot;use&quot; of the received data that takes a bit of time. // std::cout &lt;&lt; static_cast&lt;int&gt;(ex) &lt;&lt; &quot; &quot;; // std::cout &lt;&lt; std::endl &lt;&lt; std::endl; auto bunch_of_zeros = std::vector&lt;ServerSends&gt;(1000); // send a &quot;response&quot; containing 1000 structs of zeros TCPMessageHeader send_header{&quot;abc&quot;, 1000 * sizeof(ServerSends)}; TCP_Helpers::send_full_message(socket_fd, send_header, bunch_of_zeros); } exit(EXIT_SUCCESS); } </code></pre> <pre><code>// main_client.cpp #include &quot;tcp_helpers.h&quot; int main() { // establish connection to server and get socket file descriptor. int port = 20000; auto ip = &quot;127.0.0.1&quot;; int socket1_fd = TCP_Helpers::init_client(ip, port); std::cout &lt;&lt; &quot;connected.&quot; &lt;&lt; std::endl; for (int i = 0; i &lt; 20; ++i) { // repeat (for runtime statistics) sending and receiving arbitrary data // send a message containing 500 structs of zeros auto bunch_of_zeros = std::vector&lt;ClientSends&gt;(500); TCPMessageHeader send_header{&quot;abc&quot;, 500 * sizeof(ClientSends)}; TCP_Helpers::send_full_message(socket1_fd, send_header, bunch_of_zeros); // receive response TCPMessageHeader rcv_header = TCP_Helpers::receive_header(socket1_fd); auto rcv_message = TCP_Helpers::receive_structs&lt;ServerSends&gt;(socket1_fd, rcv_header.message_bytes); // for (ServerSends ex : rcv_message) // example &quot;use&quot; of the received data that takes a bit of time. // std::cout &lt;&lt; ex.a &lt;&lt; ex.b &lt;&lt; ex.c &lt;&lt; &quot; &quot;; // std::cout &lt;&lt; std::endl &lt;&lt; std::endl; } auto end_header = TCPMessageHeader{}; // initialized all fields to zero. &quot;end&quot; signal in this demonstration. TCP_Helpers::send_header(socket1_fd, end_header); exit(EXIT_SUCCESS); } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-31T17:53:19.397", "Id": "487279", "Score": "1", "body": "You need to look up libevent. This is how you write responsive socket based applications. The problem is that most read/writes to a socket block (so you are wasting cycles). What you want to do is when you have a blocking call to read/write the thread has the opportunity to go and do other work (no hang idly waiting on the socket). Using libevent a **single thread** can easily handle thousands of simultaneous connections without blocking on any single conversation stream." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-31T17:58:43.700", "Id": "487281", "Score": "1", "body": "Have a read of a the articles I wrote on sockets: https://lokiastari.com/series/" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-31T18:08:29.667", "Id": "487284", "Score": "0", "body": "In my application there is no other useful work that can be done between computing a message to be sent and receiving a response. The response is required. Also there will only ever be two communicating parties." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-31T19:38:35.620", "Id": "487307", "Score": "0", "body": "Then simply build something on top of the simple curl interface." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-31T19:42:24.760", "Id": "487311", "Score": "0", "body": "Now that I have read your code I would say there is an issue with keeping the same connection open. If it breaks your application is hard to reset to a know state. I would design it so that each message (request/reply) is independent and can thus by done over a new connection. This will make the application easier to reset to a known state if the connection is dropped/broken. Most client servers use this form of communication. This is then optimized at a lower level by allowing the reuse of an existing connection but that should be independent of the application layer." } ]
[ { "body": "<h2>Overview</h2>\n<p>You use a single connection for all communication. This will make it hard to fix a broken/dropped connection. Better to make each message (request/response) its own connection. You can re-use connections under the hood but the application does not need to know this.</p>\n<p>You are using a custom protocol. This is a bad idea. Use a standard protocol like HTTPS. This has a well defined and well supported set of libraries (that are all heavily tested). You can still use your binary messages on top of this.</p>\n<p>You are using a binary protocol. Not an application killer but this will make the code much more brittle. I would use a human readable text protocol (especially when you are building a first version). The human readability will help in debugging. You can always switch to binary later if you can see a difference in speed.</p>\n<p>I would use JSON over HTTP with TCP as the transport.</p>\n<p>Now there is a cost to using all these layers. But I would argue that speed of development will be increased by using them. Once you have a working prototype then you can update your application and remove/replace each of the layers with an appropriate more effecient layer. But get it working first.</p>\n<h2>Look at Question</h2>\n<blockquote>\n<p>Two parties communicate</p>\n</blockquote>\n<p>Summary Paragraph 1:</p>\n<ul>\n<li>Lots of messages</li>\n<li>Speed is critical</li>\n<li>Dominated by network latency</li>\n<li>Messages are large.</li>\n</ul>\n<p>You sort of contradict yourself. Speed is critical but network latency is an issue. The only thing that matters is network latency. Any language can write to a socket much faster than the network can transport that answer. So writing reading is not a real speed critical thing (especially with small messages).</p>\n<p>Now this can become an issue when you have a large messages and you make multiple large copies of the data then resources can be squeezed and this can have an effe t on speed.</p>\n<p>Also you want to be efficient enough that the server can read messages from thousands of different sockets (many users) without causing any issues. so writing clear simple code that gracefully handle blocking calls would be a good idea.</p>\n<hr />\n<blockquote>\n<p>Probably what I want to do can be achieved by using some library.</p>\n</blockquote>\n<p>Yes you want to use a library. Which one depends on how low you want to go.</p>\n<p>You can do it your self with libs like <code>select()/pselect()/epoll()</code>. Thats the basic hard rock ground. Its nice to understand this but probably not where you want to start.</p>\n<p>The next level up is a library called <code>libevent</code>. This handles a lot of the low level details and is a thin wrapper over one of<code> select()/pselect()/epoll()</code>. It is still very low level but it abstracts away a couple of platform dependencies so makes writing multi platform code easier.</p>\n<p>The next level up is probably <code>libcurl</code>. This has two interfaces. The <a href=\"https://curl.haxx.se/libcurl/c/\" rel=\"nofollow noreferrer\">Simple interface</a> (great for clients). Make a request get data back from the request. The <a href=\"https://curl.haxx.se/libcurl/c/libcurl-multi.html\" rel=\"nofollow noreferrer\">Multi interface</a> great for servers. The multi interface makes writing servers that are handling multiple requests relatively simple.</p>\n<p>I have written a lot of socket code that is avaialbe on the internet:</p>\n<p>A couple of articles here:</p>\n<ul>\n<li><a href=\"https://lokiastari.com/blog/2016/04/08/socket-programming-in-c-version-1/index.html\" rel=\"nofollow noreferrer\">Socket Programming in C</a></li>\n<li><a href=\"https://lokiastari.com/blog/2016/04/09/socket-read/index.html\" rel=\"nofollow noreferrer\">Socket Read/Write</a></li>\n<li><a href=\"https://lokiastari.com/blog/2016/05/26/c-plus-plus-wrapper-for-socket/index.html\" rel=\"nofollow noreferrer\">C++ Wrapper for Socket</a></li>\n<li><a href=\"https://lokiastari.com/blog/2016/05/29/socket-protocols/index.html\" rel=\"nofollow noreferrer\">Socket Protocols</a></li>\n</ul>\n<p>There are examples to illustrate all these points in this github repo:</p>\n<p><a href=\"https://github.com/Loki-Astari/Examples\" rel=\"nofollow noreferrer\">https://github.com/Loki-Astari/Examples</a></p>\n<p>I have written a very basic wrapper around a socket that makes it wok just like a C++ std::istream:</p>\n<p><a href=\"https://github.com/Loki-Astari/ThorsStream/blob/master/doc/example1.md\" rel=\"nofollow noreferrer\">https://github.com/Loki-Astari/ThorsStream/blob/master/doc/example1.md</a></p>\n<hr />\n<blockquote>\n<p>I decided to use TCP rather than UDP because all data must be received in the correct order and the packet header size is not a relevant overhead, especially since latency is the issue.</p>\n</blockquote>\n<p>Sure. Also UDP is broadcast so you are basically transmitting your data to the world. Also I am not sure you can use SSL with UDB so that becomes a real security issue.</p>\n<hr />\n<h2>Code Review:</h2>\n<p>Looks like you are using a binary protocl.</p>\n<pre><code>struct TCPMessageHeader { // Header for each message (I really use this).\n uint8_t protocol_name[4];\n uint32_t message_bytes;\n};\n</code></pre>\n<p>Most systems nowadays have moved away from this. Binary protocols are very brittle and hard to change over time. A better bet is to use a soft human readable protocol like <code>JSON</code>. If you don't want to use a human readable one pick a binary protocol that is already supported (like <code>BSON</code>).</p>\n<hr />\n<p>In C++ we put everything in a namespace for a reason. Use the C++ version of types not the C version.</p>\n<pre><code>struct ServerSends { // The server sends messages that are arrays of this struct (just an example).\n uint16_t a; // std::unint16_t &lt;&lt; C++ version don't use the C\n uint32_t b;\n uint32_t c;\n};\n</code></pre>\n<hr />\n<p>The Client object is an integer?</p>\n<pre><code>typedef uint8_t ClientSends; \n</code></pre>\n<p>Also this is the old way of declaring a type-alias. Use the modern version it is simpler to read.</p>\n<pre><code>using ClientSends = std::uint8_t;\n</code></pre>\n<hr />\n<p>I have no idea what <code>Nagle's</code> algorithm is. But thanks for the name at least I can now look it up.</p>\n<pre><code>namespace TCP_Helpers {\n void disable_nagles_algorithm(int socket_fd) {\n const int enable_no_delay = 1; // Disable Nagle's algorithm for TCP socket to improve performance\n if (setsockopt(socket_fd, IPPROTO_TCP, TCP_NODELAY, &amp;enable_no_delay, sizeof(enable_no_delay))) {\n throw std::runtime_error(&quot;Failed to disble Nagle's algorithm by setting socket options&quot;);\n }\n }\n</code></pre>\n<p>If you are going to disable something. Then you need to explain why. Comments are great place to document &quot;WHY&quot; you are doing something. I would write an explanation about why &quot;Nagle's&quot; algorithm is causing speed issues and a docuemtned experiments on what you did to show this.</p>\n<p>Most of what I read about Nagle's algorithm its a bad idea to turn it off.</p>\n<p>But for real time communication is one of the few times where it would be useful. If this is your use case buffering the message like you do then sending it as a single object (rather than getting each object to write to the stream) and disabling Nagle's algorithm seem to be the best choice. But saying that its not clear from your code that this is necessary so please add some detailed documents about why you are disabling Nagle's algorithm.</p>\n<hr />\n<p>The <code>init_client()</code> looks good.</p>\n<p>This is supposed to zero initialize the structure.</p>\n<pre><code> struct sockaddr_in serv_addr{}; // That guarantees a zero - init\n // I would have to look up if that\n // is the same as a zero fill with\n // C structures. \n\n\n struct sockaddr_in serv_addr = {0}; // That guarantees a zero fill.\n</code></pre>\n<hr />\n<p>Try not to use <code>C</code> like cast.</p>\n<pre><code> if (connect(sock_fd, (struct sockaddr *) &amp;serv_addr, sizeof(serv_addr)) &lt; 0) {\n</code></pre>\n<p>Make it vey obvious in your code that you have a dangerious cast by using the C++ version that stickout like a saw thumb and makes sure your code is givent the required scruteny.</p>\n<pre><code> if (connect(sock_fd, reinterpret_cast&lt;sockaddr*&gt;(&amp;serv_addr), sizeof(serv_addr)) &lt; 0) {\n</code></pre>\n<hr />\n<p>The <code>intit_server()</code> is doing more than it should. <strike>You are also leaking the original socket file descriptor.</p>\n<p>The call to <code>accept()</code> creates a new socket connection. But the original socket <code>server_fd</code> is still open and listening (though you don't have anybody listening). The normal pattern would be more like this:</strike></p>\n<pre><code> initServer()\n server_fd = socket();\n bind(server_fd);\n\n while(!finished)\n {\n listen(server_fd);\n new_socket = accept(server_fd);\n\n workerQueue.add(newSocket); // You then have another **SINGLE** thread\n // that handles all the worker queue\n // sockets\n\n\n\n // If you use a library like libevent\n // You can do this and all the connections\n // with the same thread.\n }\n close(server_fd);\n</code></pre>\n<hr />\n<p>Not sure that copying the data into a single message byes you anything.</p>\n<pre><code> std::vector&lt;uint8_t&gt; full_msg_packet(sizeof(header_to_send) + num_message_bytes);\n memcpy(full_msg_packet.data(), &amp;header_to_send, sizeof(header_to_send));\n memcpy(full_msg_packet.data() + sizeof(header_to_send), structs_to_send.data(), num_message_bytes);\n</code></pre>\n<p>The sockets are themselves already buffered. So you are copying the data into a buffer then writing the buffer to the socket which is buffering up the writes. The advantage to you is that it makes writing the below loop easier. The disadvantage is that your objects need to be plain old data. It would be nice to have objects that know how to serialize themselves to the socket stream.</p>\n<p>** Have read a bit more about comms. This is a good idea if you have disabled Nagle's algorithm as it will create the optimally sized packages and thus reduce the overhead of the TCP/IP package header. You are basically taking over the job of the algorithm and doing the buffering.</p>\n<hr />\n<p>Stop using C algorithms when there are much better documented C++ versions:</p>\n<pre><code> memcpy(full_msg_packet.data(), &amp;header_to_send, sizeof(header_to_send));\n\n // could be written as:\n\n // may need to add some casts or access functions.\n std::copy(&amp;header_to_send, &amp;header_to_send + sizeof(header_to_send), full_msg_packet.data());\n\n \n</code></pre>\n<hr />\n<p><strong>BUG HERE</strong></p>\n<p>You don't use how many bytes you have already sent. So if it requires multiple calls to <code>send()</code> then you are resening some of the data.</p>\n<pre><code> send_retval = send(fd, full_msg_packet.data(), sizeof(uint8_t) * full_msg_packet.size(), 0);\n\n\n // Should be:\n bytesAlreadySent = 0;\n\n ...\n\n send_retval = send(fd,\n full_msg_packet.data() + bytesAlreadySent,\n sizeof(uint8_t) * full_msg_packet.size() - bytesAlreadySent,\n 0);\n\n ....\n\n bytesAlreadySent += send_retval;\n</code></pre>\n<hr />\n<p>Common issue here:</p>\n<pre><code> if (send_retval == -1) {\n int errsv = errno; // from errno.h\n std::stringstream s;\n s &lt;&lt; &quot;Sending data failed (locally). Errno:&quot; &lt;&lt; errsv\n &lt;&lt; &quot; while sending header of size&quot; &lt;&lt; sizeof(header_to_send)\n &lt;&lt; &quot; and data of size &quot; &lt;&lt; header_to_send.message_bytes &lt;&lt; &quot;.&quot;;\n throw std::runtime_error(s.str());\n }\n</code></pre>\n<p>Not all errors are catastrophic. Some errors are programming bugs and should be found during testing and removed. If these happen in production you need to stop the application by throwing a non catchable exception. Others are real problems that you should simply throw an exception for but there is a third set which simply mean the system was sudeenly busy. In these you should simply retry the send.</p>\n<hr />\n<p>Why are you making a copy of the header object?</p>\n<pre><code> void send_header(int fd, TCPMessageHeader header_to_send) {\n</code></pre>\n<p>Pass by const reference.</p>\n<hr />\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-09-02T08:58:36.630", "Id": "487498", "Score": "0", "body": "Thank you very much for the detailed answer. I will look at the libraries you suggested. In your code review I did not understand what you mean by \"I leak the server file descriptor\". If close the associated socket (which I do), the server is no longer listening for connections, right? In my use case there will only ever be two communicating parties. The server need not listen for further connections (at least until the existing connection is broken), which I take to mean that using a queue or threads has no benefit." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-09-02T13:27:54.637", "Id": "487538", "Score": "0", "body": "The question of how to correctly zero-init/zero-fill C-structs in C++ seems more complicated than I thought (see, e.g., https://stackoverflow.com/a/61240590/9988487). Still not sure what is best to use as default, although in the present case `T var{};`, `T var = {};` and `T var = {0};` (suggested by the answer) seem to give the same results." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-09-02T17:51:19.057", "Id": "487568", "Score": "0", "body": "@AdomasBaliuka There are some subtitles. Zero-init: Will initialize each member to a zero value (assuming they are all POD (this case holds; it is a C structure)). Zero-fill: Will initialize the memory used by the object to all zero bytes. All things being equal these should be the same thing. **BUT** there are parts of the object that may not be covered by members (the padding). If there is any padding in the object then this may potentially be left uninitialized. Since this is a C object I would stick to the C way of initializing it (like all the examples on the web) and use `T var = {0};`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-09-02T17:55:43.503", "Id": "487569", "Score": "0", "body": "@AdomasBaliuka You are correct you don't leak the server file descriptor. I missed that in your code. I have struck out that comment. But left in the part about normal use case for future engineers that would read the code." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-31T18:54:38.983", "Id": "248719", "ParentId": "248701", "Score": "5" } }, { "body": "<p>I agree with most of what Martin York wrote, except perhaps the remark about binary protocols. Sometimes sending structs is just the right thing to do: it's very fast, reasonably compact, and requires no conversion to and from some other format, which can waste CPU cycles and perhaps require lots of external dependencies. But, unless you think about extensibility up front, you can easily lock yourself into a set of structs without the possibility to migrate gracefully to newer versions. Your code only handles structs for which the size is known up front. You might consider adding functionality to handle &quot;structs&quot; with a variable size.</p>\n<p>Apart form that I just want to add these things:</p>\n<blockquote>\n<ol>\n<li>The first version of my send_full_message function (see linked Stackoverflow question) was making two sys-calls to send, once for the (custom) header (8 byte struct) and once for the actual message (array of structs). In this version I reduced it to a single sys-call by copying header and data into a buffer (using perhaps ugly C-style memory manipulation). I did not notice a difference in performance compared to the original (sending the header as a separate packet). Which method is perferable? Can this be achieved more elegantly?</li>\n</ol>\n</blockquote>\n<p>There is a third option which uses only one syscall and does not require copying the data, and that is by using <a href=\"https://linux.die.net/man/2/sendmsg\" rel=\"nofollow noreferrer\"><code>sendmsg</code></a>. It allows you to specify a list of discontiguous memory regions that need to be sent over a socket as if it was one contiguous block. It requires some more lines of code to set up the structs necessary to pass to <code>sendmsg()</code>, but some of them can perhaps be prepared once and then reused.</p>\n<blockquote>\n<ol start=\"3\">\n<li>Is there anything else I could do to make this faster (just as I had not known about Nagle's algorithm before asking)?</li>\n</ol>\n</blockquote>\n<p>Disabling Nagle's is trading in bandwidth for latency. Instead of doing this, consider using <a href=\"https://stackoverflow.com/questions/3761276/when-should-i-use-tcp-nodelay-and-when-tcp-cork\"><code>TCP_CORK</code></a>. When the application knows it wants to send a bunch of data, and wants the packets to be sent off without delay but with the best use of the network MTU as possible, it should enable <code>TCP_CORK</code> at the start of that bunch of data, and when it sent everything, it disables <code>TCP_CORK</code>, which will then ensure that any remaining data in the send buffer will be sent immediately (assuming the congestion window allows it). If you would disable Nagle instead, and want to send lots of small structs in a row, then each struct would be sent as a separate packet for no good reason.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-31T20:15:35.163", "Id": "248727", "ParentId": "248701", "Score": "3" } } ]
{ "AcceptedAnswerId": "248719", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-31T14:22:06.880", "Id": "248701", "Score": "4", "Tags": [ "c++", "socket", "tcp" ], "Title": "C++ sockets: Sending structs for P2P communication" }
248701
<p>I'm learning how to use SequelizeJS. What i found was that (at least for me) the definition of the DB model was too invasive in my code when creating object. I was thinking that the user of your model should not have to learn how to use sequelize (or even that i use it at all)</p> <p>So I created 2 class that add a layer on top of the model, I would want to know if it is normal/OK as the abstraction is already something that Sequelize aim to provide. I would also welcome critics of my abastraction</p> <p>Models classes :</p> <pre><code>import { Sequelize, Model, DataTypes } from 'sequelize'; const sequelize = new Sequelize({ dialect: 'sqlite', storage: 'database.sqlite' }); export class User { public sqlObject: Promise&lt;UserModel&gt;; constructor( public username: string, public birthdate?: Date, public team?: Team ) { if(team) { this.createWithTeam(team); } } private async createWithTeam(team: Team) { const sql = await team.sqlObject; console.dir(sql); (sql as any).createUser({ username: this.username, birthdate: this.birthdate, }); } } export class Team { public sqlObject: Promise&lt;TeamModel&gt;; constructor( public name: string ) { this.sqlObject = TeamModel.findOrCreate({ where: { name: this.name } }).then(([o]) =&gt; o); } } class UserModel extends Model { static TeamModel: any; } UserModel.init({ username: DataTypes.STRING, birthday: DataTypes.DATE }, { sequelize, modelName: 'user' }); class TeamModel extends Model { static UserModel: any; }; TeamModel.init({ name: DataTypes.STRING }, { sequelize, modelName: 'team' }); TeamModel.UserModel = TeamModel.hasMany(User); UserModel.TeamModel = UserModel.belongsTo(TeamModel); </code></pre> <p>Usage :</p> <pre><code>const team1 = new Team('Belgium Red Devils'); const player1 = new User('Laurent', new Date('01-01-1990'), team1); </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-31T14:33:39.187", "Id": "248702", "Score": "1", "Tags": [ "typescript", "orm" ], "Title": "SequelizeJS: Abstraction of the ORM" }
248702
<p>Getting started in VB.net I've written this console calculator based heavily off Nicholas Dingle youtube channel (in case it looks familiar). What I want to do is have a separate sub called <code>Operation(parameter)</code> and take the <code>if</code> statements out of <code>CollectNumbers()</code> since it doesn't make sense to have them in that sub. To make this happen I think what i'll end up needing to do is use Enum for the different operations, but don't know how to implement it. I think also the calling of <code>CollectNumbers()</code> will have to be reworked as well. I'm not looking for anyone to write it out, but a nudge in the right direction or tips would be very helpful.</p> <pre><code>Imports System.Runtime.Remoting.Services Imports System.Threading Module Module1 Sub Main() Menu() End Sub 'Enum operations ' Add = 1 ' Subtract = 2 ' Multiply = 3 ' Divide = 4 'End Enum Sub Menu() Dim selection As String Console.Clear() Console.WriteLine(&quot;Say Hello To My Little Calculator!&quot;) Console.WriteLine() 'print blank line Console.WriteLine(&quot;Please press...&quot;) Console.WriteLine() 'print blank line Console.WriteLine(&quot;(A) to Add&quot;) Console.WriteLine(&quot;(S) to Subtract&quot;) Console.WriteLine(&quot;(M) to Multiply&quot;) Console.WriteLine(&quot;(D) to Divide&quot;) Console.WriteLine(&quot;(Q) to Quit&quot;) selection = Console.ReadLine If selection.ToUpper = &quot;Q&quot; Then Console.WriteLine(&quot;Exiting...&quot;) Thread.Sleep(2000) Environment.Exit(0) ElseIf selection.ToUpper = &quot;A&quot; Then CollectNumbers(&quot;add&quot;) ElseIf selection.ToUpper() = &quot;S&quot; Then CollectNumbers(&quot;subtract&quot;) ElseIf selection.ToUpper() = &quot;M&quot; Then CollectNumbers(&quot;multiply&quot;) ElseIf selection.ToUpper() = &quot;D&quot; Then CollectNumbers(&quot;divide&quot;) Else Console.WriteLine(&quot;Please choose a valid option from the list...&quot;) Thread.Sleep(2000) Menu() End If End Sub Sub CollectNumbers(operation As String) Dim num1 As Integer Dim num2 As Integer Console.WriteLine(&quot;Please enter the first number...&quot;) num1 = CInt(Console.ReadLine) Console.WriteLine(&quot;Please enter the second number...&quot;) num2 = CInt(Console.ReadLine) If operation = &quot;add&quot; Then Console.WriteLine(Add(num1, num2)) ElseIf operation = &quot;subtract&quot; Then Console.WriteLine(Subtract(num1, num2)) ElseIf operation = &quot;divide&quot; Then Console.WriteLine(Divide(num1, num2)) ElseIf operation = &quot;multiply&quot; Then Console.WriteLine(Multiply(num1, num2)) End If Console.ReadLine() Menu() End Sub Function Add(a As Integer, b As Integer) As Double Return a + b End Function Function Subtract(a As Integer, b As Integer) As Double Return a - b End Function Function Multiply(a As Integer, b As Integer) As Double Return a * b End Function Function Divide(a As Integer, b As Integer) As Double Return a / b End Function End Module </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-31T18:32:47.973", "Id": "487287", "Score": "1", "body": "Thanks for the ping, I've re-read your post and glanced at the code, and you're right obviously; please accept my apologies. Consider rewording the \"*I think what i'll end up needing to do is use Enum for the different operations, but don't know how to implement it*\" part: it's what made me make the call, and likely what made others do the same." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-31T18:35:34.750", "Id": "487288", "Score": "0", "body": "@MathieuGuindon Understood. Still learning the etiquette on these exchange sites." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-31T18:40:21.420", "Id": "487289", "Score": "1", "body": "No problem! [How to get the best value out of CR](https://codereview.meta.stackexchange.com/q/2436/23788) is without a doubt one of the best resources available to help with that." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-31T17:49:36.890", "Id": "248715", "Score": "3", "Tags": [ "vb.net", "enum" ], "Title": "I want to clean up this console app calculator (VB.net)" }
248715
<p>I'm working on a project (it's a language), and for that project, I decided to go with a low-level C++ style, so that means making my own data types. I recently got done making my own string class implementation. This is actually the first time I've made a string class before, so I may be doing a lot of things wrong. As far as I know, I tested it, and it works and does what it's intended to so, but I may be overlooking something or something may not be the best practice.</p> <p>My goal here was to make a &quot;low-level C++&quot; string class, meaning I'd create everything myself without using any headers.</p> <p>I have everything in one <code>.h</code> file, and I know that not really the best way to do it, but I'm not really a big fan of splitting up my code when it's only a small class.</p> <p>Here's an overview of the methods and what they do, and why I chose them (note that this is not the actual <code>.h</code> file, I'm just showing this to provide some context and an overview of what I'm doing):</p> <pre class="lang-cpp prettyprint-override"><code>class string { public: string(); string(const char* buffer); string(const string&amp; buffer); ~string(); public: string&amp; operator=(const char* buffer); string&amp; operator=(const string&amp; buffer); void operator+=(char buffer); void operator+=(const char* buffer); void operator+=(const string&amp; buffer); bool operator==(const char* buffer) const; bool operator==(const string&amp; buffer) const; bool operator!=(const char* buffer) const; bool operator!=(const string&amp; buffer) const; char operator[](int index) const; char&amp; operator[](int index); public: int length() const; // returns the actual string const char* get() const; private: int str_len(const char* buffer) const; // given a block of memory 'dest', fill that with characters from 'buffer' void str_cpy(char* dest, int dest_size, const char* buffer); void str_cpy(char* dest, int dest_size, const string&amp; buffer); // allocate a given size of memory char* str_alc(int size); private: int size; char* str; }; </code></pre> <p>So as you can see, it's not really anything special, just some basic functions that should be enough for my project. A few comments on the code:</p> <p>I chose to add a <code>get()</code> method instead of something like <code>operator const char*()</code> since I feel like the operator overloading would be enough, and I want to make accessing the actual string more explicit.</p> <p>Also a note on the private methods, those are basically very similar to the methods that can be found in the <code>&lt;string.h&gt;</code> header, like <code>strncpy()</code> and <code>str_len()</code>.</p> <p>Here's the actual <code>string.h</code> file:</p> <pre><code>#pragma once namespace night { // 'night' is the project I'm working on class string { public: string() { size = 0; str = str_alc(1); } string(const char* buffer) { size = str_len(buffer); str = str_alc(size + 1); str_cpy(str, size + 1, buffer); } string(const string&amp; buffer) { size = buffer.size; str = str_alc(size + 1); str_cpy(str, size + 1, buffer); } ~string() { delete[] str; } public: string&amp; operator=(const char* buffer) { delete[] str; size = str_len(buffer); str = str_alc(size + 1); str_cpy(str, size + 1, buffer); return *this; } string&amp; operator=(const string&amp; buffer) { delete[] str; size = buffer.size; str = str_alc(size + 1); str_cpy(str, size + 1, buffer); return *this; } void operator+=(char buffer) { char* temp = str_alc(size + 2); str_cpy(temp, size + 2, str); temp[size] = buffer; temp[size + 1] = '\0'; delete[] str; size += 1; str = temp; } void operator+=(const char* buffer) { size += str_len(buffer); char* temp = str_alc(size + 1); str_cpy(temp, size + 1, str); str_cpy(temp, size + 1, buffer); delete[] str; str = temp; } void operator+=(const string&amp; buffer) { size += buffer.size; char* temp = str_alc(size + 1); str_cpy(temp, size + 1, str); str_cpy(temp, size + 1, buffer); delete[] str; str = temp; } bool operator==(const char* buffer) const { if (size != str_len(buffer)) return false; for (int a = 0; a &lt; size; ++a) { if (str[a] != buffer[a]) return false; } return true; } bool operator==(const string&amp; buffer) const { return operator==(buffer.str); } bool operator!=(const char* buffer) const { return !operator==(buffer); } bool operator!=(const string&amp; buffer) const { return !operator==(buffer.str); } char operator[](int index) const { if (index &lt; 0 || index &gt;= size) throw &quot;[error] index is out of range&quot;; return str[index]; } char&amp; operator[](int index) { if (index &lt; 0 || index &gt;= size) throw &quot;[error] index is out of range&quot;; return str[index]; } public: int length() const { return size; } const char* get() const { return str; } private: int str_len(const char* buffer) const { int length = 0; for (int a = 0; buffer[a] != '\0'; ++a) length += 1; return length; } void str_cpy(char* dest, int dest_size, const char* buffer) { int start = 0; while (dest[start] != '\0') start += 1; if (dest_size - start &lt; str_len(buffer)) throw &quot;[fatal error] function 'void str_cpy(char* dest, const char* buffer)' does not have enough space&quot;; for (int a = 0; a &lt; str_len(buffer); ++a) dest[start + a] = buffer[a]; dest[start + str_len(buffer)] = '\0'; } void str_cpy(char* dest, int dest_size, const string&amp; buffer) { int start = 0; while (dest[start] != '\0') start += 1; if (dest_size - start &lt; buffer.size) throw &quot;[fatal error] function 'void str_cpy(char* dest, const string&amp; buffer)' does not have enough space&quot;; for (int a = 0; a &lt; buffer.size; ++a) dest[start + a] = buffer.str[a]; dest[start + buffer.size] = '\0'; } char* str_alc(int size) { char* buffer; try { // set the new string to contain null-terminators by default buffer = new char[size]{ '\0' }; } catch (...) { throw &quot;[fatal error] function 'char* str_alc(int size)' cannot allocate enough memory&quot;; } return buffer; } private: int size; char* str; }; } // namespace night </code></pre> <p>And just as an example, here's how you would use it:</p> <pre class="lang-cpp prettyprint-override"><code>int main() { night::string test = &quot;class&quot;; test += ' '; test += &quot;string&quot;; std::cout &lt;&lt; test.get() &lt;&lt; '\n'; night::string test1 = &quot;string class&quot;; test = test1; test[0] = 'S'; test[7] = 'C'; std::cout &lt;&lt; test.get() &lt;&lt; '\n'; night::string test2 = &quot;String Class&quot;; std::cout &lt;&lt; (test == test2) &lt;&lt; '\n'; std::cout &lt;&lt; (test != test2) &lt;&lt; '\n'; } </code></pre> <p>Here's my primary area of concern:</p> <ol> <li><p>Do I need a move constructor and move assignment operator? I know those aren't necessary, but would they make a big difference in this case?</p> </li> <li><p>Are the private methods efficient? Could they be improved?</p> </li> <li><p>Is the method <code>str_alc()</code> good? Like is it good practice to wrap <code>new</code> in a try-catch statement? And should I fill the string with <code>\0</code>s by default? Or is that causing more harm than good?</p> </li> </ol> <p>Also a minor question I have is if the parameter name <code>buffer</code> is the right choice? I'm not really sure what to call the parameters...</p> <p>Any other feedback is also highly appreciated!</p> <p>Thanks!</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-09-01T09:21:00.967", "Id": "487382", "Score": "0", "body": "`std::size_t` would be better for sizes and indices." } ]
[ { "body": "<p>I might be missing something but why not <code>std::string</code>? I fail to understand why you cannot use STL or say other open source libraries. You gave some explanation but I fail to understand it. Utilizing STL and open source libraries will save you a ton of development and debugging time.</p>\n<p>For you string implementation - <strong>Major Issues:</strong></p>\n<ol>\n<li><p>Adding a single character results in a reallocation which is terrible in terms of memory and performance. Normally, one holds a reserve size and increases it exponentially (x2 or x1.5 each time). So you won't need to apply reallocation each time somebody adds a single character or more at times.</p>\n</li>\n<li><p>It lacks short string optimization. When the string is short enough, say under 32 characters, then you shouldn't make a dynamic allocation and instead store the data locally. For this purpose you'll likely need extra buffer in the string class. This is important as most strings are fairly short.</p>\n</li>\n</ol>\n<p>Besides, these issues you should support more or less the same features that <code>std::string</code> supports. Take a look at its API on <a href=\"https://en.cppreference.com/w/cpp/string/basic_string\" rel=\"nofollow noreferrer\">cppreference</a>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-31T19:04:06.837", "Id": "487294", "Score": "0", "body": "There's not really any practical reason for doing so, but, aside from the reason that I wan't this to be a little \"lower level\", it's also more fun that way in a sense." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-31T19:07:52.537", "Id": "487296", "Score": "0", "body": "Also when you talk about short string optimization, do you mean another buffer like `char* short_str = new char[32]`, and I'll use that everytime the string is under 32 characters?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-31T19:46:55.300", "Id": "487313", "Score": "1", "body": "@DynamicSquid ... No, short string optimization means that you have extra member `char buffer[32];` and you don't do any memory allocations when strings are short - instead data points towards the buffer. Though, there are other ways to implement it. The reason for it is that dynamic allocation is a relatively heavy operation and many small allocations might result in memory fragmentation issues - which will slow down the program over time." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-09-01T05:04:29.080", "Id": "487364", "Score": "0", "body": "@ALX23z Generally short string optimization does not use a separate `char buffer[32]` member. Rather, it re-purposes the storage normally used for the string's capacity and/or the pointer to its external buffer when the string is small enough to fit in that space (though some implementations make that storage slightly bigger than needed to store just the capacity/pointer)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-09-01T10:48:00.657", "Id": "487391", "Score": "0", "body": "@MilesBudnek that depends on implementation. Heard a talk on this topic with some smart memory repurposing. Unfortunately it results in most basic operations having a more complicated logic instead of just accessing memory - so author shifted towards a simpler buffer like implementation for better performance." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-31T18:57:37.677", "Id": "248720", "ParentId": "248717", "Score": "4" } }, { "body": "<p>Why do you convert an exception that has meaning into a meaningless string?</p>\n<pre><code>char* str_alc(int size)\n{\n char* buffer;\n\n try {\n // set the new string to contain null-terminators by default\n buffer = new char[size]{ '\\0' };\n }\n catch (...) {\n throw &quot;[fatal error] function 'char* str_alc(int size)' cannot allocate enough memory&quot;;\n }\n\n return buffer;\n}\n</code></pre>\n<p>How the error is reported will ultimately depend on where it is caught. You should not simply re-throw a string. Catch the exception at the point you are reporting errors and convert to an appropriate error message at that point. Or throw a more meaningful exception type (not a string).</p>\n<p>Also if you are going to make this check then simply use the non-throwing version of new and then validate the buffer is not null and throw your new exception.</p>\n<hr />\n<p>Don't reinvent exiting functions:</p>\n<pre><code>int str_len(const char* buffer) const\n</code></pre>\n<p>There is already a C-function for this and I guarantee that it is <strong>NOT</strong> slower than your version and more than likely an order of magnitude faster.</p>\n<pre><code>void str_cpy(char* dest, int dest_size, const char* buffer)\n</code></pre>\n<p>Again there are already C-String copying functions. If you are going to re-invent them use the C++ algorithms to copy the bytes around rather than manually writing loops.</p>\n<hr />\n<p>If you are comparing two string objects. You devolve into comparing a string object to a C-String as the most general case.</p>\n<pre><code>bool operator==(const char* buffer) const\n{\n if (size != str_len(buffer))\n return false;\n\n for (int a = 0; a &lt; size; ++a)\n {\n if (str[a] != buffer[a])\n return false;\n }\n\n return true;\n}\n\nbool operator==(const string&amp; buffer) const\n{\n return operator==(buffer.str);\n}\n\nbool operator!=(const char* buffer) const\n{\n return !operator==(buffer);\n}\n\nbool operator!=(const string&amp; buffer) const\n{\n return !operator==(buffer.str);\n}\n</code></pre>\n<p>As a result you are <strong>computing</strong> the string length for an object that you already know the string length for!</p>\n<hr />\n<p>You have implemented a checked <code>operator[]</code>:</p>\n<pre><code>char operator[](int index) const\n{\n if (index &lt; 0 || index &gt;= size)\n throw &quot;[error] index is out of range&quot;;\n\n return str[index];\n}\n\nchar&amp; operator[](int index)\n{\n if (index &lt; 0 || index &gt;= size)\n throw &quot;[error] index is out of range&quot;;\n\n return str[index];\n}\n</code></pre>\n<p>In C++ the <code>operator[]</code> is usually unchecked and used in situations where you have already established that the access is within bounds and thus the check is redundant.</p>\n<p>In C++ we normally also provide an unchecked version so you don't have to do a manual check. In C++ we call this version <code>at()</code>.</p>\n<pre><code>for(int loop = 0; loop &lt; str. length(); ++loop) {\n std::cout &lt;&lt; str[loop]; // Why do I need the index\n // checked here (every loop)\n // I have already established that\n // loop is within bounds by checking\n // it against the length of the string.\n} \n</code></pre>\n<hr />\n<p>You have not implemented move semantics.</p>\n<hr />\n<p>You have not implemented a reserve size. There is a difference between current length and maximum length before a resize is required.</p>\n<hr />\n<p>Your assignment operator is not exception safe.</p>\n<pre><code>string&amp; operator=(const char* buffer)\n{\n delete[] str; // you have modified the object here\n\n size = str_len(buffer);\n str = str_alc(size + 1); // This can throw. If it does\n // your object is in a bad state\n // the member str is pointing at\n // memory that has been released\n // back to the runtime. Any\n // use of this will be broken.\n //\n // You have to hope that that exception\n // is not caught and the application\n // exits.\n\n str_cpy(str, size + 1, buffer);\n\n return *this;\n}\n</code></pre>\n<p>The correct way to this is to implement the copy and swap idiom.</p>\n<pre><code>string&amp; operator=(const char* buffer)\n{\n string tmp(buffer); // safely create a copy.\n\n // Now that you have done the copy swap this with tmp\n std::swap(size, tmp.size)\n std::swap(buffer, tmp.buffer);\n\n return *this;\n}\n// destructor of tmp is called here.\n// it will release the buffer that you just placed into the object \n</code></pre>\n<hr />\n<p>The standard library version of this <code>std::string</code> implements a nice short string optimization on top of the basic dynamic memory allocation version that you have implemented.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-31T19:56:40.290", "Id": "248724", "ParentId": "248717", "Score": "5" } }, { "body": "<p>Having your strings <em>both</em> null-terminated <em>and</em> having an explicit size is a Bad Idea. C++ std::string, entirely not accidentally, doesn't do that.</p>\n<p>You can allocate an extra character and set it to zero for ease of conversion to C-style strings. While converting from or comparing with C strings, you can (and should) test for the null terminator in the C string. Don't ever look for the null terminator in any other place of your code. Use <code>size</code>.</p>\n<p>You also forgot to implement move semantics.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-09-13T05:35:32.740", "Id": "488578", "Score": "0", "body": "I actually think STL does mix size and null terminator otherwise the c_str function can't be const" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-09-13T05:45:31.627", "Id": "488580", "Score": "0", "body": "@JVApen No, C++ std::strings are **not** null-terminated. `c_str` returns a pointer to a null-terminated string, which may or may not be equal to the original c++ string (because the latter might contain embedded null characters)." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-09-01T07:34:29.913", "Id": "248753", "ParentId": "248717", "Score": "1" } } ]
{ "AcceptedAnswerId": "248724", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-31T18:37:06.960", "Id": "248717", "Score": "4", "Tags": [ "c++", "strings", "reinventing-the-wheel" ], "Title": "String class implementation" }
248717
<p>Say the beginning dataframe is this:</p> <pre><code> System Sizes X Y Z 0 1 1 1.0 0 0 1 1 2 2.4 0 0 2 1 3 50.0 50 0 3 3 100 500.0 500 0 4 3 100 501.0 501 0 5 3 100 505.0 506 0 6 3 100 1000.0 1000 0 7 3 100 1001.0 1001 0 8 3 100 1005.0 1005 0 </code></pre> <p>The &quot;Sizes&quot; refer to units of volume of a sphere. Each sphere is assigned a system in which to be, and also X, Y &amp; Z center coordinates.</p> <p>If spheres in the same system, have a volume and coordinates, such that their radii overlap the distance between them, the spheres &quot;collide&quot;. In this case, one sphere takes on all the units of volume of the colliding spheres, and the rest are assigned volume 0.</p> <p>The output would be:</p> <pre><code> System Sizes X Y Z 0 1 3.0 1.0 0 0 1 1 0.0 2.4 0 0 2 1 3.0 50.0 50 0 3 3 200.0 500.0 500 0 4 3 0.0 501.0 501 0 5 3 100.0 505.0 506 0 6 3 300.0 1000.0 1000 0 7 3 0.0 1001.0 1001 0 8 3 0.0 1005.0 1005 0 </code></pre> <p>What must be iterated through are a) the systems, and b) the groups of colliding spheres within each systems. Plus, c) the collision detector has to be used optimally.</p> <p>This code uses Atomic Simulation Environment, and the code is a work-around for the rigidity in how it outputs neighbor-lists (<a href="https://wiki.fysik.dtu.dk/ase/ase/neighborlist.html" rel="nofollow noreferrer">https://wiki.fysik.dtu.dk/ase/ase/neighborlist.html</a>)</p> <p>Spheres may be called atoms, because the library used treats them as such.</p> <p>The beginning dataframe is saved as &quot;experimental_data&quot;.</p> <p>The code I have so far, which gives the right results, is:</p> <pre><code>def adjust_size_for_neighbors(experimental_data): practical_experimental_data = experimental_data.copy() #This is the dataframe I want outputted list_of_systems = (experimental_data[&quot;System&quot;].unique().tolist()) #I'm using a list to iterate through the unique systems for system in list_of_systems: system_experimental_data = experimental_data.loc[experimental_data['System'] == system] #filter for only the data in the system system_experimental_data =system_experimental_data[system_experimental_data['Sizes'] !=0] #filtering out zero sizes positions = ((system_experimental_data[[&quot;X&quot;, &quot;Y&quot;, &quot;Z&quot;]]).values ) #This is the format Atomic Simulation Environment, the library I'm going to use for the collision detector, wants the coordinates digit = len(system_experimental_data) string = 'N' + str(digit) atoms = Atoms(string, positions) #ASE wants the first input for atoms, to be a a letter representing the atom you're using, and a number for how many there are. #For example, N7 would be 7 Nitrogen atoms. From my understanding, the picked atom is arbitrary for the calculations. #The Atoms object is a collection of atoms. #Documentation for Atoms here https://wiki.fysik.dtu.dk/ase/ase/atoms.html radii = ((3/4)*(1/math.pi) * ((system_experimental_data[[&quot;Sizes&quot;]]).values) )**(1/3) #Calculating the radii based on the volumes, going backwards from V = (4/3)(Pi)(r^3) #The output is a list of one-element lists radii = radii.reshape(len(radii)) #Creating a list out of a list of lists nl = NeighborList(radii, self_interaction=True, bothways = True) #self_interaction=True means count an atom as interacting as itself #bothways=True means if atom 1 is counted as neighboring atom 2, when the code gets to atom 2, still count it as neighboring atom 1. nl.update(atoms) second_system_experimental_data = system_experimental_data.copy() #making a new dataframe for later indices_list = [] #This will turn out to be a list of lists, with each list having the indices of group of colliding atoms for i in range(len(system_experimental_data)): #iterating through the atoms indices,offsets = nl.get_neighbors(i) indices_list.append(indices) #Because self_interaction = True and bothways = True: #For system 1, for example: # i = 0 gives indices = [0,1,0] # i = 1 gives indices = [1,0,1] # i = 3 gives indices = [2,2] #What is needed is, for example: #[[a,b],[b,c],[d,e],[e,f]] = [[a,b,c],[d,e,f]] #this comes up in system 3 #for that, I have the following code def dfs(node,index): taken[index]=True ret=node for i,item in enumerate(indices_list): if not taken[i] and not ret.isdisjoint(item): ret.update(dfs(item,i)) return ret def merge_all(indices_list): ret=[] for i,node in enumerate(indices_list): if not taken[i]: ret.append(list(dfs(node,i))) return ret #These 2 functions are actually defined before the very first for loop begins, but they're here for the continuity of the question taken=[False]*len(indices_list) indices_list=[set(elem) for elem in indices_list] list_of_lists = (merge_all(indices_list)) #list_of_lists = # [[0,1],[2]] for system 1 # [[0,1],[2], [3,4,5] for system 3 #This is all a work-around for the rigidity of the output for &quot;indices&quot; sizes_data_frame = system_experimental_data[[&quot;Sizes&quot;]] * 1 second_sizes_data_frame = second_system_experimental_data[&quot;Sizes&quot;] * 1 #Isolate the Sizes column from both the dataframes into their own dataframes if max([len(i) for i in list_of_lists])!=1: #the elements that are lists containing only one element are not of interest, ie, [0,1] is of interest, [2] isn't. for a_list in list_of_lists: (second_sizes_data_frame.iloc[a_list]) = 0 #Setting all the &quot;Sizes&quot; values in the dataframe rows that were found to neighbor each other in my copy dataframe to 0. first_index = a_list[0] #Picking out the first atom to neighbor the rest, because only one is needed (second_sizes_data_frame.iloc[first_index]) = ((sum((sizes_data_frame.iloc[a_list]).values))[0]) #Of all the rows whose &quot;Sizes&quot; value were set to 0, the first one is being set to the sum of the &quot;Sizes&quot; values belonging to those rows initially. second_system_experimental_data[&quot;Sizes&quot;] = second_sizes_data_frame #put this new &quot;Sizes&quot; column back into the copy dataframe for the system practical_experimental_data.update(second_system_experimental_data) #Update the dataframe that is the output of the whole process to have the adjusted &quot;Sizes&quot; return(practical_experimental_data) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-31T19:22:38.703", "Id": "487299", "Score": "0", "body": "\"The code I have so far\" and does it produce the correct results? Is there more to your program than just this function?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-31T19:26:22.930", "Id": "487301", "Score": "1", "body": "Yes, it does produce the correct results. And no, there isn't more to the program than just this function." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-31T19:41:08.200", "Id": "487310", "Score": "0", "body": "Good! Welcome to Code Review." } ]
[ { "body": "<p>Good submission, and it looks like you're already following several common best practices, but here are some suggestions for improvement on top of that.</p>\n<ul>\n<li><p>PEP8: spaces around <code>=</code>, operators, after commas, etc., there are several violations in this code w.r.t. spacing. An excellent tool for automatically applying PEP8 is called Black, <a href=\"https://black.now.sh/?version=stable&amp;state=_Td6WFoAAATm1rRGAgAhARYAAAB0L-Wj4BVoB7ZdAD2IimZxl1N_WlbvK5V8IreJS0IKPTToj1-Pe3gnXSW2I_6_uLII1n2BgXxRR3LYqxjqAgGytDjLJY7OGEcuivXwbZQ8eImItVDyr0ua-qobJTCI5mpSkpW_mUbuT5aeeuVxqaugnxSA5kJOXj9D5x72ir9VNNhPMpEh-_MwMNgwmDpi4Dx5BTgfQQc-VWSBZkOgnPdXSgCBH3Z6uh5bWnmmrETeTVFdFwYdlUPcw-zX9wLDlTzx4DrRApCximXIswGDff8Tw7e5CEJIiHlleFpKj8YTbb9nyKf34Wzc3DkJ4gCyM5cbb59ClxIh4KfivDu2UF0qq8cg4898IaB1iDQoBK2KLK_3OEFz3o0BbCPbAOjqCoZhoeWayaeZnimEBCzg8tedAwoiNs_kxJVRUoVwQOgRI5KQ0TynM0HSfBurtS7Pk3chkVy1BvNgza9idTpYBgryCDCse91sLoeFiHCd4c7gkjBE6yaVckxp08tlnUYL3_5XvEidrPNwhlcsyN8L8WsPo4F9twIVfogOy0tV2nVR3j0cE19r4DYVr6_nHiu9OE2FO9Ty0zLT5Yf102JYAljBphktpW2h_KXybZG_lEOdM-e90ls-KwuwmFrFKXHiRoE3E8A2ObZld7KItEI-BAq0M__jm3rrQa0_Xv14qigoM7iYcZ-_v_7iurOAUbkoNB7Ypqv03i3AuyudYNeYKjnykbbRGqyOfxF7w5T-GvbvvX1AG3g33KOVkptaL2_KarAXki_mZ002gSesN09L2jwLYGhkyxdkWCqVzK3dZtdFtfLe_NnTBXI0yYcG4YFDohSeg4DfsF9ro7dt1CR3SaNKe6-17EM-ZFWOyX_C6mGB8DgTfERz2VfZc3lDai467YU1ItsFJSHMgxOCi5b-TbHEuZR5yJttFoBD6SiF1jUbQy0Z2aJSL3KAMLWi24xOCRESTGRX_zG6fHyi6omUHTNVJR3cRBQZJ07tMk5uAWfKkAimo4gWnTprPZAil50u0VuKOrzpIBa4ZZgsaczOoZdrhUqcjJTLDuIiq5Co25aOQGv_Mz36CYVHGF3P4FqAUyF62dXqkjGC2If26nFrYaD1oSb6J3b-0mGd2hbkb3e9YTdBZ-JCguvZRST9LytQ1O5oqkE2QBqC_rYW6SOweLtNrxnIeOnE7DQPS9LQl7orf-4d46_cpYQngBXNY_7UPcRhj3zENx310DTl9WMejc04qWQBygQ5UruRcRfKODUGT27NFnjNdz-hZIS_t79HvkCW9Ep465tq21pjzEcXB5xQ5QtFvcmDiDr9O3-dmMxcfHLlym9cLDQKcofcC3-c6oE23JDV8VzeQ2UBu-6ALLpNU-Ro86XFWFvHh04Md0OZkMh7VhTu3bfbdgDflv9PrI6a8LFyZDNI5slpcUHb-GbhTsiRrp-S25ezMNpJ9-ch9avm1nFi2kwe_c5t8tR4Sn5zAn8c9EZeT0UY8xVnE5uPZ5GJaJ10TjOuygHMvJUpgApO6jGLdut_3jHXhuHImeSGS_5E8n9q1DXKiX8o3xjqtPCckKTxIwo6p9OSm8JWJw4-fmS_Brk4C9OEDFnkXzRf6oXsCY2yPIfEbfAG4KBqUjAu7VXF2TU-sQkEuVwg9hwXHHn86h5VxqqdKhlA44QcsXaWE5kHEc9c1wUAUYCFWbMuOkSpk8yv3uqLcMKbWvxzUgRaYLYPDvNJz3yfU4umBKnWBcm1-__SvDkzBcfCYc_srJr8z4sk_K0XaGEbV8ZJHMQWfSsZglNs7z5YEtsNBU4mAwYCxUBqK2RLFAxh53_4YS9gy9cgUv9nV6iNDnsjk7d8omPA41f9JpEmm-lDm-kphe6MuxjnIaR3uH3k8MC5Dbl9scoZMKHrNTEW14KkriWeiqnKGWi9RMqvzWjlSe99395dJNUPVje8q-YgQM-uw5faL3Mf_3gJySRzH9mWtgc7hOzEBuoZtalSpxAtEozyaANLGry-sqA-6Hy4wpNoRvmK-9c6BSQugPupRvu4F1hJL-JUsn8xtH7BCNy2h2oDWd7FK4PbNDRE4PkoQbh52_40bT2r2HR8uleMhipg7K0oij-pocrAqhAVYYEs0MFx6OoQy4aNMSpeROCiJvbCBW8_J-NJGgN9o2JbH83lBYO0RWkbUsrDHi45Rw9BvLDzklNm9iUadqZF4H0rHyrTXg-w8b3tao_SNHH-Y3TbmAz-hP4r-UghapXz59zvN-vKWlE4SKAQZ_dUyE3j21d6dRs2AaPgw1n7Dy7l_XMyhd8BNFQk24IoQ127SiPLqnFcebe-XOJMYP6RYhOAf43dQqytfn8kmfKY9N2ojg4NRuuhvDujgUzEMI4sVkEJDunzxZVxAX9K32PMbmv7z8mEZqq8mhAEx-FqSNWDsPqz6BHRE-YGbyixy7xr0uGMgkNiw0JYUNil8Jat-0Z6i3wZAzz6_OAGwLM9lBXkOLPGSDxIRTmdy4Dz8nxBxkwgxjwnP2U1FSW9mvD7qa2S3FjZhLyX8TtAQk4zlmReAvfed8xSGCkwLr5lurFp9-R838ioTbshJtu0hqDz8KZHBZoZ5hxqn3MX4Ntff6Lo-SIDdvKM51HKIPmRTn-NIMqo-f5jsxs81pbgZLRHoy6aAAAAAIa3EmQAKoGlAAHSD-kqAACsM16AscRn-wIAAAAABFla\" rel=\"nofollow noreferrer\">you can see a demo of it on your code snippet here</a>.</p>\n</li>\n<li><p>Excellent job using self-explaining variable names for the most part, often also with explanatory comments. Some of them are a little long, but that's preferable over using abbreviations or insufficiently descriptive names. Some (like <code>list_of_lists</code>) could be improved.</p>\n</li>\n<li><p>This is pure preference, but in Pandas, I'm a fan of the <a href=\"https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.query.html\" rel=\"nofollow noreferrer\"><code>query</code> method</a>. E.g.:</p>\n<pre><code> system_experimental_data = experimental_data.loc[experimental_data['System'] == system]\n system_experimental_data = system_experimental_data[system_experimental_data['Sizes'] != 0]\n</code></pre>\n<p>should become (not tested):</p>\n<pre><code> system_experimental_data = experimental_data.query('System == @system and Sizes != 0')\n</code></pre>\n</li>\n<li><p>Great, extensive, but not excessive use of comments throughout.</p>\n</li>\n</ul>\n<p>I didn't really dig into what the code's doing or how it's accomplishing that, so I don't know if there may be ways to break the logic up a bit to be cleaner; hopefully these few tips and praises are useful.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-31T23:15:36.803", "Id": "248737", "ParentId": "248718", "Score": "3" } }, { "body": "<h1>overwrite builtin modules</h1>\n<p>You use the variable name <code>string</code>, which can overwrite the builtin <code>string</code> module. I would use the variable name <code>atom_name</code> or something.</p>\n<h1>f-strings</h1>\n<p>With <code>f-strings</code> you can also do this <code>atom_name inline</code>: <code>atoms = Atoms(f&quot;N{len(system_experimental_data)}&quot;, positions)</code></p>\n<h1>list comprehension</h1>\n<p>Instead of instantiating a <code>list</code>, and then appending to it, a list comprehension can be clearer:</p>\n<pre><code>indices_list = [nl.get_neighbors(i)[0] for i in range(len(system_experimental_data))]\n</code></pre>\n<h1>pandas errors</h1>\n<p>There are a few things that can be done easier</p>\n<pre><code>radii = ((3/4)*(1/math.pi) * ((system_experimental_data[[&quot;Sizes&quot;]]).values) \nradii = radii.reshape(len(radii))\n</code></pre>\n<p>can be <code>((3/4)*(1/math.pi) * ((system_experimental_data[&quot;Sizes&quot;]).values)</code></p>\n<p>There is no reason to do the <code>tolist</code> in <code>(practical_experimental_data[&quot;System&quot;].unique().tolist())</code></p>\n<h1>cluster indices</h1>\n<p>Your method to find the indices is quite convoluted. The inner methods also use and change nonlocal scope variables (<code>taken</code>) which should be passed in as argument</p>\n<p>I think it would be easier to do this with a Series:</p>\n<pre><code>clusters = pd.Series(range(len(system_experimental_data)))\nfor indices in indices_list:\n cluster= clusters [indices]\n changed_indices = cluster[cluster.index != cluster]\n if changed_indices.empty:\n clusters[indices] = indices.min()\n else:\n clusters[indices] = changed_indices.min()\n</code></pre>\n<p>This makes use of the pandas indexing. The crux is using <code>neighbourhood[neighbourhood.index != neighbourhood]</code> to check for previous 'collisions'</p>\n<p>For system 3, this is the result:</p>\n<blockquote>\n<pre><code>0 0\n1 0\n2 2\n3 3\n4 3\n5 3\ndtype: int64\n</code></pre>\n</blockquote>\n<h1>Split of functions</h1>\n<p>Your code is quite long. This can be made more readable by splitting of smaller parts. One easy part to split off, is starting from the data for one system, find the clusters:</p>\n<pre><code>def find_clusters(system_data):\n &quot;&quot;&quot;Searches for neigbours in a system\n \n Expects a DataFrame with \n - [&quot;X&quot;, &quot;Y&quot;, &quot;Z&quot;] columns for the position\n - a &quot;Sizes&quot; column for the volume\n \n Returns a Series with the index of the input as index, and a label for the cluster\n \n &quot;&quot;&quot;\n positions = (system_data[[&quot;X&quot;, &quot;Y&quot;, &quot;Z&quot;]]).values\n #This is the format Atomic Simulation Environment, the library I'm going to use for the collision detector, wants the coordinates\n atoms = ase.Atoms(f&quot;N{len(system_data)}&quot;, positions)\n \n radii = ((3/4)*(1/math.pi) * ((system_data[&quot;Sizes&quot;]).values))**(1/3)\n #Calculating the radii based on the volumes, going backwards from V = (4/3)(Pi)(r^3)\n #The output is a list of one-element lists\n nl = NeighborList(radii, self_interaction=True, bothways = True)\n nl.update(atoms) # this is the way the ase API works\n \n clusters = pd.Series(range(len(system_data)))\n \n for i in range(len(system_data)):\n indices, _ = nl.get_neighbors(i)\n cluster = clusters[indices]\n changed_indices = cluster[cluster.index != cluster]\n if changed_indices.empty:\n clusters[indices] = indices.min()\n else:\n clusters[indices] = changed_indices.min()\n \n return pd.Series(clusters.values, index=system_data.index)\n</code></pre>\n<p>This might be made more efficient for larger systems by skipping indices which have been altered already, but that might give rise to certain edge cases.</p>\n<p>This is a method with a docstring explaining what the method expects, and what it will return. This method can also be easily tested in isolation</p>\n<h1><code>groupby</code></h1>\n<p>Instead of iterating over the unique values, pandas has its <code>groupby</code> functionality.</p>\n<p>Since we have the existing method to find the neighbourhoods, we can do</p>\n<pre><code>clusters = df.groupby(&quot;System&quot;, group_keys=False).apply(find_clusters)\n</code></pre>\n<p>That gives us:</p>\n<blockquote>\n<pre><code>0 0\n1 0\n2 2\n3 0\n4 0\n5 2\n6 3\n7 3\n8 3\ndtype: int64\n</code></pre>\n</blockquote>\n<p>The sum of each cluster is then as easy as <code>df.groupby([&quot;System&quot;, clusters])[&quot;Sizes&quot;].sum()</code></p>\n<pre><code>System \n1 0 3\n 2 3\n3 0 200\n 2 100\n 3 300\nName: Sizes, dtype: int64\n</code></pre>\n<p>Getting the indices for these can be done with: <code>df.reset_index().groupby([&quot;System&quot;, clusters])[&quot;index&quot;].first()</code></p>\n<pre><code>System \n1 0 0\n 2 2\n3 0 3\n 2 5\n 3 6\nName: index, dtype: int64\n</code></pre>\n<p>This can be combined : <code>df.reset_index().groupby([&quot;System&quot;, clusters]).agg({&quot;Sizes&quot;: &quot;sum&quot;, &quot;index&quot;: &quot;first&quot;})</code></p>\n<blockquote>\n<pre><code>System Sizes index\n1 0 3 0\n1 2 3 2\n3 0 200 3\n3 2 100 5\n3 3 300 6\n</code></pre>\n</blockquote>\n<p>We can transform this to the new <code>Sizes</code> column: <code>result.set_index(&quot;index&quot;).reindex(df.index).fillna(0)</code></p>\n<h1>putting it together</h1>\n<p>With some pandas reindex magic and a fluent style, The end result is as simple as:</p>\n<pre><code>def adjust_size_for_neighbors(experimental_data):\n clusters = (\n experimental_data.query(&quot;Sizes != 0&quot;)\n .groupby(&quot;System&quot;, group_keys=False)\n .apply(find_clusters)\n )\n\n grouped_sizes = (\n experimental_data.reset_index()\n .groupby([&quot;System&quot;, clusters])\n .agg({&quot;Sizes&quot;: &quot;sum&quot;, &quot;index&quot;: &quot;first&quot;})\n .set_index(&quot;index&quot;)\n .reindex(experimental_data.index)\n .fillna(0)\n )\n return experimental_data.assign(grouped_sizes=grouped_sizes)\n</code></pre>\n<p>I've picked <code>grouped_sizes</code> as name for the new column. If you want to keep the original column name, you can do <code>return experimental_data.assign(Sizes=grouped_sizes)</code></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-09-02T09:00:44.290", "Id": "248803", "ParentId": "248718", "Score": "2" } } ]
{ "AcceptedAnswerId": "248803", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-31T18:40:46.843", "Id": "248718", "Score": "3", "Tags": [ "python", "pandas" ], "Title": "Iterating through, and editing a dataframe, using outputs from a collision detector's neighbor-list" }
248718
<p>I've started programming using Python two months ago. My only prior programming experience was VBA. I'm completely self taught. I wrote the code below for a project I'm creating as a way to learn the language.</p> <p>I was hoping someone experienced with Python could look over my code quickly and let me know which places could be written better. It all works but I feel(especially with the variables) there must be best practices I am missing.</p> <p>Any feedback would be greatly appreciated.</p> <p>The code is meant to load a window with input boxes where you can save/load player information into a database file. It's will be used for a Dungeons and Dragons game. It does what its supposed to.</p> <p>I'm more concerned with the code vs functionality. Is there a more elegant way to get the same results? Specifically within the <code>def makeVar(self)</code> section.</p> <pre><code>from tkinter import * #import tkinter from tkinter import messagebox as mb import SQLclass SQL = SQLclass.Database(&quot;Players.db&quot;) #connect db window = Tk() #make variable for tkinter #overwrite the X button to exit script def xbutt(): exit() window.protocol('WM_DELETE_WINDOW', xbutt) class PlayerWindow: &quot;&quot;&quot; Player input window. Used to add groups with player stats to players database. &quot;&quot;&quot; def __init__(self, top): self.makeVar() self.layoutWindow() self.buttons() self.populateOM() self.getvalues() def layoutWindow(self): window.title(&quot;Player Entry Form&quot;) #numbers Label(window,text=&quot;1&quot;).grid(row=1,column=0) Label(window,text=&quot;2&quot;).grid(row=2,column=0) Label(window,text=&quot;3&quot;).grid(row=3,column=0) Label(window,text=&quot;4&quot;).grid(row=4,column=0) Label(window,text=&quot;5&quot;).grid(row=5,column=0) Label(window,text=&quot;6&quot;).grid(row=6,column=0) Label(window,text=&quot;7&quot;).grid(row=7,column=0) Label(window,text=&quot;8&quot;).grid(row=8,column=0) #Player Names Label(window,text=&quot;Player Name&quot;).grid(row=0,column=1, padx=5, pady=2) Entry(window, textvariable=self.PlayerValues[0][1]).grid(row=1,column=1, padx=5, pady=2) Entry(window, textvariable=self.PlayerValues[1][1]).grid(row=2,column=1, padx=5, pady=2) Entry(window, textvariable=self.PlayerValues[2][1]).grid(row=3,column=1, padx=5, pady=2) Entry(window, textvariable=self.PlayerValues[3][1]).grid(row=4,column=1, padx=5, pady=2) Entry(window, textvariable=self.PlayerValues[4][1]).grid(row=5,column=1, padx=5, pady=2) Entry(window, textvariable=self.PlayerValues[5][1]).grid(row=6,column=1, padx=5, pady=2) Entry(window, textvariable=self.PlayerValues[6][1]).grid(row=7,column=1, padx=5, pady=2) Entry(window, textvariable=self.PlayerValues[7][1]).grid(row=8,column=1, padx=5, pady=2) #Character Names Label(window,text=&quot;Character Name&quot;).grid(row=0,column=3, padx=5, pady=2) Entry(window, textvariable=self.PlayerValues[0][2]).grid(row=1,column=3, padx=5, pady=2) Entry(window, textvariable=self.PlayerValues[1][2]).grid(row=2,column=3, padx=5, pady=2) Entry(window, textvariable=self.PlayerValues[2][2]).grid(row=3,column=3, padx=5, pady=2) Entry(window, textvariable=self.PlayerValues[3][2]).grid(row=4,column=3, padx=5, pady=2) Entry(window, textvariable=self.PlayerValues[4][2]).grid(row=5,column=3, padx=5, pady=2) Entry(window, textvariable=self.PlayerValues[5][2]).grid(row=6,column=3, padx=5, pady=2) Entry(window, textvariable=self.PlayerValues[6][2]).grid(row=7,column=3, padx=5, pady=2) Entry(window, textvariable=self.PlayerValues[7][2]).grid(row=8,column=3, padx=5, pady=2) #Class Names Label(window,text=&quot;Class Name&quot;).grid(row=0,column=4, padx=5, pady=2) Entry(window, textvariable=self.PlayerValues[0][3], width=12).grid(row=1,column=4, padx=5, pady=2) Entry(window, textvariable=self.PlayerValues[1][3], width=12).grid(row=2,column=4, padx=5, pady=2) Entry(window, textvariable=self.PlayerValues[2][3], width=12).grid(row=3,column=4, padx=5, pady=2) Entry(window, textvariable=self.PlayerValues[3][3], width=12).grid(row=4,column=4, padx=5, pady=2) Entry(window, textvariable=self.PlayerValues[4][3], width=12).grid(row=5,column=4, padx=5, pady=2) Entry(window, textvariable=self.PlayerValues[5][3], width=12).grid(row=6,column=4, padx=5, pady=2) Entry(window, textvariable=self.PlayerValues[6][3], width=12).grid(row=7,column=4, padx=5, pady=2) Entry(window, textvariable=self.PlayerValues[7][3], width=12).grid(row=8,column=4, padx=5, pady=2) #Level Label(window,text=&quot;Level&quot;).grid(row=0,column=5, padx=5, pady=2) Entry(window, textvariable=self.PlayerValues[0][4], width=3).grid(row=1,column=5, padx=5, pady=4) Entry(window, textvariable=self.PlayerValues[1][4], width=3).grid(row=2,column=5, padx=5, pady=4) Entry(window, textvariable=self.PlayerValues[2][4], width=3).grid(row=3,column=5, padx=5, pady=4) Entry(window, textvariable=self.PlayerValues[3][4], width=3).grid(row=4,column=5, padx=5, pady=4) Entry(window, textvariable=self.PlayerValues[4][4], width=3).grid(row=5,column=5, padx=5, pady=4) Entry(window, textvariable=self.PlayerValues[5][4], width=3).grid(row=6,column=5, padx=5, pady=4) Entry(window, textvariable=self.PlayerValues[6][4], width=3).grid(row=7,column=5, padx=5, pady=4) Entry(window, textvariable=self.PlayerValues[7][4], width=3).grid(row=8,column=5, padx=5, pady=4) #HP Label(window,text=&quot;HP&quot;).grid(row=0,column=6, padx=5, pady=2) Entry(window, textvariable=self.PlayerValues[0][5], width=3).grid(row=1,column=6, padx=5, pady=2) Entry(window, textvariable=self.PlayerValues[1][5], width=3).grid(row=2,column=6, padx=5, pady=2) Entry(window, textvariable=self.PlayerValues[2][5], width=3).grid(row=3,column=6, padx=5, pady=2) Entry(window, textvariable=self.PlayerValues[3][5], width=3).grid(row=4,column=6, padx=5, pady=2) Entry(window, textvariable=self.PlayerValues[4][5], width=3).grid(row=5,column=6, padx=5, pady=2) Entry(window, textvariable=self.PlayerValues[5][5], width=3).grid(row=6,column=6, padx=5, pady=2) Entry(window, textvariable=self.PlayerValues[6][5], width=3).grid(row=7,column=6, padx=5, pady=2) Entry(window, textvariable=self.PlayerValues[7][5], width=3).grid(row=8,column=6, padx=5, pady=2) #Strength Names Label(window,text=&quot;STR&quot;).grid(row=0,column=7, padx=5, pady=2) Entry(window, textvariable=self.PlayerValues[0][6], width=3).grid(row=1,column=7, padx=5, pady=2) Entry(window, textvariable=self.PlayerValues[1][6], width=3).grid(row=2,column=7, padx=5, pady=2) Entry(window, textvariable=self.PlayerValues[2][6], width=3).grid(row=3,column=7, padx=5, pady=2) Entry(window, textvariable=self.PlayerValues[3][6], width=3).grid(row=4,column=7, padx=5, pady=2) Entry(window, textvariable=self.PlayerValues[4][6], width=3).grid(row=5,column=7, padx=5, pady=2) Entry(window, textvariable=self.PlayerValues[5][6], width=3).grid(row=6,column=7, padx=5, pady=2) Entry(window, textvariable=self.PlayerValues[6][6], width=3).grid(row=7,column=7, padx=5, pady=2) Entry(window, textvariable=self.PlayerValues[7][6], width=3).grid(row=8,column=7, padx=5, pady=2) #Dexterity Names Label(window,text=&quot;DEX&quot;).grid(row=0,column=8, padx=5, pady=2) Entry(window, textvariable=self.PlayerValues[0][7], width=3).grid(row=1,column=8, padx=5, pady=2) Entry(window, textvariable=self.PlayerValues[1][7], width=3).grid(row=2,column=8, padx=5, pady=2) Entry(window, textvariable=self.PlayerValues[2][7], width=3).grid(row=3,column=8, padx=5, pady=2) Entry(window, textvariable=self.PlayerValues[3][7], width=3).grid(row=4,column=8, padx=5, pady=2) Entry(window, textvariable=self.PlayerValues[4][7], width=3).grid(row=5,column=8, padx=5, pady=2) Entry(window, textvariable=self.PlayerValues[5][7], width=3).grid(row=6,column=8, padx=5, pady=2) Entry(window, textvariable=self.PlayerValues[6][7], width=3).grid(row=7,column=8, padx=5, pady=2) Entry(window, textvariable=self.PlayerValues[7][7], width=3).grid(row=8,column=8, padx=5, pady=2) #Constitution Label(window,text=&quot;CON&quot;).grid(row=0,column=9, padx=5, pady=2) Entry(window, textvariable=self.PlayerValues[0][8], width=3).grid(row=1,column=9, padx=5, pady=2) Entry(window, textvariable=self.PlayerValues[1][8], width=3).grid(row=2,column=9, padx=5, pady=2) Entry(window, textvariable=self.PlayerValues[2][8], width=3).grid(row=3,column=9, padx=5, pady=2) Entry(window, textvariable=self.PlayerValues[3][8], width=3).grid(row=4,column=9, padx=5, pady=2) Entry(window, textvariable=self.PlayerValues[4][8], width=3).grid(row=5,column=9, padx=5, pady=2) Entry(window, textvariable=self.PlayerValues[5][8], width=3).grid(row=6,column=9, padx=5, pady=2) Entry(window, textvariable=self.PlayerValues[6][8], width=3).grid(row=7,column=9, padx=5, pady=2) Entry(window, textvariable=self.PlayerValues[7][8], width=3).grid(row=8,column=9, padx=5, pady=2) #Intelligence Label(window,text=&quot;INT&quot;).grid(row=0,column=10, padx=5, pady=2) Entry(window, textvariable=self.PlayerValues[0][9], width=3).grid(row=1,column=10, padx=5, pady=2) Entry(window, textvariable=self.PlayerValues[1][9], width=3).grid(row=2,column=10, padx=5, pady=2) Entry(window, textvariable=self.PlayerValues[2][9], width=3).grid(row=3,column=10, padx=5, pady=2) Entry(window, textvariable=self.PlayerValues[3][9], width=3).grid(row=4,column=10, padx=5, pady=2) Entry(window, textvariable=self.PlayerValues[4][9], width=3).grid(row=5,column=10, padx=5, pady=2) Entry(window, textvariable=self.PlayerValues[5][9], width=3).grid(row=6,column=10, padx=5, pady=2) Entry(window, textvariable=self.PlayerValues[6][9], width=3).grid(row=7,column=10, padx=5, pady=2) Entry(window, textvariable=self.PlayerValues[7][9], width=3).grid(row=8,column=10, padx=5, pady=2) #Wisdom Label(window,text=&quot;WIS&quot;).grid(row=0,column=11, padx=5, pady=2) Entry(window, textvariable=self.PlayerValues[0][10], width=3).grid(row=1,column=11, padx=5, pady=2) Entry(window, textvariable=self.PlayerValues[1][10], width=3).grid(row=2,column=11, padx=5, pady=2) Entry(window, textvariable=self.PlayerValues[2][10], width=3).grid(row=3,column=11, padx=5, pady=2) Entry(window, textvariable=self.PlayerValues[3][10], width=3).grid(row=4,column=11, padx=5, pady=2) Entry(window, textvariable=self.PlayerValues[4][10], width=3).grid(row=5,column=11, padx=5, pady=2) Entry(window, textvariable=self.PlayerValues[5][10], width=3).grid(row=6,column=11, padx=5, pady=2) Entry(window, textvariable=self.PlayerValues[6][10], width=3).grid(row=7,column=11, padx=5, pady=2) Entry(window, textvariable=self.PlayerValues[7][10], width=3).grid(row=8,column=11, padx=5, pady=2) #Charisma Label(window,text=&quot;CHA&quot;).grid(row=0,column=12, padx=5, pady=2) Entry(window, textvariable=self.PlayerValues[0][11], width=3).grid(row=1,column=12, padx=5, pady=2) Entry(window, textvariable=self.PlayerValues[1][11], width=3).grid(row=2,column=12, padx=5, pady=2) Entry(window, textvariable=self.PlayerValues[2][11], width=3).grid(row=3,column=12, padx=5, pady=2) Entry(window, textvariable=self.PlayerValues[3][11], width=3).grid(row=4,column=12, padx=5, pady=2) Entry(window, textvariable=self.PlayerValues[4][11], width=3).grid(row=5,column=12, padx=5, pady=2) Entry(window, textvariable=self.PlayerValues[5][11], width=3).grid(row=6,column=12, padx=5, pady=2) Entry(window, textvariable=self.PlayerValues[6][11], width=3).grid(row=7,column=12, padx=5, pady=2) Entry(window, textvariable=self.PlayerValues[7][11], width=3).grid(row=8,column=12, padx=5, pady=2) def makeVar(self): self.Player1 = [StringVar() ,StringVar() ,StringVar() ,StringVar() ,StringVar() ,StringVar() ,StringVar() ,StringVar() ,StringVar() ,StringVar() ,StringVar() ,StringVar() ] self.Player2 = [StringVar() ,StringVar() ,StringVar() ,StringVar() ,StringVar() ,StringVar() ,StringVar() ,StringVar() ,StringVar() ,StringVar() ,StringVar() ,StringVar() ] self.Player3 = [StringVar() ,StringVar() ,StringVar() ,StringVar() ,StringVar() ,StringVar() ,StringVar() ,StringVar() ,StringVar() ,StringVar() ,StringVar() ,StringVar() ] self.Player4 = [StringVar() ,StringVar() ,StringVar() ,StringVar() ,StringVar() ,StringVar() ,StringVar() ,StringVar() ,StringVar() ,StringVar() ,StringVar() ,StringVar() ] self.Player5 = [StringVar() ,StringVar() ,StringVar() ,StringVar() ,StringVar() ,StringVar() ,StringVar() ,StringVar() ,StringVar() ,StringVar() ,StringVar() ,StringVar() ] self.Player6 = [StringVar() ,StringVar() ,StringVar() ,StringVar() ,StringVar() ,StringVar() ,StringVar() ,StringVar() ,StringVar() ,StringVar() ,StringVar() ,StringVar() ] self.Player7 = [StringVar() ,StringVar() ,StringVar() ,StringVar() ,StringVar() ,StringVar() ,StringVar() ,StringVar() ,StringVar() ,StringVar() ,StringVar() ,StringVar() ] self.Player8 = [StringVar() ,StringVar() ,StringVar() ,StringVar() ,StringVar() ,StringVar() ,StringVar() ,StringVar() ,StringVar() ,StringVar() ,StringVar() ,StringVar() ] self.output1 = [&quot;&quot;,&quot;&quot;,&quot;&quot;,&quot;&quot;,&quot;&quot;,&quot;&quot;,&quot;&quot;,&quot;&quot;,&quot;&quot;,&quot;&quot;,&quot;&quot;,&quot;&quot;] self.output2 = [&quot;&quot;,&quot;&quot;,&quot;&quot;,&quot;&quot;,&quot;&quot;,&quot;&quot;,&quot;&quot;,&quot;&quot;,&quot;&quot;,&quot;&quot;,&quot;&quot;,&quot;&quot;] self.output3 = [&quot;&quot;,&quot;&quot;,&quot;&quot;,&quot;&quot;,&quot;&quot;,&quot;&quot;,&quot;&quot;,&quot;&quot;,&quot;&quot;,&quot;&quot;,&quot;&quot;,&quot;&quot;] self.output4 = [&quot;&quot;,&quot;&quot;,&quot;&quot;,&quot;&quot;,&quot;&quot;,&quot;&quot;,&quot;&quot;,&quot;&quot;,&quot;&quot;,&quot;&quot;,&quot;&quot;,&quot;&quot;] self.output5 = [&quot;&quot;,&quot;&quot;,&quot;&quot;,&quot;&quot;,&quot;&quot;,&quot;&quot;,&quot;&quot;,&quot;&quot;,&quot;&quot;,&quot;&quot;,&quot;&quot;,&quot;&quot;] self.output6 = [&quot;&quot;,&quot;&quot;,&quot;&quot;,&quot;&quot;,&quot;&quot;,&quot;&quot;,&quot;&quot;,&quot;&quot;,&quot;&quot;,&quot;&quot;,&quot;&quot;,&quot;&quot;] self.output7 = [&quot;&quot;,&quot;&quot;,&quot;&quot;,&quot;&quot;,&quot;&quot;,&quot;&quot;,&quot;&quot;,&quot;&quot;,&quot;&quot;,&quot;&quot;,&quot;&quot;,&quot;&quot;] self.output8 = [&quot;&quot;,&quot;&quot;,&quot;&quot;,&quot;&quot;,&quot;&quot;,&quot;&quot;,&quot;&quot;,&quot;&quot;,&quot;&quot;,&quot;&quot;,&quot;&quot;,&quot;&quot;] self.check1 = [&quot;&quot;,&quot;&quot;,&quot;&quot;,&quot;&quot;,&quot;&quot;,&quot;&quot;,&quot;&quot;,&quot;&quot;,&quot;&quot;,&quot;&quot;,&quot;&quot;,&quot;&quot;] self.check2 = [&quot;&quot;,&quot;&quot;,&quot;&quot;,&quot;&quot;,&quot;&quot;,&quot;&quot;,&quot;&quot;,&quot;&quot;,&quot;&quot;,&quot;&quot;,&quot;&quot;,&quot;&quot;] self.check3 = [&quot;&quot;,&quot;&quot;,&quot;&quot;,&quot;&quot;,&quot;&quot;,&quot;&quot;,&quot;&quot;,&quot;&quot;,&quot;&quot;,&quot;&quot;,&quot;&quot;,&quot;&quot;] self.check4 = [&quot;&quot;,&quot;&quot;,&quot;&quot;,&quot;&quot;,&quot;&quot;,&quot;&quot;,&quot;&quot;,&quot;&quot;,&quot;&quot;,&quot;&quot;,&quot;&quot;,&quot;&quot;] self.check5 = [&quot;&quot;,&quot;&quot;,&quot;&quot;,&quot;&quot;,&quot;&quot;,&quot;&quot;,&quot;&quot;,&quot;&quot;,&quot;&quot;,&quot;&quot;,&quot;&quot;,&quot;&quot;] self.check6 = [&quot;&quot;,&quot;&quot;,&quot;&quot;,&quot;&quot;,&quot;&quot;,&quot;&quot;,&quot;&quot;,&quot;&quot;,&quot;&quot;,&quot;&quot;,&quot;&quot;,&quot;&quot;] self.check7 = [&quot;&quot;,&quot;&quot;,&quot;&quot;,&quot;&quot;,&quot;&quot;,&quot;&quot;,&quot;&quot;,&quot;&quot;,&quot;&quot;,&quot;&quot;,&quot;&quot;,&quot;&quot;] self.check8 = [&quot;&quot;,&quot;&quot;,&quot;&quot;,&quot;&quot;,&quot;&quot;,&quot;&quot;,&quot;&quot;,&quot;&quot;,&quot;&quot;,&quot;&quot;,&quot;&quot;,&quot;&quot;] self.PlayerValues = [self.Player1,self.Player2,self.Player3,self.Player4,self.Player5,self.Player6,self.Player7,self.Player8] def populateOM(self): global existingGroups existingGroups = [] existingGroups = SQL.fetchSQL('SELECT DISTINCT &quot;Group Name&quot; from players') #get group names existingGroups = [a_tuple[0] for a_tuple in existingGroups] #remove tuples from list existingGroups.append(&quot;New Group&quot;) self.groupmenu['menu'].delete(0, 'end') for choice in existingGroups: self.groupmenu['menu'].add_command(label=choice, command=lambda value=choice: self.optV.set(value)) def buttons(self): #pulldown self.optV = StringVar() self.optV.trace(&quot;w&quot;, self.OptionMenu_Change) #put a trace on the variable(pulldown) to call if anything changes self.optV.set(&quot;New Group&quot;) self.groupmenu = OptionMenu(window, self.optV , &quot;&quot;) self.groupmenu.grid(row=10,column=1, columnspan=2,padx=5, pady=2) self.optN = self.optV.get() #Buttons Button(window, text=&quot;Save and Close&quot;, command=self.SaveNClose, width=15).grid(row=10,column=3,padx=5, pady=2)#load button to points to SaveNClose function Button(window, text=&quot;Delete Group&quot;, command=self.DeleteGroup, width=15).grid(row=10,column=4,padx=5, pady=2,columnspan=2)#load button to points to SaveNClose function Button(window, text=&quot;Clear&quot;, command=self.clearvalues, width=15).grid(row=10,column=6,padx=5, pady=2,columnspan=2)#load button to points to SaveNClose function def getvalues(self): self.optN = self.optV.get() self.OutputValues = [self.output1,self.output2,self.output3,self.output4,self.output5,self.output6,self.output7,self.output8] for r in range(0,7): for c in range(1,11): #11 is how many columns in the DB table minus the group name self.OutputValues[r][c] = self.PlayerValues[r][c].get() def checkvalues(self): self.optN = self.optV.get() self.CheckedValues = [self.check1,self.check2,self.check3,self.check4,self.check5,self.check6,self.check7,self.check8] for r in range(0,7): for c in range(1,11): self.CheckedValues[r][c] = self.PlayerValues[r][c].get() def LoadData(self): self.clearvalues() self.existingGroups = SQL.fetchSQL(f'SELECT * from players where &quot;Group Name&quot; = &quot;{self.optV.get()}&quot;') for r in range(0,len(self.existingGroups)): for c in range(1,11): self.PlayerValues[r][c].set(self.existingGroups[r][c]) def OptionMenu_Change(self, *args): self.checkvalues() if self.optV.get() != &quot;New Group&quot;: if self.OutputValues == self.CheckedValues: #check for changes made since loaded self.LoadData() else: x= mb.askyesno(&quot;Load Group?&quot;, f&quot;Do you want to load {self.optV.get()}? All unsaved changes will be lost.&quot;) if x == True: self.LoadData() self.getvalues() def DeleteGroup(self): if self.optV.get() != &quot;New Group&quot;: x= mb.askyesno(&quot;Delete Group?&quot;, f&quot;Delete the group {self.optV.get()} ?&quot;) if x == True: SQL.SendSQL(f'DELETE FROM Players WHERE &quot;Group Name&quot; = &quot;{self.optV.get()}&quot;;') self.optV.set(&quot;New Group&quot;) self.clearvalues() self.populateOM() def clearvalues(self): for r in range(0,7): for c in range(1,11): self.PlayerValues[r][c].set(&quot;&quot;) def SaveNClose(self): self.getvalues() window.destroy() pWindow=PlayerWindow(window) #make PlayerWindow an object(variable) window.mainloop() #keep window open until its forced closed class InputWindow: def __init__(self, title, question): self.window2 = Tk() self.window2.title(title) self.q = StringVar() Label(self.window2,text=question, wraplength=250).grid(row=0,column=1, columnspan=2) #question Entry(self.window2, textvariable=self.q, width =50).grid(row=1,column=1, padx=5, pady=2) Button(self.window2, text=&quot;Save&quot;, command=self.SaveNClose, width=10).grid(row=2,column=1,padx=5, pady=2) self.window2.mainloop() def SaveNClose(self): self.answer = self.q.get() self.window2.destroy() if pWindow.optN == &quot;New Group&quot;: if pWindow.OutputValues[0][1] != &quot;&quot;: inpWindow=InputWindow(&quot;Group Name&quot;, &quot;What would you like to name this group?&quot;) groupname = inpWindow.answer else: groupname = pWindow.optN #make sql value statements theValues = &quot;&quot; for x in range(0,7): if x &gt; 0: if pWindow.OutputValues[x][1] != &quot;&quot;: theValues = theValues + f&quot;,('{groupname}', '{pWindow.OutputValues[x][1]}','{pWindow.OutputValues[x][2]}','{pWindow.OutputValues[x][3]}','{pWindow.OutputValues[x][4]}','{pWindow.OutputValues[x][5]}','{pWindow.OutputValues[x][6]}','{pWindow.OutputValues[x][7]}','{pWindow.OutputValues[x][8]}','{pWindow.OutputValues[x][9]}','{pWindow.OutputValues[x][10]}','{pWindow.OutputValues[x][11]}')&quot; else: if pWindow.OutputValues[x][1] != &quot;&quot;: theValues = theValues + f&quot;('{groupname}', '{pWindow.OutputValues[x][1]}','{pWindow.OutputValues[x][2]}','{pWindow.OutputValues[x][3]}','{pWindow.OutputValues[x][4]}','{pWindow.OutputValues[x][5]}','{pWindow.OutputValues[x][6]}','{pWindow.OutputValues[x][7]}','{pWindow.OutputValues[x][8]}','{pWindow.OutputValues[x][9]}','{pWindow.OutputValues[x][10]}','{pWindow.OutputValues[x][11]}')&quot; #check if the players table exists yet and if not make it SQL.SendSQL(&quot;CREATE TABLE IF NOT EXISTS players ('Group Name','Player Name', 'Character Name', 'Class','Level', 'HP','STR', 'DEX', 'CON', 'INT', 'WIS', 'CHA')&quot;) #add group to players db if theValues != &quot;&quot;: SQL.SendSQL(f&quot;INSERT INTO players VALUES{theValues}&quot;) </code></pre>
[]
[ { "body": "<p>Welcome to Python, I do hope you find it a pleasant language to work with! The first few suggestions are really common for newcomers to Python, and the later points are just general suggestions for writing clean code (tips which will port to any language):</p>\n<ul>\n<li><p>Become roughly familiar with PEP8 (the official style guide for Python). The vast majority of Python coders follow the vast majority of its recommendations, resulting in most of the ecosystem being easy and consistent to read, and most people and IDE's will get upset with you if you don't follow it in general. Some particular points that are relevant to this review are</p>\n<ol>\n<li>Using snake-case variable names (<code>self.layout_window</code> rather than <code>self.layoutWindow</code>)</li>\n<li>Some spacing issues with commas (<code>[StringVar(), StringVar(), ...</code> rather than <code>[StringVar() ,StringVar() ,...</code>, and <code>[&quot;&quot;, &quot;&quot;, ...</code> instead of <code>[&quot;&quot;,&quot;&quot;,...</code>)</li>\n</ol>\n</li>\n<li><p>Don't run code in the top-level of your code file. <a href=\"https://www.cs.toronto.edu/%7Eguerzhoy/180/lectures/W04/lec1/MainBlock.html\" rel=\"noreferrer\">Use a main block at the end</a> (<a href=\"https://stackoverflow.com/questions/419163/what-does-if-name-main-do\">explanation here</a>). Note from the first link that if TKinter requires you to define some globals, that's ok for this application, but it's not a good habit to get into otherwise. The primary point of using a main block is to allow your code file to be either imported from another script to reuse its components (in which case you don't want to open a window, block the interpreter, etc.) or be run directly (in which case you do).</p>\n<pre><code>if __name__ == '__main__':\n SQL = SQLclass.Database(&quot;Players.db&quot;) #connect db\n pWindow=PlayerWindow(window) #make PlayerWindow an object(variable)\n window.mainloop() #keep window open until its forced closed\n</code></pre>\n</li>\n<li><p><a href=\"https://en.wikipedia.org/wiki/Don%27t_repeat_yourself\" rel=\"noreferrer\">Follow the DRY principle</a>. You have huge chunks of code that are the same line repeated a bunch of times with very little changed. This makes small logical changes require large code changes, and thus require more of your time. Instead, make efficient use of loops and data structures. Rule of thumb: if you're hitting &quot;copy/paste&quot; for a line of code, your code would probably be cleaner if you used a different approach to re-using that logic.</p>\n<ul>\n<li><p>Instead of:</p>\n<pre><code>Label(window,text=&quot;1&quot;).grid(row=1,column=0)\nLabel(window,text=&quot;2&quot;).grid(row=2,column=0)\nLabel(window,text=&quot;3&quot;).grid(row=3,column=0)\n# ...\n</code></pre>\n<p>use:</p>\n<pre><code>for player_num in range(1, number_of_players + 1):\n Label(window, text=str(player_num)).grid(row=player_num, column=0)\n</code></pre>\n</li>\n<li><p>You have huge chunks of logic repeated for each player. You could convert these into a loop like I show above, or you could pull Player logic out into a separate class:</p>\n<pre><code>class Player:\n def __init__(self, num):\n self.num = num\n self.player_name = StringVar()\n self.character_name = StringVar()\n # ...\n\n def insert_into_grid(self, window):\n for column, variable in [\n (1, self.player_name),\n (3, self.character_name),\n # ...\n ]:\n Entry(window, textvariable=variable).grid(row=1, column=column, padx=5, pady=2)\n</code></pre>\n<p>When combined with loops like shown above, things get a LOT simpler:</p>\n<pre><code>class PlayerWindow:\n def __init__(self, top):\n # You don't even need ``make_vars`` anymore\n self.num_players = 8\n self.players = [Player(i + 1) for i in range(self.num_players)]\n self.layout_window()\n self.add_buttons()\n self.populate_object_model()\n self.get_values()\n\n def layout_window(self):\n window.title(&quot;Player Entry Form&quot;)\n\n # numbers\n for player_num in range(1, self.num_players + 1):\n Label(window, text=str(player_num)).grid(row=player_num, column=0)\n\n for column, name in [\n (1, &quot;Player Name&quot;),\n (3, &quot;Character Name&quot;),\n # ...\n ]:\n Label(window, text=name).grid(row=0, column=column, padx=5, pady=2)\n\n for player in self.players:\n player.insert_into_grid(window)\n\n # Done!\n</code></pre>\n</li>\n</ul>\n</li>\n<li><p>Maintain a single authoritative source of information, particularly instead of your <code>self.outputN</code> and <code>self.checkN</code> variables. These are effectively caches of information that's actually controlled somewhere else, and every time you cache information, you're in for a world of hurt trying to ensure that cache never grows stale. If it's not a significant performance hit, it's <em>much</em> better to just re-compute the desired value on-demand. Think of it as creating a view into the data: the data lives in the Player objects, the view is the values of the check boxes and text boxes (<code>self.outputN</code> and <code>self.checkN</code>). Since these variables only exist to get collapsed into the <code>self.OutputValues</code> and <code>self.CheckedValues</code> list-of-lists, I'll just compute those directly:</p>\n<pre><code> class Player:\n # ...\n\n @property\n def attributes(self):\n return self.player_name, self.character_name, # ...\n\n\n class PlayerWindow:\n # ...\n\n @property\n def output_values(self):\n return [\n [attribute.get() for attribute in player.attributes]\n for player in self.players\n ]\n</code></pre>\n</li>\n<li><p>Use self-explanatory variable names. E.g., it's unclear to me without further digging what <code>self.optV</code>, <code>mb</code>, <code>pWindow</code> (what does the &quot;p&quot; mean?), and <code>theValues</code> are.</p>\n</li>\n</ul>\n<p>So in short, keep your data and code structured, make everything have a single source of truth (both for tracking data and for enforcing its structure), don't repeat yourself, try to write your code such that it's self-explaining (e.g. <code>for player in self.players: player.roll_dice()</code>), and, since you're in Python, follow the common PEP8 style guide.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-31T21:35:51.470", "Id": "248733", "ParentId": "248721", "Score": "7" } }, { "body": "<p>The immediate problem with the code is the sheer repetition in the middle. That will be difficult to maintain, since any non-trivial change to how data is managed will likely need to be made across all ~100 lines.</p>\n<p>Note these lines:</p>\n<pre><code>Label(window, text=&quot;1&quot;).grid(row=1, column=0)\nLabel(window, text=&quot;2&quot;).grid(row=2, column=0)\nLabel(window, text=&quot;3&quot;).grid(row=3, column=0)\nLabel(window, text=&quot;4&quot;).grid(row=4, column=0)\nLabel(window, text=&quot;5&quot;).grid(row=5, column=0)\nLabel(window, text=&quot;6&quot;).grid(row=6, column=0)\nLabel(window, text=&quot;7&quot;).grid(row=7, column=0)\nLabel(window, text=&quot;8&quot;).grid(row=8, column=0)\n</code></pre>\n<p>All that changes are the <code>text</code> and <code>row</code> arguments. The duplication in these lines can be reduced using a loop:</p>\n<pre><code>for n in range(1, 9):\n Label(window, text=str(n)).grid(row=n, column=0)\n</code></pre>\n<p>This can also be applied to more complex examples like:</p>\n<pre><code>Entry(window, textvariable=self.PlayerValues[0][1]).grid(row=1,column=1, padx=5, pady=2) \nEntry(window, textvariable=self.PlayerValues[1][1]).grid(row=2,column=1, padx=5, pady=2)\nEntry(window, textvariable=self.PlayerValues[2][1]).grid(row=3,column=1, padx=5, pady=2)\n. . .\n</code></pre>\n<p>Becomes:</p>\n<pre><code>for y in range(8):\n row = y + 1 # row can be calculated from y\n Entry(window, textvariable=self.PlayerValues[y][1]).grid(row=row, column=1, padx=5, pady=2)\n</code></pre>\n<p>If you apply that change to each of the chunks, you get something like:</p>\n<pre><code>N_PLAYERS = 8 # At the top somewhere\n\n. . .\n\nLabel(window, text=&quot;Player Name&quot;).grid(row=0, column=1, padx=5, pady=2)\nfor y in range(N_PLAYERS):\n Entry(window, textvariable=self.PlayerValues[y][1]).grid(row=y+1, column=1, padx=5, pady=2)\n\nLabel(window, text=&quot;Character Name&quot;).grid(row=0,column=3, padx=5, pady=2)\nfor y in range(N_PLAYERS):\n Entry(window, textvariable=self.PlayerValues[y][2]).grid(row=y+1,column=3, padx=5, pady=2)\n\nLabel(window, text=&quot;Class Name&quot;).grid(row=0,column=4, padx=5, pady=2)\nfor y in range(N_PLAYERS):\n Entry(window, textvariable=self.PlayerValues[0][3], width=12).grid(row=1,column=4, padx=5, pady=2) \n. . .\n</code></pre>\n<p>Which has much less duplication. It's not very pretty still, but it should be much easier to change if need be.</p>\n<p>It can be improved a bit by wrapping that duplicate code in a function, then calling the functions multiple times:</p>\n<pre><code>def produce_entries_chunk(label_text: str, values_x: int, entry_width: int, grid_column: int):\n Label(window, text=label_text).grid(row=0, column=grid_column, padx=5, pady=2)\n for y in range(N_PLAYERS):\n entry = Entry(window, textvariable=self.PlayerValues[y][values_x], width=entry_width)\n entry.grid(row=y+1, column=grid_column, padx=5, pady=2)\n</code></pre>\n<p>Which allows you to now write:</p>\n<pre><code>produce_entries_chunk(&quot;Player Name&quot;, 1, 2, 1)\nproduce_entries_chunk(&quot;Character Name&quot;, 2, 2, 3)\nproduce_entries_chunk(&quot;Class Name&quot;, 3, 12, 4)\n. . .\n</code></pre>\n<p>It becomes difficult to reduce down from here though due to the varying arguments passed in to each call. You could loop over tuples of <code>(1, 2, 1)</code>, <code>(2, 2, 3)</code>, <code>(3, 12, 4)</code>, . . . or something, but at some point it becomes counter-productive.</p>\n<hr />\n<p>Lines like this:</p>\n<pre><code>self.Player1 = [StringVar() ,StringVar() ,StringVar() ,StringVar() ,StringVar() ,StringVar() ,StringVar() ,StringVar() ,StringVar() ,StringVar() ,StringVar() ,StringVar()]\n</code></pre>\n<p>Can be reduced down to:</p>\n<pre><code>self.Player1 = [StringVar() for _ in range(12)]\n</code></pre>\n<p>Again, loops are super helpful when trying to reduce duplication, and list comprehensions especially are great for cases just like this. Just like before though, if you apply this change across the lines, you'll see a pattern:</p>\n<pre><code>self.Player1 = [StringVar() for _ in range(12)]\nself.Player2 = [StringVar() for _ in range(12)]\nself.Player3 = [StringVar() for _ in range(12)]\nself.Player4 = [StringVar() for _ in range(12)]\nself.Player5 = [StringVar() for _ in range(12)]\nself.Player6 = [StringVar() for _ in range(12)]\nself.Player7 = [StringVar() for _ in range(12)]\nself.Player8 = [StringVar() for _ in range(12)]\n\nself.output1 = [&quot;&quot;] * 12\nself.output2 = [&quot;&quot;] * 12\nself.output3 = [&quot;&quot;] * 12\nself.output4 = [&quot;&quot;] * 12\nself.output5 = [&quot;&quot;] * 12\nself.output6 = [&quot;&quot;] * 12\nself.output7 = [&quot;&quot;] * 12\nself.output8 = [&quot;&quot;] * 12\n</code></pre>\n<p>You're using numbers in the variable name to enumerate players, which later necessitates lines like:</p>\n<pre><code>self.PlayerValues = [self.Player1,self.Player2,self.Player3,self.Player4,self.Player5,self.Player6,self.Player7,self.Player8]\n\nself.CheckedValues = [self.check1,self.check2,self.check3,self.check4,self.check5,self.check6,self.check7,self.check8]\n \n</code></pre>\n<p>If you start putting numbers in a variable name, that's an indication that you should instead be using a list (or potentially a dictionary):</p>\n<pre><code>self.players = [[StringVar() for _ in range(12)] for _ in range(N_PLAYERS)]\nself.output = [[&quot;&quot;] * 12 for _ in range(N_PLAYERS)]\nself.checks = [[&quot;&quot;] * 12 for _ in range(N_PLAYERS)]\n</code></pre>\n<p>Also note that I lower-cased <code>players</code>. PEP8 says that regular variable names should be lowercase, separated by underscores.\n<a href=\"https://www.python.org/dev/peps/pep-0008/#function-and-variable-names\" rel=\"noreferrer\">enter link description here</a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-31T21:40:20.600", "Id": "248734", "ParentId": "248721", "Score": "8" } } ]
{ "AcceptedAnswerId": "248734", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-31T19:00:26.050", "Id": "248721", "Score": "6", "Tags": [ "python", "beginner" ], "Title": "GUI to load/save player information in database" }
248721