body
stringlengths
25
86.7k
comments
list
answers
list
meta_data
dict
question_id
stringlengths
1
6
<p>I need some pointers on how I can speed up my code, as of now it is incredible slow for larger inputs. The way the code works is that the file Loc_Circle_50U.txt contains the true locations of 50 vehicles while the files in ns3_files contain some erroneous locations. I analyze these differences which are stored as error, and based on the error and the velocities of the vehicles, I calculate if they are likely to collide. Time is divided into slots of 1 milliseconds.</p> <p><a href="https://drive.google.com/open?id=1iZ1r0NF2Pi3spprllwU-RvaBm5rPuz-N" rel="nofollow noreferrer">Testing files are shared here.</a> The <code>sumo_file = ['Loc_Circle_50U.txt']</code> is a global file which is 25MB when extracted, and the files listed in <code>ns3_files</code> that run one by one. Currently the one I have attached for <code>ns3_files</code> is a smaller one, and the bigger ones are around 30MB.</p> <pre><code>import numpy as np import pandas as pd import matplotlib.pyplot as plt import math from joblib import Parallel, delayed ns3_files = ['EQ_100p_1Hz_50U.txt','EQ_100p_5Hz_50U.txt','EQ_100p_10Hz_50U.txt', 'EQ_100p_20Hz_50U.txt','EQ_100p_30Hz_50U.txt','EQ_100p_40Hz_50U.txt','EQ_100p_50Hz_50U.txt','EQ_100p_100Hz_50U.txt'] sumo_file = ['Loc_Circle_50U.txt'] sumo_df = pd.read_csv(sumo_file[0], delim_whitespace = True) for qqq in sumo_file: rr = pd.read_csv(qqq, delim_whitespace=True) print("analyzing file ", qqq) if 'Time' in rr.columns: if 'VID' in rr.columns: if 'Pos(X)' in rr.columns: if 'Pos(Y)' in rr.columns: if 'Vel(X)' in rr.columns: if 'Vel(Y)' in rr.columns: print("sumo file ", qqq, " is OK") for qqq in ns3_files: rr = pd.read_csv(qqq, delim_whitespace=True) print("analyzing file ", qqq) if 'PId' in rr.columns: if 'TxId' in rr.columns: if 'RxId' in rr.columns: if 'GenTime' in rr.columns: if 'RecTime' in rr.columns: if 'Delay' in rr.columns: if 'TxTruePos(X)' in rr.columns: if 'TxHeadPos(X)' in rr.columns: if 'TxTruePos(Y)' in rr.columns: if 'TxHeadPos(Y)' in rr.columns: if 'Error(m)' in rr.columns: if 'Tx_HeadVelX' in rr.columns: if 'Tx_HeadVelY' in rr.columns: if 'RecvPos(X)' in rr.columns: if 'RecvPos(Y)' in rr.columns: print("ns3 file ", qqq, " is OK") prediction = 0 # 0 means no prediction and 1 is prediction enabled def calc_error(c): # pass the ns3 dataframe cleaned of all nan values. c.sort_values("RecTime") # print("c = ", c, " to be processed") nrows = c.shape[0] error = [] # will store slot wise error collision = 0 # will be 0 as long as ttc error &lt; 6.43. Becomes 1 if ttc_error exceeds 6.43 even for 1 slot ttc_error_x = 0 # calculates the ttc error in x for every slot ttc_error_y = 0 # calculates the ttc error in y for every slot ttc_error = [] # will store slot wise ttc error sender = c.loc[0, "TxId"] # sender will be the same throughout, so take the sender value from any row receiver = c.loc[0, "RxId"] # same as above # print("sender = ", sender, "receiver = ", receiver) if nrows==1: # only 1 message exchanged error_x_val = abs( (c["TxTruePos(X)"]) - c["TxHeadPos(X)"]).values[0] error_y_val = abs( (c["TxTruePos(Y)"]) - c["TxHeadPos(Y)"]).values[0] rel_vel_x = abs (c["Tx_HeadVelX"] - c["RecvVel(X)"]).values[0] rel_vel_y = abs (c["Tx_HeadVelY"] - c["RecvVel(Y)"]).values[0] # now for the relative velocity, which of the sender's velocity to take ? the sending instant or receiving instant ? # print("error_x = ", error_x, "rel_vel_x = ", rel_vel_x) if (rel_vel_x!=0): ttc_error_x = error_x_val/rel_vel_x else: ttc_error_x = 0 # rel vel same means no error if (rel_vel_y!=0): ttc_error_y = error_y_val/rel_vel_y else: ttc_error_y = 0 # print("1 packet scenario ", ttc_error_x, ttc_error_y, error_x_val, error_y_val, rel_vel_x, rel_vel_y) ttc_error.append(max(ttc_error_x, ttc_error_y)) err = c["Error(m)"].values[0] error.append(np.mean(err)) else: # more than 1 packet exchanged for k in range(nrows-1): # one k for each BSM. here BSMs are analyzed at reception instants current_bsm = c.loc[k] next_bsm = c.loc[k+1] slots = int(next_bsm['RecTime'] - current_bsm['RecTime'] - 1) current_time = current_bsm["RecTime"] # print("slots=", slots, "current_time=",current_time,"sender=",sender,"receiver=",receiver) mask_1 = (sumo_df['VID'] == sender) df_actual = sumo_df[mask_1] # df_actual is senders sumo information # print("current_bsm" , current_bsm) #["RecTime"]) #["RecvVel(X)"]) x_actual=(current_bsm["TxTruePos(X)"]) y_actual=(current_bsm["TxTruePos(Y)"]) x_header=(current_bsm["TxHeadPos(X)"]) y_header=(current_bsm["TxHeadPos(Y)"]) error_x_val = abs(x_actual - x_header) error_y_val = abs(y_actual - y_header) error.append(math.sqrt(error_x_val**2 + error_y_val**2)) # print("x_actual",x_actual,"y_actual",y_actual,"x_header",x_header,"y_header",y_header,"error_x_val",error_x_val,"error_y_val",error_y_val) #OK mask_2 = (df_actual["Time"]==current_time) sender_velocity_x = (df_actual[mask_2])["Vel(X)"].values[0] sender_velocity_y = (df_actual[mask_2])["Vel(Y)"].values[0] rel_vel_x = abs(sender_velocity_x - current_bsm["RecvVel(X)"]) rel_vel_y = abs(sender_velocity_y - current_bsm["RecvVel(Y)"]) # print("sender_velocity_x=",sender_velocity_x,"sender_velocity_y=",sender_velocity_y,"rec_vel_x=",current_bsm["RecvVel(X)"],"rec_vel_y",current_bsm["RecvVel(Y)"], \ # "rel_vel_x",rel_vel_x,"rel_vel_y",rel_vel_y) # the next are header info as error is from rx perspective and rx has only header info x_pos_BSM = c.loc[k, "TxHeadPos(X)"] y_pos_BSM = c.loc[k, "TxHeadPos(Y)"] x_speed_BSM = c.loc[k, "Tx_HeadVelX"] y_speed_BSM = c.loc[k, "Tx_HeadVelY"] if (rel_vel_x!=0): ttc_error_x = error_x_val/rel_vel_x else: ttc_error_x = 0 if (rel_vel_y!=0): ttc_error_y = error_y_val/rel_vel_y else: ttc_error_y = 0 ttc_error.append(max(ttc_error_x, ttc_error_y)) # print(" BSM at", time," rel_vel_x=",rel_vel_x,"rel_vel_y=",rel_vel_y,"error_x=",error_x,"error_y=",error_y ) # print("ttc_error_x=", ttc_error_x, "ttc_error_y=", ttc_error_y) for j in range(slots): # this for loop will run fir every slot in between 2 receptions # print("prediction slot = ", current_slot+j+1) x_pos_predicted = x_pos_BSM + prediction*(x_speed_BSM * (j+1))*(0.001) # as slots are in msec and speed in m/s y_pos_predicted = y_pos_BSM + prediction*(y_speed_BSM * (j+1))*(0.001) mask_3 = (df_actual["Time"] == (current_time + (j+1))) # df_actual has the senders info df_row = df_actual[mask_3] # print(df_row) # row of sumo file at the ongoing slot for receiver x_pos_actual = df_row["Pos(X)"].values[0] y_pos_actual = df_row["Pos(Y)"].values[0] # print("x actual=", x_pos_actual," y actual=",y_pos_actual," x pred=",x_pos_predicted, " y pred =", y_pos_predicted) error_x_val = abs((x_pos_predicted) - (x_pos_actual)) error_y_val = abs((y_pos_predicted) - (y_pos_actual)) error.append(error_x_val**2 + error_y_val**2) # print("x error = ", error_x, ", y error = ", error_y) receiver_mask = (sumo_df["VID"]==receiver) &amp; (sumo_df["Time"]==(current_time + (j+1))) df_receiver = sumo_df[receiver_mask] # the row for sender at that instant rel_vel_x = abs(df_row["Vel(X)"].values[0] - df_receiver["Vel(X)"].values[0]) rel_vel_y = abs(df_row["Vel(Y)"].values[0] - df_receiver["Vel(Y)"].values[0]) if (rel_vel_x!=0): ttc_error_x = error_x_val/rel_vel_x else: ttc_error_x = 0 if (rel_vel_y!=0): ttc_error_y = error_y_val/rel_vel_y else: ttc_error_y = 0 ttc_error.append(max(ttc_error_x, ttc_error_y)) # print("ttc_error_x=", ttc_error_x, "ttc_error_y=", ttc_error_y) # print("predslot",current_time+j+1,"x_actual",x_pos_actual,"y_actual",y_pos_actual,"x_predicted",x_pos_predicted,"y_predicted",y_pos_predicted,"error_x_val",error_x_val,"error_y_val",error_y_val) #, " is ", slot_error) # add the last packet details err_lastpacket = c.loc[nrows-1, "Error(m)"] error.append(err_lastpacket) current_time = c.loc[nrows-1, "RecTime"] error_x_val = abs( (c.loc[nrows-1,"TxTruePos(X)"]) - c.loc[nrows-1,"TxHeadPos(X)"]) error_y_val = abs( (c.loc[nrows-1,"TxTruePos(Y)"]) - c.loc[nrows-1,"TxHeadPos(Y)"]) sender_mask = ((sumo_df["VID"]==sender) &amp; (sumo_df["Time"]==(current_time))) sender_x_vel = (sumo_df[sender_mask])["Vel(X)"].values[0] sender_y_vel = (sumo_df[sender_mask])["Vel(Y)"].values[0] rel_vel_x = abs (sender_x_vel - c.loc[nrows-1,"RecvVel(X)"]) rel_vel_y = abs (sender_y_vel - c.loc[nrows-1,"RecvVel(Y)"]) if (rel_vel_x!=0): ttc_error_x = error_x_val/rel_vel_x # print("error_x_val",error_x_val,"rel_vel_x",rel_vel_x) else: ttc_error_x = 0 if (rel_vel_y!=0): ttc_error_y = error_y_val/rel_vel_y else: ttc_error_y = 0 # print("ttc_error_x",ttc_error_x, "ttc_error_y",ttc_error_y) ttc_error.append(max(ttc_error_x, ttc_error_y)) # print("current_time",current_time,"sender ",sender) # print("overall error", error) # print("overall ttc_error", ttc_error) # print("\n") # print("error for sender", sender, "and receiver", receiver, "is", error) avg_error = np.mean(error) if np.mean(ttc_error)&gt;6.43: collision = 1 else: collision = 0 return (avg_error, collision) overall_errors = [] # to store error per file overall_collisions = [] # to store collision per file def start_process(fil): print("File ", fil, " started") b = pd.read_csv(fil, delim_whitespace = True) b = b.sort_values(['RecTime']) b = b.reset_index(drop=True) m = b['RxId'].nunique() # m is number of receivers # throughput block starts # overall_duration = (b['RecTime'].max() - b['RecTime'].min())/1000 # milliseconds to seconds ## in throughput case, we work on the whole file so 1 pair or 1 packet exchanged cases do not apply. # packets = b.shape[0] # no of rows = no of packets received receivers = b['RxId'].unique() average_errors = [] # hold error for every pair in a file average_collisions = [] # hold collision (0 or 1) for every pair in a file # collisions = 0 # will have the number of collision risky pairs in every file for i in range(len(receivers)): receiver = receivers[i] # for every receiver senders = b[b['RxId'] == receiver].TxId.unique() for j in range(len(senders)): sender = senders[j] mask = (b['RxId'] == receiver) &amp; (b['TxId'] == sender) # extract out the rx-tx pair # print("cc=",cc) c = b[mask] c = c.reset_index(drop=True) # print("cc=",cc) # print("error calculation for sender ",sender, " and receiver ", receiver, "\n") # print("c = ", c , "before being sent") avg_error, collision = calc_error(c) # calc_error is the function # this will give the whole error for that pair # pos_error should return a value of error # avg_error = np.sum(pos_error)/overall_duration # errors for single pair average_errors.append(avg_error) # average_errors will hold the error for every pair in a file average_collisions.append(collision) # print("average errors for Tx ",sender, " and receiver ", receiver, " is ", avg_error, "\n") # print("collision status is ", collision) # print("average_collisions", average_collisions,"average_errors",average_errors) average_error = np.average(average_errors) average_collision = np.average(average_collisions) print("File ", fil, " completed") # print("\n") # print("average_error = ", average_error) overall_collisions.append(average_collision) overall_errors.append(average_error) # print(average_errors) if prediction==0: print("for file ", fil, file = open("parallel_error_collision_P.txt", "a")) print("no prediction result follows with prediction flag =", prediction, file = open("parallel_error_collision_P.txt", "a")) print("overall_collisions = ", overall_collisions, file = open("parallel_error_collision_P.txt", "a")) print("overall_errors = ", overall_errors,"\n", file = open("parallel_error_collision_P.txt", "a")) else: print("for file ", fil, file = open("parallel_error_collision_P.txt", "a")) print("prediction assisted result follows with prediction flag =", prediction, file = open("parallel_error_collision_P.txt", "a")) print("overall_collisions = ", overall_collisions, file = open("parallel_error_collision_P.txt", "a")) print("overall_errors = ", overall_errors, "\n", file = open("parallel_error_collision_P.txt", "a")) Parallel(n_jobs=len(ns3_files))(delayed(start_process)(fil) for fil in ns3_files) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-31T18:38:29.717", "Id": "470239", "Score": "1", "body": "You should provide some means for others to test the code, ideally on a simple input and on the problematic one. The code is certainly hard to read (too many nesting levels for a start...), which makes it harder to find the speed bottleneck. Have you tried profiling your code?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-31T18:41:16.750", "Id": "470240", "Score": "0", "body": "@norok2 no I haven't tried profiling. Most of the mathematical operations that I use are linear, so it is confusing why it's so slow. I will try profiling.Also, do i need to upload some files where the program can be tested ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-31T20:09:14.570", "Id": "470243", "Score": "0", "body": "Uploading test files would be very helpful." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-01T00:20:28.673", "Id": "470256", "Score": "0", "body": "@pacmaninbw I have added the testing files, link is in the question description." } ]
[ { "body": "<p>I see a number of things that may help you improve your program.</p>\n\n<h2>Decompose the code into smaller functions</h2>\n\n<p>This code is very dense, very long and not well organized making it difficult to follow and understand. As a first step, I'd recommend extracting out smaller functions, such as to calculate error values. Each function should be small, well documented and testable.</p>\n\n<h2>Pass needed variables</h2>\n\n<p>Instead of relying on interspersed code and function declarations as in this code, gather things into a <code>main</code> function. Here's one way to do that:</p>\n\n<pre><code>if __name__ == \"__main__\":\n prediction = 0 # 0 means no prediction and 1 is prediction enabled\n\n ns3_files = ['EQ_100p_1Hz_50U.txt','EQ_100p_5Hz_50U.txt','EQ_100p_10Hz_50U.txt',\n 'EQ_100p_20Hz_50U.txt','EQ_100p_30Hz_50U.txt','EQ_100p_40Hz_50U.txt',\n 'EQ_100p_50Hz_50U.txt','EQ_100p_100Hz_50U.txt']\n\n sumo_file = ['Loc_Circle_50U.txt']\n sumo_df = pd.read_csv(sumo_file[0], delim_whitespace = True)\n sumo_headers = {'Time', 'VID', 'Pos(X)', 'Pos(Y)', 'Vel(X)', 'Vel(Y)'} \n if validate_headers(sumo_df, sumo_headers):\n print(\"sumo file \", sumo_file[0], \" is OK\")\n\n [start_process(fil, sumo_df) for fil in ns3_files]\n</code></pre>\n\n<h2>Write more \"pythonic\" code</h2>\n\n<p>Python makes extensive use of data structure such as lists, dictionaries and sets. If you find yourself writing long <code>if</code> constructs as in this code, STOP! There is almost always a better way to do it. For example, you'll see that in the sample code above there is a <code>validate_headers</code> function. Here's the definition</p>\n\n<pre><code>def validate_headers(df, headerset):\n return headerset &lt;= set(df.columns.values)\n</code></pre>\n\n<p>It uses the <code>&lt;=</code> operator on two sets to determine whether one is a strict subset of the other. In this case, we're trying to assure that all of the required fields exist in a dataframe, so we pass the dataframe and the set of header names. Simple!</p>\n\n<h2>Don't do redundant work</h2>\n\n<p>The original code loads the entire dataframe of each file just to validate the header and then loads it again to actually process the data. This is pointless and wastes time and memory.</p>\n\n<h2>Use <code>pandas</code> as it is intended</h2>\n\n<p>Iterating over <code>pandas</code> data, row by row using an index is the very slowest possible way to process the data. Instead, you should seek to use <em>vectorization</em>. For example, if you want to create a new column <code>errx</code> for each row in the dataframe, you could write this:</p>\n\n<pre><code>df['errx'] = abs(df['TxTruePos(X)'] - df['TxHeadPos(X)'])\n</code></pre>\n\n<p>Using vectorized operations is the way pandas is intended to be used and is very efficient compared to using <code>for</code> loops. If you find you need still more performance, however, you can use <code>numpy</code>, which you're already including but not making much use of.</p>\n\n<h2>Understand your data</h2>\n\n<p>I haven't validated all of it, but it appears that much of the calculation may be redundant. For example, the program calculates an <code>error_x_val</code> but the <code>ns3_data</code> files appear to already have such a column. If that actually contains the data you need, use it instead of recalculating. If it doesn't, I'd suggest dropping it from the data frame if it's not useful. That can be done like this:</p>\n\n<pre><code>del df['Error(X)']\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-06T05:00:24.540", "Id": "470753", "Score": "0", "body": "I tried to implement most of the recommendations listed in your answer @Edward, but I guess my way of writing the program, in terms of the sequence of operations I follow and other things, is not optimum. Vectorization, as mentioned in the answer, was the most significant improvement bringer. Overall, the code has around 11000 pairs of vehicles and each pair needs to be processed, so maybe parallelizing the for loop that calls `calc_error(c)` could be the best thing I could do as each pair is independent, though not sure if that can be done. With the code as it is, this is the best I could do." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-02T12:43:08.280", "Id": "239799", "ParentId": "239697", "Score": "3" } } ]
{ "AcceptedAnswerId": "239799", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-31T13:11:46.643", "Id": "239697", "Score": "4", "Tags": [ "python", "performance", "python-3.x", "numpy", "pandas" ], "Title": "Code for wireless communication work" }
239697
<p>The following is a simple class for establishing multiple http connections, mainly for downloading a list of small files:</p> <pre><code>#include &lt;cpprest/http_client.h&gt; #include&lt;string&gt; #include&lt;vector&gt; #include &lt;mutex&gt; #include &lt;cpprest/filestream.h&gt; using namespace utility; // Common utilities like string conversions using namespace web; // Common features like URIs. using namespace web::http; // Common HTTP functionality using namespace web::http::client; // HTTP client features using namespace concurrency::streams; // Asynchronous streams class ConnectionPool { public: ConnectionPool(size_t nWorkers, std::wstring baseUri) :BaseUri(baseUri) { for (size_t i = 0; i &lt; nWorkers; i++) Pool.emplace_back(http_client(baseUri), http_request(methods::GET)); } void ResetState(size_t nWorkers, std::wstring baseUri) { BaseUri = baseUri; nDone = 0; Pool.clear(); for (size_t i = 0; i &lt; nWorkers; i++) Pool.emplace_back(http_client(baseUri), http_request(methods::GET)); } void ResizePool(size_t nWorkers) { Pool.resize(nWorkers, { http_client(BaseUri) , http_request(methods::GET) }); } /*template&lt;typename Function&gt; void DownloadAsync(std::vector&lt;std::wstring&gt; Uris, const Function&amp; f)//Not implemented { WorkItems = Uris; const size_t limit = (std::min)(Pool.size(), WorkItems.size()); for (size_t i = 0; i &lt; limit; i++) assignWork(i, f); }*/ template&lt;typename Function&gt; void DownloadSync(const std::vector&lt;std::wstring&gt; Uris, const Function&amp; f) { std::wcout &lt;&lt; "*DownloadSync Started*" &lt;&lt; std::endl; WorkItems = Uris; for (size_t i = nDone = 0, limit = nActive = std::min(Pool.size(), WorkItems.size()); i &lt; limit; ++i) assignWork(i, f); std::unique_lock&lt;std::mutex&gt; lk(m1); cv.wait(lk, [&amp;]() { return nActive == 0; }); std::wcout &lt;&lt; "*DownloadSync Ended*" &lt;&lt; std::endl; } template&lt;typename Function&gt; void assignWork(int pidx, const Function&amp; f) { //m2 isn't needed, right?! //m2.lock(); if (nDone &gt;= WorkItems.size()) { std::lock_guard&lt;std::mutex&gt; lk(m1); --nActive; cv.notify_one(); //m2.unlock(); return; } const auto wItem = WorkItems[nDone]; int cIdx = nDone; ++nDone; //m2.unlock(); std::wcout &lt;&lt; L"Worker " &lt;&lt; pidx &lt;&lt; L": Assigning/t" &lt;&lt; wItem &lt;&lt; L" succeed" &lt;&lt; std::endl; auto&amp; [client, request] = Pool[pidx]; request.set_request_uri(wItem); client.request(request).then([=](pplx::task &lt;http_response&gt; responseTask) { try { if (auto response = responseTask.get(); response.status_code() == http::status_codes::OK) { f(response, cIdx); std::wcout &lt;&lt; L"Worker " &lt;&lt; pidx &lt;&lt; L": Downloading/t" &lt;&lt; wItem &lt;&lt;L" succeed"&lt;&lt; std::endl; } else std::wcout &lt;&lt; L"Worker " &lt;&lt; pidx &lt;&lt; L": Downloaded/t" &lt;&lt; wItem &lt;&lt; L" failed with the following code "&lt;&lt; response.status_code() &lt;&lt; std::endl; } catch (const web::http::http_exception&amp; ex) { std::wcout &lt;&lt; L"Worker " &lt;&lt; pidx&lt;&lt;L":Requesting "&lt;&lt;wItem &lt;&lt; L" failed with exception (" &lt;&lt; ex.error_code()&lt;&lt;L"): " &lt;&lt; ex.what() &lt;&lt; " : " &lt;&lt; std::endl; } try { assignWork(pidx, f);} catch (const std::exception&amp; ex) { std::wcout &lt;&lt; L"Worker " &lt;&lt; pidx &lt;&lt; L": Assigning/t" &lt;&lt; wItem &lt;&lt; L" Failed with exception: " &lt;&lt; ex.what() &lt;&lt; std::endl; } }); } ~ConnectionPool() { } private: std::vector&lt;std::pair&lt;http_client, http_request&gt;&gt; Pool; std::vector&lt;std::wstring&gt; WorkItems; std::wstring BaseUri; std::mutex m1/*,m2*/; std::condition_variable cv; std::atomic&lt;int&gt; nActive = 0, nDone = 0; }; int main() { //....code....// ConnectionPool con(n, L"base url"); con.DownloadSync(urls, [](http_response res, int idx) { auto outFile = fstream::open_ostream(std::to_wstring(idx) + L".ext").get(); res.body().read_to_end(outFile.streambuf()).wait(); outFile.close().wait(); }); } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-31T14:43:54.580", "Id": "470224", "Score": "1", "body": "Any specific aspect to review?" } ]
[ { "body": "<h1>Interface</h1>\n\n<p>Prefer <a href=\"https://en.cppreference.com/w/cpp/string/basic_string_view\" rel=\"nofollow noreferrer\"><code>wstring_view</code></a> to <code>wstring</code> for parameters to save one copy:</p>\n\n<pre><code>ConnectionPool(std::size_t nWorkers, std::wstring_view baseUri)\n</code></pre>\n\n<p>(Whether this is effective depends on the way <code>http_client</code> works.)</p>\n\n<blockquote>\n<pre><code>void assignWork(int pidx, const Function&amp; f)\n</code></pre>\n</blockquote>\n\n<p><code>std::size_t pidx</code>, I guess? (Same for other occurrences of <code>int</code>.)</p>\n\n<blockquote>\n<pre><code>~ConnectionPool()\n{\n}\n</code></pre>\n</blockquote>\n\n<p>Remove this destructor; the only thing it does is prevent move operations from generating.</p>\n\n<h1>Locking</h1>\n\n<blockquote>\n<pre><code>//m2 isn't needed, right?!\n//m2.lock();\n</code></pre>\n</blockquote>\n\n<p>Regardless of whether it's needed, use</p>\n\n<pre><code>std::lock_guard lock{m2};\n</code></pre>\n\n<p>so you don't have to repeat the unlock operation.</p>\n\n<h1>Loops</h1>\n\n<p>Don't squeeze everything on one line like this:</p>\n\n<blockquote>\n<pre><code>ConnectionPool(size_t nWorkers, std::wstring baseUri) :BaseUri(baseUri)\n{\n for (size_t i = 0; i &lt; nWorkers; i++) Pool.emplace_back(http_client(baseUri), http_request(methods::GET));\n}\n</code></pre>\n</blockquote>\n\n<p>Directly using the constructor of <code>vector</code> looks better (and avoids reallocation):</p>\n\n<pre><code>ConnectionPool(std::size_t nWorkers, std::wstring_view baseUri)\n : BaseUri(baseUri)\n , Pool(nWorkers, {http_client(baseUri), http_request(methods::GET)})\n{\n}\n</code></pre>\n\n<p>This line is especially unreadable:</p>\n\n<blockquote>\n<pre><code>for (size_t i = nDone = 0, limit = nActive = std::min(Pool.size(), WorkItems.size()); i &lt; limit; ++i) assignWork(i, f);\n</code></pre>\n</blockquote>\n\n<p>Break it into lines:</p>\n\n<pre><code>nDone = 0;\nlimit = nActive = std::min(Pool.size(), WorkItems.size());\nfor (std::size_t i = 0; i &lt; limit; ++i) {\n assignWork(i, f);\n}\n</code></pre>\n\n<h1>Miscellaneous</h1>\n\n<p><code>size_t</code> &rightarrow; <code>std::size_t</code>. And <code>#include &lt;cstddef&gt;</code> for it.</p>\n\n<blockquote>\n<pre><code>#include &lt;cpprest/http_client.h&gt;\n#include&lt;string&gt;\n#include&lt;vector&gt;\n#include &lt;mutex&gt;\n#include &lt;cpprest/filestream.h&gt;\n</code></pre>\n</blockquote>\n\n<p>Two remarks:</p>\n\n<ul>\n<li><p>consistently put a space after <code>#include</code>;</p></li>\n<li><p>group <code>cpprest</code> headers together.</p></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-03T12:22:13.043", "Id": "239866", "ParentId": "239700", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-31T14:36:07.123", "Id": "239700", "Score": "4", "Tags": [ "c++" ], "Title": "simple parallel download using a connection Pool class using cpprestsdk" }
239700
<p>I wanted a simple code review for improvement to increase the efficiency of my text generating model. This model is taken from the official TensorFlow site but is being trained on different datasets. I am using TensorFlow 2.0 (beta1) GPU version and Keras.</p> <p>I was training this on a Harry Potter book but I found that the output was not the best, despite training it for a couple of hours(when loss stabilized at around 0.0565). Here is the code:-</p> <pre><code>import numpy as np import tensorflow as tf import matplotlib.pyplot as plt from keras.models import Sequential from keras.layers import Dense from keras.layers import Dropout from keras.callbacks import ModelCheckpoint from keras.layers import LSTM from keras.utils import np_utils import os text = open ("/home/awesome_ruler/Documents/Atom projects/HarryPotter/hp.txt").read() vocab = sorted(set(text)) # Creating a mapping from unique characters to indices char2idx = {u:i for i, u in enumerate(vocab)} idx2char = np.array(vocab) text_as_int = np.array([char2idx[c] for c in text]) # The maximum length sentence we want for a single input in characters seq_length = 200 examples_per_epoch = len(text)//(seq_length+1) # Create training examples / targets char_dataset = tf.data.Dataset.from_tensor_slices(text_as_int) sequences = char_dataset.batch(seq_length+1, drop_remainder=True) def split_input_target(chunk): input_text = chunk[:-1] target_text = chunk[1:] return input_text, target_text dataset = sequences.map(split_input_target) # Batch size BATCH_SIZE = 64 # DEfault is 64 # Buffer size to shuffle the dataset # (TF data is designed to work with possibly infinite sequences, # so it doesn't attempt to shuffle the entire sequence in memory. Instead, # it maintains a buffer in which it shuffles elements). BUFFER_SIZE = 10000 dataset = dataset.shuffle(BUFFER_SIZE).batch(BATCH_SIZE, drop_remainder=True) # Length of the vocabulary in chars vocab_size = len(vocab) # The embedding dimension embedding_dim = 256 # Number of RNN units rnn_units = 960 # 32 multiple def build_model(vocab_size, embedding_dim, rnn_units, batch_size): model = tf.keras.Sequential([ tf.keras.layers.Embedding(vocab_size, embedding_dim, batch_input_shape=[batch_size, None]), tf.keras.layers.LSTM(rnn_units, return_sequences=True, stateful=True, recurrent_initializer='glorot_uniform'), tf.keras.layers.Dropout(0.5), tf.keras.layers.Dense(vocab_size) ]) return model model = build_model( vocab_size = len(vocab), embedding_dim=embedding_dim, rnn_units=rnn_units, batch_size=BATCH_SIZE) def loss(labels, logits): return tf.keras.losses.sparse_categorical_crossentropy(labels, logits, from_logits=True) model.compile(optimizer='Adam', loss=loss) # Directory where the checkpoints will be saved checkpoint_dir = '/home/awesome_ruler/Documents/Atom projects/HarryPotter/CheckPoints' checkpoint_prefix = os.path.join(checkpoint_dir, "ckpt_{epoch}") checkpoint_callback=tf.keras.callbacks.ModelCheckpoint( filepath=checkpoint_prefix, save_weights_only=True) EPOCHS=350 history = model.fit(dataset, epochs=EPOCHS, callbacks=[checkpoint_callback]) # Comment to evaluate the model checkpoint_dir = 'CheckPoints/ckpt_380' model = build_model(vocab_size, embedding_dim, rnn_units, batch_size=1) model.load_weights(checkpoint_dir) model.summary() def generate_text(model, start_string): # Evaluation step (generating text using the learned model) # Number of characters to generate num_generate = 1000 # Converting our start string to numbers (vectorizing) input_eval = [char2idx[s] for s in start_string] input_eval = tf.expand_dims(input_eval, 0) # Empty string to store our results text_generated = [] # Low temperatures results in more predictable text. # Higher temperatures results in more surprising text. # Experiment to find the best setting. temperature = 0.2 # Here batch size == 1 model.reset_states() for i in range(num_generate): predictions = model(input_eval) # remove the batch dimension predictions = tf.squeeze(predictions, 0) # using a categorical distribution to predict the character returned by the model predictions = predictions / temperature predicted_id = tf.random.categorical(predictions, num_samples=1)[-1,0].numpy() # We pass the predicted character as the next input to the model # along with the previous hidden state input_eval = tf.expand_dims([predicted_id], 0) text_generated.append(idx2char[predicted_id]) return (start_string + ''.join(text_generated)) print(generate_text(model, start_string=u"homework")) </code></pre> <blockquote> <p>Since the original dataset had many more characters, I reduced the Rnn units, keeping it a multiple of 32. Also, I converted the GRU layer to LSTM as it has better memory holding capability(theoretically). Can anyone suggest any other improvements? I would be really glad to know them</p> </blockquote> <p>Also, here is some sample output to show you an Idea of how bad the model is (I think the main reason is that the dataset is very small). But is there still something that can be done?</p> <pre><code>homework than Privet Drive, which was difficult as there wasn’t much longerulble – he went into the living-room window. Harry was streaming it all right – now, where at last on to a confused – and we couldn’t remember what I said what’s best is tites, but the reflected here, sixteen minutes later, Dumbledore with the Quidditch Cup, what’s already.’ He was engreed. It was a very direction boats as passing the wall, because of it and the fire, flanding in the middle of a ploughed field, halfway across a suspension bridge and at the top of a munched of ‘Hagrid’s arms ... this is what is it?’ Harry whispered. ‘It’s the black eyes on his cupboard, there’s something you’ve got your owl broomstick, Potter’s obviously spet the only one who’ve got yeh anything ... ‘Master,’ Harry tried. And there, she were all get still staring at the cart. He was still started looking from the roof of his neck, and fell one of them at night and getting pellets were died. He managed to bane when we arrived. </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-31T16:58:19.230", "Id": "470231", "Score": "2", "body": "So, you want better output because the current is unsatisfactory and you borrowed most of the code?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-31T17:06:28.507", "Id": "470232", "Score": "0", "body": "@Mast Basically, I want to get a feel for transfer learning - adapting existing models on a new dataset. Since it is my first time, I want to know what parts of the code are the ones usually targeted my pros when optimizing a specific code for some other dataset. This would help me much in my other projects. Advice about the no. of layers and rnn units is also very helpful and appreciated" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-31T16:08:58.620", "Id": "239702", "Score": "2", "Tags": [ "python", "machine-learning", "tensorflow" ], "Title": "ML text generating code with Python and Tensorflow" }
239702
<p>I've spent the last few days learning the beginnings of how to implement a simple neural network. I've gone through chapters 1 and 2 of this <a href="http://neuralnetworksanddeeplearning.com/chap1.html" rel="nofollow noreferrer">book</a> and have tried to write my own NN with referrals to the code given when I had some trouble.</p> <p>I am working with the mnist dataset. At the bottom of my question I have listed the equations that I am using from the book. The following are the what I expect to be the dimensions of the matrices used for the calculations based on the network structure:</p> <p>number of neurons in each layers 1, 2 and 3: <span class="math-container">$$n = 784, 16, 10$$</span> weight matrices in layer 2 and 3: <span class="math-container">$$w = [16, 784], [10, 16]$$</span> biases for layers 2 and 3: <span class="math-container">$$b = [16, 1], [10, 1]$$</span> weighted sum inputs to layers 2 and 3: <span class="math-container">$$z = [16, 1], [10, 1]$$</span> gradient vectors for weights: <span class="math-container">$$\nabla w = [16, 784], [10, 16]$$</span> gradient vectors for biases: <span class="math-container">$$\nabla b = [16, 1], [10, 1]$$</span></p> <p>One curiosity I have from the book is that the inputs to the network are considered activations in the code but this is not mentioned anywhere in it so far as I could find. i.e. x = activations[0]. Based on this the sizes for the activation output arrays for layers 1, 2 and 3 would be: <span class="math-container">$$a = [784, 1], [16, 1], [10, 1]$$</span></p> <p>If my matrix dimensions are correct and the equations I am using provided at the bottom are correct, well obviously I should get the right results. What I'm hoping someone can do for me is point out where I am making mistakes with the matrix operations used for backpropagation equations.</p> <pre><code>import random import numpy as np class NeuralNetwork: def __init__(self, inputs, targets, hidden, n_outputs, learning_rate, epochs, batch_size): # training and testing data self.training_inputs = inputs # network inputs self.targets = targets # target outputs for the training data self.n_data = len(self.training_inputs) # number of training data # network structure self.n_inputs = len(self.training_inputs[0]) # number of input nodes self.hidden_layers = hidden # list containing the number of neurons in each hidden layer. Layer number is the index. self.n_outputs = n_outputs # number of outputs in the final layer n_nuerons = [[self.n_inputs], self.hidden_layers, [self.n_outputs]] self.layers = [x for s in n_nuerons for x in s] # list of the number of neurons in each layer. Layer number is the index self.n_layers = len(self.layers) # number of layers in the network # hyperparameters self.learning_rate = learning_rate self.epochs = epochs self.batch_size = batch_size # batching is not implemented yet.. using online learning # initialise matrices self.b, self.z = [], [] for neurons in self.layers[1:]: # loop through all layers except the input network layer self.b.append(np.random.randn(neurons)) # biases self.z.append(np.zeros(neurons)) # layer weighted sum inputs self.a = [np.zeros(n) for n in self.layers] # activation outputs - including inputs to network as activation outputs for layer 0 self.w = [np.random.rand(self.layers[i + 1], self.layers[i]) - 0.5 for i in range(self.n_layers - 1)] # weights self.train() def train(self): for epoch in range(self.epochs): random.shuffle(self.training_inputs) sum_error = 0 for index in range(self.n_data): # forward pass x = self.training_inputs[index] self.a[0] = x outputs = self.feedforward(x) sum_error += sum(self.cost(outputs, index)) # backward pass dw, db = self.backpropagation(index) self.update_weights(dw, db) print('&gt;epoch=%d, error=%.3f' % (epoch, sum_error)) def feedforward(self, output): for layer in range(self.n_layers - 1): self.z[layer] = np.dot(self.w[layer], self.a[layer]) + self.b[layer] # layer inputs self.a[layer + 1] = self.sigmoid(self.z[layer]) # output activations return self.a[-1] def backpropagation(self, index): # initialise gradient matrices dw = [np.zeros(w.shape) for w in self.w] db = [np.zeros(n) for n in self.layers[1:]] # loop backwards through network layers for i in reversed(range(1, self.n_layers)): if i == self.n_layers - 1: # output layer db[-1] = (self.a[-1] - self.targets[index]) * self.sp(self.z[-1]) dw[-1] = np.dot(np.asmatrix(db[-1]), np.asmatrix(self.a[-2]).transpose()) else: # all other layers # NOTE: to compute the weight gradient vector for hidden layer 1 the inputs to the network are used as activation outputs db[i - 1] = np.multiply(np.dot(np.transpose(self.w[i]), db[i]), self.sp(self.z[i - 1])) dw[i - 1] = np.dot(np.asmatrix(db[i - 1]), np.asmatrix(self.a[i - 2]).transpose()) return dw, db def update_weights(self, dw, db): self.w = np.array([w - self.learning_rate * nw for w, nw in zip(self.w, dw)]) self.b = np.array([b - self.learning_rate * nb for b, nb in zip(self.b, db)]) def cost(self, outputs, index): return (self.targets[index] - outputs) ** 2 @staticmethod def sigmoid(z): return 1 / (1 + np.exp(-z)) @staticmethod def sp(z): return z * (1.0 - z) # Program driver if __name__ == '__main__': data = np.load('mnist.npz') (training_images, test_images) = data['x_train'], data['x_test'] (training_labels, test_labels) = data['y_train'], data['y_test'] n_outputs = 10 training_inputs = np.array([data.flatten() / 255 for data in training_images]) training_targets = [] for i in range(len(training_labels)): training_targets.append([1 if training_labels[i] == x else 0 for x in range(n_outputs)]) nn = nn.NeuralNetwork(training_inputs, np.array(training_targets), [16], n_outputs, learning_rate=0.1, epochs=10, batch_size=100) </code></pre> <p>For reference these are the equations I am using for the backpropagation taken more or less directly from the book.</p> <p>The output errors are calculated using the gradient of the cost function wrt the output activations and the slope of the activation function evaluated at the inputs to the output layer: <span class="math-container">$$\delta^L = \nabla_aC\odot\sigma'({z^L)}$$</span></p> <p>The errors in all other layers are found by backpropagating the error in the <em>next</em> layer through the weights and taking the product of this result with the slope of the activation function evaluated at the inputs to the layer.</p> <p><span class="math-container">$$\delta^l = (w^{l+1})^T\delta^{l+1}\odot\sigma'({z^l)} = (a^L-y)\odot \sigma'(z^L)$$</span></p> <p>The error for a given layer calculated using the above equations is the partial derivative of the cost function wrt the biases. Therefore the biases need to be changed by this amount.</p> <p><span class="math-container">$$\frac{\partial C}{\partial b_j^l}=\delta_j^{l}$$</span></p> <p>The equation used to find the change in weight <em>w</em> required to reduce cost function is: <span class="math-container">$$\frac{\partial C}{\partial w_{jk}^l}=a^{l-1}_k\delta_j^l$$</span></p> <p>Finally the equations that will be used to update the weights and bias matrices are: <span class="math-container">$$w^l \rightarrow w^l-\eta \delta^{l} (a^{l-1})^T$$</span> <span class="math-container">$$b^l \rightarrow b^l-\eta \delta^{l}$$</span></p> <p>The code is on <a href="https://github.com/ad-1/MachineLearning/tree/master/neural_network" rel="nofollow noreferrer">github</a> with the mnist included for anyone who may need it. Any comments, corrections, criticisms, all and everything welcome with the aim of learning.. Thanks!</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-31T18:48:40.183", "Id": "239705", "Score": "2", "Tags": [ "python", "machine-learning", "neural-network" ], "Title": "simple neural network in python" }
239705
<blockquote> <p>Exercise: Design a Stack</p> <p>A Stack is a data structure for storing a list of elements in a LIFO (last in, first out) fashion. Design a class called Stack with three methods.</p> <pre><code>void Push(object obj) object Pop() void Clear() </code></pre> <p>The <code>Push()</code> method stores the given object on top of the stack. We use the “object” type here so we can store any objects inside the stack. Remember the “object” class is the base of all classes in the .NET Framework. So any types can be automatically upcast to the object. Make sure to take into account the scenario that null is passed to this object. We should not store null references in the stack. So if null is passed to this method, you should throw an <code>InvalidOperationException</code>. Remember, when coding every method, you should think of all possibilities and make sure the method behaves properly in all these edge cases. That’s what distinguishes you from an “average” programmer.</p> <p>The <code>Pop()</code> method removes the object on top of the stack and returns it. Make sure to take into account the scenario that we call the Pop() method on an empty stack. In this case, this method should throw an <code>InvalidOperationException</code>. Remember, your classes should always be in a valid state and used properly. When they are misused, they should throw exceptions. Again, thinking of all these edge cases, separates you from an average programmer. The code written this way will be more robust and with less bugs.</p> <p>The <code>Clear()</code> method removes all objects from the stack.</p> <p>We should be able to use this stack class as follows:</p> <pre><code>var stack = new Stack(); stack.Push(1); stack.Push(2); stack.Push(3); Console.WriteLine(stack.Pop()); Console.WriteLine(stack.Pop()); Console.WriteLine(stack.Pop()); </code></pre> <p>The output of this program will be</p> <pre><code>3 2 1 </code></pre> </blockquote> <p>This was the task assigned to me. Following is my code.</p> <pre><code>using System; namespace Exercise { class Program { static void Main() { var stack = new Stack(); stack.Push(1); stack.Push(2); stack.Push(3); Console.WriteLine(stack.Pop()); Console.WriteLine(stack.Pop()); Console.WriteLine(stack.Pop()); } } } </code></pre> <pre><code>using System; using System.Collections; using System.Collections.Generic; using System.Linq; namespace Exercise { internal class Stack : IEnumerable { private object _object; private List&lt;object&gt; list = new List&lt;object&gt;(); public IEnumerator GetEnumerator() { while (list.Any()) yield return Pop(); } internal object Pop() { if (list.Count == 0) throw new InvalidOperationException("Cannot use .Pop() if list count equals 0."); _object = list.FirstOrDefault(); list.RemoveAt(0); return _object; } internal void Push(object obj) { _object = obj; if (_object == null) throw new InvalidOperationException("Cannot use .Push() if object is null."); list.Insert(0, _object); } internal void Clear() { if (list.Count == 0) throw new InvalidOperationException("Cannot use .Clear() if list is empty."); list.Clear(); } public void Print() { if (list.Count == 0) throw new InvalidOperationException("Stack is empty."); foreach (var s in list) { Console.WriteLine(s); } } } } </code></pre> <p>I'm a beginner in C#. Is there anything left to improve on with this that is within the boundaries of what the instructions expect? Any advice or suggestions if anything to teach me something new would be great. Thank you for all the help so far on this site.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-01T13:47:52.830", "Id": "470311", "Score": "1", "body": "For others, these C# Intermediate Exercises came from Udemy and can be found mirrored at https://github.com/chrisvasqm/csharp-intermediate" } ]
[ { "body": "<p>Questions:</p>\n\n<ol>\n<li>Why do you use the class field <code>_object</code>? Does it serve any real purpose that a method-local variable cannot?</li>\n<li>Why do you implement <code>IEnumerable</code>?</li>\n<li>(only consider this if you have a decent understanding of concurrency issues, and want to practice) How can you make this code thread-safe?</li>\n</ol>\n\n<p>Suggestions:</p>\n\n<ol>\n<li>Several method throw exceptions in unexceptionable scenarios. Why do you blow up if I want to print or clear an empty stack? That's like having the waiter shoot herself if I try to order food right as the kitchen has closed.</li>\n<li>When you're done with the exercise, consider making your stack generic. Casting from <code>object</code> is <em>so</em> old-school C#.</li>\n<li>Consider improving your error messages. For one, <code>\"Cannot use .Pop() if list count equals 0.\"</code> could be something like: \"Cannot pop an element off an empty stack\".</li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-31T23:56:16.697", "Id": "470253", "Score": "0", "body": "1. ```_object = list.FirstOrDefault();``` and all other calls. If you know of a way to replace this then by all means explain please? No, I cannot remove the throw exceptions because the lesson requested it. I am questioning whether you read this completely before responding.\n2. I did so for the obvious reason, to get ```Print()``` to work. If you have a suggestion to how to make it thread safe then enlighten me. I was hoping someone would point stuff out so I could learn something new." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-01T00:11:13.520", "Id": "470255", "Score": "1", "body": "@Milliorn it seems you didn't understand the observation hidden inside question 1. The vast majority of questions in this answer seem to be rhethorical" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-01T01:46:24.437", "Id": "470262", "Score": "0", "body": "@Vogel612 if that is your opinion then by all means do explain it please." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-01T06:23:28.250", "Id": "470272", "Score": "0", "body": "@Milliorn the lesson requests throwing exception when pushing null and when popping empty stack. There is no indication that Print method should throw for empty stack nor there Is indication that Print method should exist. Also no indication that Clear should throw. Nor there Is indication that stack should be enumerable, nor there Is indication that it should be cleared when enumerated." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-01T16:08:08.150", "Id": "470336", "Score": "0", "body": "https://github.com/chrisvasqm/csharp-intermediate\n@slepic" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-01T16:10:17.293", "Id": "470337", "Score": "0", "body": "Yes I added Print, and yes the lesson said to cover all edge cases. If people are going to be argumentative then why bother posting other than to aggravate someone looking for help." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-01T18:40:54.597", "Id": "470355", "Score": "0", "body": "@Milliorn You're taking it personaly. I have in no way tried to aggrevate you. If the choice of words sounds rude or in any way offensive, put that on the bill of a language barrier (I am not a native english speaker). Please re-read my previous comment carefully and treat it as constructive criticism. If something is not clear, ask for clarification of a specific part of my comment (or whatever)..." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-31T22:10:32.413", "Id": "239712", "ParentId": "239706", "Score": "4" } }, { "body": "<p>You have posted several such exercises before, and I have commented on them as well. First let's state the good: you are performing such exercises to improve your C# and .NET skills. But I have noticed a pattern that if someone questions you on why you do some things a certain, you quickly take refuge under the blanket of that's what the exercise states. But you also do things such as <code>Print()</code> all on your own. To me, this seems to be conflicting goals among (1) you want to learn and improve, (2) you want to follow the strict letter of the exercise when it suits you, and (3) when it suits you, you want to diverge from the exercise. This conflict may contribute to frustration others have when attempting to help you.</p>\n\n<p>What caught my eye about your implementation was 2 notable things: (1) you rely heavily upon LINQ, and (2) you perform more expensive <code>Insert(0, item)</code> than to <code>Add(item)</code> to the end of list. </p>\n\n<p>I take issue with <code>Pop()</code> because of <code>FirstOrDefault</code>. Not because it's LINQ, although you do not need to use any LINQ at all in your solution. Rather it's what it means. First off, you check for emptiness that is Count == 0. It would be better, i.e. more direct than for you to take list[0] because that's what the stack expects. FirstorDefault just happens to return the first item for you, but what it really means is iterate over this list and find the first item that matches the predicate (and a null predicate means any item). While it just happens to be that list[0] and FirstOrDefault works for you, they really mean 2 different things to someone reading your code.</p>\n\n<p>Besides those observations, I would add the following remarks:</p>\n\n<ul>\n<li>The <code>internal</code> methods really should be <code>public</code>.</li>\n<li><code>_object</code> does not need to be a class field or property. It should be local to a method.</li>\n<li><p>I see no crime in clearing an empty list. It may be pointless but it's less expensive than throwing an exception for it. The edge case to consider would be if <code>list</code> was null, but it won't be.</p></li>\n<li><p>I would prefer to override <code>ToString()</code> instead of <code>Print()</code>.</p></li>\n<li><p>Console writes take a small bit of overhead, so it would be best to avoid repeated calls for every item in the list. You can compose the string once with a fast <code>StringBuilder</code> and then write or return the string once. Whether you write that string to the console or a log file is up to a developer using your stack.</p></li>\n</ul>\n\n<p><strong>EDIT</strong></p>\n\n<p>In light of @HenrikHansen 's answer about GetEnumerator, I have changed my answer to provide a custom enumerator. I see some discussion between Henrik and @sleptic, so let me add some context.</p>\n\n<p>Microsoft has this to say about <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.collections.stack.getenumerator?view=netframework-4.8\" rel=\"nofollow noreferrer\">Stack.GetEnumerator</a> :</p>\n\n<pre><code>Enumerators can be used to read the data in the collection, but they cannot be used to modify the underlying collection.\n</code></pre>\n\n<p>Also, out of furthering my own skills and providing a better answer, I borrowed some code from Microsoft's <a href=\"https://referencesource.microsoft.com/#System/compmod/system/collections/generic/stack.cs,8865095e0bceeafd\" rel=\"nofollow noreferrer\">Stack implementation</a>, which uses an array BTW.</p>\n\n<p>With that said, I offer the following modifications with updated code which now includes a better GetEnumerator:</p>\n\n<pre><code>public class StackV1 : IEnumerable\n{\n private List&lt;object&gt; list = new List&lt;object&gt;();\n private int _version = 0; // used to keep in-sync with enumerator\n\n public Enumerator GetEnumerator()\n {\n return new Enumerator(this);\n }\n\n IEnumerator IEnumerable.GetEnumerator()\n {\n return new Enumerator(this);\n }\n\n public object Pop()\n {\n if (list.Count == 0)\n {\n throw new InvalidOperationException(\"Empty stack. There is nothing to Pop().\");\n }\n\n // Pop by removing from end of list.\n var index = list.Count - 1;\n var item = list[index];\n list.RemoveAt(index);\n\n _version++;\n\n return item;\n }\n\n public void Push(object item)\n {\n if (item == null)\n {\n throw new InvalidOperationException($\"{nameof(item)} is null. There is nothing to Push().\");\n }\n\n _version++;\n\n // Push by adding to end of list.\n list.Add(item);\n }\n\n public void Clear()\n {\n // list will never be null, and it should not be a crime to clear an empty list.\n if (list.Count &gt; 0)\n {\n list.Clear();\n _version++;\n }\n }\n\n public int Size =&gt; list.Count;\n\n // The original exercise did not require a Print() or ToString() method.\n public override string ToString()\n {\n if (list.Count == 0)\n {\n return \"{ empty stack }\"; // or perhaps \"{ }\"\n }\n\n // Each Console.WriteLine has a tiny cost. Let's try not even call it, but rather comnpose a string.\n // This honors the OP's order and display.\n var sb = new StringBuilder();\n for (var i = list.Count - 1; i &gt;= 0; i--)\n {\n sb.AppendLine(list[i].ToString());\n }\n\n return sb.ToString();\n }\n\n // See https://referencesource.microsoft.com/#System/compmod/system/collections/generic/stack.cs,8865095e0bceeafd\n public struct Enumerator : IEnumerator\n {\n private StackV1 _stack;\n private int _version;\n private int _index;\n private object currentElement;\n\n internal Enumerator(StackV1 stack)\n {\n _stack = stack;\n _version = stack._version;\n _index = -2;\n currentElement = default(object);\n }\n\n public void Dispose()\n {\n _index = -1;\n }\n\n public bool MoveNext()\n {\n bool retval;\n if (_version != _stack._version)\n {\n throw new Exception(\"Out-of-sync Enumerator due to a modified Stack.\");\n }\n if (_index == -2)\n { // First call to enumerator.\n _index = _stack.Size - 1;\n retval = (_index &gt;= 0);\n if (retval)\n {\n currentElement = _stack.list[_index];\n }\n return retval;\n }\n if (_index == -1)\n { // End of enumeration.\n return false;\n }\n\n retval = (--_index &gt;= 0);\n currentElement = retval ? _stack.list[_index] : default(object);\n return retval;\n }\n\n public object Current\n {\n get\n {\n if (_index == -2)\n {\n throw new Exception(\"Pointer is before top of the stack.\");\n }\n if (_index == -1)\n {\n throw new Exception(\"Pointer is past the bottom of the stack.\");\n }\n return currentElement;\n }\n }\n\n public void Reset()\n {\n if (_version != _stack._version)\n {\n throw new Exception(\"Out-of-sync Enumerator due to the Stack being modified externally.\");\n }\n _index = -2;\n currentElement = default(object);\n }\n }\n}\n</code></pre>\n\n<p>Your original Print and my ToString list each item on a new line. My personal preference would be to list as a collection like \"{ 3, 2, 1 }\"</p>\n\n<pre><code>// However my personal option would be to list as \"{ 3, 2, 1 }\"\nsb.Append(\"{ \");\nvar first = true;\nfor (var i = list.Count - 1; i &gt;= 0; i--)\n{\n var delimiter = first ? \"\" : \", \";\n sb.Append($\"{delimiter}{list[i]}\");\n if (first)\n {\n first = false;\n }\n}\nsb.Append(\" }\");\n</code></pre>\n\n<p>When I first looked at this exercise, I wondered why it was for Intermediates. It seemed too easy. After updating with a customer Enumerator, I can know see why its Intermediate.</p>\n\n<p>The real fun would be to add generics for type-specific lists. However, I see the exercise says that will be covered in an advanced exercise. It's really not that much of a stretch and would be beneficial to the skills you wish to acquire.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-02T21:05:26.380", "Id": "470446", "Score": "0", "body": "Your observations are true. I am trying to figure it out whichever way I can. I added ```Print()``` because I wanted a way to see if not only what I was doing was correct, but to learn why I couldn't print ```Stack` with a ```foreach``` loop. My intent is not to be confusing, although I can see how I can confuse others an myself. If I rely on LINQ its simply because its what I am familiar with and not what might be what's best tool in my tool box. The expensive functions I use are just familiar/easy for me to find and implement. I ask for advice so I can learn what is optimal." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-02T21:07:24.267", "Id": "470447", "Score": "0", "body": "I have refactored this code. This is the current state of it. [link](https://github.com/milliorn/Udemy/blob/master/C%23/C%23%20Intermediate%20Classes%2C%20Interfaces%20and%20OOP/4%20-%20Inheritance/5%20-%20Design%20a%20Stack/Stack.cs)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-02T21:11:12.110", "Id": "470448", "Score": "0", "body": "As for ```GetEnumerator``` that implementation I used to get ```Print``` to work was me looking through Stack Overflow post to see how to get this done. I was trying to literally get something to print. I had no idea if this was a good idea. At that point I was trying to get anything to work with something I don't quite understand yet. Thank you for posting your suggestions. I am reading them now an trying to figure out what to merge." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-02T21:15:38.320", "Id": "470450", "Score": "0", "body": "```The internal methods really should be public.``` Why is that? I recall in the past people recommending what I thought was similar methods to be made ```internal```. Guess I am now unsure why in this case they should be public? ```_object does not need to be a class field or property. It should be local to a method.``` That was done in my refactor. Not sure why I did that to begin with. ```I see no crime in clearing an empty list.``` Is there a better way to do this like init/declare an empty list locally and returning it?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-02T21:45:23.157", "Id": "470453", "Score": "0", "body": "You mention about ```list.Count == 0``` so would ```if (!list.Any())``` be a better change? If you check the link I posted above you can see the changes I made. I want to add how you done Enumerator, but I feel like I need to omit it for now until I clearly understand everything that is going on there with your suggestion. I feel like if I can't clearly explain it all then I shouldn't add it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-02T22:01:30.503", "Id": "470455", "Score": "1", "body": "You should not be using LINQ for this. Go for direct code. Do you want to check to see if your stack is empty? The most direct way to do this is check `list.Count == 0`. Compare that to `list.Any()` which means enumerate over this collection to see if it has any elements. The `Pop()` already ensures that no null elements are pushed on the stack, so really checking the `Count` is the most direct way to determine if the stack is empty or not." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-02T22:03:26.953", "Id": "470456", "Score": "1", "body": "@Milliorn Consider if you liked your custom stack so much that you wanted to publish it in a DLL for use within your organization. You would want other consumers of the DLL to see certain things from their own projects, and that's why you would favor `public` over `internal` for this particular application." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-02T22:04:13.410", "Id": "470457", "Score": "0", "body": "I definitely got mixed up on that and all that I read. Yes I want to use the most direct means to do that. I'll change that back to ```list.Count == 0```" } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-01T21:52:51.523", "Id": "239768", "ParentId": "239706", "Score": "3" } }, { "body": "<p>One thing the other answers don't address is your implementation of <code>IEnumerable</code>:</p>\n\n<blockquote>\n<pre><code> public IEnumerator GetEnumerator()\n {\n while (list.Any())\n yield return Pop();\n }\n</code></pre>\n</blockquote>\n\n<p>An iterator is supposed to iterate over all elements in the collection, but it should never ever change the state of the collection. Your implementation actual pops all the items in the stack, so it is empty afterwards.</p>\n\n<p>Using it like:</p>\n\n<pre><code>var stack = new Stack();\n\nstack.Push(1);\nstack.Push(2);\nstack.Push(3);\n\nforeach (var item in stack)\n{\n Console.PrintLine(item);\n}\n</code></pre>\n\n<p>will result in an empty stack, and I don't think that should be the case.</p>\n\n<p>If the top of the stack is the head of the list, you can just return the enumerator from the list:</p>\n\n<pre><code>public IEnumerator GetEnumerator()\n{\n return list.GetEnumerator();\n}\n</code></pre>\n\n<hr>\n\n<p>You could make the private field <code>list</code> <code>readonly</code> to secure, that it is never set to <code>null</code> or anything else:</p>\n\n<pre><code>private readonly List&lt;object&gt; list = new List&lt;object&gt;();\n</code></pre>\n\n<hr>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-02T07:14:28.460", "Id": "470376", "Score": "0", "body": "I would object that Iterator must not change state of the container. I would say it Is uncommon, maybe unintuitive, but not forbidden. If you write it in the doc and maybe give it an expressive name, ie an explicit class DestructiveStackEnumerator... It should be fine for devs who read docs. Also iterating a stack is not necesary to go from top to bottom. Again it may be more intuitive, but not mandatory." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-02T07:26:32.150", "Id": "470377", "Score": "0", "body": "@slepic: I can only wish you all the best of luck :-)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-02T10:37:25.723", "Id": "470399", "Score": "0", "body": "Im not arguing that it is always good idea. I merely say that your claims are too strong. There sure are usecases where you want to iterate stack bottom to top, and/or in a destructive way. Though they may be much fewer, never say never. There is at least one widely used programming language in which a core stack implementation allows all of this by configuring the stack on instance level." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-02T10:41:33.000", "Id": "470400", "Score": "0", "body": "To be honest i can't remember when i needed to iterate a stack And direction was important. Most often i dont care what Is the direction as long as all items are iterated. Ie sum all numbers on the stack." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-02T17:14:08.110", "Id": "470421", "Score": "0", "body": "I agree with Henrik that addressing IEnumerable.GetEnumerator was lacking in other answers and that it should be discussed. But I side with @slepic that enumerating should be non-destructive. Microsoft also feels it should be non-destructive. I have updated my answer with the Microsoft links as well as an improved GetEnumerator that uses a custom Enumerator." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-02T18:25:57.380", "Id": "470430", "Score": "0", "body": "@RickDavin yeah you have misinterpreted what both of us said :) Let me just stress out that I am not advocating for destructive iteration. I merely object that \"never ever\" Is too strong here, but i am absolutely fine with \"should\"." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-02T18:45:37.830", "Id": "470438", "Score": "0", "body": "Sorry. Got you guys switched. Was rushing to update an answer during lunch before getting back to my real job." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-02T21:53:48.767", "Id": "470454", "Score": "1", "body": "@HenrikHansen ```One thing the other answers don't address is your implementation of IEnumerable:``` My implementation is based solely on me searching the web and trying to find something to work. ```but it should never ever change the state of the collection``` I had no idea that was the case and yes that is not desirable here. ``` public IEnumerator GetEnumerator() => list.GetEnumerator();``` Add that to my refactor. I really need to learn more about IEnumerable. Also changed list to be readonly. Good catch on that one. Thank you for and everyone else here for your help!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-07T11:44:10.323", "Id": "470927", "Score": "0", "body": "I would say that the nature of a `Stack` is to push and pop. The argument could be made that adding enumeration to it changes it to a different data structure. If it were a requirement to enumerate a stack, one could provide a `ToList()` method, which would change it into an enumerable data structure." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-07T12:55:56.480", "Id": "470944", "Score": "0", "body": "@Aron: I can only agree with you, but the generic stack from .net actually implements `IEnumerable<T>`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-07T13:54:02.107", "Id": "470947", "Score": "1", "body": "@Henrik, thanks for the heads up on that. Apparently Microsoft takes a different philosophy on the capabilities of a stack. Fortunately, they also provide `ToList()`, so I can remain \"pure.\" ;-)" } ], "meta_data": { "CommentCount": "11", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-02T04:41:40.210", "Id": "239780", "ParentId": "239706", "Score": "2" } }, { "body": "<p>In reviewing the questions and answers it struck me that one way to simplify things would be to use linked list as the backing data structure instead of a <code>List</code> (which is based on an array). A <code>LinkedList</code>, allows adding and removing from the \"head\" in O(1) without concern for an index. Sample code is below.</p>\n\n<p>Additional points: </p>\n\n<ol>\n<li>I agree with the others that a generic <code>Stack&lt;T&gt;</code> would be\npreferable. </li>\n<li>I also agree that <code>_object</code> would be better as a local variable.</li>\n<li>Rather than writing <code>list.Count == 0</code> multiple times, I\ncreated the <code>HasItems</code> property. </li>\n<li>Adding the <code>Top</code> property allows the user to \"peek\" at the stack without popping.</li>\n<li>At first I implemented <code>IEnumerable</code> but upon further consideration I realized that I would say that the nature of a <code>Stack</code> is to push and pop. The argument could be made that adding enumeration to it changes it to a different data structure. This prompted me to remove <code>IEnumerable</code> and add <code>ToList()</code>. Now a user can convert it to an <code>IEnumerable</code>, and work with that however they please. I also added a comment about this to the earlier answer. </li>\n</ol>\n\n<p>Here is the sample code:</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\npublic class App_Stack\n{\n public void Run()\n {\n var stack = new Stack();\n Enumerable.Range(1, 10).ToList().ForEach(i =&gt; stack.Push(i));\n\n while (stack.HasItems)\n {\n Console.WriteLine(((int)stack.Pop()).ToString());\n }\n }\n}\n\npublic class Stack \n{\n private LinkedList&lt;object&gt; list = new LinkedList&lt;object&gt;();\n\n public object Top =&gt; list.FirstOrDefault();\n public int Count =&gt; list.Count; \n public bool HasItems =&gt; Count &gt; 0;\n\n public void Push(object item) =&gt; list.AddFirst(item);\n\n ///if stack is empty returns null\n public object Pop()\n { \n var item = Top;\n if (HasItems)\n { \n list.RemoveFirst(); \n }\n else\n {\n Console.WriteLine(\"Stack is empty\");\n }\n\n return item;\n }\n\n public void Clear() =&gt; list.Clear();\n\n public List&lt;object&gt; ToList() =&gt; list.ToList();\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-07T18:05:40.330", "Id": "470971", "Score": "0", "body": "Thanks for your suggestions. I added your suggestion ```HasItems```. Also added the ```Top``` property but why not ```public object Top => list[0];```? [link to latest code](https://github.com/milliorn/Udemy/blob/master/C%23/C%23%20Intermediate%20Classes%2C%20Interfaces%20and%20OOP/4%20-%20Inheritance/5%20-%20Design%20a%20Stack/Stack.cs)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-07T21:26:05.810", "Id": "471003", "Score": "0", "body": "Hi, you're welcome. The risk with `Top => list[0]` is that when the list is empty it will throw an exception." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-07T21:55:30.767", "Id": "471007", "Score": "0", "body": "So either I use that and handle an exception, or pass a null? Trying to make sure I am reading this right? (https://docs.microsoft.com/en-us/dotnet/api/system.linq.enumerable.firstordefault?view=netframework-4.8)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-07T23:46:43.857", "Id": "471013", "Score": "1", "body": "Yes, `FirstOrDefault()` will return `list[0]` or `null`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-08T14:46:19.103", "Id": "471055", "Score": "1", "body": "Also for the record, to get the last item in a list you could use `list.Last()` (or `list.LastOrDefault()`." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-07T11:35:26.923", "Id": "240095", "ParentId": "239706", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-31T19:03:37.973", "Id": "239706", "Score": "1", "Tags": [ "c#", "beginner", "stack", "iterator", "inheritance" ], "Title": "Exercise: Design a Stack" }
239706
<p>I am working with a project of using modern C++ on the Game Boy Advance (<a href="https://github.com/JoaoBaptMG/gba-modern" rel="nofollow noreferrer">repository is here, code under the MIT license</a>). Being a fairly limited platform (288 KB of RAM maximum, no memory controller), I try to avoid as best as I can the use of dynamic memory allocation (<code>malloc</code> and friends). Since now I could get away with "simple" classes and such, but now I felt I would need to store lambdas and pass them around. For that, I created the following container, that stores the function object inside it. I would like some serious criticism on it, please.</p> <pre><code>//-------------------------------------------------------------------------------- // StaticFunction.hpp //-------------------------------------------------------------------------------- // Provides space to store statically a function object with a defined number // of bytes, saving on allocations //-------------------------------------------------------------------------------- #pragma once #include &lt;cstddef&gt; #include &lt;new&gt; #include &lt;type_traits&gt; #include &lt;functional&gt; template &lt;std::size_t Size, typename Sig&gt; class StaticFunction; // A function holder of Size bytes and signature R(Args...) // based on the following answer: https://stackoverflow.com/a/38478032/ template &lt;std::size_t Size, typename R, typename... Args&gt; class StaticFunction&lt;Size, R(Args...)&gt; { // Define the important function pointers here typedef R(*Invoker)(std::byte*, Args...); typedef void(*Replacer)(std::byte*, const std::byte*); template &lt;typename Functor&gt; static R genericInvoker(std::byte* f, Args... args) { static_assert(std::is_invocable_r_v&lt;R, Functor, Args...&gt;, "Functor must be callable with the appropriate signature!"); return std::invoke(*std::launder(reinterpret_cast&lt;Functor*&gt;(f)), std::forward&lt;Args&gt;(args)...); } template &lt;typename Functor&gt; static void genericReplacer(std::byte* newObj, const std::byte* oldObj) { if (oldObj) new (newObj) Functor(*std::launder(reinterpret_cast&lt;const Functor*&gt;(oldObj))); else std::launder(reinterpret_cast&lt;Functor*&gt;(newObj))-&gt;~Functor(); } static R fptrInvoker(std::byte* f, Args... args) { auto fptr = reinterpret_cast&lt;R(**)(Args...)&gt;(f); return (*fptr)(args...); } static void fptrReplacer(std::byte* newObj, const std::byte* oldObj) { *reinterpret_cast&lt;R(**)(Args...)&gt;(newObj) = *reinterpret_cast&lt;R(* const*)(Args...)&gt;(oldObj); } // Now define the pointers Invoker invoker; Replacer replacer; // And finally the storage std::byte storage[Size]; public: // A trivial default constructor StaticFunction() = default; // A constructor for function pointers StaticFunction(R (*f)(Args...)) : invoker(fptrInvoker), replacer(fptrReplacer) { // Copy the function pointer replacer(storage, reinterpret_cast&lt;const std::byte*&gt;(&amp;f)); } // A templated constructor for any callable object template &lt;typename Functor&gt; StaticFunction(const Functor&amp; f) : invoker(genericInvoker&lt;Functor&gt;), replacer(genericReplacer&lt;Functor&gt;) { static_assert(std::is_invocable_r_v&lt;R, Functor, Args...&gt;, "Functor must be callable with the appropriate signature!"); static_assert(sizeof(Functor) &lt;= Size, "The required function object is too big to be stored!"); // Copy the functor replacer(storage, reinterpret_cast&lt;const std::byte*&gt;(&amp;f)); } // Copy constructor StaticFunction(const StaticFunction&amp; other) : invoker(other.invoker), replacer(other.replacer) { // Replace this one storage with the other if (replacer) replacer(storage, other.storage); } // Copy assignment operator StaticFunction&amp; operator=(const StaticFunction&amp; other) { // Destroy the object here first if (replacer) replacer(storage, nullptr); invoker = other.invoker; replacer = other.replacer; replacer(storage, other.storage); return *this; } // Call operator R operator()(Args... args) { // Calling an empty StaticFunction would trigger UB return invoker(storage, std::forward&lt;Args&gt;(args)...); } // Destructor ~StaticFunction() { replacer(storage, nullptr); } }; </code></pre> <p>The idea is that you have a <code>StaticFunction&lt;N, Sig&gt;</code> which behaves as a <code>std::function&lt;Sig&gt;</code>, but instead storing the object in an internal pool of <code>N</code> bytes. Some of the uses of it would be like this:</p> <pre><code>#include &lt;cstdio&gt; int f(int v) { return v &lt;&lt; 3; } int add(int a, int b) { return a+b; } struct C { int v; int example(int x) const { return v-x; } }; int main() { int v; StaticFunction&lt;12, int(int)&gt; container = [&amp;v] (int x) { return v+x; }; printf("%d\n", container(14)); container = f; printf("%d\n", container(11)); StaticFunction&lt;12, int(const C&amp;,int)&gt; container2 = &amp;C::example; C x = { 12 }; printf("%d\b", container2(x, 12)); container = std::bind(add, std::placeholders::_1, 24); printf("%d\n", container(-3)); } </code></pre> <p>Unfortunately, I have not battle tested it thoroughly. I tried to use perfect forwarding (replacing <code>Args...</code> by <code>Args&amp;&amp;...</code>), but suddenly, my assembly is permeated with <code>&amp;&amp;</code>, even where it's not needed (<code>int&amp;&amp;</code>, having my int hidden behind a pointer indirection). A version of the function and the example can be found <a href="https://godbolt.org/z/fXFRSY" rel="nofollow noreferrer">here</a>.</p> <p>What could be some "attack vectors"? Where could I improve this code?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-01T01:38:01.383", "Id": "470261", "Score": "0", "body": "Perfect forwarding is unnecessary here - you already know the types of the arguments. `std::function` also does not use `Args&&`. This is a bit tricky, but you've done both the argument passing part (`Args...`) and invocation part (`std::forward<Args>(args)`) correct." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-01T17:39:57.630", "Id": "470345", "Score": "1", "body": "You can't use `std::function<>`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-01T18:07:37.740", "Id": "470349", "Score": "0", "body": "@MartinYork I wish I could use, but I’m trying to avoid dynamic memory allocation, because of the limited nature of the hardware (purists would tell me not to use C++ at all!). That’s also the reason why I’m not using exceptions and taking other compromises in the code." } ]
[ { "body": "<blockquote>\n<pre><code>typedef R(*Invoker)(std::byte*, Args...);\ntypedef void(*Replacer)(std::byte*, const std::byte*);\n</code></pre>\n</blockquote>\n\n<p>Alias-declarations are easier to understand IMO:</p>\n\n<pre><code>using Invoker = R (*)(std::byte*, Args...);\nusing Replacer = void (*)(std::byte*, const std::byte*);\n</code></pre>\n\n<blockquote>\n<pre><code>template &lt;typename Functor&gt;\nstatic R genericInvoker(std::byte* f, Args... args)\n{\n static_assert(std::is_invocable_r_v&lt;R, Functor, Args...&gt;,\n \"Functor must be callable with the appropriate signature!\");\n return std::invoke(*std::launder(reinterpret_cast&lt;Functor*&gt;(f)),\n std::forward&lt;Args&gt;(args)...);\n}\n</code></pre>\n</blockquote>\n\n<p>The <code>*std::launder(reinterpret_cast&lt;Functor*&gt;(f))</code> part comes up quite a lot. Have you considered a helper function?</p>\n\n<pre><code>// somewhere\ntemplate &lt;typename F&gt;\nF* as(void* storage)\n{\n return *std::launder(std::reinterpret_cast&lt;F*&gt;(storage));\n}\n</code></pre>\n\n<p>then</p>\n\n<pre><code>using Invoker = R (*)(void*, Args...);\n\nInvoker invoker;\n\ntemplate &lt;typename F&gt;\nstatic R invoke(void* storage, Args... args)\n{\n std::invoke(*as&lt;F&gt;(storage), std::forward&lt;Args&gt;(args)...);\n}\n</code></pre>\n\n<blockquote>\n<pre><code>template &lt;typename Functor&gt;\nstatic void genericReplacer(std::byte* newObj, const std::byte* oldObj)\n{\n if (oldObj) new (newObj) Functor(*std::launder(reinterpret_cast&lt;const Functor*&gt;(oldObj)));\n else std::launder(reinterpret_cast&lt;Functor*&gt;(newObj))-&gt;~Functor();\n}\n</code></pre>\n</blockquote>\n\n<p>Don't put everything on one line &mdash; it requires horizontal scrolling and is hard to read. <code>newObj</code> and <code>oldObj</code> are a bit confusing. The logic may also be clearer if you separate the destruction part:</p>\n\n<pre><code>using Replacer = void (*)(void*, void*);\nusing Destroyer = void (*)(void*);\n\nReplacer replacer;\nDestroyer destroyer;\n\ntemplate &lt;typename F&gt;\nstatic void replace(void* storage, void* f)\n{\n ::new (storage) F(*as&lt;F&gt;(f));\n}\n\ntemplate &lt;typename F&gt;\nstatic void destroy(void* storage)\n{\n std::destroy_at(as&lt;F&gt;(storage));\n}\n</code></pre>\n\n<blockquote>\n<pre><code>static R fptrInvoker(std::byte* f, Args... args)\n{\n auto fptr = reinterpret_cast&lt;R(**)(Args...)&gt;(f);\n return (*fptr)(args...);\n}\n\nstatic void fptrReplacer(std::byte* newObj, const std::byte* oldObj)\n{\n *reinterpret_cast&lt;R(**)(Args...)&gt;(newObj) =\n *reinterpret_cast&lt;R(* const*)(Args...)&gt;(oldObj);\n}\n</code></pre>\n</blockquote>\n\n<p>I don't think these are necessary &mdash; the generic version is fine.</p>\n\n<blockquote>\n<pre><code>std::byte storage[Size];\n</code></pre>\n</blockquote>\n\n<p>Using <code>std::byte</code>s to store the function object disregards alignment, which may cause performance degradation or even undefined behavior. Use <code>std::aligned_storage</code> instead:</p>\n\n<pre><code>std::aligned_storage_t&lt;Size&gt; storage;\n</code></pre>\n\n<blockquote>\n<pre><code>// A trivial default constructor\nStaticFunction() = default;\n</code></pre>\n</blockquote>\n\n<p>This is questionable. Throwing an exception when an empty <code>StaticFunction</code> is called may be better:</p>\n\n<pre><code>// special-case nullptr\nInvoker invoker{};\nReplacer replacer{};\nDestroyer destroyer{};\n</code></pre>\n\n<blockquote>\n<pre><code>template &lt;typename Functor&gt;\nStaticFunction(const Functor&amp; f) : invoker(genericInvoker&lt;Functor&gt;), replacer(genericReplacer&lt;Functor&gt;)\n{\n static_assert(std::is_invocable_r_v&lt;R, Functor, Args...&gt;,\n \"Functor must be callable with the appropriate signature!\");\n static_assert(sizeof(Functor) &lt;= Size,\n \"The required function object is too big to be stored!\");\n\n // Copy the functor\n replacer(storage, reinterpret_cast&lt;const std::byte*&gt;(&amp;f));\n}\n</code></pre>\n</blockquote>\n\n<p>Instead of making <code>static_assert</code>s, why not SFINAE? Taking the function object by value allows move semantics:</p>\n\n<pre><code>template &lt;typename F,\n typename = std::enable_if_t&lt;std::is_invocable_r_v&lt;R, F, Args...&gt; &amp;&amp;\n sizeof(F) &lt;= Size&gt;&gt;\nStaticFunction(F f)\n : invoker{invoke&lt;F&gt;}\n , replacer{replace&lt;F&gt;}\n , destroyer{destroy&lt;F&gt;}\n{\n ::new (&amp;storage) F(std::move(f));\n}\n</code></pre>\n\n<blockquote>\n<pre><code>// Copy constructor\nStaticFunction(const StaticFunction&amp; other) : invoker(other.invoker), replacer(other.replacer)\n{\n // Replace this one storage with the other\n if (replacer) replacer(storage, other.storage);\n}\n\n// Copy assignment operator\nStaticFunction&amp; operator=(const StaticFunction&amp; other)\n{\n // Destroy the object here first\n if (replacer) replacer(storage, nullptr);\n invoker = other.invoker;\n replacer = other.replacer;\n replacer(storage, other.storage);\n return *this;\n}\n</code></pre>\n</blockquote>\n\n<p>Consider supporting move semantics (maybe <code>move_replacer</code>).</p>\n\n<blockquote>\n<pre><code>R operator()(Args... args)\n{\n // Calling an empty StaticFunction would trigger UB\n return invoker(storage, std::forward&lt;Args&gt;(args)...);\n}\n</code></pre>\n</blockquote>\n\n<p>Maybe this:</p>\n\n<pre><code>R operator()(Args... args) const\n{\n if (invoker) {\n return invoker(&amp;storage, std::forward&lt;Args&gt;(args)...);\n } else {\n throw std::bad_function_call{};\n }\n}\n</code></pre>\n\n<blockquote>\n<pre><code>~StaticFunction()\n{\n replacer(storage, nullptr);\n}\n</code></pre>\n</blockquote>\n\n<p>Yeah, with <code>destroyer</code> it becomes</p>\n\n<pre><code>~StaticFunction()\n{\n destroyer(&amp;storage);\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-01T16:13:39.760", "Id": "470338", "Score": "1", "body": "There are some design decisions that have been made thinking on the limitations of the platform. The `fptr` versions were provided because (for some reason) `std::launder` is deleted for function pointers. The decision of combining a replacer and a destroyer into a single function was to save a function pointer in space (288 KB RAM only). About exceptions, I'm running the entire project with exceptions disabled and, in that case, an empty slot will trigger an assertion (and lock up the program). Move semantics are something to consider, but that would mean yet another function pointer." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-01T16:14:41.373", "Id": "470339", "Score": "0", "body": "But so far thank you for the time you took for commenting and suggesting improvements. I'll keep looking for improvements! :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-02T00:55:11.653", "Id": "470367", "Score": "0", "body": "@JoaoBapt Yeah, I understand the compromises you have to make. Saving space is indeed a legit point to reduce the number of function pointers. Anyway, we are `std::launder`ing pointers to function pointers (we store function pointers in the `storage`), so it being deleted for function pointers shouldn't be a problem." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-02T01:01:22.260", "Id": "470368", "Score": "0", "body": "Actually, testing with [Godbolt](https://godbolt.org/z/fXFRSY), I figured out that using a lambda with this class would be faster (less pointer indirections) than a function pointer, because the lambda's body is inlined inside the `genericInvoker`, but with a function pointer it would have to go through the `fptrInvoker` then to the pointer stored in the `storage`. I wonder if there is a way to \"rearrange\" the code so function pointers could be theoretically stored in the `invoker` so we don't have to do this second hop." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-02T02:15:20.633", "Id": "470370", "Score": "0", "body": "@JoaoBapt Well, lambdas are generally better than function pointers because they can be inlined and don't require indirection. I don't really think what you are describing is possible - functions aren't objects, so they have to be decayed to function pointers before they can be stored, introducing indirection. That's the same reason why standard algorithms are faster with function objects than with function pointers." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-02T02:22:48.367", "Id": "470371", "Score": "0", "body": "After reading the [AAPCS](https://static.docs.arm.com/ihi0042/i/aapcs32.pdf), I discovered an interesting property: I can call a `R(*)(Args...)` as if it was a `R(*)(Args..., T)` because the additional argument (that would be passed on the stack or in an additional register) won't be used and the caller is the one that cleans up the stack. So I might swap the arguments around and store the function pointer in the `invoker`, thus saving a pointer indirection and making function pointer calls as efficient as lambda calls. That is _definitely_ UB, but it seems to work in the ARM." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-01T13:40:10.203", "Id": "239745", "ParentId": "239710", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-31T21:22:37.407", "Id": "239710", "Score": "3", "Tags": [ "c++" ], "Title": "std::function-like object with static allocation (no alloc)" }
239710
<p>I have written a few C++ functions that should:</p> <ul> <li>take in a string</li> <li>transform it based on index</li> <li>transform it based on number of alphabetic characters seen</li> <li>return the transformed string</li> </ul> <p>Example first, detail after:</p> <pre><code>$ rotn_a("Hello, World!") &gt; Igopt, Exbwp! $ rotn_a("aaaaaaaaaaaaaaaaaaaaaaaaaaa") &gt; bcdefghijklmnopqrstuvwxyzab $rotn_a("aa!aaaaaaaaaaaaaaaaaaaaaaaa") &gt; bc!efghijklmnopqrstuvwxyzab ^ $rotn_b("Hello, World!") &gt; Igopt, Cvzun! $rotn_b("aaaaaaaaaaaaaaaaaaaaaaaaaaa") &gt; bcdefghijklmnopqrstuvwxyzab $rotn_b("aa!aaaaaaaaaaaaaaaaaaaaaaaa") &gt; bc!defghijklmnopqrstuvwxyza ^ $unrotn_a(rotn_a("Hello, World!")) &gt; Hello, World! $unrotn_a(rotn_a("aaaaaaaaaaaaaaaaaaaaaaaaaaa")) &gt; aaaaaaaaaaaaaaaaaaaaaaaaaaa $unrotn_a(rotn_a("aa!aaaaaaaaaaaaaaaaaaaaaaaa")) &gt; aa!aaaaaaaaaaaaaaaaaaaaaaaa $unrotn_b(rotn_b("Hello, World!")) &gt; Hello, World! $unrotn_b(rotn_b("aaaaaaaaaaaaaaaaaaaaaaaaaaa")) &gt; aaaaaaaaaaaaaaaaaaaaaaaaaaa $unrotn_b(rotn_b("aa!aaaaaaaaaaaaaaaaaaaaaaaa")) &gt; aa!aaaaaaaaaaaaaaaaaaaaaaaa </code></pre> <p><code>rotn_a</code>: take in string and rotate each each character <code>index</code> times <code>rotn_a</code> example:</p> <pre><code>in: aaaaa middle step ----------- bbbbb bcccc bcddd bcdee bcdef out: bcdef </code></pre> <p><code>unrotn_a</code>: undo <code>rotn_a</code></p> <p><code>unrotn_a</code> example:</p> <pre><code>in: bcdef middle step ----------- abcde aabcd aaabc aaaab out: aaaaa </code></pre> <p><code>rotn_b</code>: take in string and rotate each each character <code>index-alpha_encountered</code> times and <code>alpha_encountered</code> is number of <code>a-z</code> seen in string so far <code>rotn_b</code> example:</p> <pre><code>in: aa'aa middle step ----------- bb'bb bc'cc bc'cc bc'dd out: bc'de </code></pre> <p><code>unrotn_b</code>: undo <code>rotn_b</code></p> <pre><code>#include &lt;iostream&gt; #include &lt;algorithm&gt; std::string rotn_a(std::string text); std::string rotn_b(std::string text); std::string unrotn_a(std::string text); std::string unrotn_b(std::string text); int main() { // Encode example std::cout &lt;&lt; rotn_a("Hello, World!") &lt;&lt; "\n" &lt;&lt; rotn_a("aaaaaaaaaaaaaaaaaaaaaaaaaaa") &lt;&lt; "\n" &lt;&lt; rotn_a("aa!aaaaaaaaaaaaaaaaaaaaaaaa") &lt;&lt; "\n\n"; std::cout &lt;&lt; rotn_b("Hello, World!") &lt;&lt; "\n" &lt;&lt; rotn_b("aaaaaaaaaaaaaaaaaaaaaaaaaaa") &lt;&lt; "\n" &lt;&lt; rotn_b("aa!aaaaaaaaaaaaaaaaaaaaaaaa") &lt;&lt; "\n\n"; // Decode example std::cout &lt;&lt; unrotn_a(rotn_a("Hello, World!")) &lt;&lt; "\n" &lt;&lt; unrotn_a(rotn_a("aaaaaaaaaaaaaaaaaaaaaaaaaaa")) &lt;&lt; "\n" &lt;&lt; unrotn_a(rotn_a("aa!aaaaaaaaaaaaaaaaaaaaaaaa")) &lt;&lt; "\n\n"; std::cout &lt;&lt; unrotn_b(rotn_b("Hello, World!")) &lt;&lt; "\n" &lt;&lt; unrotn_b(rotn_b("aaaaaaaaaaaaaaaaaaaaaaaaaaa")) &lt;&lt; "\n" &lt;&lt; unrotn_b(rotn_b("aa!aaaaaaaaaaaaaaaaaaaaaaaa")) &lt;&lt; "\n\n"; } std::string rotn_a(std::string text) { for (auto i = begin(text); i != end(text); ++i) { // Modified from https://codereview.stackexchange.com/a/14610/177972 std::transform( i, end(text), i, [] (char c) -&gt; char { if (not std::isalpha(c)) { return c; } char const pivot = std::isupper(c) ? 'A' : 'a'; return (c - pivot + 1) % 26 + pivot; } ); } return text; } std::string rotn_b(std::string text) { auto rot = 0; for (auto i = begin(text); i != end(text); ++i) { auto c = *i; if (not std::isalpha(c)) { continue; } rot++; char const pivot = std::isupper(c) ? 'A' : 'a'; *i = (c - pivot + rot) % 26 + pivot; } return text; } std::string unrotn_a(std::string text) { for (auto i = begin(text); i != end(text); ++i) { std::transform( i, end(text), i, [] (char c) -&gt; char { if (not std::isalpha(c)) { return c; } char const pivot = std::isupper(c) ? 'A' : 'a'; return (c - pivot + 25) % 26 + pivot; } ); } return text; } std::string unrotn_b(std::string text) { auto rot = 0; for (auto i = begin(text); i != end(text); ++i) { auto c = *i; if (not std::isalpha(c)) { continue; } rot++; char const pivot = std::isupper(c) ? 'A' : 'a'; *i = (c - pivot + (26-rot)) % 26 + pivot; } return text; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-01T01:14:58.380", "Id": "470259", "Score": "2", "body": "Would the person that voted to close this question please explain why they think the code is incomplete or not working." } ]
[ { "body": "<p>I'm just going to review rotn_a, but these comments apply to all of the functions.</p>\n\n<hr>\n\n<pre><code>std::string rotn_a(std::string text);\n...\nstd::string rotn_a(std::string text) { ...\n</code></pre>\n\n<p>There's nothing wrong with separating the definition and declaration, but I don't think it gets you anything in this example.</p>\n\n<hr>\n\n<pre><code>std::string rotn_a(std::string text) {\n</code></pre>\n\n<p>In this case, you don't actually need a copy. You just need a new string of the same size. It may be worthwhile to make a <code>const&amp;</code> version and a <code>&amp;&amp;</code> version.</p>\n\n<hr>\n\n<pre><code>for (auto i = begin(text); i != end(text); ++i) {\n // Modified from https://codereview.stackexchange.com/a/14610/177972\n std::transform(\n i, end(text), i,\n</code></pre>\n\n<p>Imagine you have a string <code>\"qwertyuiop\"</code> ... here's what your program will do:</p>\n\n<pre><code>q w e r t y u i o p\n&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;v\n v---------------+\n &gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;v\n v-------------+\n &gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;v\n v-----------+\n &gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;v\n v---------+\n &gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;v\n...\n</code></pre>\n\n<p>You go over the entire string many many times. <code>O(n^2)</code> times. It's very easy to make this function go over the string once.</p>\n\n<hr>\n\n<pre><code>std::transform(i, end(text), i, ...\n</code></pre>\n\n<p>Minor nit: It's good to get in the habit of using <code>std::</code> everywhere, but if you choose not to, then you should be consistent. </p>\n\n<hr>\n\n<pre><code>if (not std::isalpha(c))\n</code></pre>\n\n<p>Minor nit 2: I think if you explained this function to a human, you would say \"do blah blah blah to the letters.\" You probably wouldn't say \"first ignore the non-letters. Then with the remaining letters, do blah blah blah.\"</p>\n\n<p>So an (IMO) improved version would be:</p>\n\n<pre><code>if (std::isalpha(c)) {\n ...\n}\n</code></pre>\n\n<hr>\n\n<pre><code> char const pivot = std::isupper(c) ? 'A' : 'a';\n</code></pre>\n\n<p>I think what you wrote is good. If you want to go crazy, you could maybe optimize it to something like <code>char pivot = 01000001 | (C &amp; 00100000)</code>. I don't know for sure that the bitwise version is faster, but I suspect it would be since <code>isupper</code> is a function call that (IIRC) needs to check the current locale which basically means it won't be inlined.</p>\n\n<p>Also I think <code>pivot</code> is not a great name. Maybe \"base letter\" or something like that. Pivot makes me thing you are going to do comparisons and expect to have some things less than pivot and some things greater than pivot.</p>\n\n<p>Since many of your functions do something like this, perhaps you could factor it out and make it a helper function.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-06T03:09:45.617", "Id": "241793", "ParentId": "239711", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-31T21:44:40.693", "Id": "239711", "Score": "1", "Tags": [ "c++", "beginner", "algorithm", "c++17" ], "Title": "ROT(ation) by Index" }
239711
<p>I build database called <code>MessageBoard</code> and created StoredProcedure <code>GetHomeView</code> that return data for HomeView. I am completely new in this area.</p> <p>Stored procedure contains next fields:</p> <p><code>Id</code> - Key fied.</p> <p><code>ForumId</code> - Field that should be in result query because it is need to know, which forum should be loaded if user will open it.</p> <p><code>Category</code> - Name of category. </p> <p><code>Forum</code> - Name of forum.</p> <p><code>TopicsAmount</code> - Total amount of Topics in Forum.</p> <p><code>RepliesCount</code> - Total amount of Posts in Forum. </p> <p><code>LastDate</code> - The date of last Post in Forum.</p> <p><code>LastUserName</code> - The Name of User that left last Post.</p> <p><code>LastTopicName</code> - Last topic where user left last post in forum. </p> <p>Need advice how to improve structure and performance and keep the same output result. Also I am sure that I made common mistakes help me to find them and to fix.</p> <p>I tried only <code>CREATE NONCLUSTERED INDEX [TEST_INDEX] ON dbo.Posts (CreationDateTime) INCLUDE (TopicId,UserName)</code> it gave some improvement but not much.</p> <p><a href="https://i.stack.imgur.com/Ifgu6.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Ifgu6.png" alt="enter image description here"></a></p> <p><strong>Script generating database structure:</strong></p> <pre><code>USE [MessageBoard] GO /****** Object: Table [dbo].[Categories] Script Date: 4/1/2020 01:58:48 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE TABLE [dbo].[Categories]( [Id] [bigint] IDENTITY(1,1) NOT NULL, [Name] [nvarchar](max) NULL, CONSTRAINT [PK_Categories] PRIMARY KEY CLUSTERED ( [Id] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY] GO /****** Object: Table [dbo].[Forums] Script Date: 4/1/2020 01:58:48 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE TABLE [dbo].[Forums]( [Id] [bigint] IDENTITY(1,1) NOT NULL, [Name] [nvarchar](max) NULL, [CategoryId] [bigint] NOT NULL, CONSTRAINT [PK_Forums] PRIMARY KEY CLUSTERED ( [Id] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY] GO /****** Object: Table [dbo].[Posts] Script Date: 4/1/2020 01:58:48 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE TABLE [dbo].[Posts]( [Id] [bigint] IDENTITY(1,1) NOT NULL, [Text] [nvarchar](max) NULL, [CreationDateTime] [datetime2](7) NOT NULL, [TopicId] [bigint] NOT NULL, [UserName] [nvarchar](max) NULL, CONSTRAINT [PK_Posts] PRIMARY KEY CLUSTERED ( [Id] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY] GO /****** Object: Table [dbo].[Topics] Script Date: 4/1/2020 01:58:48 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE TABLE [dbo].[Topics]( [Id] [bigint] IDENTITY(1,1) NOT NULL, [Text] [nvarchar](max) NULL, [CreationDateTime] [datetime2](7) NOT NULL, [Author] [nvarchar](max) NULL, [ForumId] [bigint] NOT NULL, CONSTRAINT [PK_Topics] PRIMARY KEY CLUSTERED ( [Id] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY] GO ALTER TABLE [dbo].[Forums] WITH CHECK ADD CONSTRAINT [FK_Forums_Categories_CategoryId] FOREIGN KEY([CategoryId]) REFERENCES [dbo].[Categories] ([Id]) ON DELETE CASCADE GO ALTER TABLE [dbo].[Forums] CHECK CONSTRAINT [FK_Forums_Categories_CategoryId] GO ALTER TABLE [dbo].[Posts] WITH CHECK ADD CONSTRAINT [FK_Posts_Topics_TopicId] FOREIGN KEY([TopicId]) REFERENCES [dbo].[Topics] ([Id]) ON DELETE CASCADE GO ALTER TABLE [dbo].[Posts] CHECK CONSTRAINT [FK_Posts_Topics_TopicId] GO ALTER TABLE [dbo].[Topics] WITH CHECK ADD CONSTRAINT [FK_Topics_Forums_ForumId] FOREIGN KEY([ForumId]) REFERENCES [dbo].[Forums] ([Id]) ON DELETE CASCADE GO ALTER TABLE [dbo].[Topics] CHECK CONSTRAINT [FK_Topics_Forums_ForumId] GO /****** Object: StoredProcedure [dbo].[GetRepliesCountByCategories_V21] Script Date: 4/1/2020 01:58:48 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO </code></pre> <p><strong>Script generating stored procedure:</strong></p> <pre><code>CREATE PROCEDURE [dbo].[GetHomeView] AS BEGIN -- SET NOCOUNT ON added to prevent extra result sets from -- interfering with SELECT statements. SET NOCOUNT ON; -- Insert statements for procedure here With TopicsWithPosts(ForumId,TopicText,PostUserName,TopicId,PostCreationDateTime) AS ( SELECT dbo.Topics.ForumId, dbo.Topics.Text, dbo.Posts.UserName, dbo.Topics.Id, dbo.Posts.CreationDateTime FROM dbo.Topics INNER JOIN dbo.Posts on dbo.Topics.Id=dbo.Posts.TopicId ), ForumsWithTopics(ForumId,TopicId) AS ( SELECT dbo.Forums.Id, dbo.Topics.Id FROM dbo.Forums INNER JOIN dbo.Topics on dbo.Topics.ForumId = dbo.Forums.Id ), CountTopicsByForum (ForumId, Amount) AS ( SELECT ForumsWithTopics.ForumId as ForumId, COUNT(distinct ForumsWithTopics.TopicId) as Amount FROM ForumsWithTopics GROUP BY ForumsWithTopics.ForumId ), CountPostsByForum (ForumId, Amount) AS ( SELECT ForumsWithTopics.ForumId as ForumId, count(dbo.Posts.Id) as Amount FROM ForumsWithTopics LEFT JOIN dbo.Posts on dbo.Posts.TopicId = ForumsWithTopics.TopicId group by ForumsWithTopics.ForumId ), MaxPostDateInForum(ForumId,LastPostDate) AS ( SELECT TopicsWithPosts.ForumId, MAX(TopicsWithPosts.PostCreationDateTime) as LastPostDate FROM TopicsWithPosts GROUP BY TopicsWithPosts.ForumId ), LastTopicsByDate(ForumId,TopicText,LastPostDate,PostUserName,TopicId,RowNumber) AS ( SELECT TopicsWithPosts.ForumId, TopicsWithPosts.TopicText, MaxPostDateInForum.LastPostDate,TopicsWithPosts.PostUserName,TopicsWithPosts.TopicId ,row_number() over(partition by TopicsWithPosts.ForumId order by MaxPostDateInForum.LastPostDate desc) as RowNumber FROM TopicsWithPosts INNER JOIN MaxPostDateInForum on TopicsWithPosts.ForumId = MaxPostDateInForum.ForumId and MaxPostDateInForum.LastPostDate=TopicsWithPosts.PostCreationDateTime ), LastUserByDateInForum(ForumId, LastTopicName, LastPostDate,LastUserName,TopicId,RowNumber) As ( SELECT LastTopicsByDate.ForumId, LastTopicsByDate.TopicText, LastTopicsByDate.LastPostDate, LastTopicsByDate.PostUserName, LastTopicsByDate.TopicId, LastTopicsByDate.RowNumber FROM LastTopicsByDate where LastTopicsByDate.RowNumber = 1 ) SELECT ROW_NUMBER() over (order by dbo.Categories.Id asc) as Id, dbo.Forums.Id as ForumId, dbo.Categories.Name as Category, dbo.Forums.Name as Forum, CountTopicsByForum.Amount as TopicsAmount, CountPostsByForum.Amount as RepliesCount, LastUserByDateInForum.LastPostDate as LastDate, LastUserByDateInForum.LastUserName, LastUserByDateInForum.LastTopicName FROM Categories LEFT JOIN dbo.Forums on dbo.Forums.CategoryId = dbo.Categories.Id LEFT JOIN CountTopicsByForum on CountTopicsByForum.ForumId = dbo.Forums.Id LEFT JOIN CountPostsByForum on dbo.Forums.Id = CountPostsByForum.ForumId LEFT JOIN LastUserByDateInForum on dbo.Forums.Id = LastUserByDateInForum.ForumId GROUP BY dbo.Categories.Id, dbo.Forums.Id, dbo.Forums.Name, dbo.Categories.Name, CountTopicsByForum.Amount, CountPostsByForum.Amount, LastUserByDateInForum.LastPostDate, LastUserByDateInForum.LastUserName, LastUserByDateInForum.LastTopicName ORDER BY LastUserByDateInForum.LastPostDate DESC END -- GO </code></pre> <p><strong>Script that fill database with data:</strong></p> <pre><code>DELETE FROM Posts; DELETE FROM Topics; DELETE FROM Forums; DELETE FROM Categories; SET IDENTITY_INSERT Categories ON; declare @CategoryNumber int = 1; while @CategoryNumber &lt;= 10 begin insert into Categories(Id,Name) values(@CategoryNumber,'Category ' + CONVERT(varchar(MAX), @CategoryNumber)) set @CategoryNumber = @CategoryNumber + 1 end SET IDENTITY_INSERT Categories OFF; SET IDENTITY_INSERT Forums ON; declare @ForumNumber int = 1; while @ForumNumber &lt;= 50 begin insert into Forums(Id,Name,CategoryId) values(@ForumNumber,'Test ' + CONVERT(varchar(MAX), @ForumNumber), ((RAND() * 9)+1)) set @ForumNumber = @ForumNumber + 1 end SET IDENTITY_INSERT Forums OFF; SET IDENTITY_INSERT Topics ON; declare @TopicNumber int = 1; declare @date datetime = null; while @TopicNumber &lt;= 10000 begin SET @date = DATEADD(DAY, ABS(CHECKSUM(NEWID()) % 3650), '2000-01-01') insert into Topics(Id,Author,CreationDateTime,Text,ForumId) values(@TopicNumber,'Some author '+ CONVERT(varchar(MAX), @TopicNumber),@date,'Topic ' + CONVERT(varchar(MAX), @TopicNumber), ((RAND() * 49)+1)) set @TopicNumber = @TopicNumber + 1 end SET IDENTITY_INSERT Topics OFF; SET IDENTITY_INSERT Posts ON; declare @PostNumber int = 1; while @PostNumber &lt;= 1000000 begin SET @date = DATEADD(DAY, ABS(CHECKSUM(NEWID()) % 3650), '2000-01-01') insert into Posts(Id,Text,CreationDateTime,UserName,TopicId) values(@PostNumber,'Some author ' + CONVERT(varchar(MAX), @PostNumber),@date,'PostNumber ' + CONVERT(varchar(MAX), @PostNumber), ((RAND() * 9999)+1)) set @PostNumber = @PostNumber + 1 end SET IDENTITY_INSERT Posts OFF; </code></pre> <p>Need advice how to improve structure and performance and keep the same output result.</p> <p>I tried only <code>CREATE NONCLUSTERED INDEX [TEST_INDEX] ON dbo.Posts (CreationDateTime) INCLUDE (TopicId,UserName)</code> it gave some improvement but not much.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-01T01:11:18.877", "Id": "470258", "Score": "0", "body": "It would be very helpful if you posted the related tables as well, and any indexes you created." } ]
[ { "body": "<p>From what I can gather you are trying to produce a summary view with forum statistics. The code is a bit hard to read and I am not in a position to reproduce your environment right now so I will just give some tips.</p>\n\n<p>In order to analyze and optimize your queries you must absolutely get acquainted with the <strong>execution plan</strong>. It will tell you how the query parser is processing your SQL, whether it is using indexes etc, and what parts of the code are more expensive.</p>\n\n<p><strong>Indexing</strong>: generally you are going to put an index on the fields against which you will be actually searching.\nFor example indexing the user ID in the table of posts makes sense, because searching by user (user ID) is a very common type of request. So when you run a query like <code>select from table where userid = xxx</code>, the database engine can use the index and avoid doing a <strong>full table scan</strong> to retrieve the results. For an ecommerce site, you will probably index the order date when you frequently count the number of orders within a date range etc.</p>\n\n<p>When you are <strong>joining</strong> tables, it will also help if the fields being joined are covered by an index.</p>\n\n<p>An index is not an absolute requirement, if you have very few records you won't experience performance problems, but if you have lots of records and join many tables the load is going to increase exponentially.</p>\n\n<p>In terms of <strong>data storage</strong> some design choices strike me as not so efficient eg:</p>\n\n<pre><code>CREATE TABLE [dbo].[Topics](\n [Id] [bigint] IDENTITY(1,1) NOT NULL,\n [Text] [nvarchar](max) NULL,\n [CreationDateTime] [datetime2](7) NOT NULL,\n [Author] [nvarchar](max) NULL,\n [ForumId] [bigint] NOT NULL,\n CONSTRAINT [PK_Topics] PRIMARY KEY CLUSTERED \n(\n [Id] ASC\n)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]\n) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]\n</code></pre>\n\n<p>The maximum length for a username is usually quite limited (probably &lt; 50 chars) so nvarchar(50) should be more than enough. But it is common to use user IDs. Although there could be one benefit here, if you delete a user from the table of users, you could still retain the original name in the posts hes/she made... for historical purposes.</p>\n\n<p>Even for the post messages <code>[nvarchar](max)</code> does not seem to be justified. I don't think any forum will really allow unlimited post size. In fact even if you did, the webserver will likely deny very large HTTP POST requests (could be a few megabytes).</p>\n\n<p>The performance issues with <code>[nvarchar](max)</code> are not always obvious or immediate but for reference here is one discussion on the matter: <a href=\"https://sqlperformance.com/2017/06/sql-plan/performance-myths-oversizing-strings\" rel=\"nofollow noreferrer\">Performance Myths : Oversizing string columns</a></p>\n\n<p>IDs are often <code>int</code>, unless you really expect to have billions of records in your tables... even with lots of table regeneration <code>bigint</code> seems excessive.</p>\n\n<p>As to the stored procedure proper: you are under no obligation to have such a big query with lots of nested SELECT statements. Readability is not that great.</p>\n\n<p>Instead, you could collect the stats in <strong>separate statements</strong>. And then gather all the values together.\nUse a temporary table or in-memory table if you want. Since this is a stored procedure and not a regular view you have lots of freedom.</p>\n\n<p>What I would suggest is:</p>\n\n<ul>\n<li>rethink your <strong>table structure</strong>, look at how forums works, download some free forum software like phpbb, freebb or whatever and analyze the code and the database structure</li>\n<li>break your code in small bits, and evaluate each of them with the help of the execution plan</li>\n<li>if that is too complicated or too much work, simplify the code by removing some level of detail, until you get acceptable performance - this is one way to determine where the bottleneck is. Again, the execution plan should tell you.</li>\n</ul>\n\n<p>If you still cannot overcome the performance problem, then there is a very old technique: use <strong>aggregate tables</strong>. These are separate statistical tables that you update every time a post is made, moved or deleted etc. There is more overhead involved, because you must keep them in sync to maintain accurate figures (use <strong>transactions</strong> to minimize the risk of discrepancy). But this could very well be faster than computing stats on the fly. I would not be surprised if other forums use them.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-01T02:44:09.650", "Id": "239722", "ParentId": "239715", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-31T23:05:25.090", "Id": "239715", "Score": "1", "Tags": [ "database", "t-sql", "stored-procedure" ], "Title": "MSSQL database structure and stored procedure performance" }
239715
<p>For a project I am using the yelp dataset (found here: <a href="https://www.yelp.com/dataset" rel="noreferrer">https://www.yelp.com/dataset</a>) to create a Hashset of all verbs, nouns and adjectives found in the restaurant reviews. I have it up and running using the stanford nlp pipeline, however it is quite slow (takes about 1 hour to process 10000 reviews) and the dataset contains a few million reviews. I am not an advanced programmer, I usually barely get it working so I really need help increasing the performance of my program. General coding advice is very much appreciated as well!</p> <p>My code is as structured as follows: I have a MyCorpus class that has a function review_loader(). This function loads one review ( a json object) and puts the relevant data in a class named review. review contains a function that performs the pipeline operation and returns all nouns, verbs and adjectives of the review as a HashSet, I then add this hashset to a global hashset which will contain all nouns, verbs and adjectives of the yelp dataset.</p> <p>Code for the relevant functions can be seen below:</p> <p><strong>Review.java</strong></p> <pre><code>public class review { private String text; private String business_id; private int stars; private ArrayList&lt;String&gt; listOfSentences = new ArrayList&lt;String&gt;(); private ArrayList&lt;String&gt; pos_tags = new ArrayList&lt;String&gt;(); private HashSet&lt;String&gt; all_terms = new HashSet&lt;String&gt;(); public review() { } public HashSet&lt;String&gt; find_terms(StanfordCoreNLP pipeline) { CoreDocument doc = new CoreDocument(text); pipeline.annotate(doc); for(int f = 0; f &lt;doc.sentences().size(); f++) { for (int d = 0; d &lt; doc.sentences().get(f).tokens().size(); d++) { String tag = doc.sentences().get(f).posTags().get(d); CoreLabel word = doc.sentences().get(f).tokens().get(d); if (tag.contains("VB") == true|| tag.contains("JJ") == true || tag.contains("NN") == true);{ String pattern ="[\\p{Punct}&amp;&amp;[^@',&amp;]]"; // Create a Pattern object Pattern r = Pattern.compile(pattern, Pattern.CASE_INSENSITIVE); // Now create matcher object. Matcher m = r.matcher(word.originalText()); if (m.find() || word.originalText() == "") { } else { all_terms.add(word.originalText()); } } } } return all_terms; } </code></pre> <p><strong>MyCorpus.java</strong></p> <pre><code>public class MyCorpus{ private String filelocation_review; private String filelocation_business; private String filelocation_pos; private ArrayList&lt;String&gt; restaurants = new ArrayList&lt;String&gt;(); private Set&lt;String&gt; allTerms = new HashSet&lt;String&gt;(); public MyCorpus(String filelocation_review, String filelocation_business, String filelocation_pos) { this.filelocation_review = filelocation_review; this.filelocation_business = filelocation_business; this.filelocation_pos = filelocation_pos; } public void review_loader() throws FileNotFoundException, UnsupportedEncodingException { int counter = 0; Properties props = new Properties(); // set the list of annotators to run props.setProperty("annotators", "tokenize,ssplit,pos,parse"); // set a property for an annotator, in this case the coref annotator is being // set to use the neural algorithm props.setProperty("coref.algorithm", "neural"); // build pipeline StanfordCoreNLP pipeline = new StanfordCoreNLP(props); MaxentTagger tagger = new MaxentTagger(filelocation_pos); InputStream is_r = new FileInputStream(filelocation_review); Reader r_r = new InputStreamReader(is_r, "UTF-8"); Gson gson_r = new GsonBuilder().create(); JsonStreamParser p = new JsonStreamParser(r_r); while (p.hasNext()) { counter += 1; JsonElement e = p.next(); if (e.isJsonObject()) { review review = gson_r.fromJson(e, review.class); // This if statement checks if the review belongs to a restaurant by matching the business id to a list of all business_id's of a restaurant created previously if (restaurants.contains(review.get_id())) { HashSet&lt;String&gt; review_terms = review.find_terms(pipeline); allTerms.addAll(review_terms); System.out.println("size:" + allTerms.size() + "reviews processed: " + counter); } } } public static void main(String args[]) throws IOException { // WHEN YOU RUN THE FILE CHANGE THE 3 FILELOCATIONS OF THE MYCORPUS CLASS! MyCorpus yelp_dataset = new MyCorpus("E:\\review.json", "E:\\business.json", "C:\\Users\\Ruben\\git\\Heracles\\stanford-postagger-2018-10-16\\models\\english-bidirectional-distsim.tagger"); ArrayList&lt;String&gt; restaurants = yelp_dataset.business_identifier(); yelp_dataset.review_loader(); } </code></pre> <p>If there is anything that is unclear or seems weird, please do ask and thank you for taking the time to read this question.</p> <p>Kind regards, Ruben</p>
[]
[ { "body": "<p>Welcome to Code Review, here some suggestions about your code:</p>\n\n<blockquote>\n<pre><code>public class review { ... }\n</code></pre>\n</blockquote>\n\n<p>Java classnames always begin with uppercase letter so rename it to <code>Review</code>.</p>\n\n<blockquote>\n<pre><code>private ArrayList&lt;String&gt; restaurants = new ArrayList&lt;String&gt;();\n</code></pre>\n</blockquote>\n\n<p>In java language it is preferable using if possible an interface like <code>List</code> on the left part of the assignment so if you change the concrete class implementing the interface you don't notice the change in your code like below:</p>\n\n<pre><code>private List&lt;String&gt; restaurants = new ArrayList&lt;String&gt;();\n</code></pre>\n\n<p>Same approach from returning value from method:</p>\n\n<blockquote>\n<pre><code>public HashSet&lt;String&gt; find_terms(StanfordCoreNLP pipeline) { ... }\n</code></pre>\n</blockquote>\n\n<p>Use instead:</p>\n\n<pre><code>public Set&lt;String&gt; find_terms(StanfordCoreNLP pipeline) { ... }\n</code></pre>\n\n<p>You have this method and <code>doc.sentences()</code> seems me a <code>List</code>:</p>\n\n<blockquote>\n<pre><code>for(int f = 0; f &lt;doc.sentences().size(); f++) {\n for (int d = 0; d &lt; doc.sentences().get(f).tokens().size(); d++) {\n String tag = doc.sentences().get(f).posTags().get(d);\n CoreLabel word = doc.sentences().get(f).tokens().get(d);\n if (tag.contains(\"VB\") == true|| tag.contains(\"JJ\") == true || tag.contains(\"NN\") == true);{\n String pattern =\"[\\\\p{Punct}&amp;&amp;[^@',&amp;]]\";\n // Create a Pattern object\n Pattern r = Pattern.compile(pattern, Pattern.CASE_INSENSITIVE);\n // Now create matcher object.\n Matcher m = r.matcher(word.originalText());\n if (m.find() || word.originalText() == \"\") {\n } else {\n all_terms.add(word.originalText());\n }\n }\n}\n</code></pre>\n</blockquote>\n\n<p>Rewrite it in a more readable way:</p>\n\n<pre><code>for(Sentence sentence : doc.sentences()) {\n for (int d = 0; d &lt; sentence.token.size(); ++d) {\n String tag = sentence.posTags().get(d);\n CoreLabel word = sentence.tokens().get(d);\n //other instructions\n }\n}\n</code></pre>\n\n<p>The boolean condition:</p>\n\n<blockquote>\n<pre><code>tag.contains(\"VB\") == true|| tag.contains(\"JJ\") == true || tag.contains(\"NN\") == true\n</code></pre>\n</blockquote>\n\n<p>You can rewrite it like this:</p>\n\n<pre><code>tag.contains(\"VB\") || tag.contains(\"JJ\") || tag.contains(\"NN\") \n</code></pre>\n\n<p>Your pattern: </p>\n\n<blockquote>\n<pre><code>String pattern =\"[\\\\p{Punct}&amp;&amp;[^@',&amp;]]\";\nPattern r = Pattern.compile(pattern, Pattern.CASE_INSENSITIVE);\n</code></pre>\n</blockquote>\n\n<p>You are calculating it for every iteration of the loop, put it outside your loop:</p>\n\n<pre><code>String pattern =\"[\\\\p{Punct}&amp;&amp;[^@',&amp;]]\";\nPattern r = Pattern.compile(pattern, Pattern.CASE_INSENSITIVE);\nfor(Sentence sentence : doc.sentences()) {\n for (int d : sentence.token.size()) {\n String tag = sentence.posTags().get(d);\n CoreLabel word = sentence.tokens().get(d);\n //other instructions\n }\n}\n</code></pre>\n\n<p>The if else you are using:</p>\n\n<blockquote>\n<pre><code>if (m.find() || word.originalText() == \"\") {\n} else {\n all_terms.add(word.originalText());\n}\n</code></pre>\n</blockquote>\n\n<p>You are doing an error here using the operator <code>==</code> and not the <code>equals</code> method for comparing strings; rewrite the method like this:</p>\n\n<pre><code>if (!m.find() &amp;&amp; !word.originalText().equals(\"\")) {\n all_terms.add(word.originalText());\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-01T11:04:37.640", "Id": "470291", "Score": "2", "body": "What is `for (int d : sentence.token.size())`? Did they introduce a foreach integer up to integer in one of the last relases?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-01T11:58:05.313", "Id": "470297", "Score": "1", "body": "@mtj Thanks , I wrote a stupid thing and I fix it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-02T09:33:53.597", "Id": "470390", "Score": "0", "body": "Thank you so much for answering, I incorporated your and the other commenters notes and it works like a charm! I really appreciate the general notes for better code" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-02T15:13:19.953", "Id": "470416", "Score": "0", "body": "@RubenEschauzier You are welcome, if you have other questions post them on the Code Review site." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-01T10:09:23.070", "Id": "239733", "ParentId": "239716", "Score": "4" } }, { "body": "<p>Adding to what @dariosicily mentioned already:</p>\n\n<h2>Performance</h2>\n\n<p>If you just need to find out a part-of-speech of each word and do not need to <a href=\"https://stanfordnlp.github.io/CoreNLP/parse.html\" rel=\"nofollow noreferrer\">build a phrase-structure tree of sentences</a>, you need only to specify 3 annotations (without <code>parse</code>):</p>\n\n<p><code>props.setProperty(\"annotators\", \"tokenize,ssplit,pos\");</code> </p>\n\n<p>I assume this can give you a significant boost in performance.</p>\n\n<p>Since you are not doing <a href=\"https://stanfordnlp.github.io/CoreNLP/coref.html\" rel=\"nofollow noreferrer\">coreference resolution</a>, you don't need this line either:</p>\n\n<blockquote>\n<pre><code>props.setProperty(\"coref.algorithm\", \"neural\");\n</code></pre>\n</blockquote>\n\n<h2>Incorrect if-block</h2>\n\n<blockquote>\n<pre><code>if (tag.contains(\"VB\") == true|| tag.contains(\"JJ\") == true || tag.contains(\"NN\") == true);{\n String pattern =\"[\\\\p{Punct}&amp;&amp;[^@',&amp;]]\";\n...\n}\n</code></pre>\n</blockquote>\n\n<p>You should remove the semicolon before the curly bracket, since currently, it terminates the if-block (and makes it empty), so the instructions inside the curly brackets will always be executed! The code above is now equal to the following:</p>\n\n<pre><code>if (tag.contains(\"VB\") == true|| tag.contains(\"JJ\") == true || tag.contains(\"NN\") == true){\n /* Doing nothing */\n}\n\n{\n String pattern =\"[\\\\p{Punct}&amp;&amp;[^@',&amp;]]\";\n...\n}\n\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-01T12:37:07.780", "Id": "470301", "Score": "1", "body": "Absolutely correct to remark about the semicolon, I have not added it because for me it was a typo due to a bad paste and copy, anyway in the doubt better to advise about it the OP." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-02T09:35:12.737", "Id": "470391", "Score": "1", "body": "Thank you so much for answering! I didn't realize I didn't need those functions, those took 80% of all run time of the program! I was now able to run the program within ~4 hours." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-01T12:22:43.967", "Id": "239739", "ParentId": "239716", "Score": "3" } } ]
{ "AcceptedAnswerId": "239739", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-31T23:05:56.653", "Id": "239716", "Score": "7", "Tags": [ "java", "performance", "natural-language-processing" ], "Title": "Extracting all nouns, verbs and adjectives from a large text dataset" }
239716
<p>This is my first time writing an authentication system. Here's how it works, first client needs to send credential within authorization header like { Authorization : 'Basic ' + credential } through API. I encoded the credential with base64 encoder ('username:password') and then if the authentication is successfully it will return a jwt token within response headers like { Authorization : 'Bearer ' + jwtToken }. Is there any insecurity with this implementation that I should concern? Here's my code</p> <p>Security configuration:</p> <pre><code> @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private JwtRequestFilter jwtRequestFilter; @Autowired private AccountDetailsService accountDetailsService; @Autowired private AccountService accountService; @Autowired public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { // Mock an account for testing purpose this.accountService.saveAccount(new Account("pink", passwordEncoder().encode("1234"), 10L)); auth.userDetailsService(accountDetailsService); } @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } @Override @Bean public AuthenticationManager authenticationManagerBean() throws Exception { return super.authenticationManagerBean(); } @Override protected void configure(HttpSecurity httpSecurity) throws Exception { httpSecurity.cors(); httpSecurity.csrf().disable() .authorizeRequests().antMatchers("/api/v1/auth").permitAll(). anyRequest().authenticated().and(). exceptionHandling().and().sessionManagement() .sessionCreationPolicy(SessionCreationPolicy.STATELESS); httpSecurity.addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class); } } </code></pre> <p>UserDetailsService implementation:</p> <pre><code> @Service public class AccountDetailsService implements UserDetailsService { @Autowired private AccountRepository accountRepository; @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { Account account = accountRepository.findByUserName(username); if (account == null) { throw new UsernameNotFoundException(username); } return new AccountPrincipal(account); } } </code></pre> <p>Custom filter for jwt: </p> <pre><code> @Component public class JwtRequestFilter extends OncePerRequestFilter { @Autowired private AccountDetailsService accountDetailsService; @Autowired private JwtUtil jwtUtil; @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException { final String authorizationHeader = request.getHeader("Authorization"); String username = null; String jwt = null; if (authorizationHeader != null &amp;&amp; authorizationHeader.startsWith("Bearer ")) { jwt = authorizationHeader.substring(7); System.out.println(jwt); username = jwtUtil.extractUsername(jwt); } if (username != null &amp;&amp; SecurityContextHolder.getContext().getAuthentication() == null) { UserDetails accountDetails = this.accountDetailsService.loadUserByUsername(username); if (jwtUtil.validateToken(jwt, accountDetails)) { UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken( accountDetails, null, accountDetails.getAuthorities()); usernamePasswordAuthenticationToken .setDetails(new WebAuthenticationDetailsSource().buildDetails(request)); SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken); } } chain.doFilter(request, response); } } </code></pre> <p>Jwt object for creating and validating jwt :</p> <pre><code> @Service public class JwtUtil { private Key SECRET_KEY = Keys.secretKeyFor(SignatureAlgorithm.HS512); public String extractUsername(String token) { return extractClaim(token, Claims::getSubject); } public Date extractExpiration(String token) { return extractClaim(token, Claims::getExpiration); } public &lt;T&gt; T extractClaim(String token, Function&lt;Claims, T&gt; claimsResolver) { final Claims claims = extractAllClaims(token); return claimsResolver.apply(claims); } private Claims extractAllClaims(String token) { return Jwts.parser().setSigningKey(SECRET_KEY).parseClaimsJws(token).getBody(); } private Boolean isTokenExpired(String token) { return extractExpiration(token).before(new Date()); } public String generateToken(UserDetails userDetails) { Map&lt;String, Object&gt; claims = new HashMap&lt;&gt;(); return createToken(claims, userDetails.getUsername()); } private String createToken(Map&lt;String, Object&gt; claims, String subject) { return Jwts.builder().setClaims(claims).setSubject(subject).setIssuedAt(new Date(System.currentTimeMillis())) .setExpiration(new Date(System.currentTimeMillis() + (1000 * 60 * 60 * 10))) .signWith(SECRET_KEY).compact(); } public Boolean validateToken(String token, UserDetails userDetails) { final String username = extractUsername(token); return (username.equals(userDetails.getUsername()) &amp;&amp; !isTokenExpired(token)); } } </code></pre> <p>Controller for authentication</p> <pre><code> @RestController @RequestMapping("/api/v1/") public class AuthenticationController { @Autowired private AccountDetailsService accountDetailsService; @Autowired private AuthenticationManager authenticationManager; @Autowired private JwtUtil jwtTokenUtil; @RequestMapping(value = "/auth", method = RequestMethod.POST) public ResponseEntity&lt;?&gt; getAuthenticate(@RequestHeader("Authorization") String authorization) throws Exception{ String encodedCredentials = authorization.substring(6); byte[] decodedCredentialByte = Base64.getDecoder().decode(encodedCredentials); String[] decodedCredentialString = new String(decodedCredentialByte).split(":"); System.out.println(decodedCredentialString[0] + ":" + decodedCredentialString[1]); try { authenticationManager.authenticate( new UsernamePasswordAuthenticationToken(decodedCredentialString[0], decodedCredentialString[1]) ); } catch (BadCredentialsException e) { throw new Exception("Incorrect username or password", e); } final UserDetails userDetails = this.accountDetailsService.loadUserByUsername(decodedCredentialString[0]); final String jwt = "Bearer " + jwtTokenUtil.generateToken(userDetails); HttpHeaders headers = new HttpHeaders(); headers.add(HttpHeaders.AUTHORIZATION, jwt); return new ResponseEntity&lt;&gt;(headers ,HttpStatus.OK); } } </code></pre> <p>Account entity and account principal: </p> <pre><code> @Entity @Table(name = "Account") public class Account { @Id @GeneratedValue(strategy=GenerationType.AUTO) private Long accountId; private String userName; private String passWord; private Long nuggerPoint; public Account(){ } public Account(String username, String password, Long nuggerpoint){ this.userName = username; this.passWord = password; this.nuggerPoint = nuggerPoint; } public Long getAccountId(){ return accountId; } public void setAccountId(Long accountId){ this.accountId = accountId; } public String getUserName(){ return this.userName; } public void setUserName(String userName){ this.userName = userName; } public String getPassword(){ return this.passWord; } public void setPassword(String password){ this.passWord = password; } public Long getNuggerPoint(){ return this.nuggerPoint; } public void setNuggerPoint(Long nuggerPoint){ this.nuggerPoint = nuggerPoint; } } public class AccountPrincipal implements UserDetails { private Account account; public AccountPrincipal(Account account) { this.account = account; } @Override public Collection&lt;? extends GrantedAuthority&gt; getAuthorities() { return new ArrayList&lt;&gt;(); } @Override public String getPassword() { return this.account.getPassword(); } @Override public String getUsername() { return this.account.getUserName(); } @Override public boolean isAccountNonExpired() { return true; } @Override public boolean isAccountNonLocked() { return true; } @Override public boolean isCredentialsNonExpired() { return true; } @Override public boolean isEnabled() { return true; } } <span class="math-container">```</span> </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-31T23:16:22.810", "Id": "239717", "Score": "2", "Tags": [ "java", "security", "authentication", "spring" ], "Title": "JWT authentication system login through API" }
239717
<p>I have written some Python code that opens files one by one, does some work, and writes data onto the filesystem. I figured, I want to make use of my cores.I've refactored the program into this.</p> <pre><code>from multiprocessing import Pool import glob def work(file_name): # do work pass if __name__ == "__main__": pool = Pool() pool.map(work, (glob.iglob('.somedir/**/*.data', recursive=True))) pool.close() </code></pre> <p>Wanted to know if that's okay practice.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-01T04:17:07.510", "Id": "470264", "Score": "1", "body": "I think your copy and paste did not work (`passif `)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-01T09:58:15.880", "Id": "470285", "Score": "0", "body": "`# do work` This question does not match what this site is about. Code Review is about improving existing, working code. The example code that you have posted is not reviewable in this form because it leaves us guessing at your intentions. Unlike Stack Overflow, Code Review needs to look at concrete code in a real context. Please see [Why is hypothetical example code off-topic for CR?](//codereview.meta.stackexchange.com/q/1709)" } ]
[ { "body": "<h1>context manager</h1>\n\n<p>The <a href=\"https://docs.python.org/3.5/library/multiprocessing.html#using-a-pool-of-workers\" rel=\"nofollow noreferrer\">documentation</a> uses a <code>with</code> statement, instead of </p>\n\n<pre><code>pool = Pool()\n...\npool.close()\n</code></pre>\n\n<p>to make sure the <code>close</code> is run, even when there are exceptions</p>\n\n<h1>variables</h1>\n\n<p>Variables names are the primary means of commenting you code. I would make <code>glob.iglob('.somedir/**/*.data', recursive=True))</code> a variable. I would even use the <code>pathlib</code> module to make the code even more clear.</p>\n\n<p>This also gives you the opportunity to test whether the <code>glob</code> gives you back the correct files.</p>\n\n<h1>type annotations</h1>\n\n<p>You can tell the functions which types it can expect.This does nothing at run-time, but can help your IDE detect small bugs, and act as additional documentation to the users of the function</p>\n\n<h1>programming tools</h1>\n\n<p>I use <a href=\"https://github.com/psf/black\" rel=\"nofollow noreferrer\"><code>black</code></a> as code formatter, <a href=\"https://isort.readthedocs.io/en/latest/\" rel=\"nofollow noreferrer\"><code>isort</code></a> to sort my imports, a linter <a href=\"https://github.com/klen/pylama\" rel=\"nofollow noreferrer\"><code>pylama</code></a> and <a href=\"http://mypy-lang.org/\" rel=\"nofollow noreferrer\"><code>mypy</code></a> for static code analysis. All integrated into my IDE workflow.</p>\n\n<p>For mypy, I use this rather strict configuration</p>\n\n<pre><code>[mypy]\ncheck_untyped_defs = true\ndisallow_any_generics = true\ndisallow_untyped_defs = true\nignore_missing_imports = true\nno_implicit_optional = true\nwarn_redundant_casts = true\nwarn_return_any = true\nwarn_unused_ignores = true\n</code></pre>\n\n<hr>\n\n<pre><code>import typing\nfrom multiprocessing import Pool\nfrom pathlib import Path\n\n\ndef work(file_name: typing.Union[str, Path]) -&gt; None:\n \"\"\"&lt;doc-string&gt;\"\"\"\n # do work\n pass\n\n\nif __name__ == \"__main__\":\n data_dir = Path(\".somedir/\")\n file_names = data_dir.glob(\"**/*.data\")\n with Pool() as pool:\n pool.map(work, file_names)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-01T05:37:51.147", "Id": "239727", "ParentId": "239719", "Score": "1" } } ]
{ "AcceptedAnswerId": "239727", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-01T00:55:00.357", "Id": "239719", "Score": "-2", "Tags": [ "python", "python-3.x", "multiprocessing" ], "Title": "Python code refactor to use multiprocessing" }
239719
<p>The code returns a string ready to seed at sites like <a href="https://www.sudoku-solutions.com/" rel="nofollow noreferrer">sudoku-solutions.com</a>.</p> <p>It works great but as I couldn't find other simple examples for my level I hope for some insights on this and ways to correct what is wrong.</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 sudoku = []; function shuffle(a) { for (let i = a.length - 1; i &gt; 0; i--) { const j = Math.floor(Math.random() * (i + 1)); [a[i], a[j]] = [a[j], a[i]]; } return a; } function randomNumber() { let num = Math.floor(Math.random() * 9 + 1); return num; } function randomFiller(a) { while (a.length &lt; 9) { let num = randomNumber(); a.push(num); if (a.indexOf(num) &lt; a.lastIndexOf(num)) { a.pop(); } } return a; } function populateSudoku() { let arr = []; while (sudoku.length &lt; 9) { arr = []; sudoku.push(Array.from(randomFiller(arr))); } return arr; } function arrange3x3() { let arr = []; let line1 = []; let line2 = []; let line3 = []; for (let i = 0; i &lt; sudoku.length; i++) { line1.push(sudoku[i].splice(0, 3)); line2.push(sudoku[i].splice(0, 3)); line3.push(sudoku[i].splice(0, 3)); } for (let i = 0; i &lt; sudoku.length; i += 3) { sudoku[i].push(line1.splice(0, 3)); } for (let i = 1; i &lt; sudoku.length; i += 3) { sudoku[i].push(line2.splice(0, 3)); } for (let i = 2; i &lt; sudoku.length; i += 3) { sudoku[i].push(line3.splice(0, 3)); } sudoku = [].concat.apply([], sudoku); return sudoku; } function shuffleY(lmr) { let check = false; let x = []; let y = []; let z = []; while (check === false) { for (let i = 0; i &lt; sudoku.length; i++) { x.push(sudoku[i][lmr][0]); } for (let i = 0; i &lt; sudoku.length; i++) { y.push(sudoku[i][lmr][1]); } for (let i = 0; i &lt; sudoku.length; i++) { z.push(sudoku[i][lmr][2]); } if (x.every((element, index) =&gt; { return index === x.lastIndexOf(element); }) &amp;&amp; y.every((element, index) =&gt; { return index === y.lastIndexOf(element); })) { check = true; } else { x.splice(0); y.splice(0); z.splice(0); for (let i = 0; i &lt; sudoku.length; i++) { shuffle(sudoku[i][lmr]); } } } } function mirrorSudoku() { sudoku.forEach((element, index) =&gt; { sudoku[index] = [].concat.apply([], element); }) let copy = JSON.parse(JSON.stringify(sudoku)); for (let i = 0; i &lt; sudoku.length; i++) { for (let j = 0; j &lt; sudoku.length; j++) { copy[j][i] = sudoku[i][j]; } } for (let i = 0; i &lt; copy.length; i++) { sudoku[i].splice(0); sudoku[i].push(copy[i].splice(0, 3)); sudoku[i].push(copy[i].splice(0, 3)); sudoku[i].push(copy[i].splice(0, 3)); } } populateSudoku(); arrange3x3(); shuffleY(0); shuffleY(1); shuffleY(2); mirrorSudoku(); shuffleY(0); shuffleY(1); shuffleY(2); sudoku = [].concat.apply([], sudoku); sudoku = [].concat.apply([], sudoku); console.log(sudoku.join(''));</code></pre> </div> </div> </p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-01T02:21:22.790", "Id": "239721", "Score": "1", "Tags": [ "javascript", "beginner", "sudoku", "generator" ], "Title": "Sudoku seed generator" }
239721
<p>I would like to create a function like <a href="https://docs.python.org/3.0/library/itertools.html" rel="nofollow noreferrer">zip_lognest in python</a> and if the array size is uneven, I do not want to filled any value. following is my code and example</p> <pre><code>const aFixture = [ { name: 'name_a', value: 'value_a'}, { name: 'name_b', value: 'value_b'}, { name: 'name_c', value: 'value_c'}, { name: 'name_d', value: 'value_d'}, ]; const bFixture = [ { name: 'name_1', value: 'value_1'}, { name: 'name_2', value: 'value_2'}, ]; const cFixture = [ { name: 'name_x', value: 'value_x'}, { name: 'name_y', value: 'value_y'}, { name: 'name_z', value: 'value_z'}, ]; export function zipLongest(...arrays: Array&lt;any&gt;) { const length = Math.max(...arrays.map((arr) =&gt; arr.length)); const tempArray = Array.from({length}, (_, index) =&gt; arrays.map((array) =&gt; (array.length - 1 &gt;= index ? array[index] : undefined)) ) return tempArray.map((array) =&gt; array.filter((x: any) =&gt; x !== undefined)) } const myarray = zipLongest( aFixture, bFixture, cFixture, ) console.log(myarray); //[ [ { name: 'name_a', value: 'value_a' }, // { name: 'name_1', value: 'value_1' }, // { name: 'name_x', value: 'value_x' } ], // [ { name: 'name_b', value: 'value_b' }, // { name: 'name_2', value: 'value_2' }, // { name: 'name_y', value: 'value_y' } ], // [ { name: 'name_c', value: 'value_c' }, // { name: 'name_z', value: 'value_z' } ], // [ { name: 'name_d', value: 'value_d' }, ] //] </code></pre>
[]
[ { "body": "<p>How about this? You iterate through each array only once.</p>\n\n<pre><code>function zipLongest(...arrays: Array&lt;any&gt;) {\n const result:any[] = [];\n arrays.forEach((arr) =&gt; {\n arr.forEach((val: any, i: number) =&gt; { \n if (i === result.length) result.push([]);\n result[i].push(val);\n })\n });\n return result;\n}\n</code></pre>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>\"use strict\";\nconst aFixture = [\n { name: 'name_a', value: 'value_a' },\n { name: 'name_b', value: 'value_b' },\n { name: 'name_c', value: 'value_c' },\n { name: 'name_d', value: 'value_d' },\n];\nconst bFixture = [\n { name: 'name_1', value: 'value_1' },\n { name: 'name_2', value: 'value_2' },\n];\nconst cFixture = [\n { name: 'name_x', value: 'value_x' },\n { name: 'name_y', value: 'value_y' },\n { name: 'name_z', value: 'value_z' },\n];\nfunction zipLongest(...arrays) {\n const result = [];\n arrays.forEach((arr) =&gt; {\n for (var i = 0; i &lt; arr.length; i++) {\n if (i &gt;= result.length) {\n result.push([arr[i]]);\n }\n else {\n result[i] = result[i].concat(arr[i]);\n }\n }\n });\n return result;\n}\nconst myarray = zipLongest(aFixture, bFixture, cFixture);\nconsole.log(myarray);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-01T12:46:25.690", "Id": "470302", "Score": "0", "body": "If anyway I can merged a for each statement in map function?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-02T07:30:03.540", "Id": "470378", "Score": "0", "body": "map does not make sense in that scenario as you are not transforming the array. That's the use case for map." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-01T09:48:15.480", "Id": "239732", "ParentId": "239723", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-01T02:45:47.607", "Id": "239723", "Score": "1", "Tags": [ "javascript", "typescript" ], "Title": "zip_longest without fillvalue in typescript" }
239723
<p>I have this ugly massive piece of code. It does many things, mostly around querying databases. Each query depends on the result of the previous query or on the parameters of the incoming request body. Queries are done asynchronously using <code>Future</code>. The code works but is not readable. How can I restructure it to make it concise? I have thought of using <code>for</code> instead of <code>map</code> and <code>flatMap</code> but due to dependencies on previous queries, I am not able to figure out how to use result of previous <code>Future</code> in new ones and how to handle error paths.</p> <pre><code> def oldSignupUser = silhouette.UserAwareAction.async { implicit request =&gt; { val body: AnyContent = request.body val jsonBody: Option[JsValue] = body.asJson jsonBody match { case Some(json) =&gt; { val userProfile: Option[UserProfile] = json.asOpt[UserProfile] userProfile match { case Some(profile) =&gt; { val loginInfo = LoginInfo(CredentialsProvider.ID, profile.externalProfileDetails.email) val userKeys = UserKeys(utilities.bucketIDFromEmail(profile.externalProfileDetails.email),profile.externalProfileDetails.email,loginInfo,profile.externalProfileDetails.firstName,profile.externalProfileDetails.lastName) val findUserFuture: Future[Option[User]] = userRepo.findOne(userKeys) // userFuture will eventually contain the result of database query i.e Some(user) or None findUserFuture.flatMap { (userOption: Option[User]) =&gt; userOption match { case Some(user) =&gt; { if(user.profile.internalProfileDetails.get.confirmed) { Future { Ok(Json.toJson(JsonResultError(messagesApi("error.duplicateUser")(langs.availables(0))))) } } else { val userKeys = UserKeys(utilities.bucketIDFromEmail(user.profile.externalProfileDetails.email),user.profile.externalProfileDetails.email,loginInfo,user.profile.externalProfileDetails.firstName,user.profile.externalProfileDetails.lastName) val userToken:UserToken = utilities.createUserToken(user.id,userKeys,UserTokenType.RegistrationConfirmation) val userTokenSaveFuture:Future[Option[UserToken]] = userTokenRepo.save(userToken) logger.trace(s"user token save future ${userTokenSaveFuture}") userTokenSaveFuture.map( (userTokenOption:Option[UserToken])=&gt;{ userTokenOption match { case Some(userToken) =&gt; { val signupEmailOption:Option[SignupEmail] = createEmailMessageForUserToken(userToken) signupEmailOption match { case Some(signupEmail:SignupEmail) =&gt;{ val _:String = mailerService.sendEmail(signupEmail.subject, signupEmail.from,List(user.profile.externalProfileDetails.email),None,Some(signupEmail.html)) Ok(Json.toJson(JsonResultSuccess(messagesApi("success.userSignupConfirmationEmailSent")(langs.availables(0))))) } case None =&gt;{ InternalServerError(Json.toJson(JsonResultError("Internal Server Error"))) } } } case None =&gt; { Ok(Json.toJson(JsonResultError("user not added"))) //Todom - this is misleading as user is added but token isn't } } }) } } case None =&gt; { val passwordInfo:PasswordInfo = userRepo.hashPassword(profile.externalProfileDetails.password.get) val bucketId = utilities.bucketIDFromEmail(profile.externalProfileDetails.email) val newUser:User = User( utilities.getUniqueID(),//UUID.randomUUID(), UserProfile(Some(InternalUserProfile(loginInfo,bucketId,false,Some(passwordInfo))), profile.externalProfileDetails)) val saveUserFuture:Future[Option[User]] = userRepo.save(newUser) saveUserFuture.flatMap { (userOption:Option[User]) =&gt;{ userOption match { case Some(user) =&gt; { val initialPortfolio = user.profile.externalProfileDetails.portfolio val profileAndPortfolio = profile.externalProfileDetails.copy(portfolio = initialPortfolio) logger.trace(s"saving external profile and portfolio ${profileAndPortfolio}") val savedProfileAndPortfolioOptionFuture = userProfileAndPortfolioRepo.save(profileAndPortfolio) savedProfileAndPortfolioOptionFuture.flatMap(profileAndPortfolioOption =&gt;{ profileAndPortfolioOption match { case Some(profileAndPortfolio) =&gt; { val userKeys = UserKeys(utilities.bucketIDFromEmail(user.profile.externalProfileDetails.email),user.profile.externalProfileDetails.email,loginInfo,user.profile.externalProfileDetails.firstName,user.profile.externalProfileDetails.lastName) val userToken:UserToken = utilities.createUserToken(user.id,userKeys,UserTokenType.RegistrationConfirmation) val userTokenSaveFuture:Future[Option[UserToken]] = userTokenRepo.save(userToken) userTokenSaveFuture.flatMap( (userTokenOption:Option[UserToken])=&gt;{ userTokenOption match { case Some(userToken) =&gt; { val signupEmailOption = createEmailMessageForUserToken(userToken) signupEmailOption match { case Some(signupEmail) =&gt;{ val _:String = mailerService.sendEmail(signupEmail.subject,signupEmail.from,List(user.profile.externalProfileDetails.email),None,Some(signupEmail.html)) Future{Ok(Json.toJson(JsonResultSuccess((messagesApi("success.userSignupConfirmationEmailSent"))(langs.availables(0)))))} } case None =&gt;{ Future{InternalServerError(Json.toJson(JsonResultError("Internal Server Error")))} } } } case None =&gt; { Future{Ok(Json.toJson(JsonResultError("user not added"))) } } } }) } case None =&gt;{ Future{InternalServerError(Json.toJson(JsonResultError("Internal Server Error")))} } } }) } case None =&gt; { Future{Ok(Json.toJson(JsonResultError("unable to add user")))} } } } } .recover { case x =&gt; { x match { case _:EmailException =&gt;InternalServerError(Json.toJson(JsonResultError("The server encountered internal error and couldn't sent email to the email id."))) case _ =&gt; InternalServerError(Json.toJson(JsonResultError("Internal Server Error"))) } } } } } } .recover { case x =&gt; { logger.trace("Future failed in signupUser. In recover. Returning Internal Server Error"+x) x match { case _:EmailException =&gt;InternalServerError(Json.toJson(JsonResultError("The server encountered internal error and couldn't sent email to the email id."))) case _ =&gt; InternalServerError(Json.toJson(JsonResultError("Internal Server Error"))) } } } } case None =&gt; Future { logger.trace("invalid profile structure") Ok(Json.toJson(JsonResultError(messagesApi("error.incorrectBodyStructure")(langs.availables(0))))) } } } case None =&gt; Future { Ok(Json.toJson(JsonResultError(messagesApi("error.incorrectBodyType")(langs.availables(0))))) } } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-01T14:50:46.120", "Id": "470332", "Score": "3", "body": "Welcome to code review. We need more information about what the code does. The title should be a brief general overall summation of what the code does, not your concerns about the code. It would also be nice if you added a paragraph with more detail about what the code does. For more helpful hints on asking a good question see https://codereview.stackexchange.com/help/asking." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-02T18:55:08.553", "Id": "470440", "Score": "0", "body": "Try MonadError from cats" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-03T15:30:35.173", "Id": "470557", "Score": "0", "body": "As you said it does many things. I think you should separate it to several functions. After that focus us on the parts you want to improve." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-30T00:31:48.380", "Id": "477166", "Score": "0", "body": "Use `Future.successful(..)` for situations like `Future{Ok(Json.toJson(JsonResultError(\"user not added\"))) }`." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-01T07:55:57.560", "Id": "239729", "Score": "0", "Tags": [ "scala" ], "Title": "how should I optimise the scala code and make it more readable" }
239729
<p>I'm not certain if my implementation is correct, it appears to be, but looking for any feedback as far as readability and efficiency goes. Obviously using dictionaries isn't particularly efficient space wise, but how else could you achieve O(1) lookup?</p> <pre><code>import os def get_suffixes(string): return [string[i:] + "$" for i in range(len(string) + 1)] def shared_prefix(string_a, string_b): return os.path.commonprefix([string_a, string_b]) def construct_suffix_tree(string): tree = {} for i in range(len(string) + 1): suffix = string[i:] + "$" insert_suffix(suffix, tree) return tree def insert_suffix(string, suffix_tree): if len(suffix_tree) == 0: suffix_tree[string] = [] return suffix_tree found_match = False for key in list(suffix_tree): prefix = shared_prefix(string, key) n = len(prefix) if len(prefix) &gt; 0: found_match = True key_suffix = key[n:] string_suffix = string[n:] del suffix_tree[key] suffix_tree[prefix] = [key_suffix, string_suffix] if not found_match: suffix_tree[string] = [] return suffix_tree my_string = "banana" print(construct_suffix_tree(my_string)) </code></pre>
[]
[ { "body": "<p>It's pretty readable, and all comments are pretty minor ones.</p>\n\n<p>You can probably squeeze out a little performance increase, but not much. One thing you could do is to skip setting variables like <code>n = len(prefix)</code> (you also don't use <code>n</code> in the following line).</p>\n\n<p>You could also consider <code>collections.deque</code> instead of <code>list</code> where relevant, which can sometimes give you a little extra speed. Or if you have the option to use list comprehension, do so.</p>\n\n<p>And doing <code>if suffix_tree:</code> instead of <code>if len(suffix_tree) == 0:</code> is also faster; ca 30 ns vs 85 ns on my machine (Python 3.8.1).</p>\n\n<p>On the time and space complexity, you have to make a judgement call if time or space is more important; only other way you could have O(1) lookup would be with a set.</p>\n\n<p>Finally, you don't need to keep track of <code>found_match</code>---you can just use a <code>for-else</code> with a break-statement.</p>\n\n<p>PS. You should be wary of mutating objects you're iterating over.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-01T11:48:51.347", "Id": "470294", "Score": "0", "body": "Thanks for the feedback. How can I resolve the issue of mutating objects I'm iterating over? Should I keep track of the keys I need to delete, and delete all of them at the end in one loop?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-01T11:54:09.780", "Id": "470296", "Score": "0", "body": "The most common way as far as I know is to iterate over a copy of the object, and then delete from the \"real\" container, but be wary of shallow copies." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-01T11:09:03.500", "Id": "239735", "ParentId": "239730", "Score": "1" } } ]
{ "AcceptedAnswerId": "239735", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-01T08:16:49.953", "Id": "239730", "Score": "0", "Tags": [ "python", "algorithm" ], "Title": "naive suffix tree construction in Python" }
239730
<p>I have a business requirement where I have to read excel files and match each cell with a given keyword list and find the matches and write it into a dataframe.</p> <p>I have written the code, but when the excel size is increasing (7 MB - 5 sheets, 30k * 9), the code is taking unusually long time (40 minutes), and I know that it should since I have so many for loops, but is there anyway to optimize it?</p> <p>I have tried many different ways to optimize the same, but nothing worked out well. </p> <pre><code>import pandas as pd import re import datetime import numpy as np raw_details_list = [] # there are around 10 keys and 600 values keyword_dic = {"it spend": ['IT OpEx', 'OpEx'], "Infra": ["Dell", "Oracle"]} def pattern(keys): return re.compile('|'.join([r'(?&lt;!\w)%s(?!\w)' % re.escape(keys)]), flags=re.I) # this is reading each cell of the excel and doing a match whether with the keyword_dic def sheet_handler(path, page_count, row): try: global keyword_dic if isinstance(row, str): for category, keywords in keyword_dic.items(): for keys in keywords: r = pattern(keys) words = r.findall(row) # storing the matches in a list of dictionary for i in words: temp_dic = {"File Path": path, "Total Number of Page(s)/Slide(s)": page_count, "Keyword": keys, "IT Category":category} raw_details_list.append(temp_dic) except Exception as e: pass # reading the excel - all sheets and creating a dataframe def xlsx_handler(path): # reading the excel file sheets_dict = pd.read_excel(path, sheet_name=None, header=None) sheet_count = len(sheets_dict) for name, sheet in sheets_dict.items(): # removing float type columns sheet = sheet.loc[:, sheet.dtypes != np.float64] # reading each row, we have keep track of each cell's row and column details for index, row in sheet.iterrows(): for i in range(len(row)): try: # if the content is float, we can skip it float(row[i]) except Exception as e: sheet_handler(path, sheet_count, row[i]) print(datetime.datetime.now()) xlsx_handler(r"D:\Backend Python\test\test.xlsx") df = pd.DataFrame(raw_details_list) print(datetime.datetime.now()) </code></pre> <p>Sample data:</p> <pre><code>1 Oracle ERP would be good United states 2 Dell Laptops UK 3 Vaio Off-limit India 4 Oracle 1.2 E-series Chine </code></pre> <p>The output for this should somewhat look like this:</p> <pre><code>File Path Pages Keyword IT Category D://Data 1 Oracle Infra D://Data 1 Oracle Infra D://Data 1 Dell Infra </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-01T04:27:51.913", "Id": "470287", "Score": "0", "body": "first off I think you should ditch for loops - Pandas vectorized methods could significantly help. It would also be helpful if u shared a sample of ur data (not pics, or links) with the keyword list u r trying to filter for. and include ur expected output. but really, ditch the for loops" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-01T04:41:35.717", "Id": "470288", "Score": "0", "body": "Have uploaded sample input and expected output. I have already shared some sample keywords." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-01T05:06:23.297", "Id": "470289", "Score": "2", "body": "https://engineering.upside.com/a-beginners-guide-to-optimizing-pandas-code-for-speed-c09ef2c6a4d6 -- great read. I should do more of this. I agree that this more of a \"code review\"" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-01T10:56:35.530", "Id": "470290", "Score": "2", "body": "Sankar, now that this has been migrated, do add more explanation as to what your code *does*. See [How to get the best value out of Code Review - Asking Questions](https://codereview.meta.stackexchange.com/a/2438) for what makes a good Code Review question." } ]
[ { "body": "<p>The issue has been resolved.</p>\n\n<p>The problem was I was creating the pattern <code>r = pattern(keys)</code> for each keyword (remind you i had 600 keywords) for each cell of the excel which was completely unnecessary. </p>\n\n<p>So if i had a <code>10(rows) * 10 (columns) excel file</code>, the same <code>600</code> pattern was getting created <code>600 * 10 * 10 times</code>.</p>\n\n<p>So I created one dictionary of patterns just once and used the same <code>10 * 10</code> times.</p>\n\n<pre><code>for cat,key in keyword_dic.items():\n temp = [pattern(keyword) for keyword in key]\n list_of_patterns[cat] = temp\n</code></pre>\n\n<p>Thanks everyone, for taking the time to go through the post!</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-01T14:20:26.087", "Id": "239751", "ParentId": "239734", "Score": "1" } } ]
{ "AcceptedAnswerId": "239751", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-01T04:25:14.013", "Id": "239734", "Score": "2", "Tags": [ "python", "excel", "pandas" ], "Title": "Finding matches in Excel files, adding to a Pandas Dataframe" }
239734
<p>This is an extension of <a href="https://codereview.stackexchange.com/questions/239689/block-bootstrap-estimation-in-java-part-2">Block Bootstrap Estimation in Java - Part 2</a>. The text file text.txt can be found at <a href="https://drive.google.com/open?id=1vLBoNmFyh4alDZt1eoJpavuEwWlPZSKX" rel="nofollow noreferrer">https://drive.google.com/open?id=1vLBoNmFyh4alDZt1eoJpavuEwWlPZSKX</a> (please download the file directly should you wish to test it; there are some odd things about it that you will not pick up through even Notepad). <strong>This is a small 10 x 10 dataset with <code>maxBlockSize = 10</code>, but this needs to scale up to twenty 5000 x 3000 datasets with <code>maxBlockSize = 3000</code>, just to get an idea of scale.</strong> </p> <p>If helpful, I have 6 cores available with 64GB of RAM, as well as two GPUs that I have no idea how to use (Intel UHD Graphics 630, NVIDIA Quadro P620). I'll be looking over how to use these in the next few days if I have to, and have also considered re-learning Amazon Web Services.</p> <p>What is clear to me now is that <code>mbbVariance</code> is slowing this program down. Considering how much I need to scale this up, note that <code>mbbVariance</code> and <code>nbbVariance</code> would have to run for each of the 5,000 rows as arguments (<code>x</code> being a row), and have to be iterated (<code>0</code> to <code>x.length - L + 1</code> for <code>mbbVariance</code>, and <code>0</code> to <code>x.length / L</code> for <code>nbbVariance</code>) proportionally to 5,000 times since <code>maxBlockSize = 5000</code> implies that values 1, 2, ..., 5000 will be passed as <code>L</code> to the <code>mbbVariance</code> and <code>nbbVariance</code> functions. </p> <p>While the code below does work, when I ran it for a single 5000 x 3000 data set with <code>maxBlockSize = 3000</code>, I ended up shutting it down after about 10 hours. The <code>nbbThread</code> finished in 18 minutes, judging by the outputted <code>NBB_test.txt</code>. Given how much of <code>MBB_test.txt</code> was populated, through linear interpolation, I estimated that <code>mbbThread</code> would take about 28 hours total (so 18 hours after I had shut the process down). This is too long, given that I have 20 files of this size to process.</p> <pre><code>import java.io.FileInputStream; import java.lang.Math; import java.util.Scanner; import java.io.IOException; import java.io.PrintWriter; import java.io.FileOutputStream; import java.util.Arrays; import java.util.stream.IntStream; import java.util.stream.DoubleStream; import java.util.concurrent.CyclicBarrier; import java.util.concurrent.BrokenBarrierException; import java.lang.InterruptedException; public class BlockBootstrapTestParallel { // Sum of a subarray, based on B(x, i, L) -- i is one-indexing public static double sum(double[] x, int i, int L) { return Arrays.stream(x).skip(i - 1).limit(L).sum(); } // Mean of a subarray, based on B(x, i, L) -- i is one-indexing public static double mean(double[] x, int i, int L) { return Arrays.stream(x).skip(i - 1).limit(L).average().orElse(0); } // Compute MBB mean public static double mbbMu(double[] x, int L) { return IntStream.range(0, x.length - L + 1) .mapToDouble(idx -&gt; mean(x, idx + 1, L)) .average() .orElse(0); } // Compute MBB variance public static double mbbVariance(double[] x, int L, double alpha) { double mu = mbbMu(x, L); double lAlph = Math.pow(L, alpha); return IntStream.range(0, x.length - L + 1) .parallel() .mapToDouble(idx -&gt; (lAlph * Math.pow(mean(x, idx + 1, L) - mu, 2))) .average() .orElse(0); } // Compute NBB mean public static double nbbMu(double[] x, int L) { return IntStream.range(0, x.length / L) .mapToDouble(idx -&gt; (mean(x, 1 + ((idx + 1) - 1) * L, L))) .average() .orElse(0); } // Compute NBB variance public static double nbbVariance(double[] x, int L, double alpha) { double mu = nbbMu(x, L); double varSum = IntStream.range(0, x.length / L) .parallel() .mapToDouble(idx -&gt; (Math.pow(mean(x, 1 + ((idx + 1) - 1) * L, L) - mu, 2))) .average() .orElse(0); return Math.pow((double) L, alpha) * varSum; } // factorial implementation public static double factorial(int x) { double[] fact = {1.0, 1.0, 2.0, 6.0, 24.0, 120.0, 720.0, 5040.0, 40320.0, 362880.0, 3628800.0}; return fact[x]; } // Hermite polynomial public static double H(double x, int p) { double out = IntStream.range(0, (p / 2) + 1) .parallel() .mapToDouble(idx -&gt; (Math.pow(-1, idx) * Math.pow(x, p - (2 * idx)) / ((factorial(idx) * factorial(p - (2 * idx))) * (1L &lt;&lt; idx)))) .sum(); out *= factorial(p); return out; } // Row means public static double[] rowMeans(double[][] x, int nrows, int ncols) { return IntStream.range(0, nrows) .parallel() .mapToDouble(idx -&gt; (mean(x[idx], 1, ncols))) .toArray(); } public static void duration(long start, long end) { System.out.println("Total execution time: " + (((double)(end - start))/60000) + " minutes"); } public static void main(String[] argv) throws InterruptedException, BrokenBarrierException, IOException { final long start = System.currentTimeMillis(); FileInputStream fileIn = new FileInputStream("test.txt"); FileOutputStream fileOutMBB = new FileOutputStream("MBB_test.txt"); FileOutputStream fileOutNBB = new FileOutputStream("NBB_test.txt"); FileOutputStream fileOutMean = new FileOutputStream("means_test.txt"); Scanner scnr = new Scanner(fileIn); PrintWriter outFSMBB = new PrintWriter(fileOutMBB); PrintWriter outFSNBB = new PrintWriter(fileOutNBB); PrintWriter outFSmean = new PrintWriter(fileOutMean); // These variables are taken from the command line, but are inputted here for ease of use. int rows = 10; int cols = 10; int maxBlockSize = 10; // this could potentially be any value &lt;= cols int p = 1; double alpha = 0.1; double[][] timeSeries = new double[rows][cols]; // read in the file, and perform the H_p(x) transformation for (int i = 0; i &lt; rows; i++) { for (int j = 0; j &lt; cols; j++) { timeSeries[i][j] = H(scnr.nextDouble(), p); } scnr.next(); // skip null terminator } // row means double[] sampleMeans = rowMeans(timeSeries, rows, cols); for (int i = 0; i &lt; rows; i++) { outFSmean.print(sampleMeans[i] + " "); } outFSmean.println(); outFSmean.close(); final CyclicBarrier gate = new CyclicBarrier(3); Thread mbbThread = new Thread(() -&gt; { try { gate.await(); for (int j = 0; j &lt; rows; j++) { for (int m = 0; m &lt; maxBlockSize; m++) { outFSMBB.print(mbbVariance(timeSeries[j], m + 1, alpha) + " "); } outFSMBB.println(); } outFSMBB.close(); } catch (InterruptedException e) { System.out.println("Main Thread interrupted!"); e.printStackTrace(); } catch (BrokenBarrierException e) { System.out.println("Main Thread interrupted!"); e.printStackTrace(); } }); Thread nbbThread = new Thread(() -&gt; { try { gate.await(); for (int j = 0; j &lt; rows; j++) { for (int m = 0; m &lt; maxBlockSize; m++) { outFSNBB.print(nbbVariance(timeSeries[j], m + 1, alpha) + " "); } outFSNBB.println(); } outFSNBB.close(); } catch (InterruptedException e) { System.out.println("Main Thread interrupted!"); e.printStackTrace(); } catch (BrokenBarrierException e) { System.out.println("Main Thread interrupted!"); e.printStackTrace(); } }); // start threads simultaneously mbbThread.start(); nbbThread.start(); gate.await(); // wait for threads to die mbbThread.join(); nbbThread.join(); duration(start, System.currentTimeMillis()); } } </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-01T11:44:25.447", "Id": "239736", "Score": "1", "Tags": [ "java", "statistics" ], "Title": "Block Bootstrap Estimation in Java - Part 3" }
239736
<p>I created a dynamic insert function for PDO.</p> <p>It does work, but I want to be sure that it is secure and well coded.</p> <pre><code>function insertNewRows($pdo, $table, $fields, $placeholders, $values=''){ if($values){ $result = $pdo-&gt;prepare("INSERT INTO $table ($fields) VALUES ($placeholders)"); $result-&gt;execute($values); }else{ $result = $pdo-&gt;query("INSERT INTO $table ($fields) VALUES ($placeholders)"); } } </code></pre> <p>Using positional placeholders:</p> <pre><code>$session_id = '1000000001'; $createdBy = 12; $fields = "session_id, username, createdBy"; $placeholders = "?, 'boss 21', ?"; $values = array($session_id, $createdBy); insertNewRows($pdo, 'web_statistics', $fields, $placeholders, $values); </code></pre> <p>Not using positional placeholders:</p> <pre><code>$fields = "session_id, username, createdBy"; $placeholders = "'abc', 'boss 25', 3"; insertNewRows($pdo, 'web_statistics', $fields, $placeholders); </code></pre> <p>I want to use the same tactic for <code>UPDATE</code> and <code>SELECT</code> functions, so am I good to do so with the code I have written?</p>
[]
[ { "body": "<p>I don't see any point in this function in its present form.</p>\n<p>Given you've got a <a href=\"https://phpdelusions.net/pdo/pdo_wrapper#function\" rel=\"noreferrer\">general purpose query function</a>,</p>\n<pre><code>function pdo($pdo, $sql, $args = NULL)\n{\n $stmt = $pdo-&gt;prepare($sql);\n $stmt-&gt;execute($args);\n return $stmt;\n}\n</code></pre>\n<p>it will be cleaner, easier to use and more readable to have a conventional SQL than such random rags of a code:</p>\n<pre><code>$session_id = '1000000001';\n$createdBy = 12;\n\n$sql = &quot;INSERT INTO web_statistics (session_id, username, createdBy) VALUES (?,?,?)&quot;;\npdo($pdo, $sql, [$session_id, 'boss 21', $createdBy]);\n</code></pre>\n<p>The same goes for SELECT and UPDATE. You can find a complete set of examples by the link above.</p>\n<h1>Update.</h1>\n<p>Looks like this question got some traction, due to some mysterious ways of Stack overflow. It means it will attract people other than the OP, who may have the same question but have different code, or just curious about Dynamic insert function for PDO in general. Well then, I must admit that the answer is rather a trick and too localized, being focused on the actual code in the OP. For the present code, where different query parts are still hardcoded in the different function parameters, it is indeed makes a lot more sense to have them hardcoded in the form of a conventional SQL query instead.</p>\n<p>But of course the common idea of a dynamic insert function for PDO is different. it's rather a function that is called like this:</p>\n<pre><code>prepared_insert($pdo, $table_name, $data);\n</code></pre>\n<p>where <code>$data</code> is an associative array like this</p>\n<pre><code>$data = [\n 'name' =&gt; $name, \n 'password' =&gt; $hashed_password,\n];\n</code></pre>\n<p>Well then for this case I've got a simple <a href=\"https://phpdelusions.net/pdo_examples/insert_helper\" rel=\"noreferrer\">INSERT helper function for PDO Mysql</a></p>\n<pre><code>function prepared_insert($pdo, $table, $data) {\n $keys = array_keys($data);\n $keys = array_map('escape_mysql_identifier', $keys);\n $fields = implode(&quot;,&quot;, $keys);\n $table = escape_mysql_identifier($table);\n $placeholders = str_repeat('?,', count($keys) - 1) . '?';\n $sql = &quot;INSERT INTO $table ($fields) VALUES ($placeholders)&quot;;\n $pdo-&gt;prepare($sql)-&gt;execute(array_values($data));\n}\n</code></pre>\n<p>Note that his function will need a helper function of its own,</p>\n<pre><code>function escape_mysql_identifier($field){\n return &quot;`&quot;.str_replace(&quot;`&quot;, &quot;``&quot;, $field).&quot;`&quot;;\n}\n</code></pre>\n<p>to protect identifiers added to the query.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-01T13:25:47.400", "Id": "239744", "ParentId": "239741", "Score": "6" } }, { "body": "<p>Rather than sending comma-delimited strings, why not simply pass an array with value/key pairs eg:</p>\n\n<pre><code>array(\n \"field_str\" =&gt; \"foo\",\n \"field_int\" =&gt; 100,\n \"field_float\" =&gt; 3.1415926535,\n);\n</code></pre>\n\n<p>So you can pass values in mixed data types. This is more flexible. Then loop on the array and build a parameterized query.</p>\n\n<p>But you still require validation of the field names and table names, it would be a good idea to enclose them in backticks or brackets.</p>\n\n<p>The problem with this approach is that a hacker who finds a flaw could insert arbitrary data in any table, for example the table of <strong>users</strong>. Also, if the table name is prefixed with a dot, it could be possible to insert records to a table in another database. PDO will not protect against injection here.</p>\n\n<p>To secure this function you need lots of validation and you are never sure you will cover all possibilities. That does not sound like a good idea overall.</p>\n\n<p>Like suggested by @Your Common Sense, it would better to have a reusable function but provide the SQL query yourself.</p>\n\n<p>You can still develop wrapper functions, for example a function to add/modify/delete a user. In this function you can put all the logic and table names to avoid repetition. It is actually a good idea to use some level of abstraction. There is the DRY rule (don't repeat yourself). Write functions for repeated stuff.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-01T13:51:10.747", "Id": "470315", "Score": "0", "body": "Hi, thanks for answer! Your suggestion about array seems to be unnecessary here as it puts extra work on validation. But i do agree about using functions for repeated stuff." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-01T14:02:45.113", "Id": "470316", "Score": "0", "body": "It is the table and field names that require validation to protect against injection attacks. The array not so much, because the values can be **parameterized**. The table and field names cannot. The array does not involve extra work but it cannot solve the problem completely." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-01T14:10:47.027", "Id": "470320", "Score": "0", "body": "As much as i know no one can overwrite my PHP array so how it can be attacked? Table and columns are usually not dynamic or passed from user side" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-01T14:13:43.430", "Id": "470322", "Score": "1", "body": "There are plenty of **SQL injection** techniques. Whenever you process input from a remote client there is a risk of injection using comments delimiters, nullbyte injection, etc. Malicious values can potentially contaminate (and rewrite) the whole query if the code is not solid and validation is weak. I suggest that you run [SQLmap](http://sqlmap.org/) against your application - you might be surprised at what this tool could find with just the default settings. It is always a good idea to [pentest](https://en.wikipedia.org/wiki/Penetration_test) yourself, before someone else does." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-02T05:11:25.027", "Id": "470372", "Score": "1", "body": "@Ingus the key word is \"usually\". This \"usually\" notion is the source of 90% of actual injections in the world. An application is never a static piece of code. It evolves. Other people join to the project, knowing **absolutely nothing** of your notions and intents. They see a function, consider it safe and use it. There is [a lot of people](https://stackoverflow.com/q/22534183/285587) thinking that certain form elements are \"not coming from the user side\". This is why the **entire function** must be safe, not some unspoken ideas on how it should be used." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-02T05:14:27.727", "Id": "470373", "Score": "1", "body": "From this standpoint I don't really get the kind of open-ended answers like this one.It basically suggests you can do something but really shouldn't because of danger. Or you must do some vague \"lots of validation\" but without a single hint on how it must be done. And \"enclose in backticks or brackets.\" is **not a validation at all**" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-02T13:32:21.203", "Id": "470406", "Score": "0", "body": "You are right. But I can see some kind of education value here: the more you analyze this approach and try to improve it, the more you realize it is flawed and should be avoided. The point is that the original code can be made cleaner but would remain insecure in its proposed implementation. The question was twofold: whether the code is secure and well coded and both points have been well addressed, many thanks to you." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-01T13:41:00.280", "Id": "239746", "ParentId": "239741", "Score": "2" } }, { "body": "<p>Use a query builder, like the Doctrine one, for instance:\n<a href=\"https://www.doctrine-project.org/projects/doctrine-dbal/en/2.10/reference/query-builder.html#sql-query-builder\" rel=\"nofollow noreferrer\">https://www.doctrine-project.org/projects/doctrine-dbal/en/2.10/reference/query-builder.html#sql-query-builder</a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-13T23:59:18.127", "Id": "240470", "ParentId": "239741", "Score": "1" } } ]
{ "AcceptedAnswerId": "239744", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-01T13:08:30.497", "Id": "239741", "Score": "5", "Tags": [ "php", "pdo" ], "Title": "Dynamic insert function for PDO (for any case)" }
239741
<p>I am assigned to a task of creating a function int logBase10Estimate(int n) that returns the log of a number base 10. The answer is integer part only.(w/o using the Math class)</p> <p>Is this okay?</p> <pre><code>static int logBase10Estimate(int n){ int count = 0; for(int x = 10; ;x*=10){ if(x &lt; n){ count+=1; System.out.println(x); } else if(x == n){ count+=1; break; } else{ break; } } return count; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-01T14:08:41.367", "Id": "470319", "Score": "0", "body": "If you wanted a more symmetrical error, you could start at `round(sqrt(10))`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-01T14:20:13.743", "Id": "470323", "Score": "0", "body": "Why not just `int count = 0; for(; n; n/=10) { ctr++; } return count;`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-01T14:20:36.080", "Id": "470324", "Score": "0", "body": "@greybeard Error seems to be no concern here. And `round(sqrt(10))=3` btw ;)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-01T14:22:11.003", "Id": "470325", "Score": "0", "body": "(@slepic `3` does not tell why/how it was chosen.)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-01T14:24:04.743", "Id": "470326", "Score": "0", "body": "@greybeard it's irrelevant anyway, `round` and `sqrt` are methods of `Math` class which is explicitly forbidden by OP." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-01T14:35:02.093", "Id": "470328", "Score": "0", "body": "Thanks for the quick response. I'll try your recommendations." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-01T14:41:25.540", "Id": "470330", "Score": "1", "body": "Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*." } ]
[ { "body": "<p>The printing should not be there :)</p>\n\n<p>You don't need another variable <code>x</code>. You can modify the local copy <code>n</code>, because you won't need its original value for the entire algorithm and because it is passed by value, you won't change the value for the caller.</p>\n\n<p>Also check for valid input.</p>\n\n<pre><code>static int logBase10Estimate(int n)\n{\n if (n &lt;= 0) {\n throw new IllegalArgumentException('Log of non-positive number is undefined');\n }\n int count = 0;\n for (; n&gt;=10; n/=10) {\n ++count;\n }\n return count;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-01T14:35:50.993", "Id": "470329", "Score": "0", "body": "Sorry i forgot to remove the print function...Can i ask of what's the difference of putting an increment before and after a variable in a loop?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-01T14:45:04.870", "Id": "470331", "Score": "0", "body": "@ZiegfredZorrilla [Postfix vs prefix](https://stackoverflow.com/q/484462/1014587)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-01T14:19:46.307", "Id": "239750", "ParentId": "239747", "Score": "2" } }, { "body": "<p>You have the possibility of an infinite loop.</p>\n\n<p>Consider: <code>logBase10Estimate(2147483647)</code>. Should be about 9. We need a value of <span class=\"math-container\">\\$10^i\\$</span> which is greater than 1000000000. So, what values does <code>x</code> take on?</p>\n\n<pre><code> 10\n 100\n 1000\n 10000\n 100000\n 1000000\n 10000000\n 100000000\n 1000000000\n 1410065408\n 1215752192\n -727379968\n 1316134912\n 276447232\n-1530494976\n 1874919424\n 1569325056\n-1486618624\n : : :\n</code></pre>\n\n<p>Any value of <code>num</code> greater than <code>1000000000</code> is going to give incorrect results. And some values, like <code>2147483647</code> will never give an answer, because no <code>int</code> value is greater than it, and <code>x</code> will never be odd, so it will never be equal to it either.</p>\n\n<p>Not only is <a href=\"https://codereview.stackexchange.com/a/239750/100620\">slepic's solution</a> cleaner, it is correct and it terminates for all values.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-01T22:25:18.600", "Id": "239771", "ParentId": "239747", "Score": "3" } } ]
{ "AcceptedAnswerId": "239750", "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-01T13:52:30.933", "Id": "239747", "Score": "1", "Tags": [ "java", "beginner", "algorithm", "homework", "mathematics" ], "Title": "integer log base 10 function without using java.lang.Math?" }
239747
<p>I am working on a Code Kata </p> <pre><code>// There is a queue for the self-checkout tills at the supermarket. // Your task is write a function to calculate the total time // required for all the customers to check out! // input // customers: an array of positive integers representing the queue. // Each integer represents a customer, and its value is the amount // of time they require to check out. // n: a positive integer, the number of checkout tills. </code></pre> <p>A common solution is</p> <pre><code>function queueTime(customers, n) { // create a new array to represent each till // start each till at 0 minutes const tills = new Array(n).fill(0); // loop through the customers for (let i = 0; i &lt; customers.length; i++) { // find till with least minutes const shortestTill = Math.min(...tills) // find index of shortest till const index = arr.indexOf(shortestTill) // increase shortest till mins with current customer arr[index] += customers[i]; } // return the longest till return Math.max(...tills); } </code></pre> <p>My first solution, although longer, seems to work however it times out when I run it in node with a large data set. I am sure there is probably some time complexity issue or infinite loop that I am creating but can not identify.</p> <p>Where in my code should I refactor to fix this issue? </p> <pre><code>function queueTime(customers, n) { // checking edge case if (customers.length === 0) return 0 // initial time let time = 0 // create a lookup to see if each till is open, where each //key is the till number and the val is the time needed for each to finish memo = {} for (let i = 1; i &lt;= n; i++) { memo[i] = customers.shift() } // not necessarily needed because I'm using returns in the while loop, // but the intention is to break the loop let completed = false // solving the problem was taking two different approaches so // this variable allows me to check which approach to use let moreTillsThanCustomers = false // len = memo.length let len = Object.keys(memo).length for (let i = 1; i &lt;= len; i++) { // if any didn't have a customer to fill the spot, then moreTillsThanCustomers = true if (memo[i] === undefined) { moreTillsThanCustomers = true } } if (!moreTillsThanCustomers) { while (!completed) { let found = false // if there are any open spots and customers left, we 'found' a spot to fill and can break out of the loop for (let i = 1; i &lt;= len; i++) { if (memo[i] === 'open') { if (customers.length) { memo[i] = customers.shift() found = true break } } } // if no spot was found, increase the time by one and reduce all // till times by 1 or to 'open if (!found) { time++ for (let i = 1; i &lt;= len; i++) { if (memo[i] === 1) { memo[i] = 'open' } else { memo[i]-- } } } // if every value is 'open' and there are no customers left, we're done if (Object.values(memo).every(value =&gt; value === 'open')&amp;&amp; !customers.length) { completed = true return time } } // if there are more tills than customers } else { while (!completed) { // if a memo is at 0, it's done, otherwise reduce it by one for (let i = 1; i &lt;= len; i++) { if (memo[i] === 0) { memo[i] = undefined } else if (memo[i] !== undefined) { memo[i]-- } } // if all are done, we're done if (Object.values(memo).every(value =&gt; value === undefined)) { completed = true return time } //increase time time++ } } return time } </code></pre> <p>Times out in node</p> <pre><code>console.log( queueTime([28, 9, 27, 37, 12, 33, 20, 31, 19, 18, 3, 8, 39, 40, 49], 5) ) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-13T20:20:04.070", "Id": "482004", "Score": "0", "body": "If you're intereseted: https://codereview.stackexchange.com/questions/245432/benchmarking-multiple-implementations-of-a-code-kata-queue-for-the-self-checkou" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-01T13:55:54.410", "Id": "239748", "Score": "1", "Tags": [ "javascript", "time-limit-exceeded", "complexity", "timeout" ], "Title": "Why is my function timing out when run with a larger data set?" }
239748
<p>I wrote a program where the <em>computer</em> guesses a random number.</p> <p>To do this, I implemented a form of binary search. This correctly handles any edge-cases that I know of, including <code>0</code> and <code>std::numeric_limits&lt;int&gt;::max()</code>. This doesn't handle negative numbers (since <code>rand</code> will never return one) but that could easily be fixed.</p> <p>The average amount of tries it takes to guess the number is around 29 or 30.</p> <p>Here it is:</p> <pre><code>#include &lt;functional&gt; #include &lt;iostream&gt; #include &lt;cstdlib&gt; #include &lt;limits&gt; #include &lt;ctime&gt; static int random_number; int compare(int guess) { if(guess &gt; random_number) return 1; if(guess &lt; random_number) return -1; return 0; } struct guess_stats { int guesses = 0; int number = 0; }; guess_stats finder(std::function&lt;int(int)&gt; &amp;&amp;cmp) { int max = std::numeric_limits&lt;int&gt;::max(); int min = 0; int guess = (min + max) / 2; int cmp_result; guess_stats results; do { cmp_result = cmp(guess); if(cmp_result &lt; 0) { std::cout &lt;&lt; "Greater than " &lt;&lt; guess; min = guess; const int diff = max - guess; guess += diff - (diff / 2); } else if(cmp_result &gt; 0) { std::cout &lt;&lt; "Less than " &lt;&lt; guess; max = guess; const int diff = guess - min; guess -= diff - (diff / 2); } std::cout &lt;&lt; '\n'; results.guesses++; } while(cmp_result); results.number = guess; return results; } int main(void) { std::srand(std::time(0)); random_number = std::rand(); guess_stats stats = finder(compare); std::cout &lt;&lt; "Number: " &lt;&lt; stats.number &lt;&lt; '\n' &lt;&lt; "Guesses: " &lt;&lt; stats.guesses &lt;&lt; '\n'; return 0; } </code></pre> <p>What I'm looking for:</p> <ul> <li>Although I don't expect there will be, are there any edge-cases I may not have seen?</li> <li>Are there any algorithmic changes that I could make to have less time-complexity? I don't think so (because this is only <code>O(log n)</code> as it is), but I may be surprised to find out.</li> <li>Are there any better ways to generate random numbers? I used <code>srand</code>, <code>time</code>, and <code>rand</code> in this program, but those are old solutions. I imagine C++ has something much more up-to-date for generation of random numbers.</li> <li>Any other general advice on what to improve would be appreciated.</li> </ul>
[]
[ { "body": "<h1>Non-const static variables</h1>\n\n<p>Your code shows a lot of good practices:</p>\n\n<ul>\n<li>variables are always initialized when possible</li>\n<li>variables have proper names (and you stuck to a single naming scheme)</li>\n<li>no unecessary <code>std::endl</code></li>\n</ul>\n\n<p>However, there is one drawback:</p>\n\n<pre class=\"lang-c prettyprint-override\"><code>static int random_number;\n</code></pre>\n\n<p>That line right there is, at least from my point of view, a flaw. <code>static</code> variables are a nice escape hatch in some circumstances, but here it's unnecessary. We can easily use another argument to <code>finder</code>, for example:</p>\n\n<pre class=\"lang-cpp prettyprint-override\"><code>guess_stats finder(comparison_function &amp;&amp; cmp, int random_number) {\n ...\n}\n</code></pre>\n\n<p>Or we could combine the comparison function with the number to be guessed in a struct, similar to <code>guess_stats</code>.</p>\n\n<p>Either variant makes sure that our changes in <code>finder</code> won't spill into the rest of our program flow. While we don't intend to change <code>random_number</code> in <code>finder</code>, it's easy to accidentally write <code>random_number++</code> or press <code>&lt;Tab&gt;</code> in an IDE with the wrong completion. If we were to use multiple <code>finder</code> variants in separate threads, we would have a hard time to debug the behaviour, especially if there is more than a single <code>static</code> variable.</p>\n\n<p>However, I guess you've used <code>random_number</code> as a static variable to ease the use of <code>compare</code>. There are other ways that we will inspect at the end of this review.</p>\n\n<p>Note that <code>const static</code> or <code>constexpr static</code> variables on the other hand are fine, as they cannot lead to debugging troubles (unless you <code>const_cast</code> them, but at that point we're deep within undefined behaviour territory).</p>\n\n<h1>Q&amp;A</h1>\n\n<blockquote>\n <p>Although I don't expect there will be, are there any edge-cases I may not have seen?</p>\n</blockquote>\n\n<p>What happens if I use the following comparison?</p>\n\n<pre class=\"lang-cpp prettyprint-override\"><code>int compare(int unused) {\n return 1;\n}\n</code></pre>\n\n<p>Sure, that's not a valid comparison, however, there is nothing in <code>finder</code> that blocks us from using such a function. Given that a binary search should take at most <span class=\"math-container\">\\$\\log_2(n)+1\\$</span> steps, we can introduce a simple limit of 33 iterations.</p>\n\n<blockquote>\n <p>Are there any algorithmic changes that I could make to have less time-complexity? I don't think so (because this is only O(log n) as it is), but I may be surprised to find out.</p>\n</blockquote>\n\n<p>That's all correct, and from an <span class=\"math-container\">\\$\\mathcal O\\$</span> analysis there's nothing to improve.</p>\n\n<blockquote>\n <p>Are there any better ways to generate random numbers? </p>\n</blockquote>\n\n<p>There's the <a href=\"https://en.cppreference.com/w/cpp/header/random\" rel=\"nofollow noreferrer\"><code>&lt;random&gt;</code></a> header. We can use the example code from <a href=\"https://en.cppreference.com/w/cpp/numeric/random/uniform_int_distribution\" rel=\"nofollow noreferrer\"><code>uniform_int_distribution</code></a> to generate a random number:</p>\n\n<pre class=\"lang-cpp prettyprint-override\"><code>int main(void)\n{\n std::random_device rd;\n std::mt19937 gen(rd());\n std::uniform_int_distribution&lt;int&gt; dist(0, std::numeric_limits&lt;int&gt;::max());\n\n const int random_number = dist(gen);\n\n ...\n}\n</code></pre>\n\n<p>However, keep in mind that this usually won't seed a <code>mt19937</code> correctly and <a href=\"https://codereview.stackexchange.com/questions/109260/seed-stdmt19937-from-stdrandom-device\">there are ways around that issue</a>.</p>\n\n<h1>Getting rid of <code>random_number</code></h1>\n\n<p>Given that we use <code>&lt;functional&gt;</code>, we use at least C++11. Therefore, we have lambdas at hand. We can use this to our advantage to get rid of <code>random_number</code> in <code>main</code>:</p>\n\n<pre class=\"lang-cpp prettyprint-override\"><code>int main(void)\n{\n std::random_device rd;\n std::mt19937 gen(rd());\n std::uniform_int_distribution&lt;int&gt; dist(0, std::numeric_limits&lt;int&gt;::max());\n\n const int random_number = dist(gen);\n\n auto compare = [random_number](int guess) {\n if (guess &gt; random_number) {\n return 1;\n } else if (guess &lt; random_number) {\n return -1;\n }\n return 0; \n };\n\n guess_stats stats = finder(compare);\n ...\n}\n</code></pre>\n\n<p>We don't even need to change <code>finder</code> to use the new comparison, thanks to <code>std::function&lt;int(int)&gt;&amp;&amp;</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-01T21:45:23.870", "Id": "470364", "Score": "0", "body": "Nice use of a lambda. Hadn't thought about that." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-01T21:38:00.353", "Id": "239767", "ParentId": "239749", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-01T14:06:21.843", "Id": "239749", "Score": "4", "Tags": [ "c++", "number-guessing-game" ], "Title": "Guess the number with a twist" }
239749
<p>I rewrote a compiler project right now containing semantics, parser and verifier, in Java. Links: <a href="https://github.com/shockscript/sxc" rel="nofollow noreferrer">source code</a>, <a href="https://github.com/shockscript/shockscript-developer-guide/blob/master/overview.md#overview" rel="nofollow noreferrer">language overview</a>. The language is familiar for ECMAScript.</p> <p>As an example, the verifier explicitly marks 'frame properties' (or locals) captured by inner functions and also marks 'bound methods' (indirectly-called instance methods):</p> <pre><code>public Symbol resolveLexicalProperty(ast.SimpleIDNode id, int flags, boolean reportError) { // ... if (p.isObjectPropertyAccess()) { if (p.accessingProperty().isFunction() &amp;&amp; (flags &amp; VerifyFlags.OBJECT_CALL) == 0) { p.accessingProperty().setIsBoundMethod(true); } if (p.baseObject().isThis()) { if (p.baseObject().activation() != currentActivation) { p.baseObject().activation().setScopeExtendedProperty(p.baseObject()); } } // code may capture property from an enclosing with frame, such as in: // // with (0x0a) // { // function f():void { trace(toString(16)) } // } // else if (p.baseObject().isFramePropertyAccess()) { var p2 = p.baseObject(); if (p2.baseFrame().activation() != this.currentActivation) { p2.baseFrame().activation().setScopeExtendedProperty(p2.accessingProperty()); } } } else if (p.isUnionPropertyAccess() &amp;&amp; p.accessingProperties().get(0).isFunction() &amp;&amp; (flags &amp; VerifyFlags.OBJECT_CALL) == 0) { for (var p2 : p.accessingProperties()) { p2.setIsBoundMethod(true); } } else if (p.isFramePropertyAccess()) { if (p.baseFrame().activation() != currentActivation) { p.baseFrame().activation().setScopeExtendedProperty(p.accessingProperty()); } } // ... } </code></pre> <p>This is part of the org.shockscript.sxc.verifier.Verifier class. The local <code>p</code> above is a <a href="https://github.com/shockscript/sxc/blob/master/src/main/java/org/shockscript/sxc/semantics/Symbol.java" rel="nofollow noreferrer"><code>org.shockscript.sxc.semantics.Symbol</code></a> object (this class defines various abstract methods).</p> <p>About the parser, the nodes are all defined in the static class <a href="https://github.com/shockscript/sxc/blob/master/src/main/java/org/shockscript/sxc/parser/ast.java" rel="nofollow noreferrer"><code>org.shockscript.sxc.parser.ast</code></a>. Some of the nodes contain Symbol references.</p> <p>Is this good for codegen?</p> <p>To build the project, Maven and JDK 14+ are required (openjdk-14-jdk), using the commands <code>mvn compile</code> and <code>. run.sh arguments</code> in the project root. To distribute JAR, <code>mvn package</code>.</p> <p>Also, when there is no bytecode to import, the compiler auto loads the language built-ins. There are various sources being loaded in the <code>builtins</code> directory of the compiler repo.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-01T15:10:11.937", "Id": "239752", "Score": "1", "Tags": [ "java", "compiler" ], "Title": "Verifier for multi-purpose scripting language" }
239752
<p>The gist of my program is to simulate the growth of some virus. I used (attempted) OOP concepts to break down the problem into chunks and have the chunks talk to each other.</p> <p>Not sure if my implementation is effective but it seems to work pretty good. Currently, the bottleneck seems to be in the plotting. I'm still learning about matplotlib so I'm not surprised.</p> <p>The program has five classes. The first class just keeps track of simulation details, nothing too fancy.</p> <pre><code>class Details(): def __init__(self,num_people_1d,fig_size): self.num_people_1d = num_people_1d self.total_people = self.num_people_1d**2 self.fig_size = fig_size self.x_length = self.fig_size[0]/num_people_1d self.y_length = self.fig_size[0]/num_people_1d </code></pre> <p>The second class is the display. At each iteration, the 2D grid is updated with details about individuals that are either infected or have perished. The display class is updated with the information</p> <pre><code>import matplotlib.pyplot as plt import matplotlib.patches as patches class Display(): def __init__(self,details_instance): self.size_x,self.size_y = details_instance.fig_size self.length_1d = details_instance.num_people_1d self.x_length = details_instance.x_length self.y_length = details_instance.y_length def create_plot(self,plot_size = (5,5)): self.fig = plt.figure(figsize = plot_size) self.ax = self.fig.subplots() canvas = patches.Rectangle((0,0),1,1,fill=True, edgecolor='none',facecolor='g') self.ax.add_patch(canvas) def update_plot(self,infected_table=None,kill_table = None): #Transposing tables infected_table = list(map(list, zip(*infected_table))) kill_table = list(map(list, zip(*kill_table))) for i,row in enumerate(infected_table): for j,col in enumerate(row): infected_person = col dead_person = kill_table[i][j] if dead_person: coord = i*self.x_length,j*self.y_length square = patches.Rectangle(coord, self.x_length,self.y_length, fill=True, edgecolor = 'none', facecolor = 'r') self.ax.add_patch(square) if infected_person and not dead_person: coord = i*self.x_length,j*self.y_length square = patches.Rectangle(coord, self.x_length,self.y_length, fill=True, edgecolor = 'none', facecolor = 'y') self.ax.add_patch(square) plt.show() plt.pause(0.1) </code></pre> <p>The next class is the virus class. Not too much going on, just the infect and mortality rate.</p> <pre><code>class Virus(): def __init__(self,infectionRate = 0.1,mortalityRate = 0.01): self.IR = infectionRate self.MR = mortalityRate </code></pre> <p>Then is the person class. This class just keeps some basic information. If the person is infected or dead, and some simple methods.</p> <pre><code>import random class Person(): def __init__(self,id = None,discrete_location = None,infected = False): self.id = id if discrete_location: self.dl_x,self.dl_y = discrete_location else: raise Exception() self.infected = infected self.neighbors = [] self.dead = False def become_infected(self,virus): if not self.dead: self.infected = True self.virus = virus def do_i_live(self): return random.random()&gt;self.virus.MR def kill(self): self.dead = True self.infected = False </code></pre> <p>The last class is the Population class. This class holds most of the code that actually does stuff because it is what updates all of the individuals.</p> <pre><code>from person import Person import random class Population(): def __init__(self,persons=[],details_instance =None,virus_strain=None): if len(persons)&lt;1: print('There is no population! Adding a member') self.persons = persons self.count = 0 self.add_person() else: self.persons = persons self.details_instance = details_instance self.virus_strain = virus_strain self.dead_persons = [[]] def add_person(self): if len(self.persons)&lt;1: self.persons.append(Person(id=self.count, discrete_location = (0,0), infected = False) ) self.count +=1 else: loc_x = self.details_instance.x_length*(self.count%self.details_instance.num_people_1d) loc_y = self.details_instance.y_length*((self.count - self.count%self.details_instance.num_people_1d)/self.details_instance.num_people_1d) person = Person(id = self.count, discrete_location = (loc_x,loc_y), infected = False) self.count +=1 self.persons.append(person) def get_infected_table(self): truth_table = [] current_list = [] i = 0 while i &lt; self.count: current_list.append(self.persons[i].infected) i+=1 if (i)%(self.details_instance.num_people_1d) ==0: truth_table.append(current_list) current_list = [] if self.count%(self.details_instance.num_people_1d) !=0: truth_table.append(current_list) return truth_table def get_dead_table(self): truth_table = [] current_list = [] i = 0 while i &lt; self.count: current_list.append(self.persons[i].dead) i+=1 if (i)%(self.details_instance.num_people_1d) ==0: truth_table.append(current_list) current_list = [] if self.count%(self.details_instance.num_people_1d) !=0: truth_table.append(current_list) return truth_table def kill_infected(self,infected_table): linear_indices = self.get_infected_indices(infected_table) for index in linear_indices: still_living = self.persons[index].do_i_live() if not still_living: self.persons[index].kill() self.dead_persons.append(index) def add_neighbors(self): #Currently returns the linear index! Compatible with persons!! if len(self.persons)&lt;=1: return #One method: #Use self.count and modulos to identify neighbors #Possibly a better method that I do not follow: #Using discrete location to identify neighbors #Using first method for i in range(self.count): #at left boundary if i%self.details_instance.num_people_1d==0: left = -1 else: left = i-1 #at right boundary if (i+1)%self.details_instance.num_people_1d==0: right = -1 else: right = i+1 up = i+self.details_instance.num_people_1d down = i - self.details_instance.num_people_1d #First build potential neighbors potential_neighbors = [left,right,up,down] #Second identify if any potential neighbors don't exist neighbor_list = [] for j in potential_neighbors: if (j &gt;= 0) and (j&lt;self.count): neighbor_list.append(j) #Third update the person with neighbors self.persons[i].neighbors = neighbor_list def spread_infection(self,infected_table): linear_indices = self.get_infected_indices(infected_table) for index in linear_indices: current_infected_person = self.persons[index] neighbors = current_infected_person.neighbors for neighbor in neighbors: if random.random()&lt;current_infected_person.virus.IR: self.persons[neighbor].become_infected(self.virus_strain) def get_infected_count(self): infected_people = 0 for person in self.persons: if person.infected: infected_people+=1 return infected_people def get_dead_count(self): dead_people = 0 for person in self.persons: if person.dead: dead_people+=1 return dead_people def get_infected_indices(self,infected_table): #returns the linear indices of those infected linear_indices=[] for i,row in enumerate(infected_table): for j,col in enumerate(row): if col: linear_indices.append(j+i*self.details_instance.num_people_1d) return linear_indices </code></pre> <p>To run all of this code I wrote the following script:</p> <pre><code>from person import Person from virus import Virus from display import Display from details import Details from population import Population import random num_people_1d = 10 simul_details = Details(num_people_1d = num_people_1d,fig_size = (1,1)) virus_strain1 = Virus() pop = Population(details_instance = simul_details,virus_strain=virus_strain1) number_people = num_people_1d**2-1 for i in range(number_people): pop.add_person() pop.add_neighbors() starting_person = random.randint(0,number_people-1) print('The starting person is %d' % starting_person) pop.persons[starting_person].become_infected(virus_strain1) current_infected = pop.get_infected_table() current_dead = pop.get_dead_table() simul_display = Display(details_instance=simul_details) simul_display.create_plot() total = 100 for iter in range(total): infected_people = pop.get_infected_count() dead_people = pop.get_dead_count() print('The iteration we are on is %d with %d infected' %(iter,infected_people)) simul_display.update_plot(current_infected,current_dead) pop.spread_infection(current_infected) current_infected=pop.get_infected_table() pop.kill_infected(current_infected) current_dead = pop.get_dead_table() if infected_people+dead_people &gt; number_people: print('All individuals are infected or dead!') break </code></pre> <p>This is all of the code. Any comments would be gratefully appreciated.</p>
[]
[ { "body": "<h1>Files</h1>\n\n<p>Python is not Java, not every class needs it's own module. You can keep <code>Details</code>, <code>Virus</code> and <code>Person</code> in 1 file, <code>Display</code> can go in its own file, since that serves another purpose</p>\n\n<h1>Programming tools</h1>\n\n<p>You can let the IDE help you a lot by using a few tools. I myself use <code>black</code> as code formatter, <code>isort</code> to sort the imports, <code>pylama</code> with the linters <code>mccabe</code>,<code>pep8</code>,<code>pycodestyle</code>,<code>pyflakes</code> to check the code quality, <code>mypy</code> for the static type analysis and <code>py.test</code> for unit tests. All these tools nicely integrate in most common python IDEs</p>\n\n<p>This is my <code>setup.cfg</code></p>\n\n<pre><code>[pylama]\nlinters = mccabe,pep8,pycodestyle,pyflakes,mypy,isort\n\n[pylama:*/__init__.py]\nignore=W0611\n\n[pylama:pydocstyle]\nconvention = google\n\n[pylama:mccabe]\nmax-complexity = 2\n\n[pydocstyle]\nconvention = google\n\n[isort]\nmulti_line_output=3\ninclude_trailing_comma=True\nforce_grid_wrap=0\nuse_parentheses=True\nline_length=79\n\n[mypy]\ncheck_untyped_defs = true\ndisallow_any_generics = true\ndisallow_untyped_defs = true\nignore_missing_imports = true\nno_implicit_optional = true\nwarn_redundant_casts = true\nwarn_return_any = true\nwarn_unused_ignores = true\n\n[mypy-tests.*]\ndisallow_untyped_defs = false\ncheck_untyped_defs = false\n\n[tool:pytest]\njunit_family = xunit2\ntestpaths = tests\n</code></pre>\n\n<p>My project directory looks like this</p>\n\n<pre><code>project_name/\n- data/\n - raw/\n - processed/\n- docs/\n - build/\n - source/\n- notebooks/\n - 20200402 analysis interference.ipynb\n - ...\n- output/\n - analysis1/\n - ...\n- src/\n - package_name/\n - sub_module/\n - __init__.py\n - module1.py\n - module2.py\n - __init__.py\n - module1.py\n - module2.py\n - ...\n- tests/\n - data/\n - conftest.py\n - test_feature1.py\n - ...\n-.gitignore\n- requirements_dev.txt\n- requirements.txt\n- setup.cfg\n- setup.py\n</code></pre>\n\n<h1>Documentation</h1>\n\n<p>Some docstring (PEP-257) would help users of your package to know what's going on. That includes you if you revisit this project a few months later.</p>\n\n<h1>Type analysis</h1>\n\n<p>I use type annotations for 2 reasons. It serves as additional documentation, and helps the IDE spot bugs for you, especially combined with a strict <code>mypy</code> configuration.</p>\n\n<h1>Argument defaults</h1>\n\n<p>You allow creating a person with a empty <code>id</code>, but do it nowhere. Why allow this feature? Then you would also not need to do this:</p>\n\n<pre><code> if discrete_location:\n self.dl_x,self.dl_y = discrete_location\n else:\n raise Exception()\n</code></pre>\n\n<p>That can be prevented as well by removing the default argument for <code>discrete_location</code>, and either removing the default for <code>id</code> as well or moving <code>id</code> to the back, or instructing python to get all arguments as keyword arguments.</p>\n\n<h1>builtin sum</h1>\n\n<p>You can use <code>sum</code> and the fact that a boolean counts as 1:</p>\n\n<pre><code>def get_infected_count(self):\n infected_people = 0\n for person in self.persons:\n if person.infected:\n infected_people+=1\n return infected_people\n</code></pre>\n\n<p>can become</p>\n\n<pre><code>def get_infected_count(self):\n return sum(person.infected for person in self.persons)\n</code></pre>\n\n<h1>generators</h1>\n\n<pre><code>def get_infected_indices(self,infected_table):\n #returns the linear indices of those infected\n linear_indices=[]\n for i,row in enumerate(infected_table):\n for j,col in enumerate(row):\n if col:\n linear_indices.append(j+i*self.details_instance.num_people_1d)\n return linear_indices\n</code></pre>\n\n<p>can become a lot clearer as a generator</p>\n\n<pre><code>def get_infected_indices(self,infected_table):\n \"\"\"The linear indices of those infected.\"\"\"\n for i, row in enumerate(infected_table):\n for j, col in enumerate(row):\n if col:\n yield j+i*self.details_instance.num_people_1d\n</code></pre>\n\n<h1>more functional programming</h1>\n\n<p>Each iteration you follow these steps:</p>\n\n<pre><code>for iter in range(total):\n infected_people = pop.get_infected_count()\n dead_people = pop.get_dead_count()\n print('The iteration we are on is %d with %d infected' %(iter,infected_people))\n simul_display.update_plot(current_infected,current_dead)\n\n\n pop.spread_infection(current_infected)\n current_infected=pop.get_infected_table()\n pop.kill_infected(current_infected)\n current_dead = pop.get_dead_table()\n</code></pre>\n\n<p>You are mutating you population in-place, and to do so, you need to follow a complicated series of steps. A simpler option would be to have a <code>Population.advance</code> method that returns a new <code>Population</code> instance representing the state of the population. That way you can keep track of what happened, who died, ...</p>\n\n<h1><code>dataclasses</code></h1>\n\n<p>These kind of classes lend themselves very good to be implemented using <code>dataclasses</code></p>\n\n<h2><code>Person</code></h2>\n\n<pre><code>@dataclasses.dataclass(frozen=True)\nclass Person:\n \"\"\"A Person.\"\"\"\n\n alive: bool = True\n virus: typing.Optional[Virus] = None\n\n @property\n def can_spread(self) -&gt; bool:\n \"\"\"A person can spread the virus when he's alive and infected.\"\"\"\n return self.alive and self.virus is not None\n\n def infect(self, virus: Virus) -&gt; Person:\n \"\"\"Returns a new, infected Person.\"\"\"\n return dataclasses.replace(self, virus=virus)\n\n def die(self) -&gt; Person:\n \"\"\"Returns a new, dead Person.\"\"\"\n return dataclasses.replace(self, alive=False)\n</code></pre>\n\n<p>Using an <code>@property</code> to check whether someone can spread the disease, and returning a new person when dying or getting infected instead of changing in-place.</p>\n\n<p>In a later stage, allowing persons with multiple infections can be as simple as changing the <code>virus</code> to a <code>set[Virus]</code> and a small tweak to the <code>infect</code> method</p>\n\n<h2>Virus</h2>\n\n<pre><code>@dataclasses.dataclass(frozen=True)\nclass Virus:\n \"\"\"A Virus.\"\"\"\n\n infection_rate: float\n mortality_rate: float\n\n def spread(self, subject: Person) -&gt; Person:\n \"\"\"Possibly infects the subject.\n\n In this simple algorithm, it just picks a random number\n in the range [0.0, 1.0)]\n\n i this number is lower than the `virus`'s infection rate,\n the person gets inected\n \"\"\"\n dice_roll = random.random()\n if dice_roll &lt; self.infection_rate:\n return subject.infect(self)\n return subject\n\n def advance_infection(self, subject: Person) -&gt; Person:\n \"\"\"Advance the virus infection in the subject.\n\n If not infected, does nothing.\n I infected, checks whether the subject dies.\n\n In this simple algorithm, it just picks a random number\n in the range [0.0, 1.0)]\n\n i this number is lower than the `virus`'s mortality rate,\n the person dies\n \"\"\"\n dice_roll = random.random()\n if dice_roll &lt; self.mortality_rate:\n return subject.die()\n return subject\n</code></pre>\n\n<p>This is rather self-explanatory. Doing it like this lets you easily implement more sophisticated viruses with incubation_periods, ...</p>\n\n<h2>Population</h2>\n\n<pre><code>People = typing.List[typing.List[\"Person\"]] # for typing purposes\n\n\n@dataclasses.dataclass(frozen=True)\nclass Population:\n \"\"\"A Population.\"\"\"\n\n people: People\n virus: Virus\n\n @property\n def infected_count(self) -&gt; int:\n \"\"\"Returns the number of alive people who have been infected.\"\"\"\n return sum(person.can_spread for person in self)\n\n @property\n def dead_count(self) -&gt; int:\n \"\"\"Returns the number of dead people.\"\"\"\n return sum(not person.alive for person in self)\n\n def __iter__(self) -&gt; typing.Iterator[Person]:\n \"\"\"Yield all the people in the population.\"\"\"\n return itertools.chain.from_iterable(self.people)\n\n @property\n def grid_size(self) -&gt; typing.Tuple[int, int]:\n \"\"\"The gridsize of the population.\"\"\"\n return len(self.people), len(self.people[0])\n</code></pre>\n\n<p>Defines a simple population. Instead of keeping one list of all the people in the population, we use a grid. This makes searching for the neighbours a lot simpler later on. Doing it like this also allows us to calculate the number of dead and infected on the fly, instead of having to keep track of that separately.</p>\n\n<p>As a convenience, we supply a method to generate a pristine population:</p>\n\n<pre><code> @classmethod\n def new(cls, gridsize: int, virus: Virus) -&gt; Population:\n \"\"\"Generates a new Population of healthy people.\"\"\"\n return cls(\n people=[\n [Person() for _ in range(gridsize)] for _ in range(gridsize)\n ],\n virus=virus,\n )\n</code></pre>\n\n<p>To infect our initial person, we add an <code>infect_person</code> method:</p>\n\n<pre><code> def infect_person(self, x: int, y: int) -&gt; Population:\n \"\"\"Infects the person a location x, y.\n\n Returns a new Population.\n \"\"\"\n people_copy: People = [row[:] for row in self.people]\n people_copy[x][y] = people_copy[x][y].infect(self.virus)\n return Population(people=people_copy, virus=self.virus)\n</code></pre>\n\n<h1>spread the virus</h1>\n\n<p>To spread the virus, I would use a helper method that operates on a grid of people. We iterate over the grid, looking for people who are alive and have the virus. Then looking in the cells around that person looking for people who can be infected.</p>\n\n<pre><code>def _spread(people: People) -&gt; People:\n \"\"\"Spread the disease in a population.\n\n returns a new people\n \"\"\"\n rows = len(people)\n columns = len(people[0])\n people_copy: People = [row[:] for row in people]\n\n person: Person\n for i, row in enumerate(people):\n for j, person in enumerate(row):\n if not person.alive:\n continue\n if person.virus is None:\n continue\n for di, dj in [\n (-1, 0),\n (1, 0),\n (0, -1),\n (0, 1),\n ]:\n # iterate over the neighbours\n x, y = i + di, j + dj\n if (not 0 &lt;= x &lt; rows) or not (0 &lt;= y &lt; columns):\n # out of bounds\n continue\n\n neighbour = people[x][y]\n if not neighbour.alive or neighbour.virus is person.virus:\n # dead or already infected\n continue\n\n people_copy[x][y] = person.virus.spread(neighbour)\n return people_copy\n</code></pre>\n\n<p>I use the technique of the negative check a few time.</p>\n\n<p>Instead of </p>\n\n<pre><code>if person.alive:\n # spread the virus\n</code></pre>\n\n<p>I do:</p>\n\n<pre><code>if not person.alive:\n continue\n# spread the virus\n</code></pre>\n\n<p>This saves on a few levels of indentation, and makes the code easier to read.</p>\n\n<h1>kill</h1>\n\n<p>the <code>_kill</code> helper method works much in the same way:</p>\n\n<pre><code>def _kill(people: People) -&gt; People:\n \"\"\"Kills a portion of the infected.\n\n returns a new people\n \"\"\"\n people_copy: People = [row[:] for row in people]\n person: Person\n for i, row in enumerate(people):\n for j, person in enumerate(row):\n if not person.alive:\n continue\n if person.virus is None:\n continue\n virus = person.virus\n people_copy[i][j] = virus.advance_infection(people_copy[i][j])\n return people_copy\n</code></pre>\n\n<p>If you want to give the people who have been infected just that tick a tick of repriece,you need to do something like this:</p>\n\n<pre><code>def _kill(original_people: People, people_post_spread: People) -&gt; People:\n \"\"\"Kills a portion of the infected of the previous tick.\n\n returns a new people\n \"\"\"\n people_copy: People = [row[:] for row in people_post_spread]\n person: Person\n for i, row in enumerate(original_people):\n for j, person in enumerate(row):\n if not person.alive:\n continue\n if person.virus is None:\n continue\n virus = person.virus\n people_copy[i][j] = virus.advance_infection(people_copy[i][j])\n return people_copy\n</code></pre>\n\n<h1><code>Population.advance</code></h1>\n\n<p>And now to the method why we did all this work has become very simple:</p>\n\n<pre><code>def advance(self) -&gt; Population:\n \"\"\"Advances the population 1 tick.\n\n 1. Spread the virus\n 2. Kill some of the infected\n\n This returns a new Population\n \"\"\"\n people_post_spread = _spread(self.people)\n people_post_deaths = _kill(\n original_people=self.people, people_post_spread=people_post_spread\n )\n\n return Population(people=people_post_deaths, virus=self.virus)\n</code></pre>\n\n<h1>using the simulation:</h1>\n\n<p>This simulation can be used very easily:</p>\n\n<pre><code>if __name__ == \"__main__\":\n virus = Virus(infection_rate=.1, mortality_rate=.1)\n population = Population.new(gridsize=10, virus=virus).infect_person(4, 4)\n\n # print(population.dead_count, population.infected_count)\n assert population.dead_count == 0\n assert population.infected_count == 1\n\n populations: typing.List[Population] = [population]\n for i in range(1, 30):\n population = population.advance()\n populations.append(population)\n\n print(\n f\"after {i} iterations: {population.infected_count} infected and \"\n f\"{population.dead_count} dead\"\n )\n</code></pre>\n\n<p>And now you can use those <code>populations</code> to do analyses later, plotting, ...</p>\n\n<h2>plotting</h2>\n\n<p>Now you have the population as a grid, you can convert this grid to a numpy array</p>\n\n<pre><code>def matrix(self) -&gt; np.array:\n \"\"\"Creates a numpy array of the grid.\n\n A kind of bitmap\n 0 = fine\n 1 = infected, alive\n 2 = not infected, dead\n 3 = infected, dead\n \"\"\"\n return np.array(\n [\n [\n (person.virus is not None) + 2 * (not person.alive)\n for person in row\n ]\n for row in self.people\n ],\n dtype=\"int8\",\n )\n</code></pre>\n\n<p>Then the plotting is as simple as </p>\n\n<pre><code>fig, ax = plt.subplots()\nim = ax.imshow(population.matrix())\nplt.show()\n</code></pre>\n\n<p>You can choose the colormap...</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-02T18:31:36.200", "Id": "470432", "Score": "0", "body": "This is exactly what I was looking for. Thank you! If you have the time, I do have some follow up questions.\n\nFirst, why use dataclasses over standard classes? Is it because the amount of detail in the class is minimal and the classes primarily store information (such as alive, dead, infected, etc.)?\nSecond, I'm not sure I follow why the @property decorator is utilized. \n\nThird, why do you recommend creating new population instances, and creating new Persons, instead of an update-in place strategy?\n\nFourth, do you thoughts about following an update-in place structure?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-03T07:07:17.870", "Id": "470497", "Score": "2", "body": "1: `dataclasses` are just more convenient so you can skip some of the boiler plate. The `frozen=True` is a nice side effect if you want immutability; 2:the @property decorator is just a convenience as well.That way they act as variables. 3: the immutability allows you to prevent unwanted side effects. If you want in-place you need to make sure that what you do in 1 place doesn't affect another place. The only downside is a little bit more memory use, but even that is limited. I that really bothers you, you can use [`__slots__`](https://stackoverflow.com/a/28059785/1562285)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-03T07:07:52.497", "Id": "470498", "Score": "0", "body": "I added the code for plotting and fixed a bug in the `_spread`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-03T07:33:17.697", "Id": "470501", "Score": "0", "body": "This is a very nice & complete answer!" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-02T16:27:09.363", "Id": "239810", "ParentId": "239754", "Score": "4" } } ]
{ "AcceptedAnswerId": "239810", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-01T15:42:10.070", "Id": "239754", "Score": "5", "Tags": [ "python", "beginner", "simulation" ], "Title": "Simulation of virus growth" }
239754
<p>I'm trying to develop a web application for documentation.. </p> <p>The tool is functional.. Please review the code &amp; help me with performance tuning &amp; simplifying the JavaScript part..</p> <p>Any suggestions or comment most welcome. Thanks in advance!</p> <p><strong>Note:</strong> Please type something on the <code>&lt;textarea&gt;</code> to see the live preview</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>$(function() { hljs.initHighlightingOnLoad(); $('#doc_content').on('input', function() { var doc = this.value .replace(/&lt;/g, "&amp;lt;") .replace(/&gt;/g, "&amp;gt;") .replace(/__hj/g, '&lt;pre&gt;&lt;code&gt;') .replace(/hj__/g, '&lt;br/&gt;&lt;/code&gt;&lt;/pre&gt;') .replace(/__tl\s?/g, '&lt;h3&gt;') .replace(/\s?tl__/g, '&lt;/h3&gt;') .replace(/__st\s?/g, '&lt;h4&gt;') .replace(/\s?st__/g, '&lt;/h4&gt;') .replace(/__(o|u)l[^]*?(o|u)l__/g, m =&gt; m.replace(/(?:\r\n|\r|\n)/g, "&lt;/li&gt;&lt;li&gt;")) .replace(/__ol\s?/g, '&lt;ol&gt;&lt;li&gt;') .replace(/\s?ol__/g, '&lt;/li&gt;&lt;/ol&gt;') .replace(/__ul\s?/g, '&lt;ul&gt;&lt;li&gt;') .replace(/\s?ul__/g, '&lt;/li&gt;&lt;/ul&gt;'); $('#doc_preview').html(doc); hljs.initHighlighting.called = false; hljs.initHighlighting(); }) });</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>#doc_content { white-space: pre-wrap; resize: vertical; width: 99%; min-height: 100px; margin: 0px auto; font-family: 'Neuton', serif; } #doc_preview { margin-top: 30px; font-family: 'Neuton', serif; color: #242729; white-space: pre-wrap; font-size: 20px; line-height: 1.35; } #doc_preview .hljs { padding-left: 20px; } #doc_preview * { margin: 0px; padding: 0px; } #doc_preview h3 { margin-top: 8px; margin-bottom: -20px; font-family: 'Neuton', serif; } #doc_preview h4 { margin-bottom: -24px; font-family: 'Neuton', serif; } #doc_preview ul, #doc_preview ol { margin-top: 8px; } #doc_preview li { margin-left: 30px; margin-bottom: 8px; } #doc_preview li:last { margin-bottom: 0px; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;link href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.18.1/styles/atom-one-dark.min.css" rel="stylesheet" /&gt; &lt;link href="https://fonts.googleapis.com/css2?family=Neuton:wght@400&amp;display=swap" rel="stylesheet"&gt; &lt;script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.18.1/highlight.min.js"&gt;&lt;/script&gt; &lt;script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"&gt;&lt;/script&gt; &lt;div&gt; &lt;textarea id="doc_content"&gt; __tl Some good title ! tl__ You can see a live preview as you type... __hj $(function(){ hljs.initHighlightingOnLoad(); $('#doc_content').keyup(function(){ var doc = this.value .replace(/&lt;/g, "&amp;lt;") .replace(/&gt;/g, "&amp;gt;"); $('#doc_preview').html(doc); hljs.initHighlighting.called = false; hljs.initHighlighting(); }) }); hj__ __tl This is a sub title tl__ It's a great site to get answers for your programming queries !! Here is a Ordered list: __ol Login or Signup Post your query Check the answers. If you need any clarification, post a comment Accept answer ol__ Here is an Unordered list: __ul This is list item 1 This is item 2 ul__ A long passage will loook like below: Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. &lt;/textarea&gt; &lt;div id="doc_preview"&gt;&lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-01T18:14:29.610", "Id": "470352", "Score": "3", "body": "@Pugazh Some more details in the question body would be also helpful." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-01T23:37:42.480", "Id": "470366", "Score": "2", "body": "Yes from [The Help center page _How do I ask a good question?_](https://codereview.stackexchange.com/help/how-to-ask): \"_You will get more insightful reviews if you not only provide your code, but also give an explanation of what it does. The more detail, the better._\"" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-06T19:40:24.053", "Id": "470847", "Score": "0", "body": "\"a web application for documentation\" This tells us very little. What's the goal of you program?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-06T19:42:39.587", "Id": "470849", "Score": "1", "body": "For anyone voting to close this question: run the code snippet. Start typing. The code is an editor. While it could certainly use more explanation than that, it's perfectly reviewable as-is." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-01T17:24:49.700", "Id": "239759", "Score": "1", "Tags": [ "javascript", "performance" ], "Title": "Online documentation tool with JavaScript" }
239759
<p>I wanted to try and learn multi-threading, so I thought it would be good to make a small program normally first and make it multi-threaded, so I made this prime finder.</p> <pre class="lang-py prettyprint-override"><code>from time import sleep def prime_finder(num: int) -&gt; bool: """Checks to see if a number is prime""" if num == 2: return True divider = 2 while True: if (num % divider) == 0: return False elif (divider + 1) &gt;= ( num / divider): # I don't know how to explain this, but it prevents checking multiples twice return True divider += 1 num = 1 pause = 0 # A delay that makes each prime number more readable print(f"The prime numbers starting from {num} are:") while True: if prime_finder(num): print(num, end=", ") sleep(pause) num += 1 </code></pre> <p>Before I added the multi-threading I wanted to make sure that there was nothing fundamentally wrong with it. As well I wanted it to be pretty quick from the start, and so any optimization (other than multi-threading obviously) would be appreciated. I also wanted it to be easy to build on, and so if there are any ways to make it easier to add stuff, specifically multi-threading, please let me know.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-01T19:57:28.843", "Id": "470359", "Score": "1", "body": "I'm not sure what you're looking for here, since you mention speed but you have included a pause. You would get really good speed improvements from making a [sieve][1], but I'm sure there are even smarter algorithms. You don't really need to look at all numbers up to `num`, you can just look at the smaller primes. You also appear to be building up a new list of lower primes for every number investigated, which is quite the overhead compared to just keeping track of the previous ones.\n\n\n [1]: https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-01T20:00:31.553", "Id": "470360", "Score": "0", "body": "@ades The pause is just there to make it so once a prime number is found, it can pause so the user can see that it has found a prime number. I want the code that finds the primes itself to be fast, with easy addition of multi-threading in mind." } ]
[ { "body": "<p>So, I am assuming that you are aware that a more efficient algorithm for finding prime numbers can be written, so we'll ignore this aspect.</p>\n\n<h3>Comments to the <code>prime_finder</code> method</h3>\n\n<ul>\n<li><p>If we pass <code>num=1</code> to the method, will it return what you expect? Do you consider 1 a prime number?</p></li>\n<li><p>But even more important, the name of the method is misleading. The method does not really <strong>find prime numbers</strong> as the name suggests, it <strong>checks if a number is prime</strong>. It is very important to name methods properly, especially when other people have to read your code. If the name is bad, and a developer cannot understand what the method is doing, they might spend a lot of extra time reading the code. Even worse, if the method doesn't do what the name says it does, it might not be used properly and nasty bugs could be made.</p></li>\n</ul>\n\n<p>If you rename the method, you don't even need a comment explaining what it is doing:</p>\n\n<pre><code>def is_prime(num: int) -&gt; bool:\n</code></pre>\n\n<p>You will then also see that the statement below will make more sense:</p>\n\n<pre><code>while True:\n if is_prime(num):\n ...\n</code></pre>\n\n<h3>Comments to the rest of the code</h3>\n\n<p>In the code that goes after, you mix the logic of finding the next prime number and printing numbers. What if you want to reuse your code that finds prime numbers somewhere else but don't need to print them?</p>\n\n<p>I would create a separate method that returns the next prime number using the concept of <a href=\"https://wiki.python.org/moin/Generators\" rel=\"nofollow noreferrer\">generator</a>:</p>\n\n<pre><code>def next_prime_number() -&gt; int:\n num = 1\n while True:\n if is_prime(num):\n yield num\n num += 1\n</code></pre>\n\n<p>Then, if you need, you can print them:</p>\n\n<pre><code>for prime_number in next_prime_number():\n print(prime_number)\n</code></pre>\n\n<p>You can also add waiting, obviously.</p>\n\n<p>Now, if you want to add multithreading, you will have to modify the <code>next_prime_number</code> method, and you won't have problems with printing in multiple threads.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-01T22:47:52.107", "Id": "239772", "ParentId": "239761", "Score": "2" } } ]
{ "AcceptedAnswerId": "239772", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-01T19:44:38.347", "Id": "239761", "Score": "1", "Tags": [ "python", "performance", "python-3.x", "primes" ], "Title": "Python prime finder" }
239761
<p>I use zypper to download and install for openSUSE Tumbleweed (much like everyone else of course). Unfortunately it downloads packages serially, and having about a thousand packages to update a week, it gets quite boring. Also, while zypper can download packages one-by-one in advance, it can't be called concurrently. I found the <a href="https://github.com/openSUSE/libzypp-bindings/" rel="nofollow noreferrer">libzypp-bindings</a> project but it is discontinued. I set myself to improve the situation.</p> <p><strong>Goals:</strong></p> <ul> <li>Download all repositories in parallel (most often different servers);</li> <li>Download up to MAX_PROC (=6) packages from each repository in parallel;</li> <li>Save packages where zypper picks them up during system update: <code>/var/cache/zypp/packages</code>;</li> <li>Alternatively, download to <code>$HOME/.cache/zypp/packages</code>;</li> <li>Avoid external dependencies, unless necessary.</li> </ul> <p><strong>Outline:</strong></p> <ol> <li>Find the list of packages to update;</li> <li>Find the list of repositories;</li> <li>For each repository: <ol> <li>Keep up to $MAX_PROC curl processes downloading packages.</li> </ol></li> <li>Copy files to default package cache;</li> </ol> <pre><code>#!/bin/bash MAX_PROC=6 function repos_to_update () { zypper list-updates | grep '^v ' | awk -F '|' '{ print $2 }' | sort --unique | tr -d ' ' } function packages_from_repo () { local repo=$1 zypper list-updates | grep " | $repo " | awk -F '|' '{ print $6, "#", $3, "-", $5, ".", $6, ".rpm" }' | tr -d ' ' } function repo_uri () { local repo=$1 zypper repos --uri | grep " | $repo " | awk -F '|' '{ print $7 }' | tr -d ' ' } function repo_alias () { local repo=$1 zypper repos | grep " | $repo " | awk -F '|' '{ print $2 }' | tr -d ' ' } function download_package () { local alias=$1 local uri=$2 local line=$3 IFS=# read arch package_name &lt;&lt;&lt; "$line" local package_uri="$uri/$arch/$package_name" local local_dir="$HOME/.cache/zypp/packages/$alias/$arch" local local_path="$local_dir/$package_name" printf -v y %-30s "$repo" printf "Repository: $y Package: $package_name\n" if [ ! -f "$local_path" ]; then mkdir -p $local_dir curl --silent --fail -L -o $local_path $package_uri fi } function download_repo () { local repo=$1 local uri=$(repo_uri $repo) local alias=$(repo_alias $repo) local pkgs=$(packages_from_repo $repo) local max_proc=$MAX_PROC while IFS= read -r line; do if [ $max_proc -eq 0 ]; then wait -n ((max_proc++)) fi download_package "$alias" "$uri" "$line" &amp; ((max_proc--)) done &lt;&lt;&lt; "$pkgs" wait } function download_all () { local repos=$(repos_to_update) while IFS= read -r line; do download_repo $line &amp; done &lt;&lt;&lt; "$repos" wait } download_all sudo cp -r ~/.cache/zypp/packages/* /var/cache/zypp/packages/ </code></pre> <p>There's 2 or 3 places where <code>grep</code>/<code>tr</code> are subject to issues, but the nature of the data doesn't require much more than that.</p>
[]
[ { "body": "<p>I completely changed the approach which resulted in faster downloads, and improved functionality. The overall approach of the initial version works well for a generic solution looking for adding concurrency to independent jobs.</p>\n\n<ol>\n<li>Removed <code>zypper list-updates</code>. This format is easier for machine consumption, but it's not intended for Tumbleweed. Replaced with <code>zypper dup/inr/in --details</code>;</li>\n<li>Removed background jobs and waits. Replaced with aria2 which handles the maximum number of concurrent connections;</li>\n<li>It pays off learning more about awk capabilities, in order to replace sequences of grep/awk/tr with a single awk;</li>\n<li>The main job of the script became building a plain text file with URIs and target directory for each .rpm file</li>\n</ol>\n\n<p>aria2 is really great tool. Superb quality. curl is not reliable in its native concurrent download capabilities.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-06T17:55:01.840", "Id": "240064", "ParentId": "239762", "Score": "1" } } ]
{ "AcceptedAnswerId": "240064", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-01T20:00:24.550", "Id": "239762", "Score": "2", "Tags": [ "bash", "linux", "curl" ], "Title": "Parallel download of rpm packages" }
239762
<p><a href="https://leetcode.com/problems/search-a-2d-matrix/" rel="nofollow noreferrer">https://leetcode.com/problems/search-a-2d-matrix/</a></p> <blockquote> <p>Write an efficient algorithm that searches for a value in an m x n<br> matrix. This matrix has the following properties:</p> <p>Integers in each row are sorted from left to right. The first integer<br> of each row is greater than the last integer of the previous row.</p> </blockquote> <pre><code>Example 1: Input: matrix = [ [1, 3, 5, 7], [10, 11, 16, 20], [23, 30, 34, 50] ] target = 3 Output: true Example 2: Input: matrix = [ [1, 3, 5, 7], [10, 11, 16, 20], [23, 30, 34, 50] ] target = 13 Output: false </code></pre> <p>Please review for performance. maybe there are better solutions but this is how my brain worked on this question. </p> <pre><code>using Microsoft.VisualStudio.TestTools.UnitTesting; namespace ArrayQuestions { /// &lt;summary&gt; /// https://leetcode.com/problems/search-a-2d-matrix/ /// &lt;/summary&gt; [TestClass] public class SearchA2DMatrixTest { [TestMethod] public void ExampleTest() { int[][] matrix = { new[] {1, 3, 5, 7}, new[] {10, 11, 16, 20}, new[] {23, 30, 34, 50} }; int target = 3; Assert.IsTrue(SearchMatrix(matrix, target)); } [TestMethod] public void FailedTest() { int[][] matrix = { new[] {1}, new[] {3}, }; int target = 3; Assert.IsTrue(SearchMatrix(matrix, target)); } [TestMethod] public void FailedTest2() { int[][] matrix = { new[] {1,3,5,6}, new[] {10,11,16,20}, new[] {23,30,34,50}, }; int target = 11; Assert.IsTrue(SearchMatrix(matrix, target)); } public bool SearchMatrix(int[][] matrix, int target) { if (matrix == null || matrix.Length == 0 || matrix[0].Length == 0) { return false; } if (target &lt; matrix[0][0] || target &gt; matrix[matrix.Length - 1][matrix[0].Length - 1]) { return false; } int top = matrix.Length - 1; int bottom =0; int mid = 0; while (bottom &lt;= top) { mid = ((top - bottom) / 2) + bottom; if (matrix[mid][0] == target) { return true; } if (matrix[mid][0] &gt; target) { top = mid - 1; } else { bottom = mid + 1; } } //if the first cell of the curr row(mid) // is bigger than the target, // the target is in the previous row if (matrix[mid][0] &gt; target) { mid--; } int left = 0; int right = matrix[0].Length - 1; int cm; while (left &lt;= right) { cm = ((right - left) / 2) + left; if (matrix[mid][cm] == target) { return true; } if (matrix[mid][cm] &gt; target) { right = cm - 1; } else { left = cm + 1; } } return false; } } } </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-01T21:21:31.027", "Id": "239764", "Score": "1", "Tags": [ "c#", "programming-challenge", "array", "matrix" ], "Title": "LeetCode: Search a 2D Matrix C#" }
239764
<p>I finally finished my Conway's game of life in c++ project and i'd love to find out how to improve the code.</p> <h1>main.cpp</h1> <pre><code>#include "Engine/Engine.h" int main() { Conway::Engine Engine(1280, 1024); Engine.Run(); return 0; } </code></pre> <h1>Engine.h</h1> <pre><code>#pragma once #include &lt;SDL2/SDL.h&gt; #include &lt;memory&gt; #include "Board.h" // Namespace Conway to // always enclose classes in a namespace. namespace Conway { // The engine class handles // everything about the program: // It handles the window, the renderer, // Drawing, Events, Game logic, // and holds representations of the game's // parts (Cell, Grid) class Engine { public: Engine(int ScreenWidth, int ScreenHeight); ~Engine(); void Run(); private: void HandleEvents(); void Draw(); void DrawLines(); const int m_ScreenWidth; const int m_ScreenHeight; bool m_Update = false; bool m_Running = true; std::unique_ptr&lt;Board&gt; m_Board; SDL_Window* m_Window; SDL_Renderer* m_Renderer; }; } </code></pre> <h1>Engine.cpp</h1> <pre><code>#include "Engine.h" Conway::Engine::Engine(int ScreenWidth, int ScreenHeight) : m_ScreenWidth{ScreenWidth}, m_ScreenHeight{ScreenHeight} { SDL_assert(SDL_Init(SDL_INIT_VIDEO) &gt;= 0); m_Window = SDL_CreateWindow( "Conway's game of life", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, m_ScreenWidth, m_ScreenHeight, SDL_WINDOW_SHOWN ); SDL_assert(m_Window != NULL); if (!m_Board) { Coord&lt;int, int&gt; ScreenSize = {m_ScreenWidth, m_ScreenHeight}; m_Board = std::make_unique&lt;Board&gt;(ScreenSize); } SDL_assert(m_Board != nullptr); m_Renderer = SDL_CreateRenderer(m_Window, -1, SDL_RENDERER_ACCELERATED|SDL_RENDERER_PRESENTVSYNC); SDL_assert(m_Renderer != NULL); // Show lines SDL_RenderClear(m_Renderer); DrawLines(); } Conway::Engine::~Engine() { SDL_DestroyWindow(m_Window); SDL_DestroyRenderer(m_Renderer); m_Window = NULL; m_Renderer = NULL; SDL_Quit(); } void Conway::Engine::HandleEvents() { SDL_Event Event; while(SDL_PollEvent(&amp;Event)) { switch(Event.type) { case SDL_QUIT: m_Running = false; break; // Toggles the updating with a keypress case SDL_KEYDOWN: if (Event.key.keysym.sym == SDLK_SPACE) { m_Update = m_Update ? false : true; DrawLines(); } else if (Event.key.keysym.sym == SDLK_c) { m_Board-&gt;Clear(); } break; case SDL_MOUSEBUTTONDOWN: if (!m_Update) { if (Event.button.button == SDL_BUTTON_LEFT) { m_Board-&gt;ToggleClickedCell({Event.button.x, Event.button.y}); } } break; } } } // Draws the grid void Conway::Engine::Draw() { SDL_RenderClear(m_Renderer); for (int i = 0; i &lt; Board::GRID_HEIGHT; ++i) { for (int j = 0; j &lt; Board::GRID_WIDTH; ++j) { if (m_Board-&gt;ReadCell(j + Board::GRID_WIDTH * i) == Board::Cell::Alive) { SDL_SetRenderDrawColor(m_Renderer, 255, 255, 255, 255); } else { SDL_SetRenderDrawColor(m_Renderer, 0, 0, 0, 255); } SDL_Rect rect; rect.x = m_Board-&gt;GetCellSize().first * j; rect.y = m_Board-&gt;GetCellSize().second * i; rect.w = m_Board-&gt;GetCellSize().first; rect.h = m_Board-&gt;GetCellSize().second; SDL_RenderFillRect(m_Renderer, &amp;rect); } } if (!m_Update) { DrawLines(); } SDL_RenderPresent(m_Renderer); } // This function draws // the lines delimiting each cell. // The first loop draws the horizontal // lines, the second one the vertical lines. void Conway::Engine::DrawLines() { SDL_SetRenderDrawColor(m_Renderer, 255, 255, 255, 255); for (int i = 0; i &lt; Board::GRID_HEIGHT; ++i) { if (i != 0) { SDL_RenderDrawLine( m_Renderer, 0, m_Board-&gt;GetCellSize().second * i, m_Board-&gt;GetCellSize().first * Board::GRID_WIDTH, m_Board-&gt;GetCellSize().second * i ); } } for (int i = 0; i &lt; Board::GRID_WIDTH; ++i) { if (i != 0) { SDL_RenderDrawLine( m_Renderer, m_Board-&gt;GetCellSize().first * i, 0, m_Board-&gt;GetCellSize().first * i, m_Board-&gt;GetCellSize().second * Board::GRID_HEIGHT ); } } SDL_RenderPresent(m_Renderer); SDL_SetRenderDrawColor(m_Renderer, 0, 0, 0, 255); } // Main game loop void Conway::Engine::Run() { while (m_Running) { HandleEvents(); if (m_Update) { m_Board-&gt;Update(); } Draw(); SDL_Delay(100); } } </code></pre> <h1>Board.h</h1> <pre><code>#pragma once #include &lt;vector&gt; #include "Coord.h" namespace Conway { class Board { public: Board(Coord&lt;int, int&gt; ScreenSize); static constexpr int GRID_WIDTH = 80; static constexpr int GRID_HEIGHT = 60; Coord&lt;int, int&gt; GetCellSize() { return m_CellSize; } void ToggleClickedCell(Coord&lt;int, int&gt; MouseCoords); void Update(); void Clear(); enum class Cell { Dead, Alive }; private: int CountAliveNeighbors(Coord&lt;int, int&gt; GridCell); std::vector&lt;Cell&gt; m_Grid; const Coord&lt;int, int&gt; m_CellSize; public: Cell ReadCell(int Index) { return m_Grid[Index]; } }; } </code></pre> <h1>Board.cpp</h1> <pre><code>#include "Board.h" #include &lt;cmath&gt; Conway::Board::Board(Coord&lt;int, int&gt; ScreenSize) : m_CellSize{ScreenSize.first / GRID_WIDTH, ScreenSize.second / GRID_HEIGHT} { int GridSize = GRID_WIDTH * GRID_HEIGHT; std::vector&lt;Cell&gt; temp(GridSize, Cell::Dead); m_Grid = temp; } void Conway::Board::Clear() { std::fill(m_Grid.begin(), m_Grid.end(), Cell::Dead); } int Conway::Board::CountAliveNeighbors(Coord&lt;int, int&gt; GridCell) { int count = 0; for (int i = -1; i &lt; 2; ++i) { for (int j = -1; j &lt;2; ++j) { int absoluteX = GridCell.first + i; int absoluteY = GridCell.second + j; if (absoluteX == -1 || absoluteX == GRID_WIDTH || absoluteY == -1 || absoluteY == GRID_HEIGHT || (i == 0 &amp;&amp; j == 0)) { continue; } if (m_Grid[absoluteX + GRID_WIDTH * absoluteY] == Cell::Alive) { ++count; } } } return count; } // Inverses the cell that was clicked on void Conway::Board::ToggleClickedCell(Coord&lt;int, int&gt; Coords) { int ClickedCell = (floor(Coords.first / m_CellSize.first)) + GRID_WIDTH * (floor(Coords.second / m_CellSize.second)); m_Grid[ClickedCell] = m_Grid[ClickedCell] == Cell::Dead ? Cell::Alive : Cell::Dead; } void Conway::Board::Update() { std::vector&lt;Cell&gt; temp(m_Grid); for (int i = 0; i &lt; Board::GRID_HEIGHT; ++i) { for (int j = 0; j &lt; GRID_WIDTH; ++j) { if (m_Grid[j + GRID_WIDTH * i] == Cell::Alive) { if (CountAliveNeighbors({j, i}) &lt; 2 || CountAliveNeighbors({j, i}) &gt; 3) { temp[j + GRID_WIDTH * i] = Cell::Dead; } } else { if (CountAliveNeighbors({j, i}) == 3) { temp[j + GRID_WIDTH * i] = Cell::Alive; } } } } m_Grid = temp; } </code></pre> <h1>Coord.h</h1> <pre><code>#pragma once template &lt;typename T1, typename T2&gt; struct Coord { T1 first; T2 second; }; </code></pre>
[]
[ { "body": "<p>The code looks well organized, and has a clear coding style. Good separation of responsibility between classes, almost no raw pointers (except for those coming from the C API of SDL of course), and no global variables. Nice! But there are still some areas of improvement:</p>\n\n<h1>Only use <code>SDL_assert()</code> to check for programming errors</h1>\n\n<p>Assertions are a tool to help find bugs in your program. However, in release builds, these assertions are typically compiled out. Thus, they should not be used to check for errors that can reasonably happen. For example:</p>\n\n<pre><code>SDL_assert(m_Window != NULL);\n</code></pre>\n\n<p>It is very possible that, without any bugs in your program, an SDL window could not be created, for example because of an out of memory condition, or the program being run without a display server running. So instead, you have to use a regular <code>if</code>-statement to check for this condition, and then handle the error appropriately. You could use exceptions for that, like so:</p>\n\n<pre><code>#include &lt;stdexcept&gt;\n\n...\n\nif (!m_Window)\n{\n throw std::runtime_error(\"Failed to create window\");\n}\n</code></pre>\n\n<h1>Use <code>nullptr</code> instead of <code>NULL</code></h1>\n\n<p><code>NULL</code> should be used in C code, in C++ you should use <a href=\"https://stackoverflow.com/questions/1282295/what-exactly-is-nullptr\"><code>nullptr</code></a>. However, you can also avoid writing it entirely in most cases. For example, instead of <code>if (foo != nullptr)</code>, you can just write <code>if (foo)</code>. Also, instead of <code>Foo *foo = nullptr</code> you can write <code>Foo *foo = {}</code>.</p>\n\n<p>Whether you want to use <code>nullptr</code> explicitly or use the shorter notations is up to the code style you are using.</p>\n\n<h1>Avoid unnecessary indirection</h1>\n\n<p>One of things you do in the constructor of <code>Engine</code> is to allocate a new instance of <code>Board</code> and store the pointer in <code>m_Board</code>. But why allocate this way, when you can just store a <code>Board</code> directly in <code>Engine</code>, like so:</p>\n\n<pre><code>class Engine {\n ...\n private:\n Board m_Board;\n};\n</code></pre>\n\n<p>The constructor should then ensure it initializes it like so:</p>\n\n<pre><code>Conway::Engine::Engine(int ScreenWidth, int ScreenHeight)\n : m_ScreenWidth{ScreenWidth}, m_ScreenHeight{ScreenHeight}\n , m_Board({ScreenWidth, ScreenHeight})\n{\n ...\n</code></pre>\n\n<h1>Don't draw in the constructor of <code>Engine</code></h1>\n\n<p>It should not be necessary to call <code>Draw()</code> from the constructor, instead this is done in <code>Run()</code>. In general, avoid having functions do more than necessary.</p>\n\n<h1>Don't reset member variables in the destructor</h1>\n\n<p>There is no pointing in setting <code>m_Window</code> and <code>m_Renderer</code> to <code>NULL</code> in the destructor of <code>Engine</code>, since those variables will be gone as soon as the function exits.</p>\n\n<h1>Add a <code>default</code> statement to the <code>switch</code> in <code>HandleEvents</code></h1>\n\n<p>Be explicit and tell the compiler what behaviour you want if <code>Event.type</code> doesn't match any of the <code>case</code>-statements. Otherwise, when enabling warnings, the compiler might warn about unhandled event types. It just has to be:</p>\n\n<pre><code>default:\n break;\n</code></pre>\n\n<h1>Improve <code>class Coord</code></h1>\n\n<p>Your <code>class Coord</code> is basically the same as <a href=\"https://en.cppreference.com/w/cpp/utility/pair\" rel=\"nofollow noreferrer\"><code>std::pair</code></a>. So, if you really wanted to have coordinate pairs where each coordinate can have its own type, you should just have written <code>std::pair&lt;int, int&gt;</code> instead of <code>Coord&lt;int, int&gt;</code>. However, in your code you always use <code>int</code>s for coordinates. So there really is no need for a template at all. Furthermore, you clearly want x and y-coordinates, so just make that explicit:</p>\n\n<pre><code>struct Coord\n{\n int x;\n int y;\n};\n</code></pre>\n\n<p>Be consistent in how you name things. In your code, you use <code>i</code>, <code>first</code> and <code>somethingX</code> as names for variables related to the x coordinate. Make sure it has <code>x</code> in the name everywhere. Also, do use your <code>class Coord</code> wherever you have a pair of coordinate. Here is how it would look:</p>\n\n<pre><code>int Conway::Board::CountAliveNeighbors(Coord GridCell)\n{\n int count = 0;\n for (int dx = -1; dx &lt;= 1; ++dx)\n {\n for (int dy = -1; dy &lt;= 1; ++dy)\n {\n Coord absolute;\n absolute.x = GridCell.x + dx;\n absolute.y = GridCell.y + dy;\n ...\n</code></pre>\n\n<h1>Don't use arbitrary delays</h1>\n\n<p>You are calling <code>SDL_Delay(100)</code>, which limits your code to run at less than 10 frames per second. Maybe you want to have the evolution of the board go at a rate of 10 Hz, but it is in general better to decouple rendering from the timesteps of your simulation. You already set the <code>SDL_RENDERER_PRESENTVSYNC</code> flag, so you can drop the call to <code>SDL_Delay()</code> and have your code render at the same framerate as your monitor.</p>\n\n<p>If you want to limit how often the board updates, then I suggest you use <code>SDL_GetTicks()</code> to keep track of time, and only call <code>Update()</code> when enough time has passed.</p>\n\n<h1>Pass coordinate pairs to <code>ReadCell()</code></h1>\n\n<p>The fact that <code>class Board</code> stores cells as a one-dimensional <code>std::vector</code> should not have to be exposed to other classes. So it is better if <code>ReadCell()</code> takes x and y-coordinates in the form of a <code>Coord</code>, and converts them to an index itself, so in <code>Engine::Draw()</code> you can write:</p>\n\n<pre><code>if (m_Board.ReadCell({x, y}) == Board::Cell::Alive)\n</code></pre>\n\n<h1>Rename <code>ToggleClickedCell()</code> to <code>ToggleCell()</code></h1>\n\n<p>You have a very good separation of responsibility in your code: <code>class Board</code> implements the logics of the board, while <code>class Engine</code> handles user input and rendering. This makes it easy to change the <code>Engine</code> while keeping the functionality of the <code>Board</code> the same. For example, you could make a text-only version of your program by changing <code>Engine</code> such that it would not use SDL but render the board as ASCII art for example. In that case, you would not use a mouse but the keyboard to toggle cells, so it would be strange to have to call <code>ToggleClickedCell()</code> when no clicking is involved.</p>\n\n<p>You should also just pass the grid x and y coordinates to <code>ToggleCell()</code>, not the mouse coordinates. Converting mouse coordinates to grid coordinates should be done by <code>Engine</code>.</p>\n\n<h1>Make member functions <code>const</code> where appropriate</h1>\n\n<p>Apart from variables, you can also make member functions <code>const</code>. You should do this when the member function doesn't change any of the member variables of its class. That allows the compiler to optimize the code better. You just have to add it right after the declaration in the header files, like so:</p>\n\n<pre><code>int CountAliveNeighbors(Coord GridCell) const;\n</code></pre>\n\n<h1>Avoid repeatedly using a function to get the same value</h1>\n\n<p>In <code>Board::Update()</code> there are three calls to <code>CountAliveNeighbors({j, i})</code>. Apart from the code duplication, if the compiler cannot see that each call will produce exactly the same result, it will perform more function calls than necessary. While there are ways to make the compiler optimize this anyway (using <a href=\"https://en.cppreference.com/w/cpp/language/attributes\" rel=\"nofollow noreferrer\">function attributes</a> like <code>[[gnu::const]]</code> or <a href=\"https://en.wikipedia.org/wiki/Interprocedural_optimization#WPO_and_LTO\" rel=\"nofollow noreferrer\">link-time optimization</a>), you can easily improve the code yourself by calling the function once and storing the result in a variable:</p>\n\n<pre><code>auto aliveNeigbors = CountAliveNeighbors({x, y});\n\nif (ReadCell({x, y}) == Cell::Alive)\n{\n if (aliveNeighbors &lt; 2 || aliveNeighbors &gt; 3)\n {\n ...\n</code></pre>\n\n<h1>Keep two vectors of cells in memory</h1>\n\n<p>In <code>Board::Update()</code>, you create a temporary <code>std::vector&lt;Cell&gt;</code>, write the new cell state to it, and at the end copy the temporary vector into <code>m_Grid</code>, and then you destroy the temporary. If this was something you would only do sporadically, that could be fine, but this is where your program spents a large part of its time, so you should try to optimize this. A simple way to do this is to keep two vectors for storage, and a variable to keep track of the \"current\" vector. For example, in <code>Board.h</code>:</p>\n\n<pre><code>class Board\n{\n ...\n private:\n std::vector&lt;Cell&gt; m_Grids[2];\n int m_CurrentGrid = 0;\n};\n</code></pre>\n\n<p>Then, in <code>Update()</code>, do something like:</p>\n\n<pre><code>auto &amp;m_Grid = m_Grids[m_CurrentGrid]; // Get a reference to the current grid\nauto &amp;temp = m_Grids[m_CurrentGrid ^ 1]; // Get a reference to the temporary grid\n\nfor (...)\n{\n ...\n}\n\nm_CurrentGrid ^= 1; // Swap the temporary and current grid\n</code></pre>\n\n<p>Of course, everywhere you used <code>m_Grid</code> before, you have to ensure you use the current grid. This makes it even more important to use a member function to get cell at a given coordinate, instead of reading a vector directly, even inside <code>class Board</code> itself, because then you only need one place where you put the logic which of the two vectors to read.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-03T15:19:18.947", "Id": "470555", "Score": "0", "body": "I've had many an SDL application crash on me because of `SDL_assert(m_Window != NULL);`. Good advice." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-02T16:51:30.650", "Id": "239812", "ParentId": "239765", "Score": "5" } } ]
{ "AcceptedAnswerId": "239812", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-01T21:23:02.763", "Id": "239765", "Score": "3", "Tags": [ "c++", "game-of-life", "sdl2" ], "Title": "Conway's game of life in C++ using SDL2" }
239765
<p>I have two tables with a 1-many relationship, Device and TestResult. </p> <p>My application has a filter builder front-end that allows a user to retrieve TestResults based on whatever filters they specify. This generates queries similar to this:</p> <pre><code>SELECT d.id, d.serialNumber, d.createdAt, r.id, r.testBlockId, r.deviceId, r.type, r.fieldResponses, r.stationName, r.summary, r.createdAt FROM Device AS d INNER JOIN TestResult AS r ON r.deviceId = d.id WHERE d.id IN (SELECT id FROM Device WHERE serialNumber BETWEEN '000000001000' AND '000000002020' ORDER BY serialNumber ASC LIMIT 570, 10) AND r.createdAt BETWEEN '2020-03-27T11:54:43.100Z' AND '2020-04-01 09:21:02.362768' ORDER BY serialNumber ASC; </code></pre> <p>This query limits the number of Devices returned, which handles paging on the front-end. I'm also generating a query that counts the total number of Devices that match the filters, without the OFFSET and LIMIT values. This is used to tell the front-end how many pages of records there are.</p> <p>If I simply run the above query but change the SELECT statement to <code>SELECT COUNT(DISTINCT d.id) as totalDevices</code> and remove the LIMIT, it's very slow. So instead I'm generating this query to find the count:</p> <pre><code>SELECT COUNT(DISTINCT d.id) AS totalDevices FROM Device AS d INNER JOIN TestResult AS r ON r.deviceId = d.id WHERE serialNumber BETWEEN '000000001000' AND '000000002020' AND r.createdAt BETWEEN '2020-03-27T11:54:43.100Z' AND '2020-04-01 09:21:02.362768'; </code></pre> <p>This query runs faster, but it still isn't fast. I'm wondering if there is a better way to retrieve a count of the distinct Device records that would be returned from this query.</p> <p>This query shows the following execution time with 1,000,000 records:</p> <pre><code>Run Time: real 8.090 user 1.562500 sys 6.500000 </code></pre>
[]
[ { "body": "<p>I've modified the query to use a GROUP BY instead of a COUNT DISTINCT, which has sped up the execution time.</p>\n\n<pre><code>SELECT COUNT(*) AS totalDevices\nFROM (\n SELECT d.id\n FROM Device AS d\n INNER JOIN TestResult AS r ON r.deviceId = d.id\n WHERE serialNumber BETWEEN '000000001000' AND '000000002020'\n AND r.createdAt BETWEEN '2020-03-27T11:54:43.100Z' AND '2020-04-01 09:21:02.362768'\n GROUP BY d.id\n);\n</code></pre>\n\n<p>This query shows the following execution time with 1,000,000 records:</p>\n\n<pre><code>Run Time: real 3.433 user 0.953125 sys 2.484375\n</code></pre>\n\n<p>The COUNT DISTINCT query shows the following execution time:</p>\n\n<pre><code>Run Time: real 8.090 user 1.562500 sys 6.500000\n</code></pre>\n\n<p>So the GROUP BY query takes just under half of the time of the COUNT DISTINCT query.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-02T14:18:17.787", "Id": "239805", "ParentId": "239766", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-01T21:36:09.117", "Id": "239766", "Score": "1", "Tags": [ "sql", "sqlite" ], "Title": "Count distinct records in a JOINed SQL query" }
239766
<p>I had a coding assignment task(interview) for a senior data engineer role, JSON data validation. Every record in the input json indicates a customer record, I need to write a script to validate that all records confirms to few business rules and few more field type/length restrictions.</p> <p>I used object-oriented, meta-data driven approach to write this parser in Python. However, I got negative feedback for the task and I am hoping to get some feedback on the code. Here is the git repo with some extra readme for the context and Business rules - <a href="https://github.com/YADAAB/jsonparser" rel="nofollow noreferrer">https://github.com/YADAAB/jsonparser</a></p> <p>I am looking for some inputs on coding style, overall design, object-oriented approach etc.</p> <p>An example of email validation since the stackXchange wants me to add some code in the question :)</p> <pre><code> email_regex = '^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$' try: if(re.search(email_regex,self.line_dict[field_name])): return True else: self.error_dict[field_name] = str(self.error_dict.get(field_name, '')) + 'Invalid email' </code></pre> <p>Would love to answer any specific questions. Thanks for checking!</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-03T17:18:03.790", "Id": "470561", "Score": "0", "body": "bump here for any feedback" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-02T00:23:03.817", "Id": "239773", "Score": "1", "Tags": [ "python", "python-3.x", "json" ], "Title": "Simple Json log Parser Application" }
239773
<p>I am attempting to animate the series of button presses in the simon game I am creating with tkinter. The animate method is called for each button that needs to be pressed in the series. It currently presses all of the buttons at the same time rather than in a series as it is meant to.</p> <pre><code>from tkinter import * from random import choice root = Tk() Grid.rowconfigure(root, 0, weight=1) Grid.columnconfigure(root, 0, weight=1) frame = Frame(root) frame.grid(row=0, column=0, sticky=N+E+S+W) def animate(btn): btn.config(relief=SUNKEN, state=ACTIVE) btn.after(200, lambda: btn.config(relief=RAISED, state=NORMAL)) class Game(object): def __init__(self): self.colors = ["green", "red", "yellow", "blue"] self.i = 0 self.round = 1 self.moves = [] self.cpu_moves = [] self.btns = [] for row in range(2): Grid.rowconfigure(frame, row, weight=1) for col in range(2): Grid.columnconfigure(frame, col, weight=1) btn = Button(frame, width=150, height=150, bg=self.colors[0], command=lambda b=self.i: self.user_select(b)) btn.grid(row=row, column=col) self.btns.append(btn) self.colors.remove(self.colors[0]) self.i += 1 def user_select(self, btn): self.moves.append(btn) print(self.moves) print(self.cpu_moves) if self.moves == self.cpu_moves: self.clear_user_moves() self.round += 1 self.cpu_move() elif len(self.moves) == len(self.cpu_moves) and self.moves != self.cpu_moves: self.clear_cpu_moves() def clear_user_moves(self): self.moves = [] def clear_cpu_moves(self): self.cpu_moves = [] def cpu_move(self): nums = [0, 1, 2, 3] self.cpu_moves.append(choice(nums)) print(self.cpu_moves) for i in self.cpu_moves: root.after(200, animate(self.btns[i])) class App(object): def __init__(self, master): self.master = master game = Game() game.cpu_move() root.geometry("300x300") app = App(root) root.resizable(width=False, height=False) root.mainloop() </code></pre>
[]
[ { "body": "<p>Let's look at this code:</p>\n\n<pre><code>for i in self.cpu_moves:\n root.after(200, animate(self.btns[i]))\n</code></pre>\n\n<p>First, you're not using <code>after</code> correctly. You're doing the equivalent of this:</p>\n\n<pre><code>for i in self.cpu_moves:\n result = animate(self.btns[i])\n root.after(200, result)\n</code></pre>\n\n<p>You might as well not call <code>root.after</code> at all, since <code>result</code> will be <code>None</code>. If you need to pass parameters to the function you can do so by adding arguments to <code>after</code> itself:</p>\n\n<pre><code>root.after(200, animate, self.btns[i])\n</code></pre>\n\n<p>Unfortunately, you can only do this with positional parameters, not named parameters. You still need to use <code>lambda</code> the way you are doing it in <code>animate</code>.</p>\n\n<p>Second, this loop is going to end up calling every function at the same time - the first one at \"now+200ms\", the next one at \"now+200ms\", the third at \"now+200ms\" and so on. What you want is the first one to be at \"now+200ms\", the next at \"now+400ms\" and so on. A simple solution is to add 200 for each iteration of the loop:</p>\n\n<pre><code>delay=200\nfor i in self.cpu_moves:\n root.after(delay, animate(self.btns[i]))\n delay += 200\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-02T02:40:15.140", "Id": "239777", "ParentId": "239774", "Score": "0" } } ]
{ "AcceptedAnswerId": "239777", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-02T01:19:52.150", "Id": "239774", "Score": "0", "Tags": [ "python", "tkinter" ], "Title": "animate button presses in a sequence (tkinter)" }
239774
<p>I'm trying to recreate the method inject (Works like Reduce) from ruby Enumerable Module. Using Rubocop (A Linter) I got the error:</p> <pre><code>Cyclomatic complexity for my_inject is too high. [7/6] </code></pre> <p>The code is:</p> <pre><code>module Enumerable def my_inject(*args) list = to_a if Range reduce = args[0] if args[0].is_a?(Integer) operator = args[0].is_a?(Symbol) ? args[0] : args[1] if operator list.each { |item| reduce = reduce ? reduce.send(operator, item) : item } return reduce end list.each { |item| reduce = reduce ? yield(reduce, item) : item } reduce end end </code></pre> <p>I already did my best to reduce the Cyclomatic complexity, but still have 1 above (7/6), now I stuck, any directions will be appreciate.</p> <p>The code can be run on reply: <a href="https://repl.it/@ThiagoMiranda2/INJECT" rel="nofollow noreferrer">https://repl.it/@ThiagoMiranda2/INJECT</a></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-02T08:28:49.613", "Id": "470382", "Score": "1", "body": "Does `my_inject()` as presented work as specified?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-02T14:29:40.007", "Id": "470412", "Score": "0", "body": "Yes, works almost like the original, same behavior as describe on documentation, but some edge cases are not cover, like when we have an empty block ." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-06T20:49:56.547", "Id": "470867", "Score": "0", "body": "Please can you add a description on what the code achieves, currently all I've learnt from reading your question is that it's got bad cyclomatic complexity. To be able to help people need to know what it is you're doing." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-07T15:07:53.307", "Id": "470955", "Score": "0", "body": "This method works like Reduce function of any main stream language, for example if you have an array [1,2,3] and let's say you want to reduce with sum operator, so you have = 1 + 2 +3 = 6. In this case we have the array as input [1,2,3] an the return is the number 6." } ]
[ { "body": "<p>Before I answer your question I should point out that:</p>\n\n<pre><code>list = to_a if Range\n</code></pre>\n\n<p>is incorrect. <code>Range</code> is a constant and <code>if Range</code> is always true. You probably means <code>if is_a?(Range)</code> which would mean <code>list</code> was undefined in most cases.</p>\n\n<p>As a first attempt at solving this I would take the case where an operator is provided and have the method call itself with a block something like below.</p>\n\n<pre><code>module Enumerable\n def my_inject(*args)\n unless block_given?\n operator = args.delete_at(-1)\n initial = args.first \n return my_inject(initial) { |accumulator, i| accumulator.send(operator, i) }\n end\n\n list = is_a?(Range) ? to_a : self\n\n accumulator = args.first \n list.each { |item| accumulator = accumulator ? yield(accumulator, item) : item\n accumulator\n end\n\nend\n\n</code></pre>\n\n<p>Note: I didn't test this or check its complexity. </p>\n\n<p>This code is also incorrect. There is actually a difference between an initial value that is not provided and one of <code>nil</code>. It is also possible for the block to to return <code>nil</code> which would cause the yield block not to be called for that iteration. The real solution is to check <code>args.length</code> not just <code>args.first</code> but that would increase your complexity.</p>\n\n<p>To do this properly and still pass Rubocop's checks for complexity (as well as its other checks) you will need to break this method up into a few smaller methods.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-02T18:24:28.967", "Id": "470429", "Score": "0", "body": "Your code doesn't have problem with complexity, and now I have new paths to try. Thanks for the advice about Range, was missing that." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-02T16:36:00.833", "Id": "239811", "ParentId": "239776", "Score": "1" } } ]
{ "AcceptedAnswerId": "239811", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-02T02:35:33.837", "Id": "239776", "Score": "0", "Tags": [ "ruby", "cyclomatic-complexity" ], "Title": "Case of Cyclomatic Complexity" }
239776
<p>I've built a simple Book list app. It allows users to enter the name, author and isbn of a book into a form. Then when this is submitted successfully, the details get added to a new row in the table.</p> <p>I've tried to make the code as optimal as possible. Any feedback would be greatly appreciated.</p> <pre><code>const bookList = document.getElementById('book-list'); class Book { constructor(title, author, isbn){ this.title = title; this.author = author; this.isbn = isbn; } addBook(){ const bookList = document.getElementById('book-list'); const bookItem = document.createElement('tr'); bookItem.innerHTML =` &lt;td&gt;${this.title}&lt;/td&gt; &lt;td&gt;${this.author}&lt;/td&gt; &lt;td&gt;${this.isbn}&lt;/td&gt; &lt;td&gt;&lt;button type="submit" class="delete"&gt;X&lt;/button&gt;&lt;/td&gt;`; return bookList.appendChild(bookItem); } static deleteBook(target){ target.originalTarget.parentElement.parentElement.remove(); } } // Event Listener: Form Submit form.addEventListener('submit', function(e){ const bookFields = getFields(); if(!validateForm(bookFields)) { showNotification('Error', 'error'); e.preventDefault(); return false; } const book = new Book( bookFields.title, bookFields.author, bookFields.isbn ); book.addBook(book); showNotification('Success', 'success'); this.reset(); // Reset Form e.preventDefault(); }); // Event Listener: Delete Book bookList.addEventListener('click', function(e){ Book.deleteBook(e); showNotification('Deleted Item', 'success'); }); function getFields(){ return fields = { 'title': document.getElementById('title').value, 'author': document.getElementById('author').value, 'isbn': document.getElementById('isbn').value }; } function validateForm(fields){ for(let [key, value] of Object.entries(fields)){ if(value === '') return false; } return true; } // Notification function showNotification(message, type){ const container = document.querySelector('.container'); const alert = document.createElement('div'); alert.classList = `${type}`; alert.appendChild(document.createTextNode(message)); container.insertBefore(alert, form); setTimeout(function(){ alert.remove(); }, 1500); }<span class="math-container">```</span> </code></pre>
[]
[ { "body": "<p>Some possible improvements:</p>\n\n<p>You select the <code>bookList</code> multiple times. You only need to select it once, in the outer scope, and let lexical scoping do the rest - you can remove the line that re-declares it without issues.</p>\n\n<p>Inserting characters from user input <em>directly</em> into a string of HTML markup can occasionally result in unexpected elements appearing when the input contains <code>&lt;</code> brackets. (This can also allow for arbitrary code execution)</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const bookItem = document.querySelector('tr');\nconst title = 'Title &lt;Subtitle in brackets&gt;';\nconst author = '&lt;img src onerror=\"alert(\\'evil\\');\"';\nbookItem.innerHTML =`\n &lt;td&gt;${title}&lt;/td&gt;\n &lt;td&gt;${author}&lt;/td&gt;\n`;</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;table&gt;\n &lt;tr&gt;\n &lt;/tr&gt;\n&lt;/table&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>Either escape <code>&lt;</code> brackets first, or insert the <code>&lt;td&gt;</code>s without content, then select them afterwards and assign to their <code>textContent</code> (which won't have any escaping issues).</p>\n\n<pre><code>&lt;td&gt;${this.title.replace(/&lt;/g, '&amp;lt;')}&lt;/td&gt;\n&lt;td&gt;${this.author.replace(/&lt;/g, '&amp;lt;')}&lt;/td&gt;\n&lt;td&gt;${this.isbn.replace(/&lt;/g, '&amp;lt;')}&lt;/td&gt;\n&lt;td&gt;&lt;button type=\"submit\" class=\"delete\"&gt;X&lt;/button&gt;&lt;/td&gt;`;\n</code></pre>\n\n<p>The return value from <code>addBook</code> is not used, so there's no need for it to return a value. Unless you're <em>intending</em> consumers of <code>Book</code> to use the created <code>&lt;tr&gt;</code>, you can remove the <code>return</code> from the end of the function.</p>\n\n<p>Your <code>deleteBook</code> function is odd - whenever <em>anything</em> in the <code>bookList</code> is clicked, it will remove the grandparent element. This does not seem desirable. You probably want to remove a <code>&lt;tr&gt;</code> only when the <code>X</code> button is clicked. Add an event listener to the button instead:</p>\n\n<pre><code>addBook(){\n const tr = document.createElement('tr');\n tr.innerHTML =`\n &lt;td&gt;${this.title.replace(/&lt;/g, '&amp;lt;')}&lt;/td&gt;\n &lt;td&gt;${this.author.replace(/&lt;/g, '&amp;lt;')}&lt;/td&gt;\n &lt;td&gt;${this.isbn.replace(/&lt;/g, '&amp;lt;')}&lt;/td&gt;\n &lt;td&gt;&lt;button type=\"submit\" class=\"delete\"&gt;X&lt;/button&gt;&lt;/td&gt;`;\n const button = tr.querySelector('button');\n button.addEventListener('click', () =&gt; {\n tr.remove();\n showNotification('Deleted Item', 'success');\n });\n bookList.appendChild(tr);\n}\n</code></pre>\n\n<p>You could also keep using your listener on the whole <code>bookList</code>, but you'd have to make sure that the clicked element is the X button before removing elements - check if the target <code>.matches('.delete')</code>. (but even then, it's strange for that functionality to be <em>outside</em> of the <code>Book</code> class - it would make more sense for it to be encapsulated)</p>\n\n<p>If you do use the delegation method, use <code>event.target</code>, <em>not</em> <code>event.originalTarget</code> (which is <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Event/originalTarget\" rel=\"nofollow noreferrer\">non-standard</a> and only works on Firefox - on any other browser, it will throw an error). (also, best to name the variables appropriately - you're passing the <em>event</em> to <code>deleteBook</code>, not the <code>event.target</code>, so calling the parameter <code>target</code> is confusing)</p>\n\n<p>You can make the <code>submit</code> listener a bit less repetitive by calling <code>e.preventDefault</code> on the first line of the function, that way you don't have to write it twice later, nor do you have to worry about accidentally not calling it in case you add more logical paths to the function. (And if you call <code>preventDefault()</code>, there's no need to <code>return false</code>, nothing needs to be returned)</p>\n\n<p>In <code>getFields</code>, you're implicitly creating a global variable <code>fields</code>. This doesn't do anything useful, and will throw an error in strict mode (which you should be using). Just remove the <code>fields =</code> part:</p>\n\n<pre><code>function getFields(){\n return {\n 'title': document.getElementById('title').value,\n 'author': document.getElementById('author').value,\n 'isbn': document.getElementById('isbn').value\n };\n}\n</code></pre>\n\n<p>Doesn't matter much here, but if you had more fields, to be less repetitive, you could replace that with:</p>\n\n<pre><code>function getFields() {\n return Object.fromEntries(\n ['title', 'author', 'isbn'].map(\n id =&gt; [id, document.getElementById(id).value]\n )\n );\n}\n</code></pre>\n\n<p>It's good to prefer <code>const</code> whenever possible - using <code>let</code> is a warning to future readers of the script (including yourself) that you may be reassigning the variable later. So, you could replace</p>\n\n<pre><code>for(let [key, value] of Object.entries(fields)){\n</code></pre>\n\n<p>with</p>\n\n<pre><code>for(const [key, value] of Object.entries(fields)){\n</code></pre>\n\n<p>Or, even better, since you don't care about the keys at all, only that none of the values are empty:</p>\n\n<pre><code>function validateForm(fields){\n return Object.values(fields).every(Boolean);\n}\n</code></pre>\n\n<p>When <code>alert</code> is used as an identifier in Javascript, it usually refers to <code>window.alert</code>. Calling a <em>different</em> variable <code>alert</code> can be confusing. Consider changing</p>\n\n<pre><code>const alert = document.createElement('div');\n</code></pre>\n\n<p>to something like <code>alertDiv</code>.</p>\n\n<p>Template literals look nicer than concatenation with <code>+</code>, but if there's no concatenation going on, and there aren't any <code>'</code> or <code>\"</code> characters causing escaping issues, there's no point in a template literal. Replace</p>\n\n<pre><code>alertDiv.classList = `${type}`;\n</code></pre>\n\n<p>with</p>\n\n<pre><code>alertDiv.classList = type;\n</code></pre>\n\n<p>But the <code>classList</code> is generally understood to be a read-only <code>DOMTokenList</code>. While you <em>can</em> change the class of an element by assigning to the <code>classList</code> property, it looks quite odd. If you want to assign a class, either use <code>classList.add</code>, or (if you don't care about overwriting the existing class) assign to the <code>className</code> property:</p>\n\n<pre><code>alertDiv.className = type;\n</code></pre>\n\n<p>Using <code>document.createTextNode</code> is often unnecessarily verbose. You can just assign to the <code>textContent</code> of the element instead. Replace</p>\n\n<pre><code>alertDiv.appendChild(document.createTextNode(message));\n</code></pre>\n\n<p>with</p>\n\n<pre><code>alertDiv.textContent = message;\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-03T10:39:57.183", "Id": "239858", "ParentId": "239781", "Score": "1" } } ]
{ "AcceptedAnswerId": "239858", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-02T06:30:23.357", "Id": "239781", "Score": "2", "Tags": [ "javascript", "beginner" ], "Title": "Simple Book List App" }
239781
<p>I've always wondered what's the most elegant way of implementing PrintLn in C++. I have not yet come with perfect conclusion. This is my shot.</p> <p>Shortcut for std::cout, std::cerr and std::clog "print line" version. So you can type <code>CoutLn &lt;&lt; "Hello world!";</code> instead of <code>std::cout &lt;&lt; "Hello world!" &lt;&lt; '\n';</code></p> <p><strong>CoutLn</strong>, <strong>CerrLn</strong>, <strong>ClogLn</strong> are implemented.</p> <pre><code>#include &lt;iostream&gt; #include &lt;typeinfo&gt; #include &lt;mutex&gt; /* Template magic: determine if our type is printable. */ template&lt;typename S, typename T, typename = void&gt; struct is_to_stream_writable : std::false_type {}; template&lt;typename S, typename T&gt; struct is_to_stream_writable&lt;S, T, std::void_t&lt;decltype(std::declval&lt;S&amp;&gt;()&lt;&lt;std::declval&lt;T&gt;())&gt;&gt; : std::true_type {}; /* Since std::cout, std::cerr etc. are all different instances of the same type, * let's define dummy classes for detecting different instances. */ class Cout{}; class Cerr{}; class Clog{}; template&lt;class Stream = Cout&gt; class PrintLn { private: static std::ostream* stream; static std::mutex m; public: PrintLn() { if constexpr (std::is_same&lt;Stream, Cout&gt;::value) stream = &amp;std::cout; else if constexpr (std::is_same&lt;Stream, Cerr&gt;::value) stream = &amp;std::cerr; else if constexpr (std::is_same&lt;Stream, Clog&gt;::value) stream = &amp;std::clog; } template&lt;class T&gt; PrintLn&amp; operator&lt;&lt;(const T&amp; msg) { static_assert(is_to_stream_writable&lt;std::ostream, T&gt;::value, "your type is not printable"); std::lock_guard&lt;std::mutex&gt;(PrintLn&lt;Stream&gt;::m); *stream &lt;&lt; msg; return *this; } ~PrintLn() { std::lock_guard&lt;std::mutex&gt;(PrintLn&lt;Stream&gt;::m); *stream &lt;&lt; '\n'; } }; /* Declare static variables. */ template&lt;class Stream&gt; typename::std::mutex PrintLn&lt;Stream&gt;::m; template&lt;class Stream&gt; typename::std::ostream* PrintLn&lt;Stream&gt;::stream; using CoutLn = PrintLn&lt;Cout&gt;; using CerrLn = PrintLn&lt;Cerr&gt;; using ClogLn = PrintLn&lt;Clog&gt;; /* Shorter syntax, for example: `CerrLn{} &lt;&lt; "error";` -&gt; `CerrLn &lt;&lt; "error";`. */ #define CoutLn CoutLn{} #define CerrLn CerrLn{} #define ClogLn ClogLn{} </code></pre>
[]
[ { "body": "<p>Have you looked at <a href=\"https://en.cppreference.com/w/cpp/io/basic_osyncstream\" rel=\"nofollow noreferrer\">C++20 <code>osyncstream</code></a>? It seems to have a better interface.</p>\n\n<h1>Multithreading</h1>\n\n<pre><code>std::lock_guard&lt;std::mutex&gt;(PrintLn&lt;Stream&gt;::m);\n</code></pre>\n\n<p>This line is useless, because temporary objects are destroyed at the end of the full-expression. (Does this even have a temporary in C++17?) You need a named variable instead. Also make use of class template argument deduction:</p>\n\n<pre><code>std::lock_guard lock{m};\n</code></pre>\n\n<p>Also,</p>\n\n<h1>Streams</h1>\n\n<p>Your approach is unnecessarily restricted because only three hardcoded streams <code>std::cout</code>, <code>std::cerr</code>, and <code>std::clog</code> are supported. And I think <code>{}</code> is OK and these don't really help a lot:</p>\n\n<pre><code>#define CoutLn CoutLn{}\n#define CerrLn CerrLn{}\n#define ClogLn ClogLn{}\n</code></pre>\n\n<p>Make the function object have regular semantics instead. You may use a hash map internally to store the mutexes, as <code>syncbuf</code> does.</p>\n\n<p>Also SFINAE on <code>operator&lt;&lt;</code>.</p>\n\n<hr>\n\n<p>Here's the same thing implemented with <code>osyncstream</code>:</p>\n\n<pre><code>template &lt;\n class CharT,\n class Traits = std::char_traits&lt;CharT&gt;,\n class Allocator = std::allocator&lt;CharT&gt;\n&gt; class PrintLn : public std::basic_osyncstream&lt;CharT, Traits, Allocator&gt; {\n using Base = std::basic_osyncstream&lt;CharT, Traits, Allocator&gt;;\npublic:\n using Base::Base;\n\n PrintLn(PrintLn&amp;&amp;) = default;\n PrintLn&amp; operator=(PrintLn&amp;&amp;) = default;\n ~PrintLn()\n {\n if (this-&gt;get_wrapped()) {\n *static_cast&lt;Base*&gt;(this) &lt;&lt; '\\n';\n }\n }\n};\n\ninline auto cout_ln()\n{\n return PrintLn{std::cout};\n}\ninline auto cerr_ln()\n{\n return PrintLn{std::cerr};\n}\ninline auto clog_ln()\n{\n return PrintLn{std::clog};\n}\n</code></pre>\n\n<p>But anyway, why would you wanna do this when you can simply print a <code>\\n</code>?</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-02T17:49:14.503", "Id": "474204", "Score": "0", "body": "I wouldn't recommend C++20 features until most major compilers (G++, Clang++, MSVC++) support them. Even then, it might not hurt to wait a couple of years so those compilers that support them get to enough platforms." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-02T11:55:21.890", "Id": "239795", "ParentId": "239785", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-02T08:07:02.677", "Id": "239785", "Score": "4", "Tags": [ "c++" ], "Title": "PrintLn header for C++" }
239785
<p>Wrote my first mini-script to get data from the german football league table and save the data to a csv file. Do you like the approach or could I be more efficient? Thanks in advance!</p> <pre><code>from bs4 import BeautifulSoup import requests import csv url = "https://www.bundesliga.com/de/bundesliga/tabelle" r = requests.get(url) r_soup = BeautifulSoup(r.content, "lxml") table = r_soup.find_all("tr") csv_file = open("bundesliga_table.csv", "w") csv_writer = csv.writer(csv_file) csv_writer.writerow(["Rank", "Team", "Matches", "Points", "Goal Difference"]) for club in table: try: rank = club.find("td", class_="rank").text team = club.find("span", class_="d-none d-lg-inline").text matches = club.find("td", class_="matches").text points = club.find("td", class_="pts").text difference = club.find("td", class_="difference").text print(str(rank) + " " + str(team) + " " + str(matches) + " " + str(points) + " " + str(difference)) csv_writer.writerow([rank, team, matches, points, difference]) except: print("One team not found") csv_file.close() </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-02T09:49:10.823", "Id": "470393", "Score": "3", "body": "The current question title of your question is too generic to be helpful. Please edit to the site standard, which is for the title to simply **state the task accomplished by the code**. Please see [**How do I ask a good question?**](https://CodeReview.StackExchange.com/help/how-to-ask)." } ]
[ { "body": "<p>Two things about the way you handle files:</p>\n\n<ol>\n<li><p>Since you <code>open</code> the file and only <code>close</code> it at the end, if an exception disrupts your program in between, the file will not be properly closed. Instead use a <code>with</code> context manager:</p>\n\n<pre><code>with open(\"bundesliga_table.csv\", \"w\") as csv_file:\n ...\n</code></pre>\n\n<p>This automatically closes the file for you when leaving the block, whether by having finished the code within or due to an exception.</p></li>\n<li><p>Currently you are writing one row at a time. However, the writer can also take an iterable of rows and write them all at once. This allows it to potentially optimize the writing in a better way.</p></li>\n</ol>\n\n<p>The latter also gives you the opportunity to put your parsing code into a function. Actually, you should probably put all your code into functions! This way you can give them nice and clear names, add a <a href=\"https://www.python.org/dev/peps/pep-0257/\" rel=\"nofollow noreferrer\"><code>docstring</code></a> describing what the function does and how to use it and add type annotations if you want to. This makes your code much more readable, especially when it grows to more than the few lines you currently have. It also decouples getting the data from displaying it and from writing it to a file, all of which are separate things that are mushed together in your current code. Again, that is fine for small scripts or as a starting point, but when your scripts get larger you want to refactor this.</p>\n\n<p>You should also be careful with <code>try...except</code> clauses. The bare <code>except</code> you currently have will also catch e.g. the user pressing <kbd>Ctrl</kbd>+<kbd>C</kbd> if they want to abort the process (because it is taking too long or whatever). Using <code>except Exception</code> will avoid that at least, but you should catch as specific as possible.</p>\n\n<p>In this case I would use something like this:</p>\n\n<pre><code>from bs4 import BeautifulSoup\nimport requests\nimport csv\nfrom itertools import chain\n\ndef get_table(url):\n \"\"\"Parse the official bundesliga website to get the current table.\n\n Returns an iterable of rows.\"\"\"\n r = requests.get(url)\n r.raise_for_status()\n soup = BeautifulSoup(r.content, \"lxml\")\n for club in soup.find_all(\"tr\"):\n try:\n rank = club.find(\"td\", class_=\"rank\").text\n team = club.find(\"span\", class_=\"d-none d-lg-inline\").text\n matches = club.find(\"td\", class_=\"matches\").text\n points = club.find(\"td\", class_=\"pts\").text\n difference = club.find(\"td\", class_=\"difference\").text\n yield rank, team, matches, points, difference\n except Exception:\n print(\"Did not find a team:\")\n print(club)\n\ndef write_csv(rows, file_name):\n \"\"\"Write an iterable of rows to the CSV file file_name.\"\"\"\n with open(file_name, \"w\") as csv_file:\n writer = csv.writer(csv_file)\n writer.writerows(rows)\n\nif __name__ == \"__main__\":\n url = \"https://www.bundesliga.com/de/bundesliga/tabelle\"\n rows = list(get_table(url))\n for row in rows:\n print(\" \".join(map(str, row)))\n header = [\"Rank\", \"Team\", \"Matches\", \"Points\", \"Goal Difference\"]\n write_csv(chain(header, rows), \"bundesliga_table.csv\")\n</code></pre>\n\n<p>Note that I used a <a href=\"http://stackoverflow.com/questions/419163/what-does-if-name-main-do\"><code>if __name__ == \"__main__\":</code> guard</a> to allow importing from this script from another script without the scraping being run. The <code>get_table</code> function returns a <a href=\"https://wiki.python.org/moin/Generators\" rel=\"nofollow noreferrer\">generator</a>, which you can just iterate over and it produces the values as it goes. But since we need the content both for printing and for writing, we need to persist it using <code>list</code>. It also has a <code>r.raise_for_status</code>, which will raise an exception if getting the webpage failed for whatever reason, which means you know right away that you are not connected to the internet and not only when it cannot parse the (not-existing) website.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-02T12:23:51.700", "Id": "239797", "ParentId": "239788", "Score": "0" } }, { "body": "<p>Great answers, as always.\nJust a few remarks from me:</p>\n\n<p>There is not enough validation in your project.\nYou are scraping a website that could change at any time, and your script is expecting DOM elements that may not be there. So you need to check each of them.</p>\n\n<p>From the <a href=\"https://www.crummy.com/software/BeautifulSoup/bs4/doc/#find\" rel=\"nofollow noreferrer\">doc</a> (emphasis is mine):</p>\n\n<blockquote>\n <p>If find_all() can’t find anything, it returns an <strong>empty list</strong>. If find()\n can’t find anything, it returns <strong>None</strong></p>\n</blockquote>\n\n<p>To avoid <strong>repetition</strong>, instead of repeatedly calling <code>club.find</code> (even if it's just a few times), you could have a <strong>for loop</strong>, using a list or dictionary containing the DOM elements being sought and the matching HTML attribute. Then you validate the existence of the element and extract the text value in the same pass. Thus, your code becomes more solid and easier to maintain. On the other hand, you have just 5 elements in this code. But your next project may involve retrieving a lot more.</p>\n\n<p>Your HTTP request can fail too, for lots of reasons like lost connectivity. Then the rest of your code will fail. I suggest to wrap the HTTP request in its own try/catch block and stop execution if it fails. There is no point trying to parse the HTML if it was not retrieved.</p>\n\n<p>It is good to have exception handling in the functions that do specific tasks, but the <strong>main function</strong> should also have its own generic exception handler. Advice: <strong>log</strong> every exception to a file. Especially if the script is going to run unattended.</p>\n\n<p>One last thing: you should always test your code in less than ideal conditions: try to run it against another, arbitrary website, or a domain name that does not even exist, and see how it behaves.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-02T12:55:09.363", "Id": "239800", "ParentId": "239788", "Score": "1" } }, { "body": "<p>I'll go out on a limb and say that there is nothing clearly <em>wrong</em> with this script. As a casual batch file, the only improvement I would suggest using the \"Main Method\" pattern. I've yet to find a clear, focused explanation of both what the pattern is and why one should use it, but <a href=\"https://www.guru99.com/learn-python-main-function-with-examples-understand-main.html\" rel=\"nofollow noreferrer\">this is a good start</a>. </p>\n\n<p>Oh, and while it's good that you're calling <code>csv_file.close()</code>, it's greatly preferred to use <code>with open('filename', 'x') as csv_file:</code> instead.</p>\n\n<p>As for efficiency: There are probably ways you could make this script a little more performant, but for such a simple task it's probably counter-productive. It would be relatively a lot of work, and it would make the script harder to work <em>on</em>, so unless you're scraping huge amounts of data it's probably not worth it.</p>\n\n<p>Within the tools you're already using, one thing that could make this look nicer would be to use <code>csv.DictWriter()</code>, <code>DictWriter.writeheader()</code>, and <code>.writerows()</code>. In order for <code>writerows()</code> to really work well for you, you'll probably want to learn about lists, list comprehensions (and/or <code>map</code>), generators and iterables, and functions. And of course to use <code>DictWriter</code> you'll need to learn about dictionaries. And if you're going to learn about functions, it's a good idea to learn about type hints and type checkers. and so on and so forth!</p>\n\n<p>I wouldn't be here if I could help myself from banging out untested scripts for other people's problems:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>from bs4 import BeautifulSoup\nimport csv\nfrom pprint import pprint\nimport requests\nimport sys\nfrom typing import Dict\n\ndefault_file = \"bundesliga_table.csv\"\ndefault_url = \"https://www.bundesliga.com/de/bundesliga/tabelle\"\nfields_functions = {\n \"Rank\": lambda club_tr: club_tr.find(\"td\", class_=\"rank\").text,\n \"Team\": lambda club_tr: club_tr.find(\"span\", class_=\"d-none d-lg-inline\").text,\n \"Matches\": lambda club_tr: club_tr.find(\"td\", class_=\"matches\").text,\n \"Points\": lambda club_tr: club_tr.find(\"td\", class_=\"pts\").text,\n \"Goal Difference\": lambda club_tr: club_tr.find(\"td\", class_=\"difference\").text\n}\n\ndef main():\n argc = len(sys.argv)\n file = sys.argv[1] if 1 &lt; argc else default_file\n url = sys.argv[2] if 2 &lt; argc else default_url\n scrape_to_file(file, url)\n\ndef scrape_to_file(target_file: str, source_url: str) -&gt; None:\n source = BeautifulSoup(requests.get(source_url).content, \"lxml\")\n data = source.find_all(\"tr\")\n with open(target_file, \"w\", newline='') as csv_file:\n csv_writer = csv.DictWriter(csv_file, fields_functions.keys())\n csv_writer.writeheader()\n csv_writer.writerows(parse(club) for club in data)\n\ndef parse(club_tr) -&gt; Dict[str, str]:\n try:\n parsed = {key: func(club_tr) for key, func in fields_functions.items()}\n pprint(parsed.values())\n return parsed\n except Exception as e:\n pprint(\"Error parsing one row!\")\n pprint(e)\n return {}\n\nif __name__ == \"__main__\":\n main()\n<span class=\"math-container\">```</span>\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-02T13:29:35.740", "Id": "239804", "ParentId": "239788", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-02T09:30:21.753", "Id": "239788", "Score": "1", "Tags": [ "python", "python-3.x", "csv", "web-scraping", "beautifulsoup" ], "Title": "Scraping the Bundesliga table and saving it to CSV" }
239788
<p>I just care if it's any of the common formats so that later when I list all files, for those that are images, I can generate previews based on mime type.</p> <p>So PHP.NET suggest to use <code>exif_imagetype</code> function to check if file is an image. <a href="https://www.php.net/manual/en/function.exif-imagetype.php" rel="nofollow noreferrer">In case of success an integer will be returned indicating one of 18 constants</a>.</p> <p>The check I do is against an <code>UploadedFile</code> so my method is quite simple. As this is code review. Would you optimize my code to be even better? Thanks for any hints.</p> <pre><code>/** * @link https://www.php.net/manual/en/function.exif-imagetype.php * * @param UploadedFile $file * @return bool */ private function isFileImage(UploadedFile $file): bool { $result = exif_imagetype($file-&gt;getRealPath()); return is_int($result) &amp;&amp; $result &gt;= 1 &amp;&amp; $result &lt;= 18; } </code></pre> <p><a href="https://i.stack.imgur.com/MyEI7.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/MyEI7.png" alt="enter image description here"></a></p>
[]
[ { "body": "<p>The method in question does not use <code>$this</code> therefore you might consider making it static.</p>\n\n<p>Further it is a private method, i dont know of which class, but consider making it a public method of its own class.</p>\n\n<p>The method accepts UploadedFile but it is only interested in the real path. As long as you keep it private it could be ok and simpler to call, but if you ever make it public (as suggested above), you should let it accept string path instead, that way it will be more flexible.</p>\n\n<p>There are 18 constants for the image types, but you are using hardcoded numbers. What If another type is added in the future? Do you want to have to modify your code? Check the exif_ imagetype return value doc. It will never return int that is not one of the constants. <code>return is_int($result);</code> is absolutely enough.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-02T10:24:39.473", "Id": "239791", "ParentId": "239789", "Score": "2" } }, { "body": "<p>I agree with the advice in <a href=\"https://codereview.stackexchange.com/q/239789/120114\">slepic's answer</a>.</p>\n\n<p>If you want to merely ensure that the file is an image, then you could ensure that the return value of <code>exif_imagetype</code> is not <code>FALSE</code>:</p>\n\n<pre><code>return exif_imagetype($file-&gt;getRealPath()) !== FALSE;\n</code></pre>\n\n<p>That way if more constants are ever added to the list of <code>IMAGETYPE_*</code> constants you would not need to update the conditionals in this method.</p>\n\n<hr>\n\n<p>Curiosity got the better of me and I did a quick search online, finding <a href=\"https://stackoverflow.com/q/15408125/1575353\">this SO post</a>. The <a href=\"https://stackoverflow.com/a/15408176/1575353\">accepted answer</a> suggests using <a href=\"http://php.net/manual/en/function.mime-content-type.php\" rel=\"nofollow noreferrer\"><code>mime_content_type()</code></a> or <a href=\"https://www.php.net/manual/en/function.finfo-file.php\" rel=\"nofollow noreferrer\"><code>finfo_open()</code></a> depending on the PHP version used, though with those approaches you would likely need to utilize a string function to check that the mime type contains <code>'image'</code>, which seems to be slower than just calling the <code>exif_imagetype()</code> function in my local testing. </p>\n\n<p>It also mentions that <code>exif_imagetype</code> is an alternative but relies on having the appropriate libraries enabled (which you presumably do) and only returns image mimetypes. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-02T19:01:09.347", "Id": "239824", "ParentId": "239789", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-02T09:38:35.653", "Id": "239789", "Score": "1", "Tags": [ "php", "file-system" ], "Title": "PHP 7.3.9: Check if uploaded file is an image (I don't care about the format)" }
239789
<p>My task is to run a subprocess using <code>asyncio.create_subprocess_shell</code> and yield the lines of output. I am using <code>asyncio</code> to avoid creating threads just to pump the streams.</p> <ul> <li>It is necessary to separate stdout lines from stderr lines.</li> <li>Both outputs need to be read simultaneously, it is not possible to read all of stdout or stderr first, because then the other output buffer in the subprocess may fill and it would stop running.</li> <li>This function is incorporated into a gRPC service, which is the reason for wrapping the yielded lines in instances of <code>cli_pb2.ExecuteReply(...)</code></li> <li><code>.readline()</code> returns "" on EOF, so when I see it, that is when to stop reading that stream.</li> </ul> <p>I want to ask if my approach to reading stdout and stderr simultaneously can be improved. I was looking for something akin to UNIX select() and found <code>asyncio.wait({...}, return_when=asyncio.FIRST_COMPLETED)</code>. Then I had to figure out which stream (stdout, stderr) the result corresponds to. I hacked at it by looking at <code>_coro</code>.</p> <pre class="lang-py prettyprint-override"><code>import asyncio import cli_pb2 import cli_pb2_grpc async def run(cmd): proc = await asyncio.create_subprocess_shell( cmd, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE, ) stderr_readline = proc.stderr.readline() stdout_readline = proc.stdout.readline() pending = {stderr_readline, stdout_readline} while pending: done, pending = await asyncio.wait(pending, return_when=asyncio.FIRST_COMPLETED) for f in done: line = (await f).decode() if f._coro is stderr_readline: # bad, but it works and can't think of better approach if line: yield cli_pb2.ExecuteReply(stderr=line) stderr_readline = proc.stderr.readline() pending.add(stderr_readline) # put it back into the `pending` set if f._coro is stdout_readline: if line: print(line) yield cli_pb2.ExecuteReply(stdout=line) stdout_readline = proc.stdout.readline() pending.add(stdout_readline) await proc.wait() status = proc.returncode yield cli_pb2.ExecuteReply(status=status) </code></pre> <p>Usage example</p> <pre class="lang-py prettyprint-override"><code>async def printlines(): async for line in run("echo a; sleep 5; echo b; echo c"): print(line) </code></pre> <p>outputs (with a 5 second pause after first line</p> <pre><code>stdout: "a\n" stdout: "b\n" stdout: "c\n" </code></pre> <p>The protobuf definition is</p> <pre><code>syntax = "proto3"; option java_multiple_files = true; option java_package = "djtests.cli"; option java_outer_classname = "CliProto"; package cli; service Executor { rpc Execute (ExecuteRequest) returns (stream ExecuteReply) { }; } message ExecuteRequest { string cmd = 1; } message ExecuteReply { oneof reply_fields { string stdout = 1; string stderr = 2; int32 status = 3; // sent in the last message } } <span class="math-container">```</span> </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-02T11:09:29.900", "Id": "470402", "Score": "0", "body": "Example of a solution using threaded approach, which I wanted to avoid, is https://codereview.stackexchange.com/questions/6567/redirecting-subprocesses-output-stdout-and-stderr-to-the-logging-module" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-28T11:02:35.783", "Id": "473603", "Score": "0", "body": "Advice on how to better associate the returned line with its source (stdout or stderr), https://stackoverflow.com/questions/34509586/how-to-know-which-coroutines-were-done-with-asyncio-wait" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-02T10:21:15.210", "Id": "239790", "Score": "1", "Tags": [ "python", "python-3.x", "async-await", "child-process", "grpc" ], "Title": "Execute command using `asyncio.create_subprocess_shell` and yield lines of stdout, stderr and finally the return code" }
239790
<p>I've written a function to copy files remote-to-remote using SCP command, paramiko, pexpect, and paramiko-sftp.</p> <p>I want to make my code efficient; I'm new to Python and I don't know how.</p> <p>Here's my logic in 3 steps:</p> <ol> <li>Find checksum of a file by executing <code>cksum</code> command in remote-1.</li> <li>Executing SCP command from my local to copy file remote-1 to remote-2.</li> <li>Again do checksum and compare both to give status.</li> </ol> <p></p> <pre><code>class remote_file_operations(): """ Class which supports remote file operations """ def __init__(self, host=None, username=None, password=None, port=22): """ *Method description :* Initialize and setup connection :param host: Remote Host :type host: str :param username: Remote Host Username :type username: str :param password: Remote Host password :type password: str :param port: port to connect, default port is 22 :type port: int """ if host and username and password: self.sftp = None self.sftp_open = False self.client = paramiko.client.SSHClient() self.client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) try: self.client.connect(host, port=port, username=username, password=password, timeout=10) except paramiko.ssh_exception.AuthenticationException: sys.exit("[Authentication Error] Please check user: '%s' or password" % username) except TimeoutError: sys.exit("Connection Refused") except socket.gaierror: sys.exit("Host Name: '%s' not found" % host) def _open_sftp_connection(self): """ *Method description :* Opens an SFTP connection if not already open """ if not self.sftp_open: self.sftp = self.client.open_sftp() self.sftp_open = True return self.sftp_open @staticmethod def file_check_sum(user, host, password, file_paths): """ *Method description :* Give check sum value by cksum command in remote. :param user: username :type user: str :param host: hostname :type host: str :param password: password :type password: str :param file_paths: list of file paths :type file_paths: list :return check_sum: dict with key as filename and value as checksum :type check_sum: dict """ status = True logger.console("Finding checksum ...") check_sum = dict() rmt_ses = remote_file_operations(host, user, password) for file_path in file_paths: _, stdout, stderr = rmt_ses.client.exec_command("ls %s" % file_path.replace("\\", "")) if b"No such file or directory" not in stderr.read(): for abs_file_path in stdout: cmd = "cksum %s" % abs_file_path.replace("\n", "").replace("\r", "") (_, stdout, stderr) = rmt_ses.client.exec_command(cmd) sum_line = stdout.read().decode("utf-8").replace(abs_file_path, "") file_name = abs_file_path.split("/")[-1] check_sum[file_name] = sum_line.replace("\n", "").strip() logger.console(check_sum) else: logger.error("File doesn't exist: %s:%s" % (host, file_path)) status = False rmt_ses.client.close() return status, check_sum @staticmethod def scp_remote_remote(host_1, user_1, password_1, host_2, user_2, password_2, src, dest): #pylint: disable=too-many-arguments,try-except-raise,too-many-locals,too-many-branches """ *Method description :* SCP files from one remote to another remote :param host_1: Remote host-1 :type host_1: str :param user_1: Remote user-1 :type user_1: str :param password_1: Remote Host-1 password :type password_1: str :param host_2: Remote host-2 :type host_2: str :param user_2: Remote user-2 :type user_2: str :param password_2: Remote Host-2 password :type password_2: str :param src: Source dir/file :type src: str :param dest: Destination dir/file :type dest: str :return output: Output generated while scp :type output: list """ exp_pwd_2, status, output = None, False, list() check, src_check_sum = remote_file_operations.file_check_sum(user_1, host_1, password_1, [src]) if check: command = "scp -r %s@%s:%s %s@%s:%s" % (user_1, host_1, src, user_2, host_2, dest) logger.console("Executing: %s" % command) try: child = pexpect.spawn(command, timeout=COPY_TIMEOUT) logger.console("Please wait while copying files from %s to %s ..." % (host_1, host_2)) exp_pwd_1 = child.expect(["password:", "want to continue connecting"], timeout=10) if exp_pwd_1 == 0: child.sendline(password_1) elif exp_pwd_1 == 1: child.sendline("yes") child.sendline(password_1) exp_pwd_2 = child.expect(["password:", "want to continue connecting"], timeout=10) if exp_pwd_2 == 0: child.sendline(password_2) elif exp_pwd_2 == 1: child.sendline("yes") child.sendline(password_2) child.expect(pexpect.EOF) for line in child.before.decode("utf-8").split("\r\n"): for sub_line in line.replace("\r", " ").split("ETA"): logger.console(sub_line) logger.console("\n") output.append(line.replace("\r", " ")) msg = "scp: %s: " % dest if msg + "Permission denied" in output or msg + "No such file or directory" in output: logger.error("Please check the dest path: '%s' exists or have access" % dest) elif "scp: /ome/virtuora: No such file or directory" % dest in output: logger.error("Please check the dest path: '%s' exists or have access" % dest) else: status = True except pexpect.exceptions.TIMEOUT: if "Permission denied" in child.before.decode("utf-8") or "password:"\ in child.before.decode("utf-8"): logger.error("Please check the username or password") except pexpect.exceptions.EOF: if "ld not resolve hostname" in child.before.decode("utf-8"): logger.error("Please check the Hostnames: '%s', '%s'" % (host_1, host_2)) if status: logger.console(src_check_sum) dst_file = [dest + "/" + src.split("/")[-1]] status, dst_check_sum = remote_file_operations.file_check_sum(user_2, host_2, password_2, dst_file) if status: for src_file, src_check in src_check_sum.items(): for dst_file, dst_check in dst_check_sum.items(): if src_file == dst_file and src_check == dst_check: logger.console("%s Transfered Successfully" % (src_file)) status = True else: logger.console("Something went wrong in file transferring") return status, output </code></pre>
[]
[ { "body": "<h2>Type hints</h2>\n\n<p>Move your type documentation:</p>\n\n<pre><code> :type host: str\n</code></pre>\n\n<p>to actual type hints:</p>\n\n<pre><code>def __init__(self, host: Optional[str]=None, username: Optional[str]=None, password: Optional[str]=None, port: int=22):\n</code></pre>\n\n<h2>String interpolation</h2>\n\n<pre><code> sys.exit(\"Host Name: '%s' not found\" % host)\n</code></pre>\n\n<p>can be</p>\n\n<pre><code> sys.exit(f\"Host Name: '{host}' not found\")\n</code></pre>\n\n<h2>Object closure</h2>\n\n<pre><code> rmt_ses = remote_file_operations(host, user, password)\n # ...\n rmt_ses.client.close()\n</code></pre>\n\n<p>So a few things. <code>remote_file_operations</code> should be <code>RemoteFileOperations</code> since it's a class. Also, it's not clear to me that this <code>file_check_sum</code> method should be a <code>static</code> on the class - it makes just as much sense for it to be a function in global scope.</p>\n\n<p>Also, reaching into the object to <code>client.close()</code> is poor coupling; the class should be turned into a context manager whose <code>__exit__</code> calls its <code>client.close()</code>. Then, <code>file_check_sum</code> would use <code>RemoteFileOperations</code> in a <code>with</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-06T15:23:13.447", "Id": "240057", "ParentId": "239792", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-02T10:48:37.850", "Id": "239792", "Score": "5", "Tags": [ "python", "python-3.x" ], "Title": "Remote to remote copying of files" }
239792
<p>For my CS minor I was assigned to implement the Quicksort algorithm in C#. I gave it a go and found that I like the implementation of the algorithm more than Mergesort. Now that I've got my Quicksort implementation running, I'm very curious about what optimizations could be done.</p> <pre class="lang-csharp prettyprint-override"><code>using System.Collections.Generic; namespace Assignment { public class QuickSort { public void Sort(List&lt;int&gt; list) { if (list.Count &lt;= 1) { return; } int pivot = MedianOfThree(list); int equalElementCount = 0; List&lt;int&gt; smaller = new List&lt;int&gt;(); List&lt;int&gt; bigger = new List&lt;int&gt;(); for (int i = 0; i &lt; list.Count; i++) { if (list[i] == pivot) { equalElementCount++; } else if (list[i] &lt; pivot) { smaller.Add(list[i]); } else { bigger.Add(list[i]); } } Sort(smaller); Sort(bigger); int pointer = 0; for (int i = 0; i &lt; smaller.Count; i++) { list[pointer++] = smaller[i]; } for (int i = 0; i &lt; equalElementCount; i++) { list[pointer++] = pivot; } for (int i = 0; i &lt; bigger.Count; i++) { list[pointer++] = bigger[i]; } } private int MedianOfThree(List&lt;int&gt; list) { int firstElement = list[0]; int middleElement = list[list.Count / 2]; int lastElement = list[list.Count - 1]; if ((firstElement &gt; middleElement) != (firstElement &gt; lastElement)) { return firstElement; } else if ((middleElement &gt; firstElement) != (middleElement &gt; lastElement)) { return middleElement; } else { return lastElement; } } } } </code></pre>
[]
[ { "body": "<p>Over the years I have seen other students here and they are quite proud of the performance of their code. In some of those past instances I have discovered that they had simply run their code and thought it was fast. They did not compare it to other methods. </p>\n\n<p>You don't mention any testing or provide any numbers. If you were to do this, just be sure that (1) your code is a Release build and not a Debug, and (2) that you do have disabled \"Prefer 32-bit\" for Build.</p>\n\n<p>The biggest thing that strikes me about your implementation versus others I have seen is that you make 2 lists (<code>smaller</code> and <code>bigger</code>) per invocation whereas other implementations perform an in-place sort on the list or array.</p>\n\n<p><em>Does this matter?</em></p>\n\n<p><strong>YES</strong>. Performance is significantly faster when performing in-place sorting using the one list.</p>\n\n<p>I wrote a sample for you. I have decide not to post my code here because you are a CS student and your namespace is <code>Assignment</code> which tells me this is classwork. It would be unethical of me to write this code for you. What I will do instead you point you to the resources I used, and show my performance timings.</p>\n\n<p>My reference was <a href=\"https://en.wikipedia.org/wiki/Quicksort\" rel=\"nofollow noreferrer\">Wikipedia Quicksort</a>. In particular I used the <strong>Hoare partition scheme</strong>. I translated the psuedocode to C#.</p>\n\n<p>I will share key method signatures. Yes, plural.</p>\n\n<pre><code>public static void Sort2(List&lt;int&gt; list) =&gt; Sort2(list, 0, list.Count - 1);\n\nprivate static void Sort2(List&lt;int&gt; list, int lowIndex, int highIndex)\n{\n // Good luck on your assignment!\n}\n</code></pre>\n\n<p>I also had a <code>Partition</code> and <code>Swap</code> method. I leave it to you to decide whether these should be <code>public</code> or <code>private</code> and what they do.</p>\n\n<p><strong>PERFORMANCE</strong></p>\n\n<ul>\n<li><p>Size of list: 10_000</p></li>\n<li><p>Number of trials: 10_000</p></li>\n<li><p>Original QuickSort ElapsedTicks: 117_816_477</p></li>\n<li><p>In-place QuickSort ElapsedTicks: 50_171_790</p></li>\n</ul>\n\n<p>Which means your original is 2.3 times slower than my in-place sorting.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-03T20:45:03.183", "Id": "239890", "ParentId": "239794", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-02T11:41:50.370", "Id": "239794", "Score": "3", "Tags": [ "c#", "sorting", "homework", "quick-sort" ], "Title": "C# Quicksort Assignment" }
239794
<p>The find function is designed to start at the given node and return the index of the node with the value valueInput (indices start at 0). Return -1 if valueInput does not exist. How can this code be improved, optimized and free of potential runtime errors? Please note I am new to data structures and algorithms.</p> <pre><code>#include &lt;iostream&gt; class Node { public: int value; Node* next = NULL; }; void push(struct Node** head_ref, int new_data) { /* allocate node */ struct Node* new_node = (struct Node*) malloc(sizeof(struct Node)); /* put in the data */ new_node-&gt;value = new_data; /* link the old list off the new node */ new_node-&gt;next = (*head_ref); /* move the head to point to the new node */ (*head_ref) = new_node; } int find(struct Node *head, int n) { int count = 1; //if count equal too n return node-&gt;data if(count == n) return head-&gt;value; //recursively decrease n and increase // head to next pointer return find(head-&gt;next, n-1); } int main() { struct Node* head = NULL; push(&amp;head, 1); push(&amp;head, 4); push(&amp;head, 1); push(&amp;head, 12); push(&amp;head, 1); printf("Element at index 3 is %d", find(head, 3)); getchar(); return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-02T20:08:24.940", "Id": "470442", "Score": "0", "body": "Not sure why somebody voted it down. Seems like a fine question +1" } ]
[ { "body": "<h3>1. You never check if <code>head</code> was assigned a valid pointer before dereferencing it here:</h3>\n\n<pre><code>int find(struct Node *head, int n) \n{ \n int count = 1; \n\n //if count equal too n return node-&gt;data \n if(count == n) \n return head-&gt;value; // &lt;--- here\n\n //recursively decrease n and increase \n // head to next pointer \n return find(head-&gt;next, n-1); // &lt;--- here \n} \n</code></pre>\n\n<h3>2. Why are you using <code>malloc</code> in c++ code?</h3>\n\n<pre><code> (struct Node*) malloc(sizeof(struct Node));\n</code></pre>\n\n<h3>3. Missing functions from your stack interface</h3>\n\n<p>Where are the functions like <code>pop()</code> and an appropriate destructor to free memory, and remove single nodes from the stack?</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-02T15:06:28.827", "Id": "239806", "ParentId": "239801", "Score": "1" } }, { "body": "<h2>Overall</h2>\n\n<p>You don't use encapsulation. Which makes your list vulnerable to incorrect initialization and accidental incorrect modification from outside the list.</p>\n\n<p>You use several C based style choice rather than C++ style which make your codde harder to read.</p>\n\n<h2>Code Review</h2>\n\n<p>Only a list of <code>int</code>?</p>\n\n<pre><code>class Node {\n public:\n int value; // int only\n Node* next = NULL;\n};\n</code></pre>\n\n<hr>\n\n<p>Passing a pointer to a pointer. You can simplify this by passing a reference.</p>\n\n<pre><code>void push(struct Node** head_ref, int new_data) \n</code></pre>\n\n<hr>\n\n<p>In C++ you don't need to use struct keyword when using struct types.</p>\n\n<pre><code>void push(struct Node** head_ref, int new_data) \n</code></pre>\n\n<hr>\n\n<p>A better declaration would have been:</p>\n\n<pre><code>void push(Node*&amp; head_ref, int new_data) \n</code></pre>\n\n<hr>\n\n<p>C++ you should always use new (rather than the malloc family).</p>\n\n<pre><code> /* allocate node */\n struct Node* new_node = \n (struct Node*) malloc(sizeof(struct Node)); \n</code></pre>\n\n<p>There are two reasons for this:</p>\n\n<ol>\n<li><p>If your code combines both C and C++ memory allocation you need to track which is which and use the correct de-allocation method. Thus it is best to simply use one allocation method then you always know how to deallocate it.</p></li>\n<li><p>Using <code>new</code> calls the constructor to initialize the object.<br>\nRemember this line from your class declaration.</p>\n\n<pre><code> Node* next = NULL;\n</code></pre></li>\n</ol>\n\n<p>This is not going to happen if you call <code>malloc()</code> you must use <code>new</code> to get that to happen.</p>\n\n<ol start=\"3\">\n<li><p>Its also simpler to write:</p>\n\n<pre><code>Node* new_node = new Node{new_data, *head_ref};\n</code></pre></li>\n</ol>\n\n<hr>\n\n<p>Your find returns the <code>nth</code> index of the list. But your index is 1 based. Most C based languages use a zero based index. But if I pass <code>0</code> to <code>find()</code> this function will recurse for ever.</p>\n\n<hr>\n\n<p>In recursive funtions always check for the end of the recursion first. So as the first check in <code>find</code> you should check that the list pointer is not <code>nullptr</code>.</p>\n\n<hr>\n\n<p>This is not modified.</p>\n\n<pre><code> int count = 1; \n</code></pre>\n\n<p>So this should be a <code>constexpt</code>. The whole point of using a named type is to make the code more expressive. A better name would help the code be more expressive.</p>\n\n<hr>\n\n<p>Don't leave redundant code commented out. Delete it.</p>\n\n<pre><code> //if count equal too n return node-&gt;data \n</code></pre>\n\n<p>Source control system allow you to keep older versions of the code around</p>\n\n<p>It is now easy to install git on all machines learn to use it.</p>\n\n<hr>\n\n<p>Use better indentation</p>\n\n<pre><code> if(count == n) \n return head-&gt;value; \n</code></pre>\n\n<hr>\n\n<p>In C++ we use <code>nullptr</code> rather than <code>NULL</code>.</p>\n\n<pre><code> struct Node* head = NULL; \n</code></pre>\n\n<p>The difference is that <code>nullptr</code> is correctly typed as a pointer, while NULL is a macro (bad) for an integer (bad type). Thus you can not incorrectly use <code>nullptr</code> while <code>NULL</code> can be abused.</p>\n\n<hr>\n\n<p>In C++ we use the C++ streams <code>std::cout</code>.</p>\n\n<pre><code> printf(\"Element at index 3 is %d\", find(head, 3)); \n</code></pre>\n\n<p>The C++ streams have a more advanced type checking system that prevents accidents.</p>\n\n<pre><code> std::cout &lt;&lt; \"Element at index 3 is \" &lt;&lt; find(head, 3);\n</code></pre>\n\n<h2>Beter implementation</h2>\n\n<pre><code>template&lt;typename T&gt;\nclass LinkedList\n{\n struct Node {\n T value;\n Node* next;\n };\n Node* root;\n\n public:\n LinkedList()\n : root(nullptr)\n {}\n ~LinkedList() {\n while(root) {\n Node* next = root-&gt;next;\n delete root;\n root = next;\n }\n }\n LinkedList(LinkedList const&amp;) = delete;\n LinkedList&amp; operator=(LinkedList const&amp;) = delete;\n\n void push(T const&amp; new_data) \n {\n root= new Node{new_data, root};\n }\n\n int find(int n) \n { \n Node* result = findElement(root, n);\n if (result == nullptr) {\n throw std::runtime_error(\"message\"); \n }\n return result-&gt;value;\n }\n private:\n Node* findElement(Node* n, int n) {\n if (n == nullptr) {\n return nullptr;\n }\n\n if (n == 0) {\n return n;\n }\n return findElement(n-&gt;next, n-1);\n } \n}\n</code></pre>\n\n<p>Main.cpp</p>\n\n<pre><code>int main() \n{ \n LinkedList&lt;int&gt; list; \n\n list.push(1); \n list.push(4); \n list.push(1); \n list.push(12); \n list.push(1); \n\n std::cout &lt;&lt; \"Element at index 3 is \" &lt;&lt; find(head, 2) &lt;&lt; \"\\n\"; \n getchar(); \n} \n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-02T22:48:50.933", "Id": "470458", "Score": "0", "body": "What would the main function look like in your implementation?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-02T23:03:41.743", "Id": "470460", "Score": "0", "body": "@DarnocEloc Added the main for you." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-02T23:16:35.987", "Id": "470461", "Score": "0", "body": "I want to search/find the element by value and return its index, you’re doing the opposite." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-02T23:47:26.453", "Id": "470462", "Score": "0", "body": "@DarnocEloc I am doing the same as your code above. I am sure you can fix it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-03T03:16:46.587", "Id": "470489", "Score": "0", "body": "Okay, thanks for the thorough explanations, much appreciated." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-02T16:07:43.430", "Id": "239808", "ParentId": "239801", "Score": "3" } } ]
{ "AcceptedAnswerId": "239808", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-02T12:59:29.767", "Id": "239801", "Score": "1", "Tags": [ "c++", "performance", "algorithm", "linked-list" ], "Title": "Find an Element in a Linked List" }
239801
<p>I am trying to make a script that compares 2 .txt files.</p> <p>It works, but I wanted to double-check if there's something I missed about these system calls (since I'm new at this). Is there any improvement you would've done or anything else you think can help me improve with it (especially with this <code>mmap</code> thing)?</p> <p>The script returns 2 if it's the same file and 1 otherwise.</p> <pre><code>#include&lt;sys/stat.h&gt; #include&lt;unistd.h&gt; #include&lt;stdio.h&gt; #include&lt;stdlib.h&gt; #include &lt;sys/mman.h&gt; #include &lt;sys/types.h&gt; #include &lt;sys/stat.h&gt; #include &lt;fcntl.h&gt; int main(int argc , char * argv[]) { if(argc != 3) { printf("something wrong with variables\n"); exit(-1); } char* filename1 = argv[1]; char* filename2 = argv[2]; char* addr1; char* addr2; struct stat stat_p1; struct stat stat_p2; int fileSize1=0,fileSize2=0; if(stat(filename1,&amp;stat_p1) == -1) { printf("error occurred while attempting to stat %s\n" , filename1); exit(-2); } if(stat(filename2,&amp;stat_p2) == -1) { printf("error occurred while attempting to stat %s\n" , filename2); exit(-2); } if((fileSize1=stat_p1.st_size) != (fileSize2=stat_p2.st_size)) //checks if the size is different than its not the same file. { return 1; } else { int fd1,fd2; if((fd1 = open(filename1 ,O_RDONLY)) &lt; 0) { printf("error opening file %s\n",filename1); exit(-3); } if((fd2 = open(filename2 ,O_RDONLY)) &lt; 0) { printf("error opening file %s\n",filename2); exit(-3); } addr1 = mmap(NULL, fileSize1+ 1, PROT_READ,MAP_PRIVATE, fd1, 0); if (addr1 == MAP_FAILED) { printf("mmap failed\n"); exit(-4); } addr2 = mmap(NULL, fileSize2+ 1, PROT_READ,MAP_PRIVATE, fd2, 0); if (addr2 == MAP_FAILED) { printf("mmap failed\n"); exit(-4); } for(int i=0;i&lt;fileSize1+1;i++) { if(addr1[i] != addr2[i]) { return 1; } } close(fd1); close(fd2); } return 2; } </code></pre> <p>(It's in the main file because it's meant to be used as part of testing program later.)</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-02T18:36:27.153", "Id": "470433", "Score": "1", "body": "Use `memcmp(addr1, addr2, filesize1)` instead of rolling your own loop. Also, why the `+ 1` to the file sizes?" } ]
[ { "body": "<p>Here are some things that may help you improve your program.</p>\n\n<h2>Use standard library calls where appropriate</h2>\n\n<p>Instead of your <code>for</code> loop, I would recommend using <code>memcmp()</code> to accomplish the same thing, but likely more efficiently since the library version typically compares more than one byte at a time.</p>\n\n<h2>Define variables where they are declared</h2>\n\n<p>The <code>addr1</code> and <code>addr2</code> variables are only used within the <code>else</code> clause, so instead of having them at the top (and uninitialized), it's probably better to declare and initialize the variable at the same time:</p>\n\n<pre><code>char *addr1 = mmap(NULL, fileSize1+ 1, PROT_READ,MAP_PRIVATE, fd1, 0);\n</code></pre>\n\n<h2>Eliminate \"magic numbers\"</h2>\n\n<p>Things like the <code>0</code> in the code line quoted above are OK, because programmers reading this will know what that code is doing. However, when you write <code>exit(-3);</code> it's not at all obvious whether -3 is the correct value, or exactly what it represents. Better would be to use a named <code>const</code> value there such as <code>const int ERROR_FILE_OPEN = -3;</code></p>\n\n<h2>Consider explicitly releasing all resources</h2>\n\n<p>It's true that an <code>mmap</code> will automatically be released when the program terminates, but you may wish to explicitly call <code>mmunmap</code> explicitly before closiing the files. Note that just closing the files does not release the memory.</p>\n\n<h2>Be aware of possible race conditions</h2>\n\n<p>It's admittedly unlikely, but it's possible that a file could be modified between your call to <code>stat</code> and the <code>open</code> call. If it were, for example, a log file, the actual file would be longer than the <code>mmap</code> region. You may find it an acceptable risk, but it's worth knowing about this potential problem.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-02T18:08:52.667", "Id": "470426", "Score": "0", "body": "thanks ! ill go over the things you mentioned" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-02T17:45:30.857", "Id": "239816", "ParentId": "239814", "Score": "1" } }, { "body": "<p>A few things I noticed:</p>\n\n<ul>\n<li>You have a double include of <code>sys/stat.h</code></li>\n<li>When checking through value of <code>argc</code>, instead of saying “Something wrong with variables”, it would be better to print a notice that the user gave the wrong number of arguments, along with a small usage statement. There’s also an error code for that case, I believe.</li>\n<li>You set the file size variables as an <code>int</code>, but I would bet that <code>st_size</code> returns a <code>size_t</code> or at least an unsigned value, I’d suggest checking the man page and changing that declaration </li>\n<li>In the conditional branch where the file sizes are different is followed, it might be nice to print a message saying that the file sizes are different </li>\n<li>Many of the functions you call( <code>stat</code>, <code>fopen</code>,etc...) set <code>errno</code> on failure. It might be nice if when you handle those errors, you printed out the error with <code>strerror(errno)</code> so the user has a better understanding of the error (make sure to include <code>errno.h</code>)</li>\n<li>At the end of your program, it is assumed the files are equal, change <code>return 2</code> to <code>return EXIT_SUCCESS</code></li>\n<li>None of these are fatal, but worth considering for quality.</li>\n</ul>\n\n<p>So now that I have torn apart your code:\nIt looks good, the formatting was clear for me to read. I couldn’t detect anything concerning other than what was listed. The best thing I can think to do moving on would be to run <code>valgrind</code> on it, run through it with a debugger and do a bunch of tests.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-02T18:09:25.827", "Id": "470427", "Score": "0", "body": "sure ill go over it , thank you very much !" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-04T22:15:17.257", "Id": "470630", "Score": "0", "body": "`.st_size` is `off_t`. [Ref](https://linux.die.net/man/2/stat). It is _signed_. [ref](https://stackoverflow.com/q/9073667/2410359)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-04T22:18:01.270", "Id": "470631", "Score": "0", "body": "Thank you! I don’t use stat often enough to recall by memory." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-02T17:47:00.967", "Id": "239817", "ParentId": "239814", "Score": "1" } }, { "body": "<p><strong>Only for the pedantic</strong></p>\n\n<p>With non-2's complement, the below will compare <code>+0</code> as matching <code>-0</code>.</p>\n\n<pre><code>char* addr1;\nchar* addr2;\n...\nif(addr1[i] != addr2[i]) ... // Oops. +0 == -0\n</code></pre>\n\n<p>Instead use <code>unsigned char *</code></p>\n\n<pre><code>unsigned char* addr1;\nunsigned char* addr2;\n...\nif (addr1[i] != addr2[i]) ... // OK. Only one kind of 0\n</code></pre>\n\n<p>Better yet, use <code>memcmp()</code>.</p>\n\n<p><strong>Return values</strong></p>\n\n<p>\"... returns 2 if it's the same file and 1 otherwise.\" --> Not quite.</p>\n\n<p>Code also returns via <code>exit()</code> with other values.</p>\n\n<pre><code>exit(-1);\nexit(-3);\nexit(-4);\n</code></pre>\n\n<p><strong>+ 1??</strong></p>\n\n<p>Off by 1. No need for <code>+ 1</code>. <a href=\"https://codereview.stackexchange.com/questions/239814/using-system-calls-to-compare-text-files/239949#comment470433_239814\">G. Sliepen</a>.</p>\n\n<pre><code>// for(int i=0;i&lt;fileSize1+1;i++)\nfor (int i=0; i&lt;fileSize1; i++)\n</code></pre>\n\n<p><strong>Matching type</strong></p>\n\n<p><code>.st_size</code> is typed as <a href=\"https://linux.die.net/man/2/stat\" rel=\"nofollow noreferrer\"><code>off_t</code></a>. I'd expect <code>fileSize1, fileSize2, i</code> as the same.</p>\n\n<pre><code>off_t fileSize1;\n...\nfor (off_t i = 0; i &lt; fileSize1; i++)\n</code></pre>\n\n<p><strong>Big files</strong></p>\n\n<p><code>.st_size</code> is a <code>off_t</code>, some signed type. <code>mmap(void *addr, size_t length, ...)</code> takes a length of <code>size_t</code>, some <em>unsigned</em> type.</p>\n\n<p>To do this right, code may need to call <code>mmap()</code> multiple times as file size can exceed <code>SIZE_MAX</code>.</p>\n\n<p>Something like:</p>\n\n<pre><code>#define CHUNK (‭1048576‬ /* 1 Meg */)\n\noff_t fileSize1;\nfileSize1 = stat_p1.st_size;\n\n....\n\nfor (off_t offset = 0; offset &lt; fileSize1; offset += CHUNK) {\n size_t map_size1 = CHUNK;\n if (fileSize1 - offset &lt; CHUNK) {\n map_size1 = (size_t) (fileSize1 - offset);\n }\n\n addr1 = mmap(NULL, map_size1, PROT_READ,MAP_PRIVATE, fd1, offset);\n\n // as above for map_size1, addr2\n\n for (size_t i = 0; i &lt; map_size1; i++)\n ...\n // or\n if (memcmp(addr1, addr2, map_size1) .... \n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-04T22:24:21.587", "Id": "239949", "ParentId": "239814", "Score": "2" } } ]
{ "AcceptedAnswerId": "239949", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-02T17:20:04.403", "Id": "239814", "Score": "2", "Tags": [ "c" ], "Title": "using system calls to compare text files" }
239814
<p>This is a small program to implement the FVP algorithm (outlined <a href="http://markforster.squarespace.com/blog/2015/5/21/the-final-version-perfected-fvp.html" rel="nofollow noreferrer">here</a>). I'm still quite new to C++ and don't have a strong grasp of basically any concepts. Concepts I tried to use in this program:</p> <ul> <li>OOD</li> <li>Header files</li> <li>Lambda functions</li> <li><code>std::list</code> and <code>std::vector</code></li> </ul> <p>I would be grateful for any suggestions on code style, any bugs you see, and any other advice you might have.</p> <h2>main.cpp</h2> <pre class="lang-cpp prettyprint-override"><code>#include "fvpalgorithm.h" int main() { FVPAlgorithm algorithm; algorithm.run(); } </code></pre> <h2>fvpalgorithm.h</h2> <pre class="lang-cpp prettyprint-override"><code>#pragma once #include &lt;string&gt; // Need strings for Task. #include &lt;vector&gt; // Need to define an object of type vector here, so must include in the .h. #include &lt;list&gt; struct Task { // Need to give Task struct a body in header. std::string taskName; }; class FVPAlgorithm { private: std::list&lt;Task&gt; longList; // List of Tasks std::vector&lt;std::list&lt;Task&gt;::iterator&gt; shortList; // Vector of iterators to tasks in longList void addTasks(); void selectTasks(std::list&lt;Task&gt;::iterator startIterator); void promptToDo(std::list&lt;Task&gt;::iterator task); //std::list&lt;Task&gt;::iterator compareTasks(std::list&lt;Task&gt;::iterator startIterator); public: void run(); void printAllTasks(); void printShortList(); }; </code></pre> <h2>fvpalgorithm.cpp</h2> <pre class="lang-cpp prettyprint-override"><code>#include "fvpalgorithm.h" #include &lt;iostream&gt; /* ----- The algorithm ----- Create a longlist of all tasks. Add the first task to the shortlist. Iterate through each task - ask if user would rather do that than the last task on the shortlist (Which is the first task in the list, in this case) If user says no, go to next task. If user says yes, add task to shortlist. Continue until no tasks left on longlist. Tell user to complete last task added to shortlist. When user has completed last task added to shortlist, remove it from the longlist and begin iterating through longlist again from the index below the task that was just removed. Ask if the user wants to do it more than the last task on the shortlist. If the user decides they want to do the last item on the longlist, then just tell them to do the next task on the shortlist after they finish it (since there are no more tasks on the longlist that they didn't already turn down in favour of the second-last item on the shortlist. Allow for items being added to end of list. ------------------------- */ void FVPAlgorithm::addTasks() { std::cout &lt;&lt; "Please add task names. Enter q to quit adding tasks." &lt;&lt; std::endl; std::string taskInput = ""; while (taskInput != "q") { std::getline(std::cin, taskInput); if (taskInput != "q") { longList.push_back(Task{ taskInput }); std::cout &lt;&lt; "Added task." &lt;&lt; std::endl; } } std::cout &lt;&lt; "\nFinished adding tasks. The following tasks were added:" &lt;&lt; std::endl; printAllTasks(); } void FVPAlgorithm::printAllTasks() { for (std::list&lt;Task&gt;::iterator it = longList.begin(); it != longList.end(); ++it) { std::cout &lt;&lt; it-&gt;taskName &lt;&lt; std::endl; } } void FVPAlgorithm::printShortList() { for (std::vector&lt;std::list&lt;Task&gt;::iterator&gt;::iterator it = shortList.begin(); it != shortList.end(); ++it) { std::cout &lt;&lt; (*it)-&gt;taskName &lt;&lt; std::endl; } } void FVPAlgorithm::selectTasks(std::list&lt;Task&gt;::iterator startIterator) { auto compareTasks = [this](std::list&lt;Task&gt;::iterator it) { std::string shortlistedTaskName = shortList.back()-&gt;taskName; char userChoice = NULL; for (it; it != longList.end(); ++it) { std::cout &lt;&lt; "Would you like to do " &lt;&lt; it-&gt;taskName &lt;&lt; " more than " &lt;&lt; shortlistedTaskName &lt;&lt; "? (Y/N)" &lt;&lt; std::endl; std::cin &gt;&gt; userChoice; while (true) { if (userChoice == 'Y' || userChoice == 'y') { // User wants to do this task more than the current leader. shortList.push_back(it); // Add this task to the end of the shortlist. return it; // Returns the task we stopped on. } else if (userChoice == 'N' || userChoice == 'n') { break; } // User doesn't want to, move on. else std::cout &lt;&lt; "Please enter Y or N." &lt;&lt; std::endl; break; } userChoice = NULL; } return it; }; std::list&lt;Task&gt;::iterator latestTaskChecked = compareTasks(std::next(startIterator, 1)); // longList.begin() is the first element of the vector, and then increments by 1, for second element. while (latestTaskChecked != longList.end()) { // If we didn't go through all of the tasks the first time, latestTaskChecked = compareTasks(++latestTaskChecked); // Start comparing again from the next task after the one we stopped at. } } void FVPAlgorithm::promptToDo(std::list&lt;Task&gt;::iterator task) { // Instruct user to do the given task. std::cout &lt;&lt; "You should do " &lt;&lt; task-&gt;taskName &lt;&lt; ". Enter anything when done." &lt;&lt; std::endl; std::string doneTask; std::cin &gt;&gt; doneTask; std::cout &lt;&lt; "Good job!" &lt;&lt; std::endl; } void FVPAlgorithm::run() { // Add tasks to the longlist. addTasks(); // Begin algorithm loop. while (!longList.empty()) { // While we still have tasks left to do, if (shortList.empty()) { // If we have nothing on the shortlist, shortList.push_back(longList.begin()); // Add the first task to the shortlist selectTasks(shortList.back()); // Add any more tasks the user would like, after the last item in shortList. promptToDo(shortList.back()); } if (&amp;*shortList.back() != &amp;longList.back()) { // If last item in shortlist isn't last item in longist, std::list&lt;Task&gt;::iterator lastCompletedTask = shortList.back(); // Make note of the task we just finished, shortList.pop_back(); // and delete it from the shortlist. selectTasks(lastCompletedTask); // Compare everything after last task we just finished. longList.erase(lastCompletedTask); // Delete the last completed task. promptToDo(shortList.back()); } else { // The last item in the shortlist is the last item in the longlist, longList.pop_back(); // so pop them both off, shortList.pop_back(); promptToDo(shortList.back()); // and prompt to do next-last task. } } std::cout &lt;&lt; "No tasks remaining!" &lt;&lt; std::endl; } <span class="math-container">```</span> </code></pre>
[]
[ { "body": "<p>Couple of small things:</p>\n\n<p>Use emplace_back rather than push_back when you just have the parameters for the constructors:</p>\n\n<pre><code>longList.push_back(Task{ taskInput });\n\n// This is better written as:\n\nlongList.emplace_back(taskInput);\n</code></pre>\n\n<p>The difference between the two:</p>\n\n<ul>\n<li><p><code>push_back(Task{ taskInput });</code>.<br>\nThis creates a \"<code>Task</code>\" object as an input parameter. It then calls <code>push_back()</code>. If the <code>Task</code> type object is movable (it is) then it is moved into the list otherwise it is copied into the list.</p></li>\n<li><p><code>emplace_back(taskInput);</code><br>\nThis creates an object in place in the list. This means the <code>Task</code> object in the list is created at the point and place it is needed without needing to copy anything.</p></li>\n</ul>\n\n<p>The <code>emplace_back()</code> is preferred (but only very slightly). This is because if the object being put in the container is not movable then it will be copied (copies can be expensive). So it is preferred to create the object in place.</p>\n\n<p>Now. Since the paramer 'taskInput' is never going to be used again we could also use <code>std::move()</code> to move the string to the constructor so potentially avoiding a copy of the string.</p>\n\n<pre><code>longList.emplace_back(std::move(taskInput));\n</code></pre>\n\n<hr>\n\n<p>Prefer the range based for for looping over containers:</p>\n\n<pre><code>for (std::list&lt;Task&gt;::iterator it = longList.begin(); it != longList.end(); ++it) {\n std::cout &lt;&lt; it-&gt;taskName &lt;&lt; std::endl;\n}\n</code></pre>\n\n<p>Can be simplified to:</p>\n\n<pre><code>for (auto const&amp; task: longList) {\n std::cout &lt;&lt; task.taskName &lt;&lt; \"\\n\";\n}\n</code></pre>\n\n<p>So what is happening here?<br>\nThe range based for works with any object that can be used with <code>std::begin(obj)</code> and <code>std::end(obj)</code>. These methods by default simply call the <code>begin/end</code> method on <code>obj</code>.</p>\n\n<p>So:</p>\n\n<pre><code>for (auto const&amp; item: cont) {\n // CODE\n}\n</code></pre>\n\n<p>Can be considered as shorthand for:</p>\n\n<pre><code>{\n auto end = std::end(cont);\n for (auto iter = std::begin(cont); iter != end; ++iter) {\n auto const&amp; item = *iter;\n\n // CODE\n }\n}\n</code></pre>\n\n<hr>\n\n<p>Prefer to use <code>\"\\n\"</code> rather than <code>std::endl</code>.</p>\n\n<p>The difference here is that <code>std::endl</code> flushes the stream (after adding the '\\n') character. It is usually ill advised to manually flush stream (unless you have done the testing). This is because humans are bad at deciding when a stream needs to be flushed and the code will flush the stream if it needs to be flushed automatically.</p>\n\n<p>One of the biggest complaints from beginners about C++ is that <code>std::cout</code> is not as fast as printing to <code>stdcout</code> in C. The main culprit of this is usually down to inappropriate flushing of the std::cout buffer. Once that is fixed the speed of these streams are nearly identical.</p>\n\n<hr>\n\n<p>Don't copy strings if you just need a refeence:</p>\n\n<pre><code> std::string shortlistedTaskName = shortList.back()-&gt;taskName;\n</code></pre>\n\n<p>This copies the string into <code>shortlistedTaskName</code>. If you just need a short reference to the value use a reference.</p>\n\n<pre><code> std::string&amp; shortlistedTaskName = shortList.back()-&gt;taskName;\n // ^^^ This is a reference to the object on the right.\n</code></pre>\n\n<hr>\n\n<pre><code> for (it; it != longList.end(); ++it) {\n ^^ Does nothing.\n\n // write like this.\n for (; it != longList.end(); ++it) {\n</code></pre>\n\n<hr>\n\n<p>Don't use <code>NULL</code>. This is old school C for a <code>null</code> pointer. Unfortunately it is actually the number <code>0</code> and can thus accidentally be assigned to numeric types. Which is confusing as they are not pointers.</p>\n\n<p>In C++ we use <code>nullptr</code> to refer to the <code>null</code> pointer. It can only be assigned to pointer objects and thus is type safe.</p>\n\n<hr>\n\n<p>Don't use <code>NULL</code> to represent nothing.</p>\n\n<pre><code> char userChoice = NULL;\n</code></pre>\n\n<p>That is not a concept in C++. Here <code>userChoice</code> is a variable. It exists and will always have a value. The trouble is that <code>char</code> is a numeric type so assigning <code>NULL</code> too <code>userChouce</code> gave it the integer value of <code>0</code> which is the same as the char value '\\0'.</p>\n\n<p>You can leave it unassigned or put a default value it in. In this context since you are about to read into it I would just leave it unassigned.</p>\n\n<pre><code> char userChoice;\n</code></pre>\n\n<p>As long as you write into it before reading its value everything is OK.</p>\n\n<hr>\n\n<p>Reading from a stream can fail.</p>\n\n<pre><code>std::cin &gt;&gt; userChoice;\n</code></pre>\n\n<p>Reading a stream can fail. Even the std::cin input can get an EOF signal which means nothing more can be read.</p>\n\n<p>So always check the result of the read.</p>\n\n<pre><code>if (std::cin &gt;&gt; userChoice) {\n // Something was successfully read into the character.\n}\n</code></pre>\n\n<hr>\n\n<p>I don't see why you need this loop.</p>\n\n<pre><code> while (true) {\n if (userChoice == 'Y' || userChoice == 'y') {\n return it;\n }\n else if (userChoice == 'N' || userChoice == 'n') {\n break;\n }\n else std::cout &lt;&lt; \"Please enter Y or N.\" &lt;&lt; std::endl;\n break;\n }\n</code></pre>\n\n<p>You could simplify this to:</p>\n\n<pre><code> if (userChoice == 'Y' || userChoice == 'y') {\n return it;\n }\n else if (userChoice != 'N' &amp;&amp; userChoice != 'n') {\n std::cout &lt;&lt; \"Please enter Y or N.\" &lt;&lt; \"\\n\"\n }\n</code></pre>\n\n<hr>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-03T08:48:32.963", "Id": "470508", "Score": "0", "body": "Thank you for the advice! I'll make some changes you recommended. If nobody else submits an answer, or yours is the best, I'll accept yours :)\n\nDo you have any suggestions re: lambda functions? How is the actual structure of the code - is anything redundant or weird?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-02T23:46:11.840", "Id": "239841", "ParentId": "239815", "Score": "4" } }, { "body": "<p>As per signature main function must return int value</p>\n\n<pre><code>#include \"fvpalgorithm.h\"\n\nint main() {\n FVPAlgorithm algorithm;\n algorithm.run();\n}\n</code></pre>\n\n<p><strong>Task Structure</strong>: Why is taskName public? Here taskName looks like task identifier.\n Will this identifier change post creation? Do you intend to support case where\n task is created with name X and then later changed to Y? Better to take name at \n construction time and then provide a task name getter and avoid setter.</p>\n\n<p>If you are aware that task is going to have more attributes apart from name,\n then defining a separate task struct makes sense. But if it is only going to have name,\n and you want to keep your code readable make TaskName an alias for std::string \n (using/typedef) ad get rid of struct completely.</p>\n\n<pre><code>struct Task { // Need to give Task struct a body in header.\n std::string taskName;\n};\n</code></pre>\n\n<p><strong>Class FVPAlgorithm:</strong> This class violates SRP. It has three responsibilities. Read data from cin, Execute FVP algorithm, and Print. So apart from changes in algorithm steps, his class will also have to change if task input method changes (Say rather than cin, you start reading from file, or start consuming task list returned by some other module), or tasks have to be printed to streams other than cout. Also because this class is taking care of input and output, it must take case errors that can happen during input/output.\nSummary: Remove input/output responsibility from this class and let it focus on algorithm implementation and its error cases.</p>\n\n<pre><code>class FVPAlgorithm { \nprivate:\n std::list&lt;Task&gt; longList; // List of Tasks &lt;nkvns&gt;: tasks is better name for this variable\n std::vector&lt;std::list&lt;Task&gt;::iterator&gt; shortList; // Vector of iterators to tasks in longList &lt;nkvns&gt;: selectedTasks is better name for this variable. As per current name, shortList is actually a vector not list.\n\n void addTasks();\n void selectTasks(std::list&lt;Task&gt;::iterator startIterator);\n void promptToDo(std::list&lt;Task&gt;::iterator task);\n //std::list&lt;Task&gt;::iterator compareTasks(std::list&lt;Task&gt;::iterator startIterator);\n\npublic:\n void run();\n&lt;nkvns&gt;: Print* method should be marked const. Print can't change state of the object.\n void printAllTasks(); \n void printShortList();\n};\n</code></pre>\n\n<p><strong>Sanitize input before consumption:</strong> Check/sanitize input before accepting it. User can input garbage string of arbitrary length. You can go out of memory. </p>\n\n<pre><code>if (taskInput != \"q\") {\n longList.push_back(Task{ taskInput });\n std::cout &lt;&lt; \"Added task.\" &lt;&lt; std::endl;\n }\n }\n</code></pre>\n\n<p><strong>Use auto to improve readability:</strong> auto is good way of improving readability. Here you can use auto for iterators like <code>std::list&lt;Task&gt;::iterator</code>. Also loop in print* method is read loops so use cbegin and cend.</p>\n\n<pre><code>void FVPAlgorithm::printAllTasks() { \n for (std::list&lt;Task&gt;::iterator it = longList.begin(); it != longList.end(); ++it) {\n std::cout &lt;&lt; it-&gt;taskName &lt;&lt; std::endl;\n }\n}\n</code></pre>\n\n<p>void FVPAlgorithm::printShortList() {\n for (std::vector::iterator>::iterator it = shortList.begin(); it != shortList.end(); ++it) {\n std::cout &lt;&lt; (*it)->taskName &lt;&lt; std::endl;\n }\n}</p>\n\n<p><strong>CompareTasks lambda</strong>: It is good use of lambda. But given that CompareTasks has many lines of codes, Define TaskComparator separately. You may choose to make it part of Task class itself. A class can provide method for comparison. If you want to have dynamic comparison criteria (Based on task in selection or some other user criteria) use strategy pattern to decide on comparison strategy at run time. </p>\n\n<pre><code>auto compareTasks = [this](std::list&lt;Task&gt;::iterator it) {\n std::string shortlistedTaskName = shortList.back()-&gt;taskName;\n char userChoice = NULL;\n for (it; it != longList.end(); ++it) {\n std::cout &lt;&lt; \"Would you like to do \" &lt;&lt; it-&gt;taskName &lt;&lt; \" more than \" &lt;&lt; shortlistedTaskName &lt;&lt; \"? (Y/N)\" &lt;&lt; std::endl;\n std::cin &gt;&gt; userChoice;\n while (true) {\n if (userChoice == 'Y' || userChoice == 'y') { // User wants to do this task more than the current leader.\n shortList.push_back(it); // Add this task to the end of the shortlist.\n return it; // Returns the task we stopped on.\n }\n else if (userChoice == 'N' || userChoice == 'n') { break; } // User doesn't want to, move on.\n else std::cout &lt;&lt; \"Please enter Y or N.\" &lt;&lt; std::endl; break;\n }\n userChoice = NULL;\n }\n return it;\n };\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-04T17:24:10.213", "Id": "470620", "Score": "1", "body": "Welcome to Code Review. Commenting inline makes this rather confusing." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-05T07:03:31.380", "Id": "470673", "Score": "0", "body": "Updated based on comment from @chicks" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-05T14:08:53.343", "Id": "470704", "Score": "0", "body": "Much improved. Thank you." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-04T14:04:29.820", "Id": "239925", "ParentId": "239815", "Score": "2" } } ]
{ "AcceptedAnswerId": "239841", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-02T17:41:28.497", "Id": "239815", "Score": "3", "Tags": [ "c++", "beginner", "algorithm", "vectors" ], "Title": "Implementation of a Smart To-do List Algorithm" }
239815
<p>I wrote a function that takes as input a vector with two integers between <code>1</code> and <code>8</code> representing a position in a chessboard and that should output a vector where each cell is a similar vector of integers, with the positions that a knight in the input position could reach.</p> <p>E.g. for the input <code>1 1</code>, my function should output <code>[2 3] [3 2]</code> (I'm using the <code>[]</code> to represent the boxes of the cells).</p> <p>This is what I wrote:</p> <pre><code>knight_moves ← { ⍝ Monadic function, expects a vector with 2 integers ⍝ Given a chessboard position, find the legal knight moves signs ← , ∘.,⍨(¯1 1) offsets ← ((⊂⌽),⊂) 2 1 moves ← , signs ∘.× offsets locations ← moves + ⊂⍵ valid ← ^/¨(1∘≤∧≤∘8) locations valid/locations } </code></pre> <p>This works and gives the expected result for a series of test cases. Since I am quite new to APL, I wanted to know what could be written in a cleaner way.</p> <p>This question has been followed-up <a href="https://codereview.stackexchange.com/q/239897/221235">here</a>.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-02T23:02:42.667", "Id": "470459", "Score": "2", "body": "You can say `(2 3)(3 2)` instead of `[2 3] [3 2]` because the former is *the* APL expression that evaluates to the vector of length-2 vectors. Also, it is always good to mention where the problem comes from." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-07T09:00:24.367", "Id": "470909", "Score": "1", "body": "@chux Yes, it is a valid method, and it has been already covered in [one of the reviews](https://codereview.stackexchange.com/a/239843/182436)." } ]
[ { "body": "<h2>Generating possible moves</h2>\n\n<p>Assuming that the order of the elements in the output does not matter (e.g. <code>(2 3)(3 2)</code> and <code>(3 2)(2 3)</code> are equally valid outputs for the input <code>1 1</code>), it suffices to generate <em>some</em> permutation of <code>(1 2)(2 1)(¯1 2)(2 ¯1)(1 ¯2)(¯2 1)(¯1 ¯2)(¯2 ¯1)</code>.</p>\n\n<p>Using the signs-and-offsets method you used, we want the equivalent of</p>\n\n<pre><code>signs ← (1 1)(1 ¯1)(¯1 1)(¯1 ¯1)\noffsets ← (1 2)(2 1)\n</code></pre>\n\n<p>There are multiple ways to generate such arrays. Pick the one that reads the best for you (and, if you're not sure you'll understand the code later, add some comments). Remember, it is always better to write down the raw arrays than to generate them <em>in a way you don't fully understand</em>.</p>\n\n<pre><code>⍝ OP method: self outer product by pairing (,) on ¯1 1\nsigns ← , ∘.,⍨ ¯1 1\n⍝ Example method 1: generate indexes then power of ¯1\nsigns ← , ¯1*⍳2 2\n⍝ Example method 2: just write down the array\nsigns ← (1 1)(1 ¯1)(¯1 1)(¯1 ¯1)\n\n⍝ OP method\noffsets ← ((⊂⌽),⊂) 2 1\n⍝ Example method 1\noffsets ← (⌽¨,⊢) ⊂2 1\n⍝ Example method 2\noffsets ← (1 2)(2 1)\n</code></pre>\n\n<p>Of course, there are still other ways to get the <code>moves</code> array.</p>\n\n<pre><code>⍝ Example method 1: extend a starting array with reversals and negations\n⍝ I did not do \"negation of one element\" because it is hard to express\nmoves ← (⊢,-)(⊢,⌽¨) (1 2)(¯1 2)\n⍝ Or if you insist...\nmoves ← (⊢,-)(⊢,⌽¨)(⊢,-@1¨) ⊂1 2\n\n⍝ Example method 2: generate all moves from ¯2 to 2 in both directions and\n⍝ filter those whose sum of absolute values is 3\n⍝ assuming ⎕IO←1\ntmp ← ,¯3+⍳5 5\nmoves ← ({3=+/|⍵}¨tmp)/tmp\n\n⍝ Example method 3: you can always do this!\nmoves ← (1 2)(2 1)(¯1 2)(2 ¯1)(1 ¯2)(¯2 1)(¯1 ¯2)(¯2 ¯1)\n</code></pre>\n\n<h2>Nitpicking</h2>\n\n<ul>\n<li><code>(¯1 1)</code> at line 4 doesn't need parentheses, because array-forming a.k.a. stranding has higher precedence than function/operator evaluation in APL grammar.</li>\n<li>At line 8, you're using two different symbols <code>^</code> (ASCII caret) and <code>∧</code> (Unicode wedge, or mathematical AND symbol) to indicate the same function \"boolean AND\". While <a href=\"https://aplwiki.com/wiki/Unicode\" rel=\"noreferrer\">APL implementations may accept both</a>, it is not consistent across implementations, so it is advised to always stick to one standard symbol.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-03T22:54:21.570", "Id": "470587", "Score": "1", "body": "Thanks for your good review and great job at noticing the different ^ and ∧, that was unintentional on my part! I'm also commenting here to let you know I wrote a [follow-up review question](https://codereview.stackexchange.com/q/239897/221235) in case you want to stay tuned :)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-02T23:56:10.967", "Id": "239842", "ParentId": "239818", "Score": "7" } }, { "body": "<h2>Initial impression</h2>\n\n<p>Your code is already quite good, using idiomatic APL in short clear lines that each do a single job well. Your variable names are such that you don't really need comments other than the fine description you already have at the top.</p>\n\n<h3>Describe your result</h3>\n\n<p>You might want to add a third comment describing the result structure:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code> ⍝ Returns a vector of 2-element vectors\n</code></pre>\n\n<h3>Remove unnecessary parenthesis</h3>\n\n<p>The vector <code>(¯1 1)</code> could be written as <code>¯1 1</code></p>\n\n<h3>Adopt a naming convension</h3>\n\n<p>Consider a naming convention that makes it easier for the reader to distinguish syntactic classes; mainly variables and functions, but maybe even monadic operators and dyadic operators. One such scheme that some people like is:</p>\n\n<pre><code>variables lowerCamelCase\nFunctions UpperCamelCase\n_Monadic _Operators _UnderscoreUpperCamelCase\n_Dyadic_ _Operators_ _UnderscoreUpperCamelCaseUnderscore_\n</code></pre>\n\n<p>Being that you seem to prefer snake_case: An equivalent such scheme could be used too:</p>\n\n<pre><code>variables lower_snake_case\nFunctions Upper_snake_case\n_Monadic _Operators _Underscore_upper_snake_case\n_Dyadic_ _Operators_ _Underscore_upper_snake_case_underscore_\n</code></pre>\n\n<p>Alternatively, the cases could be swapped: My father used lowercase for functions and uppercase for variables according to the German (and previous Danish) orthography that specifies lowercase verbs and uppercase nouns, and this may also look more natural with things like <code>X f Y</code> rather than <code>x F y</code>.</p>\n\n<p>Interestingly, Stack Exchange's syntax colourer seems to make a distinction between uppercase and lowercase identifiers.</p>\n\n<h3>Consider naming complex functions</h3>\n\n<p>You use two non-trivial trains. Consider giving them meaningful names, which also allows you to remove their parentheses:</p>\n\n<pre><code> Dirs ← (⊂⌽),⊂\n offsets ← Dirs 2 1\n</code></pre>\n\n<pre><code> In_range ← 1∘≤∧≤∘8\n valid ← ^/¨In_range locations\n</code></pre>\n\n<p>This isn't necessarily required in this case, but could be relevant with more involved code.</p>\n\n<h3>Improve performance by keeping arrays flat</h3>\n\n<p>To avoid the overhead of pointer chasing, you can implement your function using only flat arrays, and then, as a finalising step, restructure the data as required. Here is a direct translation of your code to flat-array code:</p>\n\n<pre><code>knight_moves_flat←{\n⍝ Monadic function, expects a vector with 2 integers\n⍝ Given a chessboard position, find the legal knight moves\n⍝ Returns a 2-column table\n signs← ,[⍳2] ,⍤1 0⍤0 1⍨ (¯1 1)\n offsets ← (⌽,[1.5]⊢) 2 1\n moves ← ,[⍳2] signs (×⍤1⍤1 2) offsets\n locations ← moves (+⍤1) ⍵\n valid ← ^/(1∘≤∧≤∘8) locations\n ↓valid⌿locations\n}\n</code></pre>\n\n<p>Compare the performance:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code> ]runtime -compare knight_moves¨all knight_moves_flat¨all\n\n knight_moves¨all → 7.4E¯4 | 0% ⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕ \n knight_moves_flat¨all → 5.0E¯4 | -34% ⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕ \n</code></pre>\n\n<p>The price here is that the code becomes somewhat more involved and less clear.</p>\n\n<p>For an alternative algorithm with even better performance, see Roger Hui's blog post <a href=\"https://www.dyalog.com/blog/2020/02/2019-apl-problem-solving-competition-phase-i-problems-sample-solutions/\" rel=\"noreferrer\">2019 APL Problem Solving Competition: Phase I Problems Sample Solutions</a>.</p>\n\n<h3>Ultimate performance through lookups</h3>\n\n<p>If you need to call the function many (more than 100) times, you can get the ultimate performance by pre-computing all the results (by any means). This is because the input domain is rather limited. With only 64 valid arguments, you pay a 64-fold setup cost, but after that, the only costs will be looking up an argument in a list of valid arguments and then picking the corresponding result from a list of results. However, in this case, where the argument already is a proper argument for <code>⊃</code>, you can simply use the argument directly to pick a result from a vector of vectors of results, thus avoiding even the lookup cost:</p>\n\n<pre><code>all ← ⍳ 8 8\nresults ← ↓knight_moves¨all\nknight_moves_pick ← ⊃∘results\n</code></pre>\n\n<p>Throughput increases with almost two orders of magnitude compared to the <em>flat</em> edition:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code> ]runtime -c knight_moves_flat¨all knight_moves_pick¨all\n\n knight_moves_flat¨all → 4.4E¯4 | 0% ⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕ \n knight_moves_pick¨all → 5.2E¯6 | -99% \n</code></pre>\n\n<p>Since the result-picking is almost free in comparison to actually computing each result, the setup cost is paid off after less than 100 applications, and is certainly negligible in the above comparison where each expression is run well over 10000 (100<sup>2</sup>) times. Instead, you pay though additional storage space being required:</p>\n\n<pre><code> (⍪,⎕SIZE)⎕NL 3\nknight_moves 2800\nknight_moves_flat 3512\nknight_moves_pick 19088\n</code></pre>\n\n<p>The fully expanded text representation of the function is also unreadable:</p>\n\n<pre><code>knight_moves_pick ← ⊃∘(((2 3)(3 2))((3 1)(2 4)(3 3))((2 1)(3 2)(2 5)(3 4))((2 2)(3 3)(2 6)(3 5))((2 3)(3 4)(2 7)(3 6))((2 4)(3 5)(2 8)(3 7))((2 5)(3 6)(3 8))((2 6)(3 7)))(((1 3)(3 3)(4 2))((1 4)(4 1)(3 4)(4 3))((1 1)(1 5)(3 1)(4 2)(3 5)(4 4))((1 2)(1 6)(3 2)(4 3)(3 6)(4 5))((1 3)(1 7)(3 3)(4 4)(3 7)(4 6))((1 4)(1 8)(3 4)(4 5)(3 8)(4 7))((1 5)(3 5)(4 6)(4 8))((1 6)(3 6)(4 7)))(((2 3)(1 2)(4 3)(5 2))((1 1)(2 4)(1 3)(5 1)(4 4)(5 3))((2 1)(1 2)(2 5)(1 4)(4 1)(5 2)(4 5)(5 4))((2 2)(1 3)(2 6)(1 5)(4 2)(5 3)(4 6)(5 5))((2 3)(1 4)(2 7)(1 6)(4 3)(5 4)(4 7)(5 6))((2 4)(1 5)(2 8)(1 7)(4 4)(5 5)(4 8)(5 7))((2 5)(1 6)(1 8)(4 5)(5 6)(5 8))((2 6)(1 7)(4 6)(5 7)))(((3 3)(2 2)(5 3)(6 2))((2 1)(3 4)(2 3)(6 1)(5 4)(6 3))((3 1)(2 2)(3 5)(2 4)(5 1)(6 2)(5 5)(6 4))((3 2)(2 3)(3 6)(2 5)(5 2)(6 3)(5 6)(6 5))((3 3)(2 4)(3 7)(2 6)(5 3)(6 4)(5 7)(6 6))((3 4)(2 5)(3 8)(2 7)(5 4)(6 5)(5 8)(6 7))((3 5)(2 6)(2 8)(5 5)(6 6)(6 8))((3 6)(2 7)(5 6)(6 7)))(((4 3)(3 2)(6 3)(7 2))((3 1)(4 4)(3 3)(7 1)(6 4)(7 3))((4 1)(3 2)(4 5)(3 4)(6 1)(7 2)(6 5)(7 4))((4 2)(3 3)(4 6)(3 5)(6 2)(7 3)(6 6)(7 5))((4 3)(3 4)(4 7)(3 6)(6 3)(7 4)(6 7)(7 6))((4 4)(3 5)(4 8)(3 7)(6 4)(7 5)(6 8)(7 7))((4 5)(3 6)(3 8)(6 5)(7 6)(7 8))((4 6)(3 7)(6 6)(7 7)))(((5 3)(4 2)(7 3)(8 2))((4 1)(5 4)(4 3)(8 1)(7 4)(8 3))((5 1)(4 2)(5 5)(4 4)(7 1)(8 2)(7 5)(8 4))((5 2)(4 3)(5 6)(4 5)(7 2)(8 3)(7 6)(8 5))((5 3)(4 4)(5 7)(4 6)(7 3)(8 4)(7 7)(8 6))((5 4)(4 5)(5 8)(4 7)(7 4)(8 5)(7 8)(8 7))((5 5)(4 6)(4 8)(7 5)(8 6)(8 8))((5 6)(4 7)(7 6)(8 7)))(((6 3)(5 2)(8 3))((5 1)(6 4)(5 3)(8 4))((6 1)(5 2)(6 5)(5 4)(8 1)(8 5))((6 2)(5 3)(6 6)(5 5)(8 2)(8 6))((6 3)(5 4)(6 7)(5 6)(8 3)(8 7))((6 4)(5 5)(6 8)(5 7)(8 4)(8 8))((6 5)(5 6)(5 8)(8 5))((6 6)(5 7)(8 6)))(((7 3)(6 2))((6 1)(7 4)(6 3))((7 1)(6 2)(7 5)(6 4))((7 2)(6 3)(7 6)(6 5))((7 3)(6 4)(7 7)(6 6))((7 4)(6 5)(7 8)(6 7))((7 5)(6 6)(6 8))((7 6)(6 7)))\n</code></pre>\n\n<p>It is interesting to note that just parsing the giant constant takes about as long as computing it.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-03T00:05:54.673", "Id": "470463", "Score": "0", "body": "For the naming convention, note that `dromedaryCase` and `CamelCase` are known as `camelCase` and `PascalCase` respectively in different communities. (To me, this is the very first time I saw the name `dromedaryCase`.)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-03T00:12:39.810", "Id": "470465", "Score": "0", "body": "@Bubbler Yes, unfortunately they have no standardised names. Microsoft calls them camelCase and PascalCase. [Wikipedia says](https://en.wikipedia.org/wiki/Camel_case) \"**upper camel case** (initial uppercase letter, also known as **Pascal case**) and **lower camel case** (initial lowercase letter, also known as **Dromedary case**)\". Since the term \"camel case\" is ambiguous, maybe the best practice would be to call them PascalCase and dromedaryCase…" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-03T22:52:31.947", "Id": "470586", "Score": "1", "body": "Thanks for the thorough review! I incorporated most of the suggestions [but I would still appreciate some further reviewing!](https://codereview.stackexchange.com/q/239897/221235)" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-02T23:56:37.473", "Id": "239843", "ParentId": "239818", "Score": "11" } } ]
{ "AcceptedAnswerId": "239843", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-02T17:49:00.057", "Id": "239818", "Score": "18", "Tags": [ "chess", "apl" ], "Title": "Finding legal knight moves in a chessboard in APL" }
239818
<p>Please review my Python Alien Blitz Game code.</p> <p>There are several points I'm keen to hear about.</p> <ul> <li><p>I used globals. Was that an evil choice given the context? In the past when I've tried to refactor these kinds of programs to pass arguments instead, I've got in a real muddle keeping track of them all.</p></li> <li><p>Is this code at a level of complexity where not using OOP is "the wrong choice"? </p></li> <li><p>How well did I handle the timer callbacks?</p></li> <li><p>There was an issue with the bomb still dropping after a level was completed or there was a crash, and it carried over to the next round - I stopped this with by using the <code>playing</code> flag. Was that a good approach?</p></li> <li><p>How good is my coding in general? Is the style consistent? Have I made any obvious or subtle errors or bad choices?</p></li> </ul> <p>The very most helpful thing for me would be to see how a more experienced programmer would refactor my code. It would be great to see a version which has no globals but is still procedural, and a well-implemented OOP version. I know that is a big ask.</p> <p>There is a repo containing the sounds as well as the program here:</p> <p><a href="https://github.com/Robin-Andrews/Alien-Blitz-Retro-Game-with-Python-Turtle-Graphics" rel="nofollow noreferrer">https://github.com/Robin-Andrews/Alien-Blitz-Retro-Game-with-Python-Turtle-Graphics</a></p> <p>Many thanks in advance for any feedback.</p> <pre><code># alien_blitz.py import turtle import random try: import playsound # Not part of standard Library. SOUND = True except ImportError: SOUND = False NUM_TOWERS = 20 MAX_TOWER_HEIGHT = 10 CURSOR_SIZE = 20 PLANE_DELAY = 40 BOMB_DELAY = 40 WIDTH = 800 HEIGHT = 600 cell_colors = ["black", "dark green", "brown"] def move_plane(): global playing new_pos = (plane.xcor(), plane.ycor()) if new_pos[0] &gt; width // 2: plane.goto(- width // 2, plane.ycor() - size) else: plane.goto(plane.xcor() + 12, plane.ycor()) if check_plane_tower_collision(): playing = False restart(new_level=False) elif check_player_wins_level(): restart(new_level=True) else: screen.update() turtle.ontimer(move_plane, PLANE_DELAY) def check_player_wins_level(): if score &gt;= winning_score: player_wins_level() return True return False def player_wins_level(): update_score_display() if SOUND: playsound.playsound("victory.wav") def check_plane_tower_collision(): for tower in towers: for cell in tower: if plane.distance(cell) &lt;= size / 2 + 10: # Half cell size + half plane height plane_tower_collision() return True return False def plane_tower_collision(): bomb.hideturtle() # If present when plane crashes plane.color("red") screen.update() if SOUND: playsound.playsound("plane_crash.wav") def check_bomb_tower_collision(): if playing: for tower in towers: for cell in tower: if bomb.distance(cell) &lt;= size / 2 + 5: # Half cell size + half bomb size bomb_tower_collision(cell) return True return False def bomb_tower_collision(cell): global score, high_score if SOUND: playsound.playsound("bombed.wav", False) cell.setx(-1000) cell.clear() score += 10 if score &gt; high_score: high_score = score update_score_display() def start_bomb_drop(): # Prevent further key presses until drop is finished tp prevent event stacking. screen.onkey(None, "space") bomb.goto(plane.xcor(), plane.ycor()) bomb.showturtle() __continue_bomb_drop() def __continue_bomb_drop(): global playing bomb.goto(bomb.xcor(), bomb.ycor() - 12) if check_bomb_tower_collision() or bomb.ycor() &lt; - height // 2 or not playing: stop_bomb_drop() else: turtle.ontimer(__continue_bomb_drop, BOMB_DELAY) def stop_bomb_drop(): bomb.hideturtle() # It's now safe to allow another bomb drop, so rebind keyboard event. screen.onkey(start_bomb_drop, "space") def update_score_display(): pen.clear() pen.write("Score:{:2} High Score:{:2}".format(score, high_score), align="center", font=("Courier", 24, "normal")) def get_towers(): result = [] for col in range(-NUM_TOWERS // 2, NUM_TOWERS // 2): tower = [] for level in range(random.randrange(1, MAX_TOWER_HEIGHT + 1)): block = turtle.Turtle(shape="square") block.shapesize(size / CURSOR_SIZE) block.color(random.choice(cell_colors)) block.penup() block.goto(col * size + offset, - height // 2 + level * size + offset) tower.append(block) result.append(tower) return result def setup(): global screen, plane, bomb, pen, high_score, size, offset, height, width, score # Screen screen = turtle.Screen() screen.title("Alien Blitz") screen.setup(WIDTH, HEIGHT) screen.bgcolor("dark blue") screen.listen() screen.onkey(start_bomb_drop, "space") screen.tracer(0) # MISC. width = screen.window_width() - 50 height = screen.window_height() - 50 size = width / NUM_TOWERS # Size of tower cells in pixels offset = (NUM_TOWERS % 2) * size / 2 + size / 2 # Center even and odd cells # Plane plane = turtle.Turtle(shape="triangle", visible=False) plane.color("yellow") plane.shapesize(20 / CURSOR_SIZE, 40 / CURSOR_SIZE) plane.penup() plane.goto(- width // 2, height // 2) plane.showturtle() # Bomb bomb = turtle.Turtle(shape="circle") bomb.hideturtle() bomb.color("red") bomb.shapesize(0.5) bomb.penup() # Score Display pen = turtle.Turtle() pen.hideturtle() pen.color("white") pen.penup() pen.goto(0, 260) # Initialise high score high_score = 0 def restart(new_level=False): global score, high_score, winning_score, towers, playing # Towers list does not exist on first call. try: for tower in towers: for cell in tower: cell.setx(-1000) cell.clear() except NameError: pass plane.color("yellow") towers = get_towers() # Here we handle the score for different scenarios for restarting the game - crashed plane or completed level. if not new_level: score = 0 winning_score = sum(len(row) for row in towers) * 10 else: winning_score += sum(len(row) for row in towers) * 10 update_score_display() plane.goto(- width // 2, height // 2) bomb.goto(- width // 2, height // 2) playing = True screen.update() move_plane() def main(): setup() restart() if __name__ == "__main__": main() turtle.done() <span class="math-container">```</span> </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-02T18:27:03.587", "Id": "470431", "Score": "0", "body": "With the little authority I can be given, I wouldn't insert spaces in `- variable` to negate variables, nor would I do it around `/` and `//` when dividing variables by constants, i.e. I'd write `-width` or `size/2` or `-width//3`. While it is important to let your mathematical expressions breath, there is no point in spacing them out too much because it then becomes harder to find the important parts." } ]
[ { "body": "<p>I'd say that yes, using globals was an evil choice, and I think that splitting this functionality into objects would be a good move.</p>\n\n<p>As the original author you might have found it easier to just keep track of the globals in your head and not have to type them as arguments to each function, but as a reader, it makes it very hard to follow the changes in state between functions.</p>\n\n<p>Not having to pass large numbers of variables as arguments between functions is where OOP can help you. (Note: I always think of OOP as being a means to an end and do not advocate shoving it in without a purpose -- come at me, Java bros! In this case, the \"end\" is being able to better organize all your bits and bobs of state.) On first blush, my approach to this would be to have two objects: a \"game state\" object (that tracks where everything is in the game and implements the \"rules\") and a \"game UI\" object (that manages all of the interface business, i.e. the screen drawing and the keypresses). So instead of one big pile of globals, you have two objects that hold all that data; your \"setup\" function creates and returns those two objects and then the rest of your game logic operates on/within them. You'd probably be able to turn some of your functions into class methods (as a rule of thumb, anything that modifies one of those pieces of state should probably live inside that class).</p>\n\n<p>Once you'd finished that refactoring, my next recommendation would be to look at functions that don't operate purely on one object or the other, and then split those up -- separate your game logic from your UI. Basically you want each function to do one thing in one \"layer\" of your app, and keep responsibilities separated; this is the concept of \"model/view\" in a nutshell.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-02T19:10:12.073", "Id": "239825", "ParentId": "239819", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-02T18:00:07.807", "Id": "239819", "Score": "0", "Tags": [ "python", "game", "turtle-graphics" ], "Title": "Python Alien Blitz Game" }
239819
<p>I have functions nested here in setTimeout</p> <pre><code>function startWorker (obj) { if (!code) { return setTimeout(2000, () =&gt; { startWorker(obj) }); } console.log('worker started') } </code></pre> <p>How do I correctly use startWorker as the callback without using more functions than needed.</p> <p>What I'm trying to do:</p> <p>I'm trying to run the same function with the same argument as the callback to a setTimeout inside without duplicating function calls.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-02T18:42:32.383", "Id": "470435", "Score": "0", "body": "@SᴀᴍOnᴇᴌᴀ I don't understand, this is actual code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-02T18:45:34.233", "Id": "470437", "Score": "0", "body": "Okay I have retracted my close vote but bear in mind this tip from [The Help center page _How do I ask a good question?_](https://codereview.stackexchange.com/help/how-to-ask): \"_You will get more insightful reviews if you not only provide your code, but also give an explanation of what it does. The more detail, the better._\"" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-02T18:49:50.680", "Id": "470439", "Score": "0", "body": "Thank you, I'll edit it." } ]
[ { "body": "<p>I'm not sure I understand what you're asking, but what if you just use <code>setInterval()</code> instead of <code>setTimeout()</code>?</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function startWorker(obj) {\n if (!code) {\n setInterval( () =&gt; {\n console.log(obj.action);\n }, 2000);\n }\n}\n\nconst code = false;\nconst someObj = {\n action: \"tick\"\n};\n\nstartWorker(someObj);</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-04-02T22:26:49.953", "Id": "239836", "ParentId": "239820", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-02T18:06:07.073", "Id": "239820", "Score": "0", "Tags": [ "javascript" ], "Title": "ES6 how to avoid nested functions" }
239820
<p>I happened to delve into tkinter and created a couple of mini projects so I could get more familiar with it. I was wondering if there was any portion of my code or code structure that is sloppily written and could be more python-esque. As a beginner in both python and tkinter (been learning during this quarantine) it would be great if you fellow coders would be willing to give me some pointers about my code which will benefit me in the future (breaking bad habits now rather than later, creating good habits instead). Thanks!</p> <pre><code>from tkinter import * window = Tk() window.title("Basic Converter") window.geometry("500x300+500+350") #globally declare measurement variables measurement1 = "" measurement2 = "" def convert_SI(val, unit_in, unit_out): #based on unitconverters.net SI = {'Meter':1, 'Kilometer':1000, 'Centimeter':0.01, 'Millimeter':0.001, 'Micrometer':0.000001, 'Mile':1609.35, 'Yard':0.9144, 'Foot':0.3048, 'Inch':0.0254} return val*SI[unit_in]/SI[unit_out] def helpsection(): pass #put helpful info text here (e.g. no entering in right entry box else error) def selectedInput(): global measurement1 measurement1 = listbox.get(listbox.curselection())#whatever is currently selected def selectedOutput(): global measurement2 measurement2 = listbox1.get(listbox1.curselection()) #whatever is currently selected def converter(): try: global measurement1, measurement2 result.set(str(convert_SI(float(inputEntry.get()), measurement1, measurement2))) except: result.set("Error") title = Label(window, text="Basic Converter", font="Calibri 16") title.grid(columnspan=3) result = StringVar() #initalize dispalyed output variable #create a top-level menu filemenu = Menu(window) filemenu.add_command(label='Help', command=helpsection) window.config(menu=filemenu) #displays menu #input and output entry fields inputEntry = Entry(window) inputEntry.grid(row=1, column=0) arrow = Label(window, text="---&gt;", font="Calibri 20").grid(row=1, column=1) outputEntry = Entry(window, textvariable=result).grid(row=1, column=2) convertButton = Button(window, text='Convert!', command=converter).grid(row=2, column=1) #if nonetype error, because .grid needs to be called on their own line since it always returns None scrollbar = Scrollbar(window) #left scrollbar scrollbar.grid(row=2, column=0, sticky = NE + SE) listbox = Listbox(window, exportselection=False) #left listbox #exportselection option in order to select 2 different listbox at same time listbox.grid(row=2, column=0) measurement_list = ['Meter', 'Kilometer', 'Centimeter', 'Millimeter', 'Micrometer', 'Mile', 'Yard', 'Foot', 'Inch'] for measurement in measurement_list: listbox.insert(END, measurement) listbox.bind("&lt;&lt;ListboxSelect&gt;&gt;", lambda x: selectedInput()) #this instead of command= option # attach listbox to scrollbar listbox.config(yscrollcommand=scrollbar.set) scrollbar.config(command=listbox.yview) scrollbar1 = Scrollbar(window) #right scrollbar scrollbar1.grid(row=2, column=2, sticky = NE + SE) #add sticky if scrollbar not showing listbox1 = Listbox(window, exportselection=False) #right listbox listbox1.grid(row=2, column=2) for measurement in measurement_list: listbox1.insert(END, measurement) listbox1.bind("&lt;&lt;ListboxSelect&gt;&gt;", lambda x: selectedOutput()) listbox1.config(yscrollcommand=scrollbar1.set) scrollbar1.config(command=listbox1.yview) #configure grid layout to adjust whenever window dimensions change for i in range(3): window.grid_rowconfigure(i, weight=1) window.grid_columnconfigure(i, weight=1) window.mainloop() </code></pre>
[]
[ { "body": "<h2>Don't use wildcard imports.</h2>\n\n<p>Import tkinter with <code>import tkinter as tk</code>, and then prefix all of your calls to tkinter classes with <code>tk.</code>. For example:</p>\n\n<pre><code>import tkinter as tk\n\nwindow = tk.Tk()\n...\ntitle = tk.Label(window, text=\"Basic Converter\", font=\"Calibri 16\")\nfilemenu = tk.Menu(window)\n\n...\n</code></pre>\n\n<p><a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP8</a> is a set of guidelines that most python programmers follow, and it recommends against wildcard imports. </p>\n\n<h2>Don't call grid or pack inline</h2>\n\n<p>In python, <code>x().y()</code> always returns the value of <code>y()</code>. In tkinter, <code>grid</code>, <code>pac</code>, and <code>place</code> all return <code>None</code>. Thus, when you do this:</p>\n\n<pre><code>arrow = Label(window, text=\"---&gt;\", font=\"Calibri 20\").grid(row=1, column=1)\n</code></pre>\n\n<p>... all you're doing is setting <code>arrow</code> to <code>None</code>, which renders <code>arrow</code> useless. Plus, doing it inline (or worse, sometimes in line and sometimes now) makes the code hard to read.</p>\n\n<p>Which leads us to the next point...</p>\n\n<h2>Separate layout from widget creation.</h2>\n\n<p>I see this mistake all the time: create a widget, call grid, create a widget, call grid, ... This results in code that is hard to read, and makes it hard to visualize the layout. If you have to change the layout, such as changing the order of two rows, it's easier if those two rows are together in the code rather than intermixed with other code.</p>\n\n<p>As a rule of thumb, create all widgets within a given group together, and lay them out together.</p>\n\n<p>For example:</p>\n\n<pre><code>title = Label(window, text=\"Basic Converter\", font=\"Calibri 16\")\ninputEntry = Entry(window)\narrow = Label(window, text=\"---&gt;\", font=\"Calibri 20\")\nconvertButton = Button(window, text='Convert!', command=converter)\noutputEntry = Entry(window, textvariable=result)\nscrollbar = Scrollbar(window) #left scrollbar\n...\ntitle.grid(columnspan=3)\ninputEntry.grid(row=1, column=0)\narrow.grid(row=1, column=1)\nconvertButton..grid(row=2, column=1)\noutputEntry.grid(row=1, column=2)\nscrollbar.grid(row=2, column=0, sticky = NE + SE)\n...\n</code></pre>\n\n<p>In this specific example everything is in the root window so it doesn't matter quite so much, but if you used multiple frames for organizing your widgets this would make it much easier to see which widgets were grouped together.</p>\n\n<h2>Make your UI responsive</h2>\n\n<p>When I resized your window, the layout didn't respond very well. This is what I see when I resize the program; notice how the scrollbars are the wrong size, the listboxes didn't expand, etc.</p>\n\n<p><a href=\"https://i.stack.imgur.com/cArnh.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/cArnh.png\" alt=\"screenshot\"></a></p>\n\n<p>Tkinter makes this easy to do, but you have to use the options tkinter gives you. Think about what should happen when the user resizes the program. This becomes much easier when you group all of your calls to <code>grid</code> together. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-02T21:23:55.780", "Id": "470452", "Score": "0", "body": "thanks! I was just looking at your prior post on OOP structuring for tkinter: https://stackoverflow.com/questions/17466561/best-way-to-structure-a-tkinter-application" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-02T21:05:26.027", "Id": "239830", "ParentId": "239821", "Score": "1" } } ]
{ "AcceptedAnswerId": "239830", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-02T18:08:53.310", "Id": "239821", "Score": "2", "Tags": [ "python", "beginner", "tkinter" ], "Title": "Simple GUI unit converter with tkinter" }
239821
<p>I'm learning how to use Kafka, I've never used something similar in the past. In my job I was required to create a POC using it and integrate it to Spring Boot and save information on MongoDB (because we will need to retrieve information on-demand and I thought that it would be the best approach).</p> <p>At the consumer I created an app, but I'm not sure if I should have a <code>@RestController</code> class or this is something that should go into Kafka and how?</p> <p>Is it ok to have the <code>MyRestController</code> class? If not, how do I implement this using Kafka?</p> <p>Right now, the code is working but I would like to improve it especially the Controller part and any extra comments that you could make to improve this.</p> <p>This is the structure of my project:</p> <p><a href="https://i.stack.imgur.com/SvYRA.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/SvYRA.png" alt="enter image description here"></a></p> <p><strong>KafkaConfigurator</strong></p> <pre><code>package com.example.demo.config; import java.util.HashMap; import java.util.Map; import org.apache.kafka.clients.consumer.ConsumerConfig; import org.apache.kafka.common.serialization.StringDeserializer; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.kafka.annotation.EnableKafka; import org.springframework.kafka.config.ConcurrentKafkaListenerContainerFactory; import org.springframework.kafka.core.ConsumerFactory; import org.springframework.kafka.core.DefaultKafkaConsumerFactory; import org.springframework.kafka.support.serializer.JsonDeserializer; import com.example.demo.model.User; @EnableKafka @Configuration public class KafkaConfiguration { @Bean public ConsumerFactory&lt;String, String&gt; consumerFactory() { Map&lt;String, Object&gt; config = new HashMap(); config.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "127.0.0.1:9092"); config.put(ConsumerConfig.GROUP_ID_CONFIG, "group_id"); config.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class); config.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class); return new DefaultKafkaConsumerFactory&lt;&gt;(config); } @Bean public ConcurrentKafkaListenerContainerFactory&lt;String, String&gt; kafkaListenerContainerFactory() { ConcurrentKafkaListenerContainerFactory&lt;String, String&gt; factory = new ConcurrentKafkaListenerContainerFactory(); factory.setConsumerFactory(consumerFactory()); return factory; } @Bean public ConsumerFactory&lt;String, User&gt; userConsumerFactory() { Map&lt;String, Object&gt; config = new HashMap(); config.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "127.0.0.1:9092"); config.put(ConsumerConfig.GROUP_ID_CONFIG, "group_id"); config.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class); config.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, JsonDeserializer.class); return new DefaultKafkaConsumerFactory&lt;&gt;(config, new StringDeserializer(), new JsonDeserializer&lt;&gt;(User.class)); } @Bean public ConcurrentKafkaListenerContainerFactory&lt;String, User&gt; userKafkaListenerFactory() { ConcurrentKafkaListenerContainerFactory&lt;String, User&gt; factory = new ConcurrentKafkaListenerContainerFactory&lt;&gt;(); factory.setConsumerFactory(userConsumerFactory()); return factory; } } </code></pre> <p><strong>MyRestController</strong></p> <pre><code>package com.example.demo.controller; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.example.demo.listener.KafkaConsumer; import com.example.demo.model.User; @RestController @RequestMapping(value = "users") public class MyRestController { @Autowired private KafkaConsumer consumer; @GetMapping(path = "/findUserByOffset/{offset}") public User getUserByOffset(@PathVariable("offset") Long offset) { return consumer.getUserByOffset(offset); } @GetMapping(path = "/findUsersInRange/{lowerOffset}/{upperOffset}") public List&lt;User&gt; getUsersByOffsetRange(@PathVariable("lowerOffset") Long lowerOffset, @PathVariable("upperOffset") Long upperOffset) { return consumer.getUsersByOffsetRange(lowerOffset, upperOffset); } } </code></pre> <p><strong>UserRepository</strong></p> <pre><code>package com.example.demo.factory; import java.util.List; import org.springframework.data.mongodb.repository.MongoRepository; import org.springframework.data.mongodb.repository.Query; import com.example.demo.model.User; public interface UserRepository extends MongoRepository&lt;User, Long&gt;{ User findById(String id); User findByOffset(Long offset); @Query("{'offset' : { $gte: ?0, $lte: ?1 }}") List&lt;User&gt; findInOffsetRange(Long lowerOffset, Long upperOffset); } </code></pre> <p><strong>KafkaConsumer</strong></p> <pre><code>package com.example.demo.listener; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.kafka.annotation.KafkaListener; import org.springframework.stereotype.Service; import com.example.demo.factory.UserRepository; import com.example.demo.model.User; @Service public class KafkaConsumer { @Autowired UserRepository userRepository; @KafkaListener(topics = "Kafka_Example", groupId = "group_id") public void consume(String message) { System.out.println("Consumed message: " + message); } @KafkaListener(topics = "Kafka_Example_json", groupId = "group_json", containerFactory = "userKafkaListenerFactory") public void consumeJson(User user) { System.out.println("Consumed JSON message: " + user); userRepository.save(user); } public User getUserByOffset(Long offset) { return userRepository.findByOffset(offset); } public List&lt;User&gt; getUsersByOffsetRange(Long lowerOffset, Long upperOffset) { return userRepository.findInOffsetRange(lowerOffset, upperOffset); } } </code></pre> <p><strong>User</strong></p> <pre><code>package com.example.demo.model; import org.springframework.data.annotation.Id; import org.springframework.data.mongodb.core.mapping.Document; @Document public class User { @Id private String id; private String name; private String dept; private Long salary; private Long offset; public User(String id, String name, String dept, Long salary, Long offset) { super(); this.id = id; this.name = name; this.dept = dept; this.salary = salary; this.offset = offset; } public User() { super(); } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDept() { return dept; } public void setDept(String dept) { this.dept = dept; } public Long getSalary() { return salary; } public void setSalary(Long salary) { this.salary = salary; } public Long getOffset() { return offset; } public void setOffset(Long offset) { this.offset = offset; } @Override public String toString() { return "User [name=" + name + ", dept=" + dept + ", salary=" + salary + "]"; } } </code></pre> <p><strong>KafkaConsumerDemoApplication</strong></p> <pre><code>package com.example.demo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class KafkaConsumerDemoApplication { public static void main(String[] args) { SpringApplication.run(KafkaConsumerDemoApplication.class, args); } } </code></pre> <p><strong>application.properties</strong></p> <pre><code>#server server.port=8081 #mongodb spring.data.mongodb.host=localhost spring.data.mongodb.port=27017 spring.data.mongodb.database=app1 #logging logging.level.org.springframework.data=debug logging.level.=error </code></pre> <p><strong>pom.xml</strong></p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"&gt; &lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt; &lt;parent&gt; &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt; &lt;artifactId&gt;spring-boot-starter-parent&lt;/artifactId&gt; &lt;version&gt;2.2.5.RELEASE&lt;/version&gt; &lt;relativePath /&gt; &lt;!-- lookup parent from repository --&gt; &lt;/parent&gt; &lt;groupId&gt;com.example&lt;/groupId&gt; &lt;artifactId&gt;kafka-consumer-demo&lt;/artifactId&gt; &lt;version&gt;0.0.1-SNAPSHOT&lt;/version&gt; &lt;name&gt;kafka-consumer-demo&lt;/name&gt; &lt;description&gt;Demo project for Spring Boot&lt;/description&gt; &lt;properties&gt; &lt;java.version&gt;1.8&lt;/java.version&gt; &lt;/properties&gt; &lt;dependencies&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt; &lt;artifactId&gt;spring-boot-starter&lt;/artifactId&gt; &lt;/dependency&gt; &lt;!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-web --&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt; &lt;artifactId&gt;spring-boot-starter-web&lt;/artifactId&gt; &lt;version&gt;2.2.6.RELEASE&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework.kafka&lt;/groupId&gt; &lt;artifactId&gt;spring-kafka&lt;/artifactId&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt; &lt;artifactId&gt;spring-boot-starter-test&lt;/artifactId&gt; &lt;scope&gt;test&lt;/scope&gt; &lt;exclusions&gt; &lt;exclusion&gt; &lt;groupId&gt;org.junit.vintage&lt;/groupId&gt; &lt;artifactId&gt;junit-vintage-engine&lt;/artifactId&gt; &lt;/exclusion&gt; &lt;/exclusions&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework.kafka&lt;/groupId&gt; &lt;artifactId&gt;spring-kafka-test&lt;/artifactId&gt; &lt;scope&gt;test&lt;/scope&gt; &lt;/dependency&gt; &lt;!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind --&gt; &lt;dependency&gt; &lt;groupId&gt;com.fasterxml.jackson.core&lt;/groupId&gt; &lt;artifactId&gt;jackson-databind&lt;/artifactId&gt; &lt;/dependency&gt; &lt;!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind --&gt; &lt;dependency&gt; &lt;groupId&gt;com.fasterxml.jackson.core&lt;/groupId&gt; &lt;artifactId&gt;jackson-databind&lt;/artifactId&gt; &lt;/dependency&gt; &lt;!-- https://mvnrepository.com/artifact/org.springframework.data/spring-data-mongodb --&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework.data&lt;/groupId&gt; &lt;artifactId&gt;spring-data-mongodb&lt;/artifactId&gt; &lt;version&gt;2.2.6.RELEASE&lt;/version&gt; &lt;/dependency&gt; &lt;/dependencies&gt; &lt;build&gt; &lt;plugins&gt; &lt;plugin&gt; &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt; &lt;artifactId&gt;spring-boot-maven-plugin&lt;/artifactId&gt; &lt;/plugin&gt; &lt;/plugins&gt; &lt;/build&gt; &lt;/project&gt; </code></pre>
[]
[ { "body": "<p>From your question and code, I understand that you are trying to</p>\n<ul>\n<li>consume events from Kafka topic, persist in MongoDB.</li>\n<li>Also, exposing api's to retrieve data from Mongo DB and send in response.</li>\n</ul>\n<p>If this is the case, solution above looks Good, as you are considering MongoDB as a source of truth/primary DB.</p>\n<p>you can also persist data in Kafka as a cache and use configure API's to get data from Kafka. (Refer KTable, GlobalKTable).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-20T01:56:30.003", "Id": "248172", "ParentId": "239823", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-02T18:22:58.230", "Id": "239823", "Score": "2", "Tags": [ "java", "rest", "spring", "mongodb", "apache-kafka" ], "Title": "Spring, Kafka and Mongo how to create a RestController" }
239823
<p>After a March update, Adobe Indesign will resurrect removed directories it was responsible for creating in the first place, but not any files except for one file called "AdobeFnt.lst". So where once you had a complex folder structure, but then deleted it, you'll now have the whole structure back, but one folder somewhere will contain AdobeFnt.lst (and since it's MacOS, perhaps some .DS_Store files). My mother complained about this, and so I offered to write her a script that will check every minute for these resurrected empty directories. I wrote what's below, for addition to her crontab, but am afraid of deleting things incorrectly.</p> <p>Would this safely do the job? She saves these InDesign packages to her Desktop, and I was going to tell her to add all folders she saves stuff to into the DIRS array at the top.</p> <pre><code>#!/bin/bash # List where you save InDesign packages DIRS=( "$HOME/Desktop" ) IFS=$'\n' for DIR in "${DIRS[@]}"; do DS=($(find "$DIR" -type d -maxdepth 1 -mindepth 1)) for D in "${DS[@]}"; do FS=($(find "$D" -type f ! -iname .DS_Store)) if [ ${#FS[@]} -eq 1 ] &amp;&amp; [ $(basename "${FS[0]}") = "AdobeFnt.lst" ]; then echo "Removing $D" rm -r $D fi done done <span class="math-container">```</span> </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-02T20:52:55.043", "Id": "239829", "Score": "2", "Tags": [ "bash", "macos" ], "Title": "bash script to delete files resurrected by Adobe InDesign bug" }
239829
<p>APL is an <a href="https://en.wikipedia.org/wiki/Array_programming" rel="nofollow noreferrer">array-oriented programming language</a>. Its powerful, concise <a href="https://aplwiki.com/wiki/APL_syntax" rel="nofollow noreferrer">syntax</a> lets you develop shorter programs that enable you to think more about the problem you're trying to solve than how to express it to a computer.<sup><a href="https://aplwiki.com/" rel="nofollow noreferrer">1</a></sup></p> <p>For more information, see <a href="https://aplwiki.com" rel="nofollow noreferrer">aplwiki.com</a></p> <p><sup>1</sup><sub><a href="https://aplwiki.com/" rel="nofollow noreferrer">https://aplwiki.com/</a></sub></p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-02T21:18:20.720", "Id": "239831", "Score": "0", "Tags": null, "Title": null }
239831
APL is an array-oriented programming language. Its powerful, concise syntax lets you develop shorter programs that enable you to think more about the problem you're trying to solve than how to express it to a computer.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-02T21:18:20.720", "Id": "239832", "Score": "0", "Tags": null, "Title": null }
239832
<p>This is a recreational project, I was trying to make a parser generator with a grammar inspired from: <a href="https://docs.python.org/3/reference/grammar.html" rel="nofollow noreferrer">https://docs.python.org/3/reference/grammar.html</a></p> <p>Unfortunately, understanding that specific grammar's syntax (meta-grammar?) ended up being way harder than I expected so, I ended up creating my own.</p> <p>I call it KiloGrammar (sorry for the bad pun).</p> <p>It ended up being very different from what I was planning but seems to do the job. It actually describes a stack-machine and probably is Turing complete, though I did not have the time to attempt implementing something like rule 110 to verify it.</p> <p>here's a snippet of a grammar to parse simple math expressions:</p> <pre><code># this grammar parses simple math expressions like: a + 10 * (8 + 5) token var "[A-Za-z]+" token int "-?[0-9]+" token float "-?[0-9+]+\.[0-9]+" token whitespace "[ \s]+" keyword "(" keyword ")" keyword "+" keyword "-" keyword "*" keyword "/" shorthand "NUMBER" "int|float|var" shorthand "EXPRESSION" "MATH_NODES|NUMBER" shorthand "MATH_NODES" "ADD|SUB|MUL|DIV" shorthand "operation" "+|-|*|/" rule ignore_whitespace (whitespace) pop(1) rule math_priority (ADD|SUB, *|/, EXPRESSION) pop(3); push([0][1], [0][0], [0][2], [1], [2]) rule math (EXPRESSION, operation, EXPRESSION) pop(3) push(node( pick_name([1], operation, MATH_NODES), [1], [0], [2])) rule parenthesis ("(", EXPRESSION, ")") pop(3); push([1]) </code></pre> <p>here's the full implementation of the script: <code>kilogrammar.py</code></p> <pre class="lang-py prettyprint-override"><code>""" This script is a parser for the kilogrammar language It compiles it into a parser by just reusing its own code To use it just type the command: python kilogrammar.py my_parser.kg -compile &gt; output_parser.py to watch the parser working in interactive mode you can do: python kilogrammar.py my_parser.kg -interactive -color This file is quite long, to find meaningful sections, just search for names in this table of contents: colors used for printing: class Color functions used to make the interactive visualization: def pretty_lines def pretty_print main Node class used by the parser: class Node main Token class used by the parser: class Token class that implement tokenizing code: class Tokenizer class that implements parsing code as a stack machine: class Parser code used to simplify the implementation of new parser rules using decorators: def match class MatchRuleWrapper default functions avaliable to the kilogrammar language: KG_BUILTINS = " main tokenizer loop: while self.char_ptr &lt; len(self.text): main parser loop: for name, rule in rules Kilogrammar language parser class: class KiloParser(Parser): Kilogrammar tokenizer class: class KiloTokenizer(Tokenizer): """ # this tag is used to mark the start of the section that # is going to be copied as a new file # TAG1: reutilize code start import inspect import os import re class Color: """ colors defined as escape sequences for fancy output. easy to use but dont work on all terminals https://en.wikipedia.org/wiki/ANSI_escape_code """ @classmethod def enable(cls): cls.red = "\u001b[31m" cls.yellow = "\u001b[38;5;221m" cls.pink = "\u001b[38;5;213m" cls.cyan = "\u001b[38;5;38m" cls.green = "\u001b[38;5;112m" cls.reset = "\u001b[0m" @classmethod def disable(cls): cls.red = "" cls.yellow = "" cls.pink = "" cls.cyan = "" cls.green = "" cls.reset = "" Color.disable() class Node: """ Main class to construct an abstract syntax tree, It is expected to encapsulate instances of Node() or Token() """ def __init__(self, node_type, contents): self.type = node_type assert(type(contents) == list) self.contents = contents def pretty_lines(self, out_lines=None, indent_level=0): """ return pretyly formated lines containing the contents of its nodes and subnodes in a printable and human-readable form """ if out_lines is None: out_lines = [] out_lines.append("".join((" " * indent_level, repr(self), ":"))) for sub_thing in self.contents: if isinstance(sub_thing, Node): sub_thing.pretty_lines(out_lines, indent_level + 1) else: out_lines.append("".join( (" " * (indent_level + 1), repr(sub_thing)))) return out_lines def __hash__(self): # used for easy comparation with sets return hash(self.type) def __eq__(self, other): if isinstance(other, Node): return self.type == other.type else: return self.type == other def __repr__(self): return f"{Color.green}{self.type}{Color.reset}" def panic(msg, line, col, text): """ raise an SyntaxError and display the position of the error in the text """ text_line = text.split("\n")[line] arrow = " " * col + "^" raise SyntaxError("\n".join(("", text_line, arrow, msg, f" line: {line + 1}, collumn: {col + 1}"))) class Token: """ Main token class, its supposed to encapsulate snippets of the text being parsed """ def __init__(self, token_type, contents, line=None, col=None): self.type = token_type self.contents = contents self.line = line self.col = col def __hash__(self): return hash(self.type) def __eq__(self, other): if isinstance(other, Node): return self.type == other.type else: return self.type == other def __repr__(self): if self.contents in {None, ""}: return f"{Color.cyan}{self.type} {Color.reset}" return f"{Color.cyan}{self.type} {Color.pink}{repr(self.contents)}{Color.reset}" class Tokenizer: """ Main Tokenizer class, it parses the text and makes a list of tokens matched based on the rules defined for it it starts trying to match rules at the start of the file and when the first rule matches, it saves the match as a token and move forward by the length of the match to the next part of the text unless the rule defines a callback function, in this case the callback has to move to the next token using the feed() method If no rule matches any part of the text, it calls a panic() """ rules = ["text", r"(?:\n|.)*"] def __init__(self, text, skip_error=False): self.text = text self.tokens = [] self.errors = [] self.skip_error = skip_error self.char_ptr = 0 self.line_num = 0 self.col_num = 0 self.preprocess() self.tokenize() def preprocess(self): pass @staticmethod def default_callback(self, match, name): self.push_token(name, match[0]) self.feed(len(match[0])) return len(match[0]) &gt; 0 def push_token(self, type, value=None): self.tokens.append(Token(type, value, self.line_num, self.col_num)) def pop_token(self, index=-1): return self.tokens.pop(-1) def feed(self, n): for _ in range(n): if self.text[self.char_ptr] == "\n": self.line_num += 1 self.col_num = -1 self.char_ptr += 1 self.col_num += 1 def tokenize(self): import re import inspect rules = [] self.preprocess() for rule in self.rules: if len(rule) == 2: (name, regex), callback = rule, self.default_callback elif len(rule) == 3: name, regex, callback = rule else: raise TypeError(f"Rule not valid: {rule}") try: regex = re.compile(regex) except Exception as e: print(str(e)) raise TypeError(f"{type(self)}\n {name}: {repr(regex)}\n" f"regex compilation failed") rules.append((name, regex, callback)) while self.char_ptr &lt; len(self.text): for name, regex, callback in rules: match = regex.match(self.text, self.char_ptr) if match: done = callback(self, match, name) if done: break else: err = (f"Unexpected character: {repr(self.text[self.char_ptr])}", self.line_num, self.col_num) if self.skip_error: self.errors.append(err) self.feed(1) else: panic(*err, self.text) class MatchRuleWrapper: """ Encapsulates a parser rule definition and tests it against the parser stack, if a match is found, it calls its callback function that does its thing on the parser stack. """ def __init__(self, func, rules, priority=0): self.func = func self.rules = rules self.priority = priority def __call__(self, parser, *args): n = len(parser.stack) if len(self.rules) &gt; n or len(self.rules) &gt; n: return i = 0 for rule in reversed(self.rules): item = parser.stack[-1 - i] i += 1 if not (rule is None or item.type in rule): break else: matches = parser.stack[-len(self.rules):] self.func(parser, *matches) return matches def match(*args, priority=0): """ returns decorator that helps defining parser rules and callbacks as if they were simple instance methods. In reality those methods are turned into MatchRuleWrapper callbacks """ import inspect for arg in args: if not isinstance(arg, (set, str)) and arg is not None: raise TypeError(f"match_fun() invalid argument: {arg}") match_rules = [] for arg in args: if arg == None or type(arg) == set: match_rules.append(arg) elif isinstance(arg, str): match_rules.append({s for s in arg.split("|") if s}) else: raise TypeError(f"wrong type of argumment: {type(arg)}, {arg}") arg_count = len([type(arg) for arg in args]) + 1 def decorator(func): paramaters = inspect.signature(func).parameters if len(paramaters) is not arg_count: if not inspect.Parameter.VAR_POSITIONAL in {p.kind for p in paramaters.values()}: raise TypeError( f"function {func} does not contain {arg_count} argumments") return MatchRuleWrapper(func, match_rules, priority) return decorator class Parser: """ A stack machine that simply run its rules on its stack, every time no rule maches the contents of the stack a new token is pushed from the token list """ def __init__(self, tokenizer, preview=999999, token_preview=5): self.tokens = tokenizer.tokens self.text = tokenizer.text self.token_ptr = 0 self.stack = [] self.preview = preview self.token_preview=token_preview self.parse() def push(self, node_type, contents=None): if contents is None: contents = [] if type(node_type) in {Node, Token}: self.stack.append(node_type) else: self.stack.append(Node(node_type, contents)) def pop(self, repeat=1, index=-1): for _ in range(repeat): self.stack.pop(index) def parse(self): rules = [(name, rule) for name, rule in inspect.getmembers(self) if isinstance(rule, MatchRuleWrapper)] rules = sorted(rules, key=lambda r: -r[1].priority) while True: for name, rule in rules: matched = rule(self) if matched: break else: if not self.token_ptr &lt; len(self.tokens): break self.stack.append(self.tokens[self.token_ptr]) self.token_ptr += 1 if self.preview &gt; 0: self.pretty_print(self.preview, self.token_preview) print("stack:", self.stack, "\n") if matched: print("matched rule:", name, matched, "\n") else: print("no rule matched\n") inp = input(" Hit enter to continue, type 'e' to exit: ") if inp == "e": self.preview = 0 os.system("cls" if os.name == "nt" else "clear") def pretty_print(self, maximun_tree, maximun_tokens): lines = [] for thing in self.stack: if isinstance(thing, Node): lines.extend(thing.pretty_lines()) else: lines.append(repr(thing)) display_lines = lines[max(-maximun_tree, -len(lines)):] if len(display_lines) &lt; len(lines): print("...") print("\n".join(display_lines)) print("\nNext tokens:") for i, token in enumerate(self.tokens[self.token_ptr:]): print(token) if i == maximun_tokens: break class KiloTokenizer(Tokenizer): last_indent = None indent_deltas = [] def handle_indent(self, match, name): n = len(match[1]) if self.last_indent is None: self.last_indent = n delta = n - self.last_indent self.last_indent = n if delta &gt; 0: self.push_token("indent_increase") self.indent_deltas.append(delta) elif delta &lt; 0: while delta &lt; 0 and self.indent_deltas: self.push_token("indent_decrease") delta += self.indent_deltas.pop(-1) if delta &gt; 0: self.push_token("inconsistent_indent") rules = [["indent", r"\n([ \t]*)(?:[^ \t\n])", handle_indent], # TAG1: reutilize code end ["newline", r"\n"], ["string", r""""(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'"""], ["whitespace", r"[ ;\t]+"], ["comment", r"#.*\n"], ["integer", r"(-?[0-9]+)\b"], ["rule", r"rule"], ["case", r"case"], ["keyword", r"keyword"], ["token", r"token"], ["word", r"\b[A-Za-z_]+[A-Za-z0-9_]*\b"], ["name", r"[^0-9\[\]\(\);\| \t\'\"\n,#&gt;]+"], ["pipe", r"\|"], ["(", r"\("], [")", r"\)"], ["[", r"\["], ["]", r"\]"], [",", r","]] def preprocess(self): shorthand_re = re.compile( r"""shorthand\s*("(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*')\s*("(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*')""" ) new_lines = [] shorthands = [] for line in self.text.split("\n"): for replace, to in shorthands: replaced_line = line.replace(replace, to) if replaced_line != line: line = replaced_line match = shorthand_re.match(line) if match: shorthands.append((match[1][1:-1], match[2][1:-1])) new_lines.append("".join(("# processed ", line))) else: new_lines.append(line) self.text = "\n".join(new_lines) class KiloParser(Parser): """ Implementation of the Kilogrammar parser """ # ================================================= # === tokens and keywords # ================================================= @match("whitespace|newline|comment") def ignore(self, ig): self.pop(1) @match("token", "name|word", priority=1) def token_start(self, token, name): self.pop(2) self.push("TOKEN_DEF_START", [name]) @match("TOKEN_DEF_START", "string", priority=1) def token_def_stage_1(self, tdef, string): self.pop(1) tdef.contents.append(string) tdef.type = "TOKEN_DEFINITION" @match("keyword", "string", priority=1) def keyword_def(self, keyword, string): self.pop(2) self.push("KEYWORD", [string]) # ================================================= # === rule definitions # ================================================= @match("rule", "word") def rule_name(self, rule, name): self.pop(2) self.push("RULE_DEF_NAME", [name]) @match("RULE_DEF_NAME", "(") def rule_def_start(self, name, par): self.pop(1) name.contents.append(Node("MATCH_LIST", [])) name.type = "RULE_DEF_MATCH_LIST" @match("RULE_DEF_MATCH_LIST", "NAME_GRP", ",|)") def rule_def_extend(self, rule, names, sep): self.pop(2) rule.contents[1].contents.append(names) self.push(sep) @match("RULE_DEF_MATCH_LIST", ",") def rule_strip_comma(self, rule, comma): self.pop(1) @match("RULE_DEF_MATCH_LIST", ")") def rule_natch_list_finish(self, rule, par): rule.type = "RULE_DEF" self.pop(1) @match("RULE_DEF", "BLOCK") def rule_finish(self, rule, block): self.pop(1) rule.contents.append(block) rule.type = "RULE_DEFINITION" # ================================================= # === name groups # ================================================= @match("NAME_GRP", "pipe", "name|word|string", priority=2) def mane_grp_extend(self, grp, pipe, name): self.pop(2) grp.contents.append(name) @match("name|word|string", ",|pipe|)", priority=-1) def name_grp(self, name, sep): self.pop(2) self.push("NAME_GRP", [name]) self.push(sep) # ================================================= # === indent blocks # ================================================= @match("FUNC_CALL", "indent_decrease") def block_end(self, call, indent): self.pop(2) self.push("BLOCK_END", [call]) @match("FUNC_CALL", "BLOCK_END", priority=0) def block_end_expand(self, call, block): self.pop(2) block.contents.append(call) self.push(block) @match("indent_increase", "BLOCK_END", priority=1) def block_finish(self, indent, block): self.pop(2) self.push("BLOCK", list(reversed(block.contents))) # ================================================= # === function calls # ================================================= @match("word", "(") def func_call_start(self, name, p): self.pop(2) self.push("FUNC_CALL_START", [name, Node("ARGS", [])]) @match("FUNC_CALL_START", "indent_increase|indent_decrease|inconsistent_indent") def ignore_indent(self, call, indent): self.pop(1) @match("FUNC_CALL_START", ",") def ignore_comma(self, func, separator): self.pop(1) @match("FUNC_CALL_START", "integer|NAME_GRP|FUNC_CALL", ",|)") def add_func_arg(self, func, arg, separator): self.pop(2) func.contents[1].contents.append(arg) self.push(separator) @match("FUNC_CALL_START", ")") def func_call_finish(self, func, par): self.pop(1) func.type = "FUNC_CALL" # ================================================= # === Node Indexing # ================================================= @match("INDEXES", ",|)") def indexes_to_func(self, indexes, sep): self.pop(2) self.push("FUNC_CALL", [Token("name", "get_node"), Node("ARGS", indexes.contents)]) self.push(sep) @match("[", "integer", "]") def make_index(self, sq, n, sq1): self.pop(3) self.push("INDEXES", [n]) @match("INDEXES", "INDEXES") def sub_index(self, i, j): self.pop(1) i.contents.append(j.contents[0]) KG_BUILTINS = """ # ============================================ # Kilogrammar language builtins # ============================================ def push(parser, matches, *args): for arg in args: parser.stack.append(arg) def pop(parser, matches, *args): if len(args) == 0: parser.stack.pop(-1) else: for _ in range(args[0]): parser.stack.pop(-1) def node(parser, matches, name_grp, *args): return Node(name_grp[0], list(args)) def pick_name(parser, matches, name_selector, name_grp_from, name_grp_to): if isinstance(name_selector, (Node, Token)): name_selector = name_selector.type elif isinstance(name_selector, tuple): name_selector = name_selector[0] return (name_grp_to[name_grp_from.index(name_selector)],) def get_node(parser, matches, *args): node = matches[args[0]] for index in args[1:]: node = node.contents[index] return node """ KG_BUILTINS_FUNC_LIST = [ "push", "pop", "node", "pick_name", "get_node" ] MAIN = r""" if __name__ == '__main__': import sys if "-color" in sys.argv: Color.enable() text = None if "-type" in sys.argv: text = input("\n\n input &gt;&gt;&gt;") elif len(sys.argv) &gt; 2 and os.path.isfile(sys.argv[1]): with open(sys.argv[1], "r") as f: text = f.read() if text is not None: if '-interactive' in sys.argv: preview_length = 999999 else: preview_length = 0 tokens = TokenizerClass(text) parser = ParserClass(tokens, preview=preview_length) parser.pretty_print(999999, 999999) else: print("this script seems to not have syntax errors.") """ def validate(parser): for node in parser.stack: if node.type not in\ {"indent_decrease", "indent_increase", "RULE_DEF", "TOKEN_DEFINITION", "KEYWORD", "RULE_DEFINITION"}: while isinstance(node, Node): #find a leaf token node = node.contents[0] panic(f"untexpected token: {node}", node.line, node.col, parser.text) def parser_compile(parser): rule_defs = [] token_defs = [] keyword_defs = [] def extract_high_level_parts(contents): for node in contents: if isinstance(node, Node): extract_high_level_parts(node.contents) if node == "RULE_DEFINITION": rule_defs.append(node) elif node == "TOKEN_DEFINITION": token_defs.append(node) elif node == "KEYWORD": keyword_defs.append(node) extract_high_level_parts(parser.stack) final_lines = [] # recicling a usefull piece of code that cant be expressed directly using # this language, with open(__file__, "r") as myself: myself.seek(0) lines = myself.readlines() start = 0 end = 0 for i, line in enumerate(lines): if line.startswith("# TAG1: reutilize code start"): start = i elif line.startswith("# TAG1: reutilize code end"): end = i code = "".join(lines[1 + start:end])[0:-1] code = code.replace("KiloTokenizer", "TokenizerClass") final_lines.append(code) for token_def in token_defs: name = token_def.contents[0].contents regex = token_def.contents[1].contents[1:-1] final_lines.append(f' ["{name}", "{regex}"],') for keyword_def in keyword_defs: name = keyword_def.contents[0].contents[1:-1] regex = re.escape(name) final_lines.append(f' ["{name}", "{regex}"],') final_lines.append(" ]") def make_match_list(match_list): args = [] for name_grp in match_list.contents: arg = [] for name in name_grp.contents: if name == "string": arg.append(f"'{name.contents[1:-1]}'") elif name in {"word", "name"}: arg.append(f"'{name.contents}'") args.append("".join(("{", ", ".join(arg), "}"))) return ", ".join(args) def make_func_call(node): contents = node.contents name_token = contents[0] name = name_token.contents if name not in KG_BUILTINS_FUNC_LIST: panic(f"function does not exist: {name}", line=name_token.line, col=name_token.col, text=parser.text) argumments = contents[1].contents args = [] for arg in argumments: if arg.type in "integer": args.append(arg.contents) elif arg.type == "FUNC_CALL": args.append(make_func_call(arg)) elif arg.type == "NAME_GRP": args.append(repr(tuple(node.contents for node in arg.contents))) return f"{name}(parser, matches, {', '.join(args)})" final_lines.extend([KG_BUILTINS]) final_lines.append("class ParserClass(Parser):") final_lines.append("") for i, rule in enumerate(rule_defs): rule = rule.contents func_name = rule[0].contents block = rule[2].contents match_args = make_match_list(rule[1]) final_lines.append(f" @match({match_args}, priority={-i})") final_lines.append(f" def rule{i}_{func_name}(parser, *matches):") for func_call in block: final_lines.append(f" {make_func_call(func_call)}") final_lines.append("") final_lines.append(MAIN) for line in final_lines: print(line) if __name__ == "__main__": import sys if len(sys.argv) &gt; 1: with open(sys.argv[1], "r") as f: tok = KiloTokenizer(f.read() + "\n;") if "-color" in sys.argv: Color.enable() if "-compile" in sys.argv: parser = KiloParser(tok, preview=0) validate(parser) parser_compile(parser) else: if "-interactive" in sys.argv: preview = 999999 else: preview = 0 parser = KiloParser(tok, preview=preview) parser.pretty_print(999999, 999999) validate(parser) </code></pre> <p>you can run it using: <code>python kilogrammar.py some_input_grammar.txt -compile &gt; output_parser.py</code></p> <p>To test your new parser just <code>python output_parser.py some_input.txt -color</code> it should print a syntax tree.</p> <p>or to watch the syntax tree being constructed: <code>python output_parser.py some_input.txt -interactive -color</code></p> <p>it also works for the parser generator itsel: <code>python kilogrammar.py some_input_grammar.txt -interactive -color</code></p> <p>Even thought it's a toy project and I had no idea of what I was making I would like to know your thoughts about the usability and quality of it, specially about the meta-grammar(?) used by it.</p>
[]
[ { "body": "<h2>Singletons</h2>\n\n<p><code>Color</code> has been written as a singleton. That's fine I guess, but it doesn't need the class machinery. All you're effectively doing is making an inner scope. (You're also missing defaults.) You could get away with a submodule called <code>color</code> whose <code>__init__.py</code> consists of</p>\n\n<pre><code>RED: str = ''\nYELLOW: str = ''\nPINK: str = ''\nCYAN: str = ''\nGREEN: str = ''\nRESET: str = ''\n\ndef enable():\n global RED, YELLOW, PINK, CYAN, GREEN, RESET\n RED, YELLOW, PINK, CYAN, GREEN, RESET = (\n f'\\u001b[{code}m'\n for code in (\n '31',\n '38;5;221',\n '38;5;213',\n '38;5;38',\n '38;5;112',\n '0',\n )\n )\n\n# Similar disable\n</code></pre>\n\n<h2>Type hints</h2>\n\n<p>I have no way of knowing, in the entire definition of the <code>Token</code> class, what <code>token_type</code> is. If it's a string, declare it <code>: str</code> in the function signatures where it appears.</p>\n\n<h2>Typo</h2>\n\n<p><code>collumn</code> -> <code>column</code></p>\n\n<p><code>argumments</code> -> <code>arguments</code></p>\n\n<p><code>recicling</code> -> <code>recycling</code></p>\n\n<p><code>usefull</code> -> <code>useful</code></p>\n\n<h2>Strange logic</h2>\n\n<pre><code> if len(self.rules) &gt; n or len(self.rules) &gt; n:\n</code></pre>\n\n<p>looks like the second predicate is redundant.</p>\n\n<h2>Loop like a native</h2>\n\n<p>Without having tried it, </p>\n\n<pre><code> i = 0\n for rule in reversed(self.rules):\n item = parser.stack[-1 - i]\n i += 1\n</code></pre>\n\n<p>looks like it could be</p>\n\n<pre><code>for rule, item in reversed(zip(self.rules, parser.stack)):\n</code></pre>\n\n<h2>Imports</h2>\n\n<pre><code>import inspect\n</code></pre>\n\n<p>should appear at the top, not in function scope, unless you have a really good reason.</p>\n\n<h2>Generator</h2>\n\n<p>This</p>\n\n<pre><code>match_rules = []\nfor arg in args:\n if arg == None or type(arg) == set:\n match_rules.append(arg)\n elif isinstance(arg, str):\n match_rules.append({s for s in arg.split(\"|\") if s})\n else:\n raise TypeError(f\"wrong type of argumment: {type(arg)}, {arg}\")\n</code></pre>\n\n<p>should be pulled out into a function that, rather than building up <code>match_rules</code>, <code>yield</code>s your set on the inside of the loop.</p>\n\n<h2>Length of a comprehension</h2>\n\n<p>Isn't</p>\n\n<pre><code>arg_count = len([type(arg) for arg in args]) + 1\n</code></pre>\n\n<p>just</p>\n\n<pre><code>arg_count = len(args) + 1\n</code></pre>\n\n<p>?</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-06T02:27:20.383", "Id": "470746", "Score": "0", "body": "wow, Those are such naive mistakes.\nHow could I not see them. Thanks." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-06T01:50:34.940", "Id": "240017", "ParentId": "239835", "Score": "2" } } ]
{ "AcceptedAnswerId": "240017", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-02T22:02:44.143", "Id": "239835", "Score": "4", "Tags": [ "python", "python-3.x", "parsing", "meta-programming" ], "Title": "A self contained parser generator implementation" }
239835
<p>I am writing unit test for this function - </p> <pre><code>public void DeleteExpiredArchiveFiles(string directory, int daysInArchive) { //Delete files from the directory which are older than parameter - daysInArchive } </code></pre> <p>I need to access some sample files in the code for this unit test.<br> What is the correct approach -<br> - Add sample files in the Unit Test project and set them to 'Copy to output directory' or<br> - Add sample files to some location like on C:\SampleFiles folder</p> <p>I prefer first approach here, so any other developer running these tests, do not have to copy files to correct folder before running unit tests.</p> <p>Any comments - Is there any other better approach?</p> <p>Thank you!</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-03T05:48:28.983", "Id": "470490", "Score": "0", "body": "Can't you test against FS Mock?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-03T22:38:19.903", "Id": "470585", "Score": "1", "body": "Where is the code to be reviewed?" } ]
[ { "body": "<p>You should create the files in the test setup.<br>\nCreating and deleting files in the file system takes some time. Using some FS mock / fake will make the test run much faster.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-04T08:52:16.927", "Id": "239909", "ParentId": "239839", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-02T23:34:32.747", "Id": "239839", "Score": "-1", "Tags": [ "unit-testing", "nunit" ], "Title": "Unit Testing - test deletion of archived files" }
239839
<p>With this code, i loop through similar xml files and add them to a DataFrame.</p> <p>How can i make this code better so it is more pythonic?</p> <pre><code>Dados = pd.DataFrame([]) folder = os.listdir(path) for file in folder: if file.endswith('.xml'): with open(os.path.join(path, file), encoding="utf8") as fd: doc = xmltodict.parse(fd.read()) if 'InformeMensal' in doc['DadosEconomicoFinanceiros'].keys(): DadosEconomicoFinanceiros = doc['DadosEconomicoFinanceiros'] NomeFundo = doc['DadosEconomicoFinanceiros']['DadosGerais']['NomeFundo'] CNPJFundo = doc['DadosEconomicoFinanceiros']['DadosGerais']['CNPJFundo'] NomeAdministrador = doc['DadosEconomicoFinanceiros']['DadosGerais']['NomeAdministrador'] PublicoAlvo = doc['DadosEconomicoFinanceiros']['DadosGerais']['PublicoAlvo'] InformeMensal = doc['DadosEconomicoFinanceiros']['InformeMensal'] InformeMensalCotistas = doc['DadosEconomicoFinanceiros']['InformeMensal']['Cotistas'] if '@total' in doc['DadosEconomicoFinanceiros']['InformeMensal']['Cotistas'].keys(): TotalCotistas = doc['DadosEconomicoFinanceiros']['InformeMensal']['Cotistas']['@total'] pass if not '@total' in doc['DadosEconomicoFinanceiros']['InformeMensal']['Cotistas'].keys(): TotalCotistas = "0" pass if 'FundosInvImobiliario' in doc['DadosEconomicoFinanceiros']['InformeMensal']['Cotistas'].keys(): FIIsCotistas = doc['DadosEconomicoFinanceiros']['InformeMensal']['Cotistas']['FundosInvImobiliario'] pass if not 'FundosInvImobiliario' in doc['DadosEconomicoFinanceiros']['InformeMensal']['Cotistas'].keys(): FIIsCotistas = "0" pass InformeMensalResumo = doc['DadosEconomicoFinanceiros']['InformeMensal']['Resumo'] Ativo = doc['DadosEconomicoFinanceiros']['InformeMensal']['Resumo']['Ativo'] PatrimonioLiquido = doc['DadosEconomicoFinanceiros']['InformeMensal']['Resumo']['PatrimonioLiquido'] NumCotasEmitidas = doc['DadosEconomicoFinanceiros']['InformeMensal']['Resumo']['NumCotasEmitidas'] ValorPatrCotas = doc['DadosEconomicoFinanceiros']['InformeMensal']['Resumo']['ValorPatrCotas'] DespesasTxAdministracao = doc['DadosEconomicoFinanceiros']['InformeMensal']['Resumo']['DespesasTxAdministracao'] DespesasAgCustodiante = doc['DadosEconomicoFinanceiros']['InformeMensal']['Resumo']['DespesasAgCustodiante'] RentEfetivaMensal = doc['DadosEconomicoFinanceiros']['InformeMensal']['Resumo']['RentEfetivaMensal'] AmortizAcoesCotas = doc['DadosEconomicoFinanceiros']['InformeMensal']['Resumo']['AmortizAcoesCotas'] InformeMensalInformacoesAtivo = doc['DadosEconomicoFinanceiros']['InformeMensal']['InformacoesAtivo'] TotalNecessidadesLiq= doc['DadosEconomicoFinanceiros']['InformeMensal']['InformacoesAtivo']['TotalNecessidadesLiq'] TotalInvestido= doc['DadosEconomicoFinanceiros']['InformeMensal']['InformacoesAtivo']['TotalInvestido'] ValoresReceber= doc['DadosEconomicoFinanceiros']['InformeMensal']['InformacoesAtivo']['ValoresReceber'] InformeMensalInformacoesPassivo = doc['DadosEconomicoFinanceiros']['InformeMensal']['InformacoesPassivo'] RendimentosDistribuir = doc['DadosEconomicoFinanceiros']['InformeMensal']['InformacoesPassivo']['RendimentosDistribuir'] TxAdministracaoPagar = doc['DadosEconomicoFinanceiros']['InformeMensal']['InformacoesPassivo']['TxAdministracaoPagar'] TxPerformancePagar = doc['DadosEconomicoFinanceiros']['InformeMensal']['InformacoesPassivo']['TxPerformancePagar'] ObrigacoesAquisicaoImov = doc['DadosEconomicoFinanceiros']['InformeMensal']['InformacoesPassivo']['ObrigacoesAquisicaoImov'] AdiantamentoVendaImov = doc['DadosEconomicoFinanceiros']['InformeMensal']['InformacoesPassivo']['AdiantamentoVendaImov'] AdiantamentoAlugueis = doc['DadosEconomicoFinanceiros']['InformeMensal']['InformacoesPassivo']['AdiantamentoAlugueis'] ObrigacoesSecRecebiveis = doc['DadosEconomicoFinanceiros']['InformeMensal']['InformacoesPassivo']['ObrigacoesSecRecebiveis'] InstrumentosFinanceirosDeriv = doc['DadosEconomicoFinanceiros']['InformeMensal']['InformacoesPassivo']['InstrumentosFinanceirosDeriv'] ProvisoesContigencias = doc['DadosEconomicoFinanceiros']['InformeMensal']['InformacoesPassivo']['ProvisoesContigencias'] OutrosValoresPagar = doc['DadosEconomicoFinanceiros']['InformeMensal']['InformacoesPassivo']['OutrosValoresPagar'] TotalPassivo = doc['DadosEconomicoFinanceiros']['InformeMensal']['InformacoesPassivo']['TotalPassivo'] Data = doc['DadosEconomicoFinanceiros']['InformeMensal']['Cotistas'] ['@data_informacao'] Dados = Dados.append(pd.DataFrame({'Data':Data,'Nome': NomeFundo, 'CNPJ': CNPJFundo,'NomeAdministrador':NomeAdministrador,'PublicoAlvo':PublicoAlvo,'CotistasTotal':TotalCotistas,'FIIsCotistas':FIIsCotistas,'Ativo':Ativo,'PatrimonioLiquido':PatrimonioLiquido,'NumCotasEmitidas':NumCotasEmitidas,'ValorPatrCotas':ValorPatrCotas,'DespesasTxAdministracao':DespesasTxAdministracao,'DespesasAgCustodiante':DespesasAgCustodiante,'RentEfetivaMensal':RentEfetivaMensal,'AmortizAcoesCotas':AmortizAcoesCotas,'TotalNecessidadesLiq':TotalNecessidadesLiq, 'TotalInvestido':TotalInvestido, 'ValoresReceber':ValoresReceber,'RendimentosDistribuir':RendimentosDistribuir, 'TxAdministracaoPagar':TxAdministracaoPagar, 'TxPerformancePagar':TxPerformancePagar, 'ObrigacoesAquisicaoImov':ObrigacoesAquisicaoImov,'AdiantamentoVendaImov':AdiantamentoVendaImov, 'AdiantamentoAlugueis':AdiantamentoAlugueis, 'ObrigacoesSecRecebiveis':ObrigacoesSecRecebiveis,'InstrumentosFinanceirosDeriv':InstrumentosFinanceirosDeriv, 'ProvisoesContigencias':ProvisoesContigencias, 'OutrosValoresPagar':OutrosValoresPagar, 'TotalPassivo':TotalPassivo}, index=[0]), ignore_index=True) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-03T00:48:55.680", "Id": "470469", "Score": "0", "body": "Could you add some more info on the intent here? There's a huge amount of non-english words, so it's hard to determine the intent behind your code. Some inline comments might help get you some better feedback." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-03T00:53:34.633", "Id": "470471", "Score": "0", "body": "Also, extracting variables is probably a good place to start, so that there is less duplication. In fact, it looks like you do that: `InformeMensal = doc['DadosEconomicoFinanceiros']['InformeMensal']`, but you don't reuse that variable, when you could on nearly every following line, and that would make it more readable, most likely. Generally it's more clear when there is only one index (`[]`) or `.` in a row, although there are exceptions to that rule." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-03T01:14:56.817", "Id": "470474", "Score": "0", "body": "These are balance sheets of Brazilian real estate funds, that's why the non English words, but those are just the keys inside the 'doc' dict created by XMLtodict. I loop through all xml in folder and append these keys values to the df Dados" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-03T12:31:44.777", "Id": "470529", "Score": "0", "body": "Please include your `import` statements as well. While most of them look like they are standards, `xmltodict` does not." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-03T12:34:53.767", "Id": "470530", "Score": "0", "body": "Also, what does the XML structure look like? It seems to be the same for all files (otherwise you couldn't hardcode extracting the values), but do you e.g extract all fields, or only some?" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-02T23:39:28.267", "Id": "239840", "Score": "1", "Tags": [ "python", "xml", "pandas" ], "Title": "Improving loop through xml files ad add to DF" }
239840
<p>I need to read multiple CSV files that have the same number of rows, and compute some results for each row. For simplification purposes, and in the scope of this code review, this computation would be "sum each column of each row". </p> <p>I would like to be able to do so using the <a href="https://c2fo.io/fast-csv/" rel="nofollow noreferrer">fast-csv</a> parser that triggers events on each row reading. Mostly to avoid having to load the entire file into variables and then compute what I need.</p> <p>I came up with the following solution, with a dummy example to sum the values from each file. It seems to be working, but because I'm working with events, I'm not sure if there might be a case when some data could go missing, or if there's any other issue. I would appreciate any help to improve performance, functionality, maintainability, readability, etc..</p> <p>Because executing the code requires an external dependency and some files, <a href="https://repl.it/repls/IllfatedStaticConstant" rel="nofollow noreferrer">here's a Repl.it</a>.</p> <p>Here's the code if you just want to read:</p> <pre><code>const csv = require("fast-csv"); const fs = require('fs'); const EventEmitter = require('events'); const files = ['csv/file1.csv', 'csv/file2.csv']; // Create parsers for each file const parsers = files.map(file =&gt; csv.parseStream(fs.createReadStream(file), { delimiter: ';', headers: false })); // Variables to hold temporary data and definitive results const data = parsers.map(() =&gt; []); let result = []; // Handler for a set of the same row from all the different files var eventEmitter = new EventEmitter(); eventEmitter.on('allRows', (rows) =&gt; { var sum = (r, a) =&gt; r.map((b, i) =&gt; Number(a[i]) + Number(b)); result.push(rows.reduce(sum)); }); // Handler to display the result once all files have been read eventEmitter.on('end', (rows) =&gt; { console.log("result", result); }); // Handler for each row reading const onDataHandler = function(row, idx) { data[idx].push(row); // When we have a row parsed for each file, we emit a signal if (data.reduce((acc, el) =&gt; acc &amp;&amp; el.length &gt; 0, true)) { if (data.reduce((acc, el) =&gt; acc &amp;&amp; el[0] === null, true)) { // 'end' if all results have been shifted eventEmitter.emit('end'); } else { // 'allRows' otherwise, with the first element of each file eventEmitter.emit( 'allRows', data.reduce((acc, el) =&gt; { acc.push(el.shift()); return acc; }, []) ); } } } // We use readable to use 'flowing' mode and make sure we don't miss the last rows parsers.forEach((parser, idx) =&gt; parser.on('readable', () =&gt; { onDataHandler(parser.read(), idx); })); </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-03T07:58:14.443", "Id": "470505", "Score": "0", "body": "Welcome to Code Review. Your question looks quite good, I have already upvoted. But to truly comply with rules of this site, please consider being more specific about \"compute some results\"." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-03T08:15:10.623", "Id": "470506", "Score": "0", "body": "@slepic Thanks for commenting. My actual need is a bit complicated so I have simplified it to summing the values for each column of each file. I have edited my original post to be more specific about what the code does" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-03T15:17:20.463", "Id": "470554", "Score": "0", "body": "You generally shouldn't simplify your code for Code Review. You should copy-and-paste verbatim what you have." } ]
[ { "body": "<p>If you want to check whether every item in an array passes a test, you should use <code>.every</code> for that, not <code>.reduce</code>. Eg</p>\n\n<pre><code>data.reduce((acc, el) =&gt; acc &amp;&amp; el.length &gt; 0, true)\n</code></pre>\n\n<p>can be switched with</p>\n\n<pre><code>data.every(arr =&gt; arr.length)\n</code></pre>\n\n<p>and</p>\n\n<pre><code>data.reduce((acc, el) =&gt; acc &amp;&amp; el[0] === null, true)\n</code></pre>\n\n<p>can be switched with</p>\n\n<pre><code>data.every(arr =&gt; arr[0] === null)\n</code></pre>\n\n<p>Also, when you want to transform one array into another, <code>.map</code> is the right method, not <code>.reduce</code>. Or, when you just want to copy an array exactly, use <code>.slice()</code> or spread it. Change</p>\n\n<pre><code>data.reduce((acc, el) =&gt; {\n acc.push(el.shift());\n return acc;\n}, [])\n</code></pre>\n\n<p>to</p>\n\n<p><code>[...data]</code></p>\n\n<hr>\n\n<p>On a broader note, I would consider the logic to be a lot easier to follow if it was separated into two parts: one part to read the files and deal with the asynchronicity, and another part to (synchronously) combine into a single array. I think mixing the two and using <code>eventEmitter</code> makes things more difficult to understand than they need to be.</p>\n\n<p>A somewhat minor issue is that you're requiring all rows of a particular index to be kept in memory until they've all been parsed. In the case that you're dealing with a large number of files, or the rows are large, it would be better to combine them as soon as possible, as they come in, so that the only persistent data structure is the output array of arrays (rather than an array of arrays for each separate <code>.csv</code>).</p>\n\n<p>When any row is parsed, you can call a function that combines it with the results array. You can also map each <code>parseStream</code> to a Promise that resolves once its <code>end</code> event fires, and use <code>Promise.all</code> to log the final results array once all parsers are completed:</p>\n\n<pre><code>const result = [];\nconst combineRow = (row, rowIndex) =&gt; {\n const targetRow = result[rowIndex];\n if (!targetRow) {\n result[rowIndex] = row;\n return;\n }\n row.forEach((cell, cellIndex) =&gt; {\n targetRow[cellIndex] = (targetRow[cellIndex] || 0) + cell;\n });\n}\nconst getRows = parser =&gt; new Promise((resolve, reject) =&gt; {\n let rowIndex = 0;\n parser.on('readable', () =&gt; {\n const row = parser.read();\n if (row) {\n combineRow(row.map(Number), rowIndex);\n rowIndex++;\n }\n });\n parser.on('end', resolve);\n});\n\nPromise.all(parsers.map(getRows))\n .then(() =&gt; {\n console.log(result);\n });\n</code></pre>\n\n<p><a href=\"https://repl.it/repls/EnchantedElaborateFiber\" rel=\"nofollow noreferrer\">https://repl.it/repls/EnchantedElaborateFiber</a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-04T02:19:29.547", "Id": "239902", "ParentId": "239849", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-03T07:53:11.487", "Id": "239849", "Score": "3", "Tags": [ "javascript", "node.js", "csv", "event-handling" ], "Title": "Summing CSV files row by row using Node.js events" }
239849
<p>I am kind of new to python, so I am pretty sure there are way better elegant ways to do this. I have made a function that is able to compare two list of possible json object paths, and detect what elements do not belong to the other list.</p> <p><strong>In the docstring you will find</strong> a better description with <strong>examples</strong>.</p> <p>I will also provide the <strong>test class with a lot of examples</strong></p> <p>It will also be appreciated any help on better docstring, since I am not really sure how to describe correctly what this method exactly does</p> <p><strong>Note</strong>: The code works on both Python 3 and 2.</p> <p>my_utils.py</p> <pre><code>""" Utils """ def list_diff(list1, list2): """Returns a new list with the items in list1 that do not belong to list2""" return list(set(list1) - set(list2)) def get_unknown_data_relations(expected_data_relations_paths, real_data_relations_paths): """ Obtain all those fields which are expected to be data_relations but they are not. This function does not check afterwards the real_data_relations_paths, if a expected_data_relations_paths is expected to have any field, it will assume it's correct . (['pet.field'],['pet']) is correct, but, (['pet2.field'],['pet']) it is not :param expected_data_relations_paths: list of field paths expected to be a data_relations :param real_data_relations_paths: list of field paths with real data_relations .. Examples: expected_data_relations_paths = ['pet'], real_data_relations_paths = ['pet'] Output = [] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ expected_data_relations_paths = ['name'], real_data_relations_paths = ['pet'] Output = [name] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ expected_data_relations_paths = ['name.field'], real_data_relations_paths = ['pet'] Output = [name.field] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ expected_data_relations_paths = ['pet'], real_data_relations_paths = ['pet', 'pet2'] Output = [] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ expected_data_relations_paths = ['pet.field'], real_data_relations_paths = ['pet'] Output = [] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ """ filtered = [] for expected in expected_data_relations_paths: temporal_expected = expected for data_relation in real_data_relations_paths: if related(expected, data_relation): temporal_expected = data_relation break filtered.append(temporal_expected) return list_diff(filtered, real_data_relations_paths) def related(path1, path2): """Returns True if path1 is related to path2, False otherwise""" return list_diff(path2.split('.'), path1.split('.')) == [] </code></pre> <p>Testing file:</p> <pre><code>""" You can auto-discover and run all tests with this command: $ pytest -c env_vars [-s] Documentation: * https://docs.pytest.org/en/latest/ * https://docs.pytest.org/en/latest/fixture.html """ from my_utils import get_unknown_data_relations def test_unit_get_unknown_data_relations_perfect_match(): """Tests the most simple case with perfect match""" assert len(get_unknown_data_relations(['pet'], ['pet'])) == 0 def test_unit_get_unknown_data_relations_missing_element(): """Tests a missing element""" assert get_unknown_data_relations(['unknown_field'], ['pet']) == ['unknown_field'] def test_unit_get_unknown_data_relations_single_expected_multiple_data_relations(): """Tests single expected belong to multiple data_relations""" assert get_unknown_data_relations(['pet'], ['pet', 'pet2']) == [] def test_unit_get_unknown_data_relations_multiple_expected_multiple_data_relations_exact_dimension(): """Tests multiple expected belong to multiple data_relations""" assert get_unknown_data_relations(['pet', 'pet2'], ['pet', 'pet2']) == [] def test_unit_get_unknown_data_relations_multiple_expected_and_unexpected_multiple_data_relations_exact_dimension(): """Tests multiple with an unexpected do not belong to multiple data_relations""" assert get_unknown_data_relations(['pet', 'pet4'], ['pet', 'pet2']) == ['pet4'] def test_unit_get_unknown_data_relations_multiple_expected_multiple_data_relations_different_dimension(): """Tests multiple expected belong to multiple data_relations with different dimension""" assert get_unknown_data_relations(['pet', 'pet3'], ['pet', 'pet2', 'pet3']) == [] def test_unit_get_unknown_data_relations_empty_expected_empty_data_relations(): """Tests empty expected belong to empty data_relations""" assert get_unknown_data_relations([], []) == [] def test_unit_get_unknown_data_relations_empty_expected_multiple_data_relations(): """Tests empty expected belong to multiple data_relations""" assert get_unknown_data_relations([], ['pet', 'pet2', 'pet3']) == [] def test_unit_get_unknown_data_relations_expected_embedded_single_data_relation(): """Tests single expected embedded belong to single data_relations""" assert get_unknown_data_relations(['pet.name'], ['pet']) == [] def test_unit_get_unknown_data_relations_expected_embedded_multiple_data_relation(): """Tests single expected embedded belong to multiple data_relations""" assert get_unknown_data_relations(['pet.name'], ['pet', 'pet2']) == [] def test_unit_get_unknown_data_relations_multiple_expected_embedded_multiple_data_relation(): """Tests multiple expected embedded belong to multiple data_relations""" assert get_unknown_data_relations(['pet.name', 'pet2.name'], ['pet', 'pet2']) == [] def test_unit_get_unknown_data_relations_unkown_expected_embedded_single_data_relation(): """Tests single unknown expected embedded do not belong to single data_relations""" assert get_unknown_data_relations(['unknown_relation.unknown_field'], ['pet']) == ['unknown_relation.unknown_field'] def test_unit_get_unknown_data_relations_unkown_expected_embedded_multiple_data_relation(): """Tests single unknown expected embedded do not belong to multiple data_relations""" assert get_unknown_data_relations( ['unknown_relation.unknown_field'], ['pet', 'pet2'] ) == ['unknown_relation.unknown_field'] def test_unit_get_unknown_data_relations_some_unkown_expected_embedded_single_data_relation(): """Tests some unknown expected embedded do not belong to single data_relations""" assert get_unknown_data_relations( ['unknown_relation.unknown_field', 'pet.field'], ['pet'] ) == ['unknown_relation.unknown_field'] def test_unit_get_unknown_data_relations_some_unkown_expected_embedded_multiple_data_relation(): """Tests some unknown expected embedded do not belong to multiple data_relations""" assert get_unknown_data_relations( ['unknown_relation.unknown_field', 'pet.field'], ['pet', 'pet2'] ) == ['unknown_relation.unknown_field'] </code></pre>
[]
[ { "body": "<p>For me, this is a little bit unclear</p>\n\n<pre><code>def list_diff(list1, list2):\n \"\"\"Returns a new list with the items in list1 that do not belong to list2\"\"\"\n return list(set(list1) - set(list2))\n</code></pre>\n\n<p>since you don't just return a new list with the items in <code>list1</code> that are not in <code>list2</code>, but you also remove duplicates from <code>list1</code> (which maybe is what you want to do?), and you change the order of the list. If you wanted to \"return a new list with the items in list1 that are not in list2\" (quoting because I'm not sure what you mean by \"do not belong to\"), you could also write <code>return [digit for digit in list1 if digit not in list2]</code>.</p>\n\n<p>And I think I also find the docstring for </p>\n\n<pre><code>def related(path1, path2):\n \"\"\"Returns True if path1 is related to path2, False otherwise\"\"\"\n return list_diff(path2.split('.'), path1.split('.')) == []\n</code></pre>\n\n<p>a little bit confusing. I would also like it if you type hinted, or if you expanded on your docstring to include argument and return description; you write a little with reST-style in the function above so why not also here? Speaking of this function, by the way, I like that you're comparing against an empty list. It may bring a tiny overhead in creating the list, but it helps the readability a lot.</p>\n\n<p>I think the \"main\" function (<code>get_unknown_data_relations</code>) also could benefit from a little bit of work on the docstring. It's descriptive, but 6 examples (if you count also the in-line one) seems a bit exaggerated. It could maybe also be turned into something a bit more pythonic, but it's good enough to not struggle with trying to turn it into a list comprehension.</p>\n\n<hr>\n\n<p>I like that you've written tests. I don't (have to) write docstrings for my tests, so I would skip that since the names tend to describe the tests well enough, but maybe you have a different workflow. I would recommend looking into <a href=\"https://docs.pytest.org/en/latest/fixture.html\" rel=\"nofollow noreferrer\">fixtures</a> if you haven't. You could also have a look at mutation testing, but maybe you already have and maybe all of your tests are already sufficiently safe.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-03T08:48:41.437", "Id": "470509", "Score": "0", "body": "Thanks for your comments!! I appreciate them a lot!! :) Didn't you find anyythin wrong in the anidated loops? It is where I struggled more, needed to write break... I don't find it like a clean style code, specially in python where you can do pretty things as the one you described for my list_diff (Which I'm not used to since I come from java, js, and c)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-03T09:16:29.583", "Id": "470512", "Score": "0", "body": "I've updated the answer now @Mayday." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-03T09:30:45.567", "Id": "470513", "Score": "0", "body": "I'm sorry to say that doesn't produce the same results @ades, since the \"else path\" gets executed extra times (that's why I had a break). But it helped me a lot to learn other stuff, like arguments types declarations, and the view of your more \"pythonically\" way to do things! :) :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-03T10:04:05.500", "Id": "470517", "Score": "0", "body": "Ahh, my bad. Yeah it actually complicates things a little. I think you could use [takewhile](https://docs.python.org/3/library/itertools.html#itertools.takewhile), but it's honestly fine to just leave it as it is; it's readable and it works." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-03T10:07:29.283", "Id": "470519", "Score": "0", "body": "Great!! Thank you very much!! Edit please the last non-working part, so I will accept the answer :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-03T10:20:03.540", "Id": "470521", "Score": "0", "body": "Done, and you're very welcome." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-03T08:33:28.533", "Id": "239852", "ParentId": "239850", "Score": "1" } } ]
{ "AcceptedAnswerId": "239852", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-03T08:06:29.947", "Id": "239850", "Score": "1", "Tags": [ "python", "array", "set" ], "Title": "Finding data relations of json paths in python" }
239850
<p>I timed a few ways to look for a string in a string array (with 82 elements in the example) in a case sensitive manner plus ignoring case.</p> <p>I am kind of suprised, that the plain for loops are faster than all other variants. </p> <ol> <li>Sure, there are no checks, but are there any other flaws here? </li> <li>Does Linq not do some vectorization behind the scenes? </li> <li>Can I w/o concerns use these loops? </li> <li>Any other notes?</li> </ol> <p><strong>Code</strong></p> <pre><code>class Program { static void Main(string[] args) { Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture; StringArrayContains(); Console.Read(); } public static void StringArrayContains() { // Init timing var watch = Start(); watch.Stop(); watch.Reset(); // Setup vars string query = "big"; string[] stringArray = GetStringArray(); bool contains = false; int times = (int)1e6; Console.WriteLine("Case Sensitive Search"); // Loop with case sensitive equal watch.Start(); for (int i = 0; i &lt; times; i++) { for (int j = 0; j &lt; stringArray.Length; j++) { if (string.CompareOrdinal(query, stringArray[j]) == 0) { contains = true; break; } } } Stop(watch, $"Loop with case sensitive equal", times); // Array.Exists + Equals watch.Start(); for (int i = 0; i &lt; times; i++) { contains = Array.Exists(stringArray, item =&gt; string.CompareOrdinal(item, query) == 0); } Stop(watch, $"Array.Exists + Equals", times); // Array.Exists + == watch.Start(); for (int i = 0; i &lt; times; i++) { contains = Array.Exists(stringArray, item =&gt; item == query); } Stop(watch, $"Array.Exists + ==", times); // Array.IndexOf watch.Start(); for (int i = 0; i &lt; times; i++) { contains = Array.IndexOf(stringArray, query) &gt; -1; } Stop(watch, $"Array.IndexOf", times); Console.WriteLine("Case Insensitive Search"); // Loop with case insensitive equal watch.Start(); for (int i = 0; i &lt; times; i++) { for (int j = 0; j &lt; stringArray.Length; j++) { if (string.Equals(query, stringArray[j], StringComparison.OrdinalIgnoreCase)) { contains = true; break; } } } Stop(watch, $"Loop with case insensitive equal", times); // Array.Exists + EqualsIgnoreCase watch.Start(); for (int i = 0; i &lt; times; i++) { contains = Array.Exists(stringArray, item =&gt; string.Equals(item, query, StringComparison.OrdinalIgnoreCase)); } Stop(watch, $"Array.Exists + EqualsIgnoreCase", times); // Linq Contains: OrdinalIgnoreCase watch.Start(); for (int i = 0; i &lt; times; i++) { contains = stringArray.Contains(query, StringComparer.OrdinalIgnoreCase); } Stop(watch, $"Linq Contains: OrdinalIgnoreCase", times); // Linq Contains: InvariantCultureIgnoreCase watch.Start(); for (int i = 0; i &lt; times; i++) { contains = stringArray.Contains(query, StringComparer.InvariantCultureIgnoreCase); } Stop(watch, $"Linq Contains: InvariantCultureIgnoreCase", times); // Linq Contains: CurrentCultureIgnoreCase watch.Start(); for (int i = 0; i &lt; times; i++) { contains = stringArray.Contains(query, StringComparer.CurrentCultureIgnoreCase); } Stop(watch, $"Linq Contains: CurrentCultureIgnoreCase", times); if (!contains) throw new Exception(); } #region Miscellaneous public static string[] GetStringArray() { string words = @"the that not look put and with then don’t could a all were come house to we go will old said can little into too in are as back by he up no from day I had mum children made of my one him time it her them Mr I’m was what do get if you there me just help they out down now Mrs on this dad came called she have big oh here is went when about off for be it’s got asked at like see their saw his some looked people make but so very your an "; return words.Split(" "); } public static Stopwatch Start() =&gt; Stopwatch.StartNew(); public static void Stop(Stopwatch watch, string item, int? cnt = null) { watch.Stop(); string msg = $"{item,53}\ttook {watch.ElapsedMilliseconds,6:#,0} ms"; if (cnt != null) msg += $" to execute {cnt:#,0} times ({watch.ElapsedMilliseconds * 1e3 / cnt:0.0} us per exec)."; watch.Reset(); Console.WriteLine(msg); Debug.WriteLine(msg); Console.WriteLine(""); Debug.WriteLine(""); } #endregion } </code></pre> <p><strong>Result</strong></p> <pre><code>Case Sensitive Search Loop with case sensitive equal took 323 ms to execute 1,000,000 times (0.3 us per exec). Array.Exists + Equals took 445 ms to execute 1,000,000 times (0.4 us per exec). Array.Exists + == took 461 ms to execute 1,000,000 times (0.5 us per exec). Array.IndexOf took 511 ms to execute 1,000,000 times (0.5 us per exec). Case Insensitive Search Loop with case insensitive equal took 408 ms to execute 1,000,000 times (0.4 us per exec). Array.Exists + EqualsIgnoreCase took 543 ms to execute 1,000,000 times (0.5 us per exec). Linq Contains: OrdinalIgnoreCase took 827 ms to execute 1,000,000 times (0.8 us per exec). Linq Contains: InvariantCultureIgnoreCase took 6,220 ms to execute 1,000,000 times (6.2 us per exec). Linq Contains: CurrentCultureIgnoreCase took 6,249 ms to execute 1,000,000 times (6.2 us per exec). </code></pre> <p>Edit: Added code to have MWE</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-03T10:06:14.200", "Id": "470518", "Score": "0", "body": "Could you post the other functions, so the benchmark can be replicated? I made up some reasonable implementations, but I got different results. The .NET runtime version is also a variable: I used .NET Core 3.0. The result didn't contradict yours by the way, it was *even more extreme*, the plain loop was almost 2.5 times as fast as `Array.Exists`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-03T16:17:23.650", "Id": "470558", "Score": "0", "body": "@harold Yepp, sorry. I edited and posted the complete class. Results are from running it using .NET Core 3.1 on a simply i5 3570 Win10 x64 machine." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-03T21:50:17.170", "Id": "470583", "Score": "0", "body": "Aside: consider using benchmarkDotNet for this kind of micro benchmark." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-06T11:13:20.670", "Id": "470778", "Score": "0", "body": "I'm sorry but, unless this is an _academic question_, then any answer won't have any sense. This sort of comparison makes no sense without MUCH more context and a much more careful setup. Just to mention few: you're comparing with `String.CompareOrdinal` while you actually need `String.Equal()` with the appropriate comparer. Why? Because, in theory, an implementation MIGHT perform an ordinal case sensitive comparison slightly faster (for example because it just need to compare `ZF` after calling `REPE CMPSx`, this assuming that the compiler will optimize your own `== 0` away anyway)..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-06T11:15:53.450", "Id": "470779", "Score": "0", "body": "...also, for `IndexOf` you're comparing different things then it doesn't really make sense to have it here. If - in the real world case - you will search inside the array multiple times then you'll find yourself that (MAYBE) to sort the array and then performing a `BinarySearch` is actually faster. Also, other approaches might be easier to make parallel (if the number of items in the array is big enough to justify it)." } ]
[ { "body": "<p>I don't know why you are surprised plain loops are faster, without an explanation of why you were surprised, it is hard to comment on that. Linq is bound to have some overhead. </p>\n\n<p>By vectorisation I guess you mean the use of special machine instructions, I doubt these would have any significant effect here. Most of the comparisons will fail at the first letter, so I don't see how a special string compare instruction would help.</p>\n\n<p>A fast way of checking whether a string is in a large set of strings would be to use hashing, using the library class System.Collections.Generic.HashSet.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-06T07:04:24.537", "Id": "240032", "ParentId": "239853", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-03T08:36:18.283", "Id": "239853", "Score": "1", "Tags": [ "c#", "performance", "strings", "array", "search" ], "Title": "Performance: Use plain for loops to look for (existence of) string in string array?" }
239853
<p>You're given the number of rows and columns and the indices for the reference point. Reference point is = 0.<br> i.e:<br> 3 4 3 3<br> output:<br> 4 3 2 3<br> 3 2 1 2<br> 2 1 0 1</p> <p>I managed to solve the problem using the easiest solution there is. I calculated the elements from the same column, and then using 2 for loops I used for every single element the already calculated value from the respective row as a new reference point. I was stuck on this at first because I tried to come up with a formula so I asked on stackoverflow, and told me to submit a code, any solution.. so I came up with this:</p> <pre><code>#include &lt;iostream&gt; using namespace std; int main() { int v[501][501], i, j, m, n, o, p; cin &gt;&gt; m &gt;&gt; n &gt;&gt; o &gt;&gt; p; for (i = o; i &gt;= 1; i--) v[i][p] = o - i; for(i = o;i &lt;= m; i++) v[i][p] = i - o; for(i = 1; i &lt;= m; i++) for(j = 1; j &lt;= n; j++){ if(j &lt; p) v[i][j] = -j + p + v[i][p]; else if(j &gt; p) v[i][j] = j - p + v[i][p]; } for(i = 1 ; i &lt;= m; i++){ for(j = 1; j &lt;= n; j++) cout &lt;&lt; v[i][j] &lt;&lt; " "; cout &lt;&lt; '\n'; } } </code></pre> <p>How can I improve it?</p>
[]
[ { "body": "<p>Some suggestions:</p>\n\n<ul>\n<li>Use variable names that tells the reader what they are.</li>\n<li>Dont do <code>using namespace std;</code> in the global namespace.</li>\n<li>Always check that <code>&lt;stream&gt; &gt;&gt; variable</code> actually worked or else your program will run with uninitialized variables and cause undefined behaviour if they are read.</li>\n<li>Use an unsigned type when dealing with subscripting.</li>\n<li>If you use a hardcoded array size, check that the values entered by the user actually fits in the array.</li>\n<li>Don't use a hardcoded array size when the required size is unknown at compile time.</li>\n<li>Use 0-based arrays instead of 1-based.</li>\n</ul>\n\n<p>When it comes to the actual algorithm, it seems like that the shortest path from any point is<br>\n <code>abs(point.row - reference.row) + abs(point.column - reference.column)</code><br>\nwhich would give code like this:</p>\n\n<pre><code>#include &lt;cstdlib&gt;\n#include &lt;iostream&gt;\n#include &lt;limits&gt;\n#include &lt;vector&gt;\n\n// a helper type to keep the reference point\nclass point_t {\npublic:\n point_t() : point_t(0, 0) {}\n point_t(unsigned Row, unsigned Col) : row(Row), col(Col) {}\n\n // a function to calculate the distance to another point\n unsigned distance_to(const point_t&amp; p) const {\n return static_cast&lt;unsigned&gt;(\n std::abs(static_cast&lt;int&gt;(row) - static_cast&lt;int&gt;(p.row)) +\n std::abs(static_cast&lt;int&gt;(col) - static_cast&lt;int&gt;(p.col)));\n }\n\n // reading the point from an istream\n friend std::istream&amp; operator&gt;&gt;(std::istream&amp; is, point_t&amp; p) {\n return is &gt;&gt; p.row &gt;&gt; p.col;\n }\n\nprivate:\n unsigned row;\n unsigned col;\n};\n\nint main() {\n unsigned rows;\n unsigned cols;\n point_t ref;\n\n if(std::cin &gt;&gt; rows &gt;&gt; cols &gt;&gt; ref) {\n // check that it's not too big\n if(rows &gt; std::numeric_limits&lt;int&gt;::max() ||\n cols &gt; std::numeric_limits&lt;int&gt;::max()) {\n std::cerr &lt;&lt; \"matrix too big\\n\";\n return 1;\n }\n\n // create a 2D vector\n std::vector&lt;std::vector&lt;unsigned&gt;&gt; mat(rows, std::vector&lt;unsigned&gt;(cols, 0));\n\n // fill the matrix\n for(unsigned row = 0; row &lt; rows; ++row) {\n for(unsigned col = 0; col &lt; cols; ++col) {\n // use the distance_to function\n mat[row][col] = ref.distance_to(point_t(row, col));\n }\n }\n\n // print the result\n for(const auto&amp; row : mat) {\n for(auto col : row) std::cout &lt;&lt; col;\n std::cout &lt;&lt; '\\n';\n }\n }\n}\n</code></pre>\n\n<p>Input (with a 0-based reference point)</p>\n\n<pre><code>3 4 2 2\n</code></pre>\n\n<p>Output</p>\n\n<pre><code>4323\n3212\n2101\n\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-03T13:01:59.910", "Id": "470533", "Score": "0", "body": "Thanks a lot for the reply, I am currently learning from a course made by an ex-google intern and apart from iostream math.h fstream, no other library was presented yet and I'm already 70% done with the C++ course.. A lot of the syntax used I don't understand, is it OOP? Can you please tell me a good source to learn C++ from, it's really a shame that I don't understand your code and it's written very well, I wanna have a deep understanding of your solution." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-03T13:04:52.137", "Id": "470535", "Score": "0", "body": "I'm currently on a train without my computer, but I'll see what I can do Tonight or Tomorrow." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-03T13:08:58.653", "Id": "470540", "Score": "1", "body": "enjoy you trip, Ted!!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-03T22:57:54.787", "Id": "470588", "Score": "0", "body": "I am unexperienced at Code Review so I don't know if this is ok or not. My answer is way too long to be in a comment. Too long by over 1KiB as it happens. Can you split the question(s) up and post them as separate questions? Some should go on SO and questions like this one are perfect here on CR.\nQuestions about where to go for knowledge will be closed on SO, so books and hacking away is my answer to that." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-03T10:47:17.967", "Id": "239859", "ParentId": "239854", "Score": "4" } }, { "body": "<p>Declare for-loop-variables inside for instead of reusing them.</p>\n\n<p>So instead of:</p>\n\n<pre><code>int v[501][501], i, j, m, n, o, p;\ncin &gt;&gt; m &gt;&gt; n &gt;&gt; o &gt;&gt; p;\nfor (i = o; i &gt;= 1; i--)\n v[i][p] = o - i;\nfor(i = o;i &lt;= m; i++)\n v[i][p] = i - o;\nfor(i = 1; i &lt;= m; i++)\n for(j = 1; j &lt;= n; j++){\n</code></pre>\n\n<p>use (except you should also change types and rename variables as suggested by @Ted Lyngmo ).</p>\n\n<pre><code>int v[501][501], m, n, o, p;\ncin &gt;&gt; m &gt;&gt; n &gt;&gt; o &gt;&gt; p;\nfor (int i = o; i &gt;= 1; i--)\n v[i][p] = o - i;\nfor(int i = o;i &lt;= m; i++)\n v[i][p] = i - o;\nfor(int i = 1; i &lt;= m; i++)\n for(int j = 1; j &lt;= n; j++){\n</code></pre>\n\n<p>The reasons are:</p>\n\n<ul>\n<li>It's usual in C++</li>\n<li>Easier to find the declaration.</li>\n<li>No risk that the value is reused after the loop.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-03T13:07:27.323", "Id": "470538", "Score": "0", "body": "Hello Hans! Thanks for the reply, noted regarding the variable, very good observation, I used to have problems in the past when I implemented a good algorithm but I didn't pay attention and used a a preexisting value from a for loop. Ted pointed out very interesting things that it's the 1st time I ever hear of, which is a shame because we learn C++ in school for 4 years... they never showed us anything like this. I find C++ very hard, and I currently taking a course where I use just the information given by the course creator. Must of the syntax from Ted's code was not presented in the course" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-03T13:08:08.770", "Id": "470539", "Score": "0", "body": "it's a shame really, since I am almost finished with the c++ part of the course and soon I'll start OOP in Java." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-03T14:13:00.023", "Id": "470544", "Score": "0", "body": "I agree that it is a shame, and one possibility is that the C++ course is adapted from an old C-course with minimal changes (e.g., using the iostream-library)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-03T15:01:13.640", "Id": "470550", "Score": "0", "body": "how did you learn c++? are you an engineer currently working in C++?" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-03T11:32:24.147", "Id": "239861", "ParentId": "239854", "Score": "2" } } ]
{ "AcceptedAnswerId": "239859", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-03T09:27:16.407", "Id": "239854", "Score": "6", "Tags": [ "c++", "algorithm" ], "Title": "Create a matrix with all elements having the value of the shortest path to a given position" }
239854
<p>Good Morning</p> <p>This is a builder design pattern .. the builder problem is duplication so</p> <p>I want to know from an expert with explanation which is better on quality on this code:</p> <p>(1)</p> <pre><code>public class Animal { private String animalName; private int animalAge; public static class Builder { private Animal animal; public Builder() { animal = new Animal(); } public Builder getName(String animalName) { animal.animalName = animalName; return this; } public Builder getAge(int animalAge) { animal.animalAge = animalAge; return this; } public Animal build(){ animal.build(this); return animal; } } public Animal(){ } public void build(Builder builder) { this.animalName = builder.animal.animalName; this.animalAge = builder.animal.animalAge; } public String getAnimalName() { return animalName; } public int getAnimalAge() { return animalAge; } } </code></pre> <p>(2)</p> <pre><code>public class Animal { private String animalName; private int animalAge; public static class Builder{ private String animalName; private int animalAge; public Builder getName(String animalName){ this.animalName = animalName; return this; } public Builder getAge(int animalAge){ this.animalAge = animalAge; return this; } public Animal build(){ return new Animal(this); } } public Animal(Builder builder) { this.animalName = builder.animalName; this.animalAge = builder.animalAge; } public String getAnimalName() { return animalName; } public int getAnimalAge() { return animalAge; } } </code></pre> <p>in first model i pass animal object and create an instance and then the builder fill the data and build the animal again .</p> <p>in second model i duplicate all the animal instance variables</p> <p>which is true ? and which not broke builder rules ?</p>
[]
[ { "body": "<p>What I've seen the most when it comes to builder patterns is that the object (in your case <code>Animal</code>) will get constructed in the <code>build</code> method of the builder. It is preferred to create instances of objects with all the data that the object should have, eg not creating invalid states of an object. This prevents you from having illegal state in your program which might produce bugs. By constructing your <code>Animal</code> as soon as you create a builder instance you have to make your <code>Animal</code> mutable which is not always what you want. For example, in some cases a class might have only <code>final</code> fields which can only be assigned via constructor.</p>\n\n<p>In your case, constructing the <code>Animal</code> in the <code>build</code> method it would look something like this:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>public class Animal {\n\n private String animalName;\n private int animalAge;\n\n public static class AnimalBuilder {\n private String animalName;\n private int animalAge;\n\n public AnimalBuilder() {\n }\n\n public Builder withName(String animalName) {\n this.animalName = animalName;\n return this;\n }\n\n public Builder withAge(int animalAge) {\n this.animalAge = animalAge;\n return this;\n }\n\n public Animal build(){\n Animal animal = new Animal();\n animal.animalName = this.animalName;\n animal.animalAge = this.animalAge;\n return animal;\n }\n }\n\n public Animal(){ }\n\n public String getAnimalName() {\n return animalName;\n }\n\n public int getAnimalAge() {\n return animalAge;\n } \n}\n</code></pre>\n\n<p>You can then use it</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>Animal animal = new AnimalBuilder()\n .withName(\"Terry\")\n .withAge(5)\n .build();\n</code></pre>\n\n<p>You can also add a static method <code>builder()</code> to the <code>Animal</code> class which returns a new builder:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>public class Animal {\n ...\n\n public static AnimalBuilder builder() {\n return new AnimalBuilder();\n }\n}\n\nAnimal animal = Animal.builder()\n .withName(\"Terry\")\n .withAge(5)\n .build();\n</code></pre>\n\n<p>Does this mean a lot of duplication? Unfortunately, yes, builder patterns need a lot of duplicate code. You can also look at Lombok's Builder annotation which will generate all the builder boilerplate code for you. In that case it will just be</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>@Builder\npublic class Animal {\n\n private String animalName;\n private int animalAge;\n\n public Animal(){ }\n\n public String getAnimalName() {\n return animalName;\n }\n\n public int getAnimalAge() {\n return animalAge;\n } \n}\n<span class=\"math-container\">```</span>\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-03T09:50:17.890", "Id": "470515", "Score": "0", "body": "@pepjino \nthanks for your answer \nbut my question didn't answered yet .. \nwhy passing Animal object as instance on Builder class is wrong ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-03T10:01:37.857", "Id": "470516", "Score": "0", "body": "@AhmedMamdouh I've edited my post, does this help answering your question?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-03T10:07:49.447", "Id": "470520", "Score": "0", "body": "@pepjino Thank you very much for your interest and help\nbut i can't get it yet i'm sorry \nlook i found a post and he use the object instance .. is his answer wrong ? can you explain .. and i'm apologize for wasting your time :)) \n\nhttps://codereview.stackexchange.com/a/127509/221293 <<\n\ni mean in his case it's better to use object ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-03T10:45:35.717", "Id": "470522", "Score": "0", "body": "@AhmedMamdouh To be honest, that is the first time I've seen someone recommending create a builder like that. I prefer to create the object instance in the final step of the builder with the reasons I mentioned in my answer. It might be possible that both methods are used in different applications and that it will be a matter of personal preference. I'm afraid I cannot give a more clear answer, perhaps someone else will be better suited to give an answer regarding this matter." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-03T09:45:02.163", "Id": "239856", "ParentId": "239855", "Score": "2" } }, { "body": "<p>From @pepijno 's answer:</p>\n\n<blockquote>\n <p>What I've seen the most when it comes to builder patterns is that the object (in your case Animal) will get constructed in the build method of the builder. It is preferred to create instances of objects with all the data that the object should have, eg not creating invalid states of an object.</p>\n</blockquote>\n\n<p>That is true. However his following code contradicts this.</p>\n\n<pre><code>public Animal(){ }\n\n public String getAnimalName() {\n return animalName;\n }\n\n public int getAnimalAge() {\n return animalAge;\n } \n</code></pre>\n\n<p>So now I am free to create animal of age 0 and empty name? I know OP's code did not check for this. But if there were any checks like that (and they probably should), you are now free to create Animal with invalid state.</p>\n\n<p>The way you should interpret the above quote is like this:</p>\n\n<pre><code>public class Animal\n{\n private String animalName;\n private int animalAge;\n\n public Animal(String name, int age){ \n if (name.length() == 0) {\n throw new Exception('Name cannot be empty');\n }\n if (age &lt; 0) {\n throw new Exception('Age cannot be negative');\n }\n animalName = name;\n animalAge = age;\n }\n\n public String getAnimalName() {\n return animalName;\n }\n\n public int getAnimalAge() {\n return animalAge;\n } \n}\n\nclass AnimalBuilder\n{\n private String animalName;\n private int animalAge;\n\n public AnimalBuilder(){}\n\n public AnimalBuilder setAnimalName(String name) {\n animalName = name;\n return this;\n }\n\n public AnimalBuilder setAnimalAge(int age) {\n animalAge = age;\n return this;\n } \n\n public Animal build() {\n return new Animal(animalName, animalAge);\n }\n}\n</code></pre>\n\n<p>Now, notice a few things.</p>\n\n<p>AnimalBuilder is now ouside Animal class. This removes the circular dependency of the two classes. Builder knows the target Animal class, but the Animal is unaware of its building steps. At the same time, the Animal can be constructed without a builder and it cannot end up in an invalid state. This also explains why passing the builder to the animal constructor is bad, it would again introduce the circular coupling of the two classes (and also reminds service locator anti pattern). Same reason why in pepijno's answer, putting builder() method on the Animal class, is bad.</p>\n\n<p>There might be more specific exceptions to use, but I don't know Java.</p>\n\n<p>Also builder's methods should really be called <code>set*</code>, not <code>get*</code>, nor <code>with*</code> (as in pepijno's answer). The \"withers\" are usualy implemented in an immutable way:</p>\n\n<pre><code>class MyClass\n{\n private String myName;\n private String other;\n\n public MyClass(String name, String x) {myName = name; other = x;}\n\n public MyClass withName(String name)\n {\n return new MyClass(name, other);\n }\n}\n</code></pre>\n\n<p>As for the approach i noticed in comments\n<a href=\"https://codereview.stackexchange.com/a/127509/221293\">https://codereview.stackexchange.com/a/127509/221293</a></p>\n\n<p>Yes this is possible, but an interface should be created with only the getters and implemented by the Animal class to prevent consumers of constructed Animals from modifying it.</p>\n\n<pre><code>interface IAnimal\n{\n public String getAnimalName();\n public int getAnimalAge();\n}\n\npublic class Animal : IAnimal\n{\n private String animalName;\n private int animalAge;\n\n public Animal(String name, int age){ \n setAnimaName(name);\n setAnimalAge(age);\n }\n\n public String getAnimalName() {\n return animalName;\n }\n\n public void setAnimalName(String name) {\n if (name.length() == 0) {\n throw new Exception('Name cannot be empty');\n }\n animaName = name;\n }\n\n public int getAnimalAge() {\n return animalAge;\n } \n\n public void setAnimalAge(int age) {\n if (age &lt; 0) {\n throw new Exception('Age cannot be negative');\n }\n animalAge = age;\n }\n}\n</code></pre>\n\n<p>And the builder should be declared to return that interface and not the class.</p>\n\n<pre><code>class AnimalBuilder\n{\n ...\n public IAnimal build() {...}\n ...\n}\n</code></pre>\n\n<p>But the Animal class should remain only constructible into a valid state, but the builder requires it to have default constructor (which restricts the usage to objects with default constructors, ie. where empty name is allowed).</p>\n\n<p>And setting any property of the class after construction, must not corrupt the object. This to prevent bugs if someone decides to create the Animal directly, not using a builder, thus knowing its setters.</p>\n\n<p>And this is why the approach from the mentioned SO post has restricted usage. It is also half the way between circular coupling and decoupling the two. Because although the Animal still does not know AnimalBuilder, it provides setters in expectation of existance of a builder that could use those setters (or it expects consumer to modify it, but that would be a completly different scenario than in your (OP) question).</p>\n\n<p>It is also unsuitable when there are validations that depend on multiple properties (ie. if name is dog, his age not only must be non-negative, it cannot be more then 20 - ignore the nonsense of the example :D), because setting the two separately with distinct setters may lead to different behaviour depending on the order in which the setters are called.</p>\n\n<p>The approach I proposed (high) above is generic and always applicable. The amount of repeating is about the same, IMO.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-03T12:31:25.300", "Id": "239868", "ParentId": "239855", "Score": "2" } } ]
{ "AcceptedAnswerId": "239868", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-03T09:29:00.727", "Id": "239855", "Score": "4", "Tags": [ "java", "comparative-review" ], "Title": "Builder design pattern pass object" }
239855
<p>I have created a flocking simulation based on Craig Reynolds Boids. Could you give me some feedback on my code? I am a newbie and would really appreciate some criticism. </p> <p>Files:</p> <ul> <li><p>Boid - this is the representation of a bird like object.</p></li> <li><p>Flock - this controls and manages the flock of boids.</p></li> </ul> <p>Flock.h:</p> <pre><code>#include "Boid.h" #include &lt;vector&gt; #include &lt;random&gt; #include &lt;chrono&gt; #ifndef FLOCK_H #define FLOCK_H class Flock { private: std::vector&lt;Boid&gt; m_boidStorage; sf::RenderWindow* m_winPtr = nullptr; sf::Texture* m_t; std::uniform_real_distribution&lt;float&gt; m_uniform; int m_seed; std::mt19937 m_randomEngine; std::normal_distribution&lt;float&gt; m_gaussian; float maxForce; float maxVelocity; float minimumSeperation; void Alignment(float multiplier); void Cohesion(float multiplier); void Seperation(float multiplier); void Move(); void MassCalculate(); float AbsBoidDistance(const Boid&amp; boid1, const Boid&amp; boid2); sf::Vector2f VecBoidDistance(const Boid&amp; boid1, const Boid&amp; boid2); float VectorMagnitude(const sf::Vector2f&amp; vec); void LimitMagnitude(sf::Vector2f&amp; vec, const float&amp; magnitude); void SetMagnitude(sf::Vector2f&amp; vec, const float&amp; magnitude); bool CompareMemLocs(const Boid&amp; boid1, const Boid&amp; boid2); void Borders(Boid&amp; boid); public: enum FORCECONSTANTS { KA = 0, KC, KS }; float kA; float kS; float kC; Flock(sf::RenderWindow* winPtr); void Display(); void Update(); void ChangeConstants(FORCECONSTANTS x, bool direction); void AddBoid(bool external); }; #endif </code></pre> <p>Flock.cpp: Originally, I had calculated the Cohesion, Seperation and Alignment Forces by individual functions, however merging the algorithms together in to a single function, called <code>void Flock::MassCalculate()</code> has allowed me to increase performance by reducing the number of checks.</p> <pre><code>#include "Flock.h" #include "Constants.h" #include &lt;iostream&gt; Flock::Flock(sf::RenderWindow* winPtr) :m_winPtr(winPtr) { minimumSeperation = 40; maxForce = 0.01; maxVelocity = 0.75; kA = 1.4; kC = 1.5; kS = 1.7; m_seed = std::chrono::steady_clock::now().time_since_epoch().count(); m_randomEngine.seed(m_seed); std::normal_distribution&lt;float&gt; igaussian(WIDTH / 2, 0.2); std::uniform_real_distribution&lt;float&gt; uniformDist(-1, 1); m_uniform = uniformDist; m_gaussian = igaussian; for (int i = 0; i &lt; TOTAL_BOIDS; i++) { AddBoid(false); } } void Flock::AddBoid(bool external) { if (external) { Boid b1{ sf::Vector2f{float(WIDTH / 2),float(HEIGHT / 2)}, sf::Vector2f{0,0} }; m_boidStorage.push_back(b1); maxVelocity += 0.05; } else { Boid b2(sf::Vector2f{ m_gaussian(m_randomEngine), m_gaussian(m_randomEngine) }, sf::Vector2f{ float(m_uniform(m_randomEngine)), float(m_uniform(m_randomEngine)) }); m_boidStorage.push_back(b2); } } sf::Vector2f Flock::VecBoidDistance(const Boid&amp; boid1, const Boid&amp; boid2) { sf::Vector2f b1 = boid1.boid.getPosition(); sf::Vector2f b2 = boid2.boid.getPosition(); return b2 - b1; } float Flock::AbsBoidDistance(const Boid&amp; boid1, const Boid&amp; boid2) { sf::Vector2f b1 = boid1.boid.getPosition(); sf::Vector2f b2 = boid2.boid.getPosition(); return sqrt(pow((b2.x - b1.x), 2) + pow((b2.y - b1.y), 2)); } float Flock::VectorMagnitude(const sf::Vector2f&amp; vec) { return sqrt(pow(vec.x, 2) + pow(vec.y, 2)); } void Flock::SetMagnitude(sf::Vector2f&amp; vec, const float&amp; newmagnitude) { float currentMag = VectorMagnitude(vec); vec /= currentMag; vec *= newmagnitude; } void Flock::LimitMagnitude(sf::Vector2f&amp; vec,const float&amp; limit) { float magnitude = VectorMagnitude(vec); if (magnitude &gt; limit) { SetMagnitude(vec, limit); } } bool Flock::CompareMemLocs(const Boid&amp; boid1, const Boid&amp; boid2) { return &amp;boid1 != &amp;boid2; } void Flock::Borders(Boid&amp; boid) { if (boid.boid.getPosition().x &lt; -boid.m_radius) { boid.boid.setPosition(sf::Vector2f{ WIDTH + boid.m_radius, boid.boid.getPosition().y }); } if (boid.boid.getPosition().x &gt; WIDTH + boid.m_radius) { boid.boid.setPosition(sf::Vector2f{ 0 - boid.m_radius, boid.boid.getPosition().y }); } if (boid.boid.getPosition().y &lt; -boid.m_radius) { boid.boid.setPosition(sf::Vector2f{ boid.boid.getPosition().x, HEIGHT + boid.m_radius }); } if (boid.boid.getPosition().y &gt; HEIGHT + boid.m_radius) { boid.boid.setPosition(sf::Vector2f{ boid.boid.getPosition().x, 0 - boid.m_radius }); } } void Flock::Display() { Boid B(sf::Vector2f{ WIDTH / 2,HEIGHT / 2 }, sf::Vector2f{ 0,0 }); m_winPtr-&gt;clear(); for (const Boid&amp; boid : m_boidStorage) { m_winPtr-&gt;draw(boid.boid); } m_winPtr-&gt;display(); } void Flock::Move() { for (Boid&amp; boid : m_boidStorage) { boid.Move(); Borders(boid); } } void Flock::Update() { MassCalculate(); Move(); Display(); } void Flock::MassCalculate() { float alignmentperceptionradius = 50; float cohesionperceptionradius = 50; float seperationperceptionradius = 50; for (Boid&amp; thisBoid : m_boidStorage) { unsigned int alignmentCount = 0; unsigned int cohesionCount = 0; unsigned int seperationCount = 0; sf::Vector2f AlignmentForce = {}; sf::Vector2f CohesionForce = {}; sf::Vector2f SeperationForce = {}; sf::Vector2f Distance = {}; for (const Boid&amp; otherBoid : m_boidStorage) { float d = AbsBoidDistance(thisBoid, otherBoid); if (CompareMemLocs(thisBoid, otherBoid) &amp;&amp; d &lt; alignmentperceptionradius) { AlignmentForce += otherBoid.m_Velocity; alignmentCount++; } if (CompareMemLocs(thisBoid, otherBoid) &amp;&amp; d &lt; cohesionperceptionradius) { CohesionForce += otherBoid.boid.getPosition(); cohesionCount++; } if (CompareMemLocs(thisBoid, otherBoid) &amp;&amp; d &lt; seperationperceptionradius) { Distance = thisBoid.boid.getPosition() - otherBoid.boid.getPosition(); Distance /= (d*d); SeperationForce += Distance; seperationCount++; } } if (alignmentCount &gt; 0) { AlignmentForce /= float(alignmentCount); SetMagnitude(AlignmentForce, maxVelocity); AlignmentForce = AlignmentForce - thisBoid.m_Velocity; LimitMagnitude(AlignmentForce, maxForce); } if (cohesionCount &gt; 0) { CohesionForce /= float(cohesionCount); CohesionForce = CohesionForce - thisBoid.boid.getPosition(); SetMagnitude(CohesionForce, maxVelocity); CohesionForce = CohesionForce - thisBoid.m_Velocity; LimitMagnitude(CohesionForce, maxForce); } if (seperationCount &gt; 0) { SeperationForce /= float(seperationCount); SetMagnitude(SeperationForce, maxVelocity); SeperationForce = SeperationForce - thisBoid.m_Velocity; LimitMagnitude(SeperationForce, maxForce); } AlignmentForce *= kA; thisBoid.AddForce(AlignmentForce); CohesionForce *= kC; thisBoid.AddForce(CohesionForce); SeperationForce *= kS; thisBoid.AddForce(SeperationForce); } } void Flock::ChangeConstants(FORCECONSTANTS x, bool direction) { if (x == FORCECONSTANTS::KA) { (direction) ? kA += 0.1 : kA -= 0.1; std::cout &lt;&lt; "kA: " &lt;&lt; kA &lt;&lt; std::endl; } if (x == FORCECONSTANTS::KC) { (direction) ? kC += 0.1 : kC -= 0.1; std::cout &lt;&lt; "kC: " &lt;&lt; kC &lt;&lt; std::endl; } if (x == FORCECONSTANTS::KS) { (direction) ? kS += 0.1 : kS -= 0.1; std::cout &lt;&lt; "kS: " &lt;&lt; kS &lt;&lt; std::endl; } } </code></pre> <p>Boid.h</p> <pre><code>#include &lt;SFML/Graphics.hpp&gt; #ifndef BOID_H #define BOID_H struct Boid { sf::CircleShape boid; float m_radius; sf::Vector2f m_Velocity; sf::Vector2f m_Force; Boid(const sf::Vector2f&amp; init_Pos, const sf::Vector2f init_Vel); void AddForce(const sf::Vector2f&amp; force); void Move(); }; #endif // ! BOID_H </code></pre> <p>Boid.cpp:</p> <pre><code>#include "Boid.h" Boid::Boid(const sf::Vector2f&amp; init_pos, const sf::Vector2f init_vel) :m_Velocity(init_vel) { m_radius = 5; boid.setPosition(init_pos); boid.setFillColor(sf::Color::White); boid.setOutlineThickness(0); boid.setOutlineColor(sf::Color::White); boid.setPointCount(50); boid.setRadius(m_radius); boid.setOrigin(m_radius, m_radius); } void Boid::AddForce(const sf::Vector2f&amp; force) { m_Force += force; m_Velocity += force; } void Boid::Move() { boid.move(m_Velocity); } </code></pre> <p>Main.cpp:</p> <pre><code>#include "Flock.h" #include &lt;string&gt; #include "Constants.h" #include &lt;iostream&gt; #include &lt;iomanip&gt; int main() { std::string myTitle = "Boids"; sf::RenderWindow myWindow(sf::VideoMode(WIDTH, HEIGHT), myTitle, sf::Style::Default); Flock f(&amp;myWindow); while (myWindow.isOpen()) { sf::Event evnt; while (myWindow.pollEvent(evnt)) { switch (evnt.type) { case sf::Event::EventType::Closed: { myWindow.close(); } case sf::Event::EventType::KeyPressed: { if (sf::Keyboard::isKeyPressed(sf::Keyboard::Key::Space)) { f.AddBoid(true); } if (sf::Keyboard::isKeyPressed(sf::Keyboard::Key::Num1)) { f.ChangeConstants(f.KA, true); } if (sf::Keyboard::isKeyPressed(sf::Keyboard::Key::Num2)) { f.ChangeConstants(f.KA, false); } if (sf::Keyboard::isKeyPressed(sf::Keyboard::Key::Num3)) { f.ChangeConstants(f.KC, true); } if (sf::Keyboard::isKeyPressed(sf::Keyboard::Key::Num4)) { f.ChangeConstants(f.KC, false); } if (sf::Keyboard::isKeyPressed(sf::Keyboard::Key::Num5)) { f.ChangeConstants(f.KS, true); } if (sf::Keyboard::isKeyPressed(sf::Keyboard::Key::Num6)) { f.ChangeConstants(f.KS, false); } } } } f.Update(); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-03T12:03:36.117", "Id": "470526", "Score": "1", "body": "Hi, in the future please make sure that your title is a description of the purpose of your code, as I edited for you. Can you also indicate in your question: does your code work (a screenshot may be helpful for graphics)? A description of Craig Reynolds Boids may help reviewers understand the mechanism of your code as well." } ]
[ { "body": "<p>In all, this is a nice, solid effort, especially for a self-avowed \"newbie.\" Keep up the good work! With that, here are some things that may help you improve your program.</p>\n\n<h2>Use SFML more fully</h2>\n\n<p>I would suggest that it would be a good idea to have the <code>Flock</code> class derive from both the <code>sf::Transformable</code> and <code>sf::Drawable</code> classes. Your <code>Flock::Display()</code> would then become an implementation of <code>Flock::draw</code>. See the <a href=\"https://www.sfml-dev.org/tutorials/2.5/graphics-vertex-array.php#creating-an-sfml-like-entity\" rel=\"nofollow noreferrer\">SFML tutorial on creating entities</a> for more details.</p>\n\n<h2>Think carefully about inheiritance</h2>\n\n<p>The <code>Boid</code> class is currently this:</p>\n\n<pre><code>struct Boid\n{\n sf::CircleShape boid;\n float m_radius;\n\nsf::Vector2f m_Velocity;\nsf::Vector2f m_Force;\nBoid(const sf::Vector2f&amp; init_Pos, const sf::Vector2f init_Vel);\nvoid AddForce(const sf::Vector2f&amp; force);\nvoid Move();\n};\n</code></pre>\n\n<p>I would make several changes to this:</p>\n\n<pre><code>struct Boid : public sf::CircleShape\n{\n float m_radius = 2;\n sf::Vector2f m_Velocity;\n sf::Vector2f m_Force;\n Boid(const sf::Vector2f&amp; init_Pos, const sf::Vector2f init_Vel);\n void AddForce(const sf::Vector2f&amp; force);\n};\n</code></pre>\n\n<p>I've changed the <code>Boid</code> to inherit from <code>sf::CircleShape</code> which cleans things up. For example, lines like these:</p>\n\n<pre><code>sf::Vector2f b1 = boid1.boid.getPosition();\nsf::Vector2f b2 = boid2.boid.getPosition();\n</code></pre>\n\n<p>are now a bit simpler with this:</p>\n\n<pre><code>sf::Vector2f b1 = boid1.getPosition();\nsf::Vector2f b2 = boid2.getPosition();\n</code></pre>\n\n<p>I also moved the default value for <code>m_radius</code> into the declaration rather than the constructor. Finally, I removed the <code>Move</code> function entirely, since we can now use <code>sf::CircleShape::move</code> directly:</p>\n\n<pre><code>void Flock::Move()\n{\n for (Boid&amp; boid : m_boidStorage)\n {\n boid.move(boid.m_Velocity);\n Borders(boid);\n }\n}\n</code></pre>\n\n<p>However, see the next suggestion.</p>\n\n<h2>Think carefully about class responsibilities</h2>\n\n<p>It seems to me that <code>Borders</code> should be a function of <code>Boid</code> rather than of <code>Flock</code>. Just pass in <code>width</code> and <code>height</code> and I think you'll find it a much nicer looking piece of code. Also, <code>Borders</code> is a noun rather than a verb which makes it a somewhat misleading name for a function. I'd call it <code>Wrap</code> instead. Similarly, the only uses of <code>m_randomEngine</code>, <code>m_uniform</code>, <code>m_gaussian</code> are within <code>AddBoid</code> which strongly suggests to me that they would be better as static members of <code>Boid</code> and used for a default constructor of <code>Boid</code>.</p>\n\n<h2>Put default values in the class definition</h2>\n\n<p>Rather than assigning values in the constructor, such as for <code>kA</code>, <code>kB</code>, etc. it's better to put those into the class definition. If you do that and provide a default <code>Boid</code> constructor as mentioned above, your <code>Flock</code> constructor could look like this:</p>\n\n<pre><code>Flock::Flock(sf::RenderWindow* winPtr) :\n m_boidStorage(TOTAL_BOIDS),\n m_winPtr(winPtr)\n{\n}\n</code></pre>\n\n<p>This also simplifies <code>AddBoid</code> by removing the need for a passed parameter.</p>\n\n<h2>Use <code>emplace_back</code> instead of <code>push_back</code> where appropriate</h2>\n\n<p>We don't really need to separately construct a <code>Boid</code> and push it onto the <code>std::vector</code>. Instead, we can do both in a single step:</p>\n\n<pre><code>void Flock::AddBoid()\n{\n static const sf::Vector2f middle{ WIDTH / 2.0, HEIGHT / 2.0 };\n static const sf::Vector2f zero{ 0, 0 };\n m_boidStorage.emplace_back(middle, zero);\n maxVelocity += 0.05;\n}\n</code></pre>\n\n<p>This assumes that the previous suggestion is also used.</p>\n\n<h2>Watch out for missing <code>break</code>s</h2>\n\n<p>A common error in C++ is to forget to put a <code>break;</code> at the bottom of each <code>case</code> to prevent it from falling through. There is such a missing <code>break;</code> in <code>Main.cpp</code>.</p>\n\n<h2>Use <code>const</code> where appropriate</h2>\n\n<p>Helper functions such as <code>VectorMagnitude</code> don't modify the underlying <code>Flock</code> object and so should be <code>const</code>. However, in this case, see the next suggestion instead.</p>\n\n<h2>Omit helper functions from the interface</h2>\n\n<p>There's no need to use <code>VectorMagnitude</code> outside of the <code>Flock</code> implementation code, so I'd recommend that it (and the similar functions) be non-class member <code>static</code> functions instead.</p>\n\n<h2>Eliminate unused functions</h2>\n\n<p>The <code>VecBoidDistance</code> is never used and can be eliminated.</p>\n\n<h2>Consider refactoring using objects</h2>\n\n<p>The <code>MassCalculate</code> function has a lot of nearly duplicate code. I would be inclined to refactor that into three <code>Influence</code> objects with <code>Influence</code> being a pure virtual base class that would do all of the common stuff and two virual functions <code>updateForce</code> and <code>applyForce</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-04T13:17:54.307", "Id": "470608", "Score": "0", "body": "I really appreciate the feedback. I will implement these right away! Edward, I am in desperate need of a mentor since none of my friends know how to code. Would you be so kind so as to help me improve my code in the future? I would really, really appreciate it. I understand if you do not want to do this however." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-04T13:22:09.400", "Id": "470609", "Score": "0", "body": "That's what we're here for. You might also participate in [the 2nd monitor](https://chat.stackexchange.com/rooms/8595/the-2nd-monitor) if you have questions." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-04T13:43:45.897", "Id": "470611", "Score": "0", "body": "Edward in your point \"Omit helper functions from the interface\", where would you put these functions instead? In main.cpp, or a separate header called \"helper.h\"/ any other spot?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-04T13:58:10.123", "Id": "470613", "Score": "0", "body": "Leave them exactly where they are and make them `static`. You don't need a header file for those." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-03T21:34:52.680", "Id": "239893", "ParentId": "239860", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-03T11:05:39.397", "Id": "239860", "Score": "3", "Tags": [ "c++", "simulation", "sfml" ], "Title": "C++/SFML Boid/Flocking Simulation" }
239860
<p>I'm following a tutorial into pygame. I realized the example code was written for the sake of being easy to understand. I wondered if I could 'improve' the code, with a focus on keeping the exact same functionality. I tried, but I'm not really sure if this is an improvement. </p> <p>This is the original code from the instructions:</p> <pre><code>import pygame, sys from pygame.locals import * pygame.init() FPS = 30 # frames per second setting fpsClock = pygame.time.Clock() # set up the window DISPLAYSURF = pygame.display.set_mode((400, 300), 0, 32) pygame.display.set_caption('Animation') WHITE = (255, 255, 255) catImg = pygame.image.load('cat.png') # hosted at https://inventwithpython.com/cat.png catx = 10 caty = 10 direction = 'right' while True: # the main game loop DISPLAYSURF.fill(WHITE) if direction == 'right': catx += 5 if catx == 280: direction = 'down' elif direction == 'down': caty += 5 if caty == 220: direction = 'left' elif direction == 'left': catx -= 5 if catx == 10: direction = 'up' elif direction == 'up': caty -= 5 if caty == 10: direction = 'right' DISPLAYSURF.blit(catImg, (catx, caty)) for event in pygame.event.get(): if event.type == QUIT: pygame.quit() sys.exit() pygame.display.update() fpsClock.tick(FPS) </code></pre> <p>This is my 'improved' code. Two questions. In general, how can my version be improved and why is that improvement better then my code? And, how could the original be improved? </p> <pre><code>import pygame, sys from pygame.locals import * pygame.init() FPS = 30 fps_clock = pygame.time.Clock() window_size = (400,300) DISPLAYSURF = pygame.display.set_mode(window_size,0,32) pygame.display.set_caption("Animation test!") WHITE = (255,255,255) cat = pygame.image.load('assests/cat.png') # hosted at https://inventwithpython.com/cat.png direction = 'right' x_,y_ = 10,10 def listenToQuit(): for event in pygame.event.get(): if event.type == QUIT: pygame.quit() sys.exit() def detectCollision(cat,x,y,window_size): return cat.get_size()[0] + x &gt;= window_size[0] or \ cat.get_size()[1] + y &gt;= window_size[1] or \ x &lt;= 0 or y &lt;= 0 def getDirection(direction): directions = ['right','down','left','up'] idx = directions.index(direction) idx = 0 if idx + 1 == len(directions) else idx + 1 return directions[idx] def getMovement(x,y,direction): if direction == 'right': return x+5,y elif direction == 'down': return x , y+5 elif direction == 'left': return x - 5 , y elif direction == 'up': return x , y - 5 i = 0 while 1: DISPLAYSURF.fill(WHITE) x,y = getMovement(x_,y_,direction) while detectCollision(cat,x,y,window_size): # if there would be a collision, change direction direction = getDirection(direction) x,y = getMovement(x_,y_,direction) # re-calculate movement, now avoiding collision x_,y_ = x,y DISPLAYSURF.blit(cat,(x,y)) listenToQuit() pygame.display.update() fps_clock.tick(FPS) </code></pre> <p>I specifically chose not to make the animated object a class. I will try to do so as my next exercise towards myself.</p>
[]
[ { "body": "<p>Yours is definitely an improvement, but there is still room for more improvement:</p>\n\n<h2>PEP8</h2>\n\n<p>The official Python style guide will tell you:</p>\n\n<ul>\n<li>two newlines between every function (i.e. before <code>detectCollision</code>, etc.)</li>\n<li>function and variable names in snake_case, i.e. <code>detect_collision</code></li>\n<li>avoid line continuation: this</li>\n</ul>\n\n<pre><code> return cat.get_size()[0] + x &gt;= window_size[0] or \\\n cat.get_size()[1] + y &gt;= window_size[1] or \\\n x &lt;= 0 or y &lt;= 0\n</code></pre>\n\n<p>should become</p>\n\n<pre><code>return (\n cat.get_size()[0] + x &gt;= window_size[0]\n or cat.get_size()[1] + y &gt;= window_size[1]\n or x &lt;= 0 \n or y &lt;= 0\n)\n</code></pre>\n\n<ul>\n<li>spaces after the commas in <code>['right','down','left','up']</code></li>\n<li>remove the spaces before the commas here:</li>\n</ul>\n\n<pre><code> return x , y+5\n elif direction == 'left':\n return x - 5 , y\n elif direction == 'up':\n return x , y - 5\n</code></pre>\n\n<h2>Main function</h2>\n\n<p>Move everything starting with <code>i = 0</code> into a <code>main</code> function that is called with a name guard:</p>\n\n<pre><code>if __name__ == '__main__':\n main()\n</code></pre>\n\n<h2>Constant arrangement</h2>\n\n<p>There's a big crazy mix of constants and variables in global scope. I consider these constants that should be grouped together:</p>\n\n<pre><code>FPS = 30 # frames per second setting\nWINDOW_SIZE = (400,300)\nWHITE = (255, 255, 255)\n</code></pre>\n\n<p>Nothing else in that region should be in global scope.</p>\n\n<h2>Enums</h2>\n\n<p>Represent <code>direction</code> as an <code>enum.Enum</code> with four entries, rather than a stringly-typed variable.</p>\n\n<h2>Hard exit</h2>\n\n<p>Don't <code>exit</code> from <code>listen_to_quit</code> - just break out of the loop.</p>\n\n<p>Better yet - rearrange your code so that you don't need a forever loop:</p>\n\n<pre><code>while not should_quit():\n pygame.display.update()\n fps_clock.tick(FPS)\n\n DISPLAYSURF.fill(WHITE)\n\n x,y = getMovement(x_,y_,direction)\n while detectCollision(cat,x,y,window_size): # if there would be a collision, change direction \n direction = getDirection(direction)\n x,y = getMovement(x_,y_,direction) # re-calculate movement, now avoiding collision\n\n x_,y_ = x,y\n\n DISPLAYSURF.blit(cat,(x,y))\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-06T01:28:45.190", "Id": "240016", "ParentId": "239862", "Score": "2" } } ]
{ "AcceptedAnswerId": "240016", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-03T11:51:22.313", "Id": "239862", "Score": "3", "Tags": [ "python", "comparative-review", "pygame" ], "Title": "A simple animation in pygame" }
239862
<p>To begin, I have an XML file at /Users/gaze/lab/lab/gpib_lib/out.xml that contains lines like...</p> <pre><code>&lt;MemberCall method_name="setFastCoupleMode" callee_name="GPIB_7280" fname="/Users/gaze/lab/lab/gpib_lib/../apps/capbridge/capbridge.C" lineno="394" colno="9" /&gt; &lt;MemberCall method_name="setInputLineFilter" callee_name="GPIB_7280" fname="/Users/gaze/lab/lab/gpib_lib/../apps/capbridge/capbridge.C" lineno="395" colno="9" /&gt; &lt;MemberCall method_name="setFrequency" callee_name="capacitanceBridge" fname="/Users/gaze/lab/lab/gpib_lib/../apps/capbridge/capbridge.C" lineno="526" colno="5" /&gt; &lt;MemberCall method_name="getFrequency" callee_name="capacitanceBridge" fname="/Users/gaze/lab/lab/gpib_lib/../apps/capbridge/capbridge.C" lineno="528" colno="10" /&gt; &lt;MemberCall method_name="setupBandpass" callee_name="Stream_SR560" fname="/Users/gaze/lab/lab/gpib_lib/../apps/capbridge/capbridge.C" lineno="531" colno="9" /&gt; &lt;MemberCall method_name="thr" callee_name="listOutputFilter" fname="/Users/gaze/lab/lab/gpib_lib/../apps/capbridge/capbridge.C" lineno="540" colno="5" /&gt; &lt;MemberCall method_name="setBias" callee_name="capacitanceBridge" fname="/Users/gaze/lab/lab/gpib_lib/../apps/capbridge/capbridge.C" lineno="546" colno="5" /&gt; </code></pre> <p>To process it into a list of unique class.method() invocations I use the following code. I filter out all calls that occur outside my codebase, which is located at fpath.</p> <pre><code>filename←'/Users/gaze/lab/lab/gpib_lib/out.xml' fpath←'/Users/gaze/lab/lab' getxml←{⎕XML ⊃⎕NGET ⍵} doc←getxml filename attrib←↑doc[;4] colnames ← attrib[1;;1] col ← {attrib[;(attrib[1;;1]⍳⊂⍵);2]} oot ← ((⍴fpath)↑¨col'fname')∊⊂fpath fn ← (1+⍴fpath)↓¨oot/(col'fname') cn ← oot/(col'callee_name') mn ← oot/(col'method_name') allUsed ← ∪(⍉↑(cn mn))[⍋cn;] </code></pre> <p>OOT denotes "out of tree." I'm curious if you might have suggestions about how to structure this in a larger application. I'm mostly curious how one should set fpath, should it change from invocation to invocation of allUsed, if this code is factored such that you can change filename. I don't exactly want to make allUsed a dyad s.t. fpath is on the right and filename is on the left, since that seems a bit wrong, should there be a more general allUsed that should indeed be a dyad. Should fpath be a global variable which is changed throughout the execution of a larger program? What's the right structure here? If you have any little details you'd improve upon here, I'd love to know as well.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-03T14:33:26.337", "Id": "470547", "Score": "0", "body": "Oh, sorry I misread it as api." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-03T15:26:45.200", "Id": "470556", "Score": "0", "body": "The current question title, which states your concerns about the code, is too general to be useful here. Please [edit] to the site standard, which is for the title to simply state the task accomplished by the code. Please see [How to get the best value out of Code Review: Asking Questions](https://codereview.meta.stackexchange.com/q/2436) for guidance on writing good question titles." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-05T06:09:08.923", "Id": "470671", "Score": "0", "body": "@SᴀᴍOnᴇᴌᴀ I've taken a stab at the title (and added tag). Better?" } ]
[ { "body": "<p>Regarding the primary question, your code is very close to being a well-defined function. Simply wrap the entire code in a function, making <code>filename</code> the right argument, <code>fpath</code> the left argument, and <code>allUsed</code> the result like so (with a couple of unreference lines omitted): </p>\n\n<pre><code> GetAllUsed←{\n filename←⍵\n fpath←⍺\n getxml←{⎕XML⊃⎕NGET ⍵}\n doc←getxml filename\n attrib←↑doc[;4]\n col←{attrib[;(attrib[1;;1]⍳⊂⍵);2]}\n oot←((⍴fpath)↑¨col'fname')∊⊂fpath\n cn←oot/(col'callee_name')\n mn←oot/(col'method_name')\n ∪(⍉↑(cn mn))[⍋cn;]\n }\n</code></pre>\n\n<p>I cannot envision a scenario where one might not want it as a dyadic function, or where one would want to introduce a global variable of any sort. I prefer the file name as the right argument, leaving the opportunity to make the left argument optional (possibly having it default to the first few path segments of the right arg?)</p>\n\n<p>Regarding the actual code, the biggest issue is that it relies on the set of attributes for each MemberCall element being exactly the same. An additional or missing attribute will cause the code to fail, with an index error most likely, or produce a bad result. </p>\n\n<p>If it is indeed the case that the attribute sets are identical, then a much simpler approach can be taken by restructuring the attributes for all elements into a single matrix of name/value pairs. There is no need to construct a rank-3 array as is done currently.</p>\n\n<p>If this is not the case, then one approach is to define a little getter function that picks out a given attribute for each element. This function can handle the issue of missing or extra attributes, attributes in any order, etc. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-04T11:57:19.573", "Id": "239918", "ParentId": "239869", "Score": "5" } } ]
{ "AcceptedAnswerId": "239918", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-03T14:21:44.387", "Id": "239869", "Score": "3", "Tags": [ "xml", "apl" ], "Title": "XML attribute analysis" }
239869
<p>I wrote an algorithm that returns all k-sized <a href="https://en.wikipedia.org/wiki/Induced_subgraph" rel="nofollow noreferrer">subgraphs</a> of another given graph. Because I don't want to make the runtime of the next() call of the iterator depended on k, I don't want to return a new object every time. Instead I have one fixed instance-variable <em>subG</em> in the iterator that is changed between the calls und always represents the current subgraph that was calculated. It acts as a view that can be copied if needed if you want to use it further.<br> This method works fine and this is not my problem.</p> <p>If I want to use <em>hasNext()</em>, I'd need to calculate the next subgraph, which would change the view <em>subG</em> as a side-effect. This is not wanted. Currently I'm using my own interface for this iterator:</p> <pre><code>/** * Interface for all iterators that always return the same object, but change it in order to return the next value. * Therefore, the object should not be changed unintentionally, because that would result in unwanted side-effects. * This prevents the use of "hasNext()" as this would have to calculate the next value for the object, but this method * is not expected to have side-effects. The only method that changes the object is generateNext(), which also is * its only purpose. * * The standard pattern for using this interface would be: * while (iter.hasCurrent()) { * doSomethingWith(iter.getCurrent()); * iter.generateNext(); * } */ public interface BlindIterator&lt;T&gt; { /** * @return True iff the current element is a valid return. */ boolean hasCurrent(); /** * @return Returns the current element, but does NOT generate the next element. This method can be called * as often as wanted, without any side-effects. */ T getCurrent(); /**Generates the next element, which can then be retrieved with getCurrent(). This method thus only provides * this side-effect. If it is called while the current element is invalid, it may produce and exception, * depending on the implementation on the iterator. */ void generateNext(); } </code></pre> <p>I've never written something like this. Is there a better pattern for this, if any?</p>
[]
[ { "body": "<p>I think most people would be surprised and annoyed by an iterator that mutated previously yielded values every time you called <code>next</code>. While it makes sense to take what you can from the <em>concept</em> of an iterator, the thing you're trying to make isn't an iterator. (Perhaps the idea of a \"cursor\" would be more applicable, IDK.)</p>\n\n<p>Your proposed interface <code>{hasCurrent, getCurrent, generateNext}</code> seems fine. I do have some questions/suggestions. </p>\n\n<ol>\n<li>If <em>not</em> <code>x.hasCurrent()</code>, does <code>x.getCurrent()</code> return null, or throw an exception, or what?</li>\n<li>Depending on 1 (particularly if it <em>doesn't</em> throw an exception), <code>.getCurrent()</code> sounds more like a read-only property, in which case just call it <code>.current()</code>. (or <em>maybe</em> even just <code>.value</code>)</li>\n<li><code>.generateNext()</code> specifically doesn't <em>make</em> anything (because we're supposing that would be expensive); it changes the thing in question. Therefore maybe call it <code>.mutate()</code> or <code>.becomeNext()</code></li>\n<li>A <code>void</code> return is usually a wasted opportunity, even if just for a little extra debugging context. Exactly what will be best to return here depends on exactly how this is going to be used. Returning boolean success might save you a call to <code>.hasNext()</code>; returning <code>T</code> might save you a call to <code>.current()</code>. Probably boolean is better, but it's hard to say.</li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-03T15:01:39.793", "Id": "470551", "Score": "0", "body": "1. It should trow an exception if hasCurrent() is false, but I'm not sure how do implement this. Can I use default-methods for this? 2.&3. Yea, I renamed them, thanks. 4. I'll look what I need, but I also already thought about that." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-03T15:09:31.407", "Id": "470553", "Score": "0", "body": "But the concern about runtime is justified. This thing can generate 1 million subgraphs in a few seconds this way. Creating millions of objects takes a long time doesn't it?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-03T18:01:59.053", "Id": "470564", "Score": "0", "body": "I have very little experience specific to java. _How_ to throw an exception I don't recall being too finicky, if that's the way you want to go." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-03T18:24:44.697", "Id": "470565", "Score": "0", "body": "As for the runtime efficiency; I don't know. My intuition is that, if you structure your context so that only one (or a handful) of these millions of objects are alive in memory at once (_i.e._ they're getting garbage-collected at about the same rate as they're being generated) then it should be fine. Your concern about the cost of generating each next sub-graph scaling with the sub-graph size makes sense (of course I can't confirm it 'cause I haven't seen your code), but you're paying dearly (in terms of safety and intelligibility of your code) to avoid it with this mutable-state solution." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-03T14:53:24.427", "Id": "239876", "ParentId": "239871", "Score": "1" } } ]
{ "AcceptedAnswerId": "239876", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-03T14:25:49.603", "Id": "239871", "Score": "2", "Tags": [ "java", "object-oriented", "design-patterns", "iterator" ], "Title": "Iterator-Pattern for an iterator that returns one objects that changes" }
239871
<p>I have to implement a priority queue using a heap without any library / package for priority queue or heap. I made a BinHeap class which is a min heap, and I made a priority queue class with enqueque, dequeque methods that uses it. The priority queue class works fine but i'm not sure if the code its correct. Can you please help me? Thanks</p> <pre><code>#class Min Heap class BinHeap: #constructor def __init__(self): self.heapList = [0] #heap can be represented as a list, initialize list [] = 0 self.currentSize = 0 #initialize size = 0 #swap last appended element with the parent or right child if needed, until (min) heap structure is mantained def percUp(self,currentSize): while currentSize // 2 &gt; 0: if self.heapList[currentSize] &lt; self.heapList[currentSize // 2]: #if last appended elem &lt; parent self.heapList[currentSize // 2], self.heapList[currentSize] = self.heapList[currentSize], self.heapList[currentSize // 2] #swap them if self.heapList[currentSize] &lt; self.heapList[currentSize-1]: #if right child &lt; left child self.heapList[currentSize], self.heapList[currentSize-1] = self.heapList[currentSize-1], self.heapList[currentSize] #swap them currentSize = currentSize // 2 #continue to check until the root #insert node in the right place, if needed, swap with parent def insert(self,k): self.heapList.append(k) self.currentSize = self.currentSize + 1 self.percUp(self.currentSize) #delete greater node def delMax(self): return self.heapList.pop() #priority queque class class priority_queque(): def __init__(self): self.heap = BinHeap() def enqueque(self, val): self.heap.insert(val) def dequeque(self): self.heap.delMax() #print all pqueque def print(self): print(self.heap.heapList) ci = priority_queque() ci.enqueque(9) ci.enqueque(5) ci.enqueque(6) ci.enqueque(2) ci.enqueque(3) ci.print() ci.dequeque() ci.print() #output #[0, 2, 3, 6, 5, 9] #[0, 2, 3, 6, 5] </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-03T17:40:01.880", "Id": "470562", "Score": "1", "body": "`delMax` seems to be wrong. There is no guarantee that the max element is the last, as you can see from your second output." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-03T14:26:55.997", "Id": "239872", "Score": "1", "Tags": [ "python", "python-3.x", "heap", "priority-queue" ], "Title": "Making a priority queue using a Heap. Without using queue or heapq" }
239872
<p>The program reads in a queue of integers and returns determines whether or not it is valid (ascending). How can this code be improved? I assume iterator include statement is unnecessary?</p> <pre><code>#include &lt;iostream&gt; #include &lt;queue&gt; #include &lt;deque&gt; #include &lt;iterator&gt; template&lt;typename T, typename Container=std::deque&lt;T&gt; &gt; class iterable_queue : public std::queue&lt;T,Container&gt; { public: typedef typename Container::iterator iterator; typedef typename Container::const_iterator const_iterator; iterator begin() { return this-&gt;c.begin(); } iterator end() { return this-&gt;c.end(); } const_iterator begin() const { return this-&gt;c.begin(); } const_iterator end() const { return this-&gt;c.end(); } }; bool checkValidity(iterable_queue&lt;int&gt;&amp; q) { if (q.empty() || q.size() &lt;= 1){ std::cout &lt;&lt; "invalid entry, insufficient elements" &lt;&lt; '\n'; return false; } while(q.size()){ auto i = q.begin(); auto j = ++q.begin(); for(; i &lt; q.end() &amp;&amp; j &lt; ++q.end();){ std::cout &lt;&lt; *i &lt;&lt; " " &lt;&lt; *j &lt;&lt; '\n'; if (*(i) &gt; *(j)) { std::cout &lt;&lt; "invalid entry, not properly sorted" &lt;&lt; '\n'; return false; } i++, j++; } std::cout &lt;&lt; "valid entry, properly sorted" &lt;&lt; '\n'; return true; } std::cout &lt;&lt; "invalid entry, insufficient elements" &lt;&lt; '\n'; return false; } const char* bool_cast(const bool b) { return b ? "true" : "false"; } int main () { iterable_queue&lt;int&gt; numbers; int temp; std::cout &lt;&lt; "Pushing..." &lt;&lt; '\n'; while(temp &gt;= 0){ std::cout &lt;&lt; "Enter numbers: "; std::cin &gt;&gt; temp; if(temp &gt;= 0){ numbers.push(temp); } } bool ck = checkValidity(numbers); std::cout &lt;&lt; bool_cast(ck) &lt;&lt; '\n'; std::cout &lt;&lt; "{ "; while(numbers.size() &gt; 0){ std::cout &lt;&lt; numbers.front(); numbers.pop(); std::cout &lt;&lt; " "; } std::cout &lt;&lt; "}" &lt;&lt; '\n'; return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-03T14:53:03.243", "Id": "470549", "Score": "1", "body": "What would happen if `q.size()` yields zero?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-24T03:12:38.837", "Id": "476589", "Score": "0", "body": "Return false. invalid entry, insufficient elements." } ]
[ { "body": "<p>Queues are not designed to be used like this. Your <code>iterable_queue</code> clearly shows that you are not using queues the way they are supposed to be used. And the <code>checkValidity</code> function should be simplified with <code>std::is_sorted</code> from the standard library. In <code>q.empty() || q.size() &lt;= 1</code>, the first condition is subsumed by the second. The <code>while(q.size()){</code> loop also seems to have no significance. <code>++q.end()</code> is also undefined behavior. The <code>bool_cast</code> functionality is already provided by <code>std::boolalpha</code>.</p>\n\n<p>Overall, I think you are seriously over-complicating everything:</p>\n\n<pre><code>#include &lt;algorithm&gt;\n#include &lt;iostream&gt;\n#include &lt;iterator&gt;\n#include &lt;vector&gt;\n\nint main()\n{\n std::vector&lt;int&gt; numbers;\n for (int num; std::cin &gt;&gt; num &amp;&amp; num &gt;= 0;) {\n numbers.push_back(num);\n }\n\n bool valid = numbers.size() &gt; 1 &amp;&amp; std::is_sorted(numbers.begin(), numbers.end());\n std::cout &lt;&lt; \"Valid? \" &lt;&lt; std::boolalpha &lt;&lt; valid &lt;&lt; '\\n';\n\n std::cout &lt;&lt; \"{ \";\n for (int num : numbers) {\n std::cout &lt;&lt; num &lt;&lt; ' ';\n }\n std::cout &lt;&lt; \"}\\n\";\n}\n</code></pre>\n\n<p>(<a href=\"https://wandbox.org/permlink/KEb99eFup8AxQLgt\" rel=\"nofollow noreferrer\">live demo</a>)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-04T19:18:07.213", "Id": "470622", "Score": "0", "body": "The point of the exercise is to use the queue container and not a vector." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-05T02:10:56.107", "Id": "470656", "Score": "0", "body": "@DarnocEloc You are deriving from queue and accessing the underlying container directly. That's not how a queue is supposed to work, so in a sense, you are already disregarding \"the point of the exercise.\" I guess the intention of the exercise is to validate the numbers when you read them or when you print them (because traversing a queue is destructive). Anyway, I don't think using queues is an \"improvement\" for the code, so I'll leave my remarks for other members of the community." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-04T09:47:12.010", "Id": "239910", "ParentId": "239873", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-03T14:38:11.757", "Id": "239873", "Score": "0", "Tags": [ "c++", "performance", "iterator", "queue" ], "Title": "Ensure queue is in ascending order" }
239873
<p>I am learning Dyalog APL. I implemented a binary heap, which seems to work. How could I make it look more like APL (and less like Python)?</p> <pre><code>⎕io←0 heappush←{(⍺,⍵)siftdown 0(≢⍺)} heappop←{ heap←⍵ last←⊃¯1↑heap ⋄ rest←¯1↓heap 0=≢rest:rest last r←heap[0] (((last@0)rest)siftup 0)r } siftdown←{ heap←⍺ start pos←⍵ item←pos⌷heap newpos←{ ⍵≤start:⍵ parentpos←⌊(⍵-1)÷2 parent←parentpos⌷heap item&lt;parent:∇ parentpos⊣heap[⍵]←parent ⍵ }pos (item@newpos)heap } siftup←{ heap←⍺ p←{ pos←⍵ chp←1+2×pos chp≥≢heap:pos rpos←1+chp chp←((rpos&lt;≢heap)∧~heap[chp]&lt;heap[rpos])⊃chp rpos heap[pos]←heap[chp] ∇ chp }⍵ heap[p]←⍺[⍵] heap siftdown ⍵ p } heap←0 1 2 5 6 8 9 heappop heap ┌→────────────────┐ │ ┌→──────────┐ │ │ │1 5 2 9 6 8│ 0 │ │ └~──────────┘ │ └∊────────────────┘ heap heappush 3 ┌→──────────────┐ │0 1 2 3 6 8 9 5│ └~──────────────┘ </code></pre>
[]
[ { "body": "<blockquote>\n <p>How could I make it look more like APL (and less like Python)?</p>\n</blockquote>\n\n<p>Assuming you mean \"in a more functional and less imperative way\" by this line,</p>\n\n<h2>I don't think you can largely achieve that, for a good reason.</h2>\n\n<p>Basically, the array-based heap (and other common algorithms you see on algorithm textbooks) is designed for imperative languages. Translating it into a language <em>whose main strength isn't imperative</em> makes the code feel awkward and unfitting. It may also lead to code whose time complexity is actually worse than designed. <a href=\"https://stackoverflow.com/a/958588/4595904\">See how it looks like when a similar algorithm is written in Haskell.</a></p>\n\n<p>APL is not 100% functional, but definitely is more functional than imperative (especially when you mainly use dfns). If you want, search for \"functional algorithms\" and try implementing those. In the case of a heap, <a href=\"https://en.wikipedia.org/wiki/Leftist_tree\" rel=\"nofollow noreferrer\">leftist tree</a> isn't too complex, and supports one more <span class=\"math-container\">\\$O(\\log n)\\$</span> operation (heap merge) compared to an imperative binary heap. You can check out a <a href=\"http://typeocaml.com/2015/03/12/heap-leftist-tree/\" rel=\"nofollow noreferrer\">nice illustration</a> too.</p>\n\n<h2>But you can still improve some parts of the code.</h2>\n\n<h3>Improvement in the algorithm</h3>\n\n<ul>\n<li>Use <code>⎕IO←1</code> instead.</li>\n</ul>\n\n<p>Array-based heap uses 0-based indexing by default, so the parent-child relationship is slightly awkward:</p>\n\n<p><span class=\"math-container\">$$\n\\begin{align}\n\\text{left child}&amp;=1+2\\times\\text{parent} \\\\\n\\text{right child}&amp;=2+2\\times\\text{parent} \\\\\n\\text{parent}&amp;=\\Bigl\\lfloor \\frac{\\text{child} - 1}2 \\Bigr\\rfloor\n\\end{align}\n$$</span></p>\n\n<p>If you use 1-based indexing instead, it becomes slightly cleaner:</p>\n\n<p><span class=\"math-container\">$$\n\\begin{align}\n\\text{left child}&amp;=2\\times\\text{parent} \\\\\n\\text{right child}&amp;=1+2\\times\\text{parent} \\\\\n\\text{parent}&amp;=\\Bigl\\lfloor \\frac{\\text{child}}2 \\Bigr\\rfloor\n\\end{align}\n$$</span></p>\n\n<p>I don't have other better ideas to utilize the strengths of APL, due to the underlying algorithm being purely imperative.</p>\n\n<h3>General tips for writing APL code</h3>\n\n<ul>\n<li>Let the right argument of dyadic functions be the primary one (i.e. the heap).</li>\n<li>If you see a negation of a comparison (e.g. <code>~heap[chp]&lt;heap[rpos]</code>), use a single equivalent function (e.g. <code>heap[chp]≥heap[rpos]</code>).</li>\n<li>Prefer concatenation (e.g. <code>0,≢⍺</code>) over stranding (e.g. <code>0(≢⍺)</code>) when you concatenate two scalars.</li>\n<li>Try not to modify existing variable's contents (e.g. avoid <code>chp←((rpos&lt;≢heap)∧~heap[chp]&lt;heap[rpos])⊃chp rpos</code> which refers to <code>chp</code> and then modifies it) when it isn't essential in implementing the algorithm. Try to choose a separate and meaningful name instead.</li>\n<li>Parenthesize stranding assignments (e.g. <code>(start pos)←⍵</code> instead of <code>start pos←⍵</code>).</li>\n<li>Consider following a <a href=\"https://codereview.stackexchange.com/a/239843/182436\">naming convention</a>, and a little more descriptive names. (e.g. I can't easily see what <code>chp</code> stands for.)</li>\n<li>Consider adding comments to each function which briefly describe the input(s) and the output.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-07T08:21:52.920", "Id": "470907", "Score": "0", "body": "Thank you! I made a Leftist Tree following your suggestion, and it does indeed look much better: https://gist.github.com/xpqz/c10b3009a68f9ffdc84c2fb09b44302a" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-07T08:42:09.820", "Id": "470908", "Score": "0", "body": "@xpqz Great job :) If you want further feedback, you can post a separate question with your new piece of code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-07T09:01:31.710", "Id": "470910", "Score": "0", "body": "New question here: https://codereview.stackexchange.com/questions/240089/leftist-tree-in-dyalog-apl-can-it-be-made-more-compact-idiomatic" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-06T05:02:52.620", "Id": "240024", "ParentId": "239878", "Score": "2" } } ]
{ "AcceptedAnswerId": "240024", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-03T15:17:35.283", "Id": "239878", "Score": "4", "Tags": [ "heap", "apl" ], "Title": "A heap queue in Dyalog APL" }
239878
<h1>The problem / background</h1> <p>I have a project, <em>BusinessProject</em>, that currently stores some static data in memory using the <a href="https://csharpindepth.com/Articles/Singleton" rel="nofollow noreferrer">Singleton pattern</a> - we'll call this class <code>GlobalData</code>. This project is used in multiple applications, with different requirements on what data should be loaded into memory. One application, lets call this <em>SubProject</em>, only needs a subset of the data. The other project, <em>MasterProject</em>, calls <em>SubProject</em> as well as other functions within <em>BusinessProject</em> which require other data in <code>GlobalData</code> to be available in memory. <strong>My goal is to use inheritance to avoid storing the overlapping data twice, as well as let the project interfacing with <em>BusinessProject</em> easily define the requirements needed by simply calling the desired class.</strong></p> <h1>Simplified Code</h1> <pre><code>public class GlobalData { protected static readonly GlobalData _Instance = new GlobalData(); protected DateTime _lastUpdateDate = DateTime.MinValue; public Dictionary&lt;string, class&gt; Lookup { get; protected set; } public IList&lt;DateTime&gt; Dates { get; set; } public Dictionary&lt;string, List&lt;double&gt;&gt; DataSeries { get; protected set; } static GlobalData() { } private GlobalData() { } // each time the Instance requested, make sure the data doesn't need to be refreshed public static GlobalData Instance { get { if (!DateTime.Today.Date.Equals(_Instance._lastUpdateDate.Date)) _Instance.LoadData(); return _Instance; } } protected virtual void LoadData() { ... _lastUpdateDate = DateTime.Today; } } public class MasterData : GlobalData { protected static new readonly MasterData _Instance = new MasterData(); ... //extra data properties static MasterData() { } private MasterData() :base() {} protected override void LoadData() { base.LoadData(); ... // load extra data properties } } </code></pre> <h1>Conclusion</h1> <p>I'm looking for any feedback on my implementation of the problem ! Thank you.</p>
[]
[ { "body": "<p>If the objective is to avoid duplicating information in memory, the code you have given won't archive it.</p>\n\n<p>The <code>new</code> keyword hides the original value. It doesn't replace it. You should try another approximations, like the Decorator pattern: <a href=\"https://en.wikipedia.org/wiki/Decorator_pattern\" rel=\"nofollow noreferrer\">https://en.wikipedia.org/wiki/Decorator_pattern</a></p>\n\n<p>The MasterData inherits from the GlobalData class and stores internally the reference to that class. Whenever someone accesses to a property of the GlobalData class, you redirect the request to the instance stored internally.</p>\n\n<p>The MasterData class stores only the values of the newly added properties.</p>\n\n<p>The tricky part would be preventing other parts of your MasterApplication app calling to the GlobalData class and thus creating another instance.</p>\n\n<p>Singletons are always a nightmare...</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-05T22:18:53.537", "Id": "240007", "ParentId": "239879", "Score": "1" } } ]
{ "AcceptedAnswerId": "240007", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-03T15:39:24.327", "Id": "239879", "Score": "0", "Tags": [ "c#", "performance", "memory-management", "inheritance", "singleton" ], "Title": "Inheritance with Singletons" }
239879
<p>I wanted to be sure the thread being tested would complete its job by the Assert statement of the unit test, but I couldn't be sure bc of the way I designed the threads. I designed them to run forever in the background, performing a task - logging, assembling, or disassembling - at regular timed intervals. What I ended up doing was sleeping the test thread for a bit to ensure the thread being tested had enough time to complete its task. I have no idea whether this is the "right" way to handle this situation, and I'd appreciate any feedback!</p> <pre><code>@Test // Tests whether thread removes completed tasks from in_progress and returns // processors to available public void testOne() { t.complete = true; d.start(); try { Thread.sleep(20); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } Assert.assertEquals(cs.size(), 3); Assert.assertEquals(inProgressJobs.size(), 0); } </code></pre> <p>Full code: <a href="https://github.com/dandelion1234/Map-Reduce" rel="nofollow noreferrer">https://github.com/dandelion1234/Map-Reduce</a></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-03T18:40:32.457", "Id": "470567", "Score": "4", "body": "Please give more context and more of the actual code in the questions itself. What's `t`? What's `d`? What's `cs`? It's appropriate to put several pages of code in a CR question." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-04T07:31:52.270", "Id": "470593", "Score": "1", "body": "Independently of being [on- or off-topic](https://codereview.stackexchange.com/help/on-topic) where you post such a question: Please indicate your knowledge/experience level regarding concurrency." } ]
[ { "body": "<p>When you want to test things that happened asynchronously, one solution is to give them some time to happen as you did. A bit more practical approach is to check if the assert condition is met in a loop and sleep a bit between the checks. if the condition is met no need to continue waiting. eventually, it needs to stop after a few tries or you have an infinite loop in your test.</p>\n\n<p>Usually, you need to use this approach in E2E / Integration tests and not unit tests.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-06T10:03:23.003", "Id": "240040", "ParentId": "239880", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-03T16:44:06.083", "Id": "239880", "Score": "0", "Tags": [ "java" ], "Title": "How to Unit Test a Thread which has an infinite loop?" }
239880
<p>For my student job, I have been logging work times with the <code>org-mode</code> in emacs for quite some time. Now since I can only work from remote, I figured it would be nice to automatically use the entries from the .org files into readily-formatted entries. I am doing this because the job requires me to write an Excel sheet with the hours worked each month in a specific format:</p> <ul> <li>For each day, there is one entry</li> <li>Each entry features the date, start and ending time, pause in minutes, and hours worked.</li> </ul> <p>With the help of the Emacs package <a href="https://github.com/atheriel/org-clock-csv" rel="nofollow noreferrer"><code>org-clock-csv</code></a> I was able to generate CSV output containing start and end times including dates. I wrote a Python script to parse these into the desired format, and I feel there is a lot of room for improvement.</p> <p>The input looks like this (<code>testoutput.csv</code>):</p> <pre class="lang-none prettyprint-override"><code>organization,,,2020-04-03 10:49,2020-04-03 13:19,,, some stuff,,,2020-04-03 10:39,2020-04-03 10:49,,, more stuff,,,2020-04-02 12:25,2020-04-02 12:25,,, some stuff,,,2020-04-02 09:43,2020-04-02 09:47,,, other stuff,,,2020-04-02 09:35,2020-04-02 09:43,,, organization,,,2020-03-27 14:00,2020-03-27 14:28,,, Orga,,,2020-03-27 09:10,2020-03-27 09:42,,, Orga,,,2020-03-23 09:13,2020-03-23 09:25,,, Orga,,,2020-03-22 09:56,2020-03-22 10:03,,, </code></pre> <p>There are several things the code needs to do: summarize entries for each day, parse the times and dates, and compute total time worked as well as pause times. Pause times are the result of the difference of (latest end - earliest start) and the actual total time worked.</p> <p>The result should look like this (<code>testoutput_parsed.csv</code>, actual output of my script):</p> <pre class="lang-none prettyprint-override"><code>date,start,stop,pause (minutes),total (hours) 02.04.,09:35,12:25,158,00:12 03.04.,10:39,13:19,0,02:40 22.03.,09:56,10:03,0,00:07 23.03.,09:13,09:25,0,00:12 27.03.,09:10,14:28,258,01:00 </code></pre> <p>As far as I can tell, the output is correct. However, I am looking for comments on code quality in terms of structure, complying with conventions and such. </p> <p>Here is the actual code:</p> <pre><code>import datetime from operator import itemgetter import csv def read_timestamps_from_csv(csv_filename, delim=','): with open(csv_filename, 'r') as file: times_list = [] for line in file: # skip header if 'task' in line: continue try: start_str, stop_str = line.split(delim)[3:5] start_time = datetime.datetime.strptime(start_str, '%Y-%m-%d %H:%M') stop_time = datetime.datetime.strptime(stop_str, '%Y-%m-%d %H:%M') times_list.append([start_time, stop_time]) except: print(f'unable to parse this line: {line}') return times_list def summarize_timestamps(timestamp_pairs): summary_stamps = [] for stamp_pair in timestamp_pairs: # check if date is already in summary_stamps if date_is_present(stamp_pair[0], summary_stamps): # if so, add time and change end time date_idx = get_date_index(stamp_pair[0], summary_stamps) if summary_stamps[date_idx]['date'] == stamp_pair[0].date(): new_start = min(stamp_pair[0].time(), summary_stamps[date_idx]['start']) new_stop = max(stamp_pair[1].time(), summary_stamps[date_idx]['stop']) summary_stamps[date_idx]['start'] = new_start summary_stamps[date_idx]['stop'] = new_stop summary_stamps[date_idx]['total'] += stamp_pair[1] - stamp_pair[0] else: # if not, add a summary_stamp with start time, end time and time summary_stamps.append({'date':stamp_pair[0].date(), 'start':stamp_pair[0].time(), 'stop':stamp_pair[1].time(), 'total':stamp_pair[1] - stamp_pair[0] }) # add break field for s, sumst in enumerate(summary_stamps): stop_start_diff = datetime.datetime.combine(sumst['date'], sumst['stop']) - datetime.datetime.combine(sumst['date'], sumst['start']) pause_time = stop_start_diff - sumst['total'] summary_stamps[s]['pause_min'], _ = divmod(pause_time.seconds, 60) return summary_stamps def date_is_present(timestamp, summary_stamps): if summary_stamps == []: return False for summary_stamp in summary_stamps: if summary_stamp['date'] == timestamp.date(): return True # if no date is present: return False def get_date_index(timestamp, summary_stamps): for s, summary_stamp in enumerate(summary_stamps): if summary_stamp['date'] == timestamp.date(): return s def parse_summary_stamps_to_entries(summary_stamps): entry_list = [[] for i in range(len(summary_stamps))] for s, sumst in enumerate(summary_stamps): total_hours, rem = divmod(sumst['total'].seconds, 3600) total_minutes, _ = divmod(rem, 60) entry_list[s] = [ sumst['date'].strftime('%d.%m.'), sumst['start'].strftime('%H:%M'), sumst['stop'].strftime('%H:%M'), sumst['pause_min'], f'{total_hours:02}:{total_minutes:02}' ] return entry_list def sort_entries_by_date(entry_list): return sorted(entry_list, key=itemgetter(0)) def write_times_to_csv(sorted_entries, fname_out, delim=','): with open(fname_out, mode='w') as file: writer = csv.writer(file, delimiter=delim) for entry in sorted_entries: writer.writerow(entry) print(f'wrote csv file: {fname_out}') if __name__ == '__main__': fname_in = 'testoutput.csv' fname_out = 'testoutput_parsed.csv' timestamp_pairs = read_timestamps_from_csv(fname_in) summary_stamps =summarize_timestamps(timestamp_pairs) entry_list = parse_summary_stamps_to_entries(summary_stamps) sorted_entries = sort_entries_by_date(entry_list) header = ['date', 'start', 'stop', 'pause (minutes)', 'total (hours)'] #print(header) #for entry in sorted_entries: # print(entry) sorted_entries = [header, *sorted_entries] write_times_to_csv(sorted_entries, fname_out) </code></pre>
[]
[ { "body": "<h2>Pathlib</h2>\n\n<p>Rather than accepting <code>csv_filename</code> as a string, accept it as a <code>Path</code>. Then</p>\n\n<pre><code>with open(csv_filename, 'r') as file:\n</code></pre>\n\n<p>becomes</p>\n\n<pre><code>with csv_filename.open() as file:\n</code></pre>\n\n<h2>Generator</h2>\n\n<p>Turn <code>read_timestamps_from_csv</code> into a generator that yields 2-tuples:</p>\n\n<pre><code>from datetime import datetime\n# ...\nDATE_FMT = '%Y-%m-%d %H:%M'\n\ndef read_timestamps_from_csv(csv_filename: Path, delim: str=',') -&gt; Iterable[Tuple[datetime, datetime]]:\n with csv_filename.open() as file:\n for line in file:\n\n # skip header\n if 'task' in line:\n continue\n\n try:\n start_str, stop_str = line.split(delim)[3:5]\n start_time = datetime.strptime(start_str, DATE_FMT)\n stop_time = datetime.strptime(stop_str, DATE_FMT)\n yield start_time, stop_time\n except Exception:\n print(f'Unable to parse this line: \"{line}\"')\n</code></pre>\n\n<p>Also note:</p>\n\n<ul>\n<li>Factor out a formatting constant</li>\n<li>Importing of the <code>datetime</code> symbol</li>\n<li>Never <code>except</code>; at least catch an <code>Exception</code> if not a more narrow type</li>\n<li>Some type hints</li>\n</ul>\n\n<h2><code>summarize_timestamps</code> / <code>date_is_present</code></h2>\n\n<p>This:</p>\n\n<pre><code>for summary_stamp in summary_stamps:\n if summary_stamp['date'] == timestamp.date():\n return True\n</code></pre>\n\n<p>is a search in linear time - O(n) complexity, which is slow. To reduce this to constant time, or O(1), use a <code>set</code> of dates and the <code>in</code> operator; or alternately maintain a dictionary whose keys are the dates.</p>\n\n<p>The dictionary approach would simplify your code in <code>summarize_timestamps</code>. You have two loops. The first loop would still need to keep a dictionary since you're going back and mutating entries before being able to yield them.</p>\n\n<p>Then, your last loop can further mutate to add the break field and yield there.</p>\n\n<p>This can be more simplified if - instead of using a dictionary - you use an actual class, with attribute of <code>date</code>, <code>start</code>, <code>stop</code> and <code>total</code>. Also, this loop:</p>\n\n<pre><code>for stamp_pair in timestamp_pairs:\n</code></pre>\n\n<p>should immediately unpack that pair, i.e.</p>\n\n<pre><code>for start, stop in timestamp_pairs:\n</code></pre>\n\n<h2>Time math</h2>\n\n<pre><code> summary_stamps[s]['pause_min'], _ = divmod(pause_time.seconds, 60)\n</code></pre>\n\n<p>is a red flag.</p>\n\n<p>You're throwing out the second return value from <code>divmod</code>, so why call it at all? If you still wanted to do your own math, just use integer division - <code>//</code>. However, you should nearly never be doing your own time math. </p>\n\n<p>This is one of the many things that C# does better out-of-the-box than Python, but anyway: reading <a href=\"https://docs.python.org/3/library/datetime.html#datetime.timedelta.total_seconds\" rel=\"nofollow noreferrer\">this documentation</a>, the recommended method (without bringing in a third-party lib) is:</p>\n\n<pre><code>summary_stamps[s]['pause_min'] = pause_time // timedelta(minutes=1)\n</code></pre>\n\n<p>The same goes for </p>\n\n<pre><code> total_hours, rem = divmod(sumst['total'].seconds, 3600)\n total_minutes, _ = divmod(rem, 60)\n</code></pre>\n\n<h2>Redundant <code>if</code></h2>\n\n<p>This:</p>\n\n<pre><code>if summary_stamps == []:\n return False\n</code></pre>\n\n<p>should get deleted, because if that list is empty, the iteration will execute zero times and the return will be the same.</p>\n\n<p>However, the whole function can be replaced with</p>\n\n<pre><code>td = timestamp.date()\nreturn any(stamp['date'] == td for stamp in summary_stamps)\n</code></pre>\n\n<h2>Sorting</h2>\n\n<p>Have you tried</p>\n\n<pre><code>return sorted(entry_list, key=itemgetter(0))\n</code></pre>\n\n<p>without the <code>key</code>? The default behaviour is to sort on the first item of a tuple.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-06T14:52:57.520", "Id": "470802", "Score": "0", "body": "Thank you very much, your advice is very helpful to me! How exactly can `summarize_timestamps` or `summary_stamps` be turned into a generator? The difference to me is that for each function call, there may be several inputs necessary to generate a single output. This would require multiple runs of the outer for loop. Did I miss something?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-06T14:55:24.857", "Id": "470803", "Score": "0", "body": "Also, the type hints for `read_timestamps_from_csv` seem to require me to import `Iterable` and `Tuple`. Is it generally recommended to add imports for type hints?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-06T15:37:47.313", "Id": "470815", "Score": "1", "body": "_Is it generally recommended to add imports for type hints?_ - Using type hints, in general, is a good idea. There are some differing opinions on how this is done. Some prefer string-style type hints (i.e. `csv_filename: 'Path'`) and others bare symbols as I have shown. Some prefer that the import from `typing` be done in an unconditional manner, and others prefer to wrap their typing imports in an `if typing.TYPE_CHECKING` clause. Some prefer qualified type references like `typing.Tuple` and others just `Tuple`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-06T15:37:50.443", "Id": "470816", "Score": "1", "body": "You can experiment a little, but my preference is - bare, not string; unconditional; and unqualified." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-06T16:00:21.680", "Id": "470819", "Score": "1", "body": "As for `summary_stamps` - I've made an edit." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-06T01:12:48.387", "Id": "240015", "ParentId": "239881", "Score": "2" } } ]
{ "AcceptedAnswerId": "240015", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-03T16:45:00.030", "Id": "239881", "Score": "2", "Tags": [ "python", "python-3.x", "datetime", "csv" ], "Title": "Parse org-mode clocktable CSVs into time sheets" }
239881
<p>I want to calculate the intersection of two squares where the coordinates of the input square are given by the bottom left corner and the top right corner. The other square is 6 units wide and has a variable positive integer height h (to make the task simpler). </p> <p><a href="https://i.stack.imgur.com/27wXz.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/27wXz.jpg" alt="enter image description here"></a></p> <p>For that I defined some functions:</p> <p>The first one is to make sure that the first two coordinates a1, a2 represent the bottom left corner and the two last coordinates represent the top right corner. That way, if someone would type the coordinates the other way around, e.g. the first two numbers being the coordinates of the top left corner and the two last numbers being the coordinates for the bottom right corner, convert_to_standard would switch the coordinates to the right place:</p> <pre><code>def convert_to_standard(a1,a2,b1,b2): if a1 &lt;= b1 and a2 &lt;= b2: return (a1,a2,b1,b2) elif a1 &gt;= b1 or a2 &gt;= b2: a_1 = min(a1,b1) b_1 = max(a1,b1) a_2 = min(a2,b2) b_2 = max(a2,b2) return (a_1,a_2,b_1,b_2) </code></pre> <p>Since I'm quite new to Python I was wondering if there are more elegant ways of making this happen.</p> <p>I've also written a function to test if the squares even intersect, maybe there is way of making this better too: (The "return "incorrect" bit is for later, get_intersection_area returns the string "incorrect input" if h &lt; 0) (Sorry if I'm overexplainig too much)</p> <pre><code>def intersects(h,a1,a2,b1,b2): if h &lt; 0: return "incorrect" a1,b1,a2,b2 = convert_to_standard(a1,b1,a2,b2) if a1 &gt; 6: #square is on the right side of R_h return False if b1 &lt; 0: #square is on the left side of R_h return False if a2 &gt; h: #square is above R_h return False if b2 &lt; 0: #square is below R_h return False else: return True </code></pre> <p>What also bothers me is that I'm not sure if the code runs functions needlessly. Specifically the function that calculates the width (get_delta_x1) and height (get_delta_x2) of the resulting square. I would like to only run it when the intersection is not empty and the input is correct (an incorrect input would be a negative value for h). Here is the complete code to check that:</p> <pre><code>def convert_to_standard(a1,a2,b1,b2): if a1 &lt;= b1 and a2 &lt;= b2: return (a1,a2,b1,b2) elif a1 &gt;= b1 or a2 &gt;= b2: a_1 = min(a1,b1) b_1 = max(a1,b1) a_2 = min(a2,b2) b_2 = max(a2,b2) return (a_1,a_2,b_1,b_2) #checks if the input square intersects with the "given" square (whose height h has to be chosen) def intersects(h,a1,a2,b1,b2): if h &lt; 0: return "incorrect" a1,b1,a2,b2 = convert_to_standard(a1,b1,a2,b2) if a1 &gt; 6: #square is on the right side of R_h return False if b1 &lt; 0: #square is on the left side of R_h return False if a2 &gt; h: #square is above R_h return False if b2 &lt; 0: #square is below R_h return False else: return True #lenght of the resulting intersection square def get_delta_x1(a1,b1): if 0 &lt;= a1 &lt;= 6 and 0 &lt;= b1 &lt;= 6: #square is inside regarding x1 return b1 - a1 elif a1 &lt; 0: #square sticks out on the left return b1 elif b1 &gt; 6: #square sitcks out on the right return 6 - a1 #height of the resulting intersection square def get_delta_x2(h,a2,b2): if 0 &lt;= a2 &lt;= h and 0 &lt;= b2 &lt;= h: #square is inside regarding x2 return b2 - a2 elif a2 &lt; 0: #square sticks out below return b2 elif b2 &gt; h: #square sticks out above return h - a2 #area of the intersection def get_intersection_area(h,a1,a2,b1,b2): if intersects(h,a1,a2,b1,b2) == True: A = get_delta_x1(a1,b1) * get_delta_x2(h,a2,b2) return "The area of the resulting square is &lt;"+str(A)+"&gt; UA." elif intersects(h,a1,a2,b1,b2) == False: return "The intersection of the resulting squares is empty" elif intersects(h,a1,a2,b1,b2) == "incorrect": return "The input is incorrect" </code></pre> <p>Since this is a quick program, changes in the code almost won't change runtime. I just want to get more elegant for future projects where runtime will be an issue. I hope this is the right forum for that.</p> <p>Thank you a lot in advance</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-04T21:31:54.110", "Id": "470627", "Score": "0", "body": "Do you mean “rectangle” instead of “square”? Squares are rectangles where the height and width are the same length. Yours appear to have heights different from their widths, which should make them rectangles." } ]
[ { "body": "<p>My main piece of advice is to think in terms of general solutions rather than trying to handle each case separately. For example, taking this function:</p>\n\n<pre><code>def convert_to_standard(a1,a2,b1,b2):\n if a1 &lt;= b1 and a2 &lt;= b2:\n return (a1,a2,b1,b2)\n elif a1 &gt;= b1 or a2 &gt;= b2:\n a_1 = min(a1,b1)\n b_1 = max(a1,b1)\n a_2 = min(a2,b2)\n b_2 = max(a2,b2)\n return (a_1,a_2,b_1,b_2)\n</code></pre>\n\n<p>If <code>a1 &lt;= b1</code> then <code>min(a1, b1)</code> is the same as <code>a1</code>, right? And so on for the other values in your <code>if</code> statements. This can in fact be written as:</p>\n\n<pre><code>def convert_to_standard(a1, a2, b1, b2):\n return (\n min(a1, b1),\n min(a2, b2),\n max(a1, b1),\n max(a2, b2),\n )\n</code></pre>\n\n<p>Because it's hard to keep track of which value is which, I'd personally want to express this as two coordinate pairs rather than a single 4-tuple. I'd also use the name \"normalize\" for this operation:</p>\n\n<pre><code>from typing import Optional, Tuple\n\nRect = Tuple[Tuple[int, int], Tuple[int, int]]\n\ndef normalize(rect: Rect) -&gt; Rect:\n \"\"\"\n Given a rectangle specified as a pair of arbitrary opposite corners,\n normalize to a pair where the first is the lower left and second is upper right.\n \"\"\"\n (ax, ay), (bx, by) = rect\n return (\n (min(ax, bx), min(ay, by)),\n (max(ax, bx), max(ay, by)),\n )\n\n</code></pre>\n\n<p>In your problem description:</p>\n\n<blockquote>\n <p>The other square is 6 units wide and has a variable positive integer height h (to make the task simpler).</p>\n</blockquote>\n\n<p>this does not actually make the task simpler, it makes it harder, because now you have to deal with different formats of input. It would be simpler IMO to write a function that takes two rectangles in a standardized format and returns a rectangle representing their intersection, since it's easier to reason about that sort of straightforward geometric problem than to solve a particular special case subset of it. </p>\n\n<pre><code>def bottom(rect: Rect) -&gt; int:\n return rect[0][1]\n\ndef top(rect: Rect) -&gt; int:\n return rect[1][1]\n\ndef left(rect: Rect) -&gt; int:\n return rect[0][0]\n\ndef right(rect: Rect) -&gt; int:\n return rect[1][0]\n\ndef overlaps(a: Rect, b: Rect) -&gt; bool:\n \"\"\"\n Computes whether two normalized rectangles have a non-zero overlap.\n \"\"\"\n return (\n top(a) &gt; bottom(b) # top of a is not below b\n and top(b) &gt; bottom(a) # top of b is not below a\n and right(a) &gt; left(b) # right of a is not left of b\n and right(b) &gt; left(a) # right of b is not left of a\n )\n</code></pre>\n\n<p>etc.</p>\n\n<p>If your input is in a specialized format, I think it's still better to write the general-purpose rectangle code and then add a bit of code to translate the input into a normalized rectangle.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-04T13:56:45.273", "Id": "470612", "Score": "0", "body": "I would also consider a zero overlap an overlap even though the area is zero when there is just a line that overlaps, but that could be changed quickly changing \">\" to \">=\"." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-04T14:28:50.673", "Id": "470615", "Score": "1", "body": "That's why the docstring says \"non-zero overlap\" to clarify how I'm defining it; I can see either version being useful depending on whether you consider a zero-area rectangle to be valid. Docstrings are important! :)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-03T21:21:35.427", "Id": "239892", "ParentId": "239887", "Score": "7" } }, { "body": "<p>Using 4 variables (<code>a1,a2,b1,b2</code>) to define a rectangle is awkward. You need to pass all 4 variables, and remember what the correct order of the variables are.</p>\n\n<p>Consider:</p>\n\n<pre><code>def convert_to_standard(a1,a2,b1,b2):\n ...\n\ndef intersects(h,a1,a2,b1,b2):\n if h &lt; 0:\n return \"incorrect\"\n\n a1,b1,a2,b2 = convert_to_standard(a1,b1,a2,b2)\n\n ...\n</code></pre>\n\n<p>Is this correct? You've passed <code>b1</code> to <code>a2</code> and <code>a2</code> to <code>b1</code>! </p>\n\n<p>As suggested by <a href=\"https://codereview.stackexchange.com/a/239892/100620\">Sam Stafford</a>, using a tuple of tuples can help.</p>\n\n<pre><code>Rect = Tuple[Tuple[int, int], Tuple[int, int]]\n</code></pre>\n\n<p>But it still isn't clear if the first coordinate is the lower left, or the upper left. Better would be to use a <a href=\"https://docs.python.org/3/library/typing.html#typing.NamedTuple\" rel=\"nofollow noreferrer\"><code>NamedTuple</code></a>:</p>\n\n<pre><code>from typing import NamedTuple\n\nclass Rectangle(NamedTuple):\n left: float\n bottom: float\n right: float\n top: float\n</code></pre>\n\n<p>This <code>Rectangle</code> class gives you named members from <code>rect.left</code> through <code>rect.top</code>, which makes it easy to tell what the values represent.</p>\n\n<p>The <code>convert_to_standard()</code> functionality can be added as a <code>@classmethod</code> to this class, returning a normalized <code>Rectangle</code> regardless of the vertex orientation:</p>\n\n<pre><code> @classmethod\n def normalize(self, x1, y1, x2, y2) -&gt; 'Rectangle':\n return Rectangle(min(x1, x2), min(y1, y2), max(x1, x2), max(y1, y2))\n</code></pre>\n\n<p>You can add a <code>@property</code> for the rectangle's width and height, ensuring the width and height are never negative:</p>\n\n<pre><code> @property\n def width(self) -&gt; float:\n return max(self.right - self.left, 0)\n\n @property\n def height(self) -&gt; float:\n return max(self.top - self.bottom, 0)\n</code></pre>\n\n<p>As well as a <code>@property</code> for the rectangle's area:</p>\n\n<pre><code> @property\n def area(self) -&gt; float:\n return self.width * self.height\n</code></pre>\n\n<p>You can add a method to determine if a rectangle is valid or not, based on this area. <code>if rect</code> will return <code>True</code> only for valid rectangles, which have a positive area, so must have a top coordinate larger than the bottom, and a right coordinate larger than the left:</p>\n\n<pre><code> def __bool__(self):\n return self.area &gt; 0\n</code></pre>\n\n<p>Finally, we can define a method which returns the intersection of two <code>Rectangle</code> objects:</p>\n\n<pre><code> def intersect(self, other):\n if not isinstance(other, Rectangle):\n raise TypeError(\"Not a rectangle\")\n return Rectangle(max(self.left, other.left), max(self.bottom, other.bottom),\n min(self.right, other.right), min(self.top, other.top))\n</code></pre>\n\n<p>And we can write some code to quickly exercise this class, based on the diagram given at the top. (Also, notice the use of <code>f\"...\"</code> strings for formatted output):</p>\n\n<pre><code>if __name__ == '__main__':\n h = 5\n rh = Rectangle(0, 0, 6, h)\n r1 = Rectangle.normalize(-6, -4, 2, 1)\n r2 = Rectangle.normalize(-3, 7, 3, 5) # flipped top-bottom\n r3 = Rectangle.normalize(9, 2, 5, 4) # flipped left-right\n\n for rect in (r1, r2, r3):\n intersection = rh.intersect(rect)\n if intersection:\n print(f\"{rect} intersection area = {intersection.area}\")\n else:\n print(f\"{rect} No intersection\")\n</code></pre>\n\n<p>Output:</p>\n\n<blockquote>\n<pre><code>Rectangle(left=-6, bottom=-4, right=2, top=1) intersection area = 2\nRectangle(left=-3, bottom=5, right=3, top=7) No intersection\nRectangle(left=5, bottom=2, right=9, top=4) intersection area = 2\n</code></pre>\n</blockquote>\n\n<h1>PEP-8</h1>\n\n<p><a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP-8</a> is a style guide for Python. It defines certain conventions to improve conformity and readability amongst Python programs. Things like:</p>\n\n<ul>\n<li>All commas (such as in function parameters and arguments) must be followed by one space.</li>\n<li>Variables must be <code>snake_case</code>, which you follow except for <code>A</code> for area.</li>\n</ul>\n\n<h1>Consistent Return Types</h1>\n\n<p>What does <code>intersects(h,a1,a2,b1,b2)</code> return? A <code>bool</code>? If so, you can test it like:</p>\n\n<pre><code>if intersect(h, a1, a2, b1, b2):\n ...\nelse:\n ...\n</code></pre>\n\n<p>Except, it can also return the string <code>\"incorrect\"</code>, which is treated as <code>True</code> in all conditionals. So instead you must test the return value as <code>is True</code>, <code>is False</code> and <code>== \"incorrect\"</code>, and hope you don't accidentally write <code>== \"Incorrect\"</code> or <code>== \"invalid\"</code>.</p>\n\n<p>It is much better to raise an exception when incorrect arguments are passed to the function, such as <code>intersect()</code> raising a <code>TypeError</code> when not given a <code>Rectangle</code> argument.</p>\n\n<p>Also, you are doing the computation up to 3 times! This is inefficient; you should store the return value from <code>intersect(h, a1, a2, b1, b2)</code> in a local variable, and then test that value, instead of doing the intersection calculations repeatedly.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-04T02:19:57.803", "Id": "239903", "ParentId": "239887", "Score": "3" } } ]
{ "AcceptedAnswerId": "239903", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-03T19:23:12.207", "Id": "239887", "Score": "9", "Tags": [ "python", "beginner" ], "Title": "Calculate the intersection area of two rectangles" }
239887
<p>The other week I faced the struggle of scraping dynamically generated content. So I used the selenium library with combination of requests &amp; bs4, the thing is I am unsure of the quality of the implementation as I just learned how to use those tools. I want to have a general feedback on the way I used the libraries, the quality of my code and the logic behind it.</p> <p>Link to GitHub <a href="https://github.com/Viktor-stefanov/Web-Crawler/blob/master/README.md" rel="nofollow noreferrer">README</a>.</p> <pre><code>from selenium import webdriver from selenium.webdriver.chrome.options import Options from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as ec import selenium.common.exceptions import requests from bs4 import BeautifulSoup from time import sleep def scraper(): opts = Options() opts.add_argument('--headless') driver = webdriver.Chrome(r'C:\Users\leagu\chromedriver.exe', options=opts) pos = input('Enter your desired position: ') URL = 'https://remote.co/remote-jobs/search/?search_keywords='+pos.replace(' ', '+') driver.get(URL) # Scroll to the bottom of the page while True: try: WebDriverWait(driver, 5).until( ec.text_to_be_present_in_element( (By.CLASS_NAME, 'load_more_jobs'), 'Load more listings') ) loadMore = driver.find_element_by_class_name('load_more_jobs') loadMore.click() except: try: # can't locate element - click the close on the popup add WebDriverWait(driver, 5).until( ec.presence_of_element_located((By.CLASS_NAME, 'portstlucie-CloseButton')) ) addClose = driver.find_element_by_xpath('//*[@id="om-oqulaezshgjig4mgnmcn-optin"]/div/button') addClose.click() except: # Timeout / can't locate add - break break # Find all the job listings listings = driver.find_elements_by_class_name('job_listing') if len(listings) == 0: print(f'There are 0 jobs found by {pos} criteria. Please use different wording.') sleep(5) scraper() else: scrapeN = input(f"There are {len(listings)} number of jobs for the {pos} position. If u wish to view a portion of them enter the number of the jobs to view else write 'max': ") if scrapeN.lower() == 'max': scrapeN = len(listings) scrapeN = input(f"There are {len(listings)} number of jobs for the {pos} position. If u wish to view a portion of them enter the number of the jobs to view else write 'max': " ) print('\n') for i in range(int(scrapeN)): # Iterate trough all the job listings URL = listings[i].find_element_by_tag_name('a').get_attribute('href') html = requests.get(URL) soup = BeautifulSoup(html.content, 'html.parser') jobT = soup.find('h1', class_='font-weight-bold').text jobPD = soup.find('time').text link = soup.find('a', class_='application_button')['href'] print(f'Job - {jobT}. This job was {jobPD}.\nMore information about the job at {URL}. \nLink for application - {link}', end='\n\n') if __name__ == '__main__': scraper() </code></pre>
[]
[ { "body": "<p>What I like:</p>\n\n<ul>\n<li>usage of f-strings, but you are not using them everywhere eg: <code>URL = 'https://remote.co/remote-jobs/search/?search_keywords='+pos.replace(' ', '+')</code></li>\n<li>usage of <code>if __name__ == '__main__':</code></li>\n<li>code is fairly easy to grasp</li>\n<li>effort to provide a decent working script with a minimum of code (70 lines)</li>\n</ul>\n\n<p>What I like less:</p>\n\n<ul>\n<li>usage of exception handling: I would be more specific and not catch any type of exception, only handle those that are relevant to the operation being performed in the try/catch block (<code>selenium.common.exceptions</code>)</li>\n<li>lack of <strong>global exception handling</strong> in the rest of the code</li>\n<li>also think about <strong>logging</strong> full exception details to a file so you don't have to guess what has gone wrong</li>\n<li>I would also avoid nesting of try/catch blocks, try to separate each operation from each other (see below)</li>\n<li>mixing lower case and upper case in variable names: remember that variable names are case-sensitive in Python. <code>jobPD</code> and <code>jobpd</code> are two different variables that can get assigned different values so this could be a nasty source of bugs</li>\n<li><strong>variable names</strong> should be more descriptive and meaningful: <code>jobPD</code> does not give a clear hint about what it represents. More descriptive names would be <code>job_title</code>, <code>job_posted_time</code> etc</li>\n</ul>\n\n<hr>\n\n<p>Regarding the scraping process, make sure that the DOM elements your are expecting are really present: websites change their layout more or less often and you must spot changes that you could break your application. You can either check with Selenium or BS4 if you have already retrieved the HTML. But it seems logical to use Selenium. If you use BS, note the behavior of the different functions:</p>\n\n<p>From the BS4 <a href=\"https://www.crummy.com/software/BeautifulSoup/bs4/doc/#find\" rel=\"nofollow noreferrer\">doc</a> (emphasis is mine):</p>\n\n<blockquote>\n <p>If find_all() can’t find anything, it returns an <strong>empty list</strong>. If find()\n can’t find anything, it returns <strong>None</strong></p>\n</blockquote>\n\n<hr>\n\n<p>You have this block (the nested try/catch block):</p>\n\n<pre><code> try: # can't locate element - click the close on the popup add\n WebDriverWait(driver, 5).until(\n ec.presence_of_element_located((By.CLASS_NAME, 'portstlucie-CloseButton'))\n )\n addClose = driver.find_element_by_xpath('//*[@id=\"om-oqulaezshgjig4mgnmcn-optin\"]/div/button')\n addClose.click()\n except: # Timeout / can't locate add - break\n break\n</code></pre>\n\n<p>Is is better to anticipate and avoid exceptions, rather than handling them. So it seems to me that you should verify the existence of the element if possible, rather than trigger an exception.</p>\n\n<p>Instead, you could use the more generic <code>findElements</code> function. Note that <code>findElement</code> is different than <code>findElements</code>. The difference:</p>\n\n<blockquote>\n <p>findElements will return an empty list if no matching elements are\n found instead of an exception (<code>NoSuchElementException</code>)</p>\n</blockquote>\n\n<p>Reference: <a href=\"https://www.guru99.com/find-element-selenium.html\" rel=\"nofollow noreferrer\">Find Element and FindElements in Selenium WebDriver</a></p>\n\n<p>However, if you stick to the current approach, you should not blindly catch <strong>all exceptions</strong>: in this context the one relevant exception that may occur is: <code>NoSuchElementException</code>.</p>\n\n<hr>\n\n<p>There is one thing that is not okay: you are using the <code>requests</code> module in parallel to Selenium. That is unnecessary since you already have an instance of Selenium that you can use. To fetch the whole HTML just use:</p>\n\n<pre><code>html = driver.page_source\n</code></pre>\n\n<p>then feed it to BS</p>\n\n<p>Final thought: have you thought about logging the results to a file, a table or CSV perhaps ? The console buffer may be too small if you retrieve lots of results.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-03T21:48:51.857", "Id": "239894", "ParentId": "239889", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-03T19:46:45.183", "Id": "239889", "Score": "3", "Tags": [ "python", "web-scraping", "beautifulsoup" ], "Title": "Dynamic web scraper in Python" }
239889
<p>Typing in something like <code>Encoding.UTF8.GetString(...)</code> and <code>Encoding.UTF8.GetBytes(...)</code> everywhere in your code could be eliminated by a helper <code>UTF8</code> type:</p> <pre><code>public class UTF8_Should { [Test] public void Convert() { var text = "Hello World"; byte[] array = (UTF8)text; string copy = (UTF8)array; Assert.AreEqual(text, copy); } } </code></pre> <p>Where:</p> <pre><code>struct UTF8 { public static implicit operator UTF8(byte[] array) =&gt; new UTF8(Encoding.UTF8.GetString(array)); public static implicit operator string(UTF8 utf8) =&gt; utf8.Text; public static implicit operator UTF8(string text) =&gt; new UTF8(text); public static implicit operator byte[](UTF8 utf8) =&gt; Encoding.UTF8.GetBytes(utf8.Text); public UTF8(string text) =&gt; Text = text; string Text { get; } } </code></pre>
[]
[ { "body": "<p>You don't care about <code>null</code> references?</p>\n\n<hr>\n\n<p>IMO you create an object in order just to do something, that is more suitable for the concept of extensions:</p>\n\n<pre><code> public static class StringExtensions\n {\n public static byte[] ToUTF8Bytes(this string text)\n {\n return Encoding.UTF8.GetBytes(text);\n }\n\n public static string ToUTF8(this byte[] bytes)\n {\n return Encoding.UTF8.GetString(bytes);\n }\n }\n\n\n\n Assert.AreEqual(text, text.ToUTF8Bytes().ToUTF8());\n</code></pre>\n\n<p>The benefit of the extension methods is that you don't have to remember that you've created the <code>UTF8</code> struct somewhere, because it will show up in the intellisence.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-04T15:56:35.180", "Id": "470617", "Score": "0", "body": "1) C# 8 supports non nullable references. 2) We will lost a possibility to declare parameters of type UTF8 which makes sense to have in, for example, IoT domain - you might would like to know how the string is about to be serialized." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-04T05:26:41.167", "Id": "239905", "ParentId": "239891", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-03T21:16:58.557", "Id": "239891", "Score": "3", "Tags": [ "c#", "utf-8" ], "Title": "Save on typing while using UTF8 encoding" }
239891
<p>I'm new to React hooks and trying to learn to write custom hooks. Today I wrote a hook that I believe works as an effective debouncer of a setter function, to prevent excessive updates when data changes rapidly. I'm trying to keep this as simple as possible so as to be reusable throughout the app and by other developers on my team if they need it.</p> <p>I have tested this, and it appears to work as expected. It's currently being used to prevent excessive updates from a textfield. I'm unsure of any hidden performance drains doing this might cause, and I also don't know if I've gone about doing this in a way that makes sense (or if there might be less complicated ways of accomplishing what I want. </p> <pre><code>// Returns a callback function that wraps the passed setter in a debouncer mechanism // While the timer is off, the setter will be called immediately and trigger a new timer. // While the timer is on, the value to be set is captured and used at the end of the timer period. // Subsequent calls during the timer period will replace the captured value to be set, there is no queue. export function useDebouncedSetter(setter: (value: any) =&gt; void, timeout = 1000) { const timerActive = useRef(false); const valueCapture = useRef(null); const setterCapture = useRef(setter); // Capture the setter value to detect if a new one is passed return useCallback(async (value: any) =&gt; { if (timerActive.current === true) { valueCapture.current = value; } else { setter(value); valueCapture.current = value; timerActive.current = true; setterCapture.current = setter; setTimeout(() =&gt; { timerActive.current = false; // If the last captured value is the same as the value when the timeout was started, do nothing // If the last captured setter is different from the current setter, do nothing // This later case means a new setter was passed invalidating the old one. if (valueCapture.current !== value &amp;&amp; setterCapture.current === setter) { setter(valueCapture.current); } }, timeout); } return () =&gt; { // Cleanup, set the flag to false, get rid of the last value. timerActive.current = false; valueCapture.current = null; } }, [setter, timeout]); } </code></pre> <p>How best can I improve this? How can I tested its effectiveness compared to other methods, if any are feasible?</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-03T22:23:10.413", "Id": "239895", "Score": "2", "Tags": [ "javascript", "react.js" ], "Title": "Custom React debouncer hook" }
239895
<p>This question is a follow-up to <a href="https://codereview.stackexchange.com/q/239818/221235">this previous question of mine</a>. <sub>Assuming I understood correctly what is outlined in <a href="https://codereview.meta.stackexchange.com/q/1763/221235">this meta post</a>.</sub></p> <p>I wrote (and now, re-wrote) a function that takes as input a vector with two integers between 1 and 8 representing a position in a chessboard. This function should output a vector where each cell is a similar vector of integers, with the positions that a knight in the input position could reach.</p> <p>E.g. for the input 1 1, my function should output (2 3)(3 2).</p> <pre><code>KnightMovesRevised ← { ⍝ Monadic function, expects a vector with 2 integers, e.g. (1 1) ⍝ Given a chessboard position, find the legal knight moves. ⍝ Returns vector of 2-integer vectors, e.g. (2 3)(3 2) ⍝ aux train to check if position is inside chessboard isInsideBoard ← ∧/(1∘≤∧≤∘8) signs ← ¯1 1 ∘., ¯1 1 offsets ← (1 2)(2 1) moves ← , signs ∘.× offsets ⍝ list all the locations the knight could go to locations ← moves + ⊂⍵ ⍝ and keep the valid ones valid ← isInsideBoard¨ locations valid/locations } </code></pre> <h2>Changes</h2> <p>From the previous version to this one, I</p> <ul> <li>Reformatted code a bit with a suggested naming convention, by naming an auxiliary train and adding a couple more comments;</li> <li>Removed the train used to write <code>offsets</code>, which I had used just to give a go at tacit programming. This is such a small vector that I think it makes more sense to hardcode it;</li> <li>Rewrote <code>signs</code> by writing twice the <code>¯1 1</code> and removing <code>,</code>, <code>⍨</code>. This made it slightly easier to digest and not much more annoying to type;</li> </ul> <p>These changes were motivated by the two great reviews I got (<a href="https://codereview.stackexchange.com/a/239843/221235">here</a> and <a href="https://codereview.stackexchange.com/a/239842/221235">here</a>) and I was hoping I could get reviews on those changes, because I tried to adhere to their suggestions but I didn't necessarily agree with all of them.</p> <h2>Questions</h2> <p>(paired with the above)</p> <ul> <li>Are the extra comments ok or are they too much?</li> <li>Are <code>signs</code> and <code>offsets</code> defined in an acceptable way? I like the trade-off between hardcoding too much and using too many functions just to create a couple of constants.</li> <li>What is the standard spacing notation around <code>¨</code>? Should I write <code>f¨ arg</code>, <code>f ¨ arg</code>, <code>f ¨arg</code> or <code>f¨arg</code>?</li> </ul>
[]
[ { "body": "<p>On your previous version you commented, <em>\"This works and gives the expected result for a series of test cases.\"</em> But you never provided those test cases, right? I think the biggest thing missing here is test cases. Especially since test cases would quickly clarify the expected behavior of the function on weird inputs, and then you could maybe even get rid of some of the vague comments like </p>\n\n<pre><code>expects a vector with 2 integers, e.g. (1 1)\n</code></pre>\n\n<ul>\n<li><p>I infer that the two integers are supposed to be in the range 1..8 (not 0..7 as one might expect if one'd been doing too much programming lately and not enough chess). What happens when they're not in the range 1..8?</p></li>\n<li><p>What happens when there are three integers in the vector, or one, or none?</p></li>\n<li><p>What happens when there's something other than integers in the vector?</p></li>\n</ul>\n\n<p>I know you split out <code>isInsideBoard</code> into its own named function thanks to a comment on the earlier question; but if it's only ever used once, is that buying you anything? Honestly, as not-really-an-APLer-myself, <code>∧/(1∘≤∧≤∘8)</code> is pretty much the only part of that code that I <em>could</em> instantly understand!</p>\n\n<p>If I understand correctly, the output of <code>KnightMovesRevised</code> is a vector each of whose elements is suitable for feeding back into <code>KnightMovesRevised</code>; is that right? If so, that's good! You could even write a test case demonstrating how to find the number of cells that are exactly 2 knight-moves away from (1,1).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-04T08:39:38.587", "Id": "470595", "Score": "0", "body": "Thanks for your answer; I myself don't have access to the test cases, as those are in an automatic scoring system; as per the weird inputs, I don't have to handle those. I may assume my input is well-formed. As for the `isInsideBoard` question: I gain a bit of readability." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-04T08:40:56.690", "Id": "470596", "Score": "0", "body": "Also, no need to _\"infer that the two integers are supposed to be in the range 1..8\"_ as that is written out in my question :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-06T03:27:40.930", "Id": "470749", "Score": "1", "body": "@RGS Even if you don't have access to the \"official\" test cases, you can write your own test cases to make sure your function does what *you* expect (and be more confident about your solution)." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-04T05:18:18.300", "Id": "239904", "ParentId": "239897", "Score": "8" } }, { "body": "<h2>Answers to OP's questions</h2>\n\n<blockquote>\n <p>Are the extra comments ok or are they too much?</p>\n</blockquote>\n\n<p>Looks good to me overall, though some of them contain redundant information (that is already explained as variable names):</p>\n\n<pre><code> ⍝ aux train to check if position is inside chessboard\n isInsideBoard ← ∧/(1∘≤∧≤∘8)\n</code></pre>\n\n<p>Compare it with, e.g.</p>\n\n<pre><code> ⍝ checks if position is inside chessboard, i.e. 1 ≤ both coords ≤ 8\n isInsideBoard ← ∧/(1∘≤∧≤∘8)\n</code></pre>\n\n<p>Or you could omit it entirely since the code is talking the intent very well by itself, and just name the function better:</p>\n\n<pre><code> IsInsideChessBoard ← ∧/(1∘≤∧≤∘8)\n</code></pre>\n\n<p>which, by following the naming convention (function names capitalized), is made even more clear.</p>\n\n<blockquote>\n <p>Are <code>signs</code> and <code>offsets</code> defined in an acceptable way? I like the trade-off between hardcoding too much and using too many functions just to create a couple of constants.</p>\n</blockquote>\n\n<p>Also fine to me. I especially like how you decided to simply go with <code>(1 2)(2 1)</code> for <code>offsets</code>.</p>\n\n<p><strong>Nitpicking:</strong> Having an intermediate array of rank 3 or higher can make code hard to understand. In your current code, <code>signs</code> is a matrix and <code>offsets</code> is a vector, so <code>signs ∘.× offsets</code> yields a cube (rank 3 array). I'd suggest adding a <code>,</code> to <code>signs</code>:</p>\n\n<pre><code> signs ← , ¯1 1 ∘., ¯1 1\n</code></pre>\n\n<blockquote>\n <p>What is the standard spacing notation around <code>¨</code>? Should I write <code>f¨ arg</code>, <code>f ¨ arg</code>, <code>f ¨arg</code> or <code>f¨arg</code>?</p>\n</blockquote>\n\n<p>There's no such thing in APL, partially because some APL editors strip away all spaces not relevant to tokenization. But considering that <code>¨</code> binds to the function on its <em>left</em> to modify its behavior, I believe <code>f¨ arg</code> is the most reasonable spacing.</p>\n\n<hr>\n\n<h2>Writing test cases</h2>\n\n<p>Expanding on <a href=\"https://codereview.stackexchange.com/a/239904/182436\">Quuxplusone's suggestion</a>.</p>\n\n<p>Unfortunately, APL doesn't yet have a <em>standard</em> way to write unit tests. Yet we can find some examples of writing simple assertions. One striking example is from <a href=\"https://www.dyalog.com/blog/2015/07/20/\" rel=\"noreferrer\">Roger Hui's Dyalog blog post</a>, written back in 2015:</p>\n\n<pre><code>assert←{⍺←'assertion failure' ⋄ 0∊⍵:⍺ ⎕SIGNAL 8 ⋄ shy←0}\n\npcheck←{\n assert 2=⍴⍴⍵:\n assert (⍴⍵)≡(!⍺),⍺:\n …\n 1\n}\n</code></pre>\n\n<p>This cleverly uses dfns' guards to neatly list all the assertions to satisfy. If you run this in the interpreter and some assertion fails, a <code>⎕SIGNAL 8</code> is raised and execution is stopped at the line containing the failed assertion.</p>\n\n<p>In <a href=\"https://github.com/Bubbler-4/advent-of-apl\" rel=\"noreferrer\">Advent of APL</a>, I use slightly different formulation to allow testing for multiple functions implementing the same thing (modified to meet the naming convention you're using):</p>\n\n<pre><code>Assert←{\n 0=⍵:'Assertion Failure'⎕SIGNAL 11\n 0\n}\n_Test←{\n F←⍺⍺\n Assert 0≡F'(())':\n Assert 0≡F'()()':\n Assert 3≡F'(((':\n Assert 3≡F'(()(()(':\n Assert 3≡F'))(((((':\n 'All tests passed'\n}\n⍝ Actual testing\nSolution _Test ⍬\n</code></pre>\n\n<p>You can try writing tests for your function in this style. Since the order of the output shouldn't matter, you could write something like this:</p>\n\n<pre><code>Sort←(⍋⊃¨⊂)\nUnorderedEq←{(Sort ⍺)≡Sort ⍵}\nAssert←{⍺←'assertion failure' ⋄ 0∊⍵:⍺ ⎕SIGNAL 8 ⋄ shy←0}\nTest←{\n Assert (2 3)(3 2) UnorderedEq KnightMovesRevised 1 1:\n Assert (1 1)(1 5)(3 1)(3 5)(4 2)(4 4) UnorderedEq KnightMovesRevised 2 3:\n Assert 8 = ≢ KnightMovesRevised 3 5:\n 'All tests passed'\n}\n⎕←Test ⍬\n</code></pre>\n\n<p><a href=\"https://tio.run/##hZJPaxNBGMbv@ymeW3axtt02Qij0EEVK8M/B1g8wZt5sho47cWcbKCEXFUlSIl7EXDxYCvYg9NSLx/hN5ovEd2a3JGDBy@w7M8/ze//MioF@KM@FNtlq9SxXWb98YYZkX9FQWZJwn75gFAFu/h1Hakg5BLp9svaNEYXEwFhVKpNvoadyibJP0JQJjdOAwlvP2o4Y0LGd3CpJT7z5cTB7tpv83IlTN1m46RXHYV20EjZYleU2aLawvEmRsnaxXcd8b3o9S2WliFPsJfEeUm8MOWtjDWHjn293jrobrWwJoXVVtOkK34cNu7r4rjnTEplBadizlnh0leQB3Oy9m9/WSMEjOCUaBMhQaCVhcvIJq403/juH5fWafSfdWZ@Mo@jYFCV7Yze/cLMPy2tOmkSvc1NIKkg@fcd3o9iLuIrfiZv@qOPbcdS2loJ5xFf8aYhwwGT0hNJnBTXgLj5i101mbDhgFdznr8edo5ft52iFO9s/Z@fuODohG1BcZcUFz3w/ifd5@tioB/f8SPxoBxs@3ia8PPLm1C8cNf0jNtH8L4uTbrBaOISbXt4nZKwXNtr@mbl4i4HvXzZ4qtwl9@Jb4kn9Wq3@Ag\" rel=\"noreferrer\" title=\"APL (Dyalog Unicode) – Try It Online\">Try it online!</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-05T16:06:57.643", "Id": "470712", "Score": "0", "body": "Thanks for your insights; I really appreciate what you usually include in your \"nitpicks\" section. Please keep them coming." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-04T08:49:16.137", "Id": "239908", "ParentId": "239897", "Score": "6" } }, { "body": "<h3>Redundant parenthesis</h3>\n\n<p><code>isInsideBoard ← ∧/(1∘≤∧≤∘8)</code> was converted from inline explicit code. Back then, the train <code>1∘≤∧≤∘8</code> needed parenthesising. However, now that you've broken out this code to a separate tacit function, the <code>∧/</code> actually forms an atop (a 2-train) with the existing train, and since the original train was a fork (has 3 parts), it can simply be a 4th:</p>\n\n<pre><code>isInsideBoard ← ∧/ 1∘≤∧≤∘8\n</code></pre>\n\n<h3>Shorter name</h3>\n\n<p><a href=\"https://codereview.stackexchange.com/a/239908/221238\">Bubbler suggested</a> renaming this function to <code>IsInsideChessBoard</code>. However, I often find that a function that determines or computes something that can be given a good name (<code>valid</code> in this case) can often have a matching function name (that'd be <code>Valid</code>). I think it is obvious from context of the containing function that validity is defined to be \"inside the chess board\". Alternatively, you could name the function and variable <code>Inside</code> and <code>inside</code>.</p>\n\n<h3>Structure your code</h3>\n\n<p>I can't remember a thing, so I'd prefer defining the helper function as close as possible to where it is first used. I'd space it from the preceding code as two sections; the first finding all locations and the second determining their validity. Each section can appropriately begin with a comment on what it does. Maybe even exdent the comments to further emphasise it?</p>\n\n<h3>In summary</h3>\n\n<p>With these three changes:</p>\n\n<pre><code>KnightMovesRevised ← {\n ⍝ Monadic function, expects a vector with 2 integers, e.g. (1 1)\n ⍝ Given a chessboard position, find the legal knight moves.\n ⍝ Returns vector of 2-integer vectors, e.g. (2 3)(3 2)\n\n ⍝ list all the locations the knight could go to\n signs ← ¯1 1 ∘., ¯1 1\n offsets ← (1 2)(2 1)\n moves ← , signs ∘.× offsets\n locations ← moves + ⊂⍵\n\n ⍝ and keep the valid ones\n Inside ← ∧/ 1∘≤∧≤∘8\n inside ← Inside¨ locations\n inside/locations\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-05T16:05:40.510", "Id": "470711", "Score": "0", "body": "Thanks for your insights! I particularly appreciated the one where auxiliar trains and variables can have matching names." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-04T21:44:01.967", "Id": "239945", "ParentId": "239897", "Score": "5" } }, { "body": "<p>Having taken into account the feedback I got from the three answers that were posted, plus using my own brain, I think a good revision of the code in the question entails:</p>\n\n<ol>\n<li><p>ensuring <code>signs</code> is a vector instead of a matrix by using <code>,</code> right before assigning;</p></li>\n<li><p>moving the definition of the function <code>isInsideBoard</code> closer to where it is used;</p></li>\n<li><p>renaming the function <code>isInsideBoard</code> to <code>IsInside</code> and rename the corresponding variable to <code>inside</code>;</p></li>\n<li><p>removing unnecessary parentheses in the <code>IsInside</code> function but keeping a space to separate the final <code>∧/</code> from the fork <code>1∘≤∧≤∘8</code>;</p></li>\n</ol>\n\n<p>All in all, the code ends up looking like this:</p>\n\n<pre><code>KnightMovesRevised ← {\n ⍝ Monadic function, expects a vector with 2 integers, e.g. (1 1)\n ⍝ Given a chess board position, find the legal knight moves.\n ⍝ Returns vector of 2-integer vectors, e.g. (2 3)(3 2)\n\n ⍝ List all the locations the knight could go to\n signs ← , ¯1 1 ∘., ¯1 1\n offsets ← (1 2)(2 1)\n moves ← , signs ∘.× offsets\n locations ← moves + ⊂⍵\n\n ⍝ Find which ones are inside the chess board\n IsInside ← ∧/ 1∘≤∧≤∘8\n inside ← IsInside¨ locations\n inside/locations\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-05T16:05:04.520", "Id": "239994", "ParentId": "239897", "Score": "2" } } ]
{ "AcceptedAnswerId": "239994", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-03T22:51:36.397", "Id": "239897", "Score": "6", "Tags": [ "chess", "apl" ], "Title": "Finding legal knight moves in a chessboard in APL (follow-up)" }
239897
<p>I have an adjacency matrix "A" which I am using to represent a graph for a social network. Each node of the graph represents a person's name, and I am storing people's names in an 2-d array (the index of the person's name in the array is the same as the node's row index in the adjacency matrix). I wrote an algorithm to return the neighbors of node in the graph that are at most x nodes away from the node (the indices of the neighbor nodes will be stored in a binary tree and the root of the tree will be returned) but the algorithm is inefficient and takes 1-2 minutes or so to return the output, albeit a correct one. I would appreciate some advice on how to optimize this algorithm.</p> <pre><code>b_tree *get_friends(b_tree *root, int x, int y, char a_name[50] int dim) { /* root is root if b-tree containing pointers to the neighbors */ /* a_name is the name of a person in the graph (want to get the neighbors of this node)*/ /* x is maximum distance the neighbor can be from the node */ /* y is used to keep track of x and is always 0 and dim is the length/width of matrix */ /* M is a global variable for the matrix */ /* name_search searches the tree and returns NULL if the index is already in the tree (to prevent duplicates) */ /* friend_list is a global array containing the names of all the nodes in the graph (including a_name) */ /* retrieve_ind returns the index of the user name in the the friend_list array */ if (x == y - 1) return root; int r = retrieve_ind(a_name); for (int a = 0; a &lt; dim; a++) { if (M[r][a] &gt; 0) { if (name_search(root, a) == NULL) root = insert_in_tree(root, a); root = get_friends(root, x, y + 1, friend_list[a], dim); } } return root; } </code></pre>
[]
[ { "body": "<p>You can multiply the adjacency-matrix n times to get all paths of length n between any nodes. Therefore, if you multiply A^n * vector_with_only_your_startVertex, you can see in the resulting vector which nodes can be reached.<br>\nMake sure to also safe nodes that can be reached in less steps, because for example there may be cases where a node may be reached in 2, but not in 3 steps.<br>\nAlso make sure your multyplying right-associatively, as matrix-vector multiplication is way faster than matrix-matrix multiplication. </p>\n\n<p>I have no clue if this is faster though. Depends if you have a well-written matrix multiplication program that does not compute unnecessary zero-rows.</p>\n\n<p>You can also always use Dijkstra's algorithm for that, in this case every edge has weight 1.<br>\nAlso I don't understand why you are saving your result in a tree-structure. Unless you rely on an ordering of the elements of your result (which I guess you don't), you can use a hash-based set, which has access-time of O(1) and not O(log(N)) like trees do.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-04T00:49:17.243", "Id": "239900", "ParentId": "239898", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-03T23:52:15.710", "Id": "239898", "Score": "2", "Tags": [ "c", "graph" ], "Title": "How can I modify my graph traversal algorithm to increase efficiency?" }
239898
<p>I need to get values from a Map by Adapter position i get from a RecyclerView.</p> <p>As you can see each time i click on an Album Art i create a new array of album objects.</p> <pre><code>final Album[] albums = new Album[albumMap.size()]; for (Map.Entry&lt;Integer,Album&gt; e : albumMap.entrySet()){ albums[i++] = e.getValue(); } </code></pre> <p>Then i get the album like this: <code>String selectedAlbum = albums[position].getAlbum();</code></p> <p>But what if someone has like 10000+ albums on his device and each time an album is clicked a new array of album objects is created and i <strong>iterate</strong> through it just to get the album name.</p> <p>Would this have an impact on performance if there are alot of albums present?</p> <p><strong>TL;DR</strong> Is this code bad?</p> <p><strong>Full code</strong> </p> <pre><code>@Override public void onClickAlbum(int position, Map&lt;Integer,Album&gt; albumMap) { if (getActivity() != null) { int i = 0; final Album[] albums = new Album[albumMap.size()]; for (Map.Entry&lt;Integer,Album&gt; e : albumMap.entrySet()){ albums[i++] = e.getValue(); } String selectedAlbum = albums[position].getAlbum(); Main.getInstance().setSongsFilteredBy(SongsLibrary.getInstance().getSongsByAlbum(selectedAlbum)); Intent intent = new Intent(getActivity(), ListSongsActivity.class); intent.putExtra("title", selectedAlbum); startActivity(intent); Toast.makeText(getActivity(), "test: " + selectedAlbum, Toast.LENGTH_SHORT).show(); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-04T10:14:41.200", "Id": "470600", "Score": "0", "body": "Of course that will give you a performance hit, but maybe less than you expect. Check how hash maps affect performance. BTW 10000 is a mickey mouse number of records." } ]
[ { "body": "<p>I am not familiar with Android so I don't know how you get albumMap into the click event. Can you get selected Album (album object) into the event?</p>\n\n<p>If not.. </p>\n\n<p>I assume albumMap is a map between position to Album. </p>\n\n<p>If so I suggest the name postion2album. if not please update your post and clarify what this map is. </p>\n\n<p>So all you need to do is albumMap[position].getAlbum()</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-04T11:08:06.183", "Id": "239916", "ParentId": "239901", "Score": "1" } }, { "body": "<h3>Technical improvements</h3>\n\n<ul>\n<li>use <code>albumMap.values()</code> to get a <code>Collection&lt;Album&gt;</code> directly instantiated as list, which supports positional access <code>get(index)</code>. So no need for array and filling loop. See <em>Listing 1</em>.</li>\n<li>use some of Android's <em>ListView</em> interfaces which usually provide a convenient method on their underlying <em>data model</em> like <code>getItemAtPosition(position)</code>. See <em>Listing 2</em>.</li>\n</ul>\n\n<p><em>Listing 1</em>: <a href=\"https://stackoverflow.com/questions/1026723/how-to-convert-a-map-to-list-in-java\">Q: How to convert map to list</a></p>\n\n<pre class=\"lang-java prettyprint-override\"><code>List&lt;Album&gt; albums = new ArrayList&lt;Album&gt;(albumMap.values());\n</code></pre>\n\n<p><em>Listing 2</em>: <a href=\"https://www.vogella.com/tutorials/AndroidListView/article.html#listview_adapterlistener\" rel=\"nofollow noreferrer\">Vogella's Tutorial on Android's ListView</a></p>\n\n<pre class=\"lang-java prettyprint-override\"><code>ListView albumsView = (ListView) findViewById(R.id.listview);\n\n// fill albums data to model (adapter implementation)\nalbumsView.setAdapter(adapter)\n\nalbumsView.setOnItemClickListener(new OnItemClickListener() {\n\n @Override\n public void onItemClick(AdapterView&lt;?&gt; parent, final View view, int position, long id) {\n final Album album = (Album) parent.getItemAtPosition(position);\n // your implementation\n }\n}\n</code></pre>\n\n<h3>Design improvements</h3>\n\n<ul>\n<li><code>album.getAlbum()</code> gets the <em>title</em> of an album, so <strong>rename</strong> property|getter to <code>title</code>|<code>getTitle()</code></li>\n<li>keep the event-handler short and <strong>extract</strong> all <em>action/intend creation</em> into separate method</li>\n</ul>\n\n<h3>References</h3>\n\n<ul>\n<li><a href=\"https://stackoverflow.com/a/40584425\">Answer on using RecycleView with OnItemClickListener</a></li>\n<li><a href=\"https://www.androidhive.info/2016/01/android-working-with-recycler-view/\" rel=\"nofollow noreferrer\">Tutorial: Android working with RecyclerView</a></li>\n<li><a href=\"https://developer.android.com/guide/topics/ui/binding\" rel=\"nofollow noreferrer\">Android Official Guide on AdapterView</a></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-04T18:18:32.327", "Id": "239937", "ParentId": "239901", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-04T01:58:42.867", "Id": "239901", "Score": "2", "Tags": [ "java", "android" ], "Title": "Does iterating through a large data set in a Map each time i click impact the performance?" }
239901
<p>I have hierarchical table for my features with a parent-child relation. There was an unique constraint missing, why I have branches in the data, where multiple children relate to one parent. To add the constraint, I have to remove the branches.</p> <pre><code>CREATE TABLE feature_log ( feature_id UUID DEFAULT uuid_generate_v4(), revision_id UUID DEFAULT uuid_generate_v4(), parent_id UUID, project_id INTEGER, data_hash TEXT, created TIMESTAMP WITHOUT TIME ZONE DEFAULT NOW(), user_id INTEGER, CONSTRAINT pk_feature_log PRIMARY KEY (revision_id), CONSTRAINT fk_parent FOREIGN KEY (parent_id) REFERENCES feature_log (revision_id), CONSTRAINT fk_feature_data FOREIGN KEY (data_hash) REFERENCES feature_data (hash), CONSTRAINT fk_project FOREIGN KEY (project_id) REFERENCES project(id), CONSTRAINT uk_feature_log_parent_id UNIQUE (project_id, feature_id, parent_id) -- this was missing ); CREATE INDEX feature_log_feature_parent_id_idx on myedit.feature_log (feature_id, parent_id); CREATE INDEX feature_log_project_id_idx on myedit.feature_log (project_id); CREATE INDEX feature_log_parent_id_idx on myedit.feature_log (parent_id); CREATE INDEX feature_log_feature_id_idx on myedit.feature_log (feature_id); CREATE INDEX feature_log_data_hash_idx on myedit.feature_log (data_hash); CREATE INDEX feature_log_find_all_idx on myedit.feature_log (parent_id, revision_id, project_id); </code></pre> <p>If the data_hash is NULL, the feature is deleted. If a feature doesn't have a child, it's a node feature.</p> <p>To resolve this, I have the original table and two helper tables. One where the fixed data is in (feature_log_resolve), the other is to delete identified corrupt data and identified good data (feature_log_clipboard) - so there are only the features with problem left.</p> <p>The problem is in resolving the last part: When a feature has multiple living node children, take that one which has the most revisions. There are around 700k features left in this part and there are to many loops it takes for days. How can I make this script a little faster?</p> <pre><code>CREATE OR REPLACE FUNCTION get_node_features ( p_only_alive BOOLEAN ) RETURNS SETOF feature_log_clipboard AS <span class="math-container">$$ SELECT * FROM feature_log_clipboard AS child WHERE ( (p_only_alive AND child.data_hash IS NOT NULL) OR NOT p_only_alive ) AND NOT (EXISTS (SELECT parent.parent_id FROM feature_log_clipboard AS parent WHERE parent.parent_id = child.revision_id AND parent.project_id = child.project_id) ); $$</span> LANGUAGE 'sql'; CREATE OR REPLACE FUNCTION get_biggest_revision ( p_only_alive BOOLEAN ) RETURNS TABLE( generation INTEGER, feature_id UUID, revision_id UUID, parent_id UUID, project_id INTEGER, data_hash TEXT, created TIMESTAMP WITHOUT TIME ZONE, user_id INTEGER, row_number BIGINT ) AS $$ WITH RECURSIVE feature_hierarchy(generation, feature_id, revision_id, parent_id, project_id, data_hash, created, user_id) AS ( SELECT 0, firstGeneration.feature_id, firstGeneration.revision_id, firstGeneration.parent_id, firstGeneration.project_id, firstGeneration.data_hash, firstGeneration.created, firstGeneration.user_id FROM feature_log_clipboard AS firstGeneration WHERE parent_id NOT IN (SELECT revision_id FROM feature_log_clipboard) UNION ALL SELECT parent.generation + 1, nextGeneration.feature_id, nextGeneration.revision_id, nextGeneration.parent_id, nextGeneration.project_id, nextGeneration.data_hash, nextGeneration.created, nextGeneration.user_id FROM feature_log_clipboard AS nextGeneration INNER JOIN feature_hierarchy AS parent ON nextGeneration.parent_id = parent.revision_id ) SELECT *, ROW_NUMBER() OVER(PARTITION BY p.feature_id ORDER BY p.generation DESC, p.created DESC) AS row_number FROM feature_hierarchy AS p WHERE revision_id IN (SELECT revision_id FROM get_node_features(p_only_alive)) $$ LANGUAGE 'sql'; CREATE OR REPLACE FUNCTION get_biggest_revision_hierarchy ( p_only_alive BOOLEAN ) RETURNS TABLE( feature_id UUID, revision_id UUID, parent_id UUID, project_id INTEGER, data_hash TEXT, created TIMESTAMP WITHOUT TIME ZONE, user_id INTEGER, row_number BIGINT ) AS $$ WITH RECURSIVE biggest_revision_hierarchy AS ( SELECT lastGeneration.feature_id, lastGeneration.revision_id, lastGeneration.parent_id, lastGeneration.project_id, lastGeneration.data_hash, lastGeneration.created, lastGeneration.user_id, lastGeneration.row_number FROM get_biggest_revision(p_only_alive) AS lastGeneration WHERE lastGeneration.row_number = 1 UNION ALL SELECT nextGeneration.feature_id, nextGeneration.revision_id, nextGeneration.parent_id, nextGeneration.project_id, nextGeneration.data_hash, nextGeneration.created, nextGeneration.user_id, nextGeneration.user_id FROM feature_log_clipboard AS nextGeneration INNER JOIN biggest_revision_hierarchy AS child ON nextGeneration.revision_id = child.parent_id ) SELECT * FROM biggest_revision_hierarchy; $$ LANGUAGE 'sql'; CREATE OR REPLACE FUNCTION delete_moved_features () RETURNS VOID AS <span class="math-container">$$ DELETE FROM feature_log_clipboard WHERE feature_id IN ( SELECT DISTINCT feature_id FROM feature_log_resolve WHERE parent_id IS NOT NULL ) $$</span> LANGUAGE 'sql'; -- copy node features of latest generation with their complete hierarchy to resolve table INSERT INTO feature_log_resolve (feature_id, revision_id, parent_id, project_id, data_hash, created, user_id) SELECT feature_id, revision_id, parent_id, project_id, data_hash, created, user_id FROM get_biggest_revision_hierarchy(TRUE); -- delete whole feature_id of the node features of latest generation from clipboard SELECT * FROM delete_moved_features(); -- copy node features of latest generation with their complete hierarchy to resolve table INSERT INTO feature_log_resolve (feature_id, revision_id, parent_id, project_id, data_hash, created, user_id) SELECT feature_id, revision_id, parent_id, project_id, data_hash, created, user_id FROM get_biggest_revision_hierarchy(FALSE); -- delete whole feature_id of the node features of latest generation from clipboard SELECT * FROM delete_moved_features(); </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-04T06:25:59.443", "Id": "239906", "Score": "1", "Tags": [ "sql", "postgresql" ], "Title": "Moving hierarchy with the most revisions with more performance (SQL)" }
239906
<p>So my task was to make a lottery function, but the instructor only provides half the code when explaining and going through my resources i was unable to find proper examples on how to complete it aside from this part.</p> <pre><code>import random def user(startval, endval, numberpicked): somelist = [] while len(somelist) &lt; numberpicked: newnum = random.randint(startval,endval) if newnum not in print("Not valid, try again"): return i am aware i need to append at some point, but im racking my brain trying to understand how i know if i have created a function that generates a list of lottery numbers. they tried to provide help with the following but it did not make much sense. import random def myfuncname(parameter1, parameter2, parameter3): mytemplistname = [] do your loop to generate the number, see if it is in mytemplistname, append it if need be and you could do something like while len(mytemplistname) &lt; parameter3: #generate random number #if new number not in mytemplist name, then append it to the list #sort the list #return the list #here you would actually call your function and store the returned list in a variable etc </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-04T09:56:31.773", "Id": "470599", "Score": "2", "body": "Please learn how to separate plain text and code correctly in markdown before asking. Also we don't help you for not yet implemented code, you might want to check in our [help] what and what not you can ask here." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-05T04:43:23.917", "Id": "470667", "Score": "0", "body": "(I find it least error prone to fence code blocks in lines containing just `~~~`.)" } ]
[ { "body": "<pre><code>import random\n\ndef func(startval,endval,p):\n some_list=[]\n while(p!=0):\n x=random.randint(startval,endval)\n if x not in some_list:\n some_list.append(x)\n p=p-1\n some_list.sort()\n return some_list\n</code></pre>\n\n<p>Try and check if this works out for you!</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-05T17:05:17.190", "Id": "470719", "Score": "0", "body": "Welcome to code review, where we review working code to provide suggestions on how to improve the code. This answer is an alternate solution and is not a code review. A code review provides at least one insightful observation about the code. It would also be better to not provide answers for questions that have more than one down vote (less than -2) because these questions might be closed as off-topic as this one has. This question was off-topic because the code wasn't working." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-05T10:48:39.887", "Id": "239981", "ParentId": "239911", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-04T09:54:50.553", "Id": "239911", "Score": "-2", "Tags": [ "python", "random" ], "Title": "Python guessing game, lottery numbers but using def" }
239911
<p>Listening to messages from the udp socket, I would like to somehow determine where packets come from and scatter in sessions to get a more detailed report on the received data, I just did it forehead, looking for the current session and recording in its channel, I would like to know if more elegant methods? <a href="https://pastebin.com/2YL4V7DR" rel="nofollow noreferrer">full code</a></p> <pre><code> func serve(ctx context.Context, addr string, port int) &lt;-chan Message { type session struct { id int conn *net.UDPAddr len int64 countMessage int64 expiration int64 buffer chan []byte run func(wg *sync.WaitGroup, in chan []byte, ip string) } var ( out = make(chan Message, 64) done = make(chan error, 1) wg sync.WaitGroup localAddres = &amp;net.UDPAddr{IP: net.ParseIP(addr), Port: port} bufPool = sync.Pool{New: func() interface{} { return make([]byte, bufferSize) }} sessions []*session // TODO может будет не линейный поиск, пока посмотрим так getSession = func(addr *net.UDPAddr) (*session, bool) { for _, s := range sessions { if reflect.DeepEqual(s.conn, addr) { return s, true } } return nil, false } addSession = func(s *session) { fmt.Printf("Add new session %s:%d id: %d \n", s.conn.IP.String(), s.conn.Port, s.id) sessions = append(sessions, s) } removeSession = func(sess *session) { for i, s := range sessions { if s.id == sess.id { fmt.Printf("Remove session %s:%d id: %d \n", s.conn.IP.String(), s.conn.Port, s.id) sessions = sessions[:i+copy(sessions[i:], sessions[i+1:])] } } } gc = func() { for { &lt;-time.After(time.Duration(3 * time.Second)) for _, s := range sessions { if time.Now().UnixNano() &gt; s.expiration &amp;&amp; s.expiration &gt; 0 { removeSession(s) } } } } ) go gc() go func() { pc, err := net.ListenUDP("udp", localAddres) if err != nil { done &lt;- err } defer pc.Close() go func() { for { buff := bufPool.Get().([]byte) size, addr, err := pc.ReadFromUDP(buff[0:]) if err != nil { done &lt;- err return } switch s, ok := getSession(addr); ok { case true: s.buffer &lt;- buff[0:size] bufPool.Put(buff) s.expiration = time.Now().Add(time.Duration(time.Second * 10)).UnixNano() atomic.AddInt64(&amp;s.countMessage, 1) atomic.AddInt64(&amp;s.len, int64(size)) case false: s := &amp;session{ id: rand.Int(), conn: addr, expiration: time.Now().UnixNano(), buffer: make(chan []byte, 64), run: func(wg *sync.WaitGroup, in chan []byte, ip string) { for b := range in { var m Message err := json.Unmarshal(b, &amp;m) if err != nil { log.Fatal(err) continue } m.Device_ip = ip out &lt;- m } }, } wg.Add(1) s.buffer &lt;- buff[0:size] bufPool.Put(buff) atomic.AddInt64(&amp;s.countMessage, 1) atomic.AddInt64(&amp;s.len, int64(size)) go s.run(&amp;wg, s.buffer, s.conn.IP.String()) addSession(s) } } }() select { case &lt;-ctx.Done(): wg.Wait() log.Println("cancelled") err = ctx.Err() case err = &lt;-done: panic(err) } }() return out } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-07T12:28:12.453", "Id": "470939", "Score": "0", "body": "your code won't compile! your code is racy in gc(). given those errors are fixed i m fine with this code. elegance is not that important when the code is not functional. lets fix it at first." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-08T05:31:53.913", "Id": "471025", "Score": "0", "body": "@mh-cbon I edited the code and made a link to pastebin" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-08T08:10:57.587", "Id": "471030", "Score": "0", "body": "Дмитрий, please include the code into the question itself. Links can rot, questions have to be self-supporting." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-08T09:43:26.663", "Id": "471033", "Score": "1", "body": "@Mast insert full code for function." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-04T10:15:41.000", "Id": "239912", "Score": "2", "Tags": [ "algorithm", "go", "udp" ], "Title": "How to define UDP connection sessions more correctly?" }
239912
<p><strong>I implement BinaryTree (K extends Comparable, V) concept to binarySearchTree and I have written get and put method. As far as I check, there is no problem in my code. So now I wonder that are there any problem or weak point in my code? and m,</strong></p> <pre class="lang-java prettyprint-override"><code> public void put(K key, V value) { Node newNode = new Node(key, value, null, null); Node current = root; if (root == null) { root = newNode; return; } while (true) { int cmd = key.compareTo(current.key); if (cmd &gt; 0) { if (current.right == null) { current.right = newNode; break; } else { current = current.right; } } else if (cmd &lt; 0) { if (current.left == null) { current.left = newNode; break; } else { current = current.left; } } else { current.value = newNode.value; break; } } </code></pre> <pre class="lang-java prettyprint-override"><code> public V get(K key) { Node curr = root; if (curr == null) { throw new NoSuchElementException("There is no such a element"); } while (true) { int cmd = key.compareTo(curr.key); if (cmd &gt; 0) { curr = curr.right; } else if (cmd &lt; 0) { curr = curr.left; } else { return curr.value; } } } </code></pre> <p>And i check these and it worked</p> <pre class="lang-java prettyprint-override"><code> BinaryTree&lt;Integer,String&gt; binaryTree = new BinaryTree&lt;Integer, String&gt;(); binaryTree.put(8,"8"); binaryTree.put(4,"4"); binaryTree.put(5,"5"); binaryTree.put(1,"1"); binaryTree.put(2,"2"); binaryTree.put(3,"3"); binaryTree.put(65,"65"); binaryTree.put(4,"4 (2)"); System.out.println(binaryTree.get(8)); System.out.println(binaryTree.get(4)); System.out.println(binaryTree.get(65)); System.out.println(binaryTree.get(5)); </code></pre>
[]
[ { "body": "<p>Since the code is not compiling, it will be hard to do a proper code review.</p>\n\n<p>In my opinion, you should rename the variable <code>cmd</code> in both of the methods, since it can be confusing.</p>\n\n<h2><code>BinaryTree#put</code> method</h2>\n\n<ol>\n<li><p>In my opinion, it's a bad choice to use the range operators (&lt;, >, &lt;=, >=) with the <code>compareTo</code> method; since you always get one of those values (-1, 0 &amp; 1).</p></li>\n<li><p>I suggest that you check if the values are equals before checking if they are inferior / superior; this will alow you to merge some of the logic of the inferior / superior since they are pretty similar.</p></li>\n</ol>\n\n<pre class=\"lang-java prettyprint-override\"><code>\nif (cmd == 0) {\n current.value = newNode.value;\n break;\n}\n\nif (cmd == 1) {\n //[...]\n}\n<span class=\"math-container\">```</span>\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-05T17:56:48.307", "Id": "470726", "Score": "0", "body": "Thanks for your opinion @Doi9t) Besides cmd,everything seems, okay?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-05T19:48:35.533", "Id": "470735", "Score": "1", "body": "@samir-allahverdi yes, everything seems OK" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-06T18:40:21.550", "Id": "470839", "Score": "0", "body": "Thanks a lot) Thanks for your time ) @Doi9t" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-04T21:59:40.907", "Id": "239947", "ParentId": "239914", "Score": "1" } } ]
{ "AcceptedAnswerId": "239947", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-04T10:44:47.263", "Id": "239914", "Score": "3", "Tags": [ "java", "algorithm", "binary-search", "binary-tree" ], "Title": "I need to know that if everything okay in my BTS put and get method" }
239914
<p>I am interested in doing a 2D numerical integration. Right now I am using the <code>scipy.integrate.dblquad</code> but it is very slow. Please see the code below. My need is to evaluate this integral 100s of times with completely different parameters. Hence I want to make the processing as fast and efficient as possible. The code is:</p> <pre><code>import numpy as np from scipy import integrate from scipy.special import erf from scipy.special import j0 import time q = np.linspace(0.03, 1.0, 1000) start = time.time() def f(q, z, t): return t * 0.5 * (erf((t - z) / 3) - 1) * j0(q * t) * (1 / (np.sqrt(2 * np.pi) * 2)) * np.exp( -0.5 * ((z - 40) / 2) ** 2) y = np.empty([len(q)]) for n in range(len(q)): y[n] = integrate.dblquad(lambda t, z: f(q[n], z, t), 0, 50, lambda z: 10, lambda z: 60)[0] end = time.time() print(end - start) </code></pre> <p>Time taken is </p> <pre><code>212.96751403808594 </code></pre> <p>This is too much. Please suggest a better way to achieve what I want to do. I have read <code>quadpy</code> can do this job better and very faster but I have no idea how to implement the same. Also, I tried to use <code>cython-prange</code> but <code>scipy</code> doesn't work without <code>gil</code>. I tried <code>numba</code> but again it didn't work for <code>scipy</code>. Please help. </p>
[]
[ { "body": "<ul>\n<li><p>A very low hanging fruit, namely lifting the constant factor</p>\n\n<pre><code>0.5 * (1 / (np.sqrt(2 * np.pi) * 2))\n</code></pre>\n\n<p>out from the integral, reduces time by a quarter. On my system the original code took </p>\n\n<pre><code>294.532276869\n</code></pre>\n\n<p>while the fixed one took</p>\n\n<pre><code>224.198880911\n</code></pre></li>\n<li><p>Another fruit, a bit above, is to abandon <code>dblquad</code> whatsoever. It is just a wrong tool here.</p>\n\n<p>Notice that the only dependency on <code>q</code> is in <code>j0(q * t)</code>, and that it does not depend on <code>z</code> either. From the mathematical viewpoint it means that an integral of <code>erf(...) * exp(...)</code> over <code>dz</code> can be tabulated <em>once</em> as a function of <code>t</code>, say <code>F(t)</code> for the lack of better name, which then can be fed into the final integration as <code>t * j0(q*t) * F(t)</code>.</p>\n\n<p>Of course you'd need a lambda to interpolate tabulated values, and to manually take care of precision, and maybe do something else that <code>dblquad</code> does under the hood. Nevertheless, expect a thousand-fold speedup.</p></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-04T23:57:54.940", "Id": "239957", "ParentId": "239915", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-04T10:47:27.033", "Id": "239915", "Score": "1", "Tags": [ "python", "numpy", "numerical-methods", "scipy" ], "Title": "What would be the computationally faster way to implement this 2D numerical integration?" }
239915
<p>I wrote factorial and power functions with nasm but I don't know if it is the right to write assembly code. For example, by executing the functions I make some changes in the registers and I don't know if I have to revert them to their original value a the end with push and pop.</p> <p>To write the factorial function, I first wrote it in C, compiled it with gcc and disassembled it with gdb. It gave me inspiration to write the code. Then I followed the same way of coding for my power function.</p> <p>I use 64 bits registers.</p> <p>Here is my code :</p> <pre><code>; Factorial function n! ; Argument from rsi and return in rax factorial: push rbp mov rbp, rsp sub rsp, 0x10 ; Allocate 2 bytes on the stack mov DWORD [rbp-4], esi ; Put the parameter on the stack cmp DWORD [rbp-4], 1 ; if ==1 there is nothing to do jne factorial_rec mov eax, 1 ; return 1 jmp fin_factorial factorial_rec: mov eax, DWORD [rbp-4] ; Move the parameter in eax sub eax, 1 mov esi, eax call factorial ;Call factorial recursively with eax-1 imul eax, DWORD [rbp-4] ; multiply eax by the parameter fin_factorial: leave ret ; Power function x^n ; Argument from rsi and rdi return in rax ; rsi at the power rdi power: push rbp mov rbp, rsp cmp rdi, 0 ; if == 0 jne power_init mov eax, 1 ; Return 1 (x^0=1) jmp power_end power_init: sub rsp, 0x10 ; Allocate 2 bytes on the stack mov DWORD [rbp-4], esi ; Put the parameter on the stack mov eax, esi ; first power power_loop: dec edi cmp edi, 0 je power_end imul eax,DWORD[rbp-4] ; Multiply eax by the parameter until edi == 0 jmp power_loop power_end: leave ret </code></pre> <p>Thank you for your comments.</p>
[]
[ { "body": "<blockquote>\n<pre><code>sub rsp, 0x10 ; Allocate 2 bytes on the stack\n</code></pre>\n</blockquote>\n\n<p>The comment is not correct! <code>0x10</code> is an hexadecimal number equal to 16 in decimal.</p>\n\n<blockquote>\n<pre><code>cmp rdi, 0 ; if == 0\njne power_init\n</code></pre>\n</blockquote>\n\n<p>If you need to compare with zero, it's usually better to <code>test</code> the register to itself:</p>\n\n<pre><code>test rdi, rdi\njnz power_init\n</code></pre>\n\n<blockquote>\n<pre><code>dec edi\ncmp edi, 0\nje power_end\n</code></pre>\n</blockquote>\n\n<p>The <code>cmp edi, 0</code> instruction is redundant since the <code>dec edi</code> instruction already provides the necessary zero condition status.</p>\n\n<hr>\n\n<blockquote>\n <p>For example, by executing the functions I make some changes in the registers and I don't know if I have to revert them to their original value a the end with push and pop.</p>\n</blockquote>\n\n<p>If <em>you</em> write these functions and <em>your</em> program uses these functions, then it's up to you to decide if you deem it useful to preserve any or all of the registers. If someone else will be using your functions your comments should make it absolutely clear what registers get clobbered!</p>\n\n<hr>\n\n<p>The recursive factorial function can do without the prologue/epilogue code and is a bit complicated.</p>\n\n<pre><code>; IN (esi) OUT (eax) MOD ()\n; Calculate eax = esi!\nFactorial:\n mov eax, 1\n cmp esi, eax\n je .return ; esi was 1 -&gt; eax = 1\n push esi ; (1)\n dec esi\n call Factorial ; -&gt; EAX\n pop esi ; (1)\n imul eax, esi\n.return:\n ret\n</code></pre>\n\n<p>The power function can do without the prologue/epilogue code. There's no need to put <code>ESI</code> on the stack. If you want you could preserve the <code>EDI</code> register, but that's up to you to decide.</p>\n\n<pre><code>; IN (esi,edi) OUT (eax) MOD (edi)\n; Calculate eax = esi ^ edi\nPower:\n ; push edi\n mov eax, 1\n sub edi, eax\n jb .return ; edi was 0 -&gt; eax = esi^0 = 1\n mov eax, esi\n jz .return ; edi was 1 -&gt; eax = esi^1 = esi\n.more:\n imul eax, esi\n dec edi\n jnz .more\n.return\n ; pop edi\n ret\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-04T21:29:01.880", "Id": "470626", "Score": "0", "body": "Thank you for your very complete answer. I will work on the examples you gave me to understand them. I just have on more question. I knew that 0x10 was 16 but I thought it was 16 bits which is 2 bytes. But is it 16 bytes ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-04T21:40:25.500", "Id": "470629", "Score": "0", "body": "And do you know where I can find a good documentation of what flag each operand modify because I can't find a complete documentation." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-12T14:52:24.910", "Id": "471501", "Score": "1", "body": "@louisld The instruction `sub rsp, 0x10` operates on a register that holds a **memory address**. All memory addresses on x86 point to a single byte in memory. Therefore subtracting 16 will move the reference down 16 **bytes**." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-12T14:55:19.857", "Id": "471502", "Score": "1", "body": "@louisld For an easy to use documentation about the x86 instruction set, see https://www.felixcloutier.com/x86/. Each page has a section about which flags are affected by the instruction's operation." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-04T16:15:50.623", "Id": "239929", "ParentId": "239920", "Score": "1" } } ]
{ "AcceptedAnswerId": "239929", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-04T12:00:47.320", "Id": "239920", "Score": "2", "Tags": [ "assembly", "nasm" ], "Title": "Is this the rigth way to write power and factorial functions with nasm?" }
239920
<p>I need a class to generate json content from data retrieved from a database. This gave me an excuse to play at creating a json library. This is my first attempt so it could probably be improved in many ways.</p> <p>Features are:</p> <ol> <li>feed in json from stdin to populate internal structures.</li> <li>output json to stdout.</li> <li>insert into json.</li> <li>find by json key name.</li> </ol> <p>It uses std::variant which requires c++17 or better.</p> <p>Please review the code and give me some feedback.</p> <p>Is it heading in the right direction?</p> <p>Firstly the main header, json20.hpp:</p> <pre><code>#ifndef JSON20_HPP_ #define JSON20_HPP_ #include &lt;variant&gt; // type-safe union #include &lt;string&gt; #include &lt;vector&gt; #include &lt;map&gt; #include &lt;iostream&gt; #include "json_value.hpp" struct json_array { std::vector&lt;json_value&gt; array; }; struct json_object { std::map &lt; std::string, json_value&gt; object; json_value&amp; operator [](std::string key) { return object[key]; } }; struct json_null { }; std::ostream&amp; operator&lt;&lt; (std::ostream&amp; os, const json_value&amp; v); class json20 { public: /* start empty constructor */ json20() {} /* construct json object from input stream */ json20(std::istream&amp; istrm, std::string&amp; parse_status); /* parent node of json object */ json_value root; /* insert json object by manual construction. Returns true on successful insertion */ bool insert(const json_object&amp; object); /* find json value by key name */ bool find_by_key(const std::string&amp; key_name, json_value&amp; value); private: bool parse(std::istream&amp; istrm, std::string&amp; parse_status); json_value parse_json(std::istream&amp; istrm, json_value&amp; value, std::string&amp; parse_status); bool recursive_find_by_key(const std::string&amp; key_name, json_object&amp; next, json_value&amp; value); }; #endif // JSON20_HPP_ </code></pre> <p>json values header, json_value.hpp:</p> <pre><code>#ifndef JSON_VALUE_HPP_ #define JSON_VALUE_HPP_ #include "json20.hpp" #include &lt;variant&gt; #include &lt;string&gt; // fwd declare struct json_array; struct json_object; struct json_null; typedef std::variant&lt;double, bool, std::string, json_array, json_object, json_null&gt; json_value; #endif // JSON_VALUE_HPP_ </code></pre> <p>json implementation file, json20.cpp:</p> <pre><code>#include "json20.hpp" #include &lt;cstring&gt; static void eat_whitespace(std::istream&amp; istrm) { int ch; while (istrm) { ch = istrm.peek(); if (isspace(ch)) { istrm.get(); } else { break; } } } static char get_next_token(std::istream&amp; istrm) { eat_whitespace(istrm); char ch; if (istrm.get(ch)) return ch; else return (char)-1; // indicate failure; } std::ostream&amp; operator&lt;&lt; (std::ostream&amp; os, const json_value&amp; v) { switch (v.index()) { case 0: os &lt;&lt; std::get&lt;0&gt;(v); break; case 1: if (std::get&lt;1&gt;(v)) { os &lt;&lt; "true"; } else { os &lt;&lt; "false"; } break; case 2: os &lt;&lt; '"' &lt;&lt; std::get&lt;2&gt;(v) &lt;&lt; '"'; break; case 3: { os &lt;&lt; '['; bool first = true; json_array arr = std::get&lt;json_array&gt;(v); for (auto&amp; item : arr.array) { if (!first) { os &lt;&lt; ','; } os &lt;&lt; item; first = false; } os &lt;&lt; ']'; break; } case 4: { os &lt;&lt; '{'; bool first = true; json_object obj = std::get&lt;json_object&gt;(v); for (auto&amp; item : obj.object) { if (!first) { os &lt;&lt; ','; } os &lt;&lt; '"' &lt;&lt; item.first &lt;&lt; "\":"; os &lt;&lt; item.second; first = false; } os &lt;&lt; '}'; break; } case 5: os &lt;&lt; "null"; break; } return os; } static bool try_string(std::istream&amp; istrm, json_value&amp; value) { eat_whitespace(istrm); char ch = static_cast&lt;char&gt;(istrm.peek()); if (ch != '"') { return false; } // remove first " istrm.get(ch); std::string s; while (istrm.get(ch)) { if (ch == '"') { value.emplace&lt;2&gt;(s); return true; } else { // haven't worked out how to just append ch to end of string in value s += ch; } } return false; } static bool try_number(std::istream&amp; istrm, json_value&amp; value) { eat_whitespace(istrm); char ch = static_cast&lt;char&gt;(istrm.peek()); if (ch != '-' &amp;&amp; !isdigit(ch)) { return false; } while (istrm.get(ch)) { // start of a number if (ch == '-' || (ch &gt;= '0' &amp;&amp; ch &lt;= '9')) { char buf[10] = {}; buf[0] = ch; int i = 1; while (istrm.get(ch)) { if (ch &gt;= '0' &amp;&amp; ch &lt;= '9' || ch == '.') { buf[i] = ch; i++; } else { istrm.putback(ch); break; } } double number = strtod(buf, nullptr); value.emplace&lt;0&gt;(number); return true; break; } else { istrm.putback(ch); return false; } } return false; } static bool check_bytes(std::istream&amp; istrm, const char* expected) { const size_t length(strlen(expected)); for (size_t i = 0; i &lt; length; i++) { char ch; if(!istrm.get(ch)) { return false; } if (ch != expected[i]) { return false; } } return true; } static bool try_boolean(std::istream&amp; istrm, json_value&amp; value, std::string&amp; parse_status) { eat_whitespace(istrm); char ch = static_cast&lt;char&gt;(istrm.peek()); if (ch != 'f' &amp;&amp; ch != 't') { return false; } if (ch == 'f') { const char* expected = "false"; if (check_bytes(istrm, expected)) { value.emplace&lt;bool&gt;(false); return true; } else { parse_status += "parse of boolean false value failed|"; return false; } } if (ch == 't') { const char* expected = "true"; if (check_bytes(istrm, expected)) { value.emplace&lt;bool&gt;(true); return true; } else { parse_status += "parse of boolean true value failed|"; return false; } } return false; } static bool try_null(std::istream&amp; istrm, json_value&amp; value, std::string&amp; parse_status) { eat_whitespace(istrm); char ch = static_cast&lt;char&gt;(istrm.peek()); if (ch != 'n') { return false; } else { const char* expected = "null"; if (check_bytes(istrm, expected)) { value.emplace&lt;json_null&gt;(); return true; } else { parse_status += "parse of null value failed|"; return false; } } } json20::json20(std::istream&amp; istrm, std::string&amp; parse_status) { parse(istrm, parse_status); } json_value json20::parse_json(std::istream&amp; istrm, json_value&amp; value, std::string&amp; parse_status) { if (try_number(istrm, value)) { return value; } if (try_string(istrm, value)) { return value; } if (try_boolean(istrm, value, parse_status)) { return value; } if (try_null(istrm, value, parse_status)) { return value; } char ch = get_next_token(istrm); if (ch == '{') { json_object object; ch = get_next_token(istrm); if (ch == '}') { return object; } while (istrm) { if (ch == '"') { istrm.putback(ch); std::string key; json_value kvalue; if (!try_string(istrm, kvalue)) { parse_status += "unexpected json parsing failure of name|"; return kvalue; } else { key = std::get&lt;2&gt;(kvalue); } ch = get_next_token(istrm); if (ch != ':') { parse_status += "encountered an unexpected symbol: "; parse_status += ch; parse_status += ", : was expected|"; } object[key] = parse_json(istrm, value, parse_status); ch = get_next_token(istrm); if (ch == '}') { return object; } if (ch != ',') { parse_status += "encountered an unexpected symbol: "; parse_status += ch; parse_status += " , (comma) was expected|"; return object; } ch = get_next_token(istrm); } else { parse_status += "encountered an unexpected symbol: "; parse_status += ch; parse_status += " , \" (quote) was expected|"; return object; } } } if (ch == '[') { json_array jarray; ch = get_next_token(istrm); if (ch == ']') { return jarray; } istrm.putback(ch); while (istrm) { jarray.array.push_back(parse_json(istrm, value, parse_status)); ch = get_next_token(istrm); if (ch == ']') { break; } if (ch != ',') { parse_status += "comma expected, instead saw "; parse_status += ch; parse_status += '|'; } } return jarray; } // if get to here something is wrong parse_status += "parse failure, last character parsed: "; parse_status += ch; parse_status += '|'; return value; // no type/value will be set if return here } bool json20::parse(std::istream&amp; istrm, std::string&amp; parse_status) { root = parse_json(istrm, root, parse_status); return true; } bool json20::insert(const json_object&amp; object) { root = object; return true; } bool json20::recursive_find_by_key(const std::string&amp; key_name, json_object&amp; next, json_value&amp; value) { const auto found = next.object.find(key_name); if (found != next.object.end()) { value = found-&gt;second; return true; } // if not found, iterate over current values for child objects for (const auto element : next.object) { switch (element.second.index()) { case 3: // json_array { json_array jarray = std::get&lt;json_array&gt;(element.second); for (const auto list_item : jarray.array) { if (list_item.index() == 4) { json_object child = std::get&lt;json_object&gt;(list_item); return recursive_find_by_key(key_name, child, value); } } } break; case 4: // json_object json_object child = std::get&lt;json_object&gt;(element.second); return recursive_find_by_key(key_name, child, value); break; } } return false; } bool json20::find_by_key(const std::string&amp; key_name, json_value&amp; value) { // root should be a json_object, but check just in case switch (root.index()) { case 4: // json_object { json_object obj = std::get&lt;json_object&gt;(root); if (recursive_find_by_key(key_name, obj, value)) { return true; } break; } default: break; } return false; } </code></pre> <p>test code using gtest, test.cpp:</p> <pre><code>#include &lt;gtest/gtest.h&gt; #include "json20.hpp" #include &lt;string&gt; #include &lt;iostream&gt; #include &lt;sstream&gt; TEST(json20, GivenEmptyJsonStringThenConstructsCorrectly) { std::string myjson = "{}"; std::stringstream iostrm; iostrm &lt;&lt; myjson; // take in through stdin std::string error; json20 json(iostrm, error); // output to stdout std::ostringstream ostrm; ostrm &lt;&lt; json.root; std::string expected("{}"); EXPECT_EQ(ostrm.str(), expected); } TEST(json20, GivenJsonStringUsingNullThenConstructsCorrectly) { std::string myjson = "{ \"myvalue\": null }"; std::stringstream iostrm; iostrm &lt;&lt; myjson; // take in through stdin std::string error; json20 json(iostrm, error); // output to stdout std::ostringstream ostrm; ostrm &lt;&lt; json.root; std::string expected("{\"myvalue\":null}"); EXPECT_EQ(ostrm.str(), expected); } TEST(json20, GivenNumberJsonStringThenConstructsCorrectly) { std::string myjson = "{ \"mynumber\": 3.142 }"; std::stringstream iostrm; iostrm &lt;&lt; myjson; // take in through stdin std::string error; json20 json(iostrm, error); // output to stdout std::ostringstream ostrm; ostrm &lt;&lt; json.root; std::string expected("{\"mynumber\":3.142}"); EXPECT_EQ(ostrm.str(), expected); } TEST(json20, GivenStringJsonStringThenConstructsCorrectly) { std::string myjson = "{ \"mystring\": \"Angus\" }"; std::stringstream iostrm; iostrm &lt;&lt; myjson; std::string error; json20 json(iostrm, error); std::ostringstream ostrm; ostrm &lt;&lt; json.root; std::string expected("{\"mystring\":\"Angus\"}"); EXPECT_EQ(ostrm.str(), expected); } TEST(json20, GivenStringJsonArrayThenConstructsCorrectly) { std::string myjson = "{ \"myarray\": [\"Angus\", \"Lisa\"]}"; std::stringstream iostrm; iostrm &lt;&lt; myjson; std::string error; json20 json(iostrm, error); std::ostringstream ostrm; ostrm &lt;&lt; json.root; std::string expected("{\"myarray\":[\"Angus\",\"Lisa\"]}"); EXPECT_EQ(ostrm.str(), expected); } TEST(json20, GivenNumberJsonArrayThenConstructsCorrectly) { std::string myjson = "{ \"myarray\": [1, 2, 3]}"; std::stringstream iostrm; iostrm &lt;&lt; myjson; std::string error; json20 json(iostrm, error); std::ostringstream ostrm; ostrm &lt;&lt; json.root; std::string expected("{\"myarray\":[1,2,3]}"); EXPECT_EQ(ostrm.str(), expected); } TEST(json20, GivenAMixedJsonArrayThenConstructsCorrectly) { std::string myjson = "{ \"myarray\": [1, \"Angus\", 3]}"; std::stringstream iostrm; iostrm &lt;&lt; myjson; std::string error; json20 json(iostrm, error); std::ostringstream ostrm; ostrm &lt;&lt; json.root; std::string expected("{\"myarray\":[1,\"Angus\",3]}"); EXPECT_EQ(ostrm.str(), expected); } TEST(json20, GivenMultipleJsonArraysThenConstructsCorrectly) { std::string myjson = "{ \"myarray\": [\"Angus\", \"Lisa\", {\"objage\": [true, 4,false]}, \"Wookie\"]}"; std::stringstream iostrm; iostrm &lt;&lt; myjson; std::string error; json20 json(iostrm, error); std::ostringstream ostrm; ostrm &lt;&lt; json.root; std::string expected("{\"myarray\":[\"Angus\",\"Lisa\",{\"objage\":[true,4,false]},\"Wookie\"]}"); EXPECT_EQ(ostrm.str(), expected); } TEST(json20, GivenComplexJsonThenConstructsCorrectly) { std::string myjson = R"###({ "firstName": "John", "lastName" : "Smith", "isAlive" : true, "age" : 27, "address" : { "streetAddress": "21 2nd Street", "city" : "New York", "state" : "NY", "postalCode" : "10021-3100" }, "phoneNumbers": [ { "type": "home", "number" : "212 555-1234" }, { "type": "office", "number" : "646 555-4567" } ], "children": [], "spouse": null })###"; std::stringstream iostrm; iostrm &lt;&lt; myjson; std::string error; json20 json(iostrm, error); std::ostringstream ostrm; ostrm &lt;&lt; json.root; std::string expected("{\"myarray\":[\"Angus\",\"Lisa\",{\"objage\":[true,4,false]},\"Wookie\"]}"); } // failed cases TEST(json20, GivenEmptyStringThenConstructsCorrectly) { std::string myjson; // blank string std::stringstream iostrm; iostrm &lt;&lt; myjson; // take in through stdin std::string error; json20 json(iostrm, error); // output to stdout std::ostringstream ostrm; ostrm &lt;&lt; json.root; std::string expected(""); EXPECT_NE(error.size(), 0u); } TEST(json20, GivenInvalidUnquotedStringValueJsonStringThenNoCrash) { std::string myjson = "{ \"mynumber\":unquoted string }"; std::stringstream iostrm; iostrm &lt;&lt; myjson; // take in through stdin std::string error; json20 json(iostrm, error); // output to stdout std::ostringstream ostrm; ostrm &lt;&lt; json.root; EXPECT_NE(error.size(), 0u); } TEST(json20, GivenLargeButInvalidJsonStringThenNoCrash) { std::string myjson = R"###({ "firstName": "John", "lastName" -- "Smith", "isAlive" : true, "age" : 27, "address" : { "streetAddress": "21 2nd Street", "city" : "New York", "state" : "NY", "postalCode" : "10021-3100" }, "phoneNumbers": [ { "type": "home", "number" : "212 555-1234" }, { "type": "office", "number" : 646 555-4567 } ], "children": [[[], "spouse": nill })###"; std::stringstream iostrm; iostrm &lt;&lt; myjson; // take in through stdin std::string error; json20 json(iostrm, error); // output to stdout std::ostringstream ostrm; ostrm &lt;&lt; json.root; EXPECT_NE(error.size(), 0u); } TEST(json20, GivenAJsonObjectThenOutputAsExpected) { const std::string s = "my list"; double arrayofdoubles[] = {1.0, 2.0, 3.0}; json_array jarray; for (auto i : arrayofdoubles) { jarray.array.push_back(i); } json_object obj; obj.object[s] = jarray; json20 json; json.insert(obj); //// output to stdout std::ostringstream ostrm; ostrm &lt;&lt; json.root; std::string expected("{\"my list\":[1,2,3]}"); EXPECT_EQ(ostrm.str(), expected); } TEST(json20, GivenValidJsonThenFindValueByKey) { std::string myjson = R"###({ "firstName": "John", "lastName" : "Smith", "isAlive" : true, "age" : 27, "address" : { "streetAddress": "21 2nd Street", "city" : "New York", "state" : "NY", "postalCode" : "10021-3100" }, "phoneNumbers": [ { "type": "home", "number" : "212 555-1234" }, { "type": "office", "number" : "646 555-4567" } ], "children": [], "spouse": null })###"; std::stringstream iostrm; iostrm &lt;&lt; myjson; std::string error; json20 json(iostrm, error); json_value value; EXPECT_TRUE(json.find_by_key("firstName", value)); const json_value expected = std::string("John"); EXPECT_EQ(std::get&lt;std::string&gt;(value), std::get&lt;std::string&gt;(expected)); } TEST(json20, GivenJsonWithNestedKeyThenFindValueByKey) { std::string myjson = R"###({ "firstName": "John", "lastName" : "Smith", "nestedLevel1Key" : { "name": "childString1", "NestedLevel2Key": { "age": 10, "address1": "1 Woodlough Way" } } })###"; std::stringstream iostrm; iostrm &lt;&lt; myjson; std::string error; json20 json(iostrm, error); json_value value; EXPECT_TRUE(json.find_by_key("address1", value)); const json_value expected = std::string("1 Woodlough Way"); EXPECT_EQ(std::get&lt;std::string&gt;(value), std::get&lt;std::string&gt;(expected)); } TEST(json20, GivenJsonWithNestedKeyInArrayThenFindValueByKey) { std::string myjson = R"###({ "firstName": "John", "lastName" : "Smith", "nestedLevel1Key" : [ "age": 29, { "name": "childString1", "NestedLevel2Key": [{ "address1": "1 Woodlough Way" }] }] })###"; std::stringstream iostrm; iostrm &lt;&lt; myjson; std::string error; json20 json(iostrm, error); json_value value; EXPECT_TRUE(json.find_by_key("address1", value)); const json_value expected = std::string("1 Woodlough Way"); EXPECT_EQ(std::get&lt;std::string&gt;(value), std::get&lt;std::string&gt;(expected)); } TEST(json20, GivenInvalidbooleanJsonValueThenParseErrorShouldIndicateBooleanError) { std::string myjson = R"###({ "firstName": "John", "lastName" : "Smith", "isAlive" : truw, "age" : 27, "address" : { "streetAddress": "21 2nd Street", "city" : "New York", "state" : "NY", "postalCode" : "10021-3100" }, "phoneNumbers": [ { "type": "home", "number" : "212 555-1234" }, { "type": "office", "number" : "646 555-4567" } ], "children": [], "spouse": null })###"; std::stringstream iostrm; iostrm &lt;&lt; myjson; std::string error; json20 json(iostrm, error); size_t found_error = error.find("bool"); EXPECT_NE(error.size(), 0u); EXPECT_NE(found_error, std::string::npos); } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-04T23:29:55.047", "Id": "470647", "Score": "0", "body": "Have you see this? https://github.com/Loki-Astari/ThorsSerializer I had exactly the same issue. So I developed this. The idea was to convert to/from JSON without using an intermediate structure." } ]
[ { "body": "<h2>Code Review:</h2>\n\n<p>I don't like this as it gives you an extra level of indirection.</p>\n\n<pre><code>struct json_array {\n std::vector&lt;json_value&gt; array;\n};\n</code></pre>\n\n<p>You can simply use another name:</p>\n\n<p>using json_array = std::vector;</p>\n\n<p>This gives you a specific name for the array and removes the level of indirection.</p>\n\n<hr>\n\n<p>Sure this is resonable:</p>\n\n<pre><code>struct json_object {\n std::map &lt; std::string, json_value&gt; object;\n</code></pre>\n\n<p>Note That if you try and access an element that does not exist it will add it to the object (even if you are just reading).</p>\n\n<pre><code> json_value&amp; operator [](std::string key) {\n return object[key];\n</code></pre>\n\n<p>Maybe this is desirable, depends on your use case.</p>\n\n<pre><code> }\n};\n</code></pre>\n\n<p>But sometimes you pass by const reference. In this case you can not access members of the object because there is no const access to members. I would a way to accesses elements from a const reference.</p>\n\n<pre><code> json_value const&amp; operator [](std::string key) const {\n auto find object.find(key);\n if (find != object.end()) {\n return find-&gt;second;\n }\n // Not sure what you want to do if the object does not exist.\n }\n</code></pre>\n\n<hr>\n\n<p>Not really sure what <code>json20</code> is for?</p>\n\n<pre><code>class json20 {\n</code></pre>\n\n<p>You don't need it to hold the JSON that is what <code>json_value</code> is for. To me this is JSON parsers, which is fine but you don't need to store the json_value inside. Personally I would rename this to JsonParser and then use to read a stream that returns a json_value object.</p>\n\n<hr>\n\n<p>The stream operator <code>&gt;&gt;</code> drops all leading white space so you don't actually need to write your own.</p>\n\n<pre><code>static void eat_whitespace(std::istream&amp; istrm) {\n</code></pre>\n\n<hr>\n\n<p>Personally I would write eat_whitespace like this:</p>\n\n<pre><code>static void eat_whitespace(std::istream&amp; istrm) {\n\n int ch;\n while (istrm &gt;&gt; ch &amp;&amp; std::isspace(ch)) {\n // Do nothing\n }\n if (istrm) {\n istrm.unget(); // We read a non whitespace. Put it back.\n }\n}\n</code></pre>\n\n<hr>\n\n<p>So because <code>operator&gt;&gt;</code> drops leading white space we can re-write get_next_token</p>\n\n<pre><code>static char get_next_token(std::istream&amp; istrm) {\n char ch = static_cast&lt;char&gt;(-1);\n istrm &gt;&gt; ch; // Don't care if it does not work.\n // If the read fails then `ch` is unmodified.\n // So it will have a value of -1.\n return ch;\n}\n</code></pre>\n\n<hr>\n\n<p>OK. Streaming:</p>\n\n<pre><code>std::ostream&amp; operator&lt;&lt; (std::ostream&amp; os, const json_value&amp; v) {\n</code></pre>\n\n<p>For boolean values we can simplify it:</p>\n\n<pre><code> // IF you want to do it manually.\n os &lt;&lt; (std::get&lt;1&gt;(v)) ? \"true\" : \"false\";\n\n // Using the stream operator.\n os &lt;&lt; std::boolalpha &lt;&lt; std::get&lt;1&gt;(v);\n</code></pre>\n\n<hr>\n\n<p>For objects like the json_object, json_arry and json_null I would write their own stream operators.</p>\n\n<pre><code> std::ostream&amp; operator&lt;&lt; (std::ostream&amp; os, json_array const&amp; v);\n std::ostream&amp; operator&lt;&lt; (std::ostream&amp; os, json_object const&amp; v);\n std::ostream&amp; operator&lt;&lt; (std::ostream&amp; os, json_null const&amp; v);\n</code></pre>\n\n<p>Now you can simplify case 3/4/5:</p>\n\n<pre><code> case 3: os &lt;&lt; std::get&lt;3&gt;(v); break;\n case 4: os &lt;&lt; std::get&lt;4&gt;(v); break;\n case 5: os &lt;&lt; std::get&lt;5&gt;(v); break; \n</code></pre>\n\n<hr>\n\n<p>Lets simplify the <code>try_string()</code></p>\n\n<pre><code>static bool try_string(std::istream&amp; istrm, json_value&amp; value) {\n\n char ch;\n if (istrm &gt;&gt; ch) {\n if (ch != '\"') {\n istrm.unget();\n return false;\n }\n\n std::string s;\n std::getline(istrm, s, '\"');\n value.emplace&lt;2&gt;(s);\n return true;\n }\n return false;\n}\n</code></pre>\n\n<hr>\n\n<p>Pretty sure your try_number does not conform to the JSON standard.</p>\n\n<pre><code>static bool try_number(std::istream&amp; istrm, json_value&amp; value) {\n</code></pre>\n\n<p><a href=\"https://www.json.org/json-en.html\" rel=\"nofollow noreferrer\">https://www.json.org/json-en.html</a></p>\n\n<ul>\n<li>Your code will read a number with multiple <code>.</code> in it.</li>\n<li>Numbers can not start with 0 (unless it is just zero or zero with a fraction).</li>\n<li>You don't support E suffix to numbers.</li>\n</ul>\n\n<hr>\n\n<p>Personally I would convert the C++ code for parsing JSON into LEX code to parse JSON values. The code for lex is a lot simpler:</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-05T09:11:19.163", "Id": "470688", "Score": "0", "body": "Thanks for the feedback, brilliant. As for the using json_array = std::vector; I assume you mean using json_array = std::vector<json_value>; I am struggling with the circular dependency. I can forward declare struct json_array, but I don't think you can fwd declare using directive?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-05T10:57:54.200", "Id": "470697", "Score": "1", "body": "The greatest benefit I got from this was: Not really sure what json20 is for? Absolutely right and I need to switch on my big picture brain!" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-05T00:24:56.980", "Id": "239962", "ParentId": "239930", "Score": "2" } } ]
{ "AcceptedAnswerId": "239962", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-04T16:25:16.047", "Id": "239930", "Score": "4", "Tags": [ "c++", "parsing", "json" ], "Title": "How can this C++ json library be improved" }
239930
<p>Thanks for all the great feedback in <a href="https://codereview.stackexchange.com/questions/239248/sudoku-game-in-javascript">Part 1</a>. I implemented a lot of it. Here is version 2. I am looking for feedback on:</p> <ul> <li>Recursive solve algorithm. It's too slow. I used Chrome DevTools Performance Profiler to optimize slow functions and I sped it up a lot. But fundamentally I think the algorithm just sucks.</li> <li>The slowest, hardest test puzzle I've found so far is the following. It would be good to be able to solve this puzzle in a short amount of time (couple of seconds). 400030000000600800000000001000050090080000600070200000000102700503000040900000000</li> </ul> <h1>Fiddle</h1> <p><a href="https://jsfiddle.net/AdmiralAkbar2/80qgkps6/5/" rel="nofollow noreferrer">https://jsfiddle.net/AdmiralAkbar2/80qgkps6/5/</a></p> <h1>Screenshot</h1> <p><a href="https://i.stack.imgur.com/OwTvx.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/OwTvx.png" alt="Sudoku"></a></p> <h1>Performance</h1> <pre><code>// getSolutionCountRecursively speed, with limit set to 50,000 // 2508ms initially // 2186ms added/refactored getTrueKey // 1519ms added/refactored cloneBoard // 789ms added/refactored squareIsSolved // 298ms added/refactored setBoard // 170ms commented out RegEx in get_legal_move </code></pre> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>`use strict`; class SudokuBoard { constructor() { // Not pretty, but I declare the same thing 3 times for performance. Else I have to deep copy the blank_board array, which is expensive according to Chrome devtools performance profile. this.blank_board = [ [0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0] ]; this.board = [ [0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0] ]; this.original_board = [ [0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0] ]; } // This is only meant for use by getSolutionCountRecursively. Faster than set_board // Everything else should use set_board. set_board performs more data validation. setBoard(board) { this.board = board; } static cloneBoard(board) { let array = [ [0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0] ]; for ( let i = 0; i &lt; 9; i++ ) { for ( let j = 0; j &lt; 9; j++ ) { array[i][j] = board[i][j]; } } return array; // return Helper.deepCopyArray(board); } // returns if board changed or not set_board(board_string) { const old_board = SudokuBoard.cloneBoard(this.board); if ( ! board_string ) { return false; } if ( ! board_string.match(/^[0-9*_.]{81}$/m) ) { return false; } // TODO: foreach getBoardSquares for ( let row = 0; row &lt; 9; row++ ) { for ( let column = 0; column &lt; 9; column++ ) { let char = board_string.charAt(row*9+column); if ( char === `*` || char === `_` || char === `.` ) { char = 0; } this.board[row][column] = parseInt(char); } } if ( ! this.puzzleIsValid() ) { this.board = SudokuBoard.cloneBoard(old_board); return false; } this.set_original_board(this.board); return true; } get_board() { return this.board; } getString() { let str = ``; for ( let row = 0; row &lt; 9; row++ ) { for ( let col = 0; col &lt; 9; col++ ) { str += this.board[row][col]; } } return str; } // making this its own method to help with debugging set_original_board(obj) { this.original_board = SudokuBoard.cloneBoard(obj); } restart_puzzle() { this.board = SudokuBoard.cloneBoard(this.original_board); } make_move(row, col, value) { if ( value === `` ) { value = 0; } this.board[row][col] = value; } getSquaresOnBoard() { let squares = []; for ( let i = 0; i &lt; 9; i++ ) { for ( let j = 0; j &lt; 9; j++ ) { const value = this.board[i][j]; squares.push(new SudokuSquare(i, j, value)); } } return squares; } // TODO: consider splitting the below code into a SudokuSolver class // I haven't done it yet because I'd have to pass a board variable around. That's a lot of code re-writing. Not sure it's worth it. puzzleIsValid() { try { this.process_of_elimination(false, false); } catch { return false; } return true; } is_legal_move(row, col, value, checkForNonNumbers = true) { value = parseInt(value); // check for non numbers // Regex is very expensive. Only check this for user input. if ( checkForNonNumbers ) { if ( ! value.toString().match(/^[1-9]$/m) ) { return false; } } // check row // TODO: foreach getRowSquares for ( let i = 0; i &lt; 9; i++ ) { if ( value === this.board[row][i] ) { return false; } } // check column // TODO: foreach getColumnSquares for ( let i = 0; i &lt; 9; i++ ) { if ( value === this.board[i][col] ) { return false; } } // check 3x3 grid // TODO: foreach getBoxSquares const row_offset = Math.floor(row/3)*3; const col_offset = Math.floor(col/3)*3; for ( let i = 0 + row_offset; i &lt;= 2 + row_offset; i++ ) { for ( let j = 0 + col_offset; j &lt;= 2 + col_offset; j++ ) { if ( value === this.board[i][j] ) { return false; } } } return true; } // Possibilities {1:true, 2:true, 3:true, 4:true, 5:true, 6:true, 7:true, 8:true, 9:true} static squareIsSolved(possibilities) { let trueCount = 0; for ( let i = 1; i &lt;= 9; i++ ) { if ( possibilities[i] ) { trueCount++; } if ( trueCount &gt;= 2 ) { return false; } } if ( trueCount === 1 ) { return true; } return false; } // If 8 of 9 squares are filled in, fill in 9th square. process_of_elimination(hint_mode = false, modifyBoard = true) { let possibilities; let empty_col; let empty_row; // check row for ( let row = 0; row &lt; 9; row++ ) { // bool array [true, true, true] is faster than list [1, 2, 3] possibilities = {1:true, 2:true, 3:true, 4:true, 5:true, 6:true, 7:true, 8:true, 9:true}; empty_col = 0; for ( let col = 0; col &lt; 9; col++ ) { const value = this.board[row][col]; if ( value === 0 ) { empty_col = col; continue; } else if ( possibilities[value] ) { possibilities[value] = false; } else { this.throw_duplicate_number_error(); } } if ( SudokuBoard.squareIsSolved(possibilities) ) { if ( hint_mode ) { return new SudokuSquare(row, empty_col); } else if ( modifyBoard ) { this.board[row][empty_col] = SudokuBoard.getTrueKey(possibilities); } } } // check column for ( let col = 0; col &lt; 9; col++ ) { possibilities = {1:true, 2:true, 3:true, 4:true, 5:true, 6:true, 7:true, 8:true, 9:true}; empty_row = 0; for ( let row = 0; row &lt; 9; row++ ) { const value = this.board[row][col]; if ( value === 0 ) { empty_row = row; continue; } else if ( possibilities[value] ) { possibilities[value] = false; } else { this.throw_duplicate_number_error(); } } if ( SudokuBoard.squareIsSolved(possibilities) ) { if ( hint_mode ) { return new SudokuSquare(empty_row, col); } else if ( modifyBoard ) { this.board[empty_row][col] = SudokuBoard.getTrueKey(possibilities); } } } // check 3x3 grid for ( let row = 0; row &lt; 9; row+=3 ) { for ( let col = 0; col &lt; 9; col+=3 ) { possibilities = {1:true, 2:true, 3:true, 4:true, 5:true, 6:true, 7:true, 8:true, 9:true}; empty_row = 0; empty_col = 0; const row_offset = Math.floor(row/3)*3; const col_offset = Math.floor(col/3)*3; // iterate around 3x3 area for ( let i = 0 + row_offset; i &lt;= 2 + row_offset; i++ ) { for ( let j = 0 + col_offset; j &lt;= 2 + col_offset; j++ ) { const value = this.board[i][j]; if ( value === 0 ) { empty_row = i; empty_col = j; continue; } else if ( possibilities[value] ) { possibilities[value] = false; } else { this.throw_duplicate_number_error(); } } } if ( SudokuBoard.squareIsSolved(possibilities) ) { if ( hint_mode ) { return new SudokuSquare(empty_row, empty_col); } else if ( modifyBoard ) { this.board[empty_row][empty_col] = SudokuBoard.getTrueKey(possibilities); } } } } } puzzleIsSolved() { for ( let i = 0; i &lt; 9; i++ ) { for ( let j = 0; j &lt; 9; j++ ) { if ( this.board[i][j] === 0 ) { return false; } } } return true; } getNumberOfSolutions() { if ( ! this.puzzleIsValid() ) { this.throw_duplicate_number_error(); return 0; } if ( this.puzzleIsSolved() ) { window.alert('Puzzle is already solved'); return 1; } const initialRecursionTracker = new RecursionTracker(); const initialSudoku = new SudokuBoard(); initialSudoku.setBoard(SudokuBoard.cloneBoard(this.board)); initialRecursionTracker.setSudokuToCheck(initialSudoku); const finalRecursionTracker = this.getSolutionCountRecursively(initialRecursionTracker); const numberOfSolutions = finalRecursionTracker.getNumberOfSolutions(); const boardsChecked = finalRecursionTracker.getBoardsChecked(); console.log(`Number of solutions: ` + numberOfSolutions); console.log(`Boards checked: ` + boardsChecked); // window.alert(`Puzzle has ${numberOfSolutions} solutions`); return finalRecursionTracker; } getSolutionCountRecursively(recursionTracker) { // for first recursion, recursionTracker will be // this.numberOfSolutions = 0; // this.solutionSudokuList = null; // this.sudokuToCheck = Sudoku; // this.boardsChecked = 0; // No need to clone recursionTracker. Just keep using the same one. // Benchmark History (with limit set to 50,000) // 2508ms initially // 2186ms added/refactored getTrueKey // 1519ms added/refactored cloneBoard // 789ms added/refactored squareIsSolved // 298ms added/refactored setBoard // 170ms commented out RegEx in get_legal_move const RECURSION_LIMIT = 500000; if ( recursionTracker.getNumberOfSolutions() &gt; 500 ) { return recursionTracker; } if ( recursionTracker.getBoardsChecked() &gt; RECURSION_LIMIT ) { recursionTracker.markEarlyExit(); return recursionTracker; } const currentSudoku = recursionTracker.getSudokuToCheck(); // foreach boardsquare for ( let square of currentSudoku.getSquaresOnBoard() ) { // if square is empty if ( square.getValue() === 0 ) { // for each possible number 1-9 for ( let i = 1; i &lt;= 9; i++ ) { if ( recursionTracker.getBoardsChecked() &gt; RECURSION_LIMIT ) { recursionTracker.markEarlyExit(); return recursionTracker; } const row = square.getRow(); const col = square.getCol(); if ( currentSudoku.is_legal_move(row, col, i, false) ) { recursionTracker.incrementBoardsChecked(); // create new Sudoku let nextSudoku = new SudokuBoard(); const board = SudokuBoard.cloneBoard(currentSudoku.board); nextSudoku.setBoard(board); // make move nextSudoku.make_move(row, col, i); // console.log(currentSudoku.getString()); if ( nextSudoku.puzzleIsSolved() ) { recursionTracker.addSolution(nextSudoku); recursionTracker.incrementBoardsChecked(); // console.log(nextSudoku.getString()); } else { recursionTracker.setSudokuToCheck(nextSudoku); recursionTracker = this.getSolutionCountRecursively(recursionTracker); } } } } } return recursionTracker; } static getTrueKey(array) { let count = 0; let trueKey = false; for ( let key in array ) { if ( array[key] ) { trueKey = key; count++; } } if ( count === 1 ) { return parseInt(trueKey); } else { return false; } } } class RecursionTracker { constructor() { this.numberOfSolutions = 0; this.solutionList = []; this.sudokuToCheck = null; this.boardsChecked = 0; this.earlyExit = false; } getNumberOfSolutions() { return this.solutionList.length; } getInfoString() { let string = ``; string += this.getBoardsChecked() + ` Boards Checked\r\n`; string += this.solutionList.length + ` Solutions Found\r\n`; if ( this.earlyExit ) { string += `Recursion Limit Reached. Exited Early.\r\n`; } if ( this.solutionList.length !== 0 ) { string += `Solutions:\r\n`; } for ( let solutionString of this.solutionList ) { string += solutionString + `\r\n`; } return string; } getSudokuToCheck() { return this.sudokuToCheck; } getBoardsChecked() { return this.boardsChecked; } markEarlyExit() { this.earlyExit = true; } addSolution(sudoku) { const sudokuStringToCheck = sudoku.getString(); if ( ! this.solutionList.includes(sudokuStringToCheck) ) { this.solutionList.push(sudokuStringToCheck); } } setSudokuToCheck(sudoku) { this.sudokuToCheck = sudoku; } incrementBoardsChecked() { this.boardsChecked++; } } class SudokuSquare { constructor(row, col, value = 0) { this.row = parseInt(row); this.col = parseInt(col); this.value = parseInt(value); } getSquare() { return [this.row, this.col]; } getRow() { return this.row; } getCol() { return this.col; } getValue() { return this.value; } setValue(row, col) { this.row = row; this.col = col; } } class SudokuDOM { static display_board( sudoku_object, sudoku_squares, string_box, sudoku_wiki_link, change_square_color = true ) { const board = sudoku_object.get_board(); this.clear_board(sudoku_squares, change_square_color); for ( let row = 0; row &lt; 9; row++ ) { for ( let col = 0; col &lt; 9; col++ ) { const input = sudoku_squares[row][col]; input.classList.remove(`hint`); input.disabled = false; if ( board[row][col] != 0 ) { input.value = board[row][col]; if ( change_square_color ) { input.classList.add(`imported-square`); input.disabled = true; } } } } SudokuDOM.display_string(sudoku_object, string_box, sudoku_wiki_link); } static display_string(sudoku_object, string_box, sudoku_wiki_link) { string_box.value = sudoku_object.getString(); sudoku_wiki_link.href = `https://www.sudokuwiki.org/SudokuBoard.htm?bd=` + sudoku_object.getString(); } static clear_board(sudoku_squares, change_square_color = true) { for ( let row = 0; row &lt; 9; row++ ) { for ( let col = 0; col &lt; 9; col++ ) { sudoku_squares[row][col].value = ``; if ( change_square_color ) { sudoku_squares[row][col].classList.remove(`imported-square`); } } } } static highlight_illegal_move(obj){ obj.classList.add(`invalid`); setTimeout(function(){ obj.classList.remove(`invalid`); }, 2000); } } class Helper { static createArray(length) { var arr = new Array(length || 0), i = length; if (arguments.length &gt; 1) { var args = Array.prototype.slice.call(arguments, 1); while ( i-- ) { arr[length-1 - i] = Helper.createArray.apply(this, args); } } return arr; } } // Listeners window.addEventListener(`DOMContentLoaded`, (e) =&gt; { // DOM elements stored as constants const sudoku_table = document.getElementById(`sudoku`); const restart_button = document.getElementById(`restart`); const import_button = document.getElementById(`import`); const new_button = document.getElementById(`new`); const string_box = document.getElementById(`string-box`); const puzzle_picker = document.getElementById(`puzzle_picker`); const sudoku_wiki_link = document.getElementById(`sudoku-wiki-link`); const algorithm = document.getElementById(`algorithm`); const validate_button = document.getElementById(`validate`); const consoleBox = document.getElementById(`console`); const game1 = new SudokuBoard(); const sudoku_squares = Helper.createArray(9,9); const CUSTOM_PUZZLE_SELECTEDINDEX = 3; const DEFAULT_PUZZLE_SELECTEDINDEX = 4; // Store all the Sudoku square &lt;input type=`text`&gt; elements in variables for quick accessing for ( let row = 0; row &lt; 9; row++ ) { for ( let col = 0; col &lt; 9; col++ ) { sudoku_squares[row][col] = sudoku_table.rows[row].cells[col].children[0]; } } for ( let row = 0; row &lt; 9; row++ ) { for ( let col = 0; col &lt; 9; col++ ) { sudoku_squares[row][col].addEventListener(`input`, function(e) { e.target.classList.remove(`invalid`); e.target.classList.remove(`hint`); // Listen for illegal moves. If illegal, delete input and turn square red for 2 seconds. if ( ! game1.is_legal_move(row, col, e.target.value) &amp;&amp; e.target.value != `` ) { e.target.value = ``; SudokuDOM.highlight_illegal_move(e.target); } else { game1.make_move(row, col, e.target.value); } SudokuDOM.display_string(game1, string_box, sudoku_wiki_link); }); } } validate_button.addEventListener(`click`, function(e) { const t1 = performance.now(); const recursionTracker = game1.getNumberOfSolutions(); const t2 = performance.now(); // TODO: display recursionTracker stuff like # of solutions, strings of the solutions, etc. document.querySelector(`#algorithm span`).innerHTML = (t2 - t1).toFixed(1); algorithm.style.display = `block`; consoleBox.children[0].innerHTML = recursionTracker.getInfoString(); consoleBox.style.display = `block`; }); restart_button.addEventListener(`click`, function(e) { game1.restart_puzzle(); SudokuDOM.display_board(game1, sudoku_squares, string_box, sudoku_wiki_link); }); import_button.addEventListener(`click`, function(e) { const board = window.prompt(`Please enter a sequence of 81 numbers, with 0 representing an empty square.`); const board_changed = game1.set_board(board); if ( board_changed ) { puzzle_picker.selectedIndex = CUSTOM_PUZZLE_SELECTEDINDEX; SudokuDOM.display_board(game1, sudoku_squares, string_box, sudoku_wiki_link); } }); puzzle_picker.addEventListener(`change`, function(e) { if ( puzzle_picker.value === `import` ) { import_button.click(); } else if ( puzzle_picker.value === `random` ) { new_button.click(); } else { game1.set_board(puzzle_picker.value); SudokuDOM.display_board(game1, sudoku_squares, string_box, sudoku_wiki_link); } }); // Pick the default puzzle. Trigger the &lt;select&gt;.change listener so the puzzle gets loaded. // selectedIndex starts from 0 puzzle_picker.selectedIndex = DEFAULT_PUZZLE_SELECTEDINDEX; puzzle_picker.dispatchEvent(new Event(`change`)); });</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>body {font-family:sans-serif; background-color:#1E1E1E; color:white;} p {margin-block-start:0; margin-block-end:0.5em;} a {color:yellow;} a:hover {color:orange;} a:visited {color:yellow;} nav {float:left; width:250px; height:100vh; background-color:#383838; padding:1em;} article {float:left; padding:1em;} .done {background-color:limegreen;} .in-progress {background-color:yellow;} .todo {background-color:red;} #string-box {width:610px;} #algorithm {display:none;} #console {display:none;} #console textarea {width:85ch; height:8em;} .invalid {background-color:red;} .imported-square {background-color:lightgray;} .hint {background-color:limegreen;} #sudoku {border:4px solid black; border-collapse: collapse; margin-bottom:0.5em;} #sudoku tr {padding:0;} #sudoku td {padding:0; border:2px solid black; width:35px; height:35px;} #sudoku input {width:35px; height:35px; border:0; font-size:25pt; text-align:center; padding:0; color:black;} #sudoku .thick-right {border-right:4px solid black;} #sudoku .thick-bottom {border-bottom:4px solid black;}</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;!DOCTYPE html&gt; &lt;html lang="en-us"&gt; &lt;head&gt; &lt;title&gt;Sudoku&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;p&gt; &lt;button id="import" class="done"&gt;Import&lt;/button&gt; &lt;button id="restart" class="done"&gt;Restart&lt;/button&gt; &lt;button id="validate" class="todo"&gt;Solve Recursively&lt;/button&gt; &lt;/p&gt; &lt;p&gt; &lt;select id="puzzle_picker"&gt; &lt;option value="000000000000000000000000000000000000000000000000000000000000000000000000000000000"&gt;[Blank Board]&lt;/option&gt; &lt;option value="import"&gt;[Import Puzzle]&lt;/option&gt; &lt;option value="custom"&gt;[Custom Puzzle]&lt;/option&gt; &lt;option value="123056789467000000580000000600000000700000000800000000000000000200000000300000000"&gt;Testing - Process Of Elimination&lt;/option&gt; &lt;option value="080165427145372968726984135871296354964531782532847691213759846497628513658413279"&gt;Testing - Solution Count 1&lt;/option&gt; &lt;option value="380160407140370968726980135870296354964501782532847601213059846497028513658403279"&gt;Testing - Solution Count 2&lt;/option&gt; &lt;!-- from https://www.sudokuwiki.org/ --&gt; &lt;option value="080100007000070960026900130000290304960000082502047000013009840097020000600003070"&gt;Beginner&lt;/option&gt; &lt;option value="240070038000006070300040600008020700100000006007030400004080009860400000910060002"&gt;Intermediate - Last Number In Row, Col, &amp; Box&lt;/option&gt; &lt;option value="246070038000306074370040600008020700100000006007030400004080069860400007910060042"&gt;Intermediate - Naked Single&lt;/option&gt; &lt;/select&gt; &lt;/p&gt; &lt;table id="sudoku"&gt; &lt;tbody&gt; &lt;tr&gt; &lt;td&gt;&lt;input type="text" maxlength="1" /&gt;&lt;/td&gt; &lt;td&gt;&lt;input type="text" maxlength="1" /&gt;&lt;/td&gt; &lt;td class="thick-right"&gt;&lt;input type="text" maxlength="1" /&gt;&lt;/td&gt; &lt;td&gt;&lt;input type="text" maxlength="1" /&gt;&lt;/td&gt; &lt;td&gt;&lt;input type="text" maxlength="1" /&gt;&lt;/td&gt; &lt;td class="thick-right"&gt;&lt;input type="text" maxlength="1" /&gt;&lt;/td&gt; &lt;td&gt;&lt;input type="text" maxlength="1" /&gt;&lt;/td&gt; &lt;td&gt;&lt;input type="text" maxlength="1" /&gt;&lt;/td&gt; &lt;td&gt;&lt;input type="text" maxlength="1" /&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;&lt;input type="text" maxlength="1" /&gt;&lt;/td&gt; &lt;td&gt;&lt;input type="text" maxlength="1" /&gt;&lt;/td&gt; &lt;td class="thick-right"&gt;&lt;input type="text" maxlength="1" /&gt;&lt;/td&gt; &lt;td&gt;&lt;input type="text" maxlength="1" /&gt;&lt;/td&gt; &lt;td&gt;&lt;input type="text" maxlength="1" /&gt;&lt;/td&gt; &lt;td class="thick-right"&gt;&lt;input type="text" maxlength="1" /&gt;&lt;/td&gt; &lt;td&gt;&lt;input type="text" maxlength="1" /&gt;&lt;/td&gt; &lt;td&gt;&lt;input type="text" maxlength="1" /&gt;&lt;/td&gt; &lt;td&gt;&lt;input type="text" maxlength="1" /&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr class="thick-bottom"&gt; &lt;td&gt;&lt;input type="text" maxlength="1" /&gt;&lt;/td&gt; &lt;td&gt;&lt;input type="text" maxlength="1" /&gt;&lt;/td&gt; &lt;td class="thick-right"&gt;&lt;input type="text" maxlength="1" /&gt;&lt;/td&gt; &lt;td&gt;&lt;input type="text" maxlength="1" /&gt;&lt;/td&gt; &lt;td&gt;&lt;input type="text" maxlength="1" /&gt;&lt;/td&gt; &lt;td class="thick-right"&gt;&lt;input type="text" maxlength="1" /&gt;&lt;/td&gt; &lt;td&gt;&lt;input type="text" maxlength="1" /&gt;&lt;/td&gt; &lt;td&gt;&lt;input type="text" maxlength="1" /&gt;&lt;/td&gt; &lt;td&gt;&lt;input type="text" maxlength="1" /&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;&lt;input type="text" maxlength="1" /&gt;&lt;/td&gt; &lt;td&gt;&lt;input type="text" maxlength="1" /&gt;&lt;/td&gt; &lt;td class="thick-right"&gt;&lt;input type="text" maxlength="1" /&gt;&lt;/td&gt; &lt;td&gt;&lt;input type="text" maxlength="1" /&gt;&lt;/td&gt; &lt;td&gt;&lt;input type="text" maxlength="1" /&gt;&lt;/td&gt; &lt;td class="thick-right"&gt;&lt;input type="text" maxlength="1" /&gt;&lt;/td&gt; &lt;td&gt;&lt;input type="text" maxlength="1" /&gt;&lt;/td&gt; &lt;td&gt;&lt;input type="text" maxlength="1" /&gt;&lt;/td&gt; &lt;td&gt;&lt;input type="text" maxlength="1" /&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;&lt;input type="text" maxlength="1" /&gt;&lt;/td&gt; &lt;td&gt;&lt;input type="text" maxlength="1" /&gt;&lt;/td&gt; &lt;td class="thick-right"&gt;&lt;input type="text" maxlength="1" /&gt;&lt;/td&gt; &lt;td&gt;&lt;input type="text" maxlength="1" /&gt;&lt;/td&gt; &lt;td&gt;&lt;input type="text" maxlength="1" /&gt;&lt;/td&gt; &lt;td class="thick-right"&gt;&lt;input type="text" maxlength="1" /&gt;&lt;/td&gt; &lt;td&gt;&lt;input type="text" maxlength="1" /&gt;&lt;/td&gt; &lt;td&gt;&lt;input type="text" maxlength="1" /&gt;&lt;/td&gt; &lt;td&gt;&lt;input type="text" maxlength="1" /&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr class="thick-bottom"&gt; &lt;td&gt;&lt;input type="text" maxlength="1" /&gt;&lt;/td&gt; &lt;td&gt;&lt;input type="text" maxlength="1" /&gt;&lt;/td&gt; &lt;td class="thick-right"&gt;&lt;input type="text" maxlength="1" /&gt;&lt;/td&gt; &lt;td&gt;&lt;input type="text" maxlength="1" /&gt;&lt;/td&gt; &lt;td&gt;&lt;input type="text" maxlength="1" /&gt;&lt;/td&gt; &lt;td class="thick-right"&gt;&lt;input type="text" maxlength="1" /&gt;&lt;/td&gt; &lt;td&gt;&lt;input type="text" maxlength="1" /&gt;&lt;/td&gt; &lt;td&gt;&lt;input type="text" maxlength="1" /&gt;&lt;/td&gt; &lt;td&gt;&lt;input type="text" maxlength="1" /&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;&lt;input type="text" maxlength="1" /&gt;&lt;/td&gt; &lt;td&gt;&lt;input type="text" maxlength="1" /&gt;&lt;/td&gt; &lt;td class="thick-right"&gt;&lt;input type="text" maxlength="1" /&gt;&lt;/td&gt; &lt;td&gt;&lt;input type="text" maxlength="1" /&gt;&lt;/td&gt; &lt;td&gt;&lt;input type="text" maxlength="1" /&gt;&lt;/td&gt; &lt;td class="thick-right"&gt;&lt;input type="text" maxlength="1" /&gt;&lt;/td&gt; &lt;td&gt;&lt;input type="text" maxlength="1" /&gt;&lt;/td&gt; &lt;td&gt;&lt;input type="text" maxlength="1" /&gt;&lt;/td&gt; &lt;td&gt;&lt;input type="text" maxlength="1" /&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;&lt;input type="text" maxlength="1" /&gt;&lt;/td&gt; &lt;td&gt;&lt;input type="text" maxlength="1" /&gt;&lt;/td&gt; &lt;td class="thick-right"&gt;&lt;input type="text" maxlength="1" /&gt;&lt;/td&gt; &lt;td&gt;&lt;input type="text" maxlength="1" /&gt;&lt;/td&gt; &lt;td&gt;&lt;input type="text" maxlength="1" /&gt;&lt;/td&gt; &lt;td class="thick-right"&gt;&lt;input type="text" maxlength="1" /&gt;&lt;/td&gt; &lt;td&gt;&lt;input type="text" maxlength="1" /&gt;&lt;/td&gt; &lt;td&gt;&lt;input type="text" maxlength="1" /&gt;&lt;/td&gt; &lt;td&gt;&lt;input type="text" maxlength="1" /&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;&lt;input type="text" maxlength="1" /&gt;&lt;/td&gt; &lt;td&gt;&lt;input type="text" maxlength="1" /&gt;&lt;/td&gt; &lt;td class="thick-right"&gt;&lt;input type="text" maxlength="1" /&gt;&lt;/td&gt; &lt;td&gt;&lt;input type="text" maxlength="1" /&gt;&lt;/td&gt; &lt;td&gt;&lt;input type="text" maxlength="1" /&gt;&lt;/td&gt; &lt;td class="thick-right"&gt;&lt;input type="text" maxlength="1" /&gt;&lt;/td&gt; &lt;td&gt;&lt;input type="text" maxlength="1" /&gt;&lt;/td&gt; &lt;td&gt;&lt;input type="text" maxlength="1" /&gt;&lt;/td&gt; &lt;td&gt;&lt;input type="text" maxlength="1" /&gt;&lt;/td&gt; &lt;/tr&gt; &lt;/tbody&gt; &lt;/table&gt; &lt;p&gt; &lt;input id="string-box" type="text" /&gt; &lt;/p&gt; &lt;p&gt; Or solve this using &lt;a id="sudoku-wiki-link"&gt;Sudoku Wiki Solver&lt;/a&gt; &lt;/p&gt; &lt;p id="algorithm"&gt; &lt;span&gt;&lt;/span&gt; ms &lt;/p&gt; &lt;p id="console"&gt; &lt;textarea&gt;&lt;/textarea&gt; &lt;/p&gt;</code></pre> </div> </div> </p>
[]
[ { "body": "<h1>Performance</h1>\n<p>The main source of slowness is the <em>lack</em> of something: when an empty square is found and all possibilities for it have been tried, <code>getSolutionCountRecursively</code> does <em>not</em> return, it tries to fill in some other empty square. Filling in the board in a different order just results in the same boards being created but with a different &quot;move history&quot;, which doesn't matter, so equal solutions are created many times over.</p>\n<p>To make it explicit, the fix is this: (scroll to bottom)</p>\n<pre><code>getSolutionCountRecursively(recursionTracker) {\n \n const RECURSION_LIMIT = 500000;\n \n if ( recursionTracker.getNumberOfSolutions() &gt; 500 ) {\n return recursionTracker;\n }\n \n if ( recursionTracker.getBoardsChecked() &gt; RECURSION_LIMIT ) {\n recursionTracker.markEarlyExit();\n return recursionTracker;\n }\n \n const currentSudoku = recursionTracker.getSudokuToCheck();\n \n // foreach boardsquare\n for ( let square of currentSudoku.getSquaresOnBoard() ) {\n // if square is empty\n if ( square.getValue() === 0 ) {\n // for each possible number 1-9\n for ( let i = 1; i &lt;= 9; i++ ) {\n if ( recursionTracker.getBoardsChecked() &gt; RECURSION_LIMIT ) {\n recursionTracker.markEarlyExit();\n return recursionTracker;\n }\n \n const row = square.getRow();\n const col = square.getCol();\n \n if ( currentSudoku.is_legal_move(row, col, i, false) ) {\n recursionTracker.incrementBoardsChecked();\n \n // create new Sudoku\n let nextSudoku = new SudokuBoard();\n \n const board = SudokuBoard.cloneBoard(currentSudoku.board);\n nextSudoku.setBoard(board);\n \n // make move\n nextSudoku.make_move(row, col, i);\n \n if ( nextSudoku.puzzleIsSolved() ) {\n recursionTracker.addSolution(nextSudoku);\n recursionTracker.incrementBoardsChecked();\n } else {\n recursionTracker.setSudokuToCheck(nextSudoku);\n recursionTracker = this.getSolutionCountRecursively(recursionTracker);\n }\n }\n }\n return recursionTracker; // &lt;------------------- add this\n }\n }\n \n return recursionTracker;\n}\n</code></pre>\n<p>With this, &quot;Solution count 2&quot; runs in around 2ms on my PC. A handful of minor tricks could be used to get the time down a bit more, I could go into them if you want, but nothing else is even in the same league as adding that extra <code>return</code>.</p>\n<hr />\n<p>For fast solving of more dificult puzzles, also incorporate constraint propagation into the recursive solver. These are the techniques that you are already implementing in <code>process_of_elimination</code>, and more of them. Every time the recursive solver fills in a cell, iteratively apply these elimination steps to fill in as much of the board as possible.</p>\n<p>What tends to happen then is that for an easy puzzle, the solution is found without any search, the iterative solving steps just finish it. For harder puzzles, once the resursive solver has filled some cells, the puzzle either becomes an easy puzzle or a conflict is detected.</p>\n<p>Just filling in Naked Singles, the easiest propagation to implement, is already enough to solve your hard puzzle (300ms on my PC):</p>\n<pre><code>400030000\n000600800\n000000001\n000050090\n080000600\n070200000\n000102700\n503000040\n900000000 \n</code></pre>\n<p>But not yet enough for this other hard puzzle:</p>\n<pre><code>000000000\n000003085\n001020000\n000507000\n004000100\n090000000\n500000073\n002010000\n000040009\n</code></pre>\n<p>For example, filling in Naked Singles might look like this:</p>\n<pre><code> propagate() {\n // For each row, column and block,\n // get a mask indicating which values are already present in it.\n let rowmask = new Int32Array(9);\n let colmask = new Int32Array(9);\n let blockmask = new Int32Array(9);\n for ( let i = 0; i &lt; 9; i++ ) {\n for ( let j = 0; j &lt; 9; j++ ) {\n rowmask[i] |= 1 &lt;&lt; this.board[i][j];\n colmask[j] |= 1 &lt;&lt; this.board[i][j];\n blockmask[(i / 3 | 0) * 3 + (j / 3 | 0)] |= 1 &lt;&lt; this.board[i][j];\n }\n }\n \n // For each cell, get a mask indicating\n // which values are valid to fill in into it.\n // Excludes zero, as zero is the lack of a value.\n // For a filled cell, the only value it can have is the value it already has.\n // For empty cells, the possible values are values that\n // are not already used in the same row/column/block.\n let cellmask = new Int32Array(81);\n for ( let i = 0; i &lt; 9; i++ ) {\n for ( let j = 0; j &lt; 9; j++ ) {\n var mask = rowmask[i] | colmask[j] | blockmask[(i / 3 | 0) * 3 + (j / 3 | 0)];\n // invert to take the *unused* values\n // 0x3FE = 0011_1111_1110 (bits 1 to 9 are set)\n cellmask[i * 9 + j] = ~mask &amp; 0x3FE;\n if ( this.board[i][j] !== 0 )\n cellmask[i * 9 + j] = 1 &lt;&lt; this.board[i][j];\n }\n }\n\n var changed = false;\n do {\n changed = false;\n\n for ( let i = 0; i &lt; 9; i++ ) {\n for ( let j = 0; j &lt; 9; j++ ) {\n let mask = cellmask[i * 9 + j]; \n if ( this.board[i][j] !== 0 ) continue;\n if ( mask === 0 ) return false;\n if ( this.isSingleSetBit(mask) ) {\n let move = this.getSetBitPos(mask);\n this.make_move(i, j, move);\n changed = true;\n \n // we just filled a cell with the value 'move' \n // remove that as a possible value from cells in\n // the same row/column/block\n for ( let k = 0; k &lt; 9; k++ ) {\n cellmask[i * 9 + k] &amp;= ~(1 &lt;&lt; move);\n cellmask[k * 9 + j] &amp;= ~(1 &lt;&lt; move);\n }\n for ( let k = 0; k &lt; 3; k++ ) {\n for ( let l = 0; l &lt; 3; l++ ) {\n cellmask[((i / 3 | 0) * 3 + k) * 9 + (j / 3 | 0) * 3 + l] &amp;= ~(1 &lt;&lt; move);\n }\n }\n }\n }\n }\n\n } while (changed);\n return true;\n }\n\n isSingleSetBit(x) {\n return x !== 0 &amp;&amp; (x &amp; -x) === x;\n }\n\n getSetBitPos(x) {\n for ( let i = 0; i &lt; 31; i++ ) {\n if ((x &amp; (1 &lt;&lt; i)) !== 0)\n return i;\n }\n return -1;\n }\n</code></pre>\n<p>Though I'm not saying that this is the nicest way to do it.</p>\n<p>The intended usage is:</p>\n<pre><code>// make move\nnextSudoku.make_move(row, col, i);\n// propagate forced-moves\nif (!nextSudoku.propagate())\n continue;\n</code></pre>\n<p>Hidden Singles can be filtered with some more bitwise trickery. For example this filters them out of the rows only, turning them into Naked Singles which will immediately be detected:</p>\n<pre><code> for ( let i = 0; i &lt; 9; i++ ) {\n var m1 = 0;\n var m2 = 0;\n for ( let j = 0; j &lt; 9; j++ ) {\n var m = cellmask[i * 9 + j];\n m2 |= m1 &amp; m;\n m1 |= m;\n }\n for ( let j = 0; j &lt; 9; j++ ) {\n var m = cellmask[i * 9 + j];\n m &amp;= ~m2;\n if ( m !== 0 )\n cellmask[i * 9 + j] = m &amp; -m;\n }\n }\n</code></pre>\n<p>(<a href=\"https://jsfiddle.net/d0moLejz/\" rel=\"nofollow noreferrer\">fiddle</a>)</p>\n<p>A similar thing can be done for columns and blocks.</p>\n<p>Perhaps these bitwise tricks are not your style, of course the same effects can be accomplished with sets.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-06T05:20:33.257", "Id": "470754", "Score": "0", "body": "Thank you so much for the detailed comment. That did indeed fix it. If you're willing to share more tips for optimization, I'd love to hear them. The below puzzle is taking 46 seconds to solve on my computer so I think there is still room for improvement. Perhaps multi threading would be the best bang for the buck? 400030000000600800000000001000050090080000600070200000000102700503000040900000000" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-06T07:47:54.450", "Id": "470768", "Score": "0", "body": "Latest fiddle - https://jsfiddle.net/AdmiralAkbar2/z6rv70h4/232/" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-06T10:09:38.123", "Id": "470772", "Score": "0", "body": "@AdmiralThrawn ok I've added some more stuff" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-06T10:50:22.367", "Id": "470775", "Score": "0", "body": "Awesome. Thank you for taking the time to answer. I don't currently know bitwise stuff, but now is a good time to learn it. Especially since a lot of my projects are simple logic games with solvers that can benefit from bitwise shortcuts. I will research more and experiment with your code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-13T17:52:40.213", "Id": "471674", "Score": "0", "body": "Hey @harold. I started learning bitwise this weekend. Feels like I'm back in math class with all the binary conversions I'm doing on my pen and paper. I'm starting to wrap my head around the basics like & | ^ ~, but I'm having trouble with masks and how your code works. If you get some time, maybe you can edit your answer and add some comments to the code?" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-04T19:44:44.847", "Id": "239939", "ParentId": "239935", "Score": "3" } } ]
{ "AcceptedAnswerId": "239939", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-04T17:41:28.387", "Id": "239935", "Score": "2", "Tags": [ "javascript", "performance", "recursion", "sudoku" ], "Title": "JavaScript Sudoku Recursive Solver" }
239935
<p>Im at the point where I am designing my api security and I was going with a custom attribute I don't want to use third party systems as they cost money.</p> <p>I was going to use the client id and the secret id approach and I am asking is this a safe enough way to accomplish it I am interacting to my api through a database layer.</p> <p>So the first thing that will be called is this bit of code which goes out to find a match against the db and then called by the controller</p> <p>How should I encrypt the client id though in the database so that it cant be easy guessed.</p> <pre><code>public bool FindKeysByClientIdByApiKey(Guid apiKey, Guid clientId) { ApiKeys results = new ApiKeys(); using (var connection = new SqlConnection(constr)) { return connection.Query&lt;ApiKeys&gt;($"SELECT * FROM {schemaDefination}.[ApiKeys] where ClientId= @ClientId and ApiKey=@ApiKey and isActive=1 and isDeleted!=1", new { ApiKey = apiKey, ClientId = clientId }).Any(); } } </code></pre> <p>Controller Code</p> <pre><code>public class ApiKeysController : ControllerBase { DBContext db = new DBContext(); [HttpGet] public int Get(Guid ApiKey, Guid ClientdId) { if (!db.FindKeysByClientIdByApiKey(ApiKey, ClientdId)) { return StatusCodes.Status401Unauthorized; }else return StatusCodes.Status200OK; } } </code></pre> <p>To Enable or disable this at will I am creating a custom Attribute which will have the following.</p> <pre><code>public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next) { //before if(!context.HttpContext.Request.Headers.TryGetValue(ApiKeyHeaderName, out var potentialApiKey)) { context.Result = new UnauthorizedResult(); return; } // before if (!context.HttpContext.Request.Headers.TryGetValue(ClientId, out var potentialClientId)) { context.Result = new UnauthorizedResult(); return; } var getConfigurationResult = Do Stuff here await next(); //after } </code></pre> <p>This should mean that I can simply call attribute on my controller would this method work ok. I presume this method will also allow me to decorate my Gets and Puts to ensure that they are also authorize what should I be returning in ApiControllers get so I can make it more generic</p> <p>[Apikey]</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-05T21:22:45.040", "Id": "470739", "Score": "0", "body": "I see a view upvotes but no suggestions on how to best encrypt the client id" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-04T18:14:39.347", "Id": "239936", "Score": "2", "Tags": [ "c#", "sql-server", "asp.net-web-api" ], "Title": "API Layer ClientId and Security style" }
239936
<p>Python script that can download images and videos of the user, like Gallery with photos or videos. It saves the data in the folder.</p> <p>How it works:</p> <ul> <li><p>Log in in instragram using selenium and navigate to the profile</p></li> <li><p>Check the availability of Instagram profile if it's private or existing</p></li> <li><p>Gathering urls from images or videos</p></li> <li><p>Using threads and multiprocessing improve execution speed</p></li> </ul> <p>Usage:</p> <p><code>myfile.py -u example@hotmail.com -p mypassword -f myfile -n stackoverjoke</code></p> <p>My code:</p> <pre><code>import requests import time from selenium import webdriver from selenium.common.exceptions import NoSuchElementException from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By from multiprocessing.dummy import Pool import urllib.parse import re from concurrent.futures import ThreadPoolExecutor from typing import * import argparse chromedriver_path = None class PrivateException(Exception): pass class InstagramPV: def __init__(self, username: str, password: str, folder: Path, search_name: str): """ :param username: username :param password: password :param folder: folder name :param search_name: the name what will search """ self.username = username self.password = password self.folder = folder self.http_base = requests.Session() self._search_name = search_name self.links: List[str] = [] self.pictures: List[str] = [] self.videos: List[str] = [] self.url: str = 'https://www.instagram.com/{name}/' if chromedriver_path is not None: self.driver = webdriver.Chrome(chromedriver_path) else: self.driver = webdriver.Chrome() @property def name(self) -&gt; str: """ To avoid any errors, with regex find the url and taking the name &lt;search_name&gt; :return: The name of the Profile """ find_name = ''.join(re.findall(r'(?P&lt;url&gt;https?://[^\s]+)', self._search_name)) if find_name.startswith('https'): self._search_name = urllib.parse.urlparse(find_name).path.split('/')[1] return self._search_name def __enter__(self): return self def __exit__(self, exc_type, exc_val, exc_tb): self.http_base.close() self.driver.close() def check_availability(self) -&gt; None: """ Checking Status code, Taking number of posts, Privacy and followed by viewer Raise Error if the Profile is private and not following by viewer :return: None """ search = self.http_base.get(self.url.format(name=self.name), params={'__a': 1}) search.raise_for_status() load_and_check = search.json() privacy = load_and_check.get('graphql').get('user').get('is_private') followed_by_viewer = load_and_check.get('graphql').get('user').get('followed_by_viewer') if privacy and not followed_by_viewer: raise PrivateException('[!] Account is private') def control(self) -&gt; None: """ Create the folder name """ self.folder.mkdir(exist_ok=True) def login(self) -&gt; None: """Login To Instagram""" self.driver.get('https://www.instagram.com/accounts/login') WebDriverWait(self.driver, 10).until(EC.presence_of_element_located((By.TAG_NAME, 'form'))) self.driver.find_element_by_name('username').send_keys(self.username) self.driver.find_element_by_name('password').send_keys(self.password) submit = self.driver.find_element_by_tag_name('form') submit.submit() """Check For Invalid Credentials""" try: var_error = self.driver.find_element_by_class_name('eiCW-').text raise ValueError('[!] Invalid Credentials') except NoSuchElementException: pass try: """Close Notifications""" notifications = WebDriverWait(self.driver, 20).until( EC.presence_of_element_located((By.XPATH, '//button[text()="Not Now"]'))) notifications.click() except NoSuchElementException: pass """Taking cookies""" cookies = { cookie['name']: cookie['value'] for cookie in self.driver.get_cookies() } self.http_base.cookies.update(cookies) """Check for availability""" self.check_availability() self.driver.get(self.url.format(name=self.name)) self.submit_links() def get_href(self) -&gt; None: elements = self.driver.find_elements_by_xpath('//a[@href]') for elem in elements: urls = elem.get_attribute('href') if 'p' in urls.split('/'): self.links.append(urls) def located(self) -&gt; bool: """ Become a flag. While this element is displayed keep scrolling down until it isn't :return: True if the element is displayed, False if it isn't """ try: self.driver.find_element_by_xpath('//*[@class="_4emnV"]').is_displayed() return True except NoSuchElementException: return False def scroll_down(self) -&gt; Iterable[bool]: '''Taking hrefs while scrolling down''' while True: flag = self.located() self.get_href() time.sleep(1) self.driver.execute_script('window.scrollTo(0, document.body.scrollHeight);') time.sleep(1) yield flag def submit_links(self) -&gt; None: """Gathering Images and Videos and pass to function &lt;fetch_url&gt; Using ThreadPoolExecutor""" for displayed_more in self.scroll_down(): if not displayed_more: break self.control() seen = set() links = [link for link in self.links if not (link in seen or seen.add(link))] print('[!] Ready for video - images'.title()) print(f'[*] extracting {len(links)} posts , please wait...'.title()) new_links = [urllib.parse.urljoin(link, '?__a=1') for link in links] with ThreadPoolExecutor(max_workers=8) as executor: for link in new_links: executor.submit(self.fetch_url, link) def fetch_url(self, url: str) -&gt; None: """ This function extracts images and videos :param url: Taking the url :return None """ logging_page_id = self.http_base.get(url.split()[0]).json() try: """Taking Gallery Photos or Videos""" for log_pages in logging_page_id['graphql']['shortcode_media']['edge_sidecar_to_children']['edges']: video = log_pages['node']['is_video'] if video: video_url = log_pages['node']['video_url'] self.videos.append(video_url) else: image = log_pages['node']['display_url'] self.pictures.append(image) except KeyError: """Unique photo or Video""" image = logging_page_id['graphql']['shortcode_media']['display_url'] self.pictures.append(image) if logging_page_id['graphql']['shortcode_media']['is_video']: videos = logging_page_id['graphql']['shortcode_media']['video_url'] self.videos.append(videos) def download_video(self, new_videos: Tuple[int, str]) -&gt; None: """ Saving the video content :param new_videos: Tuple[int,str] :return: None """ number = new_videos[0] link = new_videos[1] with open(self.folder / f'Video{number}.mp4', 'wb') as f: content_of_video = self.http_base.get(link).content f.write(content_of_video) def images_download(self, new_pictures: Tuple[int, str]) -&gt; None: """ Saving the picture content :param new_pictures: Tuple[int, str] :return: None """ number = new_pictures[0] link = new_pictures[1] with open(self.folder / f'Image{number}.jpg', 'wb') as f: content_of_picture = self.http_base.get(link).content f.write(content_of_picture) def downloading_video_images(self) -&gt; None: """Using multiprocessing for Saving Images and Videos""" print('[*] ready for saving images and videos!'.title()) picture_data = enumerate(list(set(self.pictures))) video_data = enumerate(list(set(self.videos))) pool = Pool(8) pool.map(self.images_download, picture_data) pool.map(self.download_video, video_data) print('[+] Done') def main(): parser = argparse.ArgumentParser() parser.add_argument('-u', '--username', help='Username or your email of your account', action='store', required=True) parser.add_argument('-p', '--password', help='Password of your account', action='store', required=True) parser.add_argument('-f', '--filename', help='Filename for storing data', action='store', required=True) parser.add_argument('-n', '--name', help='Name to search or link', action='store', required=True) args = parser.parse_args() with InstagramPV(args.username, args.password, Path(args.filename), args.name) as pv: pv.login() pv.downloading_video_images() if __name__ == '__main__': main() </code></pre> <p>Changes: </p> <p>1) I changed the behaviour of the function <code>scroll_down</code> - avoiding "bugs" of instagram</p> <p>2) Added function <code>located</code></p> <p>My previous comparative review tag: <a href="https://codereview.stackexchange.com/questions/239539/instagram-scraping-using-selenium/239542?noredirect=1#comment470188_239542">Instagram Scraping Using Selenium</a></p>
[]
[ { "body": "<h2>Global constants</h2>\n\n<p><code>chromedriver_path</code> should be capitalized. Otherwise: I assume that you manually change it from <code>None</code> to some meaningful value for your local system. Try not to do this - instead, accept that path as an environmental variable, in a config file, or as a command-line parameter.</p>\n\n<h2>Captain Obvious</h2>\n\n<p>This:</p>\n\n<pre><code> \"\"\"\n :param username: username\n :param password: password\n :param folder: folder name\n \"\"\"\n</code></pre>\n\n<p>is worse than having no comments at all. Fill these out to be meaningful to someone who doesn't know what your script does.</p>\n\n<h2>Side-effects</h2>\n\n<p>One would expect, looking from the outside, that <code>name</code> simply returns a string - especially since it's marked as a property. It does that, but it also has the side-effect of setting <code>self._search_name</code> (sometimes). There are at least two problems with this:</p>\n\n<ul>\n<li>State modification in a getter - this is occasionally useful, i.e. in caching, but that isn't what you're doing here</li>\n<li>Conditional state modification whose reason isn't obvious - why is it that a member is only set if the URL is HTTPS?</li>\n</ul>\n\n<h2>Names</h2>\n\n<p><code>control</code> doesn't seem to control anything; it creates a directory.</p>\n\n<p><code>get_href</code> is not a getter; it doesn't return anything. It actually <em>would</em> make more sense as a static getter that <code>yield</code>s instead of appending to a list; then the caller could simply <code>self.links.extend(self.get_hrefs())</code>.</p>\n\n<h2><code>located</code></h2>\n\n<p>In its current implementation, this makes no sense:</p>\n\n<pre><code> try:\n self.driver.find_element_by_xpath('//*[@class=\"_4emnV\"]').is_displayed()\n return True\n except NoSuchElementException:\n return False\n</code></pre>\n\n<p>You call <code>is_displayed</code> and throw its return value away, relying on a no-such-element to determine the return value of your function. Why call <code>is_displayed</code> at all?</p>\n\n<h2><code>scroll_down</code></h2>\n\n<p>You have a <code>while True</code> that doesn't exit on its own. Instead, the outer caller waits for a boolean:</p>\n\n<pre><code> for displayed_more in self.scroll_down():\n if not displayed_more:\n break\n</code></pre>\n\n<p>This entire iterable structure all the way up to <code>get_href</code> needs to be re-thought. What you should have is a generator function that, instead of yielding a <code>bool</code> to terminate, yields a URL string, and breaks out of the loop (with a <code>break</code>, not a boolean flag) when the no-such-element condition is met.</p>\n\n<h2>Side-effects in comprehensions</h2>\n\n<p>This is particularly gruesome:</p>\n\n<pre><code> seen = set()\n links = [link for link in self.links if not (link in seen or seen.add(link))]\n</code></pre>\n\n<p>As soon as you have a term of a statement that's being relied upon to modify the iteration, you should expand this out into a normal loop. However, if I understand this correctly, you're simply removing dupes, in which case</p>\n\n<pre><code>links = set(self.links)\n</code></pre>\n\n<p>If you care deeply about order, then there are other ways to do this that still don't require a custom generator.</p>\n\n<h2>Generator materialization</h2>\n\n<p>This:</p>\n\n<pre><code> new_links = [urllib.parse.urljoin(link, '?__a=1') for link in links]\n</code></pre>\n\n<p>should use parentheses instead of brackets, because you don't need the list in memory - you only need the generator once through.</p>\n\n<h2>Variable reuse</h2>\n\n<p>Save</p>\n\n<pre><code>logging_page_id['graphql']['shortcode_media']\n</code></pre>\n\n<p>to a temporary variable for reuse.</p>\n\n<h2>Tuples in a function</h2>\n\n<p>This:</p>\n\n<pre><code>def download_video(self, new_videos: Tuple[int, str]) -&gt; None:\n</code></pre>\n\n<p>can simplify its tuple unpacking from</p>\n\n<pre><code> number = new_videos[0]\n link = new_videos[1]\n</code></pre>\n\n<p>to</p>\n\n<pre><code>number, link = new_videos\n</code></pre>\n\n<h2>Magic numbers</h2>\n\n<p>Pull the 8 from this</p>\n\n<pre><code>Pool(8)\n</code></pre>\n\n<p>into a constant, for instance</p>\n\n<pre><code>N_PROCESSES = 8\n# ...\nPool(N_PROCESSES)\n</code></pre>\n\n<p>This is more maintainable and self-documenting.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-05T02:57:15.020", "Id": "470657", "Score": "0", "body": "I have tons of questions but i will ask the most \"important\" for me. 1) In _name_ you mean to check everything even the URL isn't HTTPS? Should i get rid of property and try something else, because my intention is to extract the name and do the rest. 2) In scroll_down i fell into an infinity loop and i don't know if this is an instagram bug, but i saw \"wrong\" number of posts while the real posts were less. So, i wanted to find something to stop this, like the end of page. I think that the problem comes from scrolling down." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-05T02:57:32.083", "Id": "470658", "Score": "0", "body": "3) In _Side-effects in comprehensions_ i tried to remove the duplicate links without changing the order. Otherwise i could use _collections.OrderedDict_ 3) In _Tuples in a function_ in the previous post you mention _You're better off accepting number and link as separate arguments._ . 4) Magic numbers? I didn't undertand. Sorry for asking so many things but i am learning from your answers." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-05T03:10:57.070", "Id": "470659", "Score": "0", "body": "_check everything even the URL isn't HTTPS?_ - I don't know. What was your original motivation for only parsing HTTPS URLs?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-05T03:12:01.743", "Id": "470660", "Score": "0", "body": "_i wanted to find something to stop this_ - I think ending the loop on missing-element is fine, but you shouldn't be using booleans to do this." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-05T03:12:21.877", "Id": "470661", "Score": "0", "body": "_use collections.OrderedDict_ - Yes, this is what you should do." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-05T03:13:08.773", "Id": "470662", "Score": "0", "body": "_you mention You're better off accepting number and link as separate arguments_ - that's true, but I think it isn't possible given your usage of `map()`. You passing in a tuple is probably fine, but there's an easier way to unpack it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-05T03:14:29.040", "Id": "470663", "Score": "0", "body": "_Magic numbers? I didn't undertand_ - edited for context" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-06T15:53:29.457", "Id": "470818", "Score": "0", "body": "May i ask why using booleans to stop is wrong way? When and which cases we can use booleans. You mean is too much when i could use simplest way? Also, i want to understand the point of view of \"gruesome\" . Thanks!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-06T16:02:03.747", "Id": "470820", "Score": "1", "body": "_i want to understand the point of view of \"gruesome\"_ - Apologies; that's colloquial and not technical. Basically, it's not a good idea to mutate a set on the inside of a list comprehension." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-06T16:08:30.840", "Id": "470821", "Score": "1", "body": "_May i ask why using booleans to stop is wrong way?_ - Instead of looping, yielding a flag, outer looping and listening to the flag, yielding the data you actually care about, which is simpler." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-09T03:12:03.527", "Id": "471102", "Score": "1", "body": "I think i improved my code. By the way i learned so much these weeks that i didn't learned for months! Thanks to you! my [new question](https://codereview.stackexchange.com/questions/240182/download-pictures-or-videos-from-instagram-using-selenium)" } ], "meta_data": { "CommentCount": "11", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-05T01:34:58.233", "Id": "239964", "ParentId": "239940", "Score": "3" } } ]
{ "AcceptedAnswerId": "239964", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-04T20:15:50.013", "Id": "239940", "Score": "2", "Tags": [ "python", "python-3.x", "web-scraping", "selenium", "instagram" ], "Title": "Instagram Scraping Posts Using Selenium" }
239940
<p>I have a validator class, whose purpose is to validate input data. Initially I wrote the class like this:</p> <pre><code>export class ValidatorForInputs { constructor(inputData) { this._data = inputData; } validate() { let results = {}; let validateInputDataForMissingKeys = checkInputDataForMissingKeys(this._data); if (validateInputDataForMissingKeys) results = { ...results, ...validateInputDataForMissingKeys }; let validateInputDataForMissingValues = checkInputDataForMissingValues(this._data); if (validateInputDataForMissingValues) results = { ...results, validateInputDataForMissingValues }; let validateInputDataMaximums = checkInputDataMaximums(this._data); if (validateInputDataMaximums) results = { ...results, validateInputDataMaximums }; return results; } } </code></pre> <p>to be called like this:</p> <pre><code> let validatorForInputs = new ValidatorForInputs(inputData); let validationForInputsResult = validatorForInputs.validate(); // do something with validationForInputsResult </code></pre> <p>But then I wondered, is the constructor really necessary when the data could be passed directly to the <code>validate</code> method like so:</p> <pre><code> export class ValidatorForInputs { validate(data) { let results = {}; let validateInputDataForMissingKeys = checkInputDataForMissingKeys(data); if (validateInputDataForMissingKeys) results = { ...results, ...validateInputDataForMissingKeys }; let validateInputDataForMissingValues = checkInputDataForMissingValues(data); if (validateInputDataForMissingValues) results = { ...results, validateInputDataForMissingValues }; let validateInputDataMaximums = checkInputDataMaximums(data); if (validateInputDataMaximums) results = { ...results, validateInputDataMaximums }; return results; } } </code></pre> <p>and then called like this:</p> <pre><code> let validatorForInputs = new ValidatorForInputs(); let validationForInputsResult = validatorForInputs.validate(inputData); // do something with validationForInputsResult </code></pre> <p>or even called in a one liner like this:</p> <pre><code>let validationForInputsResult = ( new ValidatorForInputs() ).validate(inputData); // do something with validationForInputsResult </code></pre> <p>With a little bit of testing, I found that the code behaves the same way. I read the what the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/constructor" rel="nofollow noreferrer">docs</a> have to say about constructors but did not find any information that answers this question.</p> <p>So, in a case like this, should a constructor be used or not? If so, why? If not, why not?</p>
[]
[ { "body": "<p>I think a class provides benefits when you need <em>two</em> things:</p>\n\n<ul>\n<li>Persistent data associated with an instance, and</li>\n<li>Methods that do something with the data</li>\n</ul>\n\n<p>If you <em>only</em> need to consolidate data in a single data structure, an object or array is simpler and more suitable.</p>\n\n<p>If you <em>only</em> need to perform an operation on data and produce a result, and then have other not-very-related code work with the result, a plain function is simpler and more suitable.</p>\n\n<p>Your situation looks to fall into the second category. You have data that you want to validate, but <em>all</em> you want to do is validate, and the possible <code>class</code> wouldn't be doing anything else. If all you're doing with a <code>class</code> to set a property, then retrieve that property in a method to process data, and then you never use the instance again, there's not much point to having the class at all - it's just noise. I'd use a standalone function instead.</p>\n\n<pre><code>export const validate = (data) =&gt; {\n const results = {};\n\n const validateInputDataForMissingKeys = checkInputDataForMissingKeys(data);\n if (validateInputDataForMissingKeys) Object.assign(results, validateInputDataForMissingKeys);\n\n const validateInputDataForMissingValues = checkInputDataForMissingValues(data);\n if (validateInputDataForMissingValues) Object.assign(results, { validateInputDataForMissingValues });\n\n const validateInputDataMaximums = checkInputDataMaximums(data);\n if (validateInputDataMaximums) Object.assign(results, { validateInputDataMaximums });\n\n return results;\n};\n</code></pre>\n\n<p>Then call it like:</p>\n\n<pre><code>const validationForInputsResult = validate(inputData);\n</code></pre>\n\n<p>Also note that you should strongly prefer using <code>const</code> instead of <code>let</code>. <code>let</code> is a <em>warning</em> to other readers of your code (possibly including yourself, in the future) that you may be reassigning the variable in the future. If you're not going to reassign, better to use <code>const</code>, since it requires less cognitive overhead.</p>\n\n<p>The <code>checkInput</code> functions and <code>validateInput</code> variables look a bit repetitive. If possible, it would be nice to change things so that they return an empty object instead of a falsey value, and have <code>checkInputDataForMissingValues</code> and <code>checkInputDataMaximums</code> return objects with <code>validateInputDataForMissingValues</code> and <code>validateInputDataMaximums</code> properties. That way, you can spread them directly into the <code>results</code> object:</p>\n\n<pre><code>const validate = data =&gt; ({\n ...checkInputDataForMissingKeys(data),\n ...checkInputDataForMissingValues(data),\n ...checkInputDataMaximums(data),\n});\n</code></pre>\n\n<p>Having 3 separate <code>checkInputData</code> functions plus <code>validate</code> feels a <em>tiny</em> bit off to me. Organization-wise, you could consider putting them all into an object, together with <code>validate</code> if they're not used anywhere else, that way all the related functionality is in a single data structure:</p>\n\n<pre><code>export const validator = {\n checkInputDataForMissingKeys(data) {\n // ...\n },\n checkInputDataForMissingValues(data) {\n // ...\n },\n checkInputDataMaximums(data) {\n // ...\n },\n validate(data) {\n return {\n ...this.checkInputDataForMissingKeys(data),\n ...this.checkInputDataForMissingValues(data),\n ...this.checkInputDataMaximums(data),\n };\n }\n};\n</code></pre>\n\n<p>and</p>\n\n<pre><code>const validationForInputsResult = validator.validate(inputData);\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-05T00:59:35.143", "Id": "470652", "Score": "0", "body": "The 3 separate `checkInputData` functions were written outside of the exported entity (the class in the original code) so that they could not be accessed by anything other than the script where they were written. The intent was to make them \"private\" functions. What do you think of that approach?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-05T01:06:14.827", "Id": "470653", "Score": "1", "body": "Sure, that makes sense if all `checkInput` calls have to go through the main validator function." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-04T22:26:11.447", "Id": "239951", "ParentId": "239941", "Score": "1" } } ]
{ "AcceptedAnswerId": "239951", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-04T20:18:04.827", "Id": "239941", "Score": "1", "Tags": [ "javascript" ], "Title": "to use a constructor or not use a constructor" }
239941
<p>The following is working, no errors. But It's crazy long, not a real js developer here, so I did it the way I knew it. But I am pretty sure this can be resolved much, much easier and shorter.</p> <p>We have data in <code>countData</code> and I loop it. For each data within <code>countData</code> I need to do "<strong><em>last item minus previous to last item</em></strong>", basically I need to do <code>today - yesterday</code>.</p> <p>The way I'm doing is simple, I loop countData, get the <code>previous to last item</code> and <code>push it to its corresponding array</code>, do the same for the last item and then get the <code>sum of today</code> and <code>sum of yesterday</code> arrays and do <code>today - yesterday</code> for each item in order to know how many items we had between yesterday and today.</p> <p>Is there any better way both for performance and style not to mention code length? I just would like to learn better ways to do it and study them.</p> <p><strong>NOTE</strong>: </p> <p><code>countData</code> is an index within the main loop for ALL states <code>for (var a = 0; a &lt; filtererdData.length; ++a) {var countData = filtererdData[a];...</code> and I am running this bit on here within that for loop</p> <pre><code>var todayTeraphy = []; var todaySintomi = []; var todayHospital = []; var todayHome = []; var todayPositive = []; var todayRecovered = []; var todayDeaths = []; var todayConfirmed = []; var todaySwabs = []; var yesterdayTeraphy = []; var yesterdaySintomi = []; var yesterdayHospital = []; var yesterdayHome = []; var yesterdayPositive = []; var yesterdayRecovered = []; var yesterdayDeaths = []; var yesterdayConfirmed = []; var yesterdaySwabs = []; for (var i = 0; i &lt; countData.length; ++i) { if(i == countData.length-2) { yesterdayTeraphy.push(countData[i].terapia_intensiva); yesterdaySintomi.push(countData[i].ricoverati_con_sintomi); yesterdayHospital.push(countData[i].totale_ospedalizzati); yesterdayHome.push(countData[i].isolamento_domiciliare); yesterdayPositive.push(countData[i].totale_positivi); yesterdayRecovered.push(countData[i].dimessi_guariti); yesterdayDeaths.push(countData[i].deceduti); yesterdayConfirmed.push(countData[i].totale_casi); yesterdaySwabs.push(countData[i].tamponi); } if(i == countData.length-1) { todayTeraphy.push(countData[i].terapia_intensiva); todaySintomi.push(countData[i].ricoverati_con_sintomi); todayHospital.push(countData[i].totale_ospedalizzati); todayHome.push(countData[i].isolamento_domiciliare); todayPositive.push(countData[i].totale_positivi); todayRecovered.push(countData[i].dimessi_guariti); todayDeaths.push(countData[i].deceduti); todayConfirmed.push(countData[i].totale_casi); todaySwabs.push(countData[i].tamponi); } } var totTodayTeraphy = todayTeraphy.reduce((a, b) =&gt; a + b, 0); var totYesterdayTeraphy = yesterdayTeraphy.reduce((a, b) =&gt; a + b, 0); var totTeraphy = totTodayTeraphy - totYesterdayTeraphy; var totTodaySintomi = todaySintomi.reduce((a, b) =&gt; a + b, 0); var totYesterdaySintomi = yesterdaySintomi.reduce((a, b) =&gt; a + b, 0); var totSintomi = totTodaySintomi - totYesterdaySintomi; var totTodayHospital = todayHospital.reduce((a, b) =&gt; a + b, 0); var totYesterdayHospital = yesterdayHospital.reduce((a, b) =&gt; a + b, 0); var totHospital = totTodayHospital - totYesterdayHospital; var totTodayHome = todayHome.reduce((a, b) =&gt; a + b, 0); var totYesterdayHome = yesterdayHome.reduce((a, b) =&gt; a + b, 0); var totHome = totTodayHome - totYesterdayHome; var totTodayPositive = todayPositive.reduce((a, b) =&gt; a + b, 0); var totYesterdayPositive = yesterdayPositive.reduce((a, b) =&gt; a + b, 0); var totPositivi = totTodayPositive - totYesterdayPositive; var totTodayRecovered = todayRecovered.reduce((a, b) =&gt; a + b, 0); var totYesterdayRecovered = yesterdayRecovered.reduce((a, b) =&gt; a + b, 0); var totRecovered = totTodayRecovered - totYesterdayRecovered; var totTodayDeaths = todayDeaths.reduce((a, b) =&gt; a + b, 0); var totYesterdayDeaths = yesterdayDeaths.reduce((a, b) =&gt; a + b, 0); var totDeaths = totTodayDeaths - totYesterdayDeaths; var totTodayConfirmed = todayConfirmed.reduce((a, b) =&gt; a + b, 0); var totYesterdayConfirmed = yesterdayConfirmed.reduce((a, b) =&gt; a + b, 0); var totConfirmed = totTodayConfirmed - totYesterdayConfirmed; var totTodaySwabs = todaySwabs.reduce((a, b) =&gt; a + b, 0); var totYesterdaySwabs = yesterdaySwabs.reduce((a, b) =&gt; a + b, 0); var totSwabs = totTodaySwabs - totYesterdaySwabs; </code></pre>
[]
[ { "body": "<p>For each state, you're only interested in the final two items in its <code>countData</code> array, so there's no need for a nested loop. For example, rather than</p>\n\n<pre><code>for (var i = 0; i &lt; countData.length; ++i) {\n if (i == countData.length - 2) {\n yesterdayTeraphy.push(countData[i].terapia_intensiva);\n yesterdaySintomi.push(countData[i].ricoverati_con_sintomi);\n // ...\n</code></pre>\n\n<p>you can do</p>\n\n<pre><code>const len = countData.length;\nyesterdayTeraphy.push(countData[len - 2].terapia_intensiva);\nyesterdaySintomi.push(countData[len - 2].ricoverati_con_sintomi);\n// ...\n</code></pre>\n\n<p>But, to go further - since you're using the same sort of thing with the 2nd last day and the last day, you can abstract it into a function. Also, rather than having so many individual variable names, you can have an <em>object</em> containing the cumulative count for each day, eg:</p>\n\n<pre><code>// cumulativeToday:\n{\n hospital: 10,\n home: 20,\n // ...\n}\n</code></pre>\n\n<p>To construct such an object concisely, create a map of the italian words (the dataset properties) to the English property name you want:</p>\n\n<pre><code>const italianToEnglish = {\n totale_ospedalizzati: 'hospital',\n isolamento_domiciliare: 'home',\n // ...\n};\nconst cumulativeYesterday = {};\nconst cumulativeToday = {};\n\nconst addToCumulative = (cumulative, stateDay) =&gt; {\n for (const [italian, english] of Object.entries(italianToEnglish)) {\n cumulative[english] = (cumulative[english] || 0) + stateDay[italian];\n }\n};\nfor (const stateArr of filtererdData) {\n addToCumulative(cumulativeToday, stateArr.pop());\n addToCumulative(cumulativeYesterday, stateArr.pop());\n}\n</code></pre>\n\n<p>Then, to construct the differences (eg <code>var totSwabs = totTodaySwabs - totYesterdaySwabs;</code>), iterate over the <code>italianToEnglish</code> object and subtract the <code>cumulativeYesterday</code> value from the <code>cumulativeToday</code> value:</p>\n\n<pre><code>const diffs = {};\nfor (const [key, todayValue] of Object.entries(cumulativeToday)) {\n diffs[key] = todayValue - cumulativeYesterday[key];\n}\n</code></pre>\n\n<p>With this approach, for example, data previously in <code>totTodaySwabs</code> will be in <code>cumulativeToday.swabs</code>, <code>totYesterdaySwabs</code> will be in <code>cumulativeYesterday.swabs</code>, <code>totSwabs</code> will be in <code>diffs.swabs</code>.</p>\n\n<p>Note that it's a <em>lot</em> nicer-looking to iterate over arrays using <code>for..of</code> than ordinary <code>for</code> loops, which require manual iteration and can get pretty ugly.</p>\n\n<p>Also note that <code>const</code> should be strongly preferred over <code>var</code> in modern Javascript - <code>const</code> variables tell the reader of the code that the variable is not going to be reassigned, which makes things easier to read (one less thing to have to worry about while analyzing the code).</p>\n\n<p>If code is going to need to run on ancient browsers which don't support ES2015 syntax like <code>const</code>, the best solution for maintainable code is to use <a href=\"https://babeljs.io/\" rel=\"nofollow noreferrer\">Babel</a> to automatically transpile to ES5 for production, while keeping the source code concise and modern.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-04T23:20:36.897", "Id": "470644", "Score": "0", "body": "It's super elegant, and makes it a lot nicer and easier indeed. The only bit I don't get is english to italian, because in reality I only have italian like `ieriTerapia.push` not `yesterdayTeraphy.push` I have translated it here for everyone to understand it. Not sure if this changes your code" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-04T23:22:33.617", "Id": "470645", "Score": "0", "body": "It depends on the properties in your desired output structure. If it's going to be the same as in the input dataset, there's no need for the object. If the properties are sometimes going to be different from those in the input, regardless of language, it will still be useful to concisely transform the input property name to the desired property name." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-04T23:29:34.087", "Id": "470646", "Score": "0", "body": "ehmm, maybe you're right, I actually have 2 maps, italian and global, while in italiani \"Guariti\" is always \"Guariti\", when we switch to the global map, we actually have \"Recovered\", same thing for Deaths and Cases (wish we had more data for covid-19 as we have per the italian as the questions shows). Thanks a lot" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-04T23:14:57.660", "Id": "239954", "ParentId": "239942", "Score": "2" } } ]
{ "AcceptedAnswerId": "239954", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-04T20:36:27.437", "Id": "239942", "Score": "4", "Tags": [ "javascript" ], "Title": "Better way to get total of different items in loop?" }
239942
<p>I'm parsing commandline arguments in lua with a command parser library (<code>penlight lapp</code>). This works fine, is easy to design and flexible enough for me. However, now I have a table containing all the parsed arguments, so I'm still stuck with the <em>processing</em>, that is calling functions or changing settings etc. within my program. Some of these options are checks or similar operations that abort normal program behaviour, so I need to exit the main program before entering the normal routines. To implement such behaviour, I'm essentially using a large if-elseif chain, which is complex and hard to maintain. </p> <p>Here is some code, but my question is of a general nature: Most not-trivial-utilities-with-more-than-two-arguments need to solve this, there has to be a way to do this somewhat elegantly and non-complex. How?</p> <pre><code>local cmdargs = [[ Utility --foo enables foo --bar check for bar, then exit ]] local args = parse_args(cmdargs) if args.foo then set_switch() end if args.bar then check_something() exit(0) end do_main_stuff() </code></pre> <p>My example has only two arguments, but with 20+ arguments this style becomes really unreadable.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-04T20:47:33.267", "Id": "239943", "Score": "1", "Tags": [ "console", "lua" ], "Title": "Processing commandline arguments" }
239943
<p>Here is a class that I have implemented in order to sort rows of parameters in the form of an array of strings.</p> <pre><code>public class ParameterLinesSorter : IParameterLinesSorter { private int identiferIndex; private IEnumerable&lt;string[]&gt; parameterLines; public IEnumerable&lt;IEnumerable&lt;string[]&gt;&gt; Sort(IEnumerable&lt;string[]&gt; parameterLines, int identiferIndex) { this.identiferIndex = identiferIndex; this.parameterLines = parameterLines; return IsNotNullAndNotEmpty() ? FilterAndSort() : new List&lt;IEnumerable&lt;string[]&gt;&gt;(); } private bool IsNotNullAndNotEmpty() { return parameterLines != null &amp;&amp; parameterLines.Any(); } private IEnumerable&lt;IEnumerable&lt;string[]&gt;&gt; FilterAndSort() { return parameterLines .Where(parameterLine =&gt; parameterLine.Any()) .GroupBy(parameterLine =&gt; parameterLine.ElementAt(identiferIndex)); } } </code></pre> <p>Here is an example of use by a simple test :</p> <pre><code> [Test] public void ShouldReturnListWithTwoGroupsOfOneElement() { IEnumerable&lt;string[]&gt; parameterLines = new List&lt;string[]&gt;() { new string[]{ "C", "3", "3" }, new string[]{ "M", "3", "5" } }; IEnumerable&lt;IEnumerable&lt;string[]&gt;&gt; expectedGroups = new List&lt;IEnumerable&lt;string[]&gt;&gt;() { new List&lt;string[]&gt;(){ new string[]{ "C", "3", "3" }}, new List&lt;string[]&gt;(){ new string[]{ "M", "3", "5" }} }; Assert.AreEqual(expectedGroups, sorter.Sort(parameterLines, 0)); } </code></pre> <p>Note that this class and the Sort method will be used only once in all of the system.</p> <p>Just before, the IsNotNullAndNotEmpty and FilterAndSort methods had arguments but I read that the best for a method was to have no arguments. Therefore, I preferred to pass identifierIndex and parameterLines as instance variables. Is it really a good practice ?</p> <p>I am listening for any other recommendation.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-04T21:27:59.040", "Id": "470625", "Score": "2", "body": "Could you explain what this has to do with Javascript? I don't understand" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-04T21:38:25.833", "Id": "470628", "Score": "1", "body": "Didn't sucseed to understand what the code is doing" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-05T08:45:46.947", "Id": "470683", "Score": "3", "body": "Your title is too generic. Your title should describe what your code does." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-05T08:48:06.423", "Id": "470684", "Score": "3", "body": "\"the best for a method was to have no arguments\" is utter nonsense." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-05T12:49:17.790", "Id": "470699", "Score": "0", "body": "Thanks BCdotWEB for your first advice but i don't see how i can make the title less generic. \"the best for a method was to have no arguments\" comes from Clean Code book of Robert C Martin so i don't get this from anywhere but thank you." } ]
[ { "body": "<p>The most important part of Clean Code is that your code should be easily understood. The author's indication about the number of parameters of a function is meant to be something like: \"Better no parameters than one parameter. Better one parameter than two. You should avoid more than two parameters whenever it's possible\"</p>\n\n<p>For the function that checks the input <code>bool IsNotNullAndNotEmpty()</code> it would be more readable if you give it a parameter. It would read as: \"is this thing null or empty\". If you don't give it any parameter, maybe the name should be <em>ValidParameterLines</em></p>\n\n<p>There are more important guidelines in that book. For example, your code does more things than sort in that function, doesn't it? </p>\n\n<ul>\n<li>It filters the input excluding the empty</li>\n<li>It groups the input by the element at the indicated position</li>\n</ul>\n\n<p>I don't really see the sorting part if I tell you the truth. I think that the function does something like classifying the parameters grouping them by a positional value.</p>\n\n<p>What I'm trying to say is that the name of the function is misleading. That's a more important part of the Clean Code. You must write code that can be understood at first glance.</p>\n\n<p>I hope that helps you</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-06T01:37:49.443", "Id": "470744", "Score": "0", "body": "Thank you for your advice, By reading my code, i was thinking about the same thing so you confirm what i thought and it's what i expected ! The fact is that I'm French and I force myself to code in English so sometimes it's a bit difficult to find right names." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-10T23:06:32.483", "Id": "471321", "Score": "0", "body": "@MigMax most of the world is not natuve english speaker. But we all program in english. You don't want me to write code in hebrew and although i speak a little french i wouldn't like you to write code in it. Continue to work this way" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-05T21:21:52.497", "Id": "240006", "ParentId": "239944", "Score": "1" } } ]
{ "AcceptedAnswerId": "240006", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-04T21:08:19.997", "Id": "239944", "Score": "-3", "Tags": [ "c#", "programming-challenge", "revealing-module-pattern" ], "Title": "Does my code follow good clean code conventions?" }
239944
<p>I wrote a class that contains a static method that reads in files from <a href="http://networkrepository.com/index.php" rel="nofollow noreferrer">NetworkRepository</a> and converts them into a list of integer-arrays, each representing an edge. The file format from NetworkRepository is, that each line which is not a comment contains two integer numbers, the IDs of vertices connected by an edge, seperated by whitespace (tabs/spacebar).<br> Example:<br> <a href="https://i.stack.imgur.com/Mejku.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Mejku.png" alt="enter image description here"></a><br> corresponds to: </p> <pre><code>1 2 1 3 2 3 3 4 </code></pre> <p>Can my code for this be improved? I really don't like the unreachable <em>return null</em>, but I don't need error-handling except that I know I provided the wrong path.</p> <pre><code>public static List&lt;Integer[]&gt; edges_from_path(final String filePath) { //captures only lines that consist of two positive integer numbers separated by whitespace (each line encodes an edge) final String LINE_DATA_FORMAT = "\\d+\\s+\\d+"; final String SEPARATOR = "\\s+"; try { return Files.lines(Paths.get(filePath)) .filter(str -&gt; str.matches(LINE_DATA_FORMAT)) .map(str -&gt; Arrays.stream(str.split(SEPARATOR)).map(Integer::parseInt).toArray(Integer[]::new)) .collect(toList()); } catch (IOException e) { e.printStackTrace(); return null; } } </code></pre> <p>My method doesn't return a graph because I want to be able to create graphs from different sources, and a list of integer-pairs is the interface the constructor for graphs is supposed to use.</p>
[]
[ { "body": "<p>Since you are handling the file in the same method of the extraction, you have to deal with the exception.</p>\n\n<p>I suggest that you separate the logic of the file reading and the logic of the parsing in two separate methods, so the method that handles the file will handle the exception.</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>public static Stream&lt;String&gt; readFileAsLines(final String filePath) {\n try {\n return Files.lines(Paths.get(filePath));\n } catch (IOException e) {\n return Stream.empty();\n }\n}\n\npublic static List&lt;Integer[]&gt; edges_from_path(Stream&lt;String&gt; lines) {\n //captures only lines that consist of two positive integer numbers separated by whitespace (each line encodes an edge)\n final String LINE_DATA_FORMAT = \"\\\\d+\\\\s+\\\\d+\";\n final String SEPARATOR = \"\\\\s+\";\n\n return lines.filter(str -&gt; str.matches(LINE_DATA_FORMAT))\n .map(str -&gt; Arrays.stream(str.split(SEPARATOR)).map(Integer::parseInt).toArray(Integer[]::new))\n .collect(toList());\n}\n</code></pre>\n\n<h2>Bonus</h2>\n\n<p>The <code>LINE_DATA_FORMAT</code> &amp; <code>SEPARATOR</code> names are wrong, they should be in <a href=\"https://en.wikipedia.org/wiki/Camel_case\" rel=\"nofollow noreferrer\">camelCase</a>, not <a href=\"https://en.wikipedia.org/wiki/Snake_case\" rel=\"nofollow noreferrer\">snake_case</a>; But they should be class constants, in my opinion.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-05T00:22:07.363", "Id": "470649", "Score": "0", "body": "You've lost information here. A non-existent file, and an empty file both will result in an empty `Stream<>`, which would result in an empty `List<>`. The first should be an error, where as the second case may be valid; the caller has no way of distinguishing the two." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-05T00:52:14.330", "Id": "470651", "Score": "0", "body": "I wrote them in caps to signal that they're constants. And how else should I seperate words if not with \"_\" then? Also I didn't use them class-wide, because this class should read graph-files from multiple sources, not only this format." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-05T01:21:34.790", "Id": "470654", "Score": "0", "body": "@Morinator, for the constants, generally we use the `static` and `final` keywords combined. In this example, the variable will be recreated each time you call the method; in my opinion, this is not a constant. For the word separation, you can separate words with `camelCase` by using the upper case as the word separator.\n`LINE_DATA_FORMAT = lineDataFormat` :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-05T01:28:24.197", "Id": "470655", "Score": "0", "body": "Ok, did that now. But the runtime in this part of the program is pretty irrelevant anyways. What my program does outside this reader is NP-hard, so this won't be a bottleneck :D" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-04T23:31:54.677", "Id": "239955", "ParentId": "239950", "Score": "3" } }, { "body": "<h1>Exception Handling</h1>\n\n<p>What are you doing in the exceptional case?</p>\n\n<p>Printing an error message (ugly stack trace, actually) and returning <code>null</code>. Now the caller has to handle the problem of the function returning <code>null</code>.</p>\n\n<p>You've said:</p>\n\n<blockquote>\n <p>I don't need error-handling except that I know I provided the wrong path.</p>\n</blockquote>\n\n<p>Well, want is the caller doing when it gets the <code>null</code>? Does it say, \"I couldn't open that file, please enter a different filename\"? That too is error handling, and you've have it in two places: the <code>try ... catch</code> here, and the <code>if (list == null)</code> by the caller.</p>\n\n<p>Better is to ignore the exception here, and let the caller handle it, or the caller's caller.</p>\n\n<pre><code>public static List&lt;Integer[]&gt; edges_from_path(final String filePath) throws IOException {\n //captures only lines that consist of two positive integer numbers separated by whitespace (each line encodes an edge)\n final String LINE_DATA_FORMAT = \"\\\\d+\\\\s+\\\\d+\";\n final String SEPARATOR = \"\\\\s+\";\n return Files.lines(Paths.get(filePath))\n .filter(str -&gt; str.matches(LINE_DATA_FORMAT))\n .map(str -&gt; Arrays.stream(str.split(SEPARATOR)).map(Integer::parseInt).toArray(Integer[]::new))\n .collect(toList());\n}\n</code></pre>\n\n<blockquote>\n <p>My method doesn't return a graph because I want to be able to create graphs from different sources, and a list of integer-pairs is the interface the constructor for graphs is supposed to use.</p>\n</blockquote>\n\n<p>This is even more reason not to catch the error and return <code>null</code>; the other sources would need to have the same behaviour. They could fail in different and diverse ways; the exception will provide more details about the failure than <code>null</code> return value will.</p>\n\n<h1>List of Integer-Pairs</h1>\n\n<p>To say I almost threw-up when I saw <code>List&lt;Integer[]&gt;</code> would be an exaggeration, but only slightly. Mixing collections and raw arrays is cringe worthy. But a list of a raw arrays of a boxed type??? Yikes!</p>\n\n<p>The raison d'être for \"boxed types\" is so they can be placed into the various <a href=\"https://docs.oracle.com/en/java/javase/12/docs/api/java.base/java/util/Collection.html\" rel=\"noreferrer\"><code>Collection&lt;E&gt;</code></a> containers, which require objects instead of raw types. But here, you're not putting the integers into a <code>Collection&lt;E&gt;</code>; you're putting them into an array (<code>[]</code>), so they don't actually need to be boxed.</p>\n\n<p>To see how wrong this is, each element of the <code>List&lt;&gt;</code> is an object <code>Integer[]</code>, which holds two references to two <code>Integer</code> objects. That is 3 objects allocated in the heap (ignoring interning) for every edge in the list.</p>\n\n<p>If instead you used <code>List&lt;int[]&gt;</code>, then element of the <code>List&lt;&gt;</code> would be an <code>int[]</code> object, which directly contains the two integers, instead of references. No extra objects need to be allocated. Less memory is required, and the data is faster to access because an extra level of memory indirection has been removed.</p>\n\n<p>Still, we eschew lists of raw arrays. They are inconsistent; you need different access methods to get to the data at different levels, such as <code>list.get(idx1)[idx2]</code>. The array of integers doesn't convey any requirement on the number of values; you could be given a lists of lengths other than two. It would be better to wrap the edge information into a POD (plain old data) object:</p>\n\n<pre><code>class Edge {\n public final int from;\n public final int to;\n Edge(int _from, int _to) {\n from = _from;\n to = _to;\n }\n}\n</code></pre>\n\n<p>And then you could return a <code>List&lt;Edge&gt;</code>. Change your graph constructor from taking a list of arrays of boxed integers of arbitrary lengths to taking a list of edges. That is a much clearer interface contract.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-05T00:50:46.383", "Id": "470650", "Score": "0", "body": "Really appealing writing style. Made me feel dumb as bread. 10/10. This is what I'm here for. I also found this: https://guava.dev/releases/23.0/api/docs/com/google/common/graph/EndpointPair.html. I guess that's even better than an Edge-class." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-05T00:17:38.110", "Id": "239961", "ParentId": "239950", "Score": "6" } } ]
{ "AcceptedAnswerId": "239961", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-04T22:25:43.190", "Id": "239950", "Score": "4", "Tags": [ "java", "error-handling", "io", "exception" ], "Title": "Reader for graph-file with ugly return and questionable use of streams" }
239950
<p>This is a follow-up from my <a href="https://codereview.stackexchange.com/questions/239613/design-that-avoids-undesired-dependencies-in-kotlin-for-a-chess-engine">previous review</a> on this site. To be clear, the code is stand-alone, and does not depend on the previous review.</p> <p>As before my goal is to come up with a design for a chess engine in Kotlin that hides implementation details, and that ensures that the implementation cannot accidentally become spaghetti.</p> <h1>Example client code</h1> <pre><code>package chessapp import chessapp.api.internal.createBoard import chessapp.api.internal.createSearchEngine fun main() { val board = createBoard("1R/1p w") val searchEngine = createSearchEngine() val move = searchEngine.findBestMove(board) println(move) } </code></pre> <h1>Client facing public API</h1> <pre><code>package chessapp.api enum class PieceColor { BLACK, WHITE } enum class PieceType { PAWN, ROOK} data class ColoredPiece(val pieceColor: PieceColor, val pieceType: PieceType) interface Board { val pieces: List&lt;ColoredPiece&gt; } interface SearchEngine { fun findBestMove(board: Board): String } </code></pre> <p>Intended to be clean and easy to understand, but bad for performance.</p> <h1>Inward facing API</h1> <pre><code>package chessapp.api.internal import chessapp.api.Board internal const val BLACK_PAWN: Byte = (0x00 + 0x01).toByte() internal const val WHITE_ROOK: Byte = (0x08 + 0x05).toByte() internal interface InternalBoard: Board { val bytePieces: ByteArray fun doInternalMove(from: Int, to: Int) } </code></pre> <p>Intended to be optimized for performance and potentially hard to understand.<br> Additionally, the interface is likely volatile and can change quickly, which should not affect the public API.</p> <h1>Implementation that supports both public and internal API</h1> <pre><code>package chessapp.api.internal import chessapp.api.Board import chessapp.api.ColoredPiece import chessapp.api.PieceColor import chessapp.api.PieceType fun createBoard(fen: String): Board = InternalBoardImpl(fen) internal fun createInternalBoard(board: Board): InternalBoard = InternalBoardImpl(board as InternalBoardImpl) internal class InternalBoardImpl(override val bytePieces: ByteArray) : InternalBoard { constructor(fen: String) : this(byteArrayOf(BLACK_PAWN, WHITE_ROOK)) {} constructor(rhs: InternalBoardImpl) : this(rhs.bytePieces.copyOf()) {} override val pieces: List&lt;ColoredPiece&gt; get() = bytePieces.map { it.toColoredPiece() } override fun doInternalMove(from: Int, to: Int) {} } internal fun Byte.toColoredPiece() = when (this) { BLACK_PAWN -&gt; ColoredPiece(PieceColor.BLACK, PieceType.PAWN) WHITE_ROOK -&gt; ColoredPiece(PieceColor.WHITE, PieceType.ROOK) else -&gt; null }!! </code></pre> <p>As you may notice, there is a hidden assumption that a <code>Board</code> will always be an <code>InternalBoard</code>, and even more, implemented as an <code>InternalBoardImpl</code>. As yet I haven't figured out how to do that better without sacrificing the separation of the public and internal interface. So please feel free to comment.</p> <h1>Search engine implementation that uses only the internal interface</h1> <pre><code>package chessapp.api.internal import chessapp.api.Board import chessapp.api.SearchEngine fun createSearchEngine(): SearchEngine = OptimizedSearchEngine() internal class OptimizedSearchEngine: SearchEngine { override fun findBestMove(board: Board): String { // Intended to be badly readable code just because it is supposed to be optimized for speed return listOf(Pair(7, 8), Pair(7, 15)).map { val newInternalBoard = createInternalBoard(board) newInternalBoard.doInternalMove(it.first, it.second) Pair(evaluate(newInternalBoard), it) }.maxBy { it.first }?.second.toString() } private fun evaluate(internalBoard: InternalBoard) = 42 } </code></pre> <h1>Final words</h1> <p>I'd appreciate any thoughts you may have how this example design code can be improved.</p> <p>To be honest, I'm not pleased with the hidden assumption that a <code>Board</code> has to be an <code>InternalBoard</code>, which in turn has to be an <code>InternalBoardImpl</code>. It goes against the OO concept that an interface should be able to have different implementations.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-04T22:44:55.840", "Id": "239952", "Score": "1", "Tags": [ "object-oriented", "design-patterns", "kotlin", "chess" ], "Title": "Design to separate client API from internal API in Kotlin for a chess engine" }
239952
<p>I am learning python and trying to solve different problems i came across this program which is name mashup which is in Get Programming:Learn to code with Python.</p> <p>problem statement: Write a program that automatically combines two names given by the user. That’s an open-ended problem statement, so let’s add a few more details and restrictions:</p> <ul> <li>Tell the user to give you two names in the format FIRST LAST. Show the user two possible new -names in the format FIRST LAST.</li> <li><p>The new first name is a combination of the first names given by the user, and the new last name is a combination of the last names given by the user.</p> <p>For example, if the user gives you Alice Cat and Bob Dog, a possible mashup is Bolice Dot.</p></li> </ul> <p>I'd like to know is there any way to improve this program like using functions to make this program better.</p> <pre><code> print('Welcome to the Name Mashup Game') name1 = input('Enter one full name(FIRST LAST): ') name2 = input('Enter second full name(FIRST LAST): ') space = name1.find(" ") name1_first = name1[0:space] name1_last = name1[space+1:len(name1)] space = name2.find(" ") name2_first = name2[0:space] name2_last = name2[space+1:len(name2)] # find combinations name1_first_1sthalf = name1_first[0:int(len(name1_first)/2)] name1_first_2ndhalf = name1_first[int(len(name1_first)/2):len(name1_first)] name1_last_1sthalf = name1_last[0:int(len(name1_last)/2)] name1_last_2ndhalf = name1_last[int(len(name1_last)/2):len(name1_last)] name2_first_1sthalf = name2_first[0:int(len(name2_first)/2)] name2_first_2ndhalf = name2_first[int(len(name2_first)/2):len(name2_first)] name2_last_1sthalf = name2_last[0:int(len(name2_last)/2)] name2_last_2ndhalf = name2_last[int(len(name2_last)/2):len(name2_last)] new_name1_first = name1_first_1sthalf + name2_first_2ndhalf new_name1_last = name1_last_1sthalf + name2_last_2ndhalf new_name2_first = name2_first_1sthalf + name1_first_2ndhalf new_name2_last = name2_last_1sthalf + name1_last_2ndhalf # print results print(new_name1_first, new_name1_last) print(new_name2_first, new_name2_last) </code></pre>
[]
[ { "body": "<p>Any time you're doing essentially the same thing (even if it's in different orders) to different values, it's a strong clue that the values should be a collection (like a list or tuple) rather than independent named variables. It'll usually make your code a lot shorter, and it makes it much much easier to extend -- what if you wanted to play the mashup game with more names?</p>\n\n<pre><code>from itertools import permutations\nfrom typing import List\n\nprint('Welcome to the Name Mashup Game')\n\nnames = [\n input('Enter one full name(FIRST LAST): ').split(),\n input('Enter second full name(FIRST LAST): ').split(),\n # input('Enter third full name(FIRST LAST):' ).split(), &lt;- try me!\n]\n\ndef mash(first: List[str], second: List[str]) -&gt; List[str]:\n \"\"\"\n Produce a list where each element has the first half of the corresponding\n element from the first list and the second half of the corresponding \n element from the second list.\n\n For example:\n mash(['AA', 'BB'], ['XX', 'YY']) -&gt; ['AX', 'BY']\n \"\"\"\n return [\n a[:len(a)//2] + b[len(b)//2:]\n for a, b in zip(first, second)\n ]\n\nfor first, second in permutations(names, 2):\n print(' '.join(mash(first, second)))\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-05T05:49:09.350", "Id": "239970", "ParentId": "239956", "Score": "3" } } ]
{ "AcceptedAnswerId": "239970", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-04T23:32:11.263", "Id": "239956", "Score": "3", "Tags": [ "python", "python-3.x" ], "Title": "Name Mashup Program Improvement in Python" }
239956
<p>I'm trying to build a customer email generator in java using the abstract factory pattern. I understand how to use the factory method pattern; however, I'm a bit confused about the abstract factory pattern. I'm trying to generate an email based on customer type. Could you look at my code below and tell me if I'm using the abstract factory pattern correctly? My code works fine. I just want to make sure that I'm using the pattern correctly. Thank you</p> <pre><code>public abstract class EmailTemplate { public abstract String getHeader(); public abstract String getBody(); public abstract String getFooter(); public String generateEmail(){ return getHeader()+"\n"+getBody()+"\n"+getFooter(); } } public interface EmailFactory { EmailTemplate createEmail(); } public class BusinessEmail extends EmailTemplate { @Override public String getHeader() { return "Dear [business customer],"; } @Override public String getBody() { return "Thank you for being our valued customer. We are so grateful for the pleasure of serving you and hope we met your expectations."; } @Override public String getFooter() { return "Best Regards," + "[name]"; } } public interface EmailGeneratorFactory { EmailTemplate createEmail(); } public class BusinessFactory implements EmailGeneratorFactory { @Override public EmailTemplate createEmail() { return new BusinessEmail(); } } public class EMailGenerationSystem { private static EMailGenerationSystem EMailGenerationSystem = new EMailGenerationSystem(); private EMailGenerationSystem(){}; public static EMailGenerationSystem getInstance(){ return EMailGenerationSystem; } public EmailTemplate getEmail(EmailGeneratorFactory factory){ return factory.createEmail(); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-05T06:38:22.083", "Id": "470672", "Score": "1", "body": "I dont see abstract factory design pattern at all. Why do you think this should be it? I only see factory method pattern, twice." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-05T18:25:04.390", "Id": "470730", "Score": "0", "body": "Thank you for your feedback. I followed this example https://www.journaldev.com/1418/abstract-factory-design-pattern-in-java that's why I thought I was implementing the abstract factory pattern. If you don't mind, what needs to change to make this into an abstract factory?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-05T18:36:36.293", "Id": "470731", "Score": "0", "body": "I see, you have followed it well. Unfortunately the article does not describe abstract factory pattern, but a very bad example of factory method pattern surrounded with some useless code. Ill try to make an explanatory answer, but Its almost time to go sleep here, so hopefuly tommorow..." } ]
[ { "body": "<p>Design patterns provide means to solve common problems. Every pattern has its purpose and allows to solve a particular problem (or more precisely, a class of problems with common aspects).</p>\n\n<p>You should not ask yourself \"Does my code follow a particular design pattern?\". But rather \"Does my code follow the right design pattern to solve a particular problem?\"</p>\n\n<p>Factory method pattern serves the purpose of decoupling interface implementation from its consumer.</p>\n\n<p>Abstract factory pattern is actually very similar. You may even say that an abstract factory also follows factory method pattern. But the main difference is that abstract factory acts a bit like a pallete of similar objects to create. So in fact, it acts like multiple factory methods at the same time. These individual methods of abstract factory usualy return the same interfaces or subtypes, although I don't think it is strictly necesary.</p>\n\n<p>Factory methods offer instantiation of a polymorphic object, where consumer is not interseted in aspects of the implementation.</p>\n\n<p>Whereas abstract factory leaves the decision over the aspects of the created implementation to consumer which will decide based on the algorithm the consumer implements.</p>\n\n<p>Now what's wrong with the implementation you showed us.</p>\n\n<pre><code>public EmailTemplate getEmail(EmailGeneratorFactory factory){\n return factory.createEmail();\n}\n</code></pre>\n\n<p>Do you see the usefulness of this method? I don't. The caller must know the <code>EmailGeneratorFactory</code> instance, and it must know the instance of this singleton class. But nothing extra is done in addition to what can be done with the <code>EmailGeneratorFactory</code> alone. Calling <code>factory.createEmail()</code> can be done directly.</p>\n\n<p>Since <code>EMailGenerationSystem</code> class does not offer anything else, it is useless as a whole. I suspect that the author of the article you've linked did not understand it himself. And this code is not supposed to be a generic part of the pattern, but rather your application code, where somehow you have got an instance of the factory and do some work with it at some point of logic in your app.</p>\n\n<p>Now, I already mentioned in comments that I see factory methods twice, and no abstract factory at all, in your code.</p>\n\n<p>Let me write just one factory method.</p>\n\n<p>Please excuse any ommited public modifiers, etc, as I am not used to Java.</p>\n\n<pre><code>interface EmailFactory\n{\n String generateEmail();\n}\n\nclass BussinessEmailFactory implements EmailFactory\n{\n String generateEmail()\n {\n //use a String builder?\n return \"...\";\n }\n}\n\nclass ReportEmailFactory extends EmailFactory {...}\n</code></pre>\n\n<p>Now lets say we have a cli command that will send an email when it finishes and it does not care what email that is.</p>\n\n<pre><code>class ReportCommand\n{\n private SomeServiceForWork worker;\n private EmailSender emailSender;\n private EmaiFactory emailFactory;\n private String reportEmail;\n\n ReportCommand(SomeServiceForWork, EmailSender, EmailFactory, String) ...\n\n public void execute()\n {\n // doing some work\n // ...\n\n String emailBody = emailFactory.generateEmail();\n emailSender.send(reportEmail, emailBody);\n }\n}\n\nnew ReportCommand(\n new WeeklyReportWorker(), \n sender, \n new ReportEmailFactory(), \n \"...\"\n);\n</code></pre>\n\n<p>While abstract factory could look like this</p>\n\n<pre><code>interface EmailFactory\n{\n public String generateSuccessEmail();\n public String generateErrorEmail(Exception $e);\n}\n\nclass PlainEmailFactory implements EmailFactory\n{\n public String generateSuccessEmail()\n {\n return \"...\";\n }\n\n public String generateErrorEmail(Exception $e)\n {\n return \"......\";\n }\n}\n\nclass ReportCommand\n{\n private SomeServiceForWork worker;\n private EmailSender emailSender;\n private EmaiFactory emailFactory;\n private String reportEmail;\n\n ReportCommand(SomeServiceForWork, EmailSender, EmailFactory, String) ...\n\n public void execute()\n {\n String emailBody;\n try {\n // doing some work\n // ...\n\n emailBody = emailFactory.generateSuccessEmail();\n } catch (WorkFailException $e) {\n emailBody = emailFactory.generateErrorEmail($e);\n }\n emailSender.send(reportEmail, emailBody);\n }\n}\n\nnew ReportCommand(\n new WeeklyReportWorker(), \n sender, \n new PlainEmailFactory(), \n \"...\"\n);\n</code></pre>\n\n<p>Here the command was interested in sending one of two distinct emails, based on what happened, but he is abstracted from details of those two distinct emails, he just dictates when to send which one.</p>\n\n<p>Finally one note to your code, the methods getHeader(), getFooter(), getBody() are used nowhere outside the EmailTemplate class, therefore should not be public.</p>\n\n<p>Let me show even better thing how to do it and it will actualy combine abstract factory, stragegy and factory method patterns.</p>\n\n<pre><code>// this is the abstract factory interface\ninterface EmailComponentFactory\n{\n String getHeader();\n String getBody();\n String getFooter();\n}\n\n// this is the factory method interface\ninterface EmailFactory\n{\n String generateEmail();\n}\n\n// this is the factory method implementation\n// it also acts as strategy owner \n// and the abstract factory interface is the strategy\nclass CompositeEmailFactory implements EmailFactory\n{\n EmailComponentFactory factory;\n String separator;\n\n public CompositeEmailFactory(EmailComponentFactory f, String s = \"\\n\") {factory = f; separator = s;}\n\n String generateEmail()\n {\n String header = factory.getHeader();\n String body = factory.getBody();\n String footer factory.getFooter();\n int separatorLegth = separator.length();\n int headerLength = header.length();\n int bodyLength = body.length();\n int footerLength = footer.length();\n int nonHeaderLength = bodyLength + footerLength;\n int length = headerLength + nonHeaderLength;\n\n if (headerLength &gt; 0 &amp;&amp; nonHeaderLength &gt; 0) {\n length += separatorLength;\n }\n if (bodyLength &gt; 0 &amp;&amp; footerLength &gt; 0) {\n length += separatorLength;\n }\n StringBuilder sb = new StringBuilder(length);\n if (headerLength &gt; 0 &amp;&amp; nonHeaderLength &gt; 0) {\n sb.append(header);\n sb.append(separator);\n }\n if (bodyLength &gt; 0 &amp;&amp; footerLength &gt; 0) {\n sb.append(body);\n sb.append(separator);\n }\n sb.append(footer);\n return sb.build();\n }\n}\n</code></pre>\n\n<p>In the above code you can also see how to use a string builder to allocate just the right amount of memory for entire string (not tested). It is a bit more complex, but it should be more effective.</p>\n\n<p>Few final notes :)</p>\n\n<p>Both factory methods and abstract factories can accept arguments (and different methods of abstract factory can accept different arguments).</p>\n\n<pre><code>interface IShape {...}\ninterface ICircle extends IShape {...}\ninterface ISquare extends IShape {...}\ninterface IRectangle extends IShape {...}\ninterface AbstractShapeFactory\n{\n public ICircle createCirle(double radius);\n public ISquare createSquare(double width);\n public IRectangle createRectangle(double width, double height);\n}\n</code></pre>\n\n<p>Abstract factory is very similar to factory method accepting enum argument.</p>\n\n<pre><code>interface IColor {...}\n\ninterface AbstractColorFactory\n{\n IColor createRed();\n IColor createGreen();\n IColor createBlue();\n}\n\nenum ColorEnum {Red, Green, Blue};\ninterface ColorFactoryMethod\n{\n IColor createColor(ColorEnum color);\n}\n</code></pre>\n\n<p>Factories can of course create other factories, but there must be a reason for it (in complex application there sure are). Anyway doing so does not make it abstract factory pattern. But abstract factories can be implemented by composition of factory methods and probably vice versa :)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-06T16:40:59.080", "Id": "470826", "Score": "0", "body": "You are amazing. Thank you so much for demystifying this matter." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-06T06:43:46.433", "Id": "240029", "ParentId": "239959", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-05T00:05:12.213", "Id": "239959", "Score": "3", "Tags": [ "java", "design-patterns", "abstract-factory" ], "Title": "Building an email generator using abstract factory pattern" }
239959
<pre><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;body&gt; &lt;canvas id="myCanvas" width="1200" height="1000" style="border:1px solid #d3d3d3;"&gt; Your browser does not support the HTML5 canvas tag.&lt;/canvas&gt; &lt;script&gt; const maxWidth = 1200; const maxHeight = 1000; const radius = 5; const numberOfPeople = 250; const velocity = 5; const personArray = []; let c = document.getElementById("myCanvas"); let ctx = c.getContext("2d"); function getRandomCord(min, max) { return Math.random() * (max - min) + min; } function getRandomStartDirection() { let min = Math.ceil(-1); let max = Math.floor(1); return Math.floor(Math.random() * (max - min + 1)) + min; } function Person(initXDir, initYDir) { this.infectionHasBeenSet = false; this.xCord = getRandomCord(0, maxWidth); this.yCord = getRandomCord(0 , maxHeight); this.xDir = initXDir; this.yDir = initYDir; this.infected = false; let detectBoarderCollision = function(){ if ((this.xCord &lt; 0 + radius) || (this.xCord &gt; maxWidth - radius)) { this.xDir = this.xDir*(-1); } if ((this.yCord &lt; 0 + radius) || (this.yCord &gt; maxHeight - radius)) { this.yDir = this.yDir*(-1); } }; let startAsInfected = function() { let chance = Math.random(); if (!this.infectionHasBeenSet) { this.infectionHasBeenSet = true; if (chance &lt; 0.05) { this.infected = true; } else { this.infected = false; } } else { return; } }; this.acquireCorona = function(distArray){ let distFromMe = distArray.filter(dist =&gt; (dist.pointA.id === this)&amp;&amp;(dist.distance&lt;50)); let distToMe = distArray.filter(dist =&gt; (dist.pointB.id === this)&amp;&amp;(dist.distance&lt;50)); let closeToMe = distFromMe.concat(distToMe); let uniquePointsSet = new Set(); for (let i = 0; i &lt; closeToMe.length; i++) { uniquePointsSet.add(closeToMe[i].pointA.id); uniquePointsSet.add(closeToMe[i].pointB.id); } uniquePointsSet.forEach(eachPoint =&gt; { if (eachPoint.infected) { this.infected = true; } }); }; this.move = function (){ this.xCord += this.xDir*velocity; this.yCord += this.yDir*velocity; detectBoarderCollision.call(this); startAsInfected.call(this); }; this.returnInfectionStatus = function() { return this.infected; }; this.returnCords = function() { return { x: this.xCord, y: this.yCord }; }; } let peopleCords = function() { const coordsArray = []; function update(id, cords) { let match = coordsArray.filter(person =&gt; person.id === id); if (match.length&gt;0) { match[0].cords = cords; } else { coordsArray.push({'id':id, 'cords':cords}); } } function returnCordsArray() { return coordsArray; } return { update: update, returnCordsArray: returnCordsArray }; }(); let distancesModule = function() { const distanceArray = []; function calculateDistance(coordsArray) { for (let i = 0; i &lt; coordsArray.length; i++) { for (let o = i + 1; o &lt; coordsArray.length; o++) { let pointA = coordsArray[i]; let pointB = coordsArray[o]; let distance = 0; distance = Math.sqrt(Math.pow((pointA.cords.x-pointB.cords.x),2) + Math.pow((pointA.cords.y-pointB.cords.y),2)); updateDistanceArray(pointA, pointB, distance); } } } function updateDistanceArray(pointA, pointB, distance) { let allDistanceFromA = distanceArray.filter(distance =&gt; distance.pointA === pointA); let allDistanceFromB = distanceArray.filter(distance =&gt; distance.pointB === pointB); let match = allDistanceFromA.filter(distanceFromA =&gt; allDistanceFromB.includes(distanceFromA)); if (match.length === 0) { distanceArray.push({'pointA': pointA, 'pointB': pointB, 'distance': distance}); } else { match[0].distance = distance; } } function returnDistanceArray() { return distanceArray; } return { calculateDistance: calculateDistance, updateDistanceArray: updateDistanceArray, returnDistanceArray: returnDistanceArray }; }(); function ctxDraw(x, y, isInfected) { ctx.fillStyle = (isInfected ? "red" : "blue"); ctx.beginPath(); ctx.arc(x, y, radius, 0, 2 * Math.PI); ctx.fill(); } function clearCanvas() { ctx.clearRect(0,0,maxWidth,maxHeight); } function makePeople() { for (let i = 0; i &lt; numberOfPeople; i++) { let newPerson = new Person(getRandomStartDirection(), getRandomStartDirection()); personArray.push(newPerson); } } function peopleMove() { clearCanvas(); for (let i = 0; i &lt; personArray.length; i++) { personArray[i].move(); ctxDraw(personArray[i].returnCords().x, personArray[i].returnCords().y, personArray[i].returnInfectionStatus()); peopleCords.update(personArray[i], personArray[i].returnCords()); } distancesModule.calculateDistance(peopleCords.returnCordsArray()); setTimeout(peopleMove, 30); } function spreadInfection() { for (let i = 0; i &lt; personArray.length; i++) { personArray[i].acquireCorona(distancesModule.returnDistanceArray()); } setTimeout(spreadInfection,2000); } makePeople(); peopleMove(); spreadInfection(); &lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>A simple virus simulator I wrote. I believe there are performance bottle necks in my code, as running a simulation with numberOfPeople higher than 150 seriously slows it down. </p> <p>The key configuration parameters are:</p> <ul> <li>line 12: const numberOfPeople; it represents the number of dots on screen</li> <li>line 190: setTimeout(peopleMove, 30); every 30ms every person makes a move</li> <li>line 197: setTimeout(spreadInfection,2000); every 2000ms we check if someone gets infected</li> </ul> <p>Besides, </p> <pre><code>function foo() { bar(); //doing some tasks setTimeout(foo, 1000); } </code></pre> <p>Is this an elegant solution to call a function at a given interval? I noticed in Chrome developer console, execution stacks keeps growing with each call on foo. </p>
[]
[ { "body": "<p>Your current approach of using a nested loop to check every Person's distance from every other Person is <code>O(n ^ 2)</code>, which is pretty expensive as the number of people increase. One alternative is to iterate over all infected people and add all coordinates within the infection radius to a Set, <code>O(n)</code>. Then iterate over non-infected people and see if their coordinate is in that set, also <code>O(n)</code></p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"false\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const maxWidth = 1200;\nconst maxHeight = 1000;\nconst radius = 5;\nconst numberOfPeople = 250;\nconst velocity = 5;\nconst personArray = [];\n\nconst ctx = document.getElementById(\"myCanvas\").getContext(\"2d\");\n\nfunction getRandomCord(min, max) {\n return Math.floor(Math.random() * (max - min) + min);\n}\n\nfunction getRandomStartDirection() {\n // -1, 0, or 1\n return Math.floor(Math.random() * 3) - 1;\n}\n\nfunction Person(initXDir, initYDir) {\n this.infected = Math.random() &lt; 0.5;\n this.xCoord = getRandomCord(0, maxWidth);\n this.yCoord = getRandomCord(0, maxHeight);\n this.xDir = initXDir;\n this.yDir = initYDir;\n\n const detectBorderCollision = function() {\n if ((this.xCoord &lt; 0 + radius) || (this.xCoord &gt; maxWidth - radius)) {\n this.xDir = this.xDir * (-1);\n }\n if ((this.yCoord &lt; 0 + radius) || (this.yCoord &gt; maxHeight - radius)) {\n this.yDir = this.yDir * (-1);\n }\n };\n\n this.move = function() {\n this.xCoord += this.xDir * velocity;\n this.yCoord += this.yDir * velocity;\n detectBorderCollision.call(this);\n };\n}\n\n\n\nfunction ctxDraw(x, y, isInfected) {\n ctx.fillStyle = (isInfected ? \"red\" : \"blue\");\n ctx.beginPath();\n ctx.arc(x, y, radius, 0, 2 * Math.PI);\n ctx.fill();\n}\n\nfunction clearCanvas() {\n ctx.clearRect(0, 0, maxWidth, maxHeight);\n}\n\nfunction makePeople() {\n for (let i = 0; i &lt; numberOfPeople; i++) {\n const newPerson = new Person(getRandomStartDirection(), getRandomStartDirection());\n if (i === 0) newPerson.infected = true;\n personArray.push(newPerson);\n }\n}\n\nlet turn = 0;\nfunction peopleMove() {\n clearCanvas();\n turn++;\n if (turn % 60 === 0) {\n spreadInfection();\n }\n for (const person of personArray) {\n person.move();\n ctxDraw(person.xCoord, person.yCoord, person.infected);\n }\n setTimeout(peopleMove, 30);\n}\n\nconst infectionRange = 50;\nconst infectionRangeArr = [];\nfor (let i = -infectionRange; i &lt;= infectionRange; i += 4) {\n for (let j = -infectionRange; j &lt;= infectionRange; j += 4) {\n if (Math.sqrt(i ** 2 + j ** 2) &lt;= 50) {\n infectionRangeArr.push([i, j]);\n }\n }\n}\nconst surroundingCoordinates = (personX, personY) =&gt; {\n return infectionRangeArr.map(([rangeX, rangeY]) =&gt; [personX + rangeX, personY + rangeY]);\n};\nfunction spreadInfection() {\n const infectCoordinates = new Set();\n for (const person of personArray) {\n if (person.infected) {\n for (const [x, y] of surroundingCoordinates(person.xCoord, person.yCoord)) {\n infectCoordinates.add(x + ',' + y);\n }\n }\n }\n for (const person of personArray) {\n if (!person.infected &amp;&amp; infectCoordinates.has(person.xCoord + ',' + person.yCoord)) {\n person.infected = true;\n }\n }\n}\n\nmakePeople();\npeopleMove();</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;canvas id=\"myCanvas\" width=\"1200\" height=\"1000\" style=\"border:1px solid #d3d3d3;\"&gt;\nYour browser does not support the HTML5 canvas tag.&lt;/canvas&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>This makes larger numbers of people <em>runnable</em> due to the exponential speed-up, but it's still somewhat sluggish due to the sheer numbers of pixels to fill every time <code>spreadInfection</code> runs.</p>\n\n<p>A better approach is to push each infected person into an array of <em>segments</em> of the graph. For example, given an infection radius of 50, a width of 150, and a height of 100, there would be six 50x50 segments of the graph into which each infected person would be categorized into. Then, inside <code>spreadInfection</code>, each <em>healthy</em> person would identify the segment they fall in, as well as every adjacent segment, and check if any of the infected in those segments are less than <code>infectionRadius</code> away from the healthy person.</p>\n\n<p>On a large graph like in your real code, this means that instead of checking against <em>every</em> infected person, you'd only have to check against the infected people in 9 of the 480 segments on the graph. The smaller the infection radius and the larger the graph, the more improvement this approach provides. On my machine, this model runs with 1000 people without issues.</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"false\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const maxWidth = 1200;\nconst maxHeight = 1000;\nconst radius = 5;\nconst numberOfPeople = 1000;\nconst velocity = 5;\nconst personArray = [];\nconst infectionRadius = 50;\n\nconst ctx = document.getElementById(\"myCanvas\").getContext(\"2d\");\n\nfunction getRandomCord(min, max) {\n return Math.floor(Math.random() * (max - min) + min);\n}\n\nfunction getRandomStartDirection() {\n // -1, 0, or 1\n return Math.floor(Math.random() * 3) - 1;\n}\n\nconst segmentColumns = Array.from(\n { length: Math.ceil(maxWidth / infectionRadius) + 1 },\n () =&gt; Array.from(\n { length: Math.ceil(maxHeight / infectionRadius) + 1 },\n () =&gt; []\n )\n);\n\nclass Person {\n constructor(initXDir, initYDir) {\n this.infected = Math.random() &lt; 0.05;\n this.xCoord = getRandomCord(0, maxWidth);\n this.yCoord = getRandomCord(0, maxHeight);\n this.xDir = initXDir;\n this.yDir = initYDir;\n }\n detectBorderCollision () {\n if ((this.xCoord &lt; 0 + radius) || (this.xCoord &gt; maxWidth - radius)) {\n this.xDir = -this.xDir;\n }\n if ((this.yCoord &lt; 0 + radius) || (this.yCoord &gt; maxHeight - radius)) {\n this.yDir = -this.yDir;\n }\n this.xCoord = Math.min(maxWidth, Math.max(this.xCoord, 0));\n this.yCoord = Math.min(maxHeight, Math.max(this.yCoord, 0));\n }\n move() {\n this.xCoord += this.xDir * velocity;\n this.yCoord += this.yDir * velocity;\n this.detectBorderCollision();\n }\n}\n\nfunction ctxDraw(x, y, isInfected) {\n ctx.fillStyle = isInfected ? \"red\" : \"blue\";\n ctx.beginPath();\n ctx.arc(x, y, radius, 0, 2 * Math.PI);\n ctx.fill();\n}\n\nfunction clearCanvas() {\n ctx.clearRect(0, 0, maxWidth, maxHeight);\n}\n\nfunction makePeople() {\n for (let i = 0; i &lt; numberOfPeople; i++) {\n const newPerson = new Person(getRandomStartDirection(), getRandomStartDirection());\n if (i === 0) newPerson.infected = true;\n personArray.push(newPerson);\n }\n}\n\nlet turn = 0;\nfunction peopleMove() {\n clearCanvas();\n turn++;\n if (turn % 60 === 0) {\n spreadInfection();\n }\n \n for (const person of personArray) {\n person.move();\n ctxDraw(person.xCoord, person.yCoord, person.infected);\n }\n setTimeout(peopleMove, 30);\n}\n\nfunction spreadInfection() {\n for (const column of segmentColumns) {\n for (const square of column) {\n square.length = 0;\n }\n }\n for (const person of personArray) {\n if (person.infected) {\n const xSegment = Math.floor(person.xCoord / infectionRadius);\n const ySegment = Math.floor(person.yCoord / infectionRadius);\n segmentColumns[xSegment][ySegment].push(person);\n }\n }\n for (const person of personArray) {\n if (person.infected) continue;\n const centerXSegment = Math.floor(person.xCoord / infectionRadius);\n const centerYSegment = Math.floor(person.yCoord / infectionRadius);\n let nearbyInfected = [];\n for (let i = 0; i &lt; 3; i++) {\n const column = segmentColumns[centerXSegment + i];\n if (!column) continue;\n for (let j = 0; j &lt; 3; j++) {\n const square = column[centerYSegment + j];\n if (square) {\n nearbyInfected = nearbyInfected.concat(square);\n }\n }\n }\n for (const infected of nearbyInfected) {\n const dist = Math.sqrt(\n (infected.xCoord - person.xCoord) ** 2 +\n (infected.yCoord - person.yCoord) ** 2\n );\n if (dist &lt;= 50) {\n person.infected = true;\n }\n }\n }\n}\n\nmakePeople();\npeopleMove();</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;canvas id=\"myCanvas\" width=\"1200\" height=\"1000\" style=\"border:1px solid #d3d3d3;\"&gt;\nYour browser does not support the HTML5 canvas tag.&lt;/canvas&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>The important parts of the above code:</p>\n\n<p>Set up the segments, an array of arrays (columns), where the items of the inner arrays are squares (50x50 parts of the graph):</p>\n\n<pre><code>const segmentColumns = Array.from(\n { length: Math.ceil(maxWidth / infectionRadius) + 1 },\n () =&gt; Array.from(\n { length: Math.ceil(maxHeight / infectionRadius) + 1 },\n () =&gt; []\n )\n);\n</code></pre>\n\n<p>Then, for <code>spreadInfection</code>:</p>\n\n<pre><code>function spreadInfection() {\n // Reset all segment squares to empty\n for (const column of segmentColumns) {\n for (const square of column) {\n square.length = 0;\n }\n }\n // Add each infected person to the appropriate segment square\n for (const person of personArray) {\n if (person.infected) {\n const xSegment = Math.floor(person.xCoord / infectionRadius);\n const ySegment = Math.floor(person.yCoord / infectionRadius);\n segmentColumns[xSegment][ySegment].push(person);\n }\n }\n for (const person of personArray) {\n if (person.infected) continue;\n // Calculate center segment coordinate:\n const centerXSegment = Math.floor(person.xCoord / infectionRadius);\n const centerYSegment = Math.floor(person.yCoord / infectionRadius);\n let nearbyInfected = [];\n // Iterate through all adjacent segment squares,\n // pushing infected people to nearbyInfected:\n for (let i = 0; i &lt; 3; i++) {\n const column = segmentColumns[centerXSegment + i];\n if (!column) continue;\n for (let j = 0; j &lt; 3; j++) {\n const square = column[centerYSegment + j];\n if (square) {\n nearbyInfected = nearbyInfected.concat(square);\n }\n }\n }\n // Check if any of the nearby infected are within 50:\n for (const infected of nearbyInfected) {\n const dist = Math.sqrt(\n (infected.xCoord - person.xCoord) ** 2 +\n (infected.yCoord - person.yCoord) ** 2\n );\n if (dist &lt;= 50) {\n person.infected = true;\n }\n }\n }\n}\n</code></pre>\n\n<p>Some other notes:</p>\n\n<ul>\n<li><a href=\"https://medium.com/javascript-scene/javascript-es6-var-let-or-const-ba58b8dcde75\" rel=\"nofollow noreferrer\">Always use const to declare variables</a> whenever possible. Only use <code>let</code> when <code>const</code> is not a good option - this improves readability.</li>\n<li>You might want to ensure that at least one person is infected, else the RNG will occasionally spawn a graph without any infected. Consider unconditionally infecting the first <code>Person</code> instantiated.</li>\n<li>Proper spelling improves readability and prevents bugs - consider changing <code>detectBoarderCollision</code> to <code>detectBorderCollision</code></li>\n<li>Rather than a <code>startAsInfected</code> function that runs on every move, only run it <em>once</em>, when a Person is instantiated. No need for a persistent <code>infectionHasBeenSet</code> property either. All you need is <code>this.infected = Math.random() &lt; 0.05;</code> as the top line of the constructor, nothing else.</li>\n<li>When properties are available directly on the instance already, having accessor functions to return the instance properties can add a lot of syntax noise without really providing a benefit. If you're creating a library or something for external consumption and <em>need</em> to keep data private, sure, you can use them, but if it's just for a personal script, it doesn't help and adds extra complication.</li>\n<li>Rather than calling <code>spreadInfection</code> every 2000ms and <code>peopleMove</code> every 30ms, it might be more elegant to instead call <code>spreadInfection</code> every <code>2000 / 30</code> calls of <code>peopleMove</code> - keep track of how many times <code>peopleMove</code> has been called so far and use modulo to see if it needs to call <code>spreadInfection</code>.</li>\n</ul>\n\n<blockquote>\n <p>Is this an elegant solution to call a function at a given interval?</p>\n</blockquote>\n\n<p>Sure, there's nothing wrong with a recursive <code>setTimeout</code>, it's a fine method to use.</p>\n\n<blockquote>\n <p>I noticed in Chrome developer console, execution stacks keeps growing with each call on foo.</p>\n</blockquote>\n\n<p>There's no chance of a stack overflow, since the function runs asynchronously, so there's nothing to worry about there.</p>\n\n<hr>\n\n<p>There are some smaller optimizations that could be made to the code (such as using <code>requestAnimationFrame</code> to only calculate when needed, or separating the people into infected / healthy arrays to reduce branching, or adding extra empty arrays to the segments to reduce branching), but they're not essential given the improvements already done. Performance is already pretty decent.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-05T08:21:59.517", "Id": "470678", "Score": "0", "body": "I want to thank you for your detailed answer. Much appreciated." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-05T07:18:14.740", "Id": "239972", "ParentId": "239960", "Score": "1" } } ]
{ "AcceptedAnswerId": "239972", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-05T00:13:00.920", "Id": "239960", "Score": "2", "Tags": [ "javascript", "performance" ], "Title": "Visualize virus infection against population on a webpage" }
239960
<p>The program below results in a stackoverflow exception in C# for the input provided. I am trying to see if there are any enhancements that can be made to avoid the stack-overflow. </p> <p>When using BFS approach the program works which is obvious as there's no recursion. The BFS approach is also provided below.</p> <pre><code> public class NetworkDelayTimeDFS { Dictionary&lt;int, int&gt; visited; public int NetworkDelayTime(int[][] times, int N, int K) { var graph = new Dictionary&lt;int, List&lt;Tuple&lt;int, int&gt;&gt;&gt;(); visited = new Dictionary&lt;int, int&gt;(); foreach (var t in times) { if (graph.ContainsKey(t[0])) graph[t[0]].Add(new Tuple&lt;int, int&gt;(t[1], t[2])); else graph.Add(t[0], new List&lt;Tuple&lt;int, int&gt;&gt; { new Tuple&lt;int, int&gt;(t[1], t[2]) }); } var keys = graph.Keys.ToList(); foreach (var key in keys) { graph[key] = graph[key].OrderBy(u =&gt; u.Item2).ToList(); } for (int node = 1; node &lt;= N; ++node) visited.Add(node, Int32.MaxValue); DFS(graph, K, 0); var maxTimeTaken = 0; foreach (var item in visited.Values) { if (item == Int32.MaxValue) return -1; maxTimeTaken = Math.Max(maxTimeTaken, item); } return maxTimeTaken; } private void DFS(Dictionary&lt;int, List&lt;Tuple&lt;int, int&gt;&gt;&gt; graph, int destNode, int time) { if (visited[destNode] &lt; time) return; visited[destNode] = time; if (graph.ContainsKey(destNode)) { var neighbours = graph[destNode]; foreach (var neighbour in neighbours) { DFS(graph, neighbour.Item1, time + neighbour.Item2); } } } } </code></pre> <p>Here is the link to the test for which the program encounters Stackoverflow exception:</p> <p><a href="https://github.com/AashishUpadhyay/Codesthenics/blob/master/UnitTestProject/NetworkDelayTimeTests.cs" rel="nofollow noreferrer">https://github.com/AashishUpadhyay/Codesthenics/blob/master/UnitTestProject/NetworkDelayTimeTests.cs</a></p> <p>Check test named <strong>TestMethod5</strong></p> <p>BFS:</p> <pre><code> public class NetworkDelayTimeBFS { public int NetworkDelayTime(int[][] times, int N, int K) { var visited = new Dictionary&lt;int, int&gt;(); var graph = new Dictionary&lt;int, List&lt;Tuple&lt;int, int&gt;&gt;&gt;(); foreach (var t in times) { if (graph.ContainsKey(t[0])) graph[t[0]].Add(new Tuple&lt;int, int&gt;(t[1], t[2])); else graph.Add(t[0], new List&lt;Tuple&lt;int, int&gt;&gt; { new Tuple&lt;int, int&gt;(t[1], t[2]) }); } var queue = new Queue&lt;int&gt;(); visited.Add(K, 0); queue.Enqueue(K); while (queue.Count != 0) { var node = queue.Dequeue(); if (graph.ContainsKey(node)) { foreach (var neighbour in graph[node]) { if (!visited.ContainsKey(neighbour.Item1) || visited[neighbour.Item1] &gt; visited[node] + neighbour.Item2) { if (visited.ContainsKey(neighbour.Item1)) visited[neighbour.Item1] = visited[node] + neighbour.Item2; else visited.Add(neighbour.Item1, visited[node] + neighbour.Item2); queue.Enqueue(neighbour.Item1); } } } } return visited.Count == N ? visited.Max(v =&gt; v.Value) : -1; } } <span class="math-container">```</span> </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-05T01:03:34.133", "Id": "239963", "Score": "1", "Tags": [ "c#" ], "Title": "Looking for any enhancements to avoid a stackoverflow exception in a C# program" }
239963
<p>I wrote some code and I'm trying to get some feedback on it. I'll try to summerize the essential only. I have a function that based on a condition returns a promise or something else:</p> <pre><code>this.isActive = function(){ if(this.disableApplePay &amp;&amp; window.ApplePaySession){ return window.ApplePaySession.canMakePaymentsWithActiveCard(this.merchantId).then(function(response){ return response; }); } return !!(window.ApplePaySession &amp;&amp; window.ApplePaySession.canMakePayments() &amp;&amp; window.ApplePaySession.supportsVersion(3)); } </code></pre> <p>Then I call this function to check <code>isActive()</code> in another few methods like this:</p> <pre><code>Promise.resolve(this.isActive()).then(function(response){ if(response){ //execute code here } }); </code></pre> <p>Is the <code>Promise.resolve()</code> in this case following best practice? Is there a better way to deal with the <code>isActive()</code> function? </p> <p>PS: Let's exclude the async await for the sake of the above example please.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-05T07:47:43.067", "Id": "470676", "Score": "2", "body": "Please let me know the reason at least when you downvote so I can improve my question if needed." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-05T08:21:58.483", "Id": "470677", "Score": "1", "body": "You can find out yourself when you go to the [help] and read _How to ask a good question_. I am not happy with your hypothetical stub code, that's why I downvoted." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-05T08:33:26.673", "Id": "470679", "Score": "0", "body": "@πάνταῥεῖ , but that is like how my code looks like(~99%), I read here https://codereview.stackexchange.com/help/dont-ask about hypothetical code, but I don't know what to do to improve my question code. Should I post the whole real variables and functions? How would that help?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-05T08:34:32.587", "Id": "470680", "Score": "3", "body": "Post real and working code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-05T08:37:18.363", "Id": "470681", "Score": "0", "body": "@πάνταῥεῖ , I updated the question. I hope it's ok now." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-05T17:24:01.850", "Id": "470723", "Score": "0", "body": "One of the problems with this question is that the question doesn't tell us what the code is doing, nor can we figure it out from the code itself." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-05T20:34:29.867", "Id": "470738", "Score": "0", "body": "This is not a reasonable requirement however almost as a hack, you may check if the returned value has a `then` method to decide what you will do next... Highly discouraged though. Please don't do such things." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-06T19:43:47.397", "Id": "470850", "Score": "1", "body": "\"Let's exclude the async await\" Nonononono, no exclusions please. Either you post the real code or you risk missing out. Please keep that in mind for your next question." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-06T19:44:45.690", "Id": "470851", "Score": "1", "body": "\"I'll try to summerize the essential only.\" On Stack Overflow, that's perfect. On Code Review, [we do things differently](https://codereview.meta.stackexchange.com/q/2436/52915). Please keep that in mind on your next question." } ]
[ { "body": "<p>You really don't want a function sometimes returning a promise and sometimes returning a value. That just makes it difficult for the caller. Instead, if you sometimes have a promise to return, then you should always return a promise. </p>\n\n<pre><code>function isActive(){\n if(condition){\n return API.someFunction().then(function(response){\n return response;\n });\n }\n return Promise.resolve(active);\n}\n</code></pre>\n\n<p>Then, your caller can just know that it always returns a promise and they can code accordingly. When you have complexity like this, it's better to encapsulate it in the function itself rather than make every single caller deal with it.</p>\n\n<p>So, the caller can then always and consistently just do:</p>\n\n<pre><code>isActive().then(...).catch(...);\n</code></pre>\n\n<hr>\n\n<p>Also, if you actually have this in your real code:</p>\n\n<pre><code> .then(function(response){\n return response;\n });\n</code></pre>\n\n<p>then, you can remove that entirely and just use this as it generates the exact same result, but is less code:</p>\n\n<pre><code>function isActive(){\n if(condition){\n return API.someFunction();\n }\n return Promise.resolve(active);\n}\n</code></pre>\n\n<p>Both examples return a promise that resolves to <code>response</code>. One is obviously a lot simpler than the other.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-05T09:03:46.453", "Id": "470687", "Score": "0", "body": "@CertainPerformance - Yes, as shown that's superfluous, but I assumed it was a placeholder for some actual code that does something with the response before returning a modified value. I will add a comment to that effect." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-05T07:50:32.673", "Id": "239974", "ParentId": "239973", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "9", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-05T07:31:21.780", "Id": "239973", "Score": "0", "Tags": [ "javascript", "asynchronous", "promise" ], "Title": "Best approach on handling function that returns either a promise or just synchronous code" }
239973
<p>I have two questions.</p> <ol> <li>Does it make sense to test that an event will not be fired?</li> <li>If yes, what is the best way to accomplish that using the <code>xUnit</code> framework?</li> </ol> <p>For example I have a class with a single property <code>Mark</code>,</p> <pre><code> public class Box : INotifyPropertyChanged { private Marking mark = Marking.None; public Marking Mark { get { return mark; } set { mark = value; PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Mark))); } } public event PropertyChangedEventHandler PropertyChanged; } </code></pre> <p>and <em>I want to test</em> that when someone is going to set the value of <code>Mark</code> to the same value as the property points currently, then the <code>PropertyChanged</code> event will not be fired.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-05T12:49:24.867", "Id": "470700", "Score": "1", "body": "[Cross-posted on Stack Overflow](https://stackoverflow.com/q/61041000/1014587)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-05T12:50:53.020", "Id": "470701", "Score": "2", "body": "This question does not match what this site is about. Code Review is about improving existing, working code. The example code that you have posted is not reviewable in this form because it leaves us guessing at your intentions. Unlike Stack Overflow, Code Review needs to look at concrete code in a real context. Please see [Why is hypothetical example code off-topic for CR?](//codereview.meta.stackexchange.com/q/1709)" } ]
[ { "body": "<ol>\n<li>Sound reasonable to test it. It is a logic in your application.</li>\n<li>You can do it without XUnit. You can test it by register to the event and changing a variable called eventWasFired which is initialized to false . Assert that eventWasFired is false. </li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-05T10:40:41.067", "Id": "470694", "Score": "0", "body": "Thanks @shanif but I would like to test that in `xUnit` context." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-05T10:43:29.577", "Id": "470695", "Score": "0", "body": "Found this https://hamidmosalla.com/2020/01/20/xunit-part-3-action-based-assertions-assert-raises-and-assert-throws/" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-05T10:45:13.880", "Id": "470696", "Score": "0", "body": "Well thanks a lot, I'm gonna review that right now. I got an answer on StackOverflow if you're insterested https://stackoverflow.com/a/61041223/9164071" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-05T10:37:17.703", "Id": "239980", "ParentId": "239977", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-05T10:09:01.373", "Id": "239977", "Score": "-2", "Tags": [ "unit-testing", "event-handling", "xunit" ], "Title": "How to test that an event will not be fired in xUnit?" }
239977
<p>I made the following code. It's a simple animation of 'raindrops' falling and splattering once they reach the ground. The images I use can be found here: <a href="https://imgur.com/a/VYV07ef" rel="nofollow noreferrer">https://imgur.com/a/VYV07ef</a></p> <pre><code>import pygame, sys from pygame import locals import random import itertools def listenToQuit(): for event in pygame.event.get(): if event.type == locals.QUIT: pygame.quit() sys.exit() def makeNewDrop(display, drops): # there isa 15% chance we'll make a new drop, each frame x = display.get_width() * random.random() # a random xpostion return RainDrop(x, display, drops) class RainDrop(pygame.sprite.Sprite): img = pygame.image.load('assests/rain_drop.png') def __init__(self, x, display, group): # call the super constructor, and pass in the # group you've created and it is automatically added to the group every # time you create an instance of this class pygame.sprite.Sprite.__init__(self, group) self.y = 0 self.x = x self.fall_step = 5 self.display = display self.die = False self. animation = iter([ pygame.image.load('assests/splatter_1.png'), pygame.image.load('assests/splatter_2.png'), pygame.image.load('assests/splatter_3.png'), pygame.image.load('assests/splatter_4.png') ]) def update(self): self.checkIfShouldDie() self.fall() if self.die: try: self.img = next(self.animation) except StopIteration: self.kill() self.display.blit(self.img, (self.x,self.y)) def fall(self): self.y = self.y + self.fall_step def checkIfShouldDie(self): if self.img.get_rect().bottom + self.y &gt;= self.display.get_height(): self.die = True self.y = self.display.get_height() - self.img.get_rect().bottom - 5 if __name__ == '__main__': pygame.init() drops = pygame.sprite.Group() cooldown = 0 fps = 30 clock = pygame.time.Clock() main_display = pygame.display.set_mode((400,400),0,32) pygame.display.set_caption("rain!") while True: main_display.fill((255,255,255)) if random.random() &gt;= 0.85 and cooldown == 0: # a 15% change we'll make a new drop, each frame # assuming we didn't make a drop in the last few frames drop = makeNewDrop(main_display, drops) # automatically added to the drops group cooldown = cooldown + 5 drops.update() # reduce cooldown cooldown = 0 if cooldown &lt;= 0 else cooldown - 1 listenToQuit() pygame.display.update() clock.tick(30) </code></pre> <p>How can this code be improved? Specifically the part where I iterator over animations and catch the StopIteration error seems very hacky to me. </p>
[]
[ { "body": "<h2>PEP8</h2>\n\n<p>The official Python style guide will suggest that:</p>\n\n<ul>\n<li>there be two newlines between functions at the global scope, and only one newline between functions in the class scope (i.e. <code>check_if_should_die</code>)</li>\n<li>functions be named in lower_snake_case, i.e. <code>listen_to_quit</code></li>\n</ul>\n\n<h2>Hard exit</h2>\n\n<p>Currently, you have a forever-loop that only exits on <code>sys.exit</code>. Instead, simply return a boolean from <code>listenToQuit</code> (which can be called <code>should_quit</code>), and if the return value is true, break out of the loop.</p>\n\n<h2>Abbreviated imports</h2>\n\n<p><code>pygame.sprite.Sprite</code> can just be <code>Sprite</code> if you <code>from pygame.sprite import Sprite</code>.</p>\n\n<h2>Typo</h2>\n\n<p><code>assests</code> -> <code>assets</code></p>\n\n<h2>Generator</h2>\n\n<pre><code> self. animation = iter([\n pygame.image.load('assests/splatter_1.png'),\n pygame.image.load('assests/splatter_2.png'),\n pygame.image.load('assests/splatter_3.png'),\n pygame.image.load('assests/splatter_4.png')\n ])\n</code></pre>\n\n<p>can be</p>\n\n<pre><code>self.animation = iter(\n pygame.image.load(f'assets/splatter_{i}.png')\n for i in range(1, 5)\n)\n</code></pre>\n\n<p>Generally I don't think your <code>iter</code>/<code>StopIteration</code> approach is that bad. That said, you can rework it by changing your outer <code>while True</code> into a <code>for drop in drops</code>, where <code>drops</code> is an iterable through four instances of a drop object tied to a specific asset.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-06T11:02:08.553", "Id": "470777", "Score": "0", "body": "Quick question just to be sure I understand: The last suggestion of `for drop in drops` would work for an animation functionality, but this would not work if I would want this animation to only be the backdrop, and later add more functionality such as listening to keyboard input etc? Thanks for the detailed answer! It's very useful" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-05T15:53:57.077", "Id": "239993", "ParentId": "239982", "Score": "2" } } ]
{ "AcceptedAnswerId": "239993", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-05T11:01:49.717", "Id": "239982", "Score": "4", "Tags": [ "python", "animation", "pygame" ], "Title": "Simple rainfall animation in Pygame" }
239982
<p>In one of my projects I wrote a little tournament platform, but the way I handle participants is a bit messy and I want to clean this up.</p> <p>So in my case a Tournament can have participants, but either a User or a Team can signup to become a participant. A participant now holds a user_id or a team_id in the database, and depending on which is filled I determine if a User is linked to the participant or if it's a team.</p> <p>I rewrote the signup part of my Tournament model to accept both a User or a Team as parameter through am interface and was wondering if this is the correct way to go.</p> <p><strong>ICandidate.php</strong></p> <pre><code>interface ICandidate { public function getName(); public function hasCorrectGamesSet($tournamentGame); } </code></pre> <p><strong>User.php</strong></p> <pre><code>class User implements ICandidate { private $game; public function __construct($game) { $this-&gt;game = $game; } public function getName() { return 'Username'; } public function hasCorrectGamesSet($tournamentGame) { if($this-&gt;game != $tournamentGame){ throw new Exception('Incorrect name'); }; return true; } } </code></pre> <p><strong>Team.php</strong></p> <pre><code>class Team implements ICandidate { private $users; public function __construct($users) { $this-&gt;users = $users; } public function getName() { return 'Teamname'; } public function hasCorrectGamesSet($tournamentGame) { foreach($this-&gt;users as $user){ $user-&gt;hasCorrectGamesSet($tournamentGame); } } } </code></pre> <p><strong>Participant.php</strong></p> <pre><code>class Participant { private $name; private $class; public function setName($name) { $this-&gt;name = $name; } public function setClass($class) { $this-&gt;class = $class; } } </code></pre> <p><strong>Tournament.php</strong></p> <pre><code>class Tournament { private $participants; private $game; public function __construct($game) { $this-&gt;game = $game; } public function signUp(ICandidate $candidate) { $candidate-&gt;hasCorrectGamesSet($this-&gt;game); $participant = new Participant(); $participant-&gt;setName($candidate-&gt;getName()); $participant-&gt;setClass(get_class($candidate)); $this-&gt;participants[] = $participant; } public function getParticipants() { var_dump($this-&gt;participants); } } </code></pre> <p>So with this set, I can signup a User or a Team, do a little check and if that passes, add them as a participant to the tournament.</p> <p><strong>Logic</strong></p> <pre><code>$tournament = new Tournament('fifa'); $user1 = new User('fifa'); $user2 = new User('fifa'); $user3 = new User('fifa'); $user4 = new User('fifa'); $team = new Team([$user2, $user3, $user4]); $tournament-&gt;signUp($user1); $tournament-&gt;signUp($team); $tournament-&gt;getParticipants(); </code></pre> <p>Is this a correct way to implement this and make use of the interface?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-05T14:04:56.883", "Id": "470703", "Score": "1", "body": "In general yes. It's [Composite pattern](https://en.wikipedia.org/wiki/Composite_pattern)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-05T17:30:40.503", "Id": "470724", "Score": "0", "body": "The title of the question does not reflect what the code is doing. Put your concerns in the body of the question. The title should be something like `Tournament signup sheet`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-05T17:59:18.333", "Id": "470727", "Score": "0", "body": "The code does not seem to be doing anything useful. What Is the purpose of the code?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-06T07:11:40.973", "Id": "470765", "Score": "0", "body": "given your teams consist of multiple users, why not just have a team of 1 user, then you can do away with the extra complexity" } ]
[ { "body": "<p>Your code is actually much better than the average. Congrats.</p>\n\n<p>I would change <code>ICandidate</code> to <code>Candidate</code>. No one needs to know if this is an interface, abstract class, concrete class, etc. Don't break encapsulation.</p>\n\n<p>Also, using types makes your code more readable and less error prone.</p>\n\n<p>I wouldn't also use <code>getters</code> and <code>setters</code>. For instance:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>class Participant\n{\n private string $name;\n private string $class;\n\n public function __construct(string $name, string $class)\n {\n $this-&gt;name = $name;\n $this-&gt;class = $class;\n }\n\n public function name(): string\n {\n return $this-&gt;name;\n }\n\n public function class(): string\n {\n return $this-&gt;class;\n }\n}\n</code></pre>\n\n<p>But... do you really need the <code>Participant</code> class? From your example, it's not necessary.</p>\n\n<p>In your <code>Tournament</code> class, <code>$participants</code> is an array of <code>Candidate</code>s. </p>\n\n<p>Ah, I would also use namespaces so I would be able to implement autoloading (<a href=\"https://www.php-fig.org/psr/psr-4/\" rel=\"nofollow noreferrer\">https://www.php-fig.org/psr/psr-4/</a>)</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-14T00:12:35.443", "Id": "240473", "ParentId": "239983", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-05T11:15:00.500", "Id": "239983", "Score": "3", "Tags": [ "php", "object-oriented" ], "Title": "Model tournaments between teams" }
239983
<p>I have implemented a solution for the <strong>knapsack problem</strong> while breaking an item is allowed. I've used the dictionary data structure where I used weight as a key and value per weight as a value. After that, I sorted the dictionary by value and filled the knapsack until there's no space left. </p> <p>Here is my python code -</p> <pre><code>def calculateKnapsack(): userinputNW = list(map(int, input().split())) n = userinputNW[0] weight = userinputNW[1] weightvaluedict = {} revenue = 0 for x in range(n): vw = list(map(int, input().split())) weightvaluedict[vw[1]] = vw[0]/vw[1] weightvaluedict = {k: v for k, v in sorted( weightvaluedict.items(), key=lambda item: item[1], reverse=True)} for k, v in weightvaluedict.items(): if weight == 0: break if k &lt; weight: revenue += k * v weight -= k else: revenue += weight * v weight = 0 return revenue </code></pre> <p>I'm confused if it is an optimal solution or not. I searched online and most of the tutorial used 2D array. I wanted to ensure my code's optimality. Suggestions are welcome.</p> <p>Thanks. And also this is my first question on the Code review platform so please forgive me if I did anything wrong.</p>
[]
[ { "body": "<p>I don't understand what you mean by \"the knapsack problem white fraction is allowed,\" not even if I assume that the word \"white\" should have been \"while\" or \"what\" or \"where\". The whole thing that makes the knapsack problem NP-hard is that you're <em>not</em> allowed to break up a single item into \"fractions.\" So to understand what you meant, I tried to look at the code.</p>\n\n<p>The first thing I do to understand a piece of code is, I look at its function signature. What arguments does the function take? What verbs and prepositions are used in its name? Consider:</p>\n\n<pre><code>def countPrimesUpTo(n):\ndef listPrimesUpTo(n):\ndef printPrimesLessThan(n):\n</code></pre>\n\n<p>Here's your function signature.</p>\n\n<pre><code>def calculateKnapsack():\n</code></pre>\n\n<p>Well, that didn't give me any information at all...!</p>\n\n<p>The second way I try to understand a piece of code is to look at what it does; that is, look at its unit-tests.</p>\n\n<pre><code>assert listPrimesUpTo(10) == [2,3,5,7]\nassert listPrimesUpTo(5) == [5]\nassert listPrimesUpTo(1) == []\n</code></pre>\n\n<p>Here's your unit tests.</p>\n\n<pre><code>pass\n</code></pre>\n\n<p>Okay, I guess I should just give up on understanding what the code is intended to do, and focus on the code itself.</p>\n\n<pre><code> userinputNW = list(map(int, input().split()))\n n = userinputNW[0]\n weight = userinputNW[1]\n</code></pre>\n\n<p>Oh hey! Here's something that looks like function arguments. You could immediately refactor your function into</p>\n\n<pre><code>def computeKnapsack(n, weight):\n</code></pre>\n\n<p>But then I go on and I see there's more input happening later...</p>\n\n<pre><code> weightvaluedict = {}\n for x in range(n):\n vw = list(map(int, input().split()))\n weightvaluedict[vw[1]] = vw[0]/vw[1]\n weightvaluedict = {k: v for k, v in sorted(\n weightvaluedict.items(), key=lambda item: item[1], reverse=True)}\n</code></pre>\n\n<p>So now our knapsack function looks like</p>\n\n<pre><code>def computeKnapsackRevenue(weights, capacity):\n revenue = 0\n for size, value in weights.items():\n if capacity == 0:\n break\n if size &lt; capacity:\n revenue += size * value\n capacity -= size\n else:\n revenue += capacity * value\n capacity = 0\n return revenue\n</code></pre>\n\n<p>and we have some boilerplate user-input code that looks like</p>\n\n<pre><code> num_items, capacity = map(int, input().split())\n weights = {}\n for x in range(num_items):\n v, k = map(int, input().split())\n weights[k] = v / k\n weights = {k: v for k, v in sorted(\n weights.items(), key=lambda kv: kv[1], reverse=True)}\n</code></pre>\n\n<p>That last line isn't doing anything at all. It doesn't matter <em>how</em> you permute the list of items, if all you're doing with the result is stuffing it back into an unsorted <code>dict</code>. So we can erase that line.</p>\n\n<pre><code> num_items, capacity = map(int, input().split())\n weights = {}\n for x in range(num_items):\n v, k = map(int, input().split())\n weights[k] = v / k\n revenue = computeKnapsackRevenue(weights, capacity)\n print(revenue)\n</code></pre>\n\n<p>And there's our program! We might add some unit tests to prove that it does what we expect:</p>\n\n<pre><code> assert computeKnapsackRevenue({10: 8, 10: 9, 10: 10}, 0) == 0\n assert computeKnapsackRevenue({10: 8, 10: 9, 10: 10}, 20) == 190\n assert computeKnapsackRevenue({10: 8, 10: 9, 10: 10}, 25) == 230\n assert computeKnapsackRevenue({10: 8, 10: 9, 10: 10}, 30) == 270\n assert computeKnapsackRevenue({10: 8, 10: 9, 10: 10}, 40) == 270\n assert computeKnapsackRevenue({}, 40) == 0\n</code></pre>\n\n<p>We might even find that it has a bug. :)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-05T15:59:58.507", "Id": "470710", "Score": "0", "body": "The problem is exactly written like this - \"A thief finds much more loot than his bag can fit. Help him to find the most valuable combination of items assuming that any fraction of a loot item can be put into his bag.\" I misspelled the word while." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-05T16:21:55.200", "Id": "470713", "Score": "1", "body": "I tasted again and already found a bug , I'm working on it" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-05T17:46:03.013", "Id": "470725", "Score": "1", "body": "@MahmudulHasan: For future reference, it would have been a good idea to put that problem statement (\"A thief finds...\") at the top of your question." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-05T15:31:24.320", "Id": "239987", "ParentId": "239985", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-05T13:27:42.547", "Id": "239985", "Score": "4", "Tags": [ "python", "algorithm", "hash-map", "knapsack-problem" ], "Title": "Is this an optimal implementation for the knapsack algorithm?" }
239985