body
stringlengths
25
86.7k
comments
list
answers
list
meta_data
dict
question_id
stringlengths
1
6
<p>I'm learning C++ and currently doing Project Euler challenges. The first challenge is the following.</p> <blockquote> <p>If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.</p> <p>Find the sum of all the multiples of 3 or 5 below 1000.</p> </blockquote> <p>I did a quite simple and stupid brute-force implementation by just looping from 1 to 999, checking if its divisible by either 3 or 5 and if it is, sum it with the result variable.</p> <p>Is there any faster/better/cleaner implementation, maybe without a loop or with less division?</p> <pre class="lang-cpp prettyprint-override"><code>#include &lt;iostream&gt; int main(int argc, char *argv[]) { int result(0); for (int i = 1; i &lt; 1000; ++i) { if (!(i % 3 &amp;&amp; i % 5)) { result += i; } } std::cout &lt;&lt; "Result: " &lt;&lt; result &lt;&lt; "\n"; return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-18T11:23:38.023", "Id": "421179", "Score": "9", "body": "The thing about Euler tests is that they are trying to make you think smart. Yes you can brute force this even for large values of `n` but there should be an elegant solution that even a human could do. It is learning these tricks that will help you in later tests were a brute force attack on the problem is not feasible." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-18T14:18:58.873", "Id": "421197", "Score": "3", "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)*." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-19T07:45:24.683", "Id": "421265", "Score": "1", "body": "int result(0); and int result=0; are the same, but the latter is more clear (to me at least)" } ]
[ { "body": "<p>The code is basically fine.</p>\n<p>The if condition is perhaps a little complicated though. To interpret it you have to read &quot;if not ((i is not a multiple of 3) and (i is not a multiple of 5))&quot;, which is a double negative.</p>\n<p>Given the problem statement, we'd expect something more like &quot;if (i is a multiple of 3) or (i is a multiple of 5)&quot;, so:</p>\n<pre><code>if ((i % 3 == 0) || (i % 5 == 0))\n</code></pre>\n<p>Nitpicking:</p>\n<ul>\n<li>If we don't need <code>argc</code> and <code>argv</code>, we can declare main as <code>int main()</code> with no arguments.</li>\n<li>The <code>return 0;</code> at the end of main happens automatically in C++, so we don't have to write it ourselves.</li>\n</ul>\n<hr />\n<p>Note that <a href=\"https://adamdrake.com/an-unreasonably-deep-dive-into-project-euler-problem-1.html\" rel=\"noreferrer\">there exists an arithmetic solution to the problem</a>, which is much faster (it could even be done at compile-time in C++).</p>\n<blockquote>\n<p>We want to sum all the multiples of 3 or 5 less than 1000. We can think about the sequence of multiples of 3 as <code>(3, 6, 9, 12, 15, ..., 999)</code>, which is the same as <code>3 * (1, 2, 3, 4, 5, ..., 333)</code>. [...]</p>\n<p>Such a sequence, where the difference between each number is constant, is called a finite arithmetic progression [and the sum is] a finite arithmetic series. The formula for the sum is <code>1/2 * n * (a_1 + a_n)</code>. where n is the number of terms being added, a_1 is the first element in the sequence, and a_n is the last element in the sequence.</p>\n</blockquote>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-18T10:48:47.440", "Id": "421177", "Score": "3", "body": "Even the brute-force formula could easily be done at compile-time, though it's slightly more unwieldy." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-18T12:15:46.220", "Id": "421182", "Score": "1", "body": "Is there a difference in speed by not adding `argv` and `argc`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-18T13:45:37.213", "Id": "421193", "Score": "0", "body": "@o2640110 No there is not. :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-19T08:04:34.830", "Id": "421267", "Score": "1", "body": "The arithmetic solution could be done at compile time, or even worked out on a 4-op calculator." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-21T03:21:04.200", "Id": "421444", "Score": "0", "body": "With the arithmetic solution, you would have to somehow make sure not to count multiples of both 3 and 5 twice. With the brute-force solution, this wouldn't happen." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-18T09:48:14.417", "Id": "217664", "ParentId": "217660", "Score": "23" } }, { "body": "<p>Yes, there are ways to do this that avoid most of the divisions, and are probably faster as well.</p>\n\n<p>Let's start with a simplified version of the problem: add up all the multiples of 3.</p>\n\n<p>Now, you could do a simplified version of what you've written:</p>\n\n<pre><code>int sum = 0;\n\nfor (int i=1; i&lt;1000; i++)\n if (i % 3 == 0)\n sum += i;\n</code></pre>\n\n<p>...but we know up front that 1 and 2 aren't multiples of three. We can generate all multiples of three by counting by 3's:</p>\n\n<pre><code>int sum = 0;\n\nfor (int i=0; i&lt;1000; i += 3)\n sum += i;\n</code></pre>\n\n<p>Obviously enough, we can do the same thing for multiples of 5:</p>\n\n<pre><code>int sum = 0;\n\nfor (int i=0; i&lt;1000; i += 5)\n sum += i;\n</code></pre>\n\n<p>But if we do both in succession:</p>\n\n<pre><code>int sum = 0;\n\nfor (int i=0; i&lt;1000; i += 3)\n sum += i;\n\nfor (int i=0; i&lt;1000; i += 5)\n sum += i;\n</code></pre>\n\n<p>...we'll get the wrong answer. The problem now is that if a number is a multiple of <em>both</em> 3 and 5 (e.g., 15) we've counted it twice. There are a few ways we can avoid that. One is to have the second loop add <code>i</code> to the sum if and only if <code>i</code> is not a multiple of 3. </p>\n\n<pre><code>for (int i=0; i&lt; 1000; i += 5)\n if (i % 3 != 0)\n sum += i;\n</code></pre>\n\n<p>Another is to initially add those, but then add a third loop that generates only the numbers that are multiples of both 3 and 5, and subtracts those from the overall result:</p>\n\n<pre><code>int product = 3 * 5;\n\nfor (int i = 0; i &lt; 1000; i += product)\n sum -= i;\n</code></pre>\n\n<p>Since you're (apparently) more interested in learning programming than in learning math, I'll only sketch out the next step. There are ways to avoid doing those loops at all though. What we're really doing is (for two different values of N) summing a series of 1N + 2N + 3N + 4N + ...</p>\n\n<p>Using the distributive property, we can turn that into <code>N * (1 + 2 + 3 + 4 + ...)</code>. Gauss invented an easy way to sum a series like <code>1 + 2 + 3 + 4 + ...</code>, so what we need to do is compute the number of terms of that series we need for each of 3 and 5, compute them, multiply by 3 and 5 respectively, and add together the results. Then do the same for multiples of 15, and subtract that from the result. The number of terms in each series we need will be the upper limit divided by the N for that series--so for multiples of 3, we have 1000/3 terms, and for multiples of 5 we have 1000/5 terms.</p>\n\n<p>So, we can compute the final value as:</p>\n\n<pre><code>3 * gauss_sum(1000/3) + 5 * gauss_sum(1000/5) - 15 * gauss_sum(1000/15)\n</code></pre>\n\n<p>...and we're left with no loops at all, so we can compute the correct value for any upper limit (up to what fits in an <code>unsigned long long</code>, anyway) in constant time.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-18T15:06:38.440", "Id": "217675", "ParentId": "217660", "Score": "19" } }, { "body": "<p>The one bit that is absolutely not fine is this line:</p>\n\n<pre><code>if (!(i % 3 &amp;&amp; i % 5))\n</code></pre>\n\n<p>It is clever, and clever is <em>bad</em>. The question was about \"all integers that are multiples of 3 or 5.\" So write that:</p>\n\n<pre><code>if (i % 3 == 0 || i % 5 == 0)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-19T12:51:21.633", "Id": "421294", "Score": "1", "body": "+1! Any time you write code that has to be *deciphered*, you should change it to something that can be *read*. To be honest, half the time, I'd take it a step further, and actually put i%3 into a variable: divisibleBy3. That way, the IF statement is simply if (divisbleBy3 || divisibleBy5) - doesn't get much more readable than that." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-19T18:37:39.090", "Id": "421327", "Score": "2", "body": "@Kevin: Another possibility would be to define a lambda like: `auto divisibleBy = [](int x, int y) { return x % y == 0; }; ` Then you'd just use: `if (divisibleBy(i, 3) || divisibleBy(i, 5)) ...`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-20T06:52:02.793", "Id": "421359", "Score": "0", "body": "Just to add to this, you can see the compiler output here. \nhttps://godbolt.org/z/lAws-Z At least for this compiler (clang 7, fully optimised) *the two versions compile to exactly the same thing*. That all to say, it's OK to use the readable version over what you expect is more efficient: the compiler knows better than almost any human programmer what will be efficient." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-18T21:50:48.450", "Id": "217704", "ParentId": "217660", "Score": "12" } }, { "body": "<p>As you were asking for <em>\"less division\"</em>... Here's a different approach with <strong>absolutely no division, multiplication or modulo operations</strong>. We have two counters <code>t</code> (for increment three) and <code>f</code> (for increment five), and update them in a single <code>while</code> loop. Due to the increments it's guaranteed <code>t</code> and <code>f</code> will always be numbers divisible by 3 resp. 5. Now we just have to pick which counter to update (the lower one), and to handle the case when both counters occasionally meet :)</p>\n\n<p>(You can avoid the <code>std::min</code>-line and put the addition to <code>result</code> into the <code>if/else if/else</code>-part, but with this it's easier to understand what happens.)</p>\n\n<pre><code>#include &lt;iostream&gt;\n\nint main() {\n unsigned t=0, f=0;\n unsigned result=0;\n while (t&lt;1000) {\n result+=std::min(t, f);\n\n if (t&lt;f) t+=3;\n else if (f&lt;t) f+=5;\n else { // f==t\n t+=3;\n f+=5;\n }\n } \n std::cout &lt;&lt; \"Result: \" &lt;&lt; result &lt;&lt; std::endl;\n return(0);\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-20T16:48:57.667", "Id": "421396", "Score": "1", "body": "You know that `return` is not a function? That can be crucial in C++ when the return-type is deduced with `decltype(auto)`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-20T17:11:41.793", "Id": "421399", "Score": "0", "body": "Yes I know that. @Deduplicator, do you have an example where brackets actually do change the return type?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-20T19:02:21.260", "Id": "421421", "Score": "0", "body": "As I said, [additional parentheses around the return-expression are meaningful when the return-type is deduced with `decltype(auto)`](http://coliru.stacked-crooked.com/a/ddb59d725a3d2cfc)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-20T22:18:16.263", "Id": "421433", "Score": "0", "body": "Ok, so the deduced function types indeed would be `T()` vs `T&()` in your example - actually different in regards to `std::type_info`, but only in this aspect - and neither deduced type is technically incorrect or leads to erroneous behaviour. As a consequence, I wouldn't encourage comparing type info obtained with `auto` :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-20T22:37:57.067", "Id": "421435", "Score": "0", "body": "`std::type_info` ([returned by `typeid`](https://en.cppreference.com/w/cpp/language/typeid)) only knows fully decayed types. And if `i` was not a global, but e.g. a local or parameter, the difference between a copy and a reference may be more relevant." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-21T10:12:45.063", "Id": "421468", "Score": "0", "body": "Fascinating - I created a [place](https://codereview.stackexchange.com/questions/217824/c-return-brackets-considered-harmful) for that interesting question :)" } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-20T16:40:06.357", "Id": "217785", "ParentId": "217660", "Score": "1" } } ]
{ "AcceptedAnswerId": "217664", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-18T08:59:45.230", "Id": "217660", "Score": "19", "Tags": [ "c++", "beginner", "programming-challenge" ], "Title": "Project Euler #1 in C++" }
217660
<p>I am taking efforts to solve problem <a href="https://leetcode.com/problems/k-th-symbol-in-grammar/" rel="nofollow noreferrer">K-th Symbol in Grammar - LeetCode</a></p> <blockquote> <ol start="779"> <li>K-th Symbol in Grammar</li> </ol> <p>On the first row, we write a <code>0</code>. Now in every subsequent row, we look at the previous row and replace each occurrence of <code>0</code> with <code>01</code>, and each occurrence of <code>1</code> with <code>10</code>.</p> <p>Given row <code>N</code> and index <code>K</code>, return the <code>K</code>-th indexed symbol in row <code>N</code>. (The values of <code>K</code> are 1-indexed.) (1 indexed).</p> <pre><code>Examples: Input: N = 1, K = 1 Output: 0 Input: N = 2, K = 1 Output: 0 Input: N = 2, K = 2 Output: 1 Input: N = 4, K = 5 Output: 1 Explanation: row 1: 0 row 2: 01 row 3: 0110 row 4: 01101001 </code></pre> <p><strong>Note:</strong></p> <ol> <li><code>N</code> will be an integer in the range <code>[1, 30]</code>.</li> <li><code>K</code> will be an integer in the range <code>[1, 2^(N-1)]</code>.</li> </ol> </blockquote> <p>My solution </p> <pre><code>class Solution: def kthGrammar(self, N: int, K: int) -&gt; int: #replace function def replace(row: "List[int]") -&gt; "List[int]": """ rtype: row """ for i in range(len(row)): print(row[i]) if row[i] == 0: #0 -&gt; 01 row.insert(2*i+1, 1) elif row[i] == 1: #1 -&gt; 10 row.insert(2*i+1, 0) return row #helper function def helper(N: int) -&gt; "List(int)": """ rtype:the last row """ #error case if N &lt; 1: return [] #base case if N == 1: res = [0] return res elif N &gt; 1: return replace(helper(N-1)) #error cases if N &lt; 1 or K &lt; 1 or K &gt; 2**(N-1) : return None #recur row = helper(N) #logging.debug(f"row: {row}") return row[K-1] </code></pre> <p>Unfortunately it reported Time Limit Exceeded </p> <blockquote> <p>Last executed input: 30 434991989</p> </blockquote> <p>Review my solution:</p> <ol> <li>employed tail recursion <code>return replace(helper(N-1))</code> </li> <li>did not create a new row </li> </ol> <p>It's a relatively fine solution, </p> <p>What might be the reason of TLE?</p>
[]
[ { "body": "<p>It makes little difference how the row is constructed, the problem is intentionally designed such that constructing the row at all will lead to TLE. Consider that for N=30, the row would have 2<sup>29</sup> elements, that's no good. This is usually the case with competitive programming problems, they are made to make the straightforward solutions fail, that is what makes it competitive.</p>\n\n<p>There are a few ways you could go about solving it, for example, you could recognize that the sequence produced is the <a href=\"https://en.wikipedia.org/wiki/Thue%E2%80%93Morse_sequence\" rel=\"nofollow noreferrer\">Thue-Morse sequence</a>, which has a simple formula to calculate an element at a given index without generating the whole sequence up to that index. The result does not depend on N.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-18T09:58:19.447", "Id": "217665", "ParentId": "217663", "Score": "0" } } ]
{ "AcceptedAnswerId": "217665", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-18T09:20:47.373", "Id": "217663", "Score": "1", "Tags": [ "python", "programming-challenge", "time-limit-exceeded" ], "Title": "Time limit exceeded in K-th symbol in Grammar (LeetCode)" }
217663
<p>I've finally committed to moving to Python 3 from MATLAB. I'm currently porting my MATLAB code, and I'm sure I'm missing a lot of common best-practices.</p> <p>For reference, I'm simulating a <em>spring-loaded inverted pendulum</em> (SLIP) model, which is commonly used to model human running. The system has <em>hybrid dynamics</em>, meaning the governing ODEs switch discretely (between stance and flight). Hence, the <code>step</code> function wraps solving the ODEs.<br> The simulation is eventually used in brute-force search (or in any case with a large number of rollouts), so performance suggestions are particularly useful.</p> <p>I've taken a functional approach rather than making classes, partly because of issues I ran into with setting event properties, and partly for convenience. Below is the code with all the functions related to this specific model (other spring-mass models with different dynamics will be added eventually). Below that is a script to run everything.</p> <pre class="lang-py prettyprint-override"><code>import numpy as np import scipy.integrate as integrate def pMap(x,p): ''' Wrapper function for step function, returning only x_next, and -1 if failed Essentially, the Poincare map. ''' sol = step(x,p) return sol.y[:,-1], sol.failed def step(x,p): ''' Take one step from apex to apex/failure. returns a sol object from integrate.solve_ivp, with all phases ''' # TODO: properly update sol object with all info, not just the trajectories # take one step (apex to apex) # the "step" function in MATLAB # x is the state vector, a list or np.array # p is a dict with all the parameters # set integration options x0 = x max_time = 5 t0 = 0 # starting time # FLIGHT: simulate till touchdown events = [lambda t,x: fallEvent(t,x,p), lambda t,x: touchdownEvent(t,x,p)] for ev in events: ev.terminal = True sol = integrate.solve_ivp(fun=lambda t, x: flightDynamics(t, x, p), t_span = [t0, t0+max_time], y0 = x0, events=events, max_step=0.01) # STANCE: simulate till liftoff events = [lambda t,x: fallEvent(t,x,p), lambda t,x: liftoffEvent(t,x,p)] for ev in events: ev.terminal = True events[1].direction = 1 # only trigger when spring expands x0 = sol.y[:,-1] sol2 = integrate.solve_ivp(fun=lambda t, x: stanceDynamics(t, x, p), t_span = [sol.t[-1], sol.t[-1]+max_time], y0 = x0, events=events, max_step=0.0001) # FLIGHT: simulate till apex events = [lambda t,x: fallEvent(t,x,p), lambda t,x: apexEvent(t,x,p)] for ev in events: ev.terminal = True x0 = resetLeg(sol2.y[:,-1],p) sol3 = integrate.solve_ivp(fun=lambda t, x: flightDynamics(t, x, p), t_span = [sol2.t[-1], sol2.t[-1]+max_time], y0 = x0, events=events, max_step=0.01) # concatenate all solutions sol.t = np.concatenate((sol.t,sol2.t,sol3.t)) sol.y = np.concatenate((sol.y,sol2.y,sol3.y),axis=1) sol.t_events += sol2.t_events + sol3.t_events # TODO: mark different phases for fail_idx in (0,2,4): if sol.t_events[fail_idx].size != 0: # if empty sol.failed = True break else: sol.failed = False # TODO: clean up the list return sol def resetLeg(x,p): x[4] = x[0]+np.sin(p['aoa'])*p['resting_length'] x[5] = x[1]-np.cos(p['aoa'])*p['resting_length'] return x def flightDynamics(t,x,p): # code in flight dynamics, xdot_ = f() return np.array([x[2], x[3], 0, -p['gravity'], x[2], x[3]]) def stanceDynamics(t, x,p): # stance dynamics # energy = computeTotalEnergy(x,p) # print(energy) alpha = np.arctan2(x[1]-x[5] , x[0]-x[4]) - np.pi/2.0 leg_length = np.sqrt( (x[0]-x[4])**2 + (x[1]-x[5])**2 ) xdotdot = -p["stiffness"]/p["mass"]*(p["resting_length"] - leg_length)*np.sin(alpha) ydotdot = p["stiffness"]/p["mass"]*(p["resting_length"] - leg_length)*np.cos(alpha) - p["gravity"] return np.array([x[2], x[3], xdotdot, ydotdot, 0, 0]) def fallEvent(t,x,p): ''' Event function to detect the body hitting the floor (failure) ''' return x[1] fallEvent.terminal = True # TODO: direction def touchdownEvent(t,x,p): ''' Event function for foot touchdown (transition to stance) ''' # x[1]- np.cos(p["aoa"])*p["resting_length"] (which is = x[5]) return x[5] touchdownEvent.terminal = True # no longer actually necessary... # direction def liftoffEvent(t,x,p): ''' Event function to reach maximum spring extension (transition to flight) ''' return ((x[0]-x[4])**2 + (x[1]-x[5])**2) - p["resting_length"]**2 liftoffEvent.terminal = True liftoffEvent.direction = 1 def apexEvent(t,x,p): ''' Event function to reach apex ''' return x[3] apexEvent.terminal = True def computeTotalEnergy(x,p): # TODO: make this accept a trajectory, and output parts as well return (p["mass"]/2*(x[2]**2+x[3]**2) + p["gravity"]*p["mass"]*(x[1]) + p["stiffness"]/2* (p["resting_length"]-np.sqrt((x[0]-x[4])**2 + (x[1]-x[5])**2))**2) </code></pre> <p>Script to run an example step: </p> <pre><code>from slip import * import numpy as np import matplotlib.pyplot as plt p = {'mass':80.0, 'stiffness':8200.0, 'resting_length':1.0, 'gravity':9.81, 'aoa':1/5*np.pi} # aoa stands for angle_of_attack x0 = [0, 0.85, 5.5, 0, 0, 0] x0 = resetLeg(x0,p) p['total_energy'] = computeTotalEnergy(x0,p) sol = step(x0,p) plt.plot(sol.y[0],sol.y[1], color='orange') plt.show() </code></pre> <p>I'm aware my docstrings are not up to spec, and that's something on my todo list already. If you're interested, the code repo is <a href="https://github.com/sheim/slippy/tree/272a2d4f1d6efe0e4215847866ca3a223f4e7f53" rel="nofollow noreferrer">here</a>, and the code I'm porting was used for this <a href="https://arxiv.org/abs/1806.08081" rel="nofollow noreferrer">paper</a>.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-18T12:36:08.160", "Id": "421183", "Score": "0", "body": "Welcome to Code Review! For what Python version did you write this?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-18T12:51:38.383", "Id": "421184", "Score": "0", "body": "Thanks, edited the title: python3" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-18T13:07:45.013", "Id": "421186", "Score": "1", "body": "The first code block is contained in the file `slip.py`, right? And what is `aoa`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-18T13:33:10.617", "Id": "421190", "Score": "1", "body": "Yes, the first codeblock is in slip.py.\n`aoa` is shorthand for \"angle of attack\", which started being really long..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-18T18:11:08.747", "Id": "421221", "Score": "1", "body": "What is `x`? It looks like some vector in a configuration space? I suggest that you explain what the components of `x` represent." } ]
[ { "body": "<h2>Style</h2>\n\n<p>Your code looks quite good in general, but there is always something to nitpick on, isn't it?</p>\n\n<p>Python comes with an official <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">Style Guide</a>, often just called PEP8. It has quite an extensive collection of style best practices you should follow in Python.</p>\n\n<p>I think one of the most often cited \"rules\" is to use <code>snake_case</code> for variable and function names. You seem to follow that partly, since your variable names are written in <code>snake_case</code> while your function names use <code>camelCase</code>. I personally prefer snake case because it blends more nicely with the rest of the Python and NumPy/SciPy names.</p>\n\n<p>Another rule (appropriately titled <a href=\"https://www.python.org/dev/peps/pep-0008/#whitespace-in-expressions-and-statements\" rel=\"nofollow noreferrer\">Whitespace in Expressions and Statements</a> - <a href=\"https://www.python.org/dev/peps/pep-0008/#pet-peeves\" rel=\"nofollow noreferrer\">Pet Peeves</a>), I personally consider as more \"essential\" than the previous one, is to put a space after you have written a <code>,</code>, e.g. while listing function arguments. It helps to avoid visual clutter IMHO. E.g.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>p = {'mass':80.0, 'stiffness':8200.0, 'resting_length':1.0, 'gravity':9.81,\n'aoa':1/5*np.pi} # aoa stands for angle_of_attack\nx0 = [0, 0.85, 5.5, 0, 0, 0]\nx0 = resetLeg(x0,p)\np['total_energy'] = computeTotalEnergy(x0,p)\nsol = step(x0,p)\n\nplt.plot(sol.y[0],sol.y[1], color='orange')\nplt.show()\n</code></pre>\n\n<p>would become</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>p = {'mass': 80.0, 'stiffness': 8200.0, 'resting_length': 1.0, 'gravity': 9.81,\n 'aoa': 1/5*np.pi} # aoa stands for angle_of_attack\nx0 = [0, 0.85, 5.5, 0, 0, 0]\nx0 = resetLeg(x0, p)\np['total_energy'] = computeTotalEnergy(x0, p)\nsol = step(x0, p)\n\nplt.plot(sol.y[0], sol.y[1], color='orange')\nplt.show()\n</code></pre>\n\n<p>As you can see I also added some indentation to the parameter dictionary defintion to make it more clear which parts belong together. This effect can also be nicely shown in the body of <code>step</code>, where you could go from</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>sol2 = integrate.solve_ivp(fun=lambda t, x: stanceDynamics(t, x, p),\nt_span = [sol.t[-1], sol.t[-1]+max_time], y0 = x0,\nevents=events, max_step=0.0001)\n</code></pre>\n\n<p>to</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>sol2 = integrate.solve_ivp(\n fun=lambda t, x: stanceDynamics(t, x, p),\n t_span=[sol.t[-1], sol.t[-1]+max_time],\n y0=x0, events=events, max_step=0.0001\n)\n</code></pre>\n\n<p>I think it's hard to argue that this does not look more easy to read.</p>\n\n<p>Since you do not try to rename the <code>integrate</code> submodule from SciPy to something shorter, there is no need to use the <code>from ... import ... as ...</code> syntax. Instead you could just use <code>from scipy import integrate</code>.</p>\n\n<p>The last thing I would like to talk about here in this section is documentation. You have already mentioned that this is on your to-do list, and it definitely should be. The official Style Guide has a nice concise <a href=\"https://www.python.org/dev/peps/pep-0008/#documentation-strings\" rel=\"nofollow noreferrer\">section on that topic</a>, too, but since your specifically working in the scientific Python stack, I think it might be worth pointing you to the <a href=\"https://numpydoc.readthedocs.io/en/latest/format.html\" rel=\"nofollow noreferrer\">documentation style used in NumPy</a> and SciPy. Using this docstyle for step would yield something like:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def step(x, p):\n '''\n Take one step from apex to apex/failure.\n\n Parameters\n ----------\n x : array_like\n state vector with 6 elements\n p : dict\n physical parameters used in the differential equations\n\n Returns\n -------\n object\n a solution object from scipy.integrate.solve_ivp with all phases\n '''\n # your code here\n</code></pre>\n\n<p>Elaborating further on this topic would clearly be to much for this review, so please read the ressources linked above to get more information.</p>\n\n<h2>Performance</h2>\n\n<p>Solving differential equations is not my area of expertise, so there are probably way more fundamental changes other members of the community can come up with in order to help you. I will nevertheless try to give you some insights I gained while working with your code.</p>\n\n<p>I did some profiling on your code using the <a href=\"https://docs.python.org/3/library/profile.html\" rel=\"nofollow noreferrer\">cProfile module</a> from Python, and, as one might already has expected, most of the time is spent on numerically solving the ODEs in SciPy (I think I saw some Runge-Kutta pop op here and there). Furthermore, the profiler told me that solving the stance dynamics takes most of the time outside of the SciPy backend out of the three solutions. That was in line with my expectations since that's the call to <code>integrate.solve_ivp</code> where <code>max_step</code> is two orders of magnitude smaller. With your other parameters that lead to around <code>13610</code> calls to <code>stanceDynamics</code> (through the lambda expression of course). So that was my first point to look at.</p>\n\n<p>The first micro-optimization I came up with was to replace <code>leg_length = np.sqrt((x[0]-x[4])**2 + (x[1]-x[5])**2)</code> with the well known <code>hypot</code> function found in Python's <a href=\"https://docs.python.org/3/library/math.html#math.hypot\" rel=\"nofollow noreferrer\">math module</a> as well as in <a href=\"https://docs.scipy.org/doc/numpy/reference/generated/numpy.hypot.html\" rel=\"nofollow noreferrer\">NumPy</a> to form <code>leg_length = np.hypot(x[0]-x[4], x[1]-x[5])</code>. The effects where minuscule, but that was also within my expectations. </p>\n\n<p>So what to do next? I recently got to know (read: no expert here!) a Python package called <a href=\"http://numba.pydata.org/\" rel=\"nofollow noreferrer\">Numba</a> which allows just-in-time compilation of Python code in order to improve performance, especially if Python code is called within tight loops. Great plus: it's quite easy to use (most of the time) and works on Python code as well as with NumPy. With a little help Numba seems reasonable capable to deduce the datatype of parameters you put into a function on it's own. I went from your original code</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def stanceDynamics(t, x, p):\n alpha = np.arctan2(x[1]-x[5] , x[0]-x[4]) - np.pi/2.0\n leg_length = np.sqrt((x[0]-x[4])**2 + (x[1]-x[5])**2)\n xdotdot = -p[\"stiffness\"]/p[\"mass\"]*(p[\"resting_length\"] - leg_length) * np.sin(alpha)\n ydotdot = p[\"stiffness\"]/p[\"mass\"]*(p[\"resting_length\"] - leg_length)*np.cos(alpha) - p[\"gravity\"]\n return np.array([x[2], x[3], xdotdot, ydotdot, 0, 0])\n</code></pre>\n\n<p>to the following</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>import numba as nb\n\n@nb.jit\ndef stanceDynamics2(t, x, stiffness, mass, resting_length, gravity):\n alpha = np.arctan2(x[1] - x[5], x[0] - x[4]) - np.pi / 2.0\n leg_length = np.hypot(x[0]-x[4], x[1]-x[5])\n xdotdot = -stiffness / mass * (resting_length - leg_length) * np.sin(alpha)\n ydotdot = stiffness / mass * (resting_length - leg_length) * np.cos(alpha) - gravity\n return np.array([x[2], x[3], xdotdot, ydotdot, 0, 0])\n</code></pre>\n\n<p>As you can see, the dictionary vanished from the function signature and was replaced by the plain values in order to help Numba deduce the type (and save some dictionary lookups). You can see the result of this when looking at the profiler output (10 repetitions for each variant):</p>\n\n<pre class=\"lang-none prettyprint-override\"><code> ncalls tottime percall cumtime percall filename:lineno(function)\n 136100 2.985 0.000 3.550 0.000 slip.py:102(stanceDynamics)\n 136100 0.565 0.000 0.565 0.000 slip.py:115(stanceDynamics2)\n</code></pre>\n\n<p>In the overall timing averaged over ten runs that gives you a performance gain of about 25-30% (or about ~240ms in absolute values) on my not so powerful laptop<sup>1</sup> here. Your results may vary.</p>\n\n<p>As I said, there is possibly a lot more to gain here, but I would consider this at least as a respectable achievement for the amount of effort needed to implement those changes.</p>\n\n<hr>\n\n<p><sup>1</sup> Intel Core i5 460M, Python 3.7.3 [MSC v.1915 64 bit (AMD64)] :: Anaconda, Inc. on win32</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-18T21:42:28.957", "Id": "421233", "Score": "0", "body": "Two things I would suggest: (1) create named arguments that default to all the functions that are called, and initialize them to the dotted values `def stanceDynamics(..., atan2=np.arctan2, hypot=np.hypot, sin=np.sin, cos=np.cos, array=np.array)`; and (2) aggressively pull out common sub-expressions into local variables: anything that is used more than once should move into a local." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-18T22:23:32.587", "Id": "421238", "Score": "0", "body": "@AustinHastings: Would these hints apply to the \"standard\" version or to Numba? I can't see any real difference with (1) (standard & Numba) and (2) seems to make it worse with Numba." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-18T22:33:39.217", "Id": "421239", "Score": "0", "body": "they are for the standard version. I don't have experience with Numba." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-18T20:53:34.543", "Id": "217697", "ParentId": "217668", "Score": "5" } }, { "body": "<p>Inspired by @Alex's answer, I did some profiling and simple timing of your code, and some changes that seemed \"obvious\" to me.</p>\n\n<p>My environment for this is a 32-bit laptop that is old enough to have a driver's license, running python 3.7 on Windows. <strong>Note:</strong> Because of this, it's quite likely that your performance will differ from mine. Verify these results, it's important! </p>\n\n<p>I downloaded <code>scipy</code> for this, but I don't have any real knowledge of what you're doing. Also, at this point it's pretty late, so I'm not as smart as I was a few hours ago. Forgive me if I'm incoherent.</p>\n\n<p>I created modified versions of your main function, <code>step</code>. I'll describe the changes, and the result, then past in the code at the bottom for you to try to reproduce my results.</p>\n\n<pre><code>]$ python test.py -t\nStart: (N/A) 1555646668200\nDone orig: (1466) 1555646669666\nDone const True: (1404) 1555646671070\nDone const_lookup True: (1373) 1555646672443\nDone const_lookup_cse True: (1310) 1555646673753\nDone const_lookup_cse2 True: (1264) 1555646675017\nDone const_lookup_cse2_ary2 False: (1217) 1555646676234\n</code></pre>\n\n<p>The numbers in parens are elapsed milliseconds to run the <code>step_</code> function, so <strong>lower is better.</strong> The trailing numbers are current-time-in-ms, which you should ignore. The boolean value indicates whether the returned result matches the original <code>step</code> result -- note that <code>_ary2</code> is <code>False</code>.</p>\n\n<p>The names get longer because I was adding more changes, except for the <code>_ary</code> version, which I suppressed because it didn't work right. (I left it in, so you can see a failed example. But see the comments on <code>_ary2</code> first.)</p>\n\n<p>The functions are named <code>step_XXX</code> where XXX is whatever appears in the table above (e.g., <code>step_const_lookup_cse</code>). The parts of the name indicate what I tried to do in that iteration.</p>\n\n<h3><code>orig</code> (aka, <code>step</code>)</h3>\n\n<p>This is the original. Nothing to see here, move along.</p>\n\n<h3><code>step_const</code></h3>\n\n<p>In this version, I moved all the event and dynamics functions inside the <code>step</code> function as nested functions. I unpacked the <code>p[]</code> dictionary into variables (with uppercased names, so I called them constants) that don't change during the execution. </p>\n\n<p>For example: <code>GRAVITY = p[\"gravity\"]</code></p>\n\n<p>I then rewrote the various helpers to use these names instead of dictionary lookups. </p>\n\n<h3><code>const_lookup</code></h3>\n\n<p>In this version, I tried to remove lookups where possible. I did this by storing names into named-arguments with default values. Thus, for example, I would have a function with a parameter list like <code>(..., array=np.array)</code> so that the <code>array</code> named parameter could be used instead of a lookup of <code>np.array</code> each time.</p>\n\n<h3><code>const_lookup_cse</code></h3>\n\n<p>This was my first attempt at Common-Subexpression-Elimination. In general, I tried to eliminate repeated computations of the same result by storing results in local variables.</p>\n\n<h3><code>const_lookup_cse2</code></h3>\n\n<p>This is an extended version of <code>_cse</code> above. There aren't many changes, but not for lack of trying. </p>\n\n<p>One thing I tried was to \"unpack\" the <code>x[]</code> array into variables <code>x0, x1, ..., x5</code> in functions that used them. This <em>totally didn't work for me,</em> but it might be worth trying for you. That is, instead of expressions like <code>x[1] - x[5]</code> I used <code>x1 - x5</code>. I was surprised at how bad the performance was, so I quickly undid that change and want for some simpler ones.</p>\n\n<h3><code>const_lookup_cse2_ary2</code></h3>\n\n<p>I used the <code>cProfile</code> profiler to investigate the performance of various functions. There is a lot of time spent in library code, which is \"good\" in the sense that there's work being done and it's not your code.</p>\n\n<p>The dominant functions are related to the <code>stance_dynamics</code> call. One of the non-obvious culprits is <code>np.array</code> so I figured I would try to come up with some alternatives to calling that function.</p>\n\n<p>In my <code>_ary</code> version, which I suppressed, I created a ring of 4 <code>np.arrays</code> that I would alternate through in sequence. Sadly, this performed worse than just constructing the array from scratch each time. Yikes! Also, the results returned were not the same as the original function.</p>\n\n<p>So I tried a different approach, <code>_ary2</code> in which I held a single <code>np.array</code> for each function that returns one, and reset the values inside the array. This gets improved performance, but again, <strong>the results are not the same.</strong></p>\n\n<p>Now, here's the important part: I have no understanding of what you are doing. So it may be that the different results don't matter. If, for example, the only time the returned <code>np.array</code> is important is immediately after it is returned, then the overall results might be valid even though the details are different. So I left this in. On the other than, if the integration solver is referring back to previous values, and by overwriting the contents of the array I'm screwing those up, then this is an invalid change.</p>\n\n<p>But it's a decent speed-up, so I'm leaving that to you.</p>\n\n<p>One thing I noticed reading the docs for the solver, there's an option to vectorize the function. In that case, instead of an <code>array(n)</code> it takes and returns an <code>array(n, k)</code>. In my ignorance, I don't know if that means it would be a \"growing\" array, with new values being appended, or some other thing. That's up to you to figure out. But if it would let you append the results to the end of an existing array, it might give a similar performance boost.</p>\n\n<h2>Files</h2>\n\n<p>Here's the test driver, <code>test.py</code>, and then the module <code>slip.py</code>:</p>\n\n<h3><code>test.py</code></h3>\n\n<pre><code>import sys\nimport time\n\n#import matplotlib.pyplot as plt\nimport numpy as np\nfrom slip import *\n\n_last_time_ms = 0\ndef timestamp(msg):\n global _last_time_ms\n time_ms = int(round(time.time() * 1000))\n delta = 'N/A' if _last_time_ms == 0 else time_ms - _last_time_ms\n print(f\"{msg}: ({delta}) {time_ms}\")\n _last_time_ms = time_ms\n\n\np = {'mass':80.0, 'stiffness':8200.0, 'resting_length':1.0, 'gravity':9.81,\n'aoa':1/5*np.pi}\n# x0 = [-np.sin(p['aoa'])*p['resting_length'],1.1*p['resting_length'], # body position\n# 5*p['resting_length'],0.0, # velocities\n# 0.0,0.0] # foot position\n\ndef get_x0():\n x0 = [0, 0.85, 5.5, 0, 0, 0]\n x0 = resetLeg(x0, p)\n p['total_energy'] = computeTotalEnergy(x0, p)\n return x0\n\ndef sol_close(a, b):\n return np.allclose(a.t, b.t) and np.allclose(a.y, b.y)\n\nTIMING = ('-t' in sys.argv)\n\nif TIMING:\n run_all = True\n\n timestamp(\"Start\")\n sol = step(get_x0(), p)\n timestamp(\"Done orig\")\n\n if run_all:\n\n x = step_const(get_x0(), p)\n same = sol_close(sol, x)\n timestamp(f\"Done const {same}\")\n\n x = step_const_lookup(get_x0(), p)\n same = sol_close(sol, x)\n timestamp(f\"Done const_lookup {same}\")\n\n x = step_const_lookup_cse(get_x0(), p)\n same = sol_close(sol, x)\n timestamp(f\"Done const_lookup_cse {same}\")\n\n x = step_const_lookup_cse2(get_x0(), p)\n same = sol_close(sol, x)\n timestamp(f\"Done const_lookup_cse2 {same}\")\n\n # Doesn't work. Also, runs slower.\n #x = step_const_lookup_cse2_ary(get_x0(), p)\n #same = sol_close(sol, x)\n #timestamp(f\"Done const_lookup_cse2_ary {same}\")\n\n x = step_const_lookup_cse2_ary2(get_x0(), p)\n same = sol_close(sol, x)\n timestamp(f\"Done const_lookup_cse2_ary2 {same}\")\n\nelse:\n import cProfile\n import pstats\n\n statsfile = 'step_profile'\n\n cProfile.run('step_const_lookup_cse2(get_x0(), p)', statsfile)\n\n p = pstats.Stats(statsfile)\n p.strip_dirs().sort_stats('cumtime').print_stats()\n\n# plt.plot(sol.t,sol.y[0])\n# plt.plot(sol.t,sol.y[1], color='green')\n# plt.plot(sol.t,sol.y[0])\n# plt.plot(sol.y[0],sol.y[1], color='orange')\n# plt.show()\n</code></pre>\n\n<h3><code>slip.py</code></h3>\n\n<pre><code>import math\nimport numpy as np\nimport scipy.integrate as integrate\n\ndef pMap(x,p):\n '''\n Wrapper function for step, returning only x_next, and -1 if failed\n '''\n sol = step(x,p)\n return sol.y[:,-1], sol.failed\n\ndef step_const(x, p):\n AOA = p['aoa']\n GRAVITY = p['gravity']\n MASS = p['mass']\n RESTING_LENGTH = p['resting_length']\n STIFFNESS = p['stiffness']\n TOTAL_ENERGY = p['total_energy']\n\n SPECIFIC_STIFFNESS = STIFFNESS / MASS # FIXME: Is this name right?\n\n # Note: not taken from p[]\n HALF_PI = np.pi / 2.0\n MAX_TIME = 5\n\n # Function definitions: specific to the constants provided in `p`\n\n def apex_event(t, x):\n ''' Event function to reach apex '''\n return x[3]\n apex_event.terminal = True\n\n def fall_event(t, x):\n ''' Event function to detect the body hitting the floor (failure)\n '''\n return x[1]\n fall_event.terminal = True\n\n def flight_dynamics(t, x):\n ''' code in flight dynamics, xdot_ = f() '''\n return np.array([x[2], x[3], 0, -GRAVITY, x[2], x[3]])\n\n def liftoff_event(t, x, RESTING_LENGTH_SQ=RESTING_LENGTH**2):\n ''' Event function for maximum spring extension (transition to flight)\n '''\n return ((x[0]-x[4])**2 + (x[1]-x[5])**2) - RESTING_LENGTH_SQ\n liftoff_event.terminal = True\n liftoff_event.direction = 1\n\n def stance_dynamics(t, x):\n # energy = computeTotalEnergy(x,p)\n # print(energy)\n alpha = np.arctan2(x[1]-x[5], x[0]-x[4]) - HALF_PI\n leg_length = np.sqrt((x[0] - x[4]) ** 2 + (x[1] - x[5]) ** 2)\n xdotdot = -SPECIFIC_STIFFNESS * (RESTING_LENGTH - leg_length) \\\n * np.sin(alpha)\n ydotdot = SPECIFIC_STIFFNESS * (RESTING_LENGTH - leg_length) \\\n * np.cos(alpha) - GRAVITY\n return np.array([x[2], x[3], xdotdot, ydotdot, 0, 0])\n\n def touchdown_event(t, x):\n ''' Event function for foot touchdown (transition to stance)\n '''\n # x[1]- np.cos(p[\"aoa\"])*p[\"resting_length\"] (which is = x[5])\n return x[5]\n touchdown_event.terminal = True\n\n APEX_EVENTS = (fall_event, apex_event)\n FLIGHT_EVENTS = (fall_event, touchdown_event)\n STANCE_EVENTS = (fall_event, liftoff_event)\n\n\n t0 = 0\n ''' Starting time '''\n x0 = x\n ''' Starting state '''\n\n # FLIGHT: simulate till touchdown\n sol = integrate.solve_ivp(\n events=FLIGHT_EVENTS,\n fun=flight_dynamics,\n max_step=0.01,\n t_span=[t0, t0 + MAX_TIME],\n y0=x0,\n )\n\n # STANCE: simulate till liftoff\n x0 = sol.y[:, -1]\n sol2 = integrate.solve_ivp(\n events=STANCE_EVENTS,\n fun=stance_dynamics,\n max_step=0.0001,\n t_span=[sol.t[-1], sol.t[-1] + MAX_TIME],\n y0=x0,\n )\n\n # FLIGHT: simulate till apex\n x0 = resetLeg(sol2.y[:, -1], p)\n sol3 = integrate.solve_ivp(\n events=APEX_EVENTS,\n fun=flight_dynamics,\n max_step=0.01,\n t_span=[sol2.t[-1], sol2.t[-1] + MAX_TIME],\n y0=x0,\n )\n\n # concatenate all solutions\n sol.t = np.concatenate((sol.t, sol2.t, sol3.t))\n sol.y = np.concatenate((sol.y, sol2.y, sol3.y), axis=1)\n sol.t_events += sol2.t_events + sol3.t_events\n sol.failed = any(sol.t_events[i].size != 0 for i in (0, 2, 4))\n return sol\n\ndef step_const_lookup(x, p):\n AOA = p['aoa']\n GRAVITY = p['gravity']\n MASS = p['mass']\n RESTING_LENGTH = p['resting_length']\n STIFFNESS = p['stiffness']\n TOTAL_ENERGY = p['total_energy']\n\n SPECIFIC_STIFFNESS = STIFFNESS / MASS # FIXME: Is this name right?\n\n # Note: not taken from p[]\n HALF_PI = np.pi / 2.0\n MAX_TIME = 5\n\n # Function definitions: specific to the constants provided in `p`\n\n def apex_event(t, x):\n ''' Event function to reach apex '''\n return x[3]\n apex_event.terminal = True\n\n def fall_event(t, x):\n ''' Event function to detect the body hitting the floor (failure)\n '''\n return x[1]\n fall_event.terminal = True\n\n def flight_dynamics(t, x, array=np.array):\n ''' code in flight dynamics, xdot_ = f() '''\n return array([x[2], x[3], 0, -GRAVITY, x[2], x[3]])\n\n def liftoff_event(t, x, RESTING_LENGTH_SQ=RESTING_LENGTH**2):\n ''' Event function for maximum spring extension (transition to flight)\n '''\n return ((x[0]-x[4])**2 + (x[1]-x[5])**2) - RESTING_LENGTH_SQ\n liftoff_event.terminal = True\n liftoff_event.direction = 1\n\n def stance_dynamics(t, x, atan2=np.arctan2, sqrt=np.sqrt, sin=np.sin,\n cos=np.cos, array=np.array):\n # energy = computeTotalEnergy(x,p)\n # print(energy)\n alpha = atan2(x[1]-x[5], x[0]-x[4]) - HALF_PI\n leg_length = sqrt((x[0] - x[4]) ** 2 + (x[1] - x[5]) ** 2)\n xdotdot = -SPECIFIC_STIFFNESS * (RESTING_LENGTH - leg_length) \\\n * sin(alpha)\n ydotdot = SPECIFIC_STIFFNESS * (RESTING_LENGTH - leg_length) \\\n * cos(alpha) - GRAVITY\n return array([x[2], x[3], xdotdot, ydotdot, 0, 0])\n\n def touchdown_event(t, x):\n ''' Event function for foot touchdown (transition to stance)\n '''\n # x[1]- np.cos(p[\"aoa\"])*p[\"resting_length\"] (which is = x[5])\n return x[5]\n touchdown_event.terminal = True\n\n APEX_EVENTS = (fall_event, apex_event)\n FLIGHT_EVENTS = (fall_event, touchdown_event)\n STANCE_EVENTS = (fall_event, liftoff_event)\n\n\n t0 = 0\n ''' Starting time '''\n x0 = x\n ''' Starting state '''\n\n solve_ivp = integrate.solve_ivp\n ''' Cache lookup '''\n\n # FLIGHT: simulate till touchdown\n sol = solve_ivp(\n events=FLIGHT_EVENTS,\n fun=flight_dynamics,\n max_step=0.01,\n t_span=[t0, t0 + MAX_TIME],\n y0=x0,\n )\n\n # STANCE: simulate till liftoff\n x0 = sol.y[:, -1]\n sol2 = solve_ivp(\n events=STANCE_EVENTS,\n fun=stance_dynamics,\n max_step=0.0001,\n t_span=[sol.t[-1], sol.t[-1] + MAX_TIME],\n y0=x0,\n )\n\n # FLIGHT: simulate till apex\n x0 = resetLeg(sol2.y[:, -1], p)\n sol3 = solve_ivp(\n events=APEX_EVENTS,\n fun=flight_dynamics,\n max_step=0.01,\n t_span=[sol2.t[-1], sol2.t[-1] + MAX_TIME],\n y0=x0,\n )\n\n # concatenate all solutions\n concat = np.concatenate\n sol.t = concat((sol.t, sol2.t, sol3.t))\n sol.y = concat((sol.y, sol2.y, sol3.y), axis=1)\n sol.t_events += sol2.t_events + sol3.t_events\n ste = sol.t_events\n sol.failed = any(ste[i].size != 0 for i in (0, 2, 4))\n return sol\n\ndef step_const_lookup_cse(x, p):\n AOA = p['aoa']\n GRAVITY = p['gravity']\n MASS = p['mass']\n RESTING_LENGTH = p['resting_length']\n STIFFNESS = p['stiffness']\n TOTAL_ENERGY = p['total_energy']\n\n SPECIFIC_STIFFNESS = STIFFNESS / MASS # FIXME: Is this name right?\n\n # Note: not taken from p[]\n HALF_PI = np.pi / 2.0\n MAX_TIME = 5\n\n # Function definitions: specific to the constants provided in `p`\n\n def apex_event(t, x):\n ''' Event function to reach apex '''\n return x[3]\n apex_event.terminal = True\n\n def fall_event(t, x):\n ''' Event function to detect the body hitting the floor (failure)\n '''\n return x[1]\n fall_event.terminal = True\n\n def flight_dynamics(t, x, array=np.array):\n ''' code in flight dynamics, xdot_ = f() '''\n return array([x[2], x[3], 0, -GRAVITY, x[2], x[3]])\n\n def liftoff_event(t, x, RESTING_LENGTH_SQ=RESTING_LENGTH**2):\n ''' Event function for maximum spring extension (transition to flight)\n '''\n return ((x[0]-x[4])**2 + (x[1]-x[5])**2) - RESTING_LENGTH_SQ\n liftoff_event.terminal = True\n liftoff_event.direction = 1\n\n def stance_dynamics(t, x, atan2=np.arctan2, hypot=math.hypot, sqrt=np.sqrt,\n cos=np.cos, sin=np.sin, array=np.array):\n # energy = computeTotalEnergy(x,p)\n # print(energy)\n alpha = atan2(x[1] - x[5], x[0] - x[4]) - HALF_PI\n #leg_length = sqrt((x[0] - x[4]) ** 2 + (x[1] - x[5]) ** 2)\n stiff_x_leg = SPECIFIC_STIFFNESS * (RESTING_LENGTH -\n hypot(x[0] - x[4], x[1] - x[5]))\n xdotdot = -stiff_x_leg * sin(alpha)\n ydotdot = stiff_x_leg * cos(alpha) - GRAVITY\n return array([x[2], x[3], xdotdot, ydotdot, 0, 0])\n\n def touchdown_event(t, x):\n ''' Event function for foot touchdown (transition to stance)\n '''\n # x[1]- np.cos(p[\"aoa\"])*p[\"resting_length\"] (which is = x[5])\n return x[5]\n touchdown_event.terminal = True\n\n t0 = 0\n ''' Starting time '''\n x0 = x\n ''' Starting state '''\n\n solve_ivp = integrate.solve_ivp\n ''' Cache lookup '''\n\n # FLIGHT: simulate till touchdown\n sol = solve_ivp(\n events=(fall_event, touchdown_event),\n fun=flight_dynamics,\n max_step=0.01,\n t_span=[t0, t0 + MAX_TIME],\n y0=x0,\n )\n\n # STANCE: simulate till liftoff\n x0 = sol.y[:, -1]\n last_t = sol.t[-1]\n sol2 = solve_ivp(\n events=(fall_event, liftoff_event),\n fun=stance_dynamics,\n max_step=0.0001,\n t_span=[last_t, last_t + MAX_TIME],\n y0=x0,\n )\n\n # FLIGHT: simulate till apex\n x0 = resetLeg(sol2.y[:, -1], p)\n last_t = sol2.t[-1]\n sol3 = solve_ivp(\n events=(fall_event, apex_event),\n fun=flight_dynamics,\n max_step=0.01,\n t_span=[last_t, last_t + MAX_TIME],\n y0=x0,\n )\n\n # concatenate all solutions\n concat = np.concatenate\n sol.t = concat((sol.t, sol2.t, sol3.t))\n sol.y = concat((sol.y, sol2.y, sol3.y), axis=1)\n sol.t_events += sol2.t_events + sol3.t_events\n ste = sol.t_events\n sol.failed = any(ste[i].size != 0 for i in (0, 2, 4))\n return sol\n\ndef step_const_lookup_cse2(x, p):\n AOA = p['aoa']\n GRAVITY = p['gravity']\n MASS = p['mass']\n RESTING_LENGTH = p['resting_length']\n STIFFNESS = p['stiffness']\n TOTAL_ENERGY = p['total_energy']\n\n SPECIFIC_STIFFNESS = STIFFNESS / MASS # FIXME: Is this name right?\n\n # Note: not taken from p[]\n HALF_PI = np.pi / 2.0\n MAX_TIME = 5\n\n # Function definitions: specific to the constants provided in `p`\n\n def apex_event(t, x):\n ''' Event function to reach apex '''\n return x[3]\n apex_event.terminal = True\n\n def fall_event(t, x):\n ''' Event function to detect the body hitting the floor (failure)\n '''\n return x[1]\n fall_event.terminal = True\n\n def flight_dynamics(t, x, array=np.array):\n ''' code in flight dynamics, xdot_ = f() '''\n return array([x[2], x[3], 0, -GRAVITY, x[2], x[3]])\n\n def liftoff_event(t, x, hypot=math.hypot):\n ''' Event function for maximum spring extension (transition to flight)\n '''\n return hypot(x[0] - x[4], x[1] - x[5]) - RESTING_LENGTH\n liftoff_event.terminal = True\n liftoff_event.direction = 1\n\n def stance_dynamics(t, x, atan2=np.arctan2, hypot=math.hypot, sqrt=np.sqrt,\n cos=np.cos, sin=np.sin, array=np.array):\n # energy = computeTotalEnergy(x,p)\n # print(energy)\n x15 = x[1] - x[5]\n x04 = x[0] - x[4]\n alpha = atan2(x15, x04) - HALF_PI\n stiff_x_leg = SPECIFIC_STIFFNESS * (RESTING_LENGTH - hypot(x15, x04))\n xdotdot = -stiff_x_leg * sin(alpha)\n ydotdot = stiff_x_leg * cos(alpha) - GRAVITY\n return array([x[2], x[3], xdotdot, ydotdot, 0, 0])\n\n def touchdown_event(t, x):\n ''' Event function for foot touchdown (transition to stance)\n '''\n # x[1]- np.cos(p[\"aoa\"])*p[\"resting_length\"] (which is = x[5])\n return x[5]\n touchdown_event.terminal = True\n\n t0 = 0\n ''' Starting time '''\n x0 = x\n ''' Starting state '''\n\n solve_ivp = integrate.solve_ivp\n ''' Cache lookup '''\n\n # FLIGHT: simulate till touchdown\n sol = solve_ivp(\n events=(fall_event, touchdown_event),\n fun=flight_dynamics,\n max_step=0.01,\n t_span=[t0, t0 + MAX_TIME],\n y0=x0,\n )\n\n # STANCE: simulate till liftoff\n x0 = sol.y[:, -1]\n last_t = sol.t[-1]\n sol2 = solve_ivp(\n events=(fall_event, liftoff_event),\n fun=stance_dynamics,\n max_step=0.0001,\n t_span=[last_t, last_t + MAX_TIME],\n y0=x0,\n )\n\n # FLIGHT: simulate till apex\n x0 = resetLeg(sol2.y[:, -1], p)\n last_t = sol2.t[-1]\n sol3 = solve_ivp(\n events=(fall_event, apex_event),\n fun=flight_dynamics,\n max_step=0.01,\n t_span=[last_t, last_t + MAX_TIME],\n y0=x0,\n )\n\n # concatenate all solutions\n concat = np.concatenate\n sol.t = concat((sol.t, sol2.t, sol3.t))\n sol.y = concat((sol.y, sol2.y, sol3.y), axis=1)\n sol.t_events += sol2.t_events + sol3.t_events\n ste = sol.t_events\n sol.failed = any(ste[i].size != 0 for i in (0, 2, 4))\n return sol\n\n# NB: I pasted the code in two parts, and this is the seam.\n\ndef step_const_lookup_cse2_ary(x, p):\n AOA = p['aoa']\n GRAVITY = p['gravity']\n MASS = p['mass']\n RESTING_LENGTH = p['resting_length']\n STIFFNESS = p['stiffness']\n TOTAL_ENERGY = p['total_energy']\n\n SPECIFIC_STIFFNESS = STIFFNESS / MASS # FIXME: Is this name right?\n\n # Note: not taken from p[]\n HALF_PI = np.pi / 2.0\n MAX_TIME = 5\n\n _arrays = [np.array([0]*6) for _ in range(4)]\n _arrays.append(0)\n\n # Function definitions: specific to the constants provided in `p`\n\n def apex_event(t, x):\n ''' Event function to reach apex '''\n return x[3]\n apex_event.terminal = True\n\n def fall_event(t, x):\n ''' Event function to detect the body hitting the floor (failure)\n '''\n return x[1]\n fall_event.terminal = True\n\n def flight_dynamics(t, x, arrays=_arrays):\n ''' code in flight dynamics, xdot_ = f() '''\n i = arrays[-1]\n arrays[-1] += 1\n a = arrays[i &amp; 3]\n a[4] = a[0] = x[2]\n a[5] = a[1] = x[3]\n a[2] = 0\n a[3] = -GRAVITY\n return a\n\n def liftoff_event(t, x, hypot=math.hypot):\n ''' Event function for maximum spring extension (transition to flight)\n '''\n return hypot(x[0] - x[4], x[1] - x[5]) - RESTING_LENGTH\n liftoff_event.terminal = True\n liftoff_event.direction = 1\n\n def stance_dynamics(t, x, atan2=np.arctan2, hypot=math.hypot, sqrt=np.sqrt,\n cos=np.cos, sin=np.sin, arrays=_arrays):\n # energy = computeTotalEnergy(x,p)\n # print(energy)\n x15 = x[1] - x[5]\n x04 = x[0] - x[4]\n alpha = atan2(x15, x04) - HALF_PI\n stiff_x_leg = SPECIFIC_STIFFNESS * (RESTING_LENGTH - hypot(x15, x04))\n xdotdot = -stiff_x_leg * sin(alpha)\n ydotdot = stiff_x_leg * cos(alpha) - GRAVITY\n i = arrays[-1]\n arrays[-1] += 1\n a = arrays[i &amp; 3]\n a[0] = x[2]\n a[1] = x[3]\n a[2] = xdotdot\n a[3] = ydotdot\n a[4] = a[5] = 0\n return a\n\n def touchdown_event(t, x):\n ''' Event function for foot touchdown (transition to stance)\n '''\n # x[1]- np.cos(p[\"aoa\"])*p[\"resting_length\"] (which is = x[5])\n return x[5]\n touchdown_event.terminal = True\n\n t0 = 0\n ''' Starting time '''\n x0 = x\n ''' Starting state '''\n\n solve_ivp = integrate.solve_ivp\n ''' Cache lookup '''\n\n # FLIGHT: simulate till touchdown\n sol = solve_ivp(\n events=(fall_event, touchdown_event),\n fun=flight_dynamics,\n max_step=0.01,\n t_span=[t0, t0 + MAX_TIME],\n y0=x0,\n )\n\n # STANCE: simulate till liftoff\n x0 = sol.y[:, -1]\n last_t = sol.t[-1]\n sol2 = solve_ivp(\n events=(fall_event, liftoff_event),\n fun=stance_dynamics,\n max_step=0.0001,\n t_span=[last_t, last_t + MAX_TIME],\n y0=x0,\n )\n\n # FLIGHT: simulate till apex\n x0 = resetLeg(sol2.y[:, -1], p)\n last_t = sol2.t[-1]\n sol3 = solve_ivp(\n events=(fall_event, apex_event),\n fun=flight_dynamics,\n max_step=0.01,\n t_span=[last_t, last_t + MAX_TIME],\n y0=x0,\n )\n\n # concatenate all solutions\n concat = np.concatenate\n sol.t = concat((sol.t, sol2.t, sol3.t))\n sol.y = concat((sol.y, sol2.y, sol3.y), axis=1)\n sol.t_events += sol2.t_events + sol3.t_events\n ste = sol.t_events\n sol.failed = any(ste[i].size != 0 for i in (0, 2, 4))\n return sol\n\ndef step_const_lookup_cse2_ary2(x, p):\n AOA = p['aoa']\n GRAVITY = p['gravity']\n MASS = p['mass']\n RESTING_LENGTH = p['resting_length']\n STIFFNESS = p['stiffness']\n TOTAL_ENERGY = p['total_energy']\n\n SPECIFIC_STIFFNESS = STIFFNESS / MASS # FIXME: Is this name right?\n\n # Note: not taken from p[]\n HALF_PI = np.pi / 2.0\n MAX_TIME = 5\n\n # Function definitions: specific to the constants provided in `p`\n\n def apex_event(t, x):\n ''' Event function to reach apex '''\n return x[3]\n apex_event.terminal = True\n\n def fall_event(t, x):\n ''' Event function to detect the body hitting the floor (failure)\n '''\n return x[1]\n fall_event.terminal = True\n\n def flight_dynamics(t, x, a=np.zeros(6)):\n ''' code in flight dynamics, xdot_ = f() '''\n a[4] = a[0] = x[2]\n a[5] = a[1] = x[3]\n a[2] = 0\n a[3] = -GRAVITY\n return a\n\n def liftoff_event(t, x, hypot=math.hypot):\n ''' Event function for maximum spring extension (transition to flight)\n '''\n return hypot(x[0] - x[4], x[1] - x[5]) - RESTING_LENGTH\n liftoff_event.terminal = True\n liftoff_event.direction = 1\n\n def stance_dynamics(t, x, atan2=np.arctan2, hypot=math.hypot, sqrt=np.sqrt,\n cos=np.cos, sin=np.sin, a=np.zeros(6)):\n # energy = computeTotalEnergy(x,p)\n # print(energy)\n x15 = x[1] - x[5]\n x04 = x[0] - x[4]\n alpha = atan2(x15, x04) - HALF_PI\n stiff_x_leg = SPECIFIC_STIFFNESS * (RESTING_LENGTH - hypot(x15, x04))\n xdotdot = -stiff_x_leg * sin(alpha)\n ydotdot = stiff_x_leg * cos(alpha) - GRAVITY\n a[0] = x[2]\n a[1] = x[3]\n a[2] = xdotdot\n a[3] = ydotdot\n a[4] = a[5] = 0\n return a\n\n def touchdown_event(t, x):\n ''' Event function for foot touchdown (transition to stance)\n '''\n # x[1]- np.cos(p[\"aoa\"])*p[\"resting_length\"] (which is = x[5])\n return x[5]\n touchdown_event.terminal = True\n\n t0 = 0\n ''' Starting time '''\n x0 = x\n ''' Starting state '''\n\n solve_ivp = integrate.solve_ivp\n ''' Cache lookup '''\n\n # FLIGHT: simulate till touchdown\n sol = solve_ivp(\n events=(fall_event, touchdown_event),\n fun=flight_dynamics,\n max_step=0.01,\n t_span=[t0, t0 + MAX_TIME],\n y0=x0,\n )\n\n # STANCE: simulate till liftoff\n x0 = sol.y[:, -1]\n last_t = sol.t[-1]\n sol2 = solve_ivp(\n events=(fall_event, liftoff_event),\n fun=stance_dynamics,\n max_step=0.0001,\n t_span=[last_t, last_t + MAX_TIME],\n y0=x0,\n )\n\n # FLIGHT: simulate till apex\n x0 = resetLeg(sol2.y[:, -1], p)\n last_t = sol2.t[-1]\n sol3 = solve_ivp(\n events=(fall_event, apex_event),\n fun=flight_dynamics,\n max_step=0.01,\n t_span=[last_t, last_t + MAX_TIME],\n y0=x0,\n )\n\n # concatenate all solutions\n concat = np.concatenate\n sol.t = concat((sol.t, sol2.t, sol3.t))\n sol.y = concat((sol.y, sol2.y, sol3.y), axis=1)\n sol.t_events += sol2.t_events + sol3.t_events\n ste = sol.t_events\n sol.failed = any(ste[i].size != 0 for i in (0, 2, 4))\n return sol\n\ndef step(x,p):\n '''\n Take one step from apex to apex/failure.\n returns a sol object from integrate.solve_ivp, with all phases\n '''\n\n # TODO: properly update sol object with all info, not just the trajectories\n\n # take one step (apex to apex)\n # the \"step\" function in MATLAB\n # x is the state vector, a list or np.array\n # p is a dict with all the parameters\n\n # set integration options\n\n x0 = x\n max_time = 5\n t0 = 0 # starting time\n\n # FLIGHT: simulate till touchdown\n events = [lambda t,x: fallEvent(t,x,p), lambda t,x: touchdownEvent(t,x,p)]\n for ev in events:\n ev.terminal = True\n sol = integrate.solve_ivp(fun=lambda t, x: flightDynamics(t, x, p),\n t_span = [t0, t0+max_time], y0 = x0, events=events, max_step=0.01)\n\n # STANCE: simulate till liftoff\n events = [lambda t,x: fallEvent(t,x,p), lambda t,x: liftoffEvent(t,x,p)]\n for ev in events:\n ev.terminal = True\n events[1].direction = 1 # only trigger when spring expands\n x0 = sol.y[:,-1]\n sol2 = integrate.solve_ivp(fun=lambda t, x: stanceDynamics(t, x, p),\n t_span = [sol.t[-1], sol.t[-1]+max_time], y0 = x0,\n events=events, max_step=0.0001)\n\n # FLIGHT: simulate till apex\n events = [lambda t,x: fallEvent(t,x,p), lambda t,x: apexEvent(t,x,p)]\n for ev in events:\n ev.terminal = True\n\n x0 = resetLeg(sol2.y[:,-1], p)\n sol3 = integrate.solve_ivp(fun=lambda t, x: flightDynamics(t, x, p),\n t_span = [sol2.t[-1], sol2.t[-1]+max_time], y0 = x0,\n events=events, max_step=0.01)\n\n # concatenate all solutions\n sol.t = np.concatenate((sol.t,sol2.t,sol3.t))\n sol.y = np.concatenate((sol.y,sol2.y,sol3.y),axis=1)\n sol.t_events += sol2.t_events + sol3.t_events\n\n # TODO: mark different phases\n for fail_idx in (0,2,4):\n if sol.t_events[fail_idx].size != 0: # if empty\n sol.failed = True\n break\n else:\n sol.failed = False\n # TODO: clean up the list\n\n return sol\n\ndef resetLeg(x,p):\n x[4] = x[0]+np.sin(p['aoa'])*p['resting_length']\n x[5] = x[1]-np.cos(p['aoa'])*p['resting_length']\n return x\n\ndef stanceDynamics(t, x,p):\n # stance dynamics\n # energy = computeTotalEnergy(x,p)\n # print(energy)\n alpha = np.arctan2(x[1]-x[5] , x[0]-x[4]) - np.pi/2.0\n leg_length = np.sqrt( (x[0]-x[4])**2 + (x[1]-x[5])**2 )\n xdotdot = -p[\"stiffness\"]/p[\"mass\"]*(p[\"resting_length\"] -\n leg_length)*np.sin(alpha)\n ydotdot = p[\"stiffness\"]/p[\"mass\"]*(p[\"resting_length\"] -\n leg_length)*np.cos(alpha) - p[\"gravity\"]\n return np.array([x[2], x[3], xdotdot, ydotdot, 0, 0])\n\ndef fallEvent(t,x,p):\n '''\n Event function to detect the body hitting the floor (failure)\n '''\n return x[1]\nfallEvent.terminal = True\n# TODO: direction\n\ndef touchdownEvent(t,x,p):\n '''\n Event function for foot touchdown (transition to stance)\n '''\n # x[1]- np.cos(p[\"aoa\"])*p[\"resting_length\"] (which is = x[5])\n return x[5]\ntouchdownEvent.terminal = True # no longer actually necessary...\n# direction\n\ndef liftoffEvent(t,x,p):\n '''\n Event function to reach maximum spring extension (transition to flight)\n '''\n return ((x[0]-x[4])**2 + (x[1]-x[5])**2) - p[\"resting_length\"]**2\nliftoffEvent.terminal = True\nliftoffEvent.direction = 1\n\ndef apexEvent(t,x,p):\n '''\n Event function to reach apex\n '''\n return x[3]\napexEvent.terminal = True\n\ndef computeTotalEnergy(x,p):\n # TODO: make this accept a trajectory, and output parts as well\n return (p[\"mass\"]/2*(x[2]**2+x[3]**2) +\n p[\"gravity\"]*p[\"mass\"]*(x[1]) +\n p[\"stiffness\"]/2*\n (p[\"resting_length\"]-np.sqrt((x[0]-x[4])**2 + (x[1]-x[5])**2))**2)\n\ndef flightDynamics(t, x, p):\n ''' code in flight dynamics, xdot_ = f() '''\n return np.array([x[2], x[3], 0, -p[\"gravity\"], x[2], x[3]])\n\n### Functions for Viability\ndef map2e(x, p):\n '''\n map an apex state to its dimensionless normalized height\n TODO: make this accept trajectories\n '''\n assert(np.isclose(x[3],0))\n potential_energy = p['mass']*p['gravity']*x[1]\n kinetic_energy = p['mass']/2*x[3]**2\n return potential_energy/(potential_energy+kinetic_energy)\n\ndef map2x(x,p,e):\n '''\n map a desired dimensionless height `e` to it's state-vector\n '''\n if 'total_energy' not in p:\n print('WARNING: you did not initialize your parameters with '\n 'total energy. You really should do this...')\n\n assert(np.isclose(x[3],0)) # check that we are at apex\n\n x_new = x\n x_new[1] = p['total_energy']*e/p['mass']/p['gravity']\n x_new[2] = np.sqrt(p['total_energy']*(1-e)/p['mass']*2)\n x_new[3] = 0.0 # shouldn't be necessary, but avoids errors accumulating\n return x_new\n\ndef mapSA2xp_height_angle(state_action,x,p):\n '''\n Specifically map state_actions to x and p\n '''\n p['aoa'] = state_action[1]\n x = map2x(x,p,state_action[0])\n return x,p\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-19T17:34:07.273", "Id": "421322", "Score": "0", "body": "Thanks! I like the nested functions, I'll need to check if I can do that without sacrificing other functionality (not shown here), but I think most if not all of it is actually fine this way. Also, in regards to unpacking, is this improving performance due to not passing the variables around to subfunctions, or not looking up a dict repeatedly? My understanding is that dictionary look-ups are very fast, so I would not expect that to result in a speedup." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-19T18:45:36.700", "Id": "421328", "Score": "0", "body": "My unpacking was of the `x` array, and I hoped a single unpack would be faster than several index operations. But it wasn't, which is why having hard numbers and making incremental changes is important." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-19T18:50:33.943", "Id": "421329", "Score": "1", "body": "Ahh, you meant unpacking the `p` dictionary into constants. It's true that dictionary lookups are fast. But fast compared to what? Looking something up in a dictionary held in a variable means looking up the variable, then passing the key to the get item method of that variable. Whereas looking up a separately named variable means looking up the variable, done!" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-19T04:44:00.640", "Id": "217713", "ParentId": "217668", "Score": "6" } } ]
{ "AcceptedAnswerId": "217697", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-18T12:17:35.880", "Id": "217668", "Score": "5", "Tags": [ "python", "performance", "beginner", "physics", "scipy" ], "Title": "Simulation of spring-loaded inverted pendulum" }
217668
<p>I have to find the thousandth number (excluding numbers 3, 4, 7) but it's taking a long time, about 9 seconds. I'd like to find out how to improve performance.</p> <pre class="lang-java prettyprint-override"><code>import java.sql.Date; import java.text.DecimalFormat; import java.text.SimpleDateFormat; public class FirstChallange { private static int removedNumbers; private static int numberQuantity; private static int lastNumberFound; private static int cont; private static int pos3; private static int pos4; private static int pos7; public static void main(String[] args) { long inicio = System.currentTimeMillis(); removedNumbers = 0; numberQuantity = 10000000; for (cont = 1; removedNumbers &lt;= numberQuantity; cont++) { String str = new String(); str = String.valueOf(cont); pos3 = str.indexOf("3"); pos4 = str.indexOf("4"); pos7 = str.indexOf("7"); if((pos3 == -1) &amp;&amp; (pos4 == -1) &amp;&amp; (pos7 == -1)) { removedNumbers++; if(removedNumbers == numberQuantity){ // can not find numbers (3, 4, 7) lastNumberFound = cont; } } } DecimalFormat dfmt = new DecimalFormat("0"); System.out.println(dfmt.format(lastNumberFound)); long fim = System.currentTimeMillis(); System.out.println(new SimpleDateFormat("ss.SSS").format(new Date(fim - inicio))); } } </code></pre> <p>Is converting numbers into string and removing them with indexOf the best mode? or is there anything better than indexOf like RabinKarp?</p> <p>Expected result: 180999565 in 5/4 seconds</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-18T14:15:23.193", "Id": "421195", "Score": "1", "body": "Could you clarify what your code is doing? Maybe using a smaller number example" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-18T14:38:40.763", "Id": "421200", "Score": "0", "body": "The code has the object to find the thousand number that does not contain 3, 4 or 7" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-18T14:42:22.330", "Id": "421202", "Score": "0", "body": "What do you mean by 'the thousand number'?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-18T14:54:36.110", "Id": "421203", "Score": "2", "body": "The thousandth positive integer whose base 10 representation doesn't contain 3, 4, or 7 is 2929." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-19T01:08:10.507", "Id": "421245", "Score": "0", "body": "Seems like the program finds the 10 millionth number, which is a lot different than the 1 thousandth number in terms of how long a program like this would be expected to run." } ]
[ { "body": "<p>Do not instantiate a new String. There's no point as you set the value again on the next line anyway.</p>\n\n<pre><code>String str = String.valueOf(cont); \n</code></pre>\n\n<p>Instead of going from 1 -> X and getting the last value, you could go from X -> 1 and get the first value found.</p>\n\n<p>I strongly suggest renaming your variables to be more descriptive (English). It'll make it easier to understand what your code is accomplishing.</p>\n\n<p>Instead of using <code>indexOf()</code> you could use <code>contains()</code>, although you'll have to do some testing to see if it the performance is better.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-18T14:20:10.237", "Id": "217672", "ParentId": "217669", "Score": "1" } }, { "body": "<p>I tried several different approaches and the problem is - string manipulation is just slower than arithmetic.</p>\n\n<p>Note: I refactored the check into a function because it is good practice in that it creates smaller pieces of code whose functions are then more easily understood.</p>\n\n<pre><code>import java.sql.Date;\nimport java.text.DecimalFormat;\nimport java.text.SimpleDateFormat;\n\npublic class FirstChallenge {\n\n private static int lastNumberFound;\n\n public static void main(String[] args) \n {\n long inicio = System.currentTimeMillis();\n\n int removedNumbers = 0;\n int numberQuantity = 10000000;\n\n int cont;\n for (cont = 1; removedNumbers &lt;= numberQuantity; cont++) {\n if (go(cont)) {\n removedNumbers++;\n if(removedNumbers == numberQuantity){ // can not find numbers (3, 4, 7)\n lastNumberFound = cont; \n }\n }\n } \n\n DecimalFormat dfmt = new DecimalFormat(\"0\");\n\n System.out.println(dfmt.format(lastNumberFound));\n\n long fim = System.currentTimeMillis();\n System.out.println(new SimpleDateFormat(\"ss.SSS\").format(new Date(fim - inicio)));\n }\n\n private static boolean go(int i) {\n int j = i;\n while (j &gt; 0) {\n int d = j % 10;\n if (d == 3 || d == 4 || d == 7) return false;\n j = j / 10;\n }\n return true;\n }\n}\n</code></pre>\n\n<p>The result I got:</p>\n\n<pre><code>180999565\n01.134\n</code></pre>\n\n<p>Notice that the time is less than 1/5th the time of the other algorithm.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-18T21:27:05.707", "Id": "421231", "Score": "0", "body": "And mine is less than 1/50,000th than yours ;-)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-18T14:40:21.947", "Id": "217673", "ParentId": "217669", "Score": "3" } }, { "body": "<blockquote>\n<pre><code>import java.sql.Date;\n</code></pre>\n</blockquote>\n\n<p>You shouldn't need anything from <code>java.sql</code> unless you're using a relational database. <code>java.util.Date</code> would be more appropriate here (or nothing at all).</p>\n\n<hr>\n\n<blockquote>\n<pre><code>public class FirstChallange {\n</code></pre>\n</blockquote>\n\n<p><em>Challenge</em> has one <em>a</em> and two <em>e</em>s.</p>\n\n<p>The name is not going to be very helpful in identifying the purpose of the class in six months' time, and there's no comment to say what the source of the challenge was either.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> private static int removedNumbers;\n private static int numberQuantity;\n private static int lastNumberFound; \n private static int cont;\n private static int pos3;\n private static int pos4;\n private static int pos7; \n</code></pre>\n</blockquote>\n\n<p>Variables should usually be in the narrowest scope possible. This means that static fields should be extremely rare.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> long inicio = System.currentTimeMillis(); \n</code></pre>\n</blockquote>\n\n<p>It's best to be consistent in the use of language: either name all the variables in Portuguese or name them all in English.</p>\n\n<p>This line has trailing whitespace. If you can configure your IDE to automatically remove this, you will reduce the number of spurious changes which muddle revision control diffs.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> DecimalFormat dfmt = new DecimalFormat(\"0\");\n\n System.out.println(dfmt.format(lastNumberFound)); \n</code></pre>\n</blockquote>\n\n<p>That is heavily overkill for <code>System.out.println(lastNumberFound);</code></p>\n\n<hr>\n\n<blockquote>\n<pre><code> removedNumbers = 0;\n numberQuantity = 10000000;\n\n\n for (cont = 1; removedNumbers &lt;= numberQuantity; cont++) { \n String str = new String(); \n str = String.valueOf(cont); \n\n pos3 = str.indexOf(\"3\");\n pos4 = str.indexOf(\"4\");\n pos7 = str.indexOf(\"7\");\n</code></pre>\n</blockquote>\n\n<p>Actually iterating over objects is rarely the best way to count them. Iteration with filtering even less so. If you spend some time thinking through the mathematics before you start writing code, there's an easy way to tackle this problem by base conversion which takes about 20 milliseconds.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-18T15:10:46.803", "Id": "217676", "ParentId": "217669", "Score": "5" } }, { "body": "<p>I'm aware that another answer is already accepted, but my solution only takes 0.000022s and if I don't talk about it I will burst: ;-)</p>\n\n<pre><code>public class FirstChallange {\n static char[] mapChars = new char[0x40];\n static {\n mapChars['0'] = '0';\n mapChars['1'] = '1';\n mapChars['2'] = '2';\n mapChars['3'] = '5';\n mapChars['4'] = '6';\n mapChars['5'] = '8';\n mapChars['6'] = '9';\n }\n public final static void main(String[] args) {\n long nanoStart = System.nanoTime();\n int maxNumber = 10000000;\n char[] digits = Integer.toString(maxNumber, 7).toCharArray();\n for (int i = 0; i &lt; digits.length; i++) {\n digits[i] = mapChars[digits[i]];\n }\n String lastNumber = new String(digits);\n long diffTime = System.nanoTime() - nanoStart;\n System.out.println(diffTime);\n NumberFormat dfmt = DecimalFormat.getNumberInstance();\n dfmt.setMaximumFractionDigits(6);\n System.out.println(\"last number: \" + lastNumber);\n System.out.println(\"time: \" + dfmt.format(diffTime / 1000000000d) + \" s\");\n }\n}\n</code></pre>\n\n<p>Instead of brute forcing I'm making use of different bases. With three digits \"forbidden\" to be used, you essentially change your number base from 10 to 7, so instead of counting up a variable that is restricted to base 7 by skipping values that are outside it, you just do a conversion from one base to the other. You could do that by calculation yourself, but in order to get the correct value you need to do a remapping of the digits. The easiest way to do that is a string-replacemant, so I started with converting the decimal value to a <code>String</code> using the <code>toString</code> method that allows the specification of a radix.</p>\n\n<p>This results to the text <code>150666343</code> that looks familiar to the expected result. If we forbid the digits <code>7</code>, <code>8</code> and <code>9</code> that would already be the solution but in our case digits \"in the middle\" are forbidden, so in order to get the result for this different set of digits, we have to map the digits <code>3</code> and <code>4</code> to <code>5</code> and <code>6</code> and the digits <code>5</code> and <code>6</code> to <code>8</code> and <code>9</code>.</p>\n\n<p>That's it. Instead of iterating over a loop 180 million times you do it 9 times (plus some loops inside <code>toCharArray</code>, <code>toString</code> and <code>new String(char)</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-18T21:23:29.743", "Id": "217700", "ParentId": "217669", "Score": "3" } } ]
{ "AcceptedAnswerId": "217700", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-18T13:12:16.917", "Id": "217669", "Score": "2", "Tags": [ "java", "performance" ], "Title": "Find the thousandth integer without the digits 3, 4, and 7" }
217669
<p>After finishing my C++ course, I decided to make a hangman game. (without the drawing part) I was wondering how the code could be improved.</p> <p><strong>Header File:</strong></p> <pre><code>#ifndef GAME_H #define GAME_H #include &lt;string&gt; #include &lt;fstream&gt; #include &lt;vector&gt; #include &lt;Windows.h&gt; class Game { public: Game(); int onOffSwitch(std::string); void readRandomLine(); void display(); void revealLetter(char); void revealRandomly(); void createUnreveal(); void determineAttempts(); void countLines(); void iStreamClear(); void decrementAttempts(); void newGame(); void endGame(); bool isRevealed(char); private: char z; unsigned int attempts = 0; unsigned int totalLines = 0; std::ifstream inputStream; std::string theWord; std::string unrevealed; bool gameOver = false; bool guessedRight; HANDLE colorControl; std::vector&lt;char&gt; revealed; }; #endif // !FILE_OPERATIONS_H </code></pre> <p><strong>Implementation File:</strong></p> <pre><code>#include "Game.h" #include &lt;iostream&gt; #include &lt;fstream&gt; #include &lt;string&gt; #include &lt;ctime&gt; #include &lt;iomanip&gt; #include &lt;Windows.h&gt; #include &lt;vector&gt; #include &lt;algorithm&gt; // Constructor opens file and invokes newGame function Game::Game() { onOffSwitch("open"); newGame(); } // Function to open file along a fail-check int Game::onOffSwitch(std::string command) { if (command == "open") { inputStream.open("words.txt"); if (inputStream.fail()) { std::cerr &lt;&lt; "Error Opening File" &lt;&lt; std::endl; return -1; } } else if (command == "close") { inputStream.close(); } } // Function to count number of lines in the file (for purposes of random number generation) void Game::countLines() { std::string tempS; if (inputStream.is_open()) { while (!inputStream.eof()) { getline(inputStream, tempS); totalLines = totalLines + 1; } } else { onOffSwitch("open"); countLines(); } } // Function that reads a random line(word) from the text file void Game::readRandomLine() { srand(time(NULL)); // resets if (inputStream.is_open()) { int random = 0; countLines(); random = (rand() % totalLines) + 1; // random line to read iStreamClear(); // clear EndOfFile flag on ifstream int currentLine = 1; // While loop to keep reading until we get to the right line while (currentLine &lt;= random) { getline(inputStream, theWord); currentLine++; } determineAttempts(); } else { onOffSwitch("open"); readRandomLine(); } } // Function to display the current state of the unrevealed word void Game::display() { if (gameOver == false) { for (int t = 0; t &lt; unrevealed.length(); t++) { std::cout &lt;&lt; std::setw(2) &lt;&lt; unrevealed[t]; } std::cout &lt;&lt; std::endl; } } // Function that determines number of attempts the player has depending on word length void Game::determineAttempts() { if (theWord.length() == 4) { attempts = 2; } else if (theWord.length() &gt;= 5 &amp;&amp; theWord.length() &lt;= 7) { attempts = 3; } else if (theWord.length() &gt; 7) { attempts = 4; } std::cout &lt;&lt; "You have " &lt;&lt; attempts &lt;&lt; " attempts!" &lt;&lt; std::endl; } // Function to remove EndOfFile flag and start back in the beginning of the file void Game::iStreamClear() { inputStream.clear(); inputStream.seekg(0, inputStream.beg); } // Creates an unrevealed version of the random word we read. (with underscores) void Game::createUnreveal() { unrevealed = theWord; for (int r = 0; r &lt; theWord.length(); r++) { unrevealed[r] = '_'; } } // Reveals a letter randomly void Game::revealRandomly() { srand(time(NULL)); int ran = rand() % unrevealed.length(); revealLetter(theWord[ran]); } // Checks and reveals a specific letter void Game::revealLetter(char l) { guessedRight = false; for (int e = 0; e &lt; unrevealed.length(); e++) { if (theWord[e] == toupper(l) || theWord[e] == tolower(l)) // The condition includes both upper and lower so that it works with both lowercase and uppercase entries by the player { guessedRight = true; if (e == 0) // If it's the first letter, it should be uppercase { revealed.push_back(l); // Puts the letter into a vector for checking if the letter was already revealed unrevealed[e] = toupper(l); } else { revealed.push_back(l); // Same as above unrevealed[e] = tolower(l); } } } } // Function to lower attempts if the right conditions are met. void Game::decrementAttempts() { // Sets console color colorControl = GetStdHandle(STD_OUTPUT_HANDLE); if (unrevealed == theWord &amp;&amp; attempts != 0) // If the unrevealed letter is the same as the secret word and player still has attempts, they win { SetConsoleTextAttribute(colorControl, 13); std::cout &lt;&lt; theWord &lt;&lt; std::endl; std::cout &lt;&lt; "Congrats! You won!" &lt;&lt; std::endl; gameOver = true; endGame(); } else if (attempts &gt;= 1 &amp;&amp; guessedRight != true) // If attempts are &gt;= to 1 and they didn't guess right, they lose 1 attempt { attempts -= 1; // If attempts become 0 after the change, then the game is over and endGame function gets called to see if they want to play again if (attempts == 0) { SetConsoleTextAttribute(colorControl, 10); std::cout &lt;&lt; "No attempts left! Game over!" &lt;&lt; std::endl; SetConsoleTextAttribute(colorControl, 9); std::cout &lt;&lt; "The word was " &lt;&lt; theWord &lt;&lt; "." &lt;&lt; std::endl; gameOver = true; endGame(); } else { std::cout &lt;&lt; "You have " &lt;&lt; attempts &lt;&lt; " attempts left!" &lt;&lt; std::endl; } } } // Function that prompts the player to play again or end the game void Game::endGame() { char ans; revealed.clear(); // clearing the vector so we don't have leftover characters from previous games std::cout &lt;&lt; std::endl; colorControl = GetStdHandle(STD_OUTPUT_HANDLE); SetConsoleTextAttribute(colorControl, 4); std::cout &lt;&lt; "Want to play again? (y/n)"; std::cin &gt;&gt; ans; SetConsoleTextAttribute(colorControl, 15); if (ans == 'y' || ans == 'Y') { std::cout &lt;&lt; std::endl; newGame(); } else if (ans == 'n' || ans == 'N') { gameOver = true; SetConsoleTextAttribute(colorControl, 6); std::cout &lt;&lt; "Thank you for playing!" &lt;&lt; std::endl; } } void Game::newGame() { gameOver = false; // Clears both words theWord.clear(); unrevealed.clear(); // Calls all the necessary functions for the game to work readRandomLine(); createUnreveal(); revealRandomly(); display(); // While loop that asks the player for a letter as long as game is not over (either by winning or losing, so no more attempts left) while (attempts &gt; 0 &amp;&amp; gameOver != true) { std::cout &lt;&lt; "Enter a letter: "; std::cin &gt;&gt; z; if (isRevealed(z) == true) // If the letter is already revealed { std::cout &lt;&lt; "Letter is already revealed!" &lt;&lt; std::endl; display(); } else { revealLetter(z); decrementAttempts(); display(); } } } // Checks through the vector to see if the particular letter is already revealed bool Game::isRevealed(char s) { if (std::count(revealed.begin(), revealed.end(), tolower(s)) == true) { return true; } else if (std::count(revealed.begin(), revealed.end(), toupper(s)) == true) { return true; } else return false; } </code></pre> <p><strong>main.cpp :</strong></p> <pre><code>#include &lt;iostream&gt; #include "Game.h" int main() { Game pass; pass.onOffSwitch("close"); return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-19T12:43:08.873", "Id": "421292", "Score": "0", "body": "If you don't mind me asking, what editor do you use?" } ]
[ { "body": "<p>I will proceed from a high level to a low level perspective.</p>\n\n<p>Starting with main.cpp:</p>\n\n<blockquote>\n<pre><code>Game pass;\npass.onOffSwitch(\"close\");\n</code></pre>\n</blockquote>\n\n<p>The meaning of these two lines are not clear without reading the contents of the class <code>Game</code>. That means that not only do I need other pieces of code, but different files, to understand these two lines.</p>\n\n<p>Having looked into the <code>Game</code> class, it becomes apparent that the game, when it is created, starts itself in the constructor. This is not what you would expect from the above code lines.</p>\n\n<p>It would be easier to understand if the constructor were only used to construct the instance, without executing any logic. Viewing the <code>main</code> function as the \"user\" of the instance, what I usually try to do is formulate what that piece of code is supposed to achieve in words inside of my head, and then translate it to code.</p>\n\n<p>\"I want to create an instance of the Hangman game and then start it.\", translated to C++:</p>\n\n<pre><code>Game hangman;\nhangman.start(\"words.txt\");\n</code></pre>\n\n<hr>\n\n<p>Let's look at the constructor:</p>\n\n<blockquote>\n<pre><code>// Constructor opens file and invokes newGame function\nGame::Game()\n{\n onOffSwitch(\"open\");\n newGame();\n}\n</code></pre>\n</blockquote>\n\n<p>The comment tells us that <code>onOffSwitch</code> opens a file, but the code does not indicate that. Opening the file is all it does (apart from some error handling), so lets suppose we rename it to <code>readWordsFromFile</code>. (We will look at the <code>onOffSwitch</code> method in a moment.)</p>\n\n<p>The next thing the comment tells us is that it invokes the method, but that is something the code itself tells you already. It is usually better to only comment <em>why</em> the code does something (if it helps understanding it), but not <em>what</em> it does.</p>\n\n<p>An example of how I would rewrite that piece of code (at this level, not considering further improvements we will look at) is this:</p>\n\n<pre><code> Game::Game()\n {\n readWordsFromFile();\n newGame();\n }\n</code></pre>\n\n<p>With the renamed method name, the comment becomes obsolete and can be removed, so the maintainer has less to read for the same understanding.</p>\n\n<hr>\n\n<p>In the previous section, we renamed the method <code>onOffSwitch</code>. Let's have a look at why that name is not a good fit.</p>\n\n<blockquote>\n<pre><code>// Function to open file along a fail-check\nint Game::onOffSwitch(std::string command)\n{\n if (command == \"open\")\n {\n inputStream.open(\"words.txt\");\n if (inputStream.fail())\n {\n std::cerr &lt;&lt; \"Error Opening File\" &lt;&lt; std::endl;\n return -1;\n }\n }\n else if (command == \"close\")\n {\n inputStream.close();\n }\n}\n</code></pre>\n</blockquote>\n\n<p>Again the comment above the method is a good indication: Whenever you want to add a comment explaining what a method does, that explanation should probably be its name. What this method does is one of two things, depending on a parameter: Either it opens a file, or it closes it.</p>\n\n<p>The parameter is of type string. That means that if you mistype the parameter, the compiler will not warn you, the method will not tell you that something is wrong, instead nothing will happen (at that point). The bugs will probably occur much later in the program, and will be difficult to track. You could use a boolean or enum instead, which would prevent the typo problem. Even better would be to replace it with 2 methods which do just one thing each: <code>openFile</code> and <code>closeFile</code>, and without parameters to select what they should do.</p>\n\n<hr>\n\n<p>Most of your methods do not return anything and do not take any parameters. Instead they change the state of the object, which is essentially global state since all of the code resides inside the class and thus has access to it. This can quickly become very complex and bugs will easily be introduced, but hard to find.</p>\n\n<p>Instead of all these methods that access the file stream to open or close it, to count its lines or to select and read a random line, a better approach could be the following:</p>\n\n<ol>\n<li>Open the file stream, read all lines into an <code>std::vector&lt;string&gt;</code>, close the file stream.</li>\n<li>Use the vectors <code>size()</code> method to ask it for the number of lines, and use it for calculating the random index.</li>\n<li>Using the random index, read directly from the vector of strings, rather than reading through the whole file again.</li>\n</ol>\n\n<p>This way the code becomes more readable, more performant and less prone to bugs. For example you will only have to read the file once, and you will not have to care about when the file stream is opened and closed. You open it once, read it, and close it. (This assumes that the file is not millions of words long, which could become a memory issue, but maybe a few thousand words).</p>\n\n<hr>\n\n<p>Let's look at the implementation of some of the other methods.</p>\n\n<blockquote>\n<pre><code>void Game::determineAttempts()\n{\n if (theWord.length() == 4)\n {\n attempts = 2;\n }\n else if (theWord.length() &gt;= 5 &amp;&amp; theWord.length() &lt;= 7)\n {\n attempts = 3;\n }\n else if (theWord.length() &gt; 7)\n {\n attempts = 4;\n }\n std::cout &lt;&lt; \"You have \" &lt;&lt; attempts &lt;&lt; \" attempts!\" &lt;&lt; std::endl;\n}\n</code></pre>\n</blockquote>\n\n<p>Here the implementation does not really fit the method name, while the method name itself is a pretty good choice in my opinion. Instead of calculating the number of attempts, setting some state in the outside worlds (basically global state), and printing to the console, it is better to break things down more into small sub-problems. The sub-problem that this method should solve is this: \"Take the word, determine how many attempts the player has, and give me the result.\"</p>\n\n<pre><code>int Game::determineAttempts(std::string word)\n{\n int numberOfAttempts = 0;\n\n if (word.length() == 4)\n {\n numberOfAttempts = 2;\n }\n else if (word.length() &gt;= 5 &amp;&amp; word.length() &lt;= 7)\n {\n numberOfAttempts = 3;\n }\n else if (word.length() &gt; 7)\n {\n numberOfAttempts = 4;\n }\n\n return numberOfAttempts;\n}\n</code></pre>\n\n<p>This version does not write to the console and it does not change any state. Instead, the caller of the method can decide whether to print something to the console and what to do with the number of attempts the player should have.</p>\n\n<p>Note also that not all possible word lengths are checked. What happens when a word has only three letters (or less)?</p>\n\n<hr>\n\n<p>All of <code>Game</code>'s methods are public, but the purpose of <code>public</code> is to expose them to callers outside of the class itself. <code>onOffSwitch</code> is the only method that is called from outside (namely the main function), so all other methods should be private.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-18T15:30:27.387", "Id": "421205", "Score": "0", "body": "Thanks for the suggestions. I'll consider all these next time I do a project." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-18T15:46:05.843", "Id": "421206", "Score": "0", "body": "Just wondering, did you try to build or test it?" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-18T15:22:10.423", "Id": "217677", "ParentId": "217671", "Score": "14" } }, { "body": "<p><strong>Single Responsibility Principle</strong> </p>\n\n<p>The class Game does too much directly, this could be an aggregation of classes instead. One of the points of the <a href=\"https://en.wikipedia.org/wiki/Single_responsibility_principle\" rel=\"noreferrer\">Single Responsibility Principle</a> is that a class or function has limited tasks to perform so that it is easier to write, read and debug. The file input should have it's own class that game might evoke. The single responsibility is one of the 5 key principles of <a href=\"https://en.wikipedia.org/wiki/SOLID\" rel=\"noreferrer\">SOLID</a> programming. SOLID programming is a good method of Object Oriented programming.</p>\n\n<p><strong>Error Checking</strong> </p>\n\n<p>The function <code>onOffSwitch(std::string command)</code> returns an integer value that is <strong>always</strong> ignored. There is no error checking on the value to see if the file <code>words.txt</code> was opened successfully. If the file doesn't exist the program goes into an infinite loop (Bug number 1).</p>\n\n<p><strong>Don't Ignore Warning Messages</strong></p>\n\n<p>I built and ran this program in Visual Studio 2015. The following warning messages were issued during the build:</p>\n\n<pre><code>1&gt;------ Build started: Project: HangMan1, Configuration: Debug Win32 ------\n1&gt; Game.cpp\n1&gt;d:\\codereview\\hangman1\\hangman1\\game.cpp(58): warning C4244: 'argument': conversion from 'time_t' to 'unsigned int', possible loss of data\n1&gt;d:\\codereview\\hangman1\\hangman1\\game.cpp(86): warning C4018: '&lt;': signed/unsigned mismatch\n1&gt;d:\\codereview\\hangman1\\hangman1\\game.cpp(123): warning C4018: '&lt;': signed/unsigned mismatch\n1&gt;d:\\codereview\\hangman1\\hangman1\\game.cpp(132): warning C4244: 'argument': conversion from 'time_t' to 'unsigned int', possible loss of data\n1&gt;d:\\codereview\\hangman1\\hangman1\\game.cpp(141): warning C4018: '&lt;': signed/unsigned mismatch\n1&gt;d:\\codereview\\hangman1\\hangman1\\game.cpp(257): warning C4805: '==': unsafe mix of type 'int' and type 'bool' in operation\n1&gt;d:\\codereview\\hangman1\\hangman1\\game.cpp(261): warning C4805: '==': unsafe mix of type 'int' and type 'bool' in operation\n1&gt;d:\\codereview\\hangman1\\hangman1\\game.cpp(34): warning C4715: 'Game::onOffSwitch': not all control paths return a value\n========== Build: 1 succeeded, 0 failed, 0 up-to-date, 0 skipped ==========\n</code></pre>\n\n<p>The warning messages should be treated as error messages in this case because it shows possible bugs in the code. The last warning message in particular should be treated as an error message, <strong>all paths through the code should always return a value</strong>.</p>\n\n<p><strong>Bug Number 2</strong> </p>\n\n<p>After words.txt was added the program ran and it picked one of the lines as it was supposed to. When the first letter of the line was added (not the first guess or the first correct guess) the letter was converted to a capital which made the answer when it was entered wrong. It might be better to convert all user input to lower case upon entry.</p>\n\n<p><strong>Portability</strong> </p>\n\n<p>The code is not portable because it includes windows.h. It also uses windows only features such as STD_OUTPUT_HANDLE. It might be better to ifdef this code so it can be moved to other platforms.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-18T15:23:12.830", "Id": "217678", "ParentId": "217671", "Score": "13" } }, { "body": "<p>In your <code>isRevealed</code> method, you're using the <code>count</code> algorithm, which believes that you are interested in knowing the exact number of letters, whereas you just want to know if it is present at least once. More, you are making two complete passesover the letters where a partial pass stopping at the first occurrence would suffice. You could rewrite your function body as:</p>\n\n<pre><code>const auto lowerCaseS = tolower(s);\nreturn std::any(revealed.begin(), revealed.end(), [&amp;](char c) { return tolower(c) == lowerCaseS; });\n</code></pre>\n\n<p>In your <code>createUnreveal</code> function, you are actually trying to create a string composed of <code>_</code> alone, that has the same length as <code>theWord</code>. Your function could be simplified as:</p>\n\n<pre><code>unrevealed = std::string{theWord.length(), '_'};\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-19T15:48:28.537", "Id": "421312", "Score": "0", "body": "Noted, I wasn't aware std::any existed. Thanks." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-19T09:29:29.317", "Id": "217724", "ParentId": "217671", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-18T13:43:07.683", "Id": "217671", "Score": "16", "Tags": [ "c++", "hangman" ], "Title": "Hangman Game with C++" }
217671
<p>This script is my web crawlerfor small sites. Can you possibly review it for best coding practices?</p> <h3>Code</h3> <pre><code>import bs4 as bs import urllib.request from urllib.parse import urlparse,urljoin import pprint class Page(object): def __init__(self,base_url,url): self.url = url self.base_url = base_url def soup(self): sauce = urllib.request.urlopen(self.url).read() return (bs.BeautifulSoup(sauce,'lxml')) def title(self): soup = self.soup() return soup.title.string def links(self): urls = [] soup = self.soup() href = [i.get('href') for i in soup.findAll('a') ] links = [i for i in (list(map((lambda url : url if bool(urlparse(url).netloc) == True else urljoin (self.base_url, url)),href))) if i.startswith(self.base_url)] return links def map_page(self): map = {self.url:{'title':self.title(),'links':set(self.links())}} return map def site_map(base_url): map_pages = {} links_to_map = [base_url] def check_and_add(url): if url not in map_pages: [links_to_map.append(i) for i in Page(base_url,url).links()] (map_pages.update(Page(base_url,url).map_page())) links_to_map.remove(url) else: links_to_map.remove(url) while links_to_map != []: url = links_to_map[0] check_and_add(url) pprint.pprint(map_pages) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-18T16:13:57.683", "Id": "421207", "Score": "1", "body": "Is the code working? If not it is off topic, please see how to ask a good question and what questions not to ask https://codereview.stackexchange.com/help/dont-ask. The part about \"what I do wrong\" leads to my question." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-18T16:26:18.293", "Id": "421209", "Score": "1", "body": "Yes code is working . I mean what is the best practices" } ]
[ { "body": "<p>not exhaustive but some feedback.\nThere are some big \"No No\"s in this code as well as some minor formatting things.</p>\n\n<p>First the big \"No No\"s. </p>\n\n<p>1) Do not use list comprehension unless you plan do use the result:\n<code>[links_to_map.append(i) for i in Page(base_url,url).links()]</code>\nDo this in a normal <code>for</code> loop.</p>\n\n<p>2) <strong>DO NOT</strong> change a list you are iterating over (i.e. <code>links_to_map</code> in your lest method).</p>\n\n<p><strong>Other stuff:</strong><br>\n<code>return</code> statements don't need <code>()</code>:</p>\n\n<blockquote>\n <p><code>return (bs.BeautifulSoup(sauce,'lxml'))</code> </p>\n</blockquote>\n\n<p>Should just be:<br>\n<code>return bs.BeautifulSoup(sauce,'lxml')</code></p>\n\n<p>Avoid needless <code>()</code> as well:</p>\n\n<blockquote>\n <p><code>(map_pages.update(Page(base_url,url).map_page())</code></p>\n</blockquote>\n\n<p>to:<br>\n<code>map_pages.update(Page(base_url,url).map_page()</code></p>\n\n<p>Empty lists are considered <code>False</code> so:</p>\n\n<blockquote>\n <p><code>while links_to_map != []:</code></p>\n</blockquote>\n\n<p>can just be:<br>\n<code>while links_to_map:</code></p>\n\n<p>My last tip. Consider using a <code>set</code> for <code>links_to_map</code> instead of a <code>list</code> since the removing step will be significantly faster.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-18T20:07:45.650", "Id": "421229", "Score": "0", "body": "(Congrats on your first post here at long last…)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-18T19:26:30.907", "Id": "217689", "ParentId": "217674", "Score": "3" } }, { "body": "<p>I have made some changes to make it neater and more efficient. See the end of this response for the final solution. But I'll start with a few comments.</p>\n\n<p>There is no point making your class inherit the <code>object</code> class, especially if you're working with Python 3.</p>\n\n<pre><code>class Page(object):\n</code></pre>\n\n<p>The <code>soup()</code> method seems to be called indiscriminately causing <code>BeautifulSoup</code> to parse the contents of the page in concern too many times (see the <code>map_page()</code> method, for example). It is probably more efficient to parse once, afterwhich you can save whatever (e.g. <code>title</code> and <code>links</code>)you need as object properties.</p>\n\n<p>Using <code>list</code> and <code>map</code> in this context seems unnecessary. It helps if you strive for readability --- your future self will thank you.</p>\n\n<pre><code>links = [i for i in (list(map((lambda url : url if bool(urlparse(url).netloc) == True else urljoin (self.base_url, url)),href))) if i.startswith(self.base_url)]\n</code></pre>\n\n<p>Also, checking the truthiness of <code>urlparse(url).netloc</code> doesn't require you to coerce it to a boolean result first. Simply replacing <code>if bool(urlparse(url).netloc)</code> with <code>if urlparse(url).netloc</code> would suffice.</p>\n\n<p>In the <code>site_map()</code> function, you can replace the while loop with something simpler, e.g.:</p>\n\n<pre><code>while links_to_map:\n check_and_add(links_to_map.pop())\n</code></pre>\n\n<p>I have also made other subjective simplifications that hopefully should be obvious to you.</p>\n\n<pre><code>import pprint\nimport urllib.request\nfrom pprint import pprint\nfrom urllib.parse import urlparse, urljoin\n\nimport bs4 as bs\n\n\nclass Page:\n def __init__(self, base_url, url):\n self.url = url\n self.base_url = base_url\n self.souped = None\n self.title = None\n self.links = None\n\n def soup(self):\n def clean(url):\n return url if urlparse(url).netloc else urljoin(self.base_url, url)\n\n sauce = urllib.request.urlopen(self.url).read()\n self.souped = bs.BeautifulSoup(sauce, \"lxml\")\n self.title = self.souped.title.string\n hrefs = set([clean(i.get(\"href\")) for i in self.souped.findAll(\"a\")])\n self.links = [link for link in hrefs if link.startswith(self.base_url)]\n return self\n\n @property\n def map_page(self):\n lookup = {self.url: {\"title\": self.title, \"links\": self.links}}\n return lookup\n\n\ndef site_map(base_url):\n map_pages = {}\n links_to_map = [base_url]\n\n def check_and_add(url):\n if url not in map_pages:\n page = Page(base_url, url).soup()\n links_to_map.extend(page.links)\n map_pages.update(page.map_page)\n\n while links_to_map:\n check_and_add(links_to_map.pop())\n\n pprint(map_pages)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-18T20:54:42.040", "Id": "217698", "ParentId": "217674", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-18T15:02:30.687", "Id": "217674", "Score": "2", "Tags": [ "python", "python-3.x", "web-scraping" ], "Title": "Simple Web Crawler for Small Sites" }
217674
<p>I'm working with a small bash code which is working fine but i'm just looking if there is better way to formulate this, In this code i'm looking for the Files between year 2002 and 2018 on the 7th column.</p> <p>Below is the working code, </p> <h2>Script:</h2> <pre><code>#!/bin/bash # scriptName: Ftpcal.sh FILE="/home/pygo/Cyberark/ftplogs_3" AWK="/bin/awk" GREP="/bin/grep" USERS="`"$AWK" '$7 &gt;= "2002" &amp;&amp; $7 &lt;= "2018"' $FILE | "$AWK" '{print $3}' | sort -u`" for user in $USERS; do echo "User $user " | tr -d "\n"; "$AWK" '$7 &gt;= "2002" &amp;&amp; $7 &lt;= "2018"' "$FILE" | "$GREP" "$user" | "$AWK" '{ total += $4}; END { print "Total Space consumed: " total/1024/1024/1024 "GB"}'; done | column -t echo "" echo "==============================================================" "$AWK" '$7 &gt;= "2002" &amp;&amp; $7 &lt;= "2018"' "$FILE" | "$AWK" '{ total += $4}; END { print "Total Space consumed by All Users: " total/1024/1024/1024 "GB"}'; echo "" </code></pre> <h2>Actual data Result:</h2> <pre><code>$ sh Ftpcal.sh User 16871 Total Space consumed: 0.0905161GB User 253758 Total Space consumed: 0.0750855GB User 34130 Total Space consumed: 3.52537GB User 36640 Total Space consumed: 0.55393GB User 8490 Total Space consumed: 3.70858GB User tx-am Total Space consumed: 0.18992GB User tx-ffv Total Space consumed: 0.183137GB User tx-ttv Total Space consumed: 17.2371GB User tx-st Total Space consumed: 0.201205GB User tx-ti Total Space consumed: 58.9704GB User tx-tts Total Space consumed: 0.0762068GB ------------ snipped output -------------- ============================================================== Total Space consumed by All Users: 255.368GB </code></pre> <h2>Sample data:</h2> <pre><code>-rw-r--r-- 1 34130 14063436 Aug 15 2002 /current/focus-del/files/from_fix.v.gz -rw-r--r-- 1 34130 14060876 Jul 12 2007 /current/focus-del/files/from1_fix.v.gz -rw-r--r-- 1 34130 58668461 Feb 23 2006 /current/focus-del/files/from_1.tar.gz -rw-r--r-- 1 34130 14069343 Aug 7 20017 /current/focus-del/files/from_tm_fix.v.gz -rw-r--r-- 1 34130 38179000 Dec 7 20016 /current/focus-del/files/from_tm.gds.gz -rw-r--r-- 1 34130 15157902 Nov 22 20015 /current/focus-del/files/from_for.tar.gz -rw-r--r-- 1 34130 97986560 Nov 4 20015 /current/focus-del/files/from_layout.tar </code></pre> <h2>Sample Result:</h2> <pre><code>$ sh Ftp_cal.sh User 34130 Total Space consumed: 0.0808321GB ============================================================== Total Space consumed by All Users: 0.0808321GB </code></pre> <p>I'm okay with any better approach as a review process to make it more robust.</p> <p>Thanks.</p>
[]
[ { "body": "<blockquote>\n<pre><code>AWK=\"/bin/awk\"\n</code></pre>\n</blockquote>\n\n<p>It's easier and more readable if you just set your PATH to something appropriate.</p>\n\n<blockquote>\n<pre><code>USERS=\"`\"$AWK\" '$7 &gt;= \"2002\" &amp;&amp; $7 &lt;= \"2018\"' $FILE | \"$AWK\" '{print $3}' | sort -u`\"\n</code></pre>\n</blockquote>\n\n<p>Backticks should almost always be replaced by <code>$( … )</code>, which is faster because it does not invoke a subshell. </p>\n\n<p>Literal numbers should not be quoted. It happens to still do what you want in awk; in some languages it won't. A bad habit, easily avoided.</p>\n\n<p>There's no need to invoke awk a second time to extract the third field. Simply pair the action <code>{print $3}</code> with the condition (<code>$7 &gt;= …</code>) that's already there.</p>\n\n<p>It's good form to indent the body of a <code>for</code> block (or any other block).</p>\n\n<blockquote>\n<pre><code>echo \"User $user \" | tr -d \"\\n\";\n</code></pre>\n</blockquote>\n\n<p>To suppress a newline on <code>echo</code>, use <code>echo -n</code>.</p>\n\n<blockquote>\n<pre><code>column -t\n</code></pre>\n</blockquote>\n\n<p>This has some awkward consequences, like tabs inside of labels (\"<em>Total<code>TAB</code>Space</em>\") and unaligned numbers. <code>printf</code> will give much prettier results. Both bash and awk provide it.</p>\n\n<blockquote>\n<pre><code>total/1024/1024/1024 \n</code></pre>\n</blockquote>\n\n<p>Nothing wrong with this, as such, but <code>2**30</code> is useful shorthand for gigabyte. </p>\n\n<blockquote>\n<pre><code>==============================================================\n</code></pre>\n</blockquote>\n\n<p>Bash can generate sequences like this with the idiom <code>printf \"=%.0s\" {1..62}</code>. The <code>=</code> is the character and <code>62</code> is the count.</p>\n\n<p>You're traversing the file three times and extracting the same information each time. This is going to get slow as the file grows. Awk has associative arrays: you can store a subtotal for each user, then iterate and print those subtotals at the end of the awk script, accomplishing the whole thing in one go.</p>\n\n<p>Putting it all together:</p>\n\n<pre><code>/bin/awk -vusrfmt=\"User %-20s Total Space consumed: %11.6f GB\\n\" \\\n -vsumfmt=$( printf \"=%.0s\" {1..62} )\"\\nTotal Space consumed by All Users: %.6f GB\\n\" '\n $7 &gt;= 2002 &amp;&amp; $7 &lt;= 2018 { \n subtot[$3]+=$4\n tot+=$4\n }\n END {\n for (u in subtot) printf usrfmt, u, subtot[u] / 2**30\n printf sumfmt, tot / 2**30\n }'\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-20T21:24:24.443", "Id": "421431", "Score": "0", "body": "\"Backticks should almost always be replaced by $( … )\". Why just \"almost always\" and not \"always\" ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-21T00:44:06.340", "Id": "421440", "Score": "0", "body": "I think backticks can improve readability versus nested `$( $ ( ) )`; consider something like `x=$( printf %d $( wc -l $file ) )`; replacing the inner parens with backticks is okay there." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-18T16:31:32.740", "Id": "217680", "ParentId": "217679", "Score": "2" } } ]
{ "AcceptedAnswerId": "217680", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-18T15:45:17.420", "Id": "217679", "Score": "4", "Tags": [ "bash", "linux", "shell" ], "Title": "Shell script to calculate the total space consumed by a user by file-size" }
217679
<p>I have the following object at React state:</p> <pre><code>groups: [ { id: 1, items: [ {id: 1}, {id: 2}, {id: 3} ] }, { id: 3, items: [ {id: 1}, {id: 3}, {id: 4} ] } ] </code></pre> <p>I have written the following functions to add and remove items:</p> <pre><code> removeItem(groupId, itemId) { // make a copy let {groups} = this.state const gIndex= groups.findIndex(g=&gt; g.id == groupId); let items = groups[gIndex].items groups[gIndex].items = items.filter((i) =&gt; i.id !== itemId) this.setState({groups}) } addItem(groupId, itemId) { // make a copy let {groups} = this.state const gIndex = groups.findIndex(g =&gt; g.id == groupId); let items = groups[gIndex].items groups[gIndex].items = items.concat({id: itemId}) this.setState({groups}) } </code></pre> <p>Is there any way to write it cleaner?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-18T17:29:00.660", "Id": "421217", "Score": "0", "body": "\"Note this replicate of my code use 'group' and 'item' that its easier to read than my real code\" Yes, in the lines of a Minimum Complete Verifiable Example. Which would've been commendable, if this was Stack Overflow. However, this is Code Review. Here, we require the real deal. The actual code, within it's actual context. Please include your actual code instead of a simplification. We don't deal well with those. Please consider reading our [FAQ on how to get the best value out of Code Review when asking questions](https://codereview.meta.stackexchange.com/questions/2436/)." } ]
[ { "body": "<p>For the remove function, how about using a map and filter instead:</p>\n\n<pre><code>removeItem (groupId, itemId){\n let {groups} = this.state;\n groups = groups.map((group) =&gt; {\n if(group.id === groupId){ \n group.item = group.item.filter(item =&gt; item.id !== itemId);\n }\n return group;\n });\n this.setState({groups});\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-18T19:28:43.053", "Id": "217690", "ParentId": "217682", "Score": "1" } }, { "body": "<h2>Not a copy</h2>\n\n<pre><code>// make a copy\nlet {groups} = this.state\n</code></pre>\n\n<p>You comment that the line following makes a copy. This is not the case, you are just creating a new reference named <code>groups</code> to the array..</p>\n\n<h2>Use <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const\" rel=\"nofollow noreferrer\"><code>const</code></a></h2>\n\n<p>As you do not change the reference you should define <code>groups</code> as a constant.</p>\n\n<pre><code>const {groups} = this.state;\n// or\nconst groups = this.state.groups;\n</code></pre>\n\n<h2><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push\" rel=\"nofollow noreferrer\"><code>Array.push</code></a> rather than <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/concat\" rel=\"nofollow noreferrer\"><code>Array.concat</code></a></h2>\n\n<p><code>Array.concat</code> creates a new array, it is more efficient to just <code>Array.push</code> a new item to the existing array</p>\n\n<pre><code>groups[gIndex].items = items.concat({id: itemId});\n// can be\ngroups[gIndex].items.push({id: itemId});\n</code></pre>\n\n<h2><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find\" rel=\"nofollow noreferrer\"><code>Array.find</code></a> rather than <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/findIndex\" rel=\"nofollow noreferrer\"><code>Array.findIndex</code></a></h2>\n\n<p>You find the index of the group you want to modify. This complicates the code. If you use <code>Array.find</code> it will return the <code>group</code> and you don't need to index into <code>groups</code> each time.</p>\n\n<pre><code>const gIndex= groups.findIndex(g=&gt; g.id == groupId);\n// becomes \nconst group = groups.find(group =&gt; group.id == groupId);\n</code></pre>\n\n<h2>Common tasks in functions</h2>\n\n<p>Between the two functions you repeat some code. I would imaging that other functions also need to access <code>groups</code> by id, make changes, and set the state of the new content. It would be best to provide functions to do that.</p>\n\n<pre><code>getGroupById(id) { return this.state.groups.find(group =&gt; group.id === id) },\nupdateGroups() { this.setState({groups: this.state.groups}) },\n</code></pre>\n\n<h2>Good naming</h2>\n\n<p>The functions <code>addItem</code> and <code>removeItem</code> do not indicate that they are related to adding/removing from a group. Better names could be <code>removeItemFromGroup</code>, <code>addItemToGroup</code></p>\n\n<h2>Be consistent</h2>\n\n<p>Good code style is consistent. Whether or not you use semicolons you should avoid doing it sometimes, do it always or never. (best option is use them)</p>\n\n<h2>Rewrite</h2>\n\n<p>Using the above points you could rewrite the code as the following.</p>\n\n<p>Added two functions to do the common task of getting by group id and updating the state with groups.</p>\n\n<p>I assume that the <code>groupId</code> will exist as the code you have given indicates this to be so, if the <code>groupId</code> does not exist your code would throw, and so would the following code.</p>\n\n<pre><code>getGroupById(id) { return this.state.groups.find(g =&gt; g.id === id) },\nupdateGroups() { this.setState({groups: this.state.groups}) },\nremoveItemFromGroup(groupId, id) {\n const group = this.getGroupById(groupId);\n group.items = group.items.filter(item =&gt; item.id !== id);\n this.updateGroups();\n},\naddItemToGroup(groupId, id) {\n this.getGroupById(groupId).items.push({id});\n this.updateGroups();\n}, \n</code></pre>\n\n<p>If <code>items</code> are unique per group you can avoid the using <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter\" rel=\"nofollow noreferrer\"><code>Array.filter</code></a> and having to create a new array by splicing the item out of the array using <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice\" rel=\"nofollow noreferrer\"><code>Array.splice</code></a></p>\n\n<pre><code>removeItemFromGroup(groupId, id) {\n const items = this.getGroupById(groupId).items;\n const itemIdx = items.findIndex(item =&gt; item.id === id);\n itemIdx &gt; -1 &amp;&amp; items.splice(itemIdx, 1);\n this.updateGroups();\n},\n</code></pre>\n\n<p>Or if items are not unique, or unique only sometimes you could iterate over the array removing them as you encounter them.</p>\n\n<pre><code>removeItemFromGroup(groupId, id) {\n const items = this.getGroupById(groupId).items;\n var i = items.length;\n while (i--) { items[i].id === id &amp;&amp; items.splice(i, 1) }\n this.updateGroups();\n},\n</code></pre>\n\n<h2>Safer</h2>\n\n<p>The next example guards the function from trying to modify items if the group does not exist.</p>\n\n<pre><code>getGroupById(id) { return this.state.groups.find(g =&gt; g.id === id) },\nupdateGroups() { this.setState({groups: this.state.groups}) },\nremoveItemFromGroup(groupId, id) {\n const group = this.getGroupById(groupId);\n if (group) {\n group.items = group.items.filter(item =&gt; item.id !== id);\n this.updateGroups();\n }\n},\naddItemToGroup(groupId, id) {\n const group = this.getGroupById(groupId);\n if (group) {\n group.items.push({id});\n this.updateGroups();\n }\n}, \n</code></pre>\n\n<p>And just in case you don't want to duplicate items in a group.</p>\n\n<pre><code>// Only adds items if if it does not already exist in the group.\naddItemToGroup(groupId, id) {\n const group = this.getGroupById(groupId);\n if (group &amp;&amp; !group.items.some(item =&gt; item.id === id)) {\n group.items.push({id});\n this.updateGroups();\n }\n}, \n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-19T08:48:31.090", "Id": "421269", "Score": "0", "body": "Fantastic answer, thanks! However, I have just realized `this.state.groups` should be treated as immutable (https://reactjs.org/docs/react-component.html#state). That means it should be cloned and then updated using `setState()` strictly. This is a problem my original code has already... So maybe the final answer could be https://jsfiddle.net/tnug4v9L/1/ ? (I had to remove some of your class methods, because the operations should be done in the clone instead of the class properties)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-19T13:06:03.080", "Id": "421297", "Score": "1", "body": "@Rashomon Strictly would be enforced (the state data would be frozen and impossible to change) You are safe mutating the state because you set the state at the end of the function with `this.setState` The state can not be changed while your function is executing so there is no danger of losing state data. All the examples in my answer are safe to use as they are. As for the two extra class functions, that is up to you, but should does not mean must do, JavaScript is fully capable of enforcing such rules, so if you can do, then should do is only advisory." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-19T13:10:53.357", "Id": "421299", "Score": "0", "body": "Thank you very much for your explanations. Im new to React so I will study carefully the behaviour of the state" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-18T21:27:30.060", "Id": "217701", "ParentId": "217682", "Score": "1" } } ]
{ "AcceptedAnswerId": "217701", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-18T16:52:30.873", "Id": "217682", "Score": "2", "Tags": [ "javascript", "object-oriented", "array" ], "Title": "Remove and Add items from array in nested javascript object" }
217682
<p><strong>The task</strong></p> <blockquote> <p>Implement division of two positive integers without using the division, multiplication, or modulus operators. Return the quotient as an integer, ignoring the remainder.</p> </blockquote> <p><strong>My solution</strong></p> <pre><code>const division = (dividend, divisor) =&gt; { let remainder = null; let quotient = 1; const sign = ((dividend &gt; 0 &amp;&amp; divisor &lt; 0) || (dividend &lt; 0 &amp;&amp; divisor &gt; 0)) ? ~1 : 1; let tempdividend = Math.abs(dividend); let tempdivisor = Math.abs(divisor); if (tempdivisor === tempdividend) { remainder = 0; return sign; } else if (tempdividend &lt; tempdivisor) { remainder = dividend &lt; 0 ? sign &lt; 0 ? ~tempdividend : tempdividend : tempdividend; return 0; } while (tempdivisor &lt;&lt; 1 &lt;= tempdividend) { tempdivisor = tempdivisor &lt;&lt; 1; quotient = quotient &lt;&lt; 1; } quotient = dividend &lt; 0 ? (sign &lt; 0 ? ~quotient : quotient) + division(~(tempdividend-tempdivisor), divisor) : (sign &lt; 0 ? ~quotient : quotient) + division(tempdividend-tempdivisor, divisor); return quotient; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-18T23:50:46.037", "Id": "421243", "Score": "1", "body": "Your function does not work, very sloppy. I am amazed you found two arguments that would return the correct result. `division(-1,1)` returns `-2, `-2 / -1` returns `3` and worst any value divide 0 does not return at all." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-19T08:56:19.297", "Id": "421270", "Score": "1", "body": "It works for positive integers (as the task ask for). But you are right about the other stuff. Will fix it. @Blindman67" } ]
[ { "body": "<p>Is bitwise operation mandatory? There's a much simpler way</p>\n\n<pre><code>const divide = (dividend, divisor) =&gt; {\n let quotient = 0, neg = false;\n\n if( (dividend &lt; 0 &amp;&amp; divisor &gt; 0) || (dividend &gt; 0 &amp;&amp; divisor &lt; 0) ){ neg = true; }\n\n dividend = Math.abs(dividend);\n divisor = Math.abs(divisor);\n\n if(dividend &lt; divisor) {return 0;}\n else if(dividend &gt; 0 &amp;&amp; divisor != 0){\n while(dividend &gt;= divisor){\n dividend -= divisor;\n ++quotient;\n }\n } else { // handle what you want to do for those cases..}\n\n return neg ? -quotient : quotient;\n}\n</code></pre>\n\n<p>You get your quotient and remainder is ignored. Just do a check if dividend is negative or divisor is 0. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-18T20:01:29.463", "Id": "421227", "Score": "1", "body": "Welcome to Code Review! Better check dividend sign *before* comparing to divisor." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-18T23:49:22.463", "Id": "421242", "Score": "1", "body": "Also first if statement should be `<` not `>` and ... It may be the simple way, but divide(2**32-1, 1) may take some time to complete (On average device 11 seconds), even longer if its `divide(Number.MAX_SAFE_INTEGER, -1)` (about 22 years on average device) There is a point where complexity provides practical solutions." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-19T04:15:52.357", "Id": "421248", "Score": "0", "body": "@greybeard I have fixed my answer to accommodate the negative cases. Thanks for the suggestion." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-19T04:23:09.653", "Id": "421249", "Score": "0", "body": "@Blindman67 I have fixed the comparison. As for the division case, your case is a valid example that I have taken into account before posting the answer. However, there is no one solution to solve them all, and I thought if the OP was handling smaller cases (possible range was not mentioned), and has already a solution to handle complex cases, why not a simpler one then." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-19T15:50:18.860", "Id": "421313", "Score": "0", "body": "@Dblaze47 Oh my bad, my numbers were way wrong 32Bit int is ~7 seconds, and MAX_SAFE_INTEGER is about ~5 months. Anyways besides the point, \"Why not a simpler one then.\" Why? This is code review, the focus is the review of OP's code, its style, its logic, and with that you can add example alternative/s demonstrating the points reviewed. The OP is after all looking for feedback on their code. If alternatives were the quest then google would be the better path, don't you think." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-20T16:03:55.763", "Id": "421391", "Score": "0", "body": "@Blindman67 Thanks for your feedback. Actually the OP didn't ask for any alternatives, but just stated the task and what was his solution. So I just assumed the task required help and suggested an alternate. You are right, this is not Stackoverflow. I will keep this in mind for all future references." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-18T19:05:02.387", "Id": "217687", "ParentId": "217683", "Score": "3" } } ]
{ "AcceptedAnswerId": "217687", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-18T16:57:37.567", "Id": "217683", "Score": "3", "Tags": [ "javascript", "algorithm", "programming-challenge", "ecmascript-6", "bitwise" ], "Title": "Division without using division, multiplication, or modulus operators" }
217683
<p>The code I'm bringing forward is for a vertical menu, where I needed a marker to do the following:</p> <ul> <li><p>When hovering over a link the marker should slide down next to it.</p></li> <li><p>When not hovering over a link the marker should return to the side of the current selected link (the default being the first link).</p></li> <li><p>When a link is clicked the marker should remain next to the clicked link, unless another link is being hovered over.</p></li> </ul> <p>What I've done in jQuery is add a class ('.staydown0','.staydown1' or '.staydown2') to the marker div ('#slide') when one one of the links ('#menulink1','#menulink2' or '#menulink3') is clicked, and remove any other classes that would have it be situated next to one of the other links.</p> <p>Then I've set jQuery to add a class ('.movedown0','.movedown1' or '.movedown2') to the marker div ('#slide') when the mouse hovers over one of the links ('#menulink1','#menulink2' or '#menulink3'), and remove the class when the mouse stops hovering over the link.</p> <p><strong>The code works, but it is redundant. How could I go about abstracting it?</strong></p> <p>I've already asked a similar question recently where I only had the "hover" part of the menu set up, and <a href="https://codereview.stackexchange.com/questions/217341/sliding-marker-on-link-hover-with-jquery"> it was solved.</a></p> <p>But I am a beginner in javascript and jQuery, and even though I've managed to understand the solution that was offered to me in the previous question, I am at a loss as to how to extrapolate that knowledge to abstracting this more convoluted code.</p> <p><a href="https://codepen.io/AlbertMcTorre/pen/axyxwO" rel="nofollow noreferrer">CODEPEN</a></p> <p>HTML(Pug):</p> <pre><code>.staydown0#slide #menu a.menulink#menulink1(href="#") p RED a.menulink#menulink2(href="#") p BLUE a.menulink#menulink3(href="#") p GREEN </code></pre> <p>CSS (Sass)</p> <pre><code>a color: white text-decoration: none #slide width: 10px height: 30px position: absolute border-radius: 15px transition: 0.3s ease-in-out #slide.staydown0 margin-top: 0px background-color: red #slide.staydown1 margin-top: 40px background-color: blue #slide.staydown2 margin-top: 80px background-color: green #slide.movedown0 margin-top: 0px background-color: red #slide.movedown1 margin-top: 40px background-color: blue #slide.movedown2 margin-top: 80px background-color: green #menu margin-left: 30px .menulink height: 40px width: 70px display: block .menulink p height: 30px width: 70px margin: 0px border-radius: 15px display: flex align-items: center justify-content: center #menulink1 p background: red #menulink2 p background: blue #menulink3 p background: green </code></pre> <p>jQuery</p> <pre><code>$('#menulink1').hover( function(){ $('#slide').addClass('movedown0'); }, function(){ $('#slide').removeClass('movedown0') }); $('#menulink2').hover( function(){ $('#slide').addClass('movedown1'); }, function(){ $('#slide').removeClass('movedown1') }); $('#menulink3').hover( function(){ $('#slide').addClass('movedown2'); }, function(){ $('#slide').removeClass('movedown2') }); /////// $('#menulink1').on( 'click', function(){ $('#slide').addClass('staydown0').removeClass('staydown1 staydown2'); }); $('#menulink2').on( 'click', function(){ $('#slide').addClass('staydown1').removeClass('staydown0 staydown2'); }); $('#menulink3').on( 'click', function(){ $('#slide').addClass('staydown2').removeClass('staydown0 staydown1'); }); </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-18T17:47:11.020", "Id": "217685", "Score": "1", "Tags": [ "javascript", "beginner", "jquery", "html", "sass" ], "Title": "Sliding marker on link hover and click with jQuery" }
217685
<p><strong>The task</strong></p> <blockquote> <p>Given an array of integers where every integer occurs three times except for one integer, which only occurs once, find and return the non-duplicated integer.</p> <p>For example, given [6, 1, 3, 3, 3, 6, 6], return 1. Given [13, 19, 13, 13], return 19.</p> <p>Do this in O(N) time and O(1) space.</p> </blockquote> <p><strong>My solution</strong></p> <pre><code>const arr = [6, 1, 3, 3, 3, 6, 6]; const findUnique = arr =&gt; { const set = new Set(); return arr.reduce((sum, n) =&gt; set.has(n) ? sum - n : (set.add(n), sum + 2 * n), 0) / 2; }; </code></pre> <p>Because of the <code>Set</code> it has O(n) space, I guess. I currently don't know how to solve it with O(1) space.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-18T19:57:13.210", "Id": "421226", "Score": "1", "body": "(Count \"each bit\" separately, return combined results mod 3?)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-19T08:59:47.750", "Id": "421271", "Score": "0", "body": "Would that work with numbers larger than `3`? E.g. `[13, 12, 12, 3, 3, 3, 12]` @greybeard" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-19T09:27:26.750", "Id": "421275", "Score": "0", "body": "(I don't get the example - `[13, 12, 12, 3, 12, 3, 3, 3, 12]`, n=4?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-19T09:55:00.410", "Id": "421276", "Score": "0", "body": "I don't see why not, *occurs `n` times except for one with `n` known in advance* seems crucial. (\"The well known eXOR solution to *find sole element occurring an odd number of times*\" is just a special case.)" } ]
[ { "body": "<h2>Feedback</h2>\n<p>Good job using <code>const</code> in your code for values and functions that don't get re-assigned. I don't often see multi-line ternary operators (especially within arrow functions) and that one in your code is a bit on the complex side.</p>\n<p>You are correct- your code does not have <span class=\"math-container\">\\$O(1)\\$</span> space complexity.</p>\n<hr />\n<h3>Alternate approach</h3>\n<p>Originally I thought about suggesting <a href=\"https://codereview.stackexchange.com/revisions/219133/4\">an approach that used <code>.findIndex()</code></a> but you pointed out that would no longer be <span class=\"math-container\">\\$O(n)\\$</span> complexity.</p>\n<p>I also thought about suggesting you sort the array, then iterate over each element with <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find\" rel=\"nofollow noreferrer\"><code>Array.find()</code></a>, looking for the first item that doesn't match the next item in the list. However, I forgot that sorting the array is not exactly linear time.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-25T23:52:43.817", "Id": "423270", "Score": "0", "body": "how can we sort the array in so fast?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-25T23:54:48.807", "Id": "423271", "Score": "0", "body": "@JorgeFernández - what do you mean \"_in so fast_\"?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-25T23:56:26.227", "Id": "423273", "Score": "0", "body": "how can we sort the array in linear time?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-26T00:06:34.847", "Id": "423275", "Score": "0", "body": "You are correct- thanks for reminding me of that... I have updated my answer" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-26T00:32:01.083", "Id": "423277", "Score": "0", "body": "No problem! +1 .." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-25T21:50:57.500", "Id": "219133", "ParentId": "217691", "Score": "1" } }, { "body": "<p>I'm going to take @greybeard's internet points, since he apparently doesn't want them enough to type this ;-). </p>\n\n<p>You need to keep in mind that <span class=\"math-container\">\\$O(x)\\$</span> really means <span class=\"math-container\">\\$O(C \\times x + ...)\\$</span> for some value C. As long as you keep C a constant, you can do whatever you want. Thus, <span class=\"math-container\">\\$O(n)\\$</span> can really mean <span class=\"math-container\">\\$O(2000 \\times n)\\$</span>, and <span class=\"math-container\">\\$O(1)\\$</span> can really mean <span class=\"math-container\">\\$O(10^6)\\$</span>, etc.</p>\n\n<p>In this case, what @greybeard has suggested is that you count the individual set bits in all the numbers, and keep the counts in separate positions. Thus, for an array of 32-bit numbers, you would keep 32 separate counts.</p>\n\n<p>Since you have to perform in <span class=\"math-container\">\\$O(n)\\$</span>, you could spend one loop through your input array determining how many bits you need to keep, so even very large numbers won't break the solution. </p>\n\n<p>So let's pretend all the integers are 8-bit, just because. That doesn't mean there aren't a large number of integers, just that all the values in the array are in the range <code>[0, 256)</code>. What does that give you?</p>\n\n<p>(If you don't know, <code>&amp;</code> and <code>&lt;&lt;</code> are <a href=\"https://en.wikipedia.org/wiki/Bitwise_operation#C-family\" rel=\"noreferrer\">\"bitwise operators.\"</a> </p>\n\n<pre><code>for each element in array:\n for each bit_offset in [0..8):\n if element &amp; (1 &lt;&lt; bit_offset):\n count[bit_offset] += 1\n</code></pre>\n\n<p>What does that get you? It gets you a set of 8 separate counts, one for each bit in the 8-bit numbers. (Feel free to replace 8 with 64 if you like...)</p>\n\n<p>Each count represents the number of times that bit appeared \"set\" in the input array. Now, according to your premise, all the numbers but one appear 3 times. So all the set bits will appear a multiple of 3 times. (Since set bits might be duplicated among numbers, it won't be \"exactly 3 times\" but instead \"a multiple\").</p>\n\n<p>On the other hand, the one value that appears one time will have its set bits added to the counts one time. So there are two possibilities for each of the <code>count[i]</code> values (note: <code>k[i]</code> is some numbers that don't matter):</p>\n\n<ul>\n<li><p>Either the unique value does not have this bit set: <code>count[i] = 3 * k[i]</code></p></li>\n<li><p>Or the unique value <em>does</em> have this bit set: <code>count[i] = 3 * k[i] + 1</code></p></li>\n</ul>\n\n<p>So you have to evaluate each <code>count[i]</code> in order, and determine which form it takes:</p>\n\n<pre><code>result = 0\nfor bit_offset in [0..8):\n if count[bit_offset] % 3 == 1:\n result = set_bit(result, bit_offset)\n</code></pre>\n\n<p>Where <code>set_bit</code> is spelled <code>|= 1 &lt;&lt; bit_offset</code> in most C-derived languages.</p>\n\n<p>In terms of efficiency, what happens?</p>\n\n<ul>\n<li><p>You might process the array once by iterating over it to discover the largest number of bits required to be counted.</p></li>\n<li><p>You create an array of N_BITS counts, initialized to zero. Since N_BITS is not related to the size of the input array, this is considered <span class=\"math-container\">\\$O(1)\\$</span>. (Actually <span class=\"math-container\">\\$O(32)\\$</span> most likely, or maybe 64... But that's still 1 in big-O-hio!)</p></li>\n<li><p>You iterate over the array one time, iterating over N_BITS bit values within each element. (So effectively <span class=\"math-container\">\\$O(64 \\times n)\\$</span>, or less.) You compute the count values here.</p></li>\n<li><p>You iterate over the N_BITS counts, determining the bits that will be set in the result, and setting them.</p></li>\n<li><p>You return the result.</p></li>\n</ul>\n\n<p>So your runtime is <span class=\"math-container\">\\$O(2 \\times n)\\$</span>, or just n if you hard-code the N_BITS. And your memory is <span class=\"math-container\">\\$O(64)\\$</span> or less, which is just 1.</p>\n\n<p>Let's look at the example you gave in the comments:</p>\n\n<pre><code>[13, 12, 12, 3, 3, 3, 12]\n</code></pre>\n\n<p>First, rewrite those to binary (8 + 4 + 2 + 1):</p>\n\n<pre><code>[ 0b1101, 0b1100, 0b1100, 0b0011, 0b0011, 0b0011, 0b1100]\n</code></pre>\n\n<p>Now, count the set bits, just adding all the 1's in each column (no carry!):</p>\n\n<pre><code>[ 0b1101, \n 0b1100, \n 0b1100, \n 0b0011, \n 0b0011, \n 0b0011, \n 0b1100]\n --------\n 4434 -&gt; counts = [ 4, 4, 3, 4 ]\n</code></pre>\n\n<p>Next, our output will be 1 if the count is 1 (mod 3) and 0 if the count is 0 (mod 3). So [4,4,3,4] mod 3 are [1,1,0,1]:</p>\n\n<pre><code>result = 0b1101 \n</code></pre>\n\n<p>Which is 13.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-26T01:01:57.070", "Id": "219143", "ParentId": "217691", "Score": "5" } }, { "body": "<p>Cudos to <a href=\"https://codereview.stackexchange.com/a/219143/93149\">Austin Hastings</a> for spelling out how counting, for each bit, the number of times it is set solves the problem.<br>\nI was thinking of bit-bashing code, Python for lack of ECMAScript prowess:</p>\n\n<pre><code>''' bit-wise modular arithmetic: mod 3 '''\n\n\ndef bits_mod_3(a):\n ''' Return the bits in A \"mod 3\". '''\n one, two = bits_0_mod_3(a)\n return one &amp; ~two, two &amp; ~one\n\n\ndef bits_0_mod_3(a):\n ''' Return the bits in A \"mod 3\":\n 0 for no bit set, 3 for natural multiple of 3. '''\n one, two = 0, 0\n for v in a:\n one, carry = one ^ v, one &amp; v\n two, carry = two ^ carry, two &amp; carry\n one |= carry # carry from bit 2 means 4: congruent 1 mod 3\n # above the way I think about the approach, \"simplified\" below\n # carry = one &amp; v\n # one = (one ^ v) | two &amp; carry\n # two ^= carry\n # alternatively, one could code \"a mod-3 counter\" directly:\n # one = one &amp; ~v | ~(one | two) &amp; v\n # two = two &amp; ~v | carry\n return one, two\n\n\ndef once(a):\n \"\"\" Return \"bits in A with a count of 1 mod 3\". \"\"\"\n return bits_mod_3(a)[0]\n\n\nif __name__ == '__main__':\n print(once((13, 12, 12, 3, 3, 3, 12)))\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-26T08:31:16.833", "Id": "423310", "Score": "0", "body": "Got to run. Why *mathematics* and *statistics*, but *arithmetic*? Syntax colouring with multi-line string literals is weird." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-26T08:29:56.120", "Id": "219160", "ParentId": "217691", "Score": "0" } } ]
{ "AcceptedAnswerId": "219143", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-18T19:34:46.893", "Id": "217691", "Score": "2", "Tags": [ "javascript", "algorithm", "programming-challenge", "ecmascript-6", "iteration" ], "Title": "Find non-duplicated integer in a list where every integer occurs three times except for one integer" }
217691
<p>I made a Connect Four AI with minimax algorithm. It's my first bigger JavaFX project. Any help for improvements would be really appreciated.</p> <p><a href="https://i.stack.imgur.com/oDsrJ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/oDsrJ.png" alt="screenshot"></a></p> <p>Board:</p> <pre><code>import java.util.ArrayList; class Move { private int row, col; public Move(int row, int col) { this.row = row; this.col = col; } public int getRow() { return row; } public int getCol() { return col; } @Override public String toString() { return "Move{" + "row=" + row + ", col=" + col + '}'; } } public class Board { private final int playerX = 1; private final int playerO = 2; private int rows; private int cols ; private int board[][]; private int moves; private Move lastMove; private Ai ai; public Board(int rows, int cols, int depth) { this.rows = rows; this.cols = cols; this.board = new int[rows][cols]; this.moves = 0; this.lastMove = new Move(0, 0); this.ai = new Ai(this, depth); } public int[][] getBoard() { return board; } public int getMoves() { return moves; } public Move getLastMove() { return lastMove; } public void doMove(Move m, int player) { board[m.getRow()][m.getCol()] = player; } public void undoMove(Move m) { board[m.getRow()][m.getCol()] = 0; } public void doAiMove(int player) { Move best = ai.getBestMove(); board[best.getRow()][best.getCol()] = player; moves++; lastMove = best; } private Move generateMove(int col) { for(int r = rows - 1; r &gt;= 0; r--) { if(board[r][col] == 0) { return new Move(r, col); } } return null; } public ArrayList&lt;Move&gt; generateMoves() { ArrayList&lt;Move&gt; moves = new ArrayList&lt;&gt;(); for(int c = 0; c &lt; cols; c++) { Move m = generateMove(c); if(m != null) { moves.add(m); } } return moves; } public void playerMove(int col) { Move m = generateMove(col); if(m != null) { doMove(m, playerX); moves++; lastMove = m; } } private int checkWin(int row, int col, int player) { if(col &gt;= cols - 4) { if(board[row][col] == player &amp;&amp; board[row][col-1] == player &amp;&amp; board[row][col-2] == player &amp;&amp; board[row][col-3] == player) { return player; } } if(col &lt;= cols - 4) { if(board[row][col] == player &amp;&amp; board[row][col+1] == player &amp;&amp; board[row][col+2] == player &amp;&amp; board[row][col+3] == player) { return player; } } if(row &lt;= rows - 4) { if(board[row][col] == player &amp;&amp; board[row+1][col] == player &amp;&amp; board[row+2][col] == player &amp;&amp; board[row+3][col] == player) { return player; } } if(row &gt;= rows - 3) { if(board[row][col] == player &amp;&amp; board[row-1][col] == player &amp;&amp; board[row-2][col] == player &amp;&amp; board[row-3][col] == player) { return player; } } if(col &gt;= cols - 4 &amp;&amp; row &gt;= rows - 3) { if(board[row][col] == player &amp;&amp; board[row-1][col-1] == player &amp;&amp; board[row-2][col-2] == player &amp;&amp; board[row-3][col-3] == player) { return player; } } if(col &lt;= cols - 4 &amp;&amp; row &lt;= rows - 4) { if(board[row][col] == player &amp;&amp; board[row+1][col+1] == player &amp;&amp; board[row+2][col+2] == player &amp;&amp; board[row+3][col+3] == player) { return player; } } if(col &lt;= cols - 4 &amp;&amp; row &gt;= rows - 3) { if(board[row][col] == player &amp;&amp; board[row-1][col+1] == player &amp;&amp; board[row-2][col+2] == player &amp;&amp; board[row-3][col+3] == player) { return player; } } if(col &gt;= cols - 4 &amp;&amp; row &lt;= rows - 4) { if(board[row][col] == player &amp;&amp; board[row+1][col-1] == player &amp;&amp; board[row+2][col-2] == player &amp;&amp; board[row+3][col-3] == player) { return player; } } return 0; } public int checkBoardState(Move lastMove, int board[][]) { int x = checkWin(lastMove.getRow(), lastMove.getCol(), playerX); int o = checkWin(lastMove.getRow(), lastMove.getCol(), playerO); if(x == playerX) return x; if(o == playerO) return o; if(moves == rows * cols) return 0; return -1; } } </code></pre> <p>Ai:</p> <pre><code>import java.util.ArrayList; public class Ai { private final int playerX = 1; private final int playerO = 2; private Board board; private int depth; private Move bestMove; public Ai(Board board, int depth) { this.board = board; this.depth = depth; } /*public void setDepth(int depth) { this.depth = depth; }*/ private int min(int depth, int alpha, int beta) { ArrayList&lt;Move&gt; moves = board.generateMoves(); int minValue = beta; if(depth == 0 || moves.size() == 0) { return evaluate(board.getBoard()); } for(Move m: moves) { board.doMove(m, playerO); int v = max(depth - 1, alpha, minValue); board.undoMove(m); if(v &lt; minValue) { minValue = v; if(minValue &lt;= alpha) break; if(depth == this.depth) { bestMove = m; } } } return minValue; } private int max(int depth, int alpha, int beta) { ArrayList&lt;Move&gt; moves = board.generateMoves(); int maxValue = alpha; if(depth == 0 || moves.size() == 0) { return evaluate(board.getBoard()); } for(Move m: moves) { board.doMove(m, playerX); int v = min(depth - 1, maxValue, beta); board.undoMove(m); if(v &gt; maxValue) { maxValue = v; if(maxValue &gt;= beta) break; if(depth == this.depth) { bestMove = m; } } } return maxValue; } private int evaluateSegment(int[] s) { int countX = 0, countO = 0; for(int i = 0; i &lt; s.length; i++) { if(s[i] == playerX) countX++; if(s[i] == playerO) countO++; } if(countX == 0) { if(countO == 4) return -1000; if(countO == 3) return -50; if(countO == 2) return -10; if(countO == 1) return -1; } if(countO == 0) { if(countX == 4) return 1000; if(countX == 3) return 50; if(countX == 2) return 10; if(countX == 1) return 1; } return 0; } private int evaluate(int board[][], int row, int col) { int rows = board.length; int cols = board[0].length; int score = 0; if(col &gt;= cols - 4) { score += evaluateSegment(new int[] {board[row][col], board[row][col-1], board[row][col-2], board[row][col-3]}); } if(col &lt;= cols - 4) { score += evaluateSegment(new int[] {board[row][col], board[row][col+1], board[row][col+2], board[row][col+3]}); } if(row &lt;= rows - 4) { score += evaluateSegment(new int[] {board[row][col], board[row+1][col], board[row+2][col], board[row+3][col]}); } if(row &gt;= rows - 3) { score += evaluateSegment(new int[] {board[row][col], board[row-1][col], board[row-2][col], board[row-3][col]}); } if(col &gt;= cols - 4 &amp;&amp; row &gt;= rows - 3) { score += evaluateSegment(new int[]{board[row][col], board[row-1][col-1], board[row-2][col-2], board[row-3][col-3]}); } if(col &lt;= cols - 4 &amp;&amp; row &lt;= rows - 4) { score += evaluateSegment(new int[]{board[row][col], board[row+1][col+1], board[row+2][col+2], board[row+3][col+3]}); } if(col &lt;= cols - 4 &amp;&amp; row &gt;= rows - 3) { score += evaluateSegment(new int[]{board[row][col], board[row-1][col+1], board[row-2][col+2], board[row-3][col+3]}); } if(col &gt;= cols - 4 &amp;&amp; row &lt;= rows - 4) { score += evaluateSegment(new int[]{board[row][col], board[row+1][col-1], board[row+2][col-2], board[row+3][col-3]}); } return score; } private int evaluate(int board[][]) { int score = 0; for(int r = 0; r &lt; board.length; r++) { for(int c = 0; c &lt; board[r].length; c++) { score += evaluate(board, r, c); } } return score; } public Move getBestMove() { max(depth, Integer.MIN_VALUE, Integer.MAX_VALUE); return bestMove; } } </code></pre> <p>Main:</p> <pre><code>import javafx.application.Application; import javafx.event.EventHandler; import javafx.geometry.Insets; import javafx.scene.Scene; import javafx.scene.canvas.Canvas; import javafx.scene.canvas.GraphicsContext; import javafx.scene.control.Button; import javafx.scene.layout.GridPane; import javafx.scene.layout.VBox; import javafx.scene.paint.Color; import javafx.stage.Stage; import javafx.event.ActionEvent; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class Main extends Application { private final int rows = 6; private final int cols = 7; private final int playerX = 1; private final int playerO = 2; private final int canvasHeight = 600; private final int canvasWidth = 700; private final double cellHeight = (double) canvasHeight / rows; private final double cellWidth = (double) canvasWidth / cols; private int clickedButton = -1; private Board board; private int depth = 8; public Main() { board = new Board(rows, cols, depth); } @Override public void start(Stage primaryStage) { primaryStage.setTitle("Connect Four"); GridPane gridPane = new GridPane(); gridPane.setPadding(new Insets(20.0, 0.0, 20.0, 0.0)); VBox box = new VBox(); box.setPadding(new Insets(20.0,20.0,20.0,50.0)); Canvas canvas = new Canvas(canvasWidth, canvasHeight); GraphicsContext gc = canvas.getGraphicsContext2D(); drawBoard(gc); Button buttonArray[] = new Button[cols]; for(int i = 0; i &lt; cols; i++) { buttonArray[i] = new Button("Input"); buttonArray[i].setMinWidth(cellWidth); buttonArray[i].setMaxWidth(cellWidth); buttonArray[i].setId(""+i); gridPane.add(buttonArray[i], i, 0); } for(Button b: buttonArray) { b.setOnAction(new EventHandler&lt;ActionEvent&gt;() { @Override public void handle(ActionEvent event) { if(board.getMoves() % 2 == 0 &amp;&amp; board.checkBoardState(board.getLastMove(), board.getBoard()) == -1) { clickedButton = Integer.valueOf(b.getId()); board.playerMove(clickedButton); repaintCanvas(gc); for(Button button: buttonArray) { button.setDisable(true); } if(board.getMoves() % 2 == 1 &amp;&amp; board.checkBoardState(board.getLastMove(), board.getBoard()) == -1) { ExecutorService es = Executors.newFixedThreadPool(1); Runnable r = new Runnable() { @Override public void run() { board.doAiMove(playerO); repaintCanvas(gc); for(Button button: buttonArray) { button.setDisable(false); } } }; es.execute(r); es.shutdown(); } } } }); } VBox b = new VBox(); b.setPadding(new Insets(20.0,20.0,20.0,350.0)); Button restart = new Button("Restart"); restart.setOnAction(new EventHandler&lt;ActionEvent&gt;() { @Override public void handle(ActionEvent event) { board = new Board(rows, cols, depth); repaintCanvas(gc); } }); b.getChildren().add(restart); box.getChildren().addAll(gridPane, canvas, b); primaryStage.setScene(new Scene(box, 800, 800)); primaryStage.setResizable(false); primaryStage.show(); } private void drawBoard(GraphicsContext gc) { gc.setFill(Color.rgb(128, 255, 0)); gc.fillRect(0, 0, canvasWidth, canvasHeight); gc.setFill(Color.BLACK); for(int i = 0; i &lt;= rows; i++) { gc.strokeLine(0, i * cellHeight, canvasWidth, i * cellHeight); } for(int i = 0; i &lt;= cols; i++) { gc.strokeLine(i * cellWidth, 0, i * cellWidth, canvasHeight); } int offset = 3; int board[][] = this.board.getBoard(); for(int r = 0; r &lt; rows; r++) { for(int c = 0; c &lt; cols; c++) { if(board[r][c] == playerX) { gc.setFill(Color.RED); gc.fillOval(c * cellHeight, r * cellWidth, cellWidth - offset, cellHeight - offset); } if(board[r][c] == playerO) { gc.setFill(Color.BLUE); gc.fillOval(c * cellHeight, r * cellWidth, cellWidth - offset, cellHeight - offset); } } } } private void repaintCanvas(GraphicsContext gc) { gc.clearRect(0, 0, canvasWidth, canvasHeight); drawBoard(gc); } public static void main(String[] args) { Main m = new Main(); launch(args); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-18T22:59:46.330", "Id": "421240", "Score": "0", "body": "Note enough detail for an answer - but those colours are hurting the eyes!" } ]
[ { "body": "<p>The <code>Move</code> class could have its getters removed by making use of <code>final</code> since its members <code>row</code> and <code>col</code> are immutable:</p>\n\n<pre><code>class Move {\n\n public final int row;\n public final int col;\n\n public Move(int row, int col) {\n this.row = row;\n this.col = col;\n }\n\n @Override\n public String toString() {\n return \"Move{\" +\n \"row=\" + row +\n \", col=\" + col +\n '}';\n }\n}\n</code></pre>\n\n<p>Then just access it directly like <code>move.row</code>. There's a discussion on the idea <a href=\"https://stackoverflow.com/questions/6927763/immutable-type-public-final-fields-vs-getter\">here</a>. Of course, if the members were mutable, it would be a different story, but <code>int</code>s can't be altered.</p>\n\n<p>I also put the declarations on separate lines.</p>\n\n<hr>\n\n<p>It may be a better idea to make use of constants or an Enum for your <code>playerX</code> and <code>O</code> weights here (I'm assuming they're weights):</p>\n\n<pre><code>if(countO == 4) return -1000;\nif(countO == 3) return -50;\nif(countO == 2) return -10;\nif(countO == 1) return -1;\n</code></pre>\n\n<p>In both cases, you're using the same numbers, just negated in the first case. If you ever change the weights in the future, you may forget to change the values in both places, and may get odd behavior as a result. Something like this may be better (although with better names):</p>\n\n<pre><code>final int EXTREME_WEIGHT = 1000;\nfinal int HIGH_WEIGHT = 50;\nfinal int MEDIUM_WEIGHT = 10;\nfinal int LOW_WEIGHT = 1;\n\nif(countX == 0) {\n if(countO == 4) return -EXTREME_WEIGHT;\n if(countO == 3) return -HIGH_WEIGHT;\n if(countO == 2) return -MEDIUM_WEIGHT;\n if(countO == 1) return -LOW_WEIGHT;\n}\n\nif(countO == 0) {\n if(countX == 4) return EXTREME_WEIGHT;\n if(countX == 3) return HIGH_WEIGHT;\n if(countX == 2) return MEDIUM_WEIGHT;\n if(countX == 1) return LOW_WEIGHT;\n}\n</code></pre>\n\n<p>Now (when the names are corrected), the values will be self-explanatory, and you aren't risking asymmetrical changes in the future.</p>\n\n<p>You may also find that a <code>switch</code> or <code>Map</code> would work well here too, although any gain from them would be unnecessary.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-18T20:14:47.357", "Id": "217695", "ParentId": "217693", "Score": "2" } } ]
{ "AcceptedAnswerId": "217695", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-18T19:42:51.073", "Id": "217693", "Score": "5", "Tags": [ "java", "algorithm", "ai", "javafx", "connect-four" ], "Title": "JavaFX Connect Four AI" }
217693
<p>I am a beginner to Python (and programming overall) and I decided that it would be funny if I wrote a program that could convert Letters/Numbers to these "Letter Emojis" in Discord. It works but I am quite unsure if this is the best way to do it. There are also some bugs caused by adding spaces before actually typing Letters/Numbers. I commented it as precisely as I could to make the Code as understandable as possible</p> <pre class="lang-py prettyprint-override"><code>from tkinter import * root = Tk() # defines the funtion click which gets called when the submitButton1 is pressed def click(): # makes sure the list is empty in case the user presses the button again to convert something new result.clear() # saves the text which is entered in the textentry box, this later gets converted to "Discord Letters" entered_text=textentry.get() # deletes the output box in case the user presses the button again to convert something new output.delete(1.0, END) # the function to convert a String to "Discord Letters" discord(entered_text) # loop which gets the length of the string typed in the textentry box and then outputs it to the output textbox for i in range(len(entered_text)): output.insert(END, result[i]) # A List in which the converted Letters are stored it's later used to output the converted Letters in a Textbox result = [] # the function to convert a String to "Discord Letters" def discord(word): # List of numbers from 0-9 , is used to check the string for numbers and then convert them # to "Discord Digits" since they have a different syntax in discord than Letters chars = set('0123456789') s = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'} # In case the User enters spaces they get removed since they just cause trouble word = word.replace(" ", "") word = word.lower() w = word for i in range(len(w)): # checks if the string has a number and outputs accordingly if any((c in chars) for c in w[i]): list_one = ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", ] result.append(':' + list_one[int(w[i])] + ":" + " ") # checks if the string has letter and outputs accordingly (might be unnecessary) elif any((c in s) for c in w[i]): result.append(':regional_indicator_' + w[i] + ":" + " ") else: # In case the user inputs something wrong print("False Input") root.title("Discord Letter Converter") # TextInput textentry = Entry(root, width=20, bg="white") textentry.pack() # submitButton submitButton1 = Button(root, text="Submit", width=6, command=click)# submitButton1.pack() # TextOutput output = Text(root, width=75, height=6, wrap=WORD, background="white") output.pack() root.mainloop() <span class="math-container">```</span> </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-18T20:04:25.800", "Id": "421228", "Score": "0", "body": "Welcome to Code Review." } ]
[ { "body": "<p>Disclaimer: I know nothing about these \"Discord letters\"</p>\n\n<p><strong>Code organisation</strong></p>\n\n<p>You could reorganise your code to make units easier to use independently.</p>\n\n<p>The easiest thing to do it to re-write the <code>discord</code> function so that it returns a value instead of updating a global variable.</p>\n\n<p>Another thing to do is to put all the Tkinter logic into a function. Usually, that function actually doing things would be put <a href=\"https://stackoverflow.com/questions/419163/what-does-if-name-main-do\">behind an <code>if __name__ == \"__main__\"</code> guard</a>.</p>\n\n<p>We'd have</p>\n\n<pre><code># the function to convert a String to \"Discord Letters\"\ndef convert_to_discord_letters(word):\n # A List in which the converted Letters are stored it's later used to output the converted Letters in a Textbox\n result = []\n # List of numbers from 0-9 , is used to check the string for numbers and then convert them\n # to \"Discord Digits\" since they have a different syntax in discord than Letters\n chars = set('0123456789')\n s = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v',\n 'w', 'x', 'y', 'z'}\n # In case the User enters spaces they get removed since they just cause trouble\n word = word.replace(\" \", \"\")\n word = word.lower()\n w = word\n for i in range(len(w)):\n # checks if the string has a number and outputs accordingly\n if any((c in chars) for c in w[i]):\n list_one = [\"zero\", \"one\", \"two\", \"three\", \"four\", \"five\", \"six\", \"seven\", \"eight\", \"nine\", ]\n result.append(':' + list_one[int(w[i])] + \":\" + \" \")\n # checks if the string has letter and outputs accordingly (might be unnecessary)\n elif any((c in s) for c in w[i]):\n result.append(':regional_indicator_' + w[i] + \":\" + \" \")\n else:\n # In case the user inputs something wrong\n print(\"False Input\")\n # print(result)\n return result\n\n\n# defines the funtion click which gets called when the submitButton1 is pressed\ndef click():\n # saves the text which is entered in the textentry box, this later gets converted to \"Discord Letters\"\n entered_text=textentry.get()\n # deletes the output box in case the user presses the button again to convert something new\n output.delete(1.0, END)\n # the function to convert a String to \"Discord Letters\"\n result = convert_to_discord_letters(entered_text)\n # loop which gets the length of the string typed in the textentry box and then outputs it to the output textbox\n for i in range(len(entered_text)):\n output.insert(END, result[i])\n\n\ndef tkinter_discord_letter_converter():\n root = Tk()\n root.title(\"Discord Letter Converter\")\n # TextInput\n textentry = Entry(root, width=20, bg=\"white\")\n textentry.pack()\n # submitButton\n submitButton1 = Button(root, text=\"Submit\", width=6, command=click)#\n submitButton1.pack()\n # TextOutput\n output = Text(root, width=75, height=6, wrap=WORD, background=\"white\")\n output.pack()\n root.mainloop()\n\n\n\nif __name__ == '__main__':\n tkinter_discord_letter_converter()\n</code></pre>\n\n<p>Note: I do not have tested this because I do not have Tkinter but I've tested parts of your code because I have...</p>\n\n<p><strong>Unit Tests</strong></p>\n\n<p>Now that the code is reorganised, we can easily write small tests for the <code>discord</code> function that I've renamed <code>test_convert_to_discord_letters</code></p>\n\n<pre><code>def test_convert_to_discord_letters():\n \"\"\"Test function convert_to_discord_letters.\"\"\"\n # TODO: This could/should use a proper unit-test framework\n # Empty case\n assert convert_to_discord_letters(\"\") == []\n # Whitespace\n assert convert_to_discord_letters(\" \") == []\n # Special characters\n assert convert_to_discord_letters(\"#~&amp;$£()[]\") == []\n # Lowercase letters\n assert convert_to_discord_letters(\"abcz\") == [':regional_indicator_a: ', ':regional_indicator_b: ', ':regional_indicator_c: ', ':regional_indicator_z: ']\n # Uppercase letters\n assert convert_to_discord_letters(\"ABCZ\") == [':regional_indicator_a: ', ':regional_indicator_b: ', ':regional_indicator_c: ', ':regional_indicator_z: ']\n # Digits\n assert convert_to_discord_letters(\"42\") == [':four: ', ':two: ']\n # Mix\n assert convert_to_discord_letters(\"Bar -_- 9\") == [':regional_indicator_b: ', ':regional_indicator_a: ', ':regional_indicator_r: ', ':nine: ']\n</code></pre>\n\n<p><strong>Improving <code>test_convert_to_discord_letters</code></strong></p>\n\n<p>Now that we have unit-tests for the function, we can more safely try to improve it without breaking its behavior.</p>\n\n<p><strong>Loop like a native</strong></p>\n\n<p>I highly recommend <a href=\"https://nedbatchelder.com/text/iter.html\" rel=\"nofollow noreferrer\">Ned Batchelder's talk \"Loop like a native\"</a> about iterators. One of the most simple take away is that whenever you're doing range(len(iterabme)), you can probably do things in a better way: more concise, clearer and more efficient.</p>\n\n<p>In your case, this gives:</p>\n\n<pre><code> for char in w:\n # checks if the string has a number and outputs accordingly\n if any((c in chars) for c in char):\n list_one = [\"zero\", \"one\", \"two\", \"three\", \"four\", \"five\", \"six\", \"seven\", \"eight\", \"nine\", ]\n result.append(':' + list_one[int(char)] + \":\" + \" \")\n # checks if the string has letter and outputs accordingly (might be unnecessary)\n elif any((c in s) for c in char):\n result.append(':regional_indicator_' + char + \":\" + \" \")\n else:\n # In case the user inputs something wrong\n pass # print(\"False Input\")\n</code></pre>\n\n<p>Then, a few things seem more obvious:</p>\n\n<ul>\n<li>we don't really need the <code>w</code> variable. Also, various re-assignment of <code>word</code> are not required</li>\n<li>the variations of <code>any((c in XXX) for c in char)</code> look weird once we realise that <code>char</code> is a single character. We could write this: <code>if char in XXX</code></li>\n<li>the variable <code>chars</code> would be better named <code>digits</code> while <code>s</code> would be better named <code>letters</code></li>\n</ul>\n\n<p>At this stage, we have</p>\n\n<pre><code># the function to convert a String to \"Discord Letters\"\ndef convert_to_discord_letters(word):\n # A List in which the converted Letters are stored it's later used to output the converted Letters in a Textbox\n # List of numbers from 0-9 , is used to check the string for numbers and then convert them\n # to \"Discord Digits\" since they have a different syntax in discord than Letters\n digits = set('0123456789')\n letters = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'}\n result = []\n for char in word.replace(\" \", \"\").lower():\n # checks if the string has a number and outputs accordingly\n if char in digits:\n list_one = [\"zero\", \"one\", \"two\", \"three\", \"four\", \"five\", \"six\", \"seven\", \"eight\", \"nine\", ]\n result.append(':' + list_one[int(char)] + \":\" + \" \")\n # checks if the string has letter and outputs accordingly (might be unnecessary)\n elif char in letters:\n result.append(':regional_indicator_' + char + \":\" + \" \")\n else:\n # In case the user inputs something wrong\n pass # print(\"False Input\")\n # print(result)\n return result\n</code></pre>\n\n<p><strong>Definitions of data used</strong></p>\n\n<p>For letters, you could use <code>ascii_lowercase</code> from <code>string</code> module:</p>\n\n<pre><code>import string\n...\n letters = set(string.ascii_lowercase)\n</code></pre>\n\n<p>For digits, you define a set and a list, convert the value to integer to get the string at the relevant index. It seems like the best data structure to use would be a single dictionnary mapping digits to strings.</p>\n\n<pre><code> digits = {\"0\": \"zero\", \"1\": \"one\", \"2\": \"two\", \"3\": \"three\", \"4\": \"four\", \"5\": \"five\", \"6\": \"six\", \"7\": \"seven\", \"8\": \"eight\", \"9\": \"nine\"}\n</code></pre>\n\n<p><strong>Useless concatenations of literal string</strong></p>\n\n<p><code>\":\" + \" \"</code> can be written <code>\": \"</code>.</p>\n\n<p>At this stage, we have:</p>\n\n<pre><code># the function to convert a String to \"Discord Letters\"\ndef convert_to_discord_letters(word):\n # A List in which the converted Letters are stored it's later used to output the converted Letters in a Textbox\n # List of numbers from 0-9 , is used to check the string for numbers and then convert them\n # to \"Discord Digits\" since they have a different syntax in discord than Letters\n digits = {\"0\": \"zero\", \"1\": \"one\", \"2\": \"two\", \"3\": \"three\", \"4\": \"four\", \"5\": \"five\", \"6\": \"six\", \"7\": \"seven\", \"8\": \"eight\", \"9\": \"nine\"}\n letters = set(string.ascii_lowercase)\n result = []\n for char in word.replace(\" \", \"\").lower():\n # checks if the string has a number and outputs accordingly\n if char in digits:\n result.append(':' + digits[char] + \": \")\n # checks if the string has letter and outputs accordingly (might be unnecessary)\n elif char in letters:\n result.append(':regional_indicator_' + char + \": \")\n else:\n # In case the user inputs something wrong\n pass # print(\"False Input\")\n print(result)\n return result\n\n</code></pre>\n\n<p>And we realise that most comments are not required anymore because the code is much clearer. On the other hand, we could add a proper docstring.</p>\n\n<pre><code>def convert_to_discord_letters(word):\n \"\"\"Convert a string into a list of strings corresponding to \"Discord Letters\".\"\"\"\n digits = {\"0\": \"zero\", \"1\": \"one\", \"2\": \"two\", \"3\": \"three\", \"4\": \"four\", \"5\": \"five\", \"6\": \"six\", \"7\": \"seven\", \"8\": \"eight\", \"9\": \"nine\"}\n letters = set(string.ascii_lowercase)\n result = []\n for char in word.replace(\" \", \"\").lower():\n if char in digits:\n result.append(':' + digits[char] + \": \")\n elif char in letters:\n result.append(':regional_indicator_' + char + \": \")\n else:\n pass # TODO: I'll let you decide how to handle other cases\n return result\n</code></pre>\n\n<p><strong>Removing the useless logic</strong></p>\n\n<p>It is now clearer that the <code>.replace(\" \", \"\")</code> logic removes whitespace which would have no effect anyway (as we'd end up in the non-handled case).\nYou can remove this.</p>\n\n<p><strong>More</strong></p>\n\n<p>I suspect the <code>click</code> function could benefit from the same ideas but it can't test it at the moment.</p>\n\n<p>Also, the code seems to assume that <code>entered_text</code> and <code>result</code> will have the same length which may not be the case for non-handled characters.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-19T00:06:12.990", "Id": "421244", "Score": "0", "body": "+1 I really like the step by step approach!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-18T20:56:13.390", "Id": "217699", "ParentId": "217694", "Score": "3" } } ]
{ "AcceptedAnswerId": "217699", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-18T19:50:10.370", "Id": "217694", "Score": "2", "Tags": [ "python", "beginner", "strings", "tkinter" ], "Title": "Converting words/numbers to Discord \"letter/number emojis\"" }
217694
<p>Since the Esteemed Academia wants me to learn Haskell, and Haskell seems just weird for me, I thought that to train some basic Haskell skills I'd write a simple script I now need in Haskell.</p> <p>This is what the script is supposed to do... I have a file that looks like this:</p> <pre><code>oo R j j ai I'm a comment kd oo stack j a </code></pre> <p>I needed to extract duplicated elements from this file with lines they appear on. The catch is that the tab character denotes comments; so <code>I'm a comment</code> should not be considered here and in particular, this <code>a</code> from <code>I'm a comment</code> should not match this <code>a</code> that appears as the last element from these sample lines.</p> <p>If fed this particular sample file, my script should report finding duplicate elements: <code>oo</code> on lines <code>1</code> and <code>4</code> and <code>j</code> on lines <code>2</code>, <code>3</code> and <code>5</code>. I believe I wrote a script that does this correctly.</p> <p>Here it is:</p> <pre><code>import qualified Data.Map as Map import Data.List import Data.Function main = do input &lt;- fmap preprocess getContents printDupes $ findDupes input preprocess input = let untabbedLines = map (takeWhile (/= '\t')) $ lines input wordsedLines = map words untabbedLines numberedLines = zip wordsedLines [1..] numberedWords = concat $ map indexDown numberedLines where indexDown (words', index) = map (flip (,) $ index) words' in numberedWords findDupes entries = let occurences = Map.fromListWith (flip (++)) $ map (fmap (:[])) entries in Map.filter ((&gt;1).length) occurences printDupes :: Map.Map String [Int] -&gt; IO() printDupes dupes = let showPositions positions = intercalate ", " $ map show positions printDupe (dupe, positions) = putStrLn $ "Duplicated element " ++ dupe ++ " found on positions: " ++ showPositions positions in let sortedDupes = sortBy (compare `on` snd) $ Map.assocs dupes in mapM_ printDupe sortedDupes </code></pre> <p>The task is simple, but I guess it's OK for learning how to code in Haskell... </p> <p>So could you kindly review this self-imposed exercise? What could've been done better than I did? Simpler? Shorter? I'm sure much, but what precisely? Also how to improve readability?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-18T21:50:56.447", "Id": "421235", "Score": "1", "body": "AFTER writing this code I have feeling I needn't have used `Map`, `groupBy` would be quite enough..." } ]
[ { "body": "<p>It can be helpful to run <code>hlint</code> to see if it spots some improvements. In this case, it notes that:</p>\n\n<ul>\n<li>you can replace <code>concat $ map</code> with <code>concatMap</code> on line 13</li>\n<li>you can replace <code>flip (,) $ index</code> with <code>(,index)</code> on line 14 if you enable the <code>TupleSections</code> extension, or at least drop the dollar sign if you don't</li>\n</ul>\n\n<p>A few additional things it misses are:</p>\n\n<ul>\n<li>you can drop the <code>in let</code> on line 25</li>\n<li>you can replace <code>sortBy (compare `on` snd)</code> with <code>sortOn snd</code> in line 26</li>\n</ul>\n\n<p>It's also generally accepted as good practice to put type signatures on top-level functions. You may feel it looks cluttered, but it really helps others understand your programs. For example, I had to add them before I started working on your program, just so I could figure out what was going on.</p>\n\n<p>A larger stylistic issue is that idiomatic Haskell code typically doesn't create a lot of bindings for intermediate results that are only used once. I suspect that you've gone this route (labelling <code>untabbedLines</code> and <code>wordsedLines</code>, etc.) for two reasons -- first, you're probably more used to an imperative programming style that lays out an algorithm as a series ordered steps, and all these bindings are helping you think through the process (\"first, I remove the tabbed comments, second I make the lines into words, third I number them, etc., etc.); second, you may be using it as a kind of self-documenting coding style, but I think comments make better documentation than awkward camelcase pseudonouns like <code>wordsedLines</code>.</p>\n\n<p>So, a more usual way of writing your <code>preprocess</code> would be:</p>\n\n<pre><code>preprocess input\n = concatMap indexDown\n $ flip zip [1..]\n $ map words\n $ map (takeWhile (/= '\\t')) -- comments start with tab\n $ lines input\n where\n -- number each word on the line with the index\n indexDown (words', index) = map (,index) words'\n</code></pre>\n\n<p>Howoever, it's also pretty standard replace the pattern <code>foo x = f $ g $ h $ k x</code> with the point-free form <code>foo = f . g . h . k</code>. It's possible to get carried away with point-free code, but this particular transformation is pretty routine. Some people might prefer to collapse the <code>map</code> over the lines, too:</p>\n\n<pre><code>preprocess\n = concatMap indexDown\n . flip zip [1..]\n . map (words . takeWhile (/= '\\t'))\n . lines\n where\n -- number each word on the line with the index\n indexDown (words', index) = map (,index) words'\n</code></pre>\n\n<p>Also, in situations like this with maps at multiple levels (lines and words), it's worth considering if a list comprehension might not be easier to understand:</p>\n\n<pre><code>preprocess' :: String -&gt; [(String, Int)]\npreprocess' input =\n [ (w, i)\n -- get each numbered line of words\n | (i, ws) &lt;- zip [1..]\n $ map (words . takeWhile (/= '\\t'))\n $ lines input\n -- and process each word\n , w &lt;- ws ]\n</code></pre>\n\n<p>A similar consideration applies to <code>findDupes</code>. It would be more usual to collapse it into a single functional pipeline in point-free form:</p>\n\n<pre><code>findDupes :: [(String, Int)] -&gt; Map.Map String [Int]\nfindDupes = Map.filter ((&gt;1) . length)\n . Map.fromListWith (flip (++))\n . map (fmap (:[]))\n</code></pre>\n\n<p>However, I think <code>map (fmap (:[]))</code> is probably too clever by half. At the very least, it would be clearer to import <code>second</code> from <code>Data.Bifunctor</code> and write <code>map (second (:[]))</code>, though even better would be to just use a lambda which makes the intended transformation clear at a glance:</p>\n\n<pre><code>map (\\(w,i) -&gt; (w,[i]))\n</code></pre>\n\n<p>A rewrite of <code>printDupes</code> would probably look like:</p>\n\n<pre><code>printDupes :: Map.Map String [Int] -&gt; IO ()\nprintDupes dupes =\n forM_ (sortOn snd $ Map.assocs dupes) $ \\(w, idxs) -&gt;\n putStrLn $ \"Duplicated element \" ++ w ++\n \" found on positions: \" ++\n (intercalate \", \" $ map show idxs)\n</code></pre>\n\n<p>(Here, <code>forM_</code> comes from <code>Control.Monad</code> and is just a flipped version of <code>mapM_</code>.)</p>\n\n<p>One additional stylistic issue regards your handling of IO. Here, the <code>main</code> function is responsible for actually performing input and then calls on a pure function to perform the processing. When it comes time to generate output, though, it passes off that responsibility to another function. Haskell programs are usually carefully organized around their IO, with a clear division of responsibility between the IO and the pure processing, and it's usual to have input and output all handled at the same \"level\". I realize that sounds a little fuzzy and hand-wavy, but it boils down to this -- it would be more usual to localize input <em>and</em> output in <code>main</code> and have the remainder of the program (including <code>printDupes</code>) be pure. So, <code>printDupes</code> would instead look something like:</p>\n\n<pre><code>printDupes :: Map.Map String [Int] -&gt; String\nprintDupes =\n unlines . map render . sortOn snd . Map.assocs\n where render (w,idxs)\n = \"Duplicated element \" ++ w ++\n \" found on positions: \" ++\n intercalate \", \" (map show idxs)\n</code></pre>\n\n<p>I also personally find it a little odd that <code>findDups</code> takes a list <code>[(String,Int)]</code> but then returns a <code>Map String [Int]</code>. The <code>Map</code> seems like an implementation detail, and it \"feels\" like the function ought to return a <code>[(String,[Int])]</code>, and it might as well sort this list while it's at it.</p>\n\n<p>Anyway, with all those changes and some renaming of functions, the final program might look like:</p>\n\n<pre><code>{-# OPTIONS_GHC -Wall #-}\n\nimport qualified Data.Map as Map\nimport Data.List\n\nmain :: IO ()\nmain = interact (renderDups . findDups . getWords)\n\ngetWords :: String -&gt; [(String, Int)]\ngetWords input =\n [ (w, i)\n | (i, ws) &lt;- zip [1..]\n $ map (words . takeWhile (/= '\\t'))\n $ lines input\n , w &lt;- ws ]\n\nfindDups :: [(String, Int)] -&gt; [(String, [Int])]\nfindDups = sortOn snd . Map.assocs\n . Map.filter ((&gt;1) . length)\n . Map.fromListWith (flip (++))\n . map (\\(w,i) -&gt; (w,[i]))\n\nrenderDups :: [(String, [Int])] -&gt; String\nrenderDups = unlines . map render\n where render (w,idxs)\n = \"Duplicated element \" ++ w ++\n \" found on positions: \" ++\n intercalate \", \" (map show idxs)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-19T09:07:01.653", "Id": "421272", "Score": "0", "body": "(+1) \"*but I think comments make better documentation than awkward camelcase pseudonouns*\" - Wow. This is contrary to everything I was being told in other languages. usually, I was being told to avoid comments and only use comment if I can't express something by code itself; also because as code changes, comments tend to get obsoleted." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-19T13:53:15.997", "Id": "421304", "Score": "0", "body": "I'd say the hope behind expressing something by code is not to turn the names into pseudocomments, but to have the code's structure make the meaning clear. Then you cannot obsolete the understanding without removing its cause." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-19T15:57:07.497", "Id": "421314", "Score": "0", "body": "One more thing is that this point free style reads backwards to me. Eg your version of `findDups`. Its first line is sorting and extracting from map to list, the second line is filtering, the third line is building a map from list and the fourth line is preprocessing the list so that we can easily build a map out of it. But this is backwards! The actual ordering of operations is instead: first preprocess list, ten build map out of list, then filter this map, then extract the list out of map and finally, sort the list. Seems weird to me, but maybe this is how idiomatic Haskell works..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-19T17:08:46.427", "Id": "421321", "Score": "0", "body": "It's backwards as a sequence of operations. It's in the right order as a functional description of what you *want* in terms of what you *have*. If I want to count the number of words in a collection of files, then I want the length of the concatenation of the lists of words in the contents of my list of files, or `length . concatMap words <$> mapM readFile [\"bob.txt\", \"fred.txt\", \"alice.txt\"]`, and this is pretty idiomatic. In fact, while there's is a standard operator (`Control.Arrow.(>>>)`) that let's you write point-free in the opposite direction, it doesn't get used much." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-19T05:05:17.563", "Id": "217714", "ParentId": "217702", "Score": "3" } } ]
{ "AcceptedAnswerId": "217714", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-18T21:36:00.397", "Id": "217702", "Score": "5", "Tags": [ "haskell" ], "Title": "Finding duplicated entries" }
217702
<p>I am preprocessing a set of files where one file is included in another file with an include tag like shown below:</p> <p>file A</p> <pre><code>include file B include file C contents of file A include file D contents of file A </code></pre> <p>Here I need to replace the <code>include</code> tags with contents of each of the respective files, just like what a compiler does. I have two functions for that:</p> <pre><code>def parseContent(self, rdbFilePath, content): finalContent = self.removeComments(content) includeFileSearch = re.compile(r'(?P&lt;tag&gt;(\s)*include+(\s*)\"(\s*)(?P&lt;file&gt;[a-zA-Z0-9\.\_/]*)\")') for includes in includeFileSearch.finditer(finalContent): finalContent = re.sub(includes.group('tag'),self.parseIncludes(rdbFilePath, includes.group('file')), finalContent) return finalContent def parseIncludes(self, rdbFilePath, file): path = rdbFilePath + "/" + file f = open(path) pathDir = os.path.dirname(path) includedFileContent = self.parseContent(pathDir, f.read()) return includedFileContent </code></pre> <p>As you can see, functions <code>parseContent</code> and <code>parseIncludes</code> call each other recursively to replace all the include tags in every file. The logic works fine. But it takes a bit long time to execute. Is there any better way to do the same with lesser execution time?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-19T05:03:28.080", "Id": "421252", "Score": "0", "body": "no it is not xml" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-19T05:06:59.603", "Id": "421254", "Score": "1", "body": "What do you mean by slow? How big are your files?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-19T05:10:46.360", "Id": "421255", "Score": "0", "body": "Have you tried what this code does when the included file contains the text `$0.00 plus $1.23`? In other words, using `re.sub` looks wrong to me." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-19T05:13:24.947", "Id": "421256", "Score": "0", "body": "Is your file format line-based? In that case it might be easier to parse the input into a list of strings, instead of working with the `finalContent` (which by the way is not so final at all, since you are modifying it constantly)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-19T05:39:13.603", "Id": "421260", "Score": "0", "body": "@RolandIllig I see no advantage to working line by line." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-19T06:02:28.090", "Id": "421261", "Score": "0", "body": "@200_success in the code from the question, if there is a large including file that includes several other files, the whole content of that large file is processed again and again. By splitting the input into lines I wanted to avoid this needless copying." } ]
[ { "body": "<p><code>parseContent()</code> calls both <code>re.finditer()</code> and <code>re.sub()</code>, which is inefficient, because the <code>re.sub()</code> has to find the insertion point that <code>re.finditer()</code> had already found. What you want is just <a href=\"https://docs.python.org/3/library/re.html#re.sub\" rel=\"nofollow noreferrer\"><code>re.sub()</code></a>:</p>\n\n<blockquote>\n <p><em>repl</em> can be a string or a function… If <em>repl</em> is a function, it is called for every non-overlapping occurrence of <em>pattern</em>. The function takes a single <a href=\"https://docs.python.org/3/library/re.html#match-objects\" rel=\"nofollow noreferrer\">match object</a> argument, and returns the replacement string.</p>\n</blockquote>\n\n<p>Going further, you should make just one substitution pass that handles both comments and includes. (You didn't show us the <code>removeComments()</code> code, so you'll have to adapt the regex yourself.)</p>\n\n<p>The double-quotes in the regex have no special significance, and do not need to be escaped with backslashes. Also, the dot and the underscore characters do not need to be escaped within a character class.</p>\n\n<pre><code>DIRECTIVE_RE = re.compile(r'(?P&lt;comment&gt;#.*)|(?P&lt;include&gt;(\\s)*include+(\\s*)\"(\\s*)(?P&lt;file&gt;[a-zA-Z0-9._/]*)\")')\n\ndef process_content(self, rdb_file_path, content):\n def directive_handler(match):\n if match.group('comment'):\n return ''\n elif match.group('include'):\n path = os.path.join(rdb_file_path, match.group('file'))\n with open(path) as f:\n return self.process_content(rdb_file_path, f.read())\n return DIRECTIVE_RE.sub(directive_handler, content)\n</code></pre>\n\n<p><code>open()</code> should almost always be called using a <code>with</code> block to ensure that the filehandle gets closed automatically.</p>\n\n<p>Note that I have used <a href=\"https://docs.python.org/3/library/os.path.html#os.path.join\" rel=\"nofollow noreferrer\"><code>os.path.join()</code></a> as a portable alternative to <code>+ \"/\" +</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-22T20:57:12.460", "Id": "421708", "Score": "0", "body": "@Hari furthermore, you are not doing anything with the captured optional whitespaces, so you can remove their parentheses. `\\w` is thr concise way to express `[A-Za-z0-9_]` and this may be used inside or outside of a character class. In your case, you can use `[\\w.]`. Out of curiosity, do you have input that contains `includeeeeeeeeeeeeeeeeeeeeeee` that you want to match?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-22T23:43:49.230", "Id": "421724", "Score": "0", "body": "Errm... `[\\w./]` (I overlooked the forward slash)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-19T05:31:16.913", "Id": "217715", "ParentId": "217712", "Score": "4" } } ]
{ "AcceptedAnswerId": "217715", "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-19T04:42:19.980", "Id": "217712", "Score": "4", "Tags": [ "python", "performance", "recursion", "regex", "file" ], "Title": "Processing file inclusion directives using mutual recursion" }
217712
<p>I made program to open a text file and count the number of lines without doubled words. This number is printed in the end.</p> <p>This is an example text file:</p> <pre><code>sayndz zfxlkl attjtww cti sokkmty brx fhh suelqbp xmuf znkhaes pggrlp zia znkhaes znkhaes nti rxr bogebb zdwrin sryookh unrudn zrkz jxhrdo zrkz bssqn wbmdc rigc zketu ketichh enkixg bmdwc stnsdf jnz mqovwg ixgken </code></pre> <p>I've already made a program, and it looks like that program works. But I'm aware that in programming if something works it doesn't mean that program is made properly.</p> <p>My code:</p> <pre><code>class SkyphrasesValidation(object): def get_text_file(self): file = open('C:/Users/PC/Documents/skychallenge_skyphrase_input.txt', 'r') return file def lines_list(self): text = self.get_text_file() line_list = text.readlines() return [line.split() for line in line_list] def phrases_validation(self): validated_phrases = 0 for line in self.lines_list(): new_line = [] for word in line: exam = line.count(word) if exam &gt; 1: new_line.append(0) else: new_line.append(1) if 0 in new_line: validated_phrases += 0 else: validated_phrases += 1 return validated_phrases def __str__(self): return str(self.phrases_validation()) text = SkyphrasesValidation() print(text) </code></pre> <p>Is my logic good and is this program is well-made? Or maybe it looks like poop and I could write this more clearly?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-19T19:47:15.637", "Id": "421332", "Score": "0", "body": "When you say \"doubled words\" do you mean the same word immediately repeated, like \"the the\" or do you mean a line that contains the same word twice, possibly with words in between, like \"if I could I would\"?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-19T22:58:25.793", "Id": "421336", "Score": "0", "body": "I mean that in one line are 2 or even more same words." } ]
[ { "body": "<p>Here are some suggestions:</p>\n\n<h2>Keep file handlers in one function.</h2>\n\n<p>First off, the <code>get_text_file()</code> and <code>lines_list()</code> methods:</p>\n\n<blockquote>\n<pre><code>def get_text_file(self):\n file = open('C:/Users/PC/Documents/skychallenge_skyphrase_input.txt', 'r')\n return file\n\ndef lines_list(self):\n text = self.get_text_file()\n line_list = text.readlines()\n return [line.split() for line in line_list]\n</code></pre>\n</blockquote>\n\n<ol>\n<li><p>It's generally a bad idea to pass files outside of a function... it poses some questions: Who will close the file? When? And how? Instead, <em>open and close it in the same function</em> so that the file can be <em>contained</em>.</p></li>\n<li><p>Since the <code>lines_list()</code> method is only reading text off from <code>get_text_file()</code> (and nothing else), it may be better to simply write <em>one</em> function which reads handles and reads lines off the file. (The splitting of lines, <code>line.split()</code>, can be done in <code>phrases_validation()</code>.)</p></li>\n</ol>\n\n<p>With these points in mind, we could define <code>get_text_lines()</code> as:</p>\n\n<pre><code>def get_text_lines(self):\n with open('C:/Users/PC/Documents/skychallenge_skyphrase_input.txt', 'r') as file:\n line_list = file.readlines()\n\n return line_list\n</code></pre>\n\n<p>Notice that the use of the <a href=\"https://stackoverflow.com/questions/3012488/what-is-the-python-with-statement-designed-for\"><code>with</code> statement</a>. This automatically closes the file when the block-scope is exited.</p>\n\n<p>Using the above function implies modifying <code>phrases_validation()</code>:</p>\n\n<pre><code>def phrases_validation(self):\n # ...\n for line in get_text_lines(): # call function here\n # ...\n words = line.split() # split lines here\n for word in words: # iterate through split line here\n # ...\n</code></pre>\n\n<h2>The Validation Algorithm</h2>\n\n<p>I've tried annotating the meat of your <code>phrases_validation</code>:</p>\n\n<blockquote>\n<pre><code># iterate through lines...\nfor line in get_text_lines():\n\n new_line = [] # container to store 1s and 0s\n\n # iterate through words...\n words = line.split()\n for word in words:\n\n exam = line.count(word)\n\n # append 0 if word is duplicated\n if exam &gt; 1:\n new_line.append(0)\n\n # append 1 if word is not duplicated\n else:\n new_line.append(1)\n\n # increment validated_phrases if no duplicates\n if 0 in new_line:\n validated_phrases += 0\n else:\n validated_phrases += 1\n</code></pre>\n</blockquote>\n\n<p>Some general suggestions:</p>\n\n<ol>\n<li>Opt for readability. Since only <code>0</code> and <code>1</code> are being used, this implies a <em>binary</em> domain, and thus can be substituted with <code>False</code> and <code>True</code> respectively.</li>\n<li><p><code>validated_phrases += 0</code> This can be removed since nothing is added. Simply do</p>\n\n<pre><code>if 0 not in new_line:\n validated_phrases += 1\n</code></pre></li>\n</ol>\n\n<p>Some possible improvements to the algorithm:</p>\n\n<h3>Using the <code>any</code> built-in function.</h3>\n\n<p>The <code>any</code> built-in function takes a list and tests for truth. If any of the elements are <a href=\"https://stackoverflow.com/questions/39983695/what-is-truthy-and-falsy-in-python-how-is-it-different-from-true-and-false\"><em>Truthy</em></a>, <code>any</code> returns <code>True</code>, else <code>False</code>. Your inner loop can make use of the <code>any</code> function:</p>\n\n<pre><code>for line in get_text_lines():\n words = line.split()\n\n has_duplicates = any(words.count(word) &gt; 1 for word in words)\n if not has_duplicates:\n validated_phrases += 1\n</code></pre>\n\n<p>Here, a <a href=\"https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions\" rel=\"nofollow noreferrer\">comprehension</a> was used: <code>words.count(word) &gt; 1 for word in words</code>.</p>\n\n<p>This generates an iterable of <code>True</code>/<code>False</code> values: <code>True</code> if <code>words.count(word) &gt; 1</code> and <code>False</code> otherwise. We then check whether there are any duplicates and if not, increment <code>validated_phrases</code>.</p>\n\n<p>(To keep track of the number of duplicates, you can use the <code>sum</code> function instead. This will add the <code>True</code> values, counting the number of duplicates.)</p>\n\n<h3>Using the <code>set</code> class.</h3>\n\n<p>Indeed, there are a couple more ways to check for duplicates. <code>list.count</code> has a time-complexity with an upper-bound of <span class=\"math-container\">\\$O(n)\\$</span> (with <span class=\"math-container\">\\$n\\$</span> being the length of the list), i.e. it searches the entire list, which may be slow when the list grows to sizes of thousands or millions.</p>\n\n<p>One other way to check for duplicates would be to obtain a container of <em>unique</em> words, and check whether it has the same length as the list of words in the line. We can use <code>set</code> to obtain the unique words.</p>\n\n<pre><code>for line in get_text_lines():\n words = line.split()\n\n unique_words = set(words)\n has_duplicates = len(unique_words) != len(words)\n if not has_duplicates:\n validated_phrases += 1,\n</code></pre>\n\n<p>I'm not entirely sure about the complexity of <code>set(words)</code> but <a href=\"https://stackoverflow.com/questions/1115313/cost-of-len-function\">the <code>len</code> function has a time complexity of <span class=\"math-container\">\\$O(1)\\$</span></a> which can be <em>really fast</em> in the long run.</p>\n\n<h3>Using the <code>collections.Counter</code> class.</h3>\n\n<p>Another way that might be of interest would be to use <code>Counter</code> from the <code>collections</code> module.</p>\n\n<pre><code>for line in get_text_lines():\n words = line.split()\n\n counter = Counter(words)\n has_duplicates = any(counter[word] != 1 for word in counter)\n if not has_duplicates:\n validated_phrases += 1\n</code></pre>\n\n<p><sup><em>(For this, remember to add <code>from collections import Counter</code> at the top of your script.)</em></sup></p>\n\n<h2>Try not to rely on <code>__str__</code>.</h2>\n\n<p>In your code, the main algorithm, <code>phrases_validation()</code>, is only called when <code>str(text)</code> or <code>text__str__()</code> is called (this is implicitly called by <code>print(text)</code>).</p>\n\n<p>It's creative... but prefer to directly call <code>phrases_validation()</code>:</p>\n\n<pre><code>validator = SkyphrasesValidation()\nprint(validator.phrases_validation())\n</code></pre>\n\n<p>(And call <code>str()</code> on it if needed.) This is more explicit to readers that you're calling the <code>phrases_validation()</code> method.</p>\n\n<p>Generally, the <code>__str__</code> magic method should be overloaded when you're trying to display a class' members contents. Unfortunately, <code>SkyphrasesValidation</code> doesn't have any members.</p>\n\n<p>The variable name <code>text</code> can be interpreted in several ways. Is it a text file? A string? Consider a more descriptive name instead. (<code>validator</code> was used in the example above.)</p>\n\n<h2>Class?</h2>\n\n<p>The class could have been substituted with one/two functions. But sticking with a class... since the <code>self</code> argument is rarely used, consider making the methods <a href=\"https://stackoverflow.com/questions/3012488/what-is-the-python-with-statement-designed-for\">static</a> or instead, place <code>get_text_lines()</code> <em>outside</em> of the class and pass the lines of text to <code>phrases_validation()</code> as an argument.</p>\n\n<p>Hope this helps!</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-19T23:34:04.667", "Id": "421338", "Score": "1", "body": "There are a lot of good suggestions in this answer, unfortunately bracketed by some ungood language. You might want to read the [Code of Conduct](https://codereview.stackexchange.com/conduct) again, and be a bit more friendly." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-20T00:34:06.213", "Id": "421342", "Score": "0", "body": "Thanks, it was very helpful, I closed all program in one function" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-20T05:29:19.580", "Id": "421357", "Score": "0", "body": "@AustinHastings Hmm, okay. I've tried to tidy the answer some more. I'll try to catch hold of my fingers before typing next time. Thanks for the tip!" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-19T08:10:58.593", "Id": "217720", "ParentId": "217718", "Score": "3" } } ]
{ "AcceptedAnswerId": "217720", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-19T06:37:55.077", "Id": "217718", "Score": "3", "Tags": [ "python" ], "Title": "Program to check if in line are doubled words" }
217718
<p>Didn't post on the Codereview for a while but trying to learn Golang now and wrote my first utility a few days ago and will be glad to see what I did wrong here and what can be done better.</p> <blockquote> <p>This tool is used to check public repositories in out GitHub organization and compare such a list with another list which contains repositories that are allowed to be public. If any differences will be found between both lists - it will send an alarm to Slack.</p> </blockquote> <p>I googled and tried a lot of solutions to make slices comparison but finally had to write own loop.</p> <p>The main thing I'm thinking about now is to use <code>map[]</code> instead of two <code>for</code> loops and working about it now.</p> <p>The <code>main()</code> function:</p> <pre><code>func main() { client := github.NewClient(nil) opt := &amp;github.RepositoryListByOrgOptions{Type: "public"} // get our public repositories list to the repos variable repos, _, _ := client.Repositories.ListByOrg(context.Background(), os.Getenv("GITHUB_ORG_NAME"), opt) // the list of repositories that are expected to be public allowedRepos := strings.Fields(os.Getenv("ALLOWED_REPOS")) for _, repo := range repos { fmt.Printf("\nChecking %s\n", *repo.Name) if isAllowedRepo(*repo.Name, allowedRepos) { fmt.Printf("OK: repo %s found in Allowed\n", *repo.Name) } else { fmt.Printf("ALARM: repo %s was NOT found in Allowed!\n", *repo.Name) sendSlackAlarm(*repo.Name, *repo.HTMLURL) } } } </code></pre> <p>And it uses isAllowedRepo() to check if values are identical:</p> <pre><code>func isAllowedRepo(repoName string, allowedRepos []string) bool { // and just iterate the repoName over the allowedRepos list for _, i := range allowedRepos { if i == repoName { return true } } return false } </code></pre> <p>Te full code can be seen <a href="https://github.com/setevoy2/setevoy-tools/blob/master/go-github-public-repos-checker/go-github-public-repos-checker.go" rel="nofollow noreferrer">here</a>.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-07T14:53:53.957", "Id": "424769", "Score": "1", "body": "You can transform the allowed repos list into a regex expression and lose one of the loops." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-19T08:20:02.790", "Id": "217721", "Score": "3", "Tags": [ "beginner", "go" ], "Title": "Golang tool to check public repositories list in Github" }
217721
<p>I made a option to user choose to stay logged in even after he closes the browser. It's really simple to implement, but i'm not sure about the hash i used to identify the user that is stored in a cookie. </p> <p>To generate the hash i used <code>bin2hex(random_bytes(59/2))</code> this function generate a string like this one:</p> <pre><code>118f9bc738e28b5079cf04bc3c88b2754f8ae04c9f1e1127d020389c49 </code></pre> <p>To make sure that it's unique for each user, before register new accounts i check all hashes that i already have in my database.</p> <p>I only use this hash to identify the user using the cookie, is it safe? The lenght of the hash is good enough to a Brute force attack be impossible, right?</p> <p>What do you guys think about my code?</p> <p>register.php</p> <pre><code>$hash = bin2hex(random_bytes(59/2)); </code></pre> <p>login.php</p> <pre><code>## ## Get data from database using $_POST variable from &lt;form&gt; ## if(!empty($_POST['stay_loggedIn'])){ setcookie('stay_loggedIn', $fetch_data['hash'], strtotime('+14 days'), '/'); } </code></pre> <p>index.php</p> <pre><code>if(!empty($_COOKIE['stay_loggedIn']) &amp;&amp; empty($_SESSION['logged_cookie'])){ ## Set this session variable to run this code only one time $_SESSION['logged_cookie'] = 1; $hash = $_COOKIE['stay_loggedIn']; $logeIn = $conn-&gt;prepare("SELECT * FROM users WHERE `hash` = :hash"); $logeIn-&gt;bindValue(':hash', $hash, PDO::PARAM_STR); $logeIn-&gt;execute(); $user_data = $logeIn-&gt;fetch(PDO::FETCH_ASSOC); ## ## Set session variables ## } </code></pre> <p>logout.php</p> <pre><code>$params = session_get_cookie_params(); setcookie('stay_loggedIn', '', time() - 3600, $params['path'], $params['domain'], $params['secure'], isset($params['httponly'])); </code></pre>
[]
[ { "body": "<p>I think this is a bad approach on two fronts (the second one is more important):</p>\n\n<ol>\n<li><p>Having to check a randomly generated 'hash' against the database, to see if it has been used before, is inefficient. First of all, this is not a <em>hash</em>, it's a random string. A <em>hash</em> is created from something sensible, to verify it later. Can I assume you already have an unique identifier for each user in your database? You could store that in the cookie, it tells you which user it is. User id's don't need to be a secret. However, you don't want someone to change it and see information from another to user. To prevent this, you could add a small random string to the cookie, and in your database, to verify that they are who they say they are. Such a string is called a 'token'. An user is only valid if the user id and the token in the cookie match with the id and token in the database. Your queries will now probably be quicker because you can use the user id to look up the token.</p></li>\n<li><p>Staying 'logged in' after closing the browser is done by <em>not</em> erasing the session cookie when the browser closes. It's as simple as that. See: <a href=\"https://www.php.net/manual/en/function.session-set-cookie-params.php\" rel=\"nofollow noreferrer\">https://www.php.net/manual/en/function.session-set-cookie-params.php</a> (see 'lifetime', it defaults to 0).</p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-19T12:41:23.633", "Id": "421291", "Score": "0", "body": "Indeed. But there's any downside about change the `PHPSSID` lifetime to keep the user logged in? I mean i have seached about it and most of the articles and SO questions don't mention this, they all talk about set a cookie with a hash/token or any other thing, to identify the user." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-19T18:21:23.367", "Id": "421324", "Score": "0", "body": "@nobody JWT token is a standard token you can use for this type of situation. However remember only to enable a single secure algorithm." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-19T18:31:01.357", "Id": "421326", "Score": "1", "body": "@422_unprocessable_entity Yes, I was very incomplete when I talked about tokens. It is a big topic. A basic introduction into JWT with an authentication example might be helpful: https://www.codeofaninja.com/2018/09/rest-api-authentication-example-php-jwt-tutorial.html" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-19T10:37:39.627", "Id": "217728", "ParentId": "217722", "Score": "3" } } ]
{ "AcceptedAnswerId": "217728", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-19T08:40:33.323", "Id": "217722", "Score": "2", "Tags": [ "php", "security" ], "Title": "Store a hash in a cookie to identify the user's account to keep logged in after close browser" }
217722
<p>Please tell me what the weak spots of this code are (specially in terms of efficiency) and how I can improve it:</p> <pre><code>def get_word_frequencies(filename): handle = open(filename,'rU') text = handle.read() handle.close() MUST_STRIP_PUNCTUATION = ['\n','&amp;','-','"','\'',':',',','.','?','!'\ ,';',')','(','[',']','{','}','*','#','@','~','`','\\','|','/','_'\ ,'+','=','&lt;','&gt;','1','2','3','4','5','6','7','8','9','0'] text = text.lower() for char in MUST_STRIP_PUNCTUATION: if char in text: text = text.replace(char,' ') words_list = text.split(' ') words_dict = {} for word in words_list: words_dict[word] = 0 for word in words_list: words_dict[word] += 1 del words_dict[''] return words_dict </code></pre> <p>Some steps sound repetitive to me and it seems that I'm looping on the text many times but I think I'm obliged to take each of those steps separately(unless I'm wrong), for instance, replacing invalid characters should be on multiple separate iterations, or lower casing the whole text must be a separate step, and so on.</p> <p>Also for creating the dictionary I'm suspicious a way better than <code>words_dict[word] = 0</code> must exist?</p>
[]
[ { "body": "<p>Some in-place improvements you could make:</p>\n\n<ul>\n<li><p><a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP-8</a> recommends four space indentation, not two;</p></li>\n<li><p><a href=\"https://docs.python.org/3/library/collections.html#collections.defaultdict\" rel=\"nofollow noreferrer\"><code>collections.defaultdict</code></a> would allow you to scan the list of words only once, without having to explicitly initialise to <code>0</code> for each word. Even easier, there's a <a href=\"https://docs.python.org/3/library/collections.html#collections.Counter\" rel=\"nofollow noreferrer\"><code>collections.Counter</code></a>, too;</p></li>\n<li><p>Rather than iterate over all of the characters you want to replace, you could use <a href=\"https://docs.python.org/3/library/re.html#re.sub\" rel=\"nofollow noreferrer\"><code>re.sub</code></a> with a regular expression pattern matching those characters (or <a href=\"https://docs.python.org/3/library/re.html#re.findall\" rel=\"nofollow noreferrer\"><code>re.findall</code></a> for the characters you <em>do</em> want); and</p></li>\n<li><p>You should generally use the <code>with</code> <em>\"context manager\"</em> to handle files; see e.g. <a href=\"https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files\" rel=\"nofollow noreferrer\">the tutorial</a>.</p></li>\n</ul>\n\n<p>More broadly, though, you have one function with three different purposes:</p>\n\n<ol>\n<li><p>Handling the file;</p></li>\n<li><p>Cleaning up the text; and</p></li>\n<li><p>Counting the words.</p></li>\n</ol>\n\n<p>Splitting these separate concerns up into separate functions would make those functions easier to test, understand and reuse.</p>\n\n<p>With these ideas applied, you could write something like:</p>\n\n<pre><code>from collections import Counter\nimport re\n\ndef get_text(filename):\n \"\"\"Read and return the content of a specified file.\"\"\"\n with open(filename, \"rU\") as handle:\n return handle.read()\n\ndef clean_text(text):\n \"\"\"Lowercase text and extract words.\"\"\"\n return re.findall(\"[a-z]+\", text.lower())\n\ndef get_word_frequencies(filename):\n text = get_text(filename)\n words = clean_text(text)\n return Counter(words)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-19T10:16:51.823", "Id": "217725", "ParentId": "217723", "Score": "3" } }, { "body": "<p><strong>General Implementation Suggestions</strong></p>\n\n<ol>\n<li><p>First of all I would suggest that the function is doing too much - and could be broken into multiple smaller functions to keep single behaviour in a single function. This is a good mindset to get into for unit testing and mocking (later down the line).</p>\n\n<p>For example currently your method is doing the following 2 bit of behaviour:</p>\n\n<ol>\n<li>Opening, Reading and Closing a file from the file system.</li>\n<li>Collecting the word frequency</li>\n</ol>\n\n<p>I would suggest having 2 methods:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def open_and_read_file_content(filepath):\n handle = open(filename,'rU')\n text = handle.read()\n handle.close()\n return text\n\ndef collect_word_frequency_in_text(text):\n ...\n\n</code></pre></li>\n</ol>\n\n<p><strong>Code Review</strong></p>\n\n<p>First I would suggest that there is a redundant <code>if</code> statement when checking if the punctuation character is in the text body and you just want to call the replace.</p>\n\n<p>In this case if the punctuation doesn't exist you are doing the same number of iterations as currently, however, if it does exist it is replaced there and then rather than being checked before hand:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code># Before\n...\nfor char in MUST_STRIP_PUNCTUATION:\n if char in text:\n text = text.replace(char,' ')\n...\n\n# After\n...\nfor char in MUST_STRIP_PUNCTUATION:\n text = text.replace(char,' ')\n...\n</code></pre>\n\n<p>Finally, while the 2 <code>for</code> statements don't look pretty and look like they can be made clearer - if efficiency is what you are looking for - I am not sure of any solution that will be better.</p>\n\n<p>Currently the time complexity (for the two loops) is O(2n) - you could collect each unique entry in the text block and then count each occurrence of the word using Python's <code>count()</code>, however I am not sure this will be more time efficient but might look cleaner.</p>\n\n<p>Additionally - You could do an <code>if</code> to check the <code>word != ''</code> rather than deleting it from the set at the end of the process - however, depending on the frequency of <code>''</code> in the data set, that might not be desired. </p>\n\n<p>I would stress though, that similar to my initial point made before the code review section, for readability and understanding (debugging/testing) this might be desired (example below)</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>...\n words_list = text.split(' ')\n words_dict = {}\n for word in words_list:\n if(word != '')\n words_dict[word] = text.count(word)\n return words_dict\n...\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-19T10:28:57.490", "Id": "421277", "Score": "2", "body": "`if word:` would achieve the same as `if word != '':` (note the parentheses aren't required, but the colon is) and is considered more idiomatic (see e.g. PEP-8)." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-19T10:22:57.747", "Id": "217727", "ParentId": "217723", "Score": "2" } } ]
{ "AcceptedAnswerId": "217725", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-19T08:56:19.213", "Id": "217723", "Score": "0", "Tags": [ "python", "hash-map" ], "Title": "Words dictionary out of a text file" }
217723
<p>I really do not like how bad this looks. It is not readable and I am not sure if I need the stacked map's. There are a lot of iterations going on here (map, join, replace) and performance is really important, please help :(</p> <p><strong>Input:</strong></p> <pre><code>const alternatives = [ "flex", "float", [ "background-size", "background-image" ] ] </code></pre> <p><strong>Expected Output:</strong></p> <pre><code>'Consider using 'flex', 'float' or 'background-size' with 'background-image' instead.' </code></pre> <p><strong>Working Code:</strong></p> <pre><code>const result = `Consider using ${alternatives .map((alternative) =&gt; { return Array.isArray(alternative) ? alternative.map((a) =&gt; `'${a}'`).join(' with ') : `'${alternative}'`; }) .join(', ') .replace(/, ([^,]*)$/, ' or $1')} instead.` </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-20T05:07:18.993", "Id": "421352", "Score": "1", "body": "I would use the Oxford comma in this situation since English doesn't define the operator precedence between `or` and `with`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-20T05:12:47.723", "Id": "421354", "Score": "0", "body": "Why is performance so important for this particular piece of code? This is not the test whether to generate a diagnostic (which I agree should be really fast), it's the part generating the diagnostic (which shouldn't be called that often anyway). Did you measure which part of the code really needs the performance boost?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-20T05:14:13.937", "Id": "421355", "Score": "0", "body": "Are `a` and `alternative` always strings? If so, you can omit the quotes and the inner `map`." } ]
[ { "body": "<h2>Remove the last item</h2>\n\n<p>You are not going to avoid the stepping over each item at least once. However the replace and be avoided by removing the last item.</p>\n\n<h2>One iteration</h2>\n\n<p>Use a for loop, building the string as you step over each item. Before the loop <code>pop</code> the last item, then after the loop <code>push</code> it back to keep the array intact. You can then add the last item after the conjunction.</p>\n\n<p>I will use <code>options</code> rather than <code>alternatives</code> as in the bottom example it is more semantically fitting.</p>\n\n<pre><code>function toHumanReadable(options) {\n const toStr = opt =&gt; `\"${Array.isArray(opt) ? `${opt[0]}\" with \"${opt[1]}` : opt}\"`;\n const last = options.pop(); \n var res = 'Consider using ';\n for (const opt of options) { res += toStr(opt) + ', ' }\n options.push(last);\n return res + `or ${toStr(last)} instead.`; \n}\nconst alt1 = [ \"flex\", \"float\" , [\"background-size\", \"background-image\" ] ];\nconst readable = toHumanReadable(alt1);\n</code></pre>\n\n<p>or you can make options an argument array, and don't need to push the last item back onto the array. It does mean an extra iteration.</p>\n\n<pre><code>function toHumanReadable(...options) {\n const toStr = opt =&gt; `\"${Array.isArray(opt) ? `${opt[0]}\" with \"${opt[1]}` : opt}\"`;\n const last = options.pop(); \n var res = 'Consider using ';\n for (const opt of options) { res += toStr(opt) + ', ' }\n return res + `or ${toStr(last)} instead.`; \n}\n\nconst alt1 = [ \"flex\", \"float\" , [\"background-size\", \"background-image\" ] ];\nconst readable = toHumanReadable(...alt1);\n</code></pre>\n\n<h2>Reusable</h2>\n\n<p>I am guessing this is just one of a many similar human readable strings. To make the function reusable you can add some arguments</p>\n\n<p>The next version requires two iterations, but does not need the replace. This time the last item is popped from a copy of the options array and the conjunction is added via joining the joined options and the last option.</p>\n\n<pre><code>function toHumanReadable(options, open, close, conjunction) {\n options = options.map(opt =&gt; Array.isArray(opt) ? opt.join('\" with \"') : opt);\n const last = options.pop();\n return `${open} \"${[options.join('\", \"'), last].join(`\", ${conjunction} \"`)}\" ${close}`;\n}\n\nconst alt1 = [ \"flex\", \"float\" , [\"background-size\", \"background-image\" ] ];\nconst readable = toHumanReadable(alt1, \"Consider using\", \"instead.\", \"or\");\n</code></pre>\n\n<h2>Example usage</h2>\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>setTimeout(()=&gt; { // just for snippet to put relevant code at top\n\n const alt1 = [ \"flex\", \"float\" , [\"background-size\", \"background-image\" ] ];\n const alt2 = [ \"foo\", [\"bar\",\"poo\"], [\"min-width\", \"max-height\" ] ];\n log(toHumanReadable(alt1, sentenceTypes.anyOf));\n log(toHumanReadable(alt2, sentenceTypes.oneOf));\n log(toHumanReadable(alt1, sentenceTypes.allOf)); \n},0);\n\nfunction toHumanReadable(options, {open, close, conjunction}) {\n options = options.map(opt =&gt; Array.isArray(opt) ? opt.join('\" with \"') : opt);\n const last = options.pop();\n return `${open} \"${[options.join('\", \"'), last].join(`\", ${conjunction} \"`)}\" ${close}`;\n}\n\nconst sentenceTypes = {\n create(name, open, close, conjunction) { this[name] = {open, close, conjunction} }\n};\nsentenceTypes.create(\"anyOf\", \"Consider using\", \"instead.\", \"or\");\nsentenceTypes.create(\"oneOf\", \"Use any one of\", \"to stay consistent.\", \"or\");\nsentenceTypes.create(\"allOf\", \"All the following\", \"are required.\", \"and\");\nfunction log(t){txt.appendChild(Object.assign(document.createElement(\"div\"),{textContent:t}))}</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>body {\nfont-family: arial;\nfont-size: small;\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;div id=\"txt\"&gt;&lt;/div&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-20T13:55:43.583", "Id": "217775", "ParentId": "217729", "Score": "1" } } ]
{ "AcceptedAnswerId": "217775", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-19T11:55:10.677", "Id": "217729", "Score": "0", "Tags": [ "javascript", "strings" ], "Title": "Building complex sentences based on a data structure" }
217729
<p>I have an .NET Core EF application, setup as Database first, that is supposed to take in a payload containing items to be persisted to my database. They payloads can be huge containing multiple "Securities" and each "Security" has multiple "Positions/Transactions" to be persisted to the database. This application can be called multiple times in parallel from a commandline tool. Sometimes these payloads can take up to 20 minutes to deserialize to their components and persist. The ultimate goal here is to reduce the amount of time taken to run through a payload and persist. The SaveChanges() function call is not the issue here (afaik). I think the issue is the nested looping through the securities and all of their positions on the payload and the corresponding LINQ queries. These operations are happening in HandlePostions/HandleTransactions/TryFindSecId functions. Any help pointing out any obvious code smells, any performance improvements, or any help optimizing the queries would be welcomed. Here is my calling function:</p> <pre><code> private async Task&lt;AccPackBody&gt; Persist(AccPackBody pack) { bool hasModifications = false, hasErrors = false; using (var dbContext = new newportMasterContext(Configs.MasterDbConnString)) { dbContext.Database.SetCommandTimeout(300); foreach(var mappedSecurity in pack.Internal) { mappedSecurity.FirmId = pack.FirmId; SEC_IDENTIFIER existingSecurity = null; try { existingSecurity = await TryFindSecId(mappedSecurity, pack.FirmId.Value, dbContext); } catch(Exception ex) { await Logger.Send(LogType.Error, "Something failed while trying to clone security"); } if(existingSecurity == null) { await Logger.Send(pack, LogType.Error, $"Missing security for: Identifier: {mappedSecurity.IdentifierName} Value: {mappedSecurity.IdentifierValue}, Firm{pack.FirmId}, Currency:{mappedSecurity.Currency}"); throw new LoggedException(); } else { mappedSecurity.SecurityGuid = existingSecurity.Security_UID; POSITION[] updatedPositions = null; if(mappedSecurity.Postitions != null &amp;&amp; mappedSecurity.Postitions.Length &gt; 0) { updatedPositions = HandlePositions(pack,dbContext, pack.State, pack.AccountUID.Value, mappedSecurity, pack.StatementDate.Value); mappedSecurity.Postitions = updatedPositions != null &amp;&amp; updatedPositions.Count() &gt; 0 ? updatedPositions : new POSITION[0]; if(updatedPositions != null &amp;&amp; updatedPositions.Count() &gt; 0) hasModifications = true; } //EditTransaction TRANSACTION[] updatedTransactions = null; if(mappedSecurity.Transactions != null &amp;&amp; mappedSecurity.Transactions.Length &gt; 0) { updatedTransactions = HandleTransctions(dbContext, pack, mappedSecurity); mappedSecurity.Transactions = updatedTransactions != null &amp;&amp; updatedTransactions.Count() &gt; 0 ? updatedTransactions : new TRANSACTION[0]; if(updatedTransactions != null &amp;&amp; updatedTransactions.Count() &gt; 0) hasModifications = true; } } } if(!hasErrors &amp;&amp; dbContext.ChangeTracker.HasChanges()) { try { await dbContext.SaveChangesAsync(); } catch(Exception ex) { await Logger.Send(pack,LogType.Warning, "Error persisting changes to db, rolling back: " + ex.ToString()); throw new LoggedException(); } } } return pack; } </code></pre> <p>Here are my three functions that the above method calls - these are where a lot of the slowdowns are occuring:</p> <pre><code> private async Task&lt;SEC_IDENTIFIER&gt; TryFindSecId(AccMappedSecurity mappedSecurity, long firmId, newportMasterContext dbContext, Guid? packUid = null) { var existingSecurities = dbContext.SEC_IDENTIFIER .Where(x =&gt; x.IdentifierName == mappedSecurity.IdentifierName &amp;&amp; mappedSecurity.IdentifierValue == x.Identifier &amp;&amp; x.FirmID == firmId &amp;&amp; (string.IsNullOrEmpty(mappedSecurity.Currency) || x.SECURITY.Currency == mappedSecurity.Currency) &amp;&amp; x.SECURITY.ChangeType != "D"); var existingSecurity = existingSecurities.FirstOrDefault(); if(existingSecurity == null) { var cloneResult = await ClonePostition.Clone( new ClonePositionRequest { IdentifierName = mappedSecurity.IdentifierName, IdentifierValue = mappedSecurity.IdentifierValue, NewCurrency = mappedSecurity.Currency, FirmId = firmId }, Logger.LocalLog ); if(cloneResult.Code != HttpStatusCode.InternalServerError) { existingSecurity = dbContext.SEC_IDENTIFIER .FirstOrDefault(x =&gt; x.IdentifierName == mappedSecurity.IdentifierName &amp;&amp; mappedSecurity.IdentifierValue == x.Identifier &amp;&amp; x.FirmID == firmId &amp;&amp; (string.IsNullOrEmpty(mappedSecurity.Currency) || x.SECURITY.Currency == mappedSecurity.Currency)); } else { await Logger.Send(LogType.Error, "Internal server error on clone function - clone failed" + cloneResult.Code); } } else { } return existingSecurity; } private POSITION[] HandlePositions(AccPackBody reqPayload, newportMasterContext dbContext, PackState state, Guid accountGuid, AccMappedSecurity mappedSecurity, DateTime statementDate, Guid? packUid = null) { if(useDiagnosticLogging) LocalLoggingUtilities.WriteDiagnosticLog(_logText, packUid.Value, "Hit handle positions"); var handledPositions = new List&lt;POSITION&gt;(); int posCnt = mappedSecurity.Postitions.Length; if(useDiagnosticLogging) LocalLoggingUtilities.WriteDiagnosticLog(_logText, packUid.Value, "Deserializing mapped positions"); List&lt;POSITION&gt; deserializedPositions = mappedSecurity.Postitions .Select(x =&gt; JsonConvert.DeserializeObject&lt;POSITION&gt;(x.ToString(), Configs.JsonCircularRefFixConfig)) .OrderBy(x =&gt; x.DateStart) .ToList(); var updatedPosDetails = new List&lt;POSITION_DETAIL&gt;(); POSITION prevailingPosition = null; if(useDiagnosticLogging) LocalLoggingUtilities.WriteDiagnosticLog(_logText, packUid.Value, "Checking for prevailing position."); prevailingPosition = dbContext.POSITION .Include(x =&gt; x.POSITION_DETAIL) .Include(x =&gt; x.POSITION_DETAIL).ThenInclude(x =&gt; x.POSITION_BOND) .Include(x =&gt; x.POSITION_DETAIL).ThenInclude(x =&gt; x.POSITION_FX) .Include(x =&gt; x.POSITION_DETAIL).ThenInclude(x =&gt; x.POSITION_OPTION) .Include(x =&gt; x.POSITION_DETAIL).ThenInclude(x =&gt; x.POSITION_PRICE) .Where(x =&gt; x.Account_UID == accountGuid &amp;&amp; x.Security_UID == mappedSecurity.SecurityGuid &amp;&amp; x.SecurityFirmID == mappedSecurity.FirmId &amp;&amp; (x.DateStart.Date &lt;= statementDate) &amp;&amp; (!x.DateEnd.HasValue || x.DateEnd.Value.Date &lt; statementDate) &amp;&amp; x.ChangeType != "D" &amp;&amp; x.POSITION_DETAIL.Any(pd =&gt; pd.Genesis == "FEED" &amp;&amp; pd.ChangeType != "D")) .OrderByDescending(x =&gt; x.DateStart) .ToList().FirstOrDefault(); if(useDiagnosticLogging) LocalLoggingUtilities.WriteDiagnosticLog(_logText, packUid.Value, "Looping incoming positions."); foreach(var incomingPosition in deserializedPositions) { if(useDiagnosticLogging) LocalLoggingUtilities.WriteDiagnosticLog(_logText, packUid.Value, string.Format("Hit new incoming position:{0}", incomingPosition.Position_UID.ToString())); incomingPosition.Account_UID = accountGuid; incomingPosition.Security_UID = mappedSecurity.SecurityGuid.Value; incomingPosition.SecurityFirmID = mappedSecurity.FirmId.Value; incomingPosition.Position_UID = Guid.NewGuid(); if (prevailingPosition == null) { EntityEntry&lt;POSITION&gt; newPosition = null; dbContext.POSITION.Add(incomingPosition); newPosition = dbContext.Entry(incomingPosition); newPosition.CurrentValues.SetValues(new { ChangeType = "I" }); foreach(var posDetail in incomingPosition.POSITION_DETAIL.Where(x =&gt; x.ChangeType.ToUpper() != "D")) { EntityEntry&lt;POSITION_DETAIL&gt; newPositionDetail = null; posDetail.Detail_UID = Guid.NewGuid(); dbContext.POSITION_DETAIL.Add(posDetail); newPositionDetail = dbContext.Entry(posDetail); newPositionDetail.CurrentValues.SetValues(new { ChangeType = "I"}); updatedPosDetails.Add(posDetail); } handledPositions.Add(incomingPosition); if(useDiagnosticLogging) LocalLoggingUtilities.WriteDiagnosticLog(_logText, packUid.Value, "Inserted: " + incomingPosition.Position_UID.ToString()); } else { if(prevailingPosition.DateStart.Date == incomingPosition.DateStart.Date) { foreach(var posDetail in prevailingPosition.POSITION_DETAIL.Where(x =&gt; x.ChangeType.ToUpper() != "D")) { EntityEntry&lt;POSITION_DETAIL&gt; positionDetailToRemove = dbContext.Entry(posDetail); positionDetailToRemove.CurrentValues.SetValues(new { ChangeDate = DateTime.Now, ChangeType = "D" }); } EntityEntry&lt;POSITION&gt; positionToRemove = dbContext.Entry(prevailingPosition); positionToRemove.CurrentValues.SetValues(new { ChangeDate = DateTime.Now, ChangeType = "D" }); EntityEntry&lt;POSITION&gt; newPosition = null; dbContext.POSITION.Add(incomingPosition); newPosition = dbContext.Entry(incomingPosition); newPosition.CurrentValues.SetValues(new { ChangeType = "I" }); handledPositions.Add(incomingPosition); if(useDiagnosticLogging) LocalLoggingUtilities.WriteDiagnosticLog(_logText, packUid.Value, "inserted: " + incomingPosition.Position_UID.ToString()); foreach(var posDetail in incomingPosition.POSITION_DETAIL.Where(x =&gt; x.ChangeType.ToUpper() != "D")) { EntityEntry&lt;POSITION_DETAIL&gt; newPositionDetail = null; posDetail.Detail_UID = Guid.NewGuid(); dbContext.POSITION_DETAIL.Add(posDetail); newPositionDetail = dbContext.Entry(posDetail); newPositionDetail.CurrentValues.SetValues(new { ChangeType = "I"}); updatedPosDetails.Add(posDetail); } } else if(prevailingPosition.DateStart.Date &lt; incomingPosition.DateStart.Date &amp;&amp; PositionHasChange(prevailingPosition, incomingPosition, packUid)) { EntityEntry&lt;POSITION&gt; newPosition = null; dbContext.POSITION.Add(incomingPosition); newPosition = dbContext.Entry(incomingPosition); newPosition.CurrentValues.SetValues(new { ChangeType = "I" }); handledPositions.Add(incomingPosition); if(useDiagnosticLogging) LocalLoggingUtilities.WriteDiagnosticLog(_logText, packUid.Value, "inserted: " + incomingPosition.Position_UID.ToString()); foreach(var posDetail in incomingPosition.POSITION_DETAIL.Where(x =&gt; x.ChangeType.ToUpper() != "D")) { EntityEntry&lt;POSITION_DETAIL&gt; newPositionDetail = null; posDetail.Detail_UID = Guid.NewGuid(); dbContext.POSITION_DETAIL.Add(posDetail); newPositionDetail = dbContext.Entry(posDetail); newPositionDetail.CurrentValues.SetValues(new { ChangeType = "I"}); updatedPosDetails.Add(posDetail); } } else if(prevailingPosition.DateStart.Date &lt; incomingPosition.DateStart.Date &amp;&amp; !PositionHasChange(prevailingPosition, incomingPosition, packUid)) { } } } return handledPositions.ToArray(); } private TRANSACTION[] HandleTransctions(newportMasterContext dbContext, AccPackBody pack, AccMappedSecurity mappedSecurity, Guid? packUid = null) { object[] transactionsToProcess = new object[0]; var handledTransactions = new List&lt;TRANSACTION&gt;(); foreach(var trans in mappedSecurity.Transactions) { TRANSACTION handledTransaction = null, mappedTransaction = null; mappedTransaction = JsonConvert.DeserializeObject&lt;TRANSACTION&gt;(trans.ToString(), Configs.JsonCircularRefFixConfig); mappedTransaction.Security_UID = mappedSecurity.SecurityGuid.Value; //HACK if(string.IsNullOrWhiteSpace(mappedTransaction.BaseCurrency)) { mappedTransaction.BaseCurrency = "USD"; } //missing transId - drop out if(mappedTransaction.Reversal &amp;&amp; string.IsNullOrWhiteSpace(mappedTransaction.TranID)) { Logger.Send(pack, LogType.Warning, "Reversal Transaction is missing a transacation Id"); throw new LoggedException(); } else { //if(mappedTransaction.Reversal &amp;&amp; !string.IsNullOrWhiteSpace(mappedTransaction.TranID)) if(mappedTransaction.Reversal) { List&lt;TRANSACTION&gt; transactionsInDb = dbContext.TRANSACTION .Where(x =&gt; x.Account_UID == pack.AccountUID &amp;&amp; x.Security_UID == mappedSecurity.SecurityGuid &amp;&amp; x.SecurityFirmID == mappedSecurity.FirmId &amp;&amp; x.TradeDate.Date == mappedTransaction.TradeDate.Date &amp;&amp; x.TranID == mappedTransaction.TranID &amp;&amp; !x.Reversal &amp;&amp; x.ChangeType != "D") .ToList(); if(transactionsInDb.Count == 1) { mappedTransaction.Visible = false; TRANSACTION transactionInDb = transactionsInDb.FirstOrDefault(); transactionInDb.Visible = false; } } mappedTransaction.SecurityFirmID = mappedSecurity.FirmId.Value; mappedTransaction.Account_UID = pack.AccountUID.Value; if(mappedTransaction?.Comment?.Length &gt;= 100) { mappedTransaction.Comment = mappedTransaction.Comment.Substring(0,96) + "..."; } mappedTransaction.Tran_UID = Guid.NewGuid(); var comparer = new TransactionComparer(); EntityEntry&lt;TRANSACTION&gt; transactionToInsert = null; dbContext.TRANSACTION.Add(mappedTransaction); transactionToInsert = dbContext.Entry(mappedTransaction); transactionToInsert.CurrentValues.SetValues(new { ChangeType = "I" }); if(useDiagnosticLogging) LocalLoggingUtilities.WriteDiagnosticLog(_logText, packUid.Value, "inserted: " + mappedTransaction.Tran_UID.ToString()); if(transactionToInsert != null) { transactionToInsert.CurrentValues.SetValues(new { ChangeDate = DateTime.Now }); } handledTransaction = transactionToInsert?.Entity; if(handledTransaction != null) { handledTransactions.Add(handledTransaction); } // } } } return handledTransactions.ToArray(); } </code></pre> <p>I have refactored the HandlePositions method to multiple functions for readability and code clarity. I am working some of the other code as well right now. </p> <pre><code> private POSITION[] HandlePositions(AccPackBody reqPayload, newportMasterContext dbContext, PackState state, Guid accountGuid, AccMappedSecurity mappedSecurity, DateTime statementDate, Guid? packUid = null) { var handledPositions = new List&lt;POSITION&gt;(); //deserialize positions sent in through mappedSecurity List&lt;POSITION&gt; deserializedPositions = mappedSecurity.Postitions .Select(x =&gt; JsonConvert.DeserializeObject&lt;POSITION&gt;(x.ToString(), Configs.JsonCircularRefFixConfig)) .OrderBy(x =&gt; x.DateStart) .ToList(); //get the prevailing position if it exists POSITION prevailingPosition = GetPrevailingPosition(accountGuid, statementDate, mappedSecurity, dbContext); //loop the incoming positions to persist as necessary foreach(var incomingPosition in deserializedPositions) { incomingPosition.Account_UID = accountGuid; incomingPosition.Security_UID = mappedSecurity.SecurityGuid.Value; incomingPosition.SecurityFirmID = mappedSecurity.FirmId.Value; incomingPosition.Position_UID = Guid.NewGuid(); if (prevailingPosition == null) { //persist a position POSITION persistedPosition = AddPostionToContext(incomingPosition, dbContext); if(persistedPosition!=null) handledPositions.Add(incomingPosition); } else { if(prevailingPosition.DateStart.Date == incomingPosition.DateStart.Date) { //soft delete a position/details POSITION positionToRemove = RemovePostionFromContext(prevailingPosition, dbContext); //persist a position POSITION persistedPosition = AddPostionToContext(incomingPosition, dbContext); if(persistedPosition != null) handledPositions.Add(persistedPosition); } else if(prevailingPosition.DateStart.Date &lt; incomingPosition.DateStart.Date &amp;&amp; PositionHasChange(prevailingPosition, incomingPosition, packUid)) { //persist a position POSITION persistedPosition = AddPostionToContext(incomingPosition, dbContext); if(persistedPosition != null) handledPositions.Add(persistedPosition); } } } return handledPositions.ToArray(); } </code></pre> <p>New functions to support the above code:</p> <pre><code> private static POSITION AddPostionToContext(POSITION position, newportMasterContext context) { EntityEntry&lt;POSITION&gt; newPosition = null; context.POSITION.Add(position); newPosition = context.Entry(position); newPosition.CurrentValues.SetValues(new { ChangeType = "I" }); foreach(var posDetail in position.POSITION_DETAIL.Where(x =&gt; x.ChangeType.ToUpper() != "D")) { EntityEntry&lt;POSITION_DETAIL&gt; newPositionDetail = null; posDetail.Detail_UID = Guid.NewGuid(); context.POSITION_DETAIL.Add(posDetail); newPositionDetail = context.Entry(posDetail); newPositionDetail.CurrentValues.SetValues(new { ChangeType = "I"}); } return position; } private static POSITION RemovePostionFromContext(POSITION position, newportMasterContext context) { foreach(var posDetail in position.POSITION_DETAIL.Where(x =&gt; x.ChangeType.ToUpper() != "D")) { EntityEntry&lt;POSITION_DETAIL&gt; positionDetailToRemove = context.Entry(posDetail); positionDetailToRemove.CurrentValues.SetValues(new { ChangeDate = DateTime.Now, ChangeType = "D" }); } EntityEntry&lt;POSITION&gt; positionToRemove = context.Entry(position); positionToRemove.CurrentValues.SetValues(new { ChangeDate = DateTime.Now, ChangeType = "D" }); return position; } private static POSITION GetPrevailingPosition(Guid accountId, DateTime statementDate, AccMappedSecurity mappedSecurity, newportMasterContext context) { return (context.POSITION .Include(x =&gt; x.POSITION_DETAIL) .Include(x =&gt; x.POSITION_DETAIL).ThenInclude(x =&gt; x.POSITION_BOND) .Include(x =&gt; x.POSITION_DETAIL).ThenInclude(x =&gt; x.POSITION_FX) .Include(x =&gt; x.POSITION_DETAIL).ThenInclude(x =&gt; x.POSITION_OPTION) .Include(x =&gt; x.POSITION_DETAIL).ThenInclude(x =&gt; x.POSITION_PRICE) .OrderByDescending(x =&gt; x.DateStart) .FirstOrDefault(x =&gt; x.Account_UID == accountId &amp;&amp; x.Security_UID == mappedSecurity.SecurityGuid &amp;&amp; x.SecurityFirmID == mappedSecurity.FirmId &amp;&amp; (x.DateStart.Date &lt;= statementDate) &amp;&amp; (!x.DateEnd.HasValue || x.DateEnd.Value.Date &lt; statementDate) &amp;&amp; x.ChangeType != "D" &amp;&amp; x.POSITION_DETAIL.Any(pd =&gt; pd.Genesis == "FEED" &amp;&amp; pd.ChangeType != "D"))); } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-19T13:10:43.770", "Id": "421298", "Score": "1", "body": "`.ToList().FirstOrDefault();` doesn't make any sense since both of those methods will materialize the query. You could safely remove the `.ToList()`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-19T13:13:34.137", "Id": "421300", "Score": "2", "body": "A lot of this code doesn't make any sense. For example, `secGuidsWithPositions` is a `List<Guid>` that just gets added to, but nothing is ever done with it. Also, the formatting is really off. `secGuidsWithPositions` is Hungarian notation. `List<Guid>` should almost always be a `HashSet<Guid>` instead to prevent duplicates." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-19T13:22:32.690", "Id": "421301", "Score": "0", "body": "@BradM - secGuidsWithPositions isn't being used you are correct. I am going to pull that out. It was being used at one point." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-19T13:40:26.330", "Id": "421302", "Score": "1", "body": "Why do you do a `Where` only to later use a `FirstOrDefault`? I only see items being added to `updatedPosDetails` -- what's the point?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-19T13:46:19.827", "Id": "421303", "Score": "0", "body": "@BCdotWEB - updatedPosDetails was used previously and now that you pointed it out, it has been removed. For my use of Where() coupled with FirstOrDefault() on the prevailingPosition linq query - I am trying to get position from the database with the top date start value. Is there a cleaner way to do this?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-19T14:05:08.280", "Id": "421306", "Score": "2", "body": "You can replace the `Where` with the `FirstOrDefault`, that way the db will only return the `TOP 1` result. My main problem with your code is that there is for instance a 100+ line method in there which does all kinds of things. Understanding this code requires a lot of business knowledge and keeping track of such things is hard is a 100+ lines method with various loops and `if` blocks etc. You should split that up into properly named smaller methods. `HandlePositions` should IMHO be a class of its own (`PositionsHandler`?) with a number of methods." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-19T14:39:13.080", "Id": "421308", "Score": "0", "body": "@BCdotWEB HandlePositions has been refactored and added as an edit to the original question. I chose to keep it in the same class for now but a further refactor is necessary since you are right it should be a class of its own." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-22T12:28:08.810", "Id": "421615", "Score": "0", "body": "I'm afraid this question won't get a good answer even with a 1k bounty because it requries a lot of internal knowledge and context about the database structure like tables, indexes, relations etc and you are not providing any of these. You also are not sure what is really slowing it down. You _think_ it might be some loops but you have not proof for it. As a matter of fact it could even be the queries themselves. You should first run some benchmarks and a profiler and look at the execution plan of your database and then try to optimize the true bottlenecks." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-22T21:10:17.753", "Id": "421710", "Score": "0", "body": "@t3chb0t any recommendations on a profiler for vs code?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-26T17:19:45.283", "Id": "423408", "Score": "0", "body": "Visual Studio comes with one: [Measure app performance in Visual Studio](https://docs.microsoft.com/en-us/visualstudio/profiling/?view=vs-2019)" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "10", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-19T12:36:40.060", "Id": "217734", "Score": "1", "Tags": [ "c#", "performance", "entity-framework-core", ".net-core" ], "Title": "Persist payload containing multiple items using EF Core Performance Improvements" }
217734
<p>What do you think of this bubble sorting function in C, for a string array? I would like to improve the readability, performance, and any good practices.</p> <pre><code>void sort_entries(char **entries, int reverse) { char **next; char **previous; char *t; int value; previous = tab; while (*(next = previous + 1)) { value = strcasecmp(*previous, *next); if ((!reverse &amp;&amp; value &gt; 0) || (reverse &amp;&amp; value &lt; 0)) { t = *previous; *previous = *next; *next = t; previous = entries; continue ; } previous++; } } </code></pre>
[]
[ { "body": "<p><strong>Portability</strong><br>\nThe function <code>strcasecmp()</code> is a POSIX standard and not a in the C programming standard as pointed out in <a href=\"https://stackoverflow.com/questions/31127260/strcasecmp-a-non-standard-function\">this stack overflow question</a>. Therefore the <code>sort_entries()</code> function may not compile or link on some systems. It would be better if the program that contained the <code>sort_entries()</code> function also contained a version of <code>strcasecmp()</code>.</p>\n\n<p><strong>Performance</strong><br>\nGenerally a bubble sort will be implemented as nested loops, the inner loop going over the whole input list to perform as many swaps as possible in a single pass. This implementation restarts at the beginning after a single swap requiring more passes. There is no performance improvement by this single loop over the nested loop implementation, and there may be a performance hit.</p>\n\n<p>If the code swapped the pointers rather than the strings themselves there might be an improvement in the performance.</p>\n\n<p><strong>Variable Scope</strong><br>\nIt is better from a maintainability perspective and overall code comprehension to create variables as needed rather than create all the variables at the top of the function. It would be better if the variables <code>t</code>, <code>next</code> and <code>value</code> were defined within the loop rather than at the top of the function. The variables <code>t</code> and <code>next</code> are only needed within the if statement.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-19T15:09:08.963", "Id": "217740", "ParentId": "217737", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-19T14:24:25.363", "Id": "217737", "Score": "1", "Tags": [ "c", "strings", "sorting" ], "Title": "Bubble sort in C (for strings)" }
217737
<p>I'm new to C++, been a C programmer most of my life. I wanted to get into graphics and Direct3D is C++ so I figured it was about time. I've been learning about strings, vectors, references, smart pointers, etc. Not using classes because I still struggle to understand how to apply them in design.</p> <p>Before I dive any further in graphics I wanted to make a good debug layer just in case anything breaks. But it's probably super messy and there are many things I don't know how to do cleanly. I'd appreciate a review on this, I tried to comment it as much as possible. Thanks!</p> <pre class="lang-cpp prettyprint-override"><code>#include "../resource.h" // For IDI_ICON1 (get an icon to the window) #include "../dxerr/dxerr.h" // From https://github.com/planetchili/hw3d #include &lt;string&gt; #include &lt;vector&gt; #include &lt;memory&gt; #include &lt;windows.h&gt; #include &lt;d3d11.h&gt; #include &lt;dxgidebug.h&gt; #pragma warning(push, 0) #include &lt;fmt/format.h&gt; // Just a string formatting library, it works #pragma warning(pop) typedef const char* str; struct Window { HWND handle; int width; int height; }; struct Panic { int line; str file; std::string desc; }; #define PANIC_OK Panic { -1, "", "OK" } // Globals namespace g { static bool running = true; } // The window callback, closes the window if the close button is pressed LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam) { LRESULT result = 0; switch (msg) { case WM_CLOSE: g::running = false; break; default: result = DefWindowProcA(hwnd, msg, wparam, lparam); break; } return result; } // Creates a window properly Window create_window(str title, int width, int height) { HINSTANCE instance = GetModuleHandleA(0); WNDCLASSA winclass = {}; winclass.style = CS_OWNDC | CS_HREDRAW | CS_VREDRAW; winclass.lpfnWndProc = WndProc; winclass.hInstance = instance; winclass.lpszClassName = "DX11 Engine Window"; winclass.hIcon = LoadIconA(instance, MAKEINTRESOURCEA(IDI_ICON1)); RegisterClassA(&amp;winclass); // Do not allow maximizing or resizing DWORD style = WS_OVERLAPPEDWINDOW ^ (WS_SIZEBOX | WS_MAXIMIZEBOX); // Calculate the desired client region size RECT wr; wr.left = 100; wr.right = width + wr.left; wr.top = 100; wr.bottom = height + wr.top; AdjustWindowRect(&amp;wr, style, FALSE); HWND handle = CreateWindowA( winclass.lpszClassName, title, style, CW_USEDEFAULT, CW_USEDEFAULT, wr.right - wr.left, wr.bottom - wr.top, nullptr, nullptr, instance, 0 ); // Position the window at the center of the screen RECT rc; GetWindowRect(handle, &amp;rc); int x = (GetSystemMetrics(SM_CXSCREEN) - rc.right) / 2; int y = (GetSystemMetrics(SM_CYSCREEN) - rc.bottom) / 2; SetWindowPos(handle, 0, x, y, 0, 0, SWP_NOZORDER | SWP_NOSIZE); UnregisterClassA(winclass.lpszClassName, instance); ShowWindow(handle, SW_SHOW); return Window { handle, width, height }; } // Message loop void update_window(Window&amp; window) { MSG msg; while (PeekMessageA(&amp;msg, window.handle, 0, 0, PM_REMOVE)) { TranslateMessage(&amp;msg); DispatchMessageA(&amp;msg); } } // --- The 0 at the end of the macros is so you can use the semicolon. --- // Just create a Panic struct with proper line and file. #define CREATE_DX_PANIC(hr) Panic { __LINE__, __FILE__, gfx::get_hr(hr, __LINE__, __FILE__) }; // Same but with info #define CREATE_DX_PANIC_INFO(hr) Panic { __LINE__, __FILE__, gfx::get_hr_info(hr, __LINE__, __FILE__, gfx::get_info_messages(gfx.info)) } // Create a new scope so hr doesn't leak into the code. If assigning it to the call failed, get the proper panic. Else it's just PANIC_OK. #define PANIC_DX(call) { HRESULT hr; gfx::set_info_queue(gfx.info); if (FAILED(hr = (call))) panic = CREATE_DX_PANIC_INFO(hr); else panic = PANIC_OK; } 0 // Same thing as PANIC_DX() with the scope. For some reason comparing callr to PANIC_OK fails. Is there a cleaner way to do this? #ifdef __DEBUG #define CHECK_PANIC(call) { Panic callr = (call); if (callr.desc != "OK") \ { MessageBoxA(0, callr.desc.c_str(), "Error!", MB_OK | MB_ICONERROR); __debugbreak(); } } 0 // Same as above but just with the panic struct in functions. Since DirectX is windows only anyway I don't think it's bad to use __debugbreak(). #define CHECK_PANIC_NO_CALL() if (panic.desc != "OK") { MessageBoxA(0, panic.desc.c_str(), "Error!", MB_OK | MB_ICONERROR); __debugbreak(); } 0 // Just adds up the previous macros so you don't have to call both everytime. #define DX_CALL(call) PANIC_DX(call); CHECK_PANIC_NO_CALL(); #else #define CHECK_PANIC(call) call #define CHECK_PANIC_NO_CALL() 0 #define DX_CALL(call) call #endif namespace gfx { struct DebugInfo { unsigned long long next = 0; IDXGIInfoQueue* queue = nullptr; }; struct Graphics { IDXGISwapChain* swap; ID3D11Device* device; ID3D11DeviceContext* context; ID3D11RenderTargetView* screen; DebugInfo info; }; // Loads the dxgidebug functions as well DebugInfo create_debug_info() { DebugInfo info; // define function signature of DXGIGetDebugInterface typedef HRESULT (WINAPI* DXGIGetDebugInterface) (REFIID,void **); // load the dll that contains the function DXGIGetDebugInterface HMODULE dxgi_mod = LoadLibraryExA("dxgidebug.dll", nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32); if (dxgi_mod == nullptr) { // How to handle this? } // get address of DXGIGetDebugInterface in dll const auto DxgiGetDebugInterface = (DXGIGetDebugInterface) (void*) GetProcAddress(dxgi_mod, "DXGIGetDebugInterface"); if (DxgiGetDebugInterface == nullptr) { // How to handle this? } DxgiGetDebugInterface(__uuidof(IDXGIInfoQueue), (void**) &amp;info.queue); return info; } // Sets a point in the info queue where the messages can start to be collected void set_info_queue(DebugInfo info) { info.next = info.queue-&gt;GetNumStoredMessages(DXGI_DEBUG_ALL); } // Gets the messages from the queue std::vector&lt;std::string&gt; get_info_messages(DebugInfo info){ std::vector&lt;std::string&gt; messages; UINT64 end = info.queue-&gt;GetNumStoredMessages( DXGI_DEBUG_ALL ); for (unsigned long long i = info.next; i &lt; end; i++) { SIZE_T msg_len; // get the size of message i in bytes #pragma warning(suppress: 6001) // Use of uninitialized memory is ok here info.queue-&gt;GetMessageA(DXGI_DEBUG_ALL, i, nullptr, &amp;msg_len); // allocate memory for message auto bytes = std::make_unique&lt;unsigned char[]&gt;(msg_len); auto msg = (DXGI_INFO_QUEUE_MESSAGE*) (bytes.get()); // get the message and push its description into the vector #pragma warning(suppress: 6001) // Use of uninitialized memory is ok here info.queue-&gt;GetMessageA(DXGI_DEBUG_ALL, i, msg, &amp;msg_len); messages.emplace_back(msg-&gt;pDescription); } return messages; } std::string get_hr(HRESULT hr, int line, str file) { // Use DXErr to get error description and title. Supposedly FormatMessage() works with DX errors, but only on Windows 8 and above. std::string err_code = fmt::format("{:#x}", hr); str err_str = DXGetErrorStringA(hr); char desc[512]; DXGetErrorDescriptionA(hr, desc, sizeof desc); return fmt::format("[Code] {}\n[String] {}\n[Desc] {}\n\n[Line] {}\n[File] {}\n", err_code, err_str, desc, line, file); } // The same but with the info queue. std::string get_hr_info(HRESULT hr, int line, str file, std::vector&lt;std::string&gt; msgs) { std::string err_code = fmt::format("{:#x}", hr); // Formats it as hex str err_str = DXGetErrorStringA(hr); char desc[512]; DXGetErrorDescriptionA(hr, desc, sizeof desc); std::string info; // join all info messages with newlines into single string for(auto&amp; m : msgs) { info += m; info.push_back('\n'); } // remove final newline if exists if(!info.empty()) info.pop_back(); return fmt::format("[Code] {}\n[String] {}\n[Desc] {}\n[Info] {}\n\n[Line] {}\n[File] {}\n", err_code, err_str, desc, info, line, file); } // Is there a cleaner way to do this? struct CreateResult { Graphics gfx; Panic panic; }; CreateResult create(Window&amp; window) { Graphics gfx = {}; Panic panic; DXGI_SWAP_CHAIN_DESC swd = {}; swd.BufferDesc.Format = DXGI_FORMAT_B8G8R8A8_UNORM; swd.BufferDesc.Scaling = DXGI_MODE_SCALING_UNSPECIFIED; swd.BufferDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED; swd.SampleDesc.Count = 1; swd.SampleDesc.Quality = 0; swd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; swd.BufferCount = 1; swd.OutputWindow = window.handle; swd.Windowed = TRUE; swd.SwapEffect = DXGI_SWAP_EFFECT_DISCARD; #ifdef __DEBUG UINT flags = D3D11_CREATE_DEVICE_DEBUG; gfx.info = create_debug_info(); #else UINT flags = 0; #endif DX_CALL(D3D11CreateDeviceAndSwapChain( nullptr, D3D_DRIVER_TYPE_HARDWARE, nullptr, flags, nullptr, 0, D3D11_SDK_VERSION, &amp;swd, &amp;gfx.swap, &amp;gfx.device, nullptr, &amp;gfx.context )); ID3D11Resource* back_buffer; DX_CALL(gfx.swap-&gt;GetBuffer(0, __uuidof(ID3D11Resource), (void**) &amp;back_buffer)); DX_CALL(gfx.device-&gt;CreateRenderTargetView(back_buffer, nullptr, &amp;gfx.screen)); back_buffer-&gt;Release(); return CreateResult { gfx, panic }; } Panic present(Graphics&amp; gfx) { HRESULT hr; Panic panic; // If the error is DXGI_ERROR_DEVICE_REMOVED you actually have to get the reason from the device. if (FAILED(hr = gfx.swap-&gt;Present(1, 0))) { if (hr == DXGI_ERROR_DEVICE_REMOVED) { panic = CREATE_DX_PANIC(gfx.device-&gt;GetDeviceRemovedReason()); } else { panic = CREATE_DX_PANIC(hr); } return panic; } else { return PANIC_OK; } } void clear(Graphics&amp; gfx, float r, float g, float b) { f32 color[] = { r, g, b, 1.0f }; gfx.context-&gt;ClearRenderTargetView(gfx.screen, color); } } i32 CALLBACK WinMain(_In_ HINSTANCE instance, _In_opt_ HINSTANCE, _In_ LPSTR args, _In_ int) { Window window = create_window("DirectX 11", 800, 600); // Don't know a way to not handle this manually gfx::CreateResult gfx_r = gfx::create(window); if (gfx_r.panic.desc != "OK") { MessageBoxA(0, gfx_r.panic.desc.c_str(), "Error!", MB_OK | MB_ICONERROR); g::running = false; } gfx::Graphics gfx = gfx_r.gfx; while (g::running) { update_window(window); gfx::clear(gfx, 1.0f, 0.0f, 0.0f); CHECK_PANIC(gfx::present(gfx)); } return 0; } <span class="math-container">```</span> </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-19T14:47:41.157", "Id": "217738", "Score": "2", "Tags": [ "c++", "error-handling", "graphics" ], "Title": "DirectX11 Error Handling" }
217738
<p>Code below is answer to an exercise in Paul Graham's ANSI Common Lisp (ex. 4.1). The challenge is to rotate an array by 90 degrees. I found an example solution which I've commented below.</p> <p>It seems ok'ish and I'm enjoying learning how to use <code>do</code>, but in this particular case it seems actually more verbose than the familir c-style nested for loops to process a 2d array. I'm wondering if the below is good style or if it can be improved upon?</p> <p>Is the answer going to be the loop macro? I'm avoiding that at the moment while learning, waiting till I have better mastery of the basics. Yet would like to not pick up bad habits. Hence this question about style regarding the below.</p> <pre class="lang-lisp prettyprint-override"><code>(defun quarter-turn (arr) (let* ((dim (array-dimensions arr)) ; let* sets sequentially, not in parallel. (row (first dim)) (col (second dim)) (n row) ; initialise n to row, just to organise new-arr) ; shorthand for (new-arr nil) (cond ((not (= row col)) (format t "The arg is not a square array.~%")) (t (setf new-arr (make-array dim :initial-element nil)) (do ((i 0 (+ i 1))) ; Q. surprisingly, lisp's 'do' here looks more ((= i n)) ; verbose than c-style 'for'. Is this good style? (do ((j 0 (+ j 1))) ((= j n)) (setf (aref new-arr j i) (aref arr (- n i 1) j)))) new-arr)))) </code></pre> <p>Source for the above code: <a href="http://www.cs.uml.edu/~lhao/ai/lisp/ansi-common-lisp/solution-ch04.htm" rel="nofollow noreferrer">http://www.cs.uml.edu/~lhao/ai/lisp/ansi-common-lisp/solution-ch04.htm</a></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-20T11:45:55.987", "Id": "421378", "Score": "0", "body": "You didn't write this yourself, did you? Please take a look at the [help/on-topic]." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-22T15:39:16.617", "Id": "421638", "Score": "0", "body": "I have taken a look at the help center. The code is a solution to an exercise from a well known lisp book, which I tried to solve myself, but had no idea how to. So, I searched online and found a solution which seemed to do what was asked. I typed it in and ran the code. But I was not entirely happy with the solution and had questions I wanted to ask about it. The comments in the code are my own, forming the questions I wanted to discuss about the code. I also attributed the source as seen above. I understand the rules now, but had not realised I was falling foul of them when making this post." } ]
[ { "body": "<p>A few comments about your code:</p>\n\n<ol>\n<li>Why introduce a new variable <code>n</code> copy of another variable? If you want to be more concise you could use <code>n</code> and <code>m</code> insted of <code>row</code> and <code>col</code> (that I don't like because they are singular names, while they represent the number of rows and of columns).</li>\n<li>Why define <code>new-arr</code> before the test and then assign it after the test of squareness? Don't by shy of use <code>let</code> as many times as you need, to introduce variables when they are really necessary.</li>\n<li>Use <code>assert</code> instead of <code>cond</code> to check for correct parameters: in this way you give the user the opportunity of correct them, and produce a shorter and more readable code.</li>\n<li>Why initialize the new array to a value <code>nil</code> which is immediately overwritten?</li>\n<li>The fist <code>do</code> could return the result, so to avoid the last line of the function.</li>\n<li>Use the primitive function <code>1+</code> instead of summing by 1.</li>\n<li>Document the function with a comment about its scope as first form of the body of the function.</li>\n</ol>\n\n<p>So, after this first set of comments, the function could be rewritten as:</p>\n\n<pre><code>(defun quarter-turn (arr)\n \"rotate a square matrix 90° clockwise\"\n (let* ((dim (array-dimensions arr))\n (n (first dim))\n (m (second dim)))\n (assert (= n m) (arr) \"The argument is not a square array.\")\n (let ((new-arr (make-array dim)))\n (do ((i 0 (1+ i)))\n ((= i n) new-arr)\n (do ((j 0 (1+ j)))\n ((= j n))\n (setf (aref new-arr j i) (aref arr (- n i 1) j)))))))\n</code></pre>\n\n<p><strong>DO versus LOOP</strong></p>\n\n<p>As you have already noted, in this case <code>do</code> is more verbose than <code>loop</code>. I think that in a case like this they are more or less equivalent (just a personal opinion). I would prefer the <code>loop</code> form not only because it seems to me slightly more concise, but also because it is more “natural” for me to think of a classical nested loop for a bidimensional array in terms two nested <code>loop</code> forms:</p>\n\n<pre><code>(defun quarter-turn (arr)\n \"rotate a square matrix 90° clockwise\"\n (let* ((dim (array-dimensions arr))\n (n (first dim))\n (m (second dim)))\n (assert (= n m) (arr) \"The argument is not a square array.\")\n (let ((new-arr (make-array dim)))\n (loop for i below n\n do (loop for j below n\n do (setf (aref new-arr j i) (aref arr (- n i 1) j))))\n new-arr)))\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-22T15:52:50.683", "Id": "421640", "Score": "0", "body": "Thanks @Renzo that's a beautiful answer." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-23T07:53:16.510", "Id": "421761", "Score": "0", "body": "I noticed that, in your solutions, `let` replaces a `setf` compared to the one I posted. That seems strikingly interesting. `setf` seems one kind of scope, `let` another. I'm not quite sure how to pose this question correctly, but can/does `let` replace `setf`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-23T08:07:59.213", "Id": "421764", "Score": "0", "body": "As a thought experiment, I was trying to establish whether the second `setf` could be replaced somehow with `let`. Tentatively it appears perhaps not. I believe there might be a name for this :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-23T08:31:24.817", "Id": "421774", "Score": "0", "body": "Trying not to get confused here... I thought I'd encountered 'lexical scope' but on a quick check of what that could mean it appears i'm not quite ready for that yet. So, given the current question, would it be correct to say \"`let` creates a new lexical context, so if we tried to use it to replace the second `setf` above, it could reference, but it couldn't set, `new-arr`\". ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-23T09:22:02.183", "Id": "421789", "Score": "0", "body": "@mwal, `let` introduces new bindings: that is new variables (leaving aside special variables), and initialize them to a certain value. `setf` is a way of performing a side effect on some previously bounded variable (or even part of a data structure) and to bound that variable to a new value. So in the version you have presented the variable is introduce by the `let` and then updated by `setf` (if check is passed). In my version it is simply introduced only after the check, initializing it to a new array. So the two operators are quite different." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-23T09:24:25.823", "Id": "421790", "Score": "1", "body": "So, `setf` on a variable requires that the variable already exists, while with `let` the variable is created (even if a variabile with the name introduced already exists, it is “hidden” by the new definition, which holds only for the body of `let`)." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-19T17:26:30.993", "Id": "217747", "ParentId": "217739", "Score": "2" } } ]
{ "AcceptedAnswerId": "217747", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-19T14:49:38.773", "Id": "217739", "Score": "1", "Tags": [ "common-lisp" ], "Title": "Nested loop in lisp to process a 2d array - what's good style (with and/or without loop macro)?" }
217739
<p>Given a list <code>vs</code>, I want to get the list <code>vs'</code> of the unique elements of <code>vs</code>, as well as the indices of the elements of <code>vs</code> in <code>vs'</code>. For example, if <code>vs = [7, 8, 7, 8, 9]</code> I want to get <code>[7,8,9]</code> (the unique elements) and <code>[0,1,0,1,2]</code> (the indices).</p> <p>An easy implementation is:</p> <pre><code>import Data.List import Data.Maybe unique :: Eq a =&gt; [a] -&gt; ([a], [Int]) unique vs = (vsnub, indices) where vsnub = nub vs indices = map (\v -&gt; fromJust $ elemIndex v vsnub) vs </code></pre> <p>However I think this is not efficient. I've done an implementation using mutable vectors. The pseudo-code is (saying that <code>vs</code> is a list of numbers):</p> <pre><code>n = length of vs idx = list of n integers (to store the indices) visited = [false, false, ..., false] (n elements) nvs = list of n numbers (to store the unique elements) count = 0 for(i = 0; i &lt; n; ++i) { if(not visited[i]) { nvs[count] = vs[i] idx[i] = count visited[i] = true for(j = i+1; j &lt; n; ++j) { if(vs[j] = vs[i]) { visited[j] = true idx[j] = count } } count ++ } } nvs = first 'count' elements of nvs </code></pre> <p>And here is my Haskell code:</p> <pre><code>{-# LANGUAGE ScopedTypeVariables #-} import Control.Monad ((&gt;&gt;=)) import Data.Vector.Unboxed (Unbox, Vector, freeze, (!)) import Data.Vector.Unboxed.Mutable (IOVector, new, write) import qualified Data.Vector.Unboxed.Mutable as VM unique' :: forall a . (Unbox a, Eq a) =&gt; [a] -&gt; IO (Vector a, Vector Int) unique' vs = do let n = length vs idx &lt;- VM.replicate n 0 :: IO (IOVector Int) visited &lt;- VM.replicate n False :: IO (IOVector Bool) nvs &lt;- new n :: IO (IOVector a) let inner :: Int -&gt; Int -&gt; Int -&gt; IO () inner i j count | j == n = return () | otherwise = if vs !! i == vs !! j then do write visited j True write idx j count inner i (j+1) count else inner i (j+1) count let go :: Int -&gt; Int -&gt; IO (IOVector a) go i count | i == n = return $ VM.take count nvs | otherwise = do vst &lt;- VM.read visited i if not vst then do write nvs count (vs !! i) write idx i count write visited i True _ &lt;- inner i (i+1) count go (i+1) (count + 1) else go (i+1) count nvs' &lt;- go 0 0 &gt;&gt;= freeze idx' &lt;- freeze idx return (nvs', idx') </code></pre> <p>Is it nice? Can it be improved? Is there a solution that does not resort to <code>IO</code>?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-19T15:46:33.653", "Id": "421311", "Score": "0", "body": "Hmm.. I've done some benchmarks and the second implementation is highly slower than the first one." } ]
[ { "body": "<h3>Various Comments</h3>\n\n<p>First, Stack Exchange sent the body of my response into the void when I logged in to post it, so I'm going to be a bit more brief and a bit less organized than I originally wanted because I'm lazy.</p>\n\n<p>This is not really reviewing your code, so it would've been better served as a comment, but I didn't think to comment my approach before I wrote out all the code. Might as well share it in case it's helpful. </p>\n\n<p>To be honest, I don't quite understand your second solution, but on a second read it looks like it might still be <code>n^2</code> (same asymptotic complexity as your first solution), so that would explain why it's slower. I assumed at first it was just something to do with mutability and vectors (which I don't really understand myself), but on second read I'm no longer so sure about this.</p>\n\n<p>If you don't mind me being frank in answering your first question: I don't really think it's nice. I had a pretty rough time reading it, to the point where I instead just wrote a more Haskell-inclined solution that has better asymptotic performance than your first one.</p>\n\n<h3>Proposed Solution</h3>\n\n<p>Are you okay with an <code>n log n</code> solution? If memory serves, with the right choice of set/map, the <code>log</code>'s base is so large that it is effectively linear.</p>\n\n<p>Here is one such solution</p>\n\n<pre><code>import Data.List (foldl', sortOn)\nimport Data.Map (Map)\nimport qualified Data.Map as Map\n\n-- | Gives the unique elements of 'elems' in order.\norderedNub :: Ord a =&gt; [a] -&gt; [a]\norderedNub elems = sortOn (firstIndexMap Map.!) (Map.keys firstIndexMap)\n where\n -- Insert such that if the value is already in 'firstIndexMap', it is not\n -- updated.\n addElem m (elem, index) = Map.insertWith (flip const) elem index m\n -- Left fold in order to get the first occurance of each element.\n firstIndexMap = foldl' addElem Map.empty $ zip elems [0..]\n\n-- | Gives the unique elements of 'elems' and the indices of 'elems' in\n-- the unique list of elements.\nunique :: Ord a =&gt; [a] -&gt; ([a], [Int])\nunique elems = (uniques, indices)\n where\n uniques = orderedNub elems\n uniqueInds = zip uniques [0..]\n indexMap = foldr (uncurry Map.insert) Map.empty uniqueInds\n -- We can use unsafe indexing since we know that 'indexMap' has\n -- the right values.\n indices = [indexMap Map.! x | x &lt;- elems]\n</code></pre>\n\n<h3>Some Notes About the Solution</h3>\n\n<ol>\n<li>I changed the code so it is correct now, assuming you want to preserve order. Some of these comments may be a bit out of date as a result.</li>\n<li><code>orderedNub'</code> is a kind of clunky definition, but it should have better asymptotic performance than <code>nub</code>. I’m pretty sure you can avoid the overhead of an actual sort (one clunky way would be to use a vector like you’re using).</li>\n<li><code>uncurry Map.insert</code> is a cute pointfree thing, if that's not your dig just sub it with a lambda or helper function.</li>\n<li>I can't think of a good way to avoid using <code>Map.!</code>, even though it's partial. If I used <code>Map.lookup</code>, then there'd have to be a <code>fromJust</code> or a <code>Maybe</code> overhead, even though the map is, by construction, going to have the right keys. Guess this is a shortcoming of the type system.</li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-21T14:51:25.057", "Id": "421497", "Score": "2", "body": "You can also use [`Set.findIndex`](https://hackage.haskell.org/package/containers-0.6.0.1/docs/Data-Set.html#v:findIndex) rather than creating a `Map`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-21T18:05:14.580", "Id": "421512", "Score": "0", "body": "@4castle Do we know the input will be sorted?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-21T18:09:30.357", "Id": "421514", "Score": "0", "body": "No, but `Set.fromList` sorts its input." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-21T18:28:37.580", "Id": "421515", "Score": "0", "body": "@4castle Unless I’m mistaken, this would then give for the input [9, 8, 7, 8, 7] the output [7, 8, 9], [2, 1, 0, 1, 0]. I’m not sure if this is what the OP wants." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-21T18:32:38.713", "Id": "421516", "Score": "1", "body": "Your code already gives that output. `nub'` is producing a sorted list." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-21T21:22:30.947", "Id": "421531", "Score": "0", "body": "@4castle Ah crap, let me fix that then. Thanks for pointing that out." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-21T07:05:00.137", "Id": "217818", "ParentId": "217741", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-19T15:21:20.250", "Id": "217741", "Score": "2", "Tags": [ "haskell" ], "Title": "Unique elements of a list and corresponding indices in Haskell" }
217741
<p>I'm currently doing the Project Euler challenges to learn C++. The fifth problem is the following.</p> <blockquote> <p>2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.</p> <p>What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?</p> </blockquote> <p>I thought of a loop between 20 and 10 as everything under 10 is a multiple of something under 10. At each iteration, the result is the lcm of the loop variable and the current result.</p> <p>If I am correct, the complexity of this should be <span class="math-container">\$\mathcal{O}(n/2)\$</span>. Am I right?</p> <p>Is there any faster/better/cleaner implementation or another algorithm with a better complexity?</p> <p>This is my code.</p> <pre class="lang-cpp prettyprint-override"><code>#include &lt;iostream&gt; long gcd(long a, long b) { long t; if (b == 0) return a; while (b != 0) { t = b; b = a % b; a = t; } return a; } long lcm(long a, long b) { return (a * b) / gcd(a, b); } int main() { long n(20), result(1); for (long i = n; i &gt; n/2; --i) { result = lcm(result, i); } std::cout &lt;&lt; "Result: " &lt;&lt; result &lt;&lt; "\n"; } </code></pre>
[]
[ { "body": "<p>Welcome to Code Review! This is actually pretty good code for a beginner, but here are some things that may help you improve your program. </p>\n\n<h2>Simplify the code</h2>\n\n<p>The <code>gcd</code> routine looks like this:</p>\n\n<pre><code>long gcd(long a, long b)\n{\n long t;\n\n if (b == 0) return a;\n\n while (b != 0) {\n t = b;\n b = a % b;\n a = t;\n }\n return a;\n}\n</code></pre>\n\n<p>It can be simplified in three ways. First, we can declare <code>t</code> within the loop. Second, we can eliminate the <code>if</code> statement entirely. Third, we can simplify the while loop condition to simply <code>while (b)</code> which is the same as <code>while (b != 0)</code>:</p>\n\n<pre><code>long gcd(long a, long b)\n{\n while (b) {\n long t = b;\n b = a % b;\n a = t;\n }\n return a;\n}\n</code></pre>\n\n<h2>Use <code>const</code> where appropriate</h2>\n\n<p>The value of <code>n</code> is constant, so it would make sense to declare it either <code>const</code> or even better <code>constexpr</code>. </p>\n\n<h2>Consider signed versus unsigned</h2>\n\n<p>It's always worth thinking about the <em>domain</em> of the numbers in a calculation. In this case, it seems that all of the numbers are probably intended to be unsigned, but they're declared <code>long</code> which gives signed numbers. </p>\n\n<h2>Think of alternative algorithms and implementations</h2>\n\n<p>I think your algorithm is fast enough, but an alternative approach would instead be to calculate all of the <em>unique</em> prime factors of all of the numbers &lt; 20 and simply multiply them together. With the judicious use of <code>constexpr</code>, one could even calculate everything at compile-time which would make for a very fast calculation. For inspiration, see <a href=\"https://codereview.stackexchange.com/questions/93775/compile-time-sieve-of-eratosthenes\">Compile-time sieve of Eratosthenes</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-19T16:11:37.097", "Id": "421316", "Score": "0", "body": "If we declare `t` within the loop it will be redeclared for each pass in the loop, does this change something in term of pure performance?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-19T16:14:35.173", "Id": "421317", "Score": "0", "body": "Generally, declaring variables with the minimal possible scope allows the compiler to make better decisions regarding register allocation. However with code as small and simple as yours, it probably doesn't make a huge difference with modern compilers." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-19T16:19:28.843", "Id": "421318", "Score": "1", "body": "OK, I thought there was some specific assembly instruction executed when declaring a variable. I know this doesn't matter right here but I'm interested in optimization." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-20T04:42:41.760", "Id": "421351", "Score": "0", "body": "The condition `while (b)` is a bad abbreviation. For anything other than a boolean or a stream I prefer the explicit form `while (b != 0)`. Having this implicit type conversion is not helpful for human readers." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-20T09:17:15.253", "Id": "421371", "Score": "1", "body": "@RolandIllig: I prefer it with the shorter syntax. Regardless of which one uses, it's helpful to understand that they are 100% equivalent." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-19T15:57:49.077", "Id": "217743", "ParentId": "217742", "Score": "3" } } ]
{ "AcceptedAnswerId": "217743", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-19T15:28:35.477", "Id": "217742", "Score": "3", "Tags": [ "c++", "beginner", "programming-challenge" ], "Title": "Project Euler #5 in C++" }
217742
<p>Windows 10 has an interesting feature where it will display "fun facts" and images on the lock screen. Occasionally, these images are something I would want to use for a background.</p> <p>These images are stored in <code>%LocalAppData%\Packages\Microsoft.Windows.ContentDeliveryManager_cw5n1h2txyewy\LocalState\Assets</code>.</p> <p>As I wasn't certain if <code>_cw5n1h2txyewy</code> would be constant on the <code>Microsoft.Windows.ContentDeliveryManager</code> folder, I wanted to just search the <code>%LocalAppData%\Packages</code> directory for <code>Microsoft.Windows.ContentDeliveryManager*</code>, and pull the first directory that matches that pattern.</p> <p>Then, in that directory, I wanted to copy the images and read a "magic number" from each image, which can vary but determines the image type. In this case, I use the first 4 bytes as <code>0x89 0x50 0x4E 0x47</code> (or <code>0x89</code> then <code>PNG</code>), or bytes 6 through 9 as <code>0x4A 0x46 0x49 0x46</code> (<code>JFIF</code>) or <code>0x45 0x78 0x69 0x66</code> (<code>Exif</code>). The first condition would add the <code>png</code> extension, the second would add <code>jpg</code>.</p> <p>The first function is my <code>detect_file_type</code>, which evaluates the file contents and determines what image type it is:</p> <pre><code>fn detect_file_type(data : &amp;Vec&lt;u8&gt;) -&gt; Option&lt;String&gt; { if data[0] == 0x89 &amp;&amp; data[1] == 0x50 &amp;&amp; data[2] == 0x4E &amp;&amp; data[3] == 0x47 { // ?PNG Some("png".to_string()) } else if data[6] == 0x4A &amp;&amp; data[7] == 0x46 &amp;&amp; data[8] == 0x49 &amp;&amp; data[9] == 0x46 { // JFIF Some("jpg".to_string()) } else if data[6] == 0x45 &amp;&amp; data[7] == 0x78 &amp;&amp; data[8] == 0x69 &amp;&amp; data[9] == 0x66 { // Exif Some("jpg".to_string()) } else { None } } </code></pre> <p>This is rather simple.</p> <p>Next, I wanted my directory search function:</p> <pre><code>fn find_dir(search : &amp;str, path : PathBuf) -&gt; Option&lt;PathBuf&gt; { for entry in fs::read_dir(path).unwrap() { let path = entry.unwrap().path(); if path.is_dir() { if path.file_name().unwrap().to_str().unwrap().starts_with(search) { return Some(path); } } } return None; } </code></pre> <p>Again, rather simple. We stuck to <code>Option</code> with both of these so that we can handle the error cases (if we need to).</p> <p>And finally, we have all the critical work:</p> <pre><code>fn main() { let args = App::new("Pull Windows Lock-Screen Pictures") .version("0.1") .about("Loads the images used for the main Windows 10 Lock-Screen backgrounds to the specified folder (or './out' if not specified).") .arg(Arg::with_name("destination") .help("The destination directory ('./out' by default)") .takes_value(true) .required(false)) .get_matches(); let my_dirs = Directories::with_prefix("windows_lock_screen_pictures", "Windows_Lock_Screen_Pictures").unwrap(); let home = my_dirs.bin_home().parent().unwrap().parent().unwrap().join("Packages"); let dir = find_dir("Microsoft.Windows.ContentDeliveryManager", home).unwrap().join("LocalState").join("Assets"); for entry in fs::read_dir(dir).unwrap() { let path = entry.unwrap().path(); if !path.is_dir() { let data = fs::read(&amp;path).unwrap(); let path_str = path.display().to_string(); let file = path.file_name().unwrap().to_str().unwrap().to_string(); let path_ext = match detect_file_type(&amp;data) { Some(path_ext) =&gt; { let mut res = ".".to_string(); res.push_str(&amp;path_ext); res }, _ =&gt; "".to_string() }; let mut base_dest_dir = "".to_string(); let mut default = std::env::current_dir().unwrap().to_str().unwrap().to_string(); default.push_str("\\out\\"); let dest_dir = args.value_of("destination").unwrap_or(&amp;default); base_dest_dir.push_str(dest_dir); if !Path::new(&amp;base_dest_dir).exists() { fs::create_dir(Path::new(&amp;base_dest_dir)).expect("Could not create directory"); } base_dest_dir.push_str(&amp;file); base_dest_dir.push_str(&amp;path_ext); println!("{} -&gt; {}", path_str, base_dest_dir); fs::write(Path::new(&amp;base_dest_dir), data).expect("Could not write file"); } } } </code></pre> <p>Overall, we kept things rather small, but still allowed flexibility (and most of the safety we needed).</p> <p>Our whole program is as follows:</p> <p>extern crate clap; extern crate dirs;</p> <pre><code>use std::fs::{self}; use std::path::{Path,PathBuf}; use clap::{App,Arg}; use dirs::{Directories}; fn detect_file_type(data : &amp;Vec&lt;u8&gt;) -&gt; Option&lt;String&gt; { if data[0] == 0x89 &amp;&amp; data[1] == 0x50 &amp;&amp; data[2] == 0x4E &amp;&amp; data[3] == 0x47 { // ?PNG Some("png".to_string()) } else if data[6] == 0x4A &amp;&amp; data[7] == 0x46 &amp;&amp; data[8] == 0x49 &amp;&amp; data[9] == 0x46 { // JFIF Some("jpg".to_string()) } else if data[6] == 0x45 &amp;&amp; data[7] == 0x78 &amp;&amp; data[8] == 0x69 &amp;&amp; data[9] == 0x66 { // Exif Some("jpg".to_string()) } else { None } } fn find_dir(search : &amp;str, path : PathBuf) -&gt; Option&lt;PathBuf&gt; { for entry in fs::read_dir(path).unwrap() { let path = entry.unwrap().path(); if path.is_dir() { if path.file_name().unwrap().to_str().unwrap().starts_with(search) { return Some(path); } } } return None; } fn main() { let args = App::new("Pull Windows Lock-Screen Pictures") .version("0.1") .about("Loads the images used for the main Windows 10 Lock-Screen backgrounds to the specified folder (or './out' if not specified).") .arg(Arg::with_name("destination") .help("The destination directory ('./out' by default)") .takes_value(true) .required(false)) .get_matches(); let my_dirs = Directories::with_prefix("windows_lock_screen_pictures", "Windows_Lock_Screen_Pictures").unwrap(); let home = my_dirs.bin_home().parent().unwrap().parent().unwrap().join("Packages"); let dir = find_dir("Microsoft.Windows.ContentDeliveryManager", home).unwrap().join("LocalState").join("Assets"); for entry in fs::read_dir(dir).unwrap() { let path = entry.unwrap().path(); if !path.is_dir() { let data = fs::read(&amp;path).unwrap(); let path_str = path.display().to_string(); let file = path.file_name().unwrap().to_str().unwrap().to_string(); let path_ext = match detect_file_type(&amp;data) { Some(path_ext) =&gt; { let mut res = ".".to_string(); res.push_str(&amp;path_ext); res }, _ =&gt; "".to_string() }; let mut base_dest_dir = "".to_string(); let mut default = std::env::current_dir().unwrap().to_str().unwrap().to_string(); default.push_str("\\out\\"); let dest_dir = args.value_of("destination").unwrap_or(&amp;default); base_dest_dir.push_str(dest_dir); if !Path::new(&amp;base_dest_dir).exists() { fs::create_dir(Path::new(&amp;base_dest_dir)).expect("Could not create directory"); } base_dest_dir.push_str(&amp;file); base_dest_dir.push_str(&amp;path_ext); println!("{} -&gt; {}", path_str, base_dest_dir); fs::write(Path::new(&amp;base_dest_dir), data).expect("Could not write file"); } } } </code></pre>
[]
[ { "body": "<p>A couple of general notes. </p>\n\n<ul>\n<li>The app directory <em>should</em> be consistent. It’s a UWP app and this is part of the app package family name. Your implementation is fine though. </li>\n<li>I would take advantage of some strong type instead of <code>”jpg”</code> and <code>”png”</code> strings. </li>\n<li>Speaking of file type detection, you might want to <a href=\"https://docs.rs/tree_magic/0.2.1/tree_magic/\" rel=\"nofollow noreferrer\">use a library like tree_magic</a></li>\n<li>You really shouldn’t <code>unwrap()</code> unless you’re absolutely sure it shouldn’t fail. It’s really user unfriendly and should be reserved for developer errors. Most of your <code>unwraps</code> could fail due to file permissions. In a small app like this, I’d probably go with <a href=\"https://doc.rust-lang.org/std/result/enum.Result.html#method.expect\" rel=\"nofollow noreferrer\">expect</a> to give a friendlier error message. In something larger, the linked doc contains all the methods you’d expect on a result type. </li>\n</ul>\n\n<p>Some things I like:</p>\n\n<ul>\n<li>You quickly embraced idioms, like pattern matching and omitting the <code>return</code> keyword. </li>\n</ul>\n\n<p>Confusion:</p>\n\n<p>We’ve been reviewing each other’s code for a long time. I’m consistently surprised by your propensity to in-line dense logic in preference to extracting methods. \nI don’t mind the dense logic, I just think you have a general opportunity to <em>name</em> things and raise the level of abstraction. For this app, I expect the code to read like this, hiding away the lower level details. </p>\n\n<pre><code>let outdir = parse_args().or_else(“./out”);\nlet files = get_files();\ncopy_files(files, outdir);\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-20T01:15:57.950", "Id": "421343", "Score": "0", "body": "The `expect` didn't even dawn on me and I used it in two places there already...lol" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-20T01:11:11.927", "Id": "217760", "ParentId": "217745", "Score": "2" } } ]
{ "AcceptedAnswerId": "217760", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-19T16:12:28.750", "Id": "217745", "Score": "2", "Tags": [ "file", "rust" ], "Title": "Pulling images from Windows 10 Lock Screen to a different folder" }
217745
<p>As someone who has programmed in C for a long time, I have just written my first C++ program and feel it would be very valuable to get a review of the code, to see what features of C++ I could make more use of.</p> <p>The program provides a protocol for sending and receiving arrays of data over TCP. The idea is to</p> <pre><code>i) Send/receive the dimension of the array. ii) Send/receive the shape of the array. iii) Send/receive the data of the array. </code></pre> <p>To run the code you can do the following</p> <pre><code>g++ protocol.cpp -o protocol </code></pre> <p>Then in separate terminals, for example</p> <pre><code>./protocol server int32 float32 </code></pre> <p>and</p> <pre><code>./protocol client int32 float32 </code></pre> <p>The program itself is below</p> <pre><code>#include &lt;stdlib.h&gt; #include &lt;sys/socket.h&gt; #include &lt;netinet/in.h&gt; #include &lt;arpa/inet.h&gt; #include &lt;endian.h&gt; #include &lt;unistd.h&gt; #include &lt;iostream&gt; #include &lt;cstring&gt; int is_system_le() { // Test if the system is little endian. short int word = 0x0001; char *b = (char *) &amp;word; // In the little endian case, 1 will be read as 1 in a character. if (b[0]) { return 1; } else { return 0; } } template &lt;class int_T, class data_T&gt; class Array { public: // Fields. int_T size; int_T dim; int_T *shape; data_T *data; // Methods. Array(int size, int dim); ~Array(void); int allocate(void); }; template &lt;class int_T, class data_T&gt; Array&lt;int_T, data_T&gt;::Array(int size, int dim) { // Set fields. this-&gt;size = size; this-&gt;dim = dim; } template &lt;class int_T, class data_T&gt; int Array&lt;int_T, data_T&gt;::allocate() { // Create memory necessary for the array. this-&gt;shape = new int[dim]; this-&gt;data = new data_T[size]; return 0; } template &lt;class int_T, class data_T&gt; Array&lt;int_T, data_T&gt;::~Array() { // Delete the created memory. delete[] shape; delete[] data; } class Protocol { public: // Class constants. static const int CHUNK_BYTES = 1024; // Fields. std::string socket_type; int verbose; // Methods. Protocol(std::string socket_type, int verbose); ~Protocol(void); int plisten(std::string host, int port); int pconnect(std::string host, int port); int pclose(); template &lt;class int_T, class data_T&gt; int psend( Array&lt;int_T, data_T&gt; *arr, std::string int_format, std::string data_format ); template &lt;class int_T, class data_T&gt; int preceive( Array&lt;int_T, data_T&gt; *arr, std::string int_format, std::string data_format ); private: // Fields. int sock; int conn; // Methods. template &lt;class int_T, class data_T&gt; int psend_tcp( Array&lt;int_T, data_T&gt; *arr, std::string int_format, std::string data_format ); template &lt;class int_T, class data_T&gt; int preceive_tcp( Array&lt;int_T, data_T&gt; *arr, std::string int_format, std::string data_format ); }; // Member functions. Protocol::Protocol(std::string socket_type, int verbose) { if (verbose) { std::cout &lt;&lt; "Protocol object created." &lt;&lt; std::endl; } this-&gt;socket_type = socket_type; this-&gt;verbose = verbose; } Protocol::~Protocol(void) { if (verbose) { std::cout &lt;&lt; "Protocol object deleted." &lt;&lt; std::endl; } } int Protocol::plisten(std::string host, int port) { // Listen for a connection on the host/port. if (socket_type.compare("server") != 0) { throw "Error: Can only listen with server sockets."; } // Create the socket. sock = socket(AF_INET, SOCK_STREAM, 0); // Set up host address structure (don't understand this). struct sockaddr_in server_addr; server_addr.sin_family = AF_INET; server_addr.sin_port = htons(port); server_addr.sin_addr.s_addr = inet_addr(host.c_str()); memset(server_addr.sin_zero, '\0', sizeof(server_addr.sin_zero)); // Bind to host port. bind(sock, (struct sockaddr *) &amp;server_addr, sizeof(server_addr)); // Listen for connection. if (verbose) { std::cout &lt;&lt; "Listening for connections." &lt;&lt; std::endl; } listen(sock, 1); // Accept a connection. struct sockaddr_in client_addr; socklen_t client_addr_len = sizeof(client_addr); conn = accept(sock, (struct sockaddr *) &amp;client_addr, &amp;client_addr_len); if (verbose) { std::cout &lt;&lt; "Accepted connection." &lt;&lt; std::endl; } return 0; } int Protocol::pconnect(std::string host, int port) { // Connect to an actual socket. if (socket_type.compare("client") != 0) { throw "Error: Can only connect with client sockets."; } // Create the socket. sock = socket(AF_INET, SOCK_STREAM, 0); // Set up host address structure (don't understand this). struct sockaddr_in server_addr; server_addr.sin_family = AF_INET; server_addr.sin_port = htons(port); server_addr.sin_addr.s_addr = inet_addr(host.c_str()); memset(server_addr.sin_zero, '\0', sizeof(server_addr.sin_zero)); // Try to connect. if (verbose) { std::cout &lt;&lt; "Trying to connect." &lt;&lt; std::endl; } connect( sock, (struct sockaddr *) &amp;server_addr, sizeof(server_addr) ); if (verbose) { std::cout &lt;&lt; "Accepted connection." &lt;&lt; std::endl; } return 0; } int Protocol::pclose() { // Close a created server or client socket. if (socket_type.compare("server") == 0) { if (verbose) { std::cout &lt;&lt; "Closing server socket." &lt;&lt; std::endl; } close(sock); } else if (socket_type.compare("client") == 0) { if (verbose) { std::cout &lt;&lt; "Closing client socket." &lt;&lt; std::endl; } shutdown(sock, SHUT_WR); close(sock); } return 0; } template &lt;class int_T, class data_T&gt; int Protocol::psend(Array&lt;int_T, data_T&gt; *arr, std::string int_format, std::string data_format) { // Send data in arr across the network. int ack; ack = psend_tcp(arr, int_format, data_format); if (ack != 0) { throw "Did not receive good acknowledgement after sending data."; } return 0; } template &lt;class int_T, class data_T&gt; int Protocol::psend_tcp(Array&lt;int_T, data_T&gt; *arr, std::string int_format, std::string data_format) { // Send data in arr across the network using TCP. // This can certainly be cleaned up by using templates and factoring out // the function for sending chunked data over the network. // Note we always use little endian. uint8_t buffer[1024]; size_t buffer_byte_size; // Server sends over conn, client over sock. int send_sock; if (socket_type.compare("server") == 0) { send_sock = conn; } else if (socket_type.compare("client") == 0) { send_sock = sock; } // i) Send the integer dimensions. if (int_format.compare("int32") == 0) { int32_t little_endian_int = (int32_t) htole32((uint32_t) arr-&gt;dim); memcpy( &amp;buffer[0], &amp;little_endian_int, sizeof(little_endian_int) ); buffer_byte_size = sizeof(int32_t); } else if (int_format.compare("int64") == 0) { int64_t little_endian_int = (int64_t) htole64((uint64_t) arr-&gt;dim); memcpy( &amp;buffer[0], &amp;little_endian_int, sizeof(little_endian_int) ); buffer_byte_size = sizeof(int64_t); } if (verbose) { std::cout &lt;&lt; "Sending dimensions: " &lt;&lt; int_format &lt;&lt; std::endl; } send(send_sock, buffer, buffer_byte_size, 0); // ii) Send the integer shape. May need to be done in multiple chunks. if (int_format.compare("int32") == 0) { buffer_byte_size = sizeof(int32_t); } else if (int_format.compare("int64") == 0) { buffer_byte_size = sizeof(int64_t); } // Make sure our arr-&gt;shape is stored in int_format. In future can maybe // auto-fix by converting it. if (sizeof(int_T) != buffer_byte_size) { throw "Error: Array integers not in int_format so cannot send."; } // Make sure our host system is little endian as we don't bother converting // here. We could theoretically write to a buffer at convert. if (!is_system_le()) { throw "Currently rely on the system being little endian."; } int reps = arr-&gt;dim * buffer_byte_size/CHUNK_BYTES; int leftover = arr-&gt;dim * buffer_byte_size % CHUNK_BYTES; if (verbose) { std::cout &lt;&lt; "Sending shape: " &lt;&lt; int_format &lt;&lt; std::endl; } for (int i=0; i&lt;reps; i++) { memcpy( &amp;buffer[0], &amp;arr-&gt;shape[i*CHUNK_BYTES/buffer_byte_size], CHUNK_BYTES ); send(send_sock, buffer, CHUNK_BYTES, 0); } // Send leftover bytes. memcpy( &amp;buffer[0], &amp;arr-&gt;shape[reps*CHUNK_BYTES/buffer_byte_size], leftover ); send(send_sock, buffer, leftover, 0); // iii) Send the array data (I'm not sure if we can be sure of float and // double size). Requires converting to data_format. if (data_format.compare("int32") == 0) { buffer_byte_size = sizeof(int32_t); } else if (data_format.compare("int64") == 0) { buffer_byte_size = sizeof(int64_t); } else if (data_format.compare("float32") == 0) { buffer_byte_size = sizeof(float); } else if (data_format.compare("float64") == 0) { buffer_byte_size = sizeof(double); } if (sizeof(data_T) != buffer_byte_size) { throw "Error: Array data not in data_format so cannot send."; } reps = arr-&gt;size * buffer_byte_size/CHUNK_BYTES; leftover = arr-&gt;size * buffer_byte_size % CHUNK_BYTES; if (verbose) { std::cout &lt;&lt; "Sending data: " &lt;&lt; data_format &lt;&lt; std::endl; } for (int i=0; i&lt;reps; i++) { memcpy( &amp;buffer[0], &amp;arr-&gt;data[i*CHUNK_BYTES/buffer_byte_size], CHUNK_BYTES ); send(send_sock, buffer, CHUNK_BYTES, 0); } // Send lefotver bytes. memcpy( &amp;buffer[0], &amp;arr-&gt;data[reps*CHUNK_BYTES/buffer_byte_size], leftover ); send(send_sock, buffer, leftover, 0); // Receive acknowledgement. recv(send_sock, buffer, 1, 0); return buffer[0]; } template &lt;class int_T, class data_T&gt; int Protocol::preceive(Array&lt;int_T, data_T&gt; *arr, std::string int_format, std::string data_format) { // Put the received value into arr. preceive_tcp(arr, int_format, data_format); return 0; } template &lt;class int_T, class data_T&gt; int Protocol::preceive_tcp(Array &lt;int_T, data_T&gt; *arr, std::string int_format, std::string data_format) { // Receive network data over TCP. // Note we always use little endian. uint8_t buffer[1024]; size_t buffer_byte_size; // Server receives over conn, client over sock. int send_sock; if (socket_type.compare("server") == 0) { send_sock = conn; } else if (socket_type.compare("client") == 0) { send_sock = sock; } // i) Receive integer dimension. if (int_format.compare("int32") == 0) { buffer_byte_size = sizeof(int32_t); } else { buffer_byte_size = sizeof(int64_t); } if (buffer_byte_size != sizeof(int_T)) { throw "Tried to receive data into an array with wrong integer format"; } recv(send_sock, buffer, buffer_byte_size, 0); if (int_format.compare("int32") == 0) { int32_t little_endian_int = (int32_t) le32toh(((uint32_t *) buffer)[0]); arr-&gt;dim = (int) little_endian_int; } else if (int_format.compare("int64") == 0) { int64_t little_endian_int = (int64_t) le64toh(((uint64_t *) buffer)[0]); arr-&gt;dim = (int) little_endian_int; } if (verbose) { std::cout &lt;&lt; "Received dimensions: " &lt;&lt; arr-&gt;dim &lt;&lt; std::endl; } // ii) Receive integer shape (may need to be done in chunks). arr-&gt;shape = new int[arr-&gt;dim]; //arr-&gt;shape = (int_T *) malloc(arr-&gt;dim*sizeof(int_T)); int reps = arr-&gt;dim * buffer_byte_size/CHUNK_BYTES; int leftover = arr-&gt;dim * buffer_byte_size % CHUNK_BYTES; for (int i=0; i&lt;reps; i++) { recv(send_sock, &amp;arr-&gt;shape[i*CHUNK_BYTES/buffer_byte_size], CHUNK_BYTES, 0); } // Recieve lefotver bytes. recv(send_sock, &amp;arr-&gt;shape[reps*CHUNK_BYTES/buffer_byte_size], leftover, 0); if (verbose) { std::cout &lt;&lt; "Received shape:" &lt;&lt; std::endl; std::cout &lt;&lt; " ["; for (int i=0; i&lt;arr-&gt;dim; i++) { std::cout &lt;&lt; arr-&gt;shape[i]; if (i != arr-&gt;dim - 1) { std::cout &lt;&lt; ","; } } std::cout &lt;&lt; "]" &lt;&lt; std::endl; } // iii) Recieve data. if (data_format.compare("int32") == 0) { buffer_byte_size = sizeof(int32_t); } else if (data_format.compare("int64") == 0) { buffer_byte_size = sizeof(int64_t); } else if (data_format.compare("float32") == 0) { buffer_byte_size = sizeof(float); } else { buffer_byte_size = sizeof(double); } if (sizeof(data_T) != buffer_byte_size) { // Should check on full type not just bytes. Unfortunately don't know // how to do this in C++. throw "Error: Array data not in data_format so cannot receive."; } // Determine the size from the shape. arr-&gt;size = 1; for (int i=0; i&lt;arr-&gt;dim; i++) { arr-&gt;size *= arr-&gt;shape[i]; } arr-&gt;data = new data_T[arr-&gt;size]; //arr-&gt;data = (data_T *) malloc(arr-&gt;size * sizeof(data_T)); reps = arr-&gt;size * buffer_byte_size/CHUNK_BYTES; leftover = arr-&gt;size * buffer_byte_size % CHUNK_BYTES; for (int i=0; i&lt;reps; i++) { recv( send_sock, &amp;arr-&gt;data[i*CHUNK_BYTES/buffer_byte_size], CHUNK_BYTES, 0 ); } // Receive leftover bytes. recv( send_sock, &amp;arr-&gt;data[reps*CHUNK_BYTES/buffer_byte_size], leftover, 0 ); if (verbose) { std::cout &lt;&lt; "Received data:" &lt;&lt; std::endl; if ((arr-&gt;size &lt; 50) &amp; (arr-&gt;dim == 2)) { for (int i=0; i&lt;arr-&gt;shape[0]; i++) { for (int j=0; j&lt;arr-&gt;shape[1]; j++) { std::cout &lt;&lt; arr-&gt;data[i*arr-&gt;shape[1] + j] &lt;&lt; ", "; } std::cout &lt;&lt; std::endl; } } } // No acknowledgement necessary for TCP however send anyway. buffer[0] = 0; send(send_sock, buffer, 1, 0); return 0; } int main(int argc, char *argv[]) { // Declare the protocol. std::string socket_type; if (argc == 1) { std::cout &lt;&lt; "No socket type provided so using server." &lt;&lt; std::endl; socket_type = "server"; } else { std::cout &lt;&lt; "Using protocol type " &lt;&lt; argv[1] &lt;&lt; "." &lt;&lt; std::endl; socket_type = argv[1]; } Protocol cp(socket_type, 1); std::cout &lt;&lt; "Total chunk bytes: " &lt;&lt; cp.CHUNK_BYTES &lt;&lt; std::endl; std::cout &lt;&lt; "Socket Type: " &lt;&lt; cp.socket_type &lt;&lt; std::endl; std::cout &lt;&lt; "Verbose: " &lt;&lt; cp.verbose &lt;&lt; std::endl; if (cp.socket_type.compare("server") == 0) { try { cp.plisten("127.0.0.1", 65432); } catch (const char *msg) { std::cerr &lt;&lt; msg &lt;&lt; std::endl; } // Now send some random data (5 x 2 array). Array&lt;int, float&gt; arr(10, 2); arr.allocate(); arr.shape[0] = 5; arr.shape[1] = 2; for (int i=0; i&lt;10; i++) { if (!strcmp(argv[3], "float32") || !strcmp(argv[3], "float64")) { arr.data[i] = i + i*0.1; } else { arr.data[i] = i; } } cp.psend(&amp;arr, argv[2], argv[3]); } else { try { cp.pconnect("127.0.0.1", 65432); } catch (const char *msg) { std::cerr &lt;&lt; msg &lt;&lt; std::endl; } // Now receive some random data. Array&lt;int, float&gt; arr(-1, -1); cp.preceive(&amp;arr, argv[2], argv[3]); } cp.pclose(); return 0; } </code></pre> <p><strong>Notes</strong></p> <p>1) One of the issues I had was that I felt it would be nicer for the <code>Protocol::preceive</code> method to return an <code>Array</code> instance but I didn't know how to pass the template to the method when none of the arguments used it. Instead I went for passing a pointer to an instance. </p> <p>2) This had another issue that I wanted the <code>Array</code> constructor to allocate the memory necessary for holding the shape and data information. However the size of this memory is not known before the method is run. Hence I ended up not including this in my constructor. I would be interested in hearing if there is a way around this.</p> <p>3) Note that a quirk of the program is that I have <code>Protocol::psend</code> and <code>Protocol::psend_tcp</code> methods (similarly for receiving). This is for a fairly good reason that I copied the logic of this program from a Python program I wrote that also allowed sending and receiving over UDP. I wanted to leave them like this in case I wanted to add this feature in future.</p> <p>4) I thought it may be a good idea to wrap some of the C libraries (to do with sockets) in a namespace as I got quite a few name clashes (hence why I have the prefix <code>p</code> in all my methods). When I tried to do this however I ended up getting a compiler error so gave up and moved on.</p>
[]
[ { "body": "<p><strong>Alternate Header Files</strong><br>\nIn C++ if you want to include stdlib.h or string.h the proper include statements are</p>\n\n<pre><code>#include &lt;cstdlib&gt;\n#include &lt;cstring&gt;\n</code></pre>\n\n<p><strong>C++ Container Classes</strong><br>\nIn C++ there is <a href=\"https://en.cppreference.com/w/cpp/container/array\" rel=\"nofollow noreferrer\">std::array</a> that provides a built in array with iterators that might prove helpful. <a href=\"https://en.cppreference.com/w/cpp/container/vector\" rel=\"nofollow noreferrer\">std::vector</a> might be even more helpful since it is basically a variable sized array of any type. </p>\n\n<p><a href=\"https://en.cppreference.com/w/cpp/iterator/iterator\" rel=\"nofollow noreferrer\">Iterators</a> have taken the place of pointers when using container classes. Iterators make for loops over containers safer because the container classes have 2 defined iterators as member, <code>begin</code> and <code>end</code>.</p>\n\n<p><strong>Old Style C Casts Versus new C++ Casts</strong><br>\nC++ has 2 new forms of casting variables, <a href=\"https://en.cppreference.com/w/cpp/language/static_cast\" rel=\"nofollow noreferrer\">static_cast</a> and <a href=\"https://en.cppreference.com/w/cpp/language/dynamic_cast\" rel=\"nofollow noreferrer\">dynamic_cast</a>. These casts perform error checking on the cast and make casting type safe. The cast in <code>int is_system_le()</code> is not type safe if it is changed to a static_cast. See the second answer of this <a href=\"https://stackoverflow.com/questions/1001307/detecting-endianness-programmatically-in-a-c-program\">stack overflow question</a> for a workaround to the cast.</p>\n\n<p>The third answer to the stack overflow question suggests using <code>htonl()</code> as a library function that performs the same test and is portable.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-19T23:44:13.187", "Id": "217758", "ParentId": "217746", "Score": "2" } }, { "body": "<p>Reading your code is difficult because you have put all the features into a single class, the <code>Protocol</code>. It's better to split this class into several, each with its own responsibility.</p>\n\n<p>Programming sockets using the C/POSIX API is something really ugly. You should hide away all these details in a class called <code>Socket</code> (and maybe a second class called <code>ServerSocket</code>). Then you can write:</p>\n\n<pre><code>Socket conn(host, port);\nconn.psend(\"hello\", 5);\nif (!conn)\n std::cerr &lt;&lt; \"sending failed: \" &lt;&lt; conn.last_error() &lt;&lt; \"\\n\";\n</code></pre>\n\n<p>This is much nicer than dealing with raw sockets and <code>struct inaddr</code>.</p>\n\n<p>On top of this <code>Socket</code> class you should build the <code>LowLevelProtocol</code> that knows how to encode an <code>int32_t</code> and in which order to send it over the wire:</p>\n\n<pre><code>LowLevelProtocol llproto(conn);\nllproto.write_int32(12345678);\nllproto.write_uint32(12345678);\n</code></pre>\n\n<p>Using this low-level protocol, you can finally build your encoding of arrays. At this point, you don't have to think about big endian or little endian anymore, you just tell the low-level protocol to <em>send this, send that</em>.</p>\n\n<p>The benefit of this separation is that at each of these abstraction levels, there are only a few topics of interest. It easy to test these levels individually by connecting them to mocked-away objects that you only create during the test. For example, the <code>LowLevelProtocol</code> can not only write to a socket, it can also write to a <code>std::ostringstream</code>, and this one can be tested very easily.</p>\n\n<p>Another benefit is that the high-level protocol now contains the rules of how an array is encoded, and nothing else. This makes it easy to understand this small part of the program.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-20T04:12:00.483", "Id": "217764", "ParentId": "217746", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-19T17:06:57.390", "Id": "217746", "Score": "3", "Tags": [ "c++", "socket" ], "Title": "C++ protocol for sending arrays over TCP" }
217746
<h3>Introduction</h3> <p>I'm writing unit tests for an extension method I wrote. Its only purpose it is to wrap startup logic which extends <a href="https://docs.microsoft.com/dotnet/api/microsoft.aspnetcore.mvc.razor.razorviewengineoptions.viewlocationexpanders" rel="nofollow noreferrer"><code>ViewLocationExpanders</code></a> list by an instance implementating <a href="https://docs.microsoft.com/dotnet/api/microsoft.aspnetcore.mvc.razor.iviewlocationexpander" rel="nofollow noreferrer"><code>IViewLocationExpander</code></a>. <code>ViewLocationExpanders</code> is a property of <a href="https://docs.microsoft.com/dotnet/api/microsoft.aspnetcore.mvc.razor.razorviewengineoptions" rel="nofollow noreferrer"><code>RazorViewEngineOptions</code></a>, which can be configured in application startup in <code>ConfigureServices()</code> method. I'm using XUnit 2.4.1.</p> <h3>Usage</h3> <p>Instead of:</p> <pre><code>services.Configure&lt;RazorViewEngineOptions&gt;(options =&gt; { options.ViewLocationExpanders.Add(new ViewLocationExpander()); }); </code></pre> <p>I can use:</p> <pre><code>services.AddViewLocationExpander(new ViewLocationExpander()); </code></pre> <h3>ViewLocationExpander</h3> <pre><code>public class ViewLocationExpander : IViewLocationExpander { public IEnumerable&lt;string&gt; ExpandViewLocations( ViewLocationExpanderContext context, IEnumerable&lt;string&gt; viewLocations) { if (context == null) { throw new ArgumentNullException(nameof(context)); } if (viewLocations == null) { throw new ArgumentNullException(nameof(viewLocations)); } /* * Note: * {0} = action name * {1} = controller name * {2} = area name */ var newViewLocations = new string[] { // Example: '/Views/Home/_Partials/FooBar.cshtml' "/Views/{1}/_Partials/{0}.cshtml", }; // Add new locations *AFTER* MVC default locations. return viewLocations.Union(newViewLocations); } public void PopulateValues(ViewLocationExpanderContext context) { context.Values["customviewlocation"] = nameof(ViewLocationExpander); } } </code></pre> <h3>Extension method</h3> <pre><code>public static IServiceCollection AddViewLocationExpander( this IServiceCollection services, IViewLocationExpander viewLocationExpander) { if (services == null) { throw new ArgumentNullException(nameof(services)); } if (viewLocationExpander == null) { throw new ArgumentNullException(nameof(viewLocationExpander)); } return services.Configure&lt;RazorViewEngineOptions&gt;(options =&gt; { options.ViewLocationExpanders.Add(viewLocationExpander); }); } </code></pre> <h3>Unit tests</h3> <pre><code>[Fact] public void ExtensionMethodAddsNewViewLocationExpander() { // Arrange var services = new ServiceCollection(); services.AddMvc(); // These two are required to active the RazorViewEngineOptions. services.AddSingleton&lt;IHostingEnvironment, HostingEnvironment&gt;(); services.AddSingleton&lt;ILoggerFactory, LoggerFactory&gt;(); // Act var serviceProvider = services.BuildServiceProvider(); var oldOptions = serviceProvider.GetRequiredService&lt;IOptions&lt;RazorViewEngineOptions&gt;&gt;().Value; services.AddViewLocationExpander(new ViewLocationExpander()); serviceProvider = services.BuildServiceProvider(); var newOptions = serviceProvider.GetRequiredService&lt;IOptions&lt;RazorViewEngineOptions&gt;&gt;().Value; // Assert Assert.True(newOptions.ViewLocationExpanders.Count &gt; oldOptions.ViewLocationExpanders.Count); } </code></pre> <h3>Questions</h3> <ol> <li>Am I going beyond the scope of what unit testing should include? I'm afraid that my code is actually testing the basic functions of generic collections and/or aspects of ASP.NET Core.</li> <li>If my concern above is true, that should I write unit tests to this at all? How should it work?</li> </ol>
[]
[ { "body": "<p>I find your test is excelent (and I'll borrow it from you). I would, however, make it a litte bit more exact and not only test the counts of generated locations but also whether they have the expected values.</p>\n\n<p>You are not testing basic functions of collections or ASP.NET-Core aspects because it doesn't matter how it's implemented. What you are testing is whether your application has all the view locations it needs to work correctly.</p>\n\n<p>This is a very important (integration) test and you should not remove it but improve it by asserting the actual locations too. If this breaks then your app wont't work anymore so it's a real lifesaver.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-19T21:32:23.093", "Id": "421335", "Score": "0", "body": "Thank you for answer. Maybe I should write further integration test checking if appropriate views are found with the new `ViewLocationExpanderadded`? But that would probably be outside the scope of unit testing and secondly inside that unit test method there is not much more to test (or at least I see it that way in debugger). And please, go ahead and borrow anything you want from my post. I'm happy it's useful." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-19T19:59:14.373", "Id": "217753", "ParentId": "217748", "Score": "4" } } ]
{ "AcceptedAnswerId": "217753", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-19T17:35:19.167", "Id": "217748", "Score": "4", "Tags": [ "c#", "unit-testing", "asp.net-core" ], "Title": "Unit testing extension method adding view location expander" }
217748
<p>I have an image stack. I am trying to use <strong>multiprocessing</strong> to do some process on each image in stack to get new image, and then <code>bitwise_or</code> with the old image.</p> <p>Since multiprocessing won't keep the original order, I pass image index as <code>args</code>.</p> <p>Later I <code>bitwise_or</code> the new image and old image by a for loop.</p> <p>Is there a way to avoid for-loop for <code>bitwise_or</code> to have a better performance? Thanks</p> <pre><code>import cv2 as cv import numpy as np from multiprocessing import Pool def process_img(idx, img): new_img = do_something(img) return idx, new_img def main() # ... output_stack = np.copy(img_stack) with Pool() as pool: args = zip( range(len(img_stack)), img_stack) new_imgs_with_idx = pool.starmap(process_img, args) for i, new_img in new_imgs_with_idx: # Any better ways? output_stack[i] = cv.bitwise_or(output_stack[i], new_img) # ... return output_stack </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-19T17:45:38.610", "Id": "217749", "Score": "1", "Tags": [ "python", "performance", "python-3.x", "multiprocessing" ], "Title": "Image processing using multiprocessing in Python" }
217749
<p>As my first Python program I have written a simple BMI calculator. I want to know how i can improve this program. Would functions be useful? How can I improve the way that it is presented? </p> <pre><code>#Introduce BMI Calculator print ('Welcome to BMI Calculator!') #Ask if user would like to use Metric or Imperial units input1 = input ('Would you like to input Metric units or Imperial units? ') #If Imperial... If Metric... Calculate BMI... if input1 == 'imperial': heightIN = float(input('Input your height in Inches (in): ')) weightLB = float(input('Input your weight in Pounds (lbs):' )) BMI = round(((weightLB/(heightIN*heightIN))*703), 2) if BMI &gt;= 19 and BMI &lt;= 24: print ('Your BMI is', BMI, 'so, you are healthy weight!') elif BMI &gt;= 25 and BMI &lt;= 29: print ('Your BMI is', BMI, 'so, you are overweight!') elif BMI &gt;= 30 and BMI &lt;= 39: print ('Your BMI is', BMI, 'so, you are obese!') elif BMI &gt; 39: print ('Your BMI is', BMI, 'so, you are extremely obese!') elif BMI &lt; 19: print ('Your BMI is', BMI, 'so, you are underweight!') elif input1 == 'metric': heightCM = float(input('Input your height in Centimeters (cm): ')) weightKG = float(input('Input your weight in kilograms (kg): ')) heightM = heightCM*0.01 BMI = round((weightKG/(heightM*heightM)), 2) if BMI &gt;= 19 and BMI &lt;= 24: print ('Your BMI is', BMI, 'so, you are healthy weight!') elif BMI &gt;= 25 and BMI &lt;= 29: print ('Your BMI is', BMI, 'so, you are overweight!') elif BMI &gt;= 30 and BMI &lt;= 39: print ('Your BMI is', BMI, 'so, you are obese!') elif BMI &gt; 39: print ('Your BMI is', BMI, 'so, you are extremely obese!') elif BMI &lt; 19: print ('Your BMI is', BMI, 'so, you are underweight!') else: print ('There was an error with your input. Please restart the program!') </code></pre>
[]
[ { "body": "<p>It's probably best to use a function that uses SI units - you can then convert lbs to kgs and in to cm. Additionally, since the majority of the world either uses Imperial or metric, we can use a Boolean to indicate which one to use:</p>\n\n<pre><code>def BMI(height,weight,is_metric):\n if (is_metric):\n # Height in meters, weight in kg\n return weight / height**2\n else:\n # Height in inches, weight in lbs\n height = height * 0.0254\n weight = weight * 0.453\n return BMI(height,weight,True)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-19T19:26:52.530", "Id": "421331", "Score": "0", "body": "Thanks for replying! I'm not really sure of how to implement this section of code into my program. I'm also not sure how the Boolean function knows what information it is checking with 'is_metric'. Is there any way that you could explain/show me how?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-15T19:16:47.523", "Id": "425657", "Score": "0", "body": "What I would do is ask the user if they prefer metric or Imperial/US Customary units. Store the preference as a BOOLEAN that indicates whether metric was specified. Then, ask their height and weight and store them as floats. Call this function with these parameters and store the result in another variable that you can use to determine the user's health." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-19T18:50:13.497", "Id": "217752", "ParentId": "217751", "Score": "1" } }, { "body": "<p>You aren't using loops or functions, so I assume you haven't learned them yet.</p>\n\n<p>Your code is clean and readable, for the most part, so let me suggest just a few changes.</p>\n\n<p>First, see <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP-8</a>. It's the coding standard for Python (like it or not). Many of the issues I have with your code will be fixed by conforming to that standard: </p>\n\n<ul>\n<li><p>spaces between operands and operators</p></li>\n<li><p><code>snake_case</code> names</p></li>\n</ul>\n\n<p>Next, be aware that Python has an exponent operator, <code>**</code> you can use for your computations. </p>\n\n<p>Your comments are correct, but add no value. Delete any comment that simply explains in English what the next line obviously does in Python.</p>\n\n<p>Finally, apply the DRY principle: <em>don't repeat yourself!</em> Those <code>if...elif...else</code> statements in each block are the same, since the index values are normalized. Move them to the bottom, after your first <code>if else</code> (Freedom vs. Metric units) and set the index to some bogus value in your error case.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-01T16:40:22.530", "Id": "504069", "Score": "0", "body": "well what would be look like if we add loops here" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-19T20:08:02.977", "Id": "217754", "ParentId": "217751", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-19T18:33:26.607", "Id": "217751", "Score": "5", "Tags": [ "python", "beginner", "python-3.x", "calculator" ], "Title": "Simple BMI Calculator (Python 3)" }
217751
<p>I thought it would be a good idea to take some easy to solve (by hand) problems and model them in Prolog for practice. Here is <a href="https://brilliant.org/problems/messy-kid/" rel="nofollow noreferrer">a problem</a> I modeled in Prolog:</p> <blockquote> <p>A messy kid wrote a multiplication problem. </p> <ol> <li>Alice saw 100 x 6.</li> <li>Bob saw 101 x 6.</li> <li>Dan saw 102 x 9.</li> </ol> <p>Each one only misread one digit. What is the <em>real</em> solution to the problem?</p> </blockquote> <p>It proved to be (<em>much</em>) trickier to model than solve by hand, but here is what I came up with:</p> <pre><code>%- Read person saw number at position. saw(alice, 1, 0). saw(alice, 0, 1). saw(alice, 0, 2). saw(alice, 6, 3). saw(bob, 1, 0). saw(bob, 0, 1). saw(bob, 1, 2). saw(bob, 6, 3). saw(dan, 1, 0). saw(dan, 0, 1). saw(dan, 2, 2). saw(dan, 9, 3). %- Consider the case when two people see one number and one person saw a anoth- % er number. This doesnt actually mean the person "definitely" misread the nu- % mber, but if the problem can be solved it measns they definitely did. definitely_misread(Person, Digit, Position) :- saw(Person, Digit, Position), saw(Q, D, Position), Q \== Person, D \== Digit, saw(R, D, Position), R \== Q, R \== Person. %- Read a person misread the digit at poisition at position. misread(Person, Digit, Position) :- saw(Person, Digit, Position), not((definitely_misread(Person, D, P), D \== Digit, P \== Position)), (saw(Q, D1, Position), Q \== Person, D1 \== Digit), (saw(R, D2, Position), R \== Q, R \== Person, D2 \== Digit). %- Resolve if the question is actually the correct digit at that position. correct(Digit, Position) :- (saw(alice, Digit, Position), not(misread(alice, Digit, Position))); (saw(bob, Digit, Position), not(misread(bob, Digit, Position))); (saw(dan, Digit, Position), not(misread(dan, Digit, Position))). </code></pre> <p>And thus one can get the correct solutions by calling <code>correct</code> (although, it displays some digit position pairings multiple times):</p> <pre><code>?- correct(D, P). D = 1, P = 0 ; D = 0, P = 1 ; D = 6, P = 3 ; D = 1, P = 0 ; D = 0, P = 1 ; D = 6, P = 3 ; D = 1, P = 0 ; D = 0, P = 1 ; D = P, P = 2 ; false. </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-19T21:24:17.577", "Id": "217755", "Score": "3", "Tags": [ "prolog" ], "Title": "Basic logic problem in Prolog" }
217755
<p>This code is meant to take a rectangular area, and randomly divide it up into smaller rectangles in a binary tree.</p> <p>I'm somewhat new to Rust.</p> <p>I'm concerned mostly about the <code>create_subrooms</code> function. I've tried lots of other permutations, but I can't find any more elegant way of writing this, and it still looks pretty ugly in my opinion.</p> <p>Some specific questions I have:</p> <ul> <li>Would it be poor form to have the function take ownership of root, modify it and return it? This would mean I could create the tree in a single line instead of creating the Room, creating it's children and then explicitly assigning it to the left/right of it's parent</li> <li>Would I be better off having the function accept four size parameters, instead of creating the root Room beforehand and passing a reference? Or would that be too verbose?</li> </ul> <p>This struct represents a node in the tree:</p> <pre class="lang-rust prettyprint-override"><code>struct Room { x: u32, y: u32, end_x: u32, end_y: u32, left: Option&lt;Rc&lt;Room&gt;&gt;&gt;, right: Option&lt;Rc&lt;Room&gt;&gt;, } </code></pre> <p>And this function takes a previously created root Room, and recursively generates its children:</p> <pre class="lang-rust prettyprint-override"><code>fn create_subrooms(&amp;mut self, root: &amp;mut Room, depth: u32) { if depth &lt; self.max_rec_depth &amp;&amp; self.is_valid_size(root) { let mut left: Room; let mut right: Room; // Horizontal and Vertical are the direction along which, the // rectangle is split, and the new boundaries are randomly chosen // perpendicular to that match rand::random::&lt;Direction&gt;() { Vertical =&gt; { let cut = self.rng.gen_range(root.x, root.end_x); // Not including the 'new' method for brevity, // but it's form is (x, y, end_x, end_y) // children are None by default left = Room::new(root.x, root.y, cut, root.end_y); right = Room::new(cut, root.y, root.end_x, root.end_y); } Horizontal =&gt; { let cut = self.rng.gen_range(root.y, root.end_y); left = Room::new(root.x, root.y, root.end_x, cut); right = Room::new(root.x, cut, root.end_x, root.end_y); } }; self.create_subrooms(&amp;mut left, depth + 1); root.left = Some(Rc::new(left)); self.create_subrooms(&amp;mut right, depth + 1); root.right = Some(Rc::new(right)); } } </code></pre> <p>The <code>self</code> parameters are from a Builder struct which is used to customise how the area is divided.</p> <p>The create_rooms function is initially called like this:</p> <pre class="lang-rust prettyprint-override"><code>fn divide_room(&amp;mut self) { let mut root = SubDungeon::new(0, 0, self.width, self.height); self.create_subdungeons(&amp;mut root, 0); Rc::new(root) } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-19T23:43:45.587", "Id": "421340", "Score": "0", "body": "Is the tree important, or just the leaf nodes? If you're generating \"rooms\", I would expect just the leaf nodes. If it's \"subrooms\", what's the difference?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-20T04:39:30.720", "Id": "421350", "Score": "0", "body": "Can you add some code to the question that shows how `create_rooms` is called? That's helpful for understanding it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-20T08:17:30.897", "Id": "421366", "Score": "0", "body": "@AustinHastings the tree is important, as I need to do some task later where the tree is stepped through and a calculation is performed using the Rooms at each level of the tree." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-19T23:01:12.923", "Id": "217757", "Score": "3", "Tags": [ "beginner", "rust" ], "Title": "Recursively create a tree in Rust" }
217757
<p>I've written a Python script that randomly selects radio buttons for each question, and submits the google form. My main questions for improvement are:</p> <ul> <li><strong>Algorithm:</strong> I collect all the buttons into a 2D array, then use <code>random.choice</code> to select the radio buttons based on each nested array. I'm sure there's a better way to do this, since my algorithm is basically hard coded.</li> <li><strong>Performance:</strong> I know <code>random.choice</code> takes a lot more time than other methods, but it's the only way I know enough to write with it.</li> <li><strong>Wait Time:</strong> Right now, I wait .75 seconds before entering in another form. I'm wondering if there's a way to wait for the page to load completely, rather than wait and hope that it loads fast enough to not generate a <em>page not found</em> error.</li> </ul> <p><strong>script.py</strong></p> <pre><code>#run with python3 from selenium import webdriver import random import time #Setup paths and open chrome browser chrome_path = "desktop/code/python/driver/chrome/chromedriver" website_path = "https://docs.google.com/forms/d/e/1FAIpQLSdcWrIYQlNbywuLg276z0CbBw-GyQOj_s2ncR9qVA7F7FPARQ/viewform" driver = webdriver.Chrome(chrome_path) driver.get(website_path) #Define options based on each section #EXCEPT: 9 18 25 28 31 (for text areas) options = [ [0, 1, 2, 3], [4, 5, 6], [7, 8], [10, 11], [12, 13, 14, 15], [16, 17], [19, 20, 21], [22, 23, 24], [26, 27], [29, 30], [32, 33] ] #Main loop def main(counter): count = counter + 1 #Collect all buttons on page and submit button buttons = driver.find_elements_by_xpath("//*[@class='freebirdFormviewerViewItemsRadioOptionContainer']") submit = driver.find_element_by_xpath("//*[@class='quantumWizButtonPaperbuttonLabel exportLabel']") """ Randomly chooses an option from the 2D array based on what i is, and that number is the index of `buttons`, which the button in that index will be clicked """ for i in range(len(options)): buttons[random.choice(options[i])].click() #Submit form submit.click() #Go to previous page, which will be the form driver.execute_script("window.history.go(-1)") #Output how many forms have been submitted thus far print(f"Form #{count} has been submitted!") #Wait for page to load again, then call main to run again time.sleep(.75) main(count) if __name__ == '__main__': main(0) </code></pre>
[]
[ { "body": "<p>I don't think there's much to review here! Since your options are hard coded, there's not a lot of wiggle room. There are a couple things you can add if you're feeling up to it.</p>\n\n<p><strong>Docstrings</strong>: These allow documentation to see what your code is doing, marked with <code>\"\"\"</code></p>\n\n<p><strong>Constants</strong>: Variables that are constants should be uppercase LIKE_THIS</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-05T10:15:25.723", "Id": "225573", "ParentId": "217765", "Score": "1" } } ]
{ "AcceptedAnswerId": "225573", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-20T04:18:27.243", "Id": "217765", "Score": "2", "Tags": [ "python", "python-3.x", "form", "selenium" ], "Title": "Submit random choices on Google form" }
217765
<p>Part 2: <a href="https://codereview.stackexchange.com/questions/232698/tic-tac-toe-with-changeable-board-size-part-2">Tic-Tac-Toe with changeable board size (Part 2)</a></p> <p>I've created a Tic-Tac-Toe program with python which has a option to change a standard 3x3 board to NxN board. I've also created easy, hard and insane AIs.</p> <p>Please help me in improving the code and removing bugs(if any)</p> <p>Code:</p> <pre class="lang-py prettyprint-override"><code>import os from random import randint cls = lambda: os.system('CLS') # Works only in command console. # Random names names = [ 'Jacob', 'Michael', 'Joshua', 'Ethan', 'Matthew', 'Daniel', 'Christopher', 'Andrew', 'Anthony', 'William', 'Joseph', 'Alexander', 'David', 'Ryan', 'Noah', 'James', 'Nicholas', 'Tyler', 'Logan', 'John', 'Christian', 'Jonathan', 'Nathan', 'Benjamin', 'Samuel', 'Dylan', 'Brandon', 'Gabriel', 'Elijah', 'Aiden', 'Angel', 'Jose', 'Zachary', 'Caleb', 'Jack', 'Jackson', 'Kevin', 'Gavin', 'Mason', 'Isaiah', 'Austin', 'Evan', 'Luke', 'Aidan', 'Justin', 'Jordan', 'Robert', 'Isaac', 'Landon', 'Jayden', 'Thomas', 'Cameron', 'Connor', 'Hunter', 'Jason', 'Diego', 'Aaron', 'Bryan', 'Owen', 'Lucas', 'Charles', 'Juan', 'Luis', 'Adrian', 'Adam', 'Julian', 'Alex', 'Sean', 'Nathaniel', 'Carlos', 'Jeremiah', 'Brian', 'Hayden', 'Jesus', 'Carter', 'Sebastian', 'Eric', 'Xavier', 'Brayden', 'Kyle', 'Ian', 'Wyatt', 'Chase', 'Cole', 'Dominic', 'Tristan', 'Carson', 'Jaden', 'Miguel', 'Steven', 'Caden', 'Kaden', 'Antonio', 'Timothy', 'Henry', 'Alejandro', 'Blake', 'Liam', 'Richard', 'Devin', 'Riley', 'Jesse', 'Seth', 'Victor', 'Brady', 'Cody', 'Jake', 'Vincent', 'Bryce', 'Patrick', 'Colin', 'Marcus', 'Cooper', 'Preston', 'Kaleb', 'Parker', 'Josiah', 'Oscar', 'Ayden', 'Jorge', 'Ashton', 'Alan', 'Jeremy', 'Joel', 'Trevor', 'Eduardo', 'Ivan', 'Kenneth', 'Mark', 'Alexis', 'Omar', 'Cristian', 'Colton', 'Paul', 'Levi', 'Damian', 'Jared', 'Garrett', 'Eli', 'Nicolas', 'Braden', 'Tanner', 'Edward', 'Conner', 'Nolan', 'Giovanni', 'Brody', 'Micah', 'Maxwell', 'Malachi', 'Fernando', 'Ricardo', 'George', 'Peyton', 'Grant', 'Gage', 'Francisco', 'Edwin', 'Derek', 'Max', 'Andres', 'Javier', 'Travis', 'Manuel', 'Stephen', 'Emmanuel', 'Peter', 'Cesar', 'Shawn', 'Jonah', 'Edgar', 'Dakota', 'Oliver', 'Erick', 'Hector', 'Bryson', 'Johnathan', 'Mario', 'Shane', 'Jeffrey', 'Collin', 'Spencer', 'Abraham', 'Leonardo', 'Brendan', 'Elias', 'Jace', 'Bradley', 'Erik', 'Wesley', 'Jaylen', 'Trenton', 'Josue', 'Raymond', 'Sergio', 'Damien', 'Devon', 'Donovan', 'Dalton', 'Martin', 'Landen', 'Miles', 'Israel', 'Andy', 'Drew', 'Marco', 'Andre', 'Gregory', 'Roman', 'Ty', 'Jaxon', 'Avery', 'Cayden', 'Jaiden', 'Roberto', 'Dominick', 'Rafael', 'Grayson', 'Pedro', 'Calvin', 'Camden', 'Taylor', 'Dillon', 'Braxton', 'Keegan', 'Clayton', 'Ruben', 'Jalen', 'Troy', 'Kayden', 'Santiago', 'Harrison', 'Dawson', 'Corey', 'Maddox', 'Leo', 'Johnny', 'Kai', 'Drake', 'Julio', 'Lukas', 'Kaiden', 'Zane', 'Aden', 'Frank', 'Simon', 'Sawyer', 'Marcos', 'Hudson', 'Trey' ] # Dummy Variable start = 0 # Essential Variables: player = 'Player' # Player name board_type = 2 # Board Type (1 or 2) board = [['', '', ''], ['', '', ''], ['', '', '']] # The TicTacToe board win_board = [['', '', ''], ['', '', ''], ['', '', '']] # Traces the win (if any) of 'board' X = 'X' # Character for player 1 O = 'O' # Character for player 2 size = 3 # Size of 'board' def countWins(p1, p2): """ p1: Player 1 p2: Player 2 Counts the wins possible in the current move for 'p1' """ count = 0 # Keeps count of wins possible for i in range(size): for j in range(size): if board[i][j] != p1 and board[i][j] != p2: copy = board[i][j] # A dummy variable to restore 'board[i][j]' board[i][j] = p1 if win(p1) == 1: count += 1 board[i][j] = copy return count def get_insane_AI_move(ai, pl, x=0, name=''): """ ai: ai character pl: player character x: dummy variable name: ai name The best AI Follows all the tips and checks for moves leading to multiple wins constantly """ for i in range(size): for j in range(size): if board[i][j] != ai and board[i][j] != pl: copy = board[i][j] board[i][j] = ai if win(ai) == 1 or tie() == 1: if x: print(name + ' Moved To Grid', i * size + j + 1) return board[i][j] = copy for i in range(size): for j in range(size): if board[i][j] != ai and board[i][j] != pl: copy = board[i][j] board[i][j] = pl if win(pl) == 1 or tie() == 1: board[i][j] = ai if x: print(name + ' Moved To Grid', i * size + j + 1) return board[i][j] = copy wins2 = [] l = 0 for i in range(size): for j in range(size): if board[i][j] != ai and board[i][j] != pl: copy = board[i][j] board[i][j] = ai if countWins(ai, pl) &gt; 1: l += 1 r = [i, j] wins2.append(r) board[i][j] = copy if l: m = wins2[randint(0, 1000) % l] board[m[0]][m[1]] = ai if x: print(name + ' Moved To Grid', m[0] * size + m[1] + 1) return l = 0 pos_centers = [[i, j] for i in range(size) for j in range(size) if (i in [0, size - 1]) == (j in [0, size - 1]) == False] centers = [] for i in range(len(pos_centers)): x = pos_centers[i][0] y = pos_centers[i][1] if board[x][y] != ai and board[x][y] != pl: centers.append(pos_centers[i]) l += 1 if l: r = centers[randint(1, 1000) % l] board[r[0]][r[1]] = ai if x: print(name + ' Moved To Grid', r[0] * size + r[1] + 1) return l1 = 0 l2 = 0 pos_edges = [[0, 0], [0, size - 1], [size - 1, 0], [size - 1, size - 1]] edges = [] for i in range(len(pos_edges)): x = pos_edges[i][0] y = pos_edges[i][1] if board[x][y] != ai and board[x][y] != pl: edges.append(pos_edges[i]) l1 += 1 if l1: r = edges[randint(1, 1000) % l1] board[r[0]][r[1]] = ai if x: print(name + ' Moved To Grid', r[0] * size + r[1] + 1) return pos_middles = [[i, j] for i in range(size) for j in range(size) if (i in [0, size - 1]) != (j in [0, size - 1])] middles = [] for i in range(len(pos_middles)): x = pos_middles[i][0] y = pos_middles[i][1] if board[x][y] != ai and board[x][y] != pl: middles.append(pos_middles[i]) l2 += 1 r = middles[randint(1, 1000) % l2] board[r[0]][r[1]] = ai if x: print(name + ' Moved To Grid', r[0] * size + r[1] + 1) return def get_hard_AI_move(ai, pl, x=0, name=''): """ A medium AI Can only look ahead 1 move """ for i in range(size): for j in range(size): if board[i][j] != ai and board[i][j] != pl: copy = board[i][j] board[i][j] = ai if win(ai) == 1 or tie() == 1: if x: print(name + ' Moved To Grid', i * size + j + 1) return board[i][j] = copy for i in range(size): for j in range(size): if board[i][j] != ai and board[i][j] != pl: copy = board[i][j] board[i][j] = pl if win(pl) == 1 or tie() == 1: board[i][j] = ai if x: print(name + ' Moved To Grid', i * size + j + 1) return board[i][j] = copy l = 0 possible = [[i, j] for i in range(size) for j in range(size)] available = [] for i in range(len(possible)): x = possible[i][0] y = possible[i][1] if board[x][y] != ai and board[x][y] != pl: available.append(possible[i]) l += 1 r = available[randint(1, 1000) % l] board[r[0]][r[1]] = ai if x: print(name + ' Moved To Grid', r[0] * size + r[1] + 1) return def get_easy_AI_move(ai, pl, x=0, name=''): """ An easy AI Moves randomly """ l = 0 possible = [[i, j] for i in range(size) for j in range(size)] available = [] for i in range(len(possible)): x = possible[i][0] y = possible[i][1] if board[x][y] != ai and board[x][y] != pl: available.append(possible[i]) l += 1 r = available[randint(1, 1000) % l] board[r[0]][r[1]] = ai if x: print(name + ' Moved To Grid', r[0] * size + r[1] + 1) return def get_user_move(p1, p2): """ Gets user input and processes it """ g = int(input(f'Please Enter Grid Number (1 ~ {size * size}): ')) - 1 x = g // size y = g % size if x &gt;= size or y &gt;= size or board[x][y] == p1 or board[x][y] == p2: print('Please Enter A Valid Move') get_user_move(p1, p2) return print(player + ' Moved To Grid', g + 1) board[x][y] = p1 print() def get_win(p): """ Traces the win into 'win_board' """ for i in range(size): # Rows if all(board[i][j] == p for j in range(size)): for j in range(size): win_board[i][j] = p return # Columns if all(board[j][i] == p for j in range(size)): for j in range(size): win_board[j][i] = p return # Diagonals if all(board[i][i] == p for i in range(size)): for i in range(size): win_board[i][i] = p return if all(board[i][-(i + 1)] == p for i in range(size)): for i in range(size): win_board[i][-(i + 1)] = p return ## Returns in every case as multiple wins might be traced out def printBoard1(): """ Prints board type 1 """ for i in range(size - 1): print(' ' + '| ' * (size - 1)) print(end=' ') for j in range(size - 1): print(board[i][j], end=' | ') print(board[i][-1]) print(' ' + '| ' * (size - 1)) print('------' + '--------' * (size - 1)) ' | ' print(' ' + '| ' * (size - 1)) print(end=' ') for j in range(size - 1): print(board[-1][j], end=' | ') print(board[-1][-1]) print(' ' + '| ' * (size - 1)) print() def printBoard2(): """ Prints board type 2 """ for i in range(size - 1): for j in range(size - 1): print(board[i][j], end=' | ') print(board[i][-1]) print('---' * size + '-' * (size - 3)) for j in range(size - 1): print(board[-1][j], end=' | ') print(board[-1][-1]) print() def printWin(p): """ Prints 'win_board' at board type 2""" get_win(p) for i in range(size - 1): for j in range(size - 1): print(win_board[i][j], end=' | ') print(win_board[i][-1]) print('---' * size + '-' * (size - 2)) for j in range(size - 1): print(win_board[-1][j], end=' | ') print(win_board[-1][-1]) print() def getRandomName(): """ Gets random names from 'names' """ name = names[randint(1, 1000) % 250] return name def helper(): """ Help section containing Rules, Tips and Credits """ print() print('B for Back\n') print('1. Rules') print('2. Tips') print('3. Credits') option = input('\nPlease Enter Your Option: ').lower() print() if option == 'b': return if option == '1': rules() if option == '2': tips() if option == '3': about() input('Enter To Continue . . . ') print() helper() def about(): ## Couldn't name this credits as there's a built-in name print('This Game Of Tic-Tac-Toe Is Created By Srivaths') print('If You Are Unfamiliar With This Game, Please Read The Rules And Tips') print('Enjoy!!\n') def changeName(): """ Changes player name: 'player' """ global player player = input('Please Enter Your Name: ') def changeBoard(): """ Changes board type: 'board_type' """ global board_type print() print('B for Back\n') print('1.') printBoard1() print('2.\n') printBoard2() print() option = input('\nPlease Enter Your Option: ') if option == 'b' or option == 'B': return if option == '1': board_type = 1 if option == '2': board_type = 2 def changeCharacters(): """ Changes characters: 'X', 'O' """ global X, O print() X = input('Please Enter Character For Player 1 (currently ' + X + '): ') O = input('Please Enter Character For Player 2 (currently ' + O + '): ') def changeSize(): """ Changes board size: 'size' """ global size size = int(input('Please Enter Size: ')) initialize() def settings(): """ Settings """ print() print('B for Back\n') print('1. Change Name') print('2. Change Size') print('3. Change Board') print('4. Change Characters') option = input('\nPlease Enter Your Option: ').lower() if option == 'b': return if option == '1': changeName() if option == '2': changeSize() if option == '3': changeBoard() if option == '4': changeCharacters() print() settings() def main_menu(): """ The main menu """ global start # cls() print() if start == 0: intro() start = 1 main_menu() return print('Hello ' + player) print('\nQ for Quit\n') print('1. Help') print('2. Settings') print('3. Play') option = input('\nPlease Enter Your Option: ') if option == '1': helper() if option == '2': settings() if option == '3': initialize() play('X', 'O') if option == 'q' or option == 'Q': print('Thanks For Playing!\n') return print() main_menu() def rules(): """ Basic rules """ print('1. In Tic-Tac-Toe, there are 2 players \n\tand their characters are X and O respectively') print('2. Any row or column or diagonal filled tith the same character is a win') print('3. A board where there are no moves left is a tie') print('4. You are not allowed to place characters over another') print('5. The playes must play in alternate turns, starting with X') print() def tips(): """ Basic tips """ print('1. Always try and capture the center') print('2. Next try to capture the edges') print('3. Occupy the edges only if necessary') print('4. Be aware of immediate moves') print('5. Try the easy bot to get the hang of the game') print() def intro(): """ Introduction """ global board_type initialize() print('Hello Player', end=', ') changeName() print('\nHello ' + player + ', Welcome To The Game Of Tic-Tac-Toe!!') know = input('Are You Familiar With The Game? (y / n): ').lower() if know == 'n': print('\nFirst A Little Introduction To The Rules: \n') rules() print('\nNext A Few Tips: \n') tips() print('\nAnd That\'s ALL!!!\n') input('Enter To Continue . . . ') print('\n') print('\nPlease Pick Your Board Preference: \n') print('1.') printBoard1() print('2.\n') printBoard2() print() option = input('Please Enter Your Option: ') if option == '1': board_type = 1 if option == '2': board_type = 2 print() print('Change Characters Via [Main Menu -&gt; Settings -&gt; Change Characters]') print() print('Here You Must Try Your Luck Against Three Levels!!\n') print('1. Easy') print('2. Hard') print('3. Insane') print() print('Can YOU Beat Them ALL????') print('Let\'s See....\n') input('Enter To Continue . . . ') def play(p1, p2): """ The play area p1: Player 1 p2: Player 2 """ print() initialize() computer = getRandomName() print('1. Easy') print('2. Hard') print('3. Insane') print() level = int(input('Please Enter Level: ')) print() while computer == player: computer = getRandomName() print('\t\t' + player + ' VS ' + computer + '\n\n') c = randint(0, 1) pl = p1 ai = p2 if c == 0: ai = p1 pl = p2 print('\n' + computer + ' Goes First!\n\n') else: print('\n' + player + ' Goes First!\n\n') if board_type == 1: printBoard1() else: printBoard2() d = 0 while True: t = d % 2 if t == c: if level == 1: get_easy_AI_move(ai, pl, 1, computer) if level == 2: get_hard_AI_move(ai, pl, 1, computer) if level == 3: get_insane_AI_move(ai, pl, 1, computer) if board_type == 1: printBoard1() else: printBoard2() if win(ai): print(computer + ' Wins!\n') print('Below Is How ' + computer + ' Won\n\n') printWin(ai) break else: get_user_move(pl, ai) if board_type == 1: printBoard1() else: printBoard2() if win(pl): print(player + ' Wins!') print('Below Is How ' + player + ' Won\n') printWin(pl) break if tie(): print('Tie!') break d += 1 play_again(p1, p2) def initialize(): """ Resets the board """ global board, win_board board = [[' ' for _ in range(size)] for __ in range(size)] win_board = [[' ' for _ in range(size)] for __ in range(size)] def play_again(p1, p2): """ Gets input from the player asking if they want to play again """ option = input('Would You Like To Play Again? (y(yes) / n(no) / m(Main Menu): ').lower() if option == 'y': play(p1, p2) elif option == 'n': return elif option == 'm': return else: print('\nPlease Enter a Valid Option') play_again(p1, p2) def win(p): """ Checks for win """ if any(all(board[i][j] == p for j in range(size)) for i in range(size)): return True if any(all(board[j][i] == p for j in range(size)) for i in range(size)): return True if all(board[i][i] == p for i in range(size)): return True if all(board[i][-(i + 1)] == p for i in range(size)): return True return False def tie(): """ Checks for tie """ return all(all(j in [X, O] for j in i) for i in board) main_menu() </code></pre> <p>It would be more interactive if the program is run on a CMD console instead of a IDE console. If you do run the program on a CMD console, you can add <code>cls()</code> to the program in places you like.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-20T07:44:18.463", "Id": "421364", "Score": "1", "body": "Welcome to Code Review. `I would like to write better docstrings` Great! Start with revisiting [PEP 257](https://www.python.org/dev/peps/pep-0257/#specification) and comparing python library docstrings to yours." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-20T08:24:17.583", "Id": "421367", "Score": "0", "body": "Thanks! I suppose I should add return values and parameter definitions to the docstrings?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-20T08:31:15.327", "Id": "421368", "Score": "0", "body": "Anything that eases use for someone importing your module (and not familiar with its internals), but no more." } ]
[ { "body": "<p>and welcome, and thanks for providing an interesting subject. I like the idea of difficulty levels for the game!</p>\n\n<p>That said, your code is too long. Not \"too long to review,\" just \"too long.\" </p>\n\n<h3>Moar functions! (&amp; Generators!)</h3>\n\n<p>Consider this:</p>\n\n<pre><code>for i in range(size):\n for j in range(size):\n if board[i][j] != ai and board[i][j] != pl:\n copy = board[i][j]\n board[i][j] = ai\n\n if win(ai) == 1 or tie() == 1:\n if x:\n print(name + ' Moved To Grid', i * size + j + 1)\n return\n\n board[i][j] = copy\n</code></pre>\n\n<p>(Taken from the insane AI function)</p>\n\n<p>Now consider this:</p>\n\n<pre><code>for i in range(size):\n for j in range(size):\n if board[i][j] != ai and board[i][j] != pl:\n copy = board[i][j]\n board[i][j] = pl\n\n if win(pl) == 1 or tie() == 1:\n board[i][j] = ai\n if x:\n print(name + ' Moved To Grid', i * size + j + 1)\n return\n board[i][j] = copy\n</code></pre>\n\n<p>Now consider this:</p>\n\n<pre><code>for i in range(size):\n for j in range(size):\n if board[i][j] != ai and board[i][j] != pl:\n copy = board[i][j]\n board[i][j] = ai\n\n if countWins(ai, pl) &gt; 1:\n l += 1\n r = [i, j]\n wins2.append(r)\n\n board[i][j] = copy\n</code></pre>\n\n<p>Those three blocks are taken from the same function, but they are different lines. Can you see how much repetition there is in there?</p>\n\n<ul>\n<li>Iterate over <code>(i, j)</code> rows and columns</li>\n<li>Get a X/O/Empty value</li>\n<li>Check if the cell is empty</li>\n<li>Copy the prior value</li>\n<li>Check for a win or a tie</li>\n<li>Translate from coordinates into grid location</li>\n<li>Print a \"moved to\" message</li>\n<li>Set the cell.</li>\n</ul>\n\n<p>How much of that code can you replace with functions? How much of that code can you replace with generators?</p>\n\n<p>Iterating over the row/column ranges has value, but it would be better to iterate over the <code>(i, j)</code> tuples directly - it's not like you ever do one without the other.</p>\n\n<p>Even better still would be to iterate over only the tuples that represent empty cells:</p>\n\n<pre><code>for i, j in board.empty_cells():\n</code></pre>\n\n<p>Or, if you haven't learned classes yet:</p>\n\n<pre><code>for i, j in empty_cells(board):\n</code></pre>\n\n<p>You would use the <code>yield</code> keyword in a <a href=\"https://stackoverflow.com/questions/1756096/understanding-generators-in-python\">generator function</a> for this.</p>\n\n<p>Next, what are you doing? In the first loop, you ask if the player would win or tie with the next move. It turns out that \"tie\" for you means \"every location would be filled\", which is disappointing but true.</p>\n\n<p>I'd suggest that \"about to tie\" means \"only one empty spot\" and that's a globally true condition. You don't need to check it so often.</p>\n\n<p>On the other hand, all the set/check/unset logic seems like a good place to write a function:</p>\n\n<pre><code>def would_win_if_moved_to(player, location) -&gt; bool:\n ''' Return true if player would win if their glyph was placed at location. '''\n # TODO\n pass\n</code></pre>\n\n<p>If you had that function, your two top loops look like this:</p>\n\n<pre><code>for locn in empty_cells(board):\n if would_win_if_moved_to(ai, locn):\n # Go for the win!\n move_to(locn)\n\nfor locn in empty_cells(board):\n if would_win_if_moved_to(player, locn):\n # Block opponent win!\n move_to(locn)\n</code></pre>\n\n<p>Of course, you could make your logic <em>even more clear</em> by wrapping those lines into their own functions:</p>\n\n<pre><code>for locn in moves_to_win(ai):\n return locn\nfor locn in moves_to_block_win(player):\n return locn\n</code></pre>\n\n<p>In your last loop, you're appending to a list. That's a good indicator that you could be using a list comprehension, if only the rest of the loop could be written shorter. You can do that:</p>\n\n<pre><code>wins2 = [locn for locn in empty_cells(board) if wins_after_move_to(ai, locn) &gt; 1]\n</code></pre>\n\n<p>You just need a function that will do your \"speculative\" move first.</p>\n\n<h3>Moar docstrings!</h3>\n\n<p>Another use for the docstring syntax is to span multiple lines with a single string. You should use this for your giant blocks of text, like the rules and hints. Instead of doing this:</p>\n\n<pre><code>print(\"line 1\")\nprint(\"line 2\")\nprint(\"line 3\")\n</code></pre>\n\n<p>You can do this:</p>\n\n<pre><code>text = \"\"\"\n line 1\n line 2\n line 3\n\"\"\".strip('\\n')\nprint(textwrap.dedent(text))\n</code></pre>\n\n<p>Using the <code>textwrap</code> module that ships with Python.</p>\n\n<p>I think if you make these changes, your code will get a lot smaller. And you'll be ready for another review. ;-)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-22T05:45:40.167", "Id": "421569", "Score": "0", "body": "Thanks! I do know OOPS, but I prefer functions anyway. Should I use classes instead of functions? `And you'll be ready for another review. ;-)` Hope you'll be there too!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-21T20:43:20.103", "Id": "217848", "ParentId": "217767", "Score": "5" } } ]
{ "AcceptedAnswerId": "217848", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-20T05:52:14.957", "Id": "217767", "Score": "6", "Tags": [ "python", "beginner", "python-3.x", "tic-tac-toe", "ai" ], "Title": "Tic-Tac-Toe with changeable board size (Part 1)" }
217767
<p>I've been playing around a bit with a case of State Pattern but including as well ranges in order to get into a specific state.</p> <p>So the definition is as simple as this:</p> <p>There is a Steak that has a state based on its temperature, the temperature can be modified, which changes the state.</p> <p><strong>A Steak has 6 cooking states based on its temperature:</strong> </p> <ul> <li>Raw (temp &lt;= 100)</li> <li>Rare (temp > 100 &amp;&amp; temp &lt;= 110)</li> <li>MediumRare (temp > 110 &amp;&amp; temp &lt;= 120)</li> <li>Medium (temp > 120 &amp;&amp; temp &lt;= 130)</li> <li>MediumWell (temp > 130 &amp;&amp; temp &lt;= 140)</li> <li>WellDone (temp > 140)</li> </ul> <p>I am stuck trying to refactor the rules that dictate if the state must change or not. I'm aiming for a fully object-oriented solution, avoiding <code>if</code> branching conditions (if it's possible)</p> <p>I've got to a solution, without using <code>if</code> branching conditions, but feels a bit complicated and overengineered...</p> <h2>Consuming code:</h2> <pre><code>static void Main(string[] args) { var steakRules = new SteakRules(); steakRules.Add(new RawRule()); steakRules.Add(new RareRule()); steakRules.Add(new MediumRareRule()); steakRules.Add(new MediumRule()); steakRules.Add(new MediumWellRule()); steakRules.Add(new WellDoneRule()); var steak = new Steak(steakRules); //Temp 0. This stake is Raw and cannot be eaten. steak.AddTemperature(50); //Temp 50. This stake is Raw and cannot be eaten. steak.AddTemperature(55); //Temp 105. This stake is Rare and can be eaten. steak.AddTemperature(20); //Temp 125. This stake is Medium and can be eaten. steak.AddTemperature(40); //Temp 165. This stake is Well Done and can be eaten. } </code></pre> <h2>ISteakState</h2> <pre><code>public interface ISteakState { bool CanEat(); ISteakState AddTemperature(int temp); } </code></pre> <h2>Steak</h2> <pre><code>public class Steak { private ISteakState _state; public Steak(SteakRules steakRules) { _state = new Raw(0, steakRules); } public void AddTemperature(int temp) { _state = _state.AddTemperature(temp); } public override string ToString() { var canBeEaten = _state.CanEat() ? "can be eaten." : "cannot be eaten."; return $"This stake is {_state} and {canBeEaten}"; } } </code></pre> <h2>StakeState</h2> <pre><code>public abstract class SteakState : ISteakState { private int _temp; private SteakRules _steakRules; protected SteakState(int temp, SteakRules steakRules) { _temp = temp; _steakRules = steakRules; } public ISteakState AddTemperature(int temp) { return _steakRules.GetState(_temp += temp); } public abstract bool CanEat(); } </code></pre> <h2>Raw State</h2> <pre><code>public class Raw : SteakState { public Raw(int temp, SteakRules steakRules) : base(temp, steakRules) { } public override bool CanEat() =&gt; false; public override string ToString() =&gt; "Raw"; } </code></pre> <h2>Medium State</h2> <pre><code>public class Medium : SteakState { public Medium(int temp, SteakRules steakRules) : base(temp, steakRules) { } public override bool CanEat() =&gt; true; public override string ToString() =&gt; "Medium"; } </code></pre> <h2>WellDone State</h2> <pre><code>public class WellDone : SteakState { public WellDone(int temp, SteakRules steakRules) : base(temp, steakRules) { } public override bool CanEat() =&gt; true; public override string ToString() =&gt; "Well Done"; } </code></pre> <h2>SteakRules</h2> <pre><code>public class SteakRules { private IList&lt;ISteakRule&gt; _steakRules = new List&lt;ISteakRule&gt;(); public void Add(ISteakRule rule) { _steakRules.Add(rule); } public ISteakState GetState(int temp) { return _steakRules .First(rule =&gt; rule.Predicate(temp)) .GetState(temp)(this); } } </code></pre> <h2>ISteakRule</h2> <pre><code>public interface ISteakRule { bool Predicate(int temp); Func&lt;SteakRules, ISteakState&gt; GetState(int temp); } </code></pre> <h2>RawRule</h2> <pre><code>public class RawRule : ISteakRule { public bool Predicate(int temp) =&gt; temp &lt;= 100; public Func&lt;SteakRules, ISteakState&gt; GetState(int temp) =&gt; (steakRules) =&gt; new Raw(temp, steakRules); } </code></pre> <h2>MediumRule</h2> <pre><code>public class MediumRule : ISteakRule { public bool Predicate(int temp) =&gt; temp &gt; 120 &amp;&amp; temp &lt;= 130; public Func&lt;SteakRules, ISteakState&gt; GetState(int temp) =&gt; (steakRules) =&gt; new Medium(temp, steakRules); } </code></pre> <h2>WellDoneRule</h2> <pre><code>public class WellDoneRule : ISteakRule { public bool Predicate(int temp) =&gt; temp &gt; 140; public Func&lt;SteakRules, ISteakState&gt; GetState(int temp) =&gt; (steakRules) =&gt; new WellDone(temp, steakRules); } </code></pre> <p>This solution has no <code>if</code> branching conditions, classes follow SOLID principles (do they really?) and it is very extensible. However, the design is too complicated and some dependencies there seem to be out of place.</p> <p>What would your suggestion be?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-20T14:09:52.733", "Id": "421383", "Score": "2", "body": "The same or not, on Code Review there is virtually no such thing as unnecessary code. The more the better so, it'd be nice if you added all of it. We cannot review what we cannot see. You'll get a much better feedback if you include everything and when people actually can even run it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-20T16:39:01.833", "Id": "421394", "Score": "2", "body": "Hey, thanks for your feedback. I'll edit my question including the latest design I came up with. I really appreciate your comments." } ]
[ { "body": "<p>I'm not sure that eliminating <code>if</code> statements is a worthwhile exercise. <code>_steakRules.First(rule =&gt; rule.Predicate(temp))</code> is just a weakly disguised conditional test anyway.</p>\n\n<p>Your state transition rules are too liberal. According to your implementation, if you cool down a well done steak back to room temperature (<code>steak.AddTemperature(-80)</code>), then it reverts to a raw state!</p>\n\n<p>Also, <a href=\"https://en.wikipedia.org/wiki/Steak_tartare\" rel=\"nofollow noreferrer\">some raw steaks are edible</a>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-20T18:46:17.503", "Id": "421419", "Score": "0", "body": "Hey, thanks for your answer. I know this is not how real cooking works!!! You cant go from well done to raw in reality! My point was just to achieve the requirements without breaking any SOLID principles and using a fully object-oriented approach." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-20T18:28:13.770", "Id": "217789", "ParentId": "217774", "Score": "3" } }, { "body": "<p>You are correct that your current solution is over engineered. This is because you define one class per object of your program. Several of these classes behave exactly the same. Therefore their classes can be merged into one.</p>\n\n<p>A <code>SteakRule</code> consists of:</p>\n\n<ul>\n<li>Name</li>\n<li>Edible</li>\n<li>Minimum temperature</li>\n<li>Maximum temperature</li>\n</ul>\n\n<p>If one of the temperatures is optional you can pass <code>int.MinValue</code> or <code>int.MaxValue</code> for them.</p>\n\n<p>A rule does not know about other rules. It is an independent object.</p>\n\n<p>There is no need to define a specialized <code>MediumRule</code> since it fits nicely into the general <code>SteakRule</code>.</p>\n\n<p>Don't confuse \"steak\" and \"stake\", by the way.</p>\n\n<p>After merging duplicate code and removing the boilerplate interfaces, the code becomes:</p>\n\n<pre><code>using System.Collections.Generic;\nusing System.Linq;\nusing Microsoft.VisualStudio.TestTools.UnitTesting;\n\nnamespace Tests\n{\n [TestClass]\n public class SteakTest\n {\n [TestMethod]\n public void Test()\n {\n var steakRules = new List&lt;SteakRule&gt;\n {\n new SteakRule(\"Raw\", false, int.MinValue, 100),\n new SteakRule(\"Rare\", true, 101, 120),\n new SteakRule(\"MediumRare\", true, 111, 120),\n new SteakRule(\"Medium\", true, 121, 130),\n new SteakRule(\"MediumWell\", true, 131, 140),\n new SteakRule(\"WellDone\", true, 141, 200),\n new SteakRule(\"Burned\", false, 201, int.MaxValue)\n };\n\n var steak = new Steak(steakRules);\n\n Assert.AreEqual(0, steak.Temperature);\n Assert.AreEqual(\"This steak is Raw and cannot be eaten.\", steak.ToString());\n\n steak.AddTemperature(50);\n\n Assert.AreEqual(50, steak.Temperature);\n Assert.AreEqual(\"This steak is Raw and cannot be eaten.\", steak.ToString());\n\n steak.AddTemperature(55);\n\n Assert.AreEqual(105, steak.Temperature);\n Assert.AreEqual(\"This steak is Rare and can be eaten.\", steak.ToString());\n\n steak.AddTemperature(20);\n\n Assert.AreEqual(125, steak.Temperature);\n Assert.AreEqual(\"This steak is Medium and can be eaten.\", steak.ToString());\n\n steak.AddTemperature(40);\n\n Assert.AreEqual(165, steak.Temperature);\n Assert.AreEqual(\"This steak is WellDone and can be eaten.\", steak.ToString());\n\n steak.AddTemperature(40);\n\n Assert.AreEqual(205, steak.Temperature);\n Assert.AreEqual(\"This steak is Burned and cannot be eaten.\", steak.ToString());\n }\n\n public class Steak\n {\n private readonly IReadOnlyList&lt;SteakRule&gt; _rules;\n\n public Steak(IReadOnlyList&lt;SteakRule&gt; rules)\n {\n _rules = rules;\n }\n\n public int Temperature { get; private set; }\n\n public void AddTemperature(int temp)\n =&gt; Temperature += temp;\n\n public string State\n =&gt; _rules.First(rule =&gt; rule.Applies(Temperature)).Name;\n\n public bool CanEat()\n =&gt; _rules.First(rule =&gt; rule.Applies(Temperature)).Edible;\n\n public override string ToString()\n {\n var canBeEaten = CanEat() ? \"can be eaten\" : \"cannot be eaten\";\n return $\"This steak is {State} and {canBeEaten}.\";\n }\n }\n\n public class SteakRule\n {\n public string Name { get; }\n public bool Edible { get; }\n public int MinTemperature { get; }\n public int MaxTemperature { get; }\n\n public SteakRule(string name, bool edible, int minTemperature, int maxTemperature)\n {\n Name = name;\n Edible = edible;\n MinTemperature = minTemperature;\n MaxTemperature = maxTemperature;\n }\n\n public bool Applies(int temp)\n =&gt; MinTemperature &lt;= temp &amp;&amp; temp &lt;= MaxTemperature;\n }\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-22T12:48:26.340", "Id": "421620", "Score": "0", "body": "Hi, I really appreciate the time you spent to clarify, expose and explain the point. Your answer is clean and smart. I chose the previous one case it kept within state pattern. \nThanks a lot!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-21T05:21:46.060", "Id": "217815", "ParentId": "217774", "Score": "3" } }, { "body": "<p>I have to dissapoint you because this is not a state-pattern what you have written. This is some strange hybrid that I don't know what to call.</p>\n\n<p>When you take a look at the <a href=\"https://sourcemaking.com/design_patterns/state\" rel=\"nofollow noreferrer\">State Design Pattern</a> then you can find there the following checklist:</p>\n\n<blockquote>\n <ul>\n <li>Define a \"context\" class to present a single interface to the outside world.</li>\n <li>Define a State abstract base class.</li>\n <li>Represent the different \"states\" of the state machine as derived classes of the State base class.</li>\n <li>Define state-specific behavior in the appropriate State derived classes.</li>\n <li>Maintain a pointer to the current \"state\" in the \"context\" class.\n To change the state of the state machine, change the current \"state\" pointer.</li>\n </ul>\n</blockquote>\n\n<p>Your code fails the last two of them. The <code>SteakState</code>s instead of returning the next state uses a <em>lookup</em> class. This is wrong because each state should encapsulate the logic that leads to the next state which is usually unique to this state. If it isn't, then it doesn't make sense to use the state-pattern because it's cheaper to solve it in another way. Probably similar to your current solution but with fewer classes.</p>\n\n<hr>\n\n<p>I have <em>upgraded</em> your code according to the above state-pattern rules. Here's an example. Don't take it to serious, especially the <code>async/await</code>. I did it only for demonstration purposes and intentionally didn't use the <code>Async</code> suffix to make it more readable.</p>\n\n<hr>\n\n<p>You start with the <code>Raw</code> state and let the <code>while</code> loop <em>cook</em> the stake until it's done. It can also be any other state that you start with.</p>\n\n<pre><code>static async Task Main(string[] args)\n{\n var steak = new Steak\n {\n Current = new Raw()\n };\n\n while (await steak.Current.Next(steak) != null)\n {\n\n }\n}\n</code></pre>\n\n<p>Each state has a max temperature and a method to the next state:</p>\n\n<pre><code>public interface ISteakState\n{\n int MaxTemperature { get; }\n\n Task&lt;ISteakState&gt; Next(Steak context);\n}\n</code></pre>\n\n<p>The said <em>context</em> is <code>Steak</code> in this case. For cooking purposes it also maintains the previous state.</p>\n\n<pre><code>// Context\npublic class Steak\n{\n private ISteakState _current;\n public ISteakState Previous { get; private set; }\n public ISteakState Current\n {\n get =&gt; _current; set\n {\n Previous = _current;\n _current = value;\n }\n }\n}\n</code></pre>\n\n<p><code>SteakState</code> has a helper <code>Cook</code> method that for the sake of this demonstation prints the time it takes to cook the stake.</p>\n\n<pre><code>public abstract class SteakState : ISteakState\n{\n private int _maxTemperature;\n\n protected SteakState(int maxTemperature)\n {\n _maxTemperature = maxTemperature;\n }\n\n public int MaxTemperature =&gt; _maxTemperature;\n\n public abstract Task&lt;ISteakState&gt; Next(Steak context);\n\n protected async Task Cook(int minTemperature)\n {\n var cookDelay = (MaxTemperature - minTemperature);\n Console.WriteLine($\"Cooking for {cookDelay / 10} minutes.\");\n await Task.Delay(cookDelay * 100);\n Console.WriteLine($\"Steak is now {GetType().Name}\");\n }\n}\n</code></pre>\n\n<p>Each of the states sets it's max temperature and returns the next state. This is where you configure how a steak should be cooked. It also updates the <code>Current</code> state of the <code>Steak</code>.</p>\n\n<pre><code>public class Raw : SteakState\n{\n public Raw() : base(50) { }\n\n public override async Task&lt;ISteakState&gt; Next(Steak context)\n {\n Console.WriteLine($\"Starting cooking...\");\n await Cook(context.Previous?.MaxTemperature ?? 0);\n return context.Current = new Rare();\n }\n}\n\npublic class Rare : SteakState\n{\n public Rare() : base(105) { }\n\n public override async Task&lt;ISteakState&gt; Next(Steak context)\n {\n await Cook(context.Previous?.MaxTemperature ?? 0);\n return context.Current = new Medium();\n }\n}\n\npublic class Medium : SteakState\n{\n public Medium() : base(125) { }\n\n public override async Task&lt;ISteakState&gt; Next(Steak context)\n {\n await Cook(context.Previous?.MaxTemperature ?? 0);\n return context.Current = new WellDone();\n }\n}\n\npublic class WellDone : SteakState\n{\n public WellDone() : base(165) { }\n\n public override async Task&lt;ISteakState&gt; Next(Steak context)\n {\n await Cook(context.Previous?.MaxTemperature ?? 0);\n return default;\n }\n}\n</code></pre>\n\n<p>The last state doesn't return any state and the <code>while</code> loop stops there.</p>\n\n<hr>\n\n<p>This is not 100% clean-code as there are still some repetitions but it should be enough to show the idea.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-22T12:47:03.930", "Id": "421619", "Score": "1", "body": "Hey!! Thanks a lot for the time you took to explain and to expose, I really appreciate it!. Your answer is amazing, that was what I was looking for. Just to clarify, This was example was taken from a real case where we had to move from a finite state machine to states that vary depending upon ranges.\nThanks." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-23T08:13:54.643", "Id": "421765", "Score": "0", "body": "@FacundoLaRocca cool ;-) I find that this example is perfect to show the state-pattern. Much better than in many books or something completely abstract without absolutely any relation to the real world." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-21T09:47:07.330", "Id": "217823", "ParentId": "217774", "Score": "3" } } ]
{ "AcceptedAnswerId": "217823", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-20T13:33:26.700", "Id": "217774", "Score": "3", "Tags": [ "c#", "state" ], "Title": "Cooking steak with State Pattern and without IFs" }
217774
<p>I tried to build a "typed" property system in Java and this is what I came up with: first the class Properties that any class can use as an attribute (demo code in the end).</p> <pre><code>import java.util.HashMap; import java.util.Objects; public class Properties { private HashMap&lt;Type, Object&gt; properties = new HashMap&lt;&gt;(); public void add(Property property) { if(property != null) properties.put(property.getType(), property); } public void add(Type type, Object property) { Objects.requireNonNull(type, "null is not allowed as a type!"); Objects.requireNonNull(property, "cannot add null as a property!"); if(!property.getClass().isAssignableFrom(type.getPropertyClass())) { throw new IllegalArgumentException( "the property is of "+property.getClass()+", but subtype of "+type.getPropertyClass()+ " needed"); } properties.put(type, property); } public &lt;P&gt; P get(Type&lt;P&gt; type) { return get(type, type.getPropertyClass()); } public &lt;P&gt; P get(Type&lt;? super P&gt; type, Class&lt;P&gt; subProperty) { var property = properties.get(type); if(property == null) return null; if(!subProperty.isAssignableFrom(property.getClass())) { throw new ClassCastException( "the property is of "+property.getClass()+" which is not a subclass of "+subProperty); } return subProperty.cast(property); } public boolean has(Type type) { return properties.containsKey(type); } public &lt;P&gt; boolean has(Type&lt;? super P&gt; type, Class&lt;P&gt; subProperty) { var property = properties.get(type); return property!=null &amp;&amp; subProperty.isAssignableFrom(property.getClass()); } } </code></pre> <p>Type looks as follows:</p> <pre><code>public abstract class Type&lt;P&gt; { public final static Type&lt;PropertyA&gt; TYPE_A = new Type&lt;&gt;() { @Override public Class&lt;PropertyA&gt; getPropertyClass() { return PropertyA.class; } }; public final static Type&lt;PropertyB&gt; TYPE_B = new Type&lt;&gt;() { @Override public Class&lt;PropertyB&gt; getPropertyClass() { return PropertyB.class; } }; public final static Type&lt;String&gt; TYPE_STRING = new Type&lt;&gt;() { @Override public Class&lt;String&gt; getPropertyClass() { return String.class; } }; public abstract Class&lt;P&gt; getPropertyClass(); } </code></pre> <p>And we can have Properties like that:</p> <pre><code>public abstract class Property&lt;P extends Property&gt; { public abstract Type&lt;P&gt; getType(); } public class PropertyA extends Property&lt;PropertyA&gt; { @Override public Type&lt;PropertyA&gt; getType() { return Type.TYPE_A; } } public class PropertySubA extends PropertyA { } ... </code></pre> <p>Any Type can have a dedicated Property-class (which may or may not be subclassed again) or the Type can be just any class, but in the latter case the one-argument add(Property)-method cannot be used.</p> <p>I considered having <code>Type&lt;P extends Property&gt;</code> instead of just <code>Type&lt;P&gt;</code>, but then simple properties like <code>TYPE_STRING</code> would not be possible. Another idea is to omit the type altogether but use the class directly as key. However, that makes using instances of subclasses as properties much more complicated.</p> <p>The following code demonstrates what one can do with this:</p> <pre><code>public class Main { public static void main(String... args) { Properties properties = new Properties(); properties.add(new PropertyA()); properties.add(new PropertySubB()); PropertyA a = properties.get(Type.TYPE_A); // PropertySubA subA = properties.get(Type.TYPE_A, PropertySubA.class); // -&gt; exception as expected PropertyB b = properties.get(Type.TYPE_B); PropertySubB subB = properties.get(Type.TYPE_B, PropertySubB.class); PropertySubB subBCast = (PropertySubB) properties.get(Type.TYPE_B); // PropertyA niceTry = properties.get(Type.TYPE_B); // -&gt; does not compile // PropertyA niceTry2 = properties.get(Type.TYPE_B, PropertyA.class); // -&gt; does not compile either Object propA = new PropertyA(); properties.add(Type.TYPE_A, propA); // properties.add(Type.TYPE_B, propA); // -&gt; exception as expected properties.add(Type.TYPE_STRING, "Hello world!"); System.out.println(properties.get(Type.TYPE_STRING)); // -&gt; prints "Hello world!" } } </code></pre> <p>So we can avoid lots of casting with this system compared to using the HashMap directly. A cast and the one-argumetn get(...) can "replace" the two-argument get(...), but the latter has the advantage of compile-time checking.</p> <p>Thanks already for looking over my code, now a few questions:</p> <p>Is somthing wrong or unnecessarily complicated with my approach?</p> <p>Is a similar system used in some standard libraries?</p> <p>Am I missing some important functionality that a property-system should have? A first idea would be to allow multiple properties of the same type, but that is only a minor change.</p> <p>I know that my Type-class is somewhat close to an Enum, but to my knowledge an Enum cannot be used together with generics. Therefore <code>public abstract Class&lt;P&gt; getPropertyClass();</code> could only be declared as <code>public abstract Class&lt;?&gt; getPropertyClass();</code> in an Enum. As a consequence I would lose the one-parameter get(...) method and some of the compile-time checks. Is there any way to get around this problem and still use an enum?</p>
[]
[ { "body": "<p>This approach looks more complicated than it is worth for the compile time checking you get out of it. Not allowing multiple properties of the same type makes this more difficult to use. You could use a function like the one below to avoid casting every time you retrieve an element from a map with different types of objects. This assumes that you know which type the element should be.</p>\n\n<pre><code>/**\n * Get a cast value from a map.\n * @param &lt;T&gt; the type of key.\n * @param &lt;R&gt; the type of cast value. \n * @param key the key corresponding to a value.\n * @param map the containing the key value pairs.\n * @return the value cast to the expected type.\n */\n@SuppressWarnings(\"unchecked\")\npublic static &lt;T,R&gt; R get(T key, Map&lt;T,? super R&gt; map){\n Object value = map.get(key);\n return (R)value;\n}\n\n/**\n * Put a key value pair in a map.\n * @param &lt;T&gt; the type of key.\n * @param &lt;R&gt; the type of value.\n * @param key the key corresponding to a value.\n * @param value the value being mapped.\n * @param map the map.\n */\npublic static &lt;T,R&gt; void put(T key, R value, Map&lt;T,? super R&gt; map){\n map.put(key, value);\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-23T07:14:49.230", "Id": "421753", "Score": "0", "body": "Thank you for your answer! Sure, as the class-information is included in my type, I could just use explicit casts everywhere. Allowing multiple elements for each type is a relatively easy change. The problem I see with you alternative is that, while they have to be present for several reason, I mostly prefer to use the one-arguement get and add/put methods over the two-argument ones (i.e. omit the \"explicit\" cast)." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-23T04:31:55.803", "Id": "217922", "ParentId": "217776", "Score": "0" } }, { "body": "<p><em>Is somthing wrong or unnecessarily complicated with my approach?</em></p>\n\n<p>Requiring a dedicated class for each property is unnecessarily complicated.</p>\n\n<p><em>Is a similar system used in some standard libraries?</em></p>\n\n<p>No (standard library is a questionable term, the JRE doesn't come with such a featrue).</p>\n\n<p><em>Am I missing some important functionality that a property-system should have?</em></p>\n\n<p>Serialization.</p>\n\n<p>Since your properties require dedicated code for each property, what benefits does it offer over simply serializing a dedicated property-object into a DataOutputStream? The code requires a lot of JavaDoccing and is a lot more complicated than, for example, Commons Configuration.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-23T07:23:35.600", "Id": "421756", "Score": "0", "body": "Thank you for your answer! Maybe \"commonly used\" would have been a better term than \"standard\". Having separate classes for each type is unnecessary indeed, not making Type abstract and having several instances works just as well. And Property itself would be better as an interface. As limited as the \"concept idea\" is, I agree that it does not have many benefits. A type could, e.g., come with a limit of how many properties it allows. Commons Configurations is mainly for configuration files with primitive (and String) entries which is a different usecase, I think." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-23T07:57:25.103", "Id": "421762", "Score": "0", "body": "Restrictions should be defined in the class that is being instantiated, not in the property framework. If you want a typed configuration system, you should look at Spring Configuration." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-23T08:18:31.967", "Id": "421766", "Score": "0", "body": "Thanks, I'll have a look at how things are done there. I do not understand the first comment though: just because I have some Type-examples in my framework does not mean that any class can define their own Types to use? The Properties-object then should probably check that only allowed properties are added." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-23T06:18:38.070", "Id": "217927", "ParentId": "217776", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-20T14:00:54.343", "Id": "217776", "Score": "1", "Tags": [ "java", "generics", "properties" ], "Title": "Typed properties in Java" }
217776
<p>I am trying to implement a red black tree. The problem is that the code runs slowly and I wonder if I did something wrong or just did it too many times. I already checked and the problem is in the insertion part. Can you possibly review my code for performance and best coding practices?</p> <h3>Code</h3> <pre><code>typedef struct RBNode* RBNodePtr; typedef enum Color { RED, BLACK } Color; typedef struct RBNode { RBNodePtr child[2], parent; // child[0] is left, child[1] is right. int key, size; // size is the subtree size. Color color; } RBNode; RBNode NIL_T_NODE; RBNodePtr NIL_T = &amp;NIL_T_NODE; int flag = 0; int first_flag = 1; RBNodePtr Rotate(RBNodePtr* Root, RBNodePtr node, int side) { // rotate RB tree to &quot;side&quot; direction - // Just fixing all pointers and moving some nodes RBNodePtr y = node-&gt;child[!side]; int temp = y-&gt;size; y-&gt;size = node-&gt;size; node-&gt;size = node-&gt;size - temp + y-&gt;child[side]-&gt;size; node-&gt;child[!side] = y-&gt;child[side]; if (y-&gt;child[side] != NIL_T) y-&gt;child[side]-&gt;parent = node; y-&gt;parent = node-&gt;parent; if (node-&gt;parent == NIL_T) (*Root) = y; else if (node == node-&gt;parent-&gt;child[side]) node-&gt;parent-&gt;child[side] = y; else node-&gt;parent-&gt;child[!side] = y; y-&gt;child[side] = node; node-&gt;parent = y; return *Root; } void RB_fixup(RBNodePtr* Root, RBNodePtr node) { // fix insert violation according to the algorithms RBNodePtr temp; while (node-&gt;parent-&gt;color == RED) { if (node-&gt;parent == node-&gt;parent-&gt;parent-&gt;child[LEFT]) { temp = node-&gt;parent-&gt;parent-&gt;child[RIGHT]; if (temp-&gt;color == RED) { // case 1- side 1 node-&gt;parent-&gt;color = BLACK; temp-&gt;color = BLACK; node-&gt;parent-&gt;parent-&gt;color = RED; node = node-&gt;parent-&gt;parent; } else { if (node == node-&gt;parent-&gt;child[RIGHT]) { // case 2- side 1 node = node-&gt;parent; *Root = Rotate(Root, node, LEFT); } node-&gt;parent-&gt;color = BLACK; // case 3- side 1 node-&gt;parent-&gt;parent-&gt;color = RED; *Root = Rotate(Root, node-&gt;parent-&gt;parent, RIGHT); } } else { // all cases again just flips sides- same thing temp = node-&gt;parent-&gt;parent-&gt;child[LEFT]; if (temp-&gt;color == RED) { node-&gt;parent-&gt;color = BLACK; temp-&gt;color = BLACK; node-&gt;parent-&gt;parent-&gt;color = RED; node = node-&gt;parent-&gt;parent; } else { if (node == node-&gt;parent-&gt;child[LEFT]) { node = node-&gt;parent; *Root = Rotate(Root, node, RIGHT); } node-&gt;parent-&gt;color = BLACK; node-&gt;parent-&gt;parent-&gt;color = RED; *Root = Rotate(Root, node-&gt;parent-&gt;parent, LEFT); } } } (*Root)-&gt;color = BLACK; } RBNodePtr rb_insert(RBNodePtr tnode, int k) { // insert a new node z RBNodePtr z = new_rb_node(k); RBNodePtr y = NIL_T; // will be parent of z RBNodePtr x = tnode; RBNodePtr temp = rb_search(tnode, k); if (temp == NULL || temp == NIL_T) { // only insert if k isn't in tree while (x &amp;&amp; x != NIL_T) { // go down the tree and look for a spot to insert y = x; x-&gt;size++; if (z-&gt;key &lt; x-&gt;key) x = x-&gt;child[LEFT]; else x = x-&gt;child[RIGHT]; } z-&gt;parent = y; // update all pointers after the insertion if (y == NIL_T) tnode = z; else if (z-&gt;key &lt; y-&gt;key) y-&gt;child[LEFT] = z; else y-&gt;child[RIGHT] = z; RB_fixup(&amp;tnode, z); // fix violation } return tnode; } RBNodePtr new_rb_node(int k) { if (first_flag) { // initialize NIL_T for the first and only time NIL_T-&gt;color = BLACK; NIL_T-&gt;child[LEFT] = NULL; NIL_T-&gt;child[RIGHT] = NULL; NIL_T-&gt;parent = NULL; NIL_T-&gt;key = 0; NIL_T-&gt;size = 0; first_flag = 0; } // allocate space for new node RBNodePtr temp = (RBNodePtr)malloc(sizeof(RBNode)); if (!temp) { return NULL; } temp-&gt;size = 1; // initialize new node temp-&gt;key = k; temp-&gt;color = RED; temp-&gt;child[LEFT] = NIL_T; temp-&gt;child[RIGHT] = NIL_T; temp-&gt;parent = NIL_T; return temp; } RBNodePtr rb_search(RBNodePtr tnode, int k) { // search for node with key k while (tnode != NULL &amp;&amp; tnode != NIL_T &amp;&amp; tnode-&gt;key != k) { // if tree exist and didn't reach leaf or found the correct node if (tnode-&gt;key &gt; k) // go left or right in binary search tree tnode = tnode-&gt;child[LEFT]; else tnode = tnode-&gt;child[RIGHT]; } return tnode; // return the correct node/ NIL_T if couldn't found and NULL // if tree doesn't exist } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-20T14:13:02.973", "Id": "421384", "Score": "0", "body": "There are several other people on this site who have implemented a red black tree in C. You could take their implementations and compare it with yours, to get some more ideas. Just search for \"red black tree c\"." } ]
[ { "body": "<p>Why does <code>Rotate</code> return the modified root node as both a pointer parameter, and return it by value? It should do one or the other. Everywhere you call that function you assign the returned node to <code>Root</code>, which is also passed in as the first parameter.</p>\n\n<p><code>RB_fixup</code> has a lot of duplicated code. You can eliminate that by setting a variable to specify if you're working with the LEFT or RIGHT branch.</p>\n\n<p><code>rb_insert</code> leaks memory if a value is already in the tree, since it would allocate a node, not store the pointer anywhere, and not free it up. It would be better to not allocate <code>z</code> until you know you're going to use it. You also call <code>rb_search</code> to see if the node exists, then essentially do the same thing again (while increasing the counts). These could be combined into only one walk down the tree, and another back up to increase the counts if the node is added.</p>\n\n<p>There's also a little inconsistency there, as you use a less than comparison in <code>rb_insert</code> but a greater than comparison in <code>rb_search</code>. This can be a bit confusing.</p>\n\n<p>I don't see why you're using <code>NIL_T</code>. Everywhere you're using it will work just as well using <code>NULL</code>. You compare node pointers to see if they're pointing to this special node, but you never dereference it.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-21T08:06:04.913", "Id": "421452", "Score": "0", "body": "Thank you for the comments, I will try to change most of it. As for the NIL_T, it is defined to have color black(unlike null which isn't even a node) and the main algorithms check for colors and assume NIL_T has a black color. One more thing, do you happen to have an idea why my code is running slowly besides what you have written? Thank you" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-20T22:11:21.243", "Id": "217798", "ParentId": "217777", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-20T14:05:06.910", "Id": "217777", "Score": "1", "Tags": [ "performance", "algorithm", "c", "tree" ], "Title": "Slow insertion into a Red Black tree" }
217777
<p>Assume that the project has the following files, where the first files is dependent on the files under it's category in the unordered list:</p> <ul> <li>main.c <ul> <li>global.h (contains enumerations and #define macros)</li> <li>sdlevent.h (generic header file) <ul> <li>sdlevent.c (contains implementations of sdlevent.h)</li> </ul></li> <li>sdlshape.h (generic header file) <ul> <li>sdlshape.c (contains implementations of sdlshape.h)</li> </ul></li> </ul></li> </ul> <p>Now, I have the following makefile:</p> <pre><code>CC = gcc CFLAGS = -g -w -std=c99 LIBS = -lSDL2 -lSDL2_image -lSDL2_ttf SRCS = main.c sdlshape.c sdlevent.c OBJS = $(SRCS:.c=.o) EXE = play all: $(EXE) .c.o: $(CC) -c $(CFLAGS) $&lt; $(EXE): $(OBJS) $(CC) -o $(EXE) $(OBJS) $(LIBS) $(OBJS): global.h sdlevent.h sdlshape.h run : all ./$(EXE) clean: rm -f *.o *~ $(EXE) </code></pre> <blockquote> <p>The target <code>$(EXE)</code> is dependent on the target <code>.c.o</code>. Do I absolutely need to define the target <code>$(EXE)</code> <em>after</em> the target <code>.c.o</code>?</p> </blockquote> <p>I don't think so, because even though the target <code>$(EXE)</code> is dependent on the target <code>$(OBJS)</code>, the target <code>($EXE)</code> is declared <em>before</em> <code>$(OBJS)</code>.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-20T16:46:26.590", "Id": "421395", "Score": "1", "body": "I don't like the idea behind 'in the future if I divide the header files into their respective .c files'. The .h files are generally for publishing declarations of objects - global variables and routines (and types, constants etc.), .c files are for their implementation (initializers and code, respectively). What you said implies you have some code in .h file. That's rather bad, because the implementation will appear in every module which includes such .h file. It doesn't seem to hurt as long as you have just one .c module, but better fix it asap." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-20T17:19:28.230", "Id": "421401", "Score": "0", "body": "@CiaPan, Could you explain \"the implementation will appear in every module which includes such .h file\"? Because if the module `include`'s the header file, then it checks with `ifndef` if the header file was included before anyway. I don't see any way the code can occur more than once. Maybe I'm not understanding the idea of module. Could you talk in respect of pure C, please and thanks?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-20T17:23:49.323", "Id": "421406", "Score": "0", "body": "@klaus One point of dividing stuff up is to only recompile what's needed. In the example in my answer, if you do a change to `bar.c` you will only need to generate a new `bar.o` and then link it to a final executable. The files `main.o` and `foo.o` can be reused without recompilation." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-20T17:24:01.263", "Id": "421407", "Score": "1", "body": "regarding: `CFLAGS = -g -w -std=c99` Why are you turning OFF all the warnings with the `-w`? Suggest using: `CFLAGS = -ggdb -Wall -Wextra -Wconversion -pedantic -std=c99` And c99 is a (nearly) 20 year old version of C. Suggest using a recent version like: `-std=c11`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-20T17:26:09.680", "Id": "421408", "Score": "0", "body": "@user3629249, thanks. I know I'm using old version of C and turning off warnings. I'm not building useful stuff. This is all for learning purposes. And the c99 standard forces you to know a lot of intricate stuff." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-25T10:36:01.320", "Id": "423168", "Score": "0", "body": "@klaus: The warnings can be very helpful when trying to learn." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-26T20:03:57.563", "Id": "423426", "Score": "0", "body": "\"And the c99 standard forces you to know a lot of intricate stuff.\" Yet you silence all warnings. All those compiler warnings exist for a reason." } ]
[ { "body": "<blockquote>\n <p>I have not divided up the header files into their .h and .c files because they are very small header files. </p>\n</blockquote>\n\n<p>I would advice against this. Dividing into header and source files is just something you do. If something deserves an own source file, it also deserves an own header file. If nothing else, future readers of your code will expect .h files to only contain declarations. If you really don't want to split them up, then include the .c files instead. That's not good, but at least you're not hiding what you're doing.</p>\n\n<p>Also, I don't really see the need to manually write dependencies. If your project is big, look into CMake or something. If it is small, use a generic Makefile. Here is a small example that basically contains everything you'll ever need before it's time to move on to CMake:</p>\n\n<pre><code># Configuration\n\nEXE = play\nCFLAGS = -g -Wall -Wextra -std=c11\nLDLIBS = -lm\nLDFLAGS =\n\n# Don't touch anything below\n\n# Every .c is a source file (dough)\nSRC = $(wildcard *.c)\n# Every source file should be compiled to an object file\nOBJ = $(SRC:.c=.o)\n# Every object file should have a dependency file\nDEP = $(OBJ:.o=.d)\n\n# Link the exe from the object files\n$(EXE): $(OBJ)\n $(CC) $(LDFLAGS) $^ -o $@ $(LDLIBS)\n\n# Generate dependencies for the object files\n%.o: %.c\n $(CC) -MMD -MP -c $&lt; -o $@\n\n# https://stackoverflow.com/q/2145590/6699433\n.PHONY: clean\n\nclean:\n $(RM) $(OBJ) $(DEP) $(EXE) *~\n\n# Include the generated dependencies\n-include $(DEP)\n</code></pre>\n\n<p>Note that you don't need to pass <code>$(CFLAGS)</code> to the <code>CC</code> commands. It's done automatically.</p>\n\n<p>I used the above Makefile on this:</p>\n\n<pre><code>$ cat *.c *.h\n/* bar.c */\n\n#include \"bar.h\"\n#include &lt;math.h&gt;\n\nint bar(int a, int b) { return a*pow(b,3); }\n/* foo.c */\n\n#include \"foo.h\"\n#include \"bar.h\"\n\nint foo(int a, int b) { return a+bar(a,b); }\n/* main.c */\n\n#include \"foo.h\"\n\nint main() { foo(1,2); }\n/* bar.h */\n\n#ifndef __BAR_H__\n#define __BAR_H__\n\nint bar(int a, int b);\n\n#endif\n/* foo.h */\n\n#ifndef __FOO_H__\n#define __FOO_H__\n\nint foo(int, int);\n\n#endif\n</code></pre>\n\n<p>I sacrificed a bit of readability to keep number of lines down. After running <code>make</code> I have a couple of .d files.</p>\n\n<pre><code>$ cat *.d\nbar.o: bar.c bar.h\n\nbar.h:\nfoo.o: foo.c foo.h bar.h\n\nfoo.h:\n\nbar.h:\nmain.o: main.c foo.h\n\nfoo.h:\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-20T17:16:03.907", "Id": "421400", "Score": "0", "body": "I updated my question. Please check that." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-20T17:20:05.300", "Id": "421402", "Score": "0", "body": "@klaus In this case it was ok, but please don't change the question when someone have answered it. It might invalidate an answer. You're not supposed to do continuous updates until you are satisfied. If needed, use the answers you've got and post a new question instead." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-20T17:21:40.487", "Id": "421405", "Score": "0", "body": "But the answer didn't associate with my question at all. Instead it suggested me another tool, which I thank you for anyway, and it just provided me with generic makefile instead of answering my question which was for learning purpose. So, the answer was invalid anyway." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-20T17:27:40.563", "Id": "421409", "Score": "0", "body": "@klaus Then I misunderstood you. Sorry about that. In that case I suggest you undelete your question on SO, since it is more suitable there. You can leave this question open since it does make sense here." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-20T17:30:52.790", "Id": "421410", "Score": "0", "body": "regarding: `-include $(DEP)` This will result in the dependency files being rebuilt even if the parameter passed to `make` is `clean` suggest: `ifneq \"$(MAKECMDGOALS)\" \"clean\"\n-include $(DEP)\nendif`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-20T17:31:52.580", "Id": "421412", "Score": "0", "body": "I reopened the question on SO. Thanks for the help." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-20T17:33:22.427", "Id": "421413", "Score": "0", "body": "@user3629249 They don't get rebuilt. I just tested that." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-20T18:15:52.377", "Id": "421415", "Score": "0", "body": "My experience is they do get rebuilt. What OS, version of `make`, etc are you running?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-20T18:17:19.587", "Id": "421416", "Score": "0", "body": "I'm running debian. make version is 4.2.1" } ], "meta_data": { "CommentCount": "9", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-20T16:58:49.660", "Id": "217787", "ParentId": "217781", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-20T15:43:33.667", "Id": "217781", "Score": "1", "Tags": [ "c", "makefile", "make" ], "Title": "Understand the dependency levels of makefiles" }
217781
<p>I'm working on a project (studying) and I have a lot of time for proof of concepts and write something from scratch.</p> <p>Basically I'm creating an HTTP server (simple, but not too simple) in C++ using sockets and multi-threading.</p> <p>There are two topics that I'm concerned about: the design pattern of my code structure and the efficiency of my thread implementation. Obs: I'm a little worried about C++ best practices, since I'm diving too fast into C++ (am I abusing of std items, since this requires a low-level implementation).</p> <p>Server is the main file, that calls Routes, Request and Response. Request and Response contains Struct (that contains Status Code). And Routes contains Request and Response.</p> <p><a href="https://i.stack.imgur.com/Qfhjh.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Qfhjh.png" alt=""></a></p> <p><strong>IMPORTANT</strong>: I'm using <a href="https://github.com/nlohmann/json" rel="nofollow noreferrer">nlohmann/json</a> and <a href="https://github.com/j-ulrich/http-status-codes-cpp" rel="nofollow noreferrer">j-ulrich status-codes</a>.</p> <h3>Server (Accepting Sockets and Multi-threading):</h3> <pre><code>#pragma once #include &lt;unistd.h&gt; #include &lt;stdio.h&gt; #include &lt;sys/socket.h&gt; #include &lt;stdlib.h&gt; #include &lt;netinet/in.h&gt; #include &lt;string.h&gt; #include &lt;iostream&gt; #include &lt;unordered_map&gt; #include &lt;thread&gt; #include &lt;mutex&gt; #include &lt;condition_variable&gt; #include "Server/Request.h" #include "Server/Response.h" #include "Server/Struct.h" #include "Server/Routes.h" #include "Tools/Logger.h" class Server { public: Server(unsigned int port, unsigned int max_connections = 64, unsigned int thread_count = 5); ~Server(); bool setRoute(std::string path, Struct::Methods method, void (*callback)(Request*, Response*)); bool doListen(); bool doStop(); private: unsigned int _port; unsigned int _max_connections; unsigned int _thread_count; std::mutex _mutex; std::condition_variable _condition; bool _signal; std::vector&lt;unsigned int&gt; _queue; std::thread* _thread_consume; std::thread* _thread_process; Routes* _routes; int _socket; struct sockaddr_in _address; bool _listen; bool _doStop(); bool _doCreateSocket(int&amp; socket_in); bool _doBindSocket(int file_descriptor); void _doConsumeSocket(); void _doProcessSocket(int id); bool _doProcessRequest(Request* request, Response* response); }; </code></pre> <hr> <pre><code>#include "Server/Server.h" Server::Server(unsigned int port, unsigned int max_connections, unsigned int thread_count) { if (port &gt; 65535) { Logger::doSendMessage(Logger::TYPES::ERROR, "[Port must be something between 0 and 65535 on Server::Constructor."); } if (max_connections &lt; 1) { Logger::doSendMessage(Logger::TYPES::ERROR, "Max connections can't be lower than 1 on Server::Constructor."); } _port = port; _max_connections = max_connections; _thread_count = thread_count; _routes = new Routes(); int status = _doCreateSocket(_socket); if (!status) { Logger::doSendMessage(Logger::TYPES::ERROR, "Failed to create socket on Server::Constructor."); } if (!_doBindSocket(_socket)) { Logger::doSendMessage(Logger::TYPES::ERROR, "Failed to bind socket on Server::Constructor."); }; _signal = false; _listen = false; } Server::~Server() { _doStop(); shutdown(_socket, SHUT_RD); close(_socket); try { _thread_consume-&gt;join(); for (size_t i = 0; i &lt; _thread_count; i++) { _thread_process[i].join(); } } catch (...) {} delete _thread_consume; delete[] _thread_process; delete _routes; } bool Server::setRoute(std::string path, Struct::Methods method, void (*callback)(Request*, Response*)) { return _routes-&gt;setRoute(path, method, callback); } bool Server::doListen() { if (_listen) return false; int status; status = listen(_socket, _max_connections); if (status &lt; 0) return false; Logger::doSendMessage(Logger::TYPES::INFO, "Server running with success at port " + std::to_string(_port) + "."); _listen = true; _thread_consume = new std::thread(&amp;Server::_doConsumeSocket, this); _thread_process = new std::thread[_thread_count]; for (size_t i = 0; i &lt; _thread_count; i++) { _thread_process[i] = std::thread(&amp;Server::_doProcessSocket, this, i); } return true; } bool Server::doStop() { return _doStop(); } bool Server::_doStop() { if (!_listen) return false; { std::lock_guard&lt;std::mutex&gt; lock(_mutex); _listen = false; } _condition.notify_one(); return true; } bool Server::_doCreateSocket(int&amp; socket_in) { int file_descriptor = socket(AF_INET, SOCK_STREAM, 0); if (file_descriptor == 0) return false; int error; int opt = 1; error = setsockopt(file_descriptor, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT, &amp;opt, sizeof(opt)); if (error) return false; socket_in = file_descriptor; return true; } bool Server::_doBindSocket(int file_descriptor) { if (!file_descriptor) return false; _address.sin_family = AF_INET; _address.sin_addr.s_addr = INADDR_ANY; _address.sin_port = htons(_port); int status; status = bind(file_descriptor, (struct sockaddr*) &amp;_address, sizeof(_address)); if (status &lt; 0) return false; return true; } void Server::_doConsumeSocket() { int socket_in; int address_size = sizeof(_address); while (_listen) { socket_in = accept(_socket, (struct sockaddr*) &amp;_address, (socklen_t*) &amp;address_size); if (socket_in &lt; 0) continue; { std::lock_guard&lt;std::mutex&gt; lock(_mutex); _queue.push_back(socket_in); _signal = true; } _condition.notify_one(); } } void Server::_doProcessSocket(int id) { while (_listen) { int queue_size = 0; { std::unique_lock&lt;std::mutex&gt; lock(_mutex); _condition.wait(lock, [this] { if (this-&gt;_signal) return true; if (!this-&gt;_listen &amp;&amp; !this-&gt;_queue.size()) return true; return false; } ); queue_size = _queue.size(); } if (!queue_size) { { std::lock_guard&lt;std::mutex&gt; lock(_mutex); _signal = false; } _condition.notify_one(); continue; } int socket_in = 0; { std::lock_guard&lt;std::mutex&gt; lock(_mutex); socket_in = _queue[0]; _queue.erase(_queue.begin()); } Request* request = new Request(socket_in); Response* response = new Response(socket_in); int status = _doProcessRequest(request, response); delete request; delete response; close(socket_in); } } bool Server::_doProcessRequest(Request* request, Response* response) { if (!request-&gt;isValid()) { response-&gt;doSendError(HttpStatus::Code::BadRequest, "Invalid request."); return false; } std::string path = request-&gt;getPath(); Struct::Methods method = request-&gt;getMethod(); Routes::Route route; if (!(_routes-&gt;getRoute(path, method, route) &amp;&amp; route.isValid())) { response-&gt;doSendError(HttpStatus::Code::Forbidden, "Path invalid/not found."); return false; } if (route.method != method) { response-&gt;doSendError(HttpStatus::Code::MethodNotAllowed, "Method invalid/not found."); return false; } void (*callback)(Request*, Response*) = route.callback; callback(request, response); if (!response-&gt;isSent()) { response-&gt;doSendError(HttpStatus::Code::ServiceUnavailable, "Resource was not found or can't respond now."); } return true; } </code></pre> <h3>Request (parsing) and Response (sending)</h3> <p><strong>Request</strong></p> <pre><code>#pragma once #include &lt;unistd.h&gt; #include &lt;string.h&gt; #include &lt;iostream&gt; #include &lt;string&gt; #include &lt;vector&gt; #include &lt;unordered_map&gt; #include &lt;regex&gt; #include &lt;json.hpp&gt; #include "Server/Struct.h" using json = nlohmann::json; class Request { public: Request(int socket, unsigned int buffer_size = 1024); ~Request(); bool isValid(); std::string getPath() {return _attributes.path;} Struct::Methods getMethod() {return _attributes.method;} std::unordered_map&lt;std::string, std::string&gt; getHeaders() {return _attributes.headers;} std::string getHeader(std::string header) {return _attributes.headers[header];} json getBody() {return _attributes.body;} private: int _socket; unsigned int _buffer_size; std::string _data; Struct::Attributes _attributes; bool _status; std::string _doReceiveData(int sock_in); bool _doParseData(std::string data, Struct::Attributes&amp; attributes); std::vector&lt;std::string&gt; _doSplitText(std::string text, std::string delimiter); std::vector&lt;std::string&gt; _doSplitText(std::string text, std::string delimiter, int lock); }; </code></pre> <hr> <pre><code>Request::Request(int socket, unsigned int buffer_size) { _socket = socket; _buffer_size = buffer_size; _status = false; _data = _doReceiveData(_socket); if (!_data.length()) return; bool result; result = _doParseData(_data, _attributes); if (!result) return; if (!_attributes.isValidRequest()) return; _status = true; } Request::~Request() { } bool Request::isValid() { return _status; } std::string Request::_doReceiveData(int sock_in) { char* buffer = new char[_buffer_size]; memset(buffer, '\0', _buffer_size); read(sock_in, buffer, _buffer_size); std::string data; data.assign(buffer); delete[] buffer; return data; } bool Request::_doParseData(std::string data, Struct::Attributes&amp; attributes) { std::string delimiter = "\r\n"; std::vector&lt;std::string&gt; rows = _doSplitText(data, delimiter); if (!rows.size()) return false; std::string header = rows[0]; rows.erase(rows.begin()); if (!header.length()) return false; std::vector&lt;std::string&gt; parsed_header = _doSplitText(header, std::string(" ")); if (parsed_header.size() &lt; 2) return false; Struct::Methods method = Struct::doParseHttpMethod(parsed_header[0]); if (method == Struct::Methods::NONE) return false; std::string path = parsed_header[1]; std::unordered_map&lt;std::string, std::string&gt; headers; for (size_t i = 0; i &lt; rows.size(); i++) { std::string row = rows[i]; delimiter = ":"; std::vector&lt;std::string&gt; splited = _doSplitText(row, delimiter, true); if (splited.size() != 2) continue; headers[splited[0]] = splited[1]; } _attributes.method = method; _attributes.path = path; _attributes.headers = headers; std::string content_length = headers["Content-Length"]; int content_size = 0; if (content_size = atoi(content_length.c_str())) { std::string body = data.substr(data.length() - content_size, data.length()); json parsed_body = json::parse(body, nullptr, false); if (parsed_body != NULL &amp;&amp; !parsed_body.is_discarded()) _attributes.body = parsed_body; } return true; } std::vector&lt;std::string&gt; Request::_doSplitText(std::string text, std::string delimiter) { std::vector&lt;std::string&gt; result; int delimiter_length = delimiter.length(); std::string block; std::string region; int index = 0; for (size_t i = 0; i &lt; text.length(); i++) { block = text.substr(i, delimiter_length); if (block.length() != delimiter_length) continue; if (block == delimiter) { region = text.substr(index, i - index); result.push_back(region); index = i + delimiter_length; } } return result; } std::vector&lt;std::string&gt; Request::_doSplitText(std::string text, std::string delimiter, int lock) { ... } </code></pre> <p><strong>Response</strong></p> <pre><code>#pragma once #include &lt;unistd.h&gt; #include &lt;iostream&gt; #include &lt;string&gt; #include &lt;unordered_map&gt; #include "Server/Struct.h" class Response { public: Response(int socket_in); ~Response(); bool isSent() {return _sent;} void setCode(HttpStatus::Code code) {_attributes.code = code;} void setHeader(std::string key, std::string value) {_attributes.headers[key] = value;} void setBody(json body) {_attributes.body = body;} void doClearHeaders() {_attributes.headers.clear();} void doClearBody() {_attributes.body = json::value_t::object;} bool doSendSuccess(); bool doSendError(HttpStatus::Code code, const std::string&amp; message); private: int _socket; bool _sent; Struct::Attributes _attributes; bool _doSendPayload(); bool _doCreatePayload(std::string&amp; payload); }; </code></pre> <hr> <pre><code>#include "Response.h" Response::Response(int socket_in) { _socket = socket_in; _sent = false; } Response::~Response() { } bool Response::doSendSuccess() { setCode(HttpStatus::Code::OK); setHeader("Connection", "Closed"); return _doSendPayload(); } bool Response::doSendError(HttpStatus::Code code, const std::string&amp; message) { setCode(code); doClearHeaders(); doClearBody(); setHeader("Connection", "Closed"); json body; body["error"] = {}; body["error"]["code"] = code; body["error"]["message"] = message; setBody(body); return _doSendPayload(); } bool Response::_doSendPayload() { if (_sent) return false; int status; setHeader("Server", "Dark"); setHeader("Content-Type", "application/json"); std::string payload; status = _doCreatePayload(payload); if (!status) return false; status = write(_socket, payload.c_str(), payload.size()); if (status &lt; 1) return false; _sent = true; return true; } bool Response::_doCreatePayload(std::string&amp; payload) { std::string current_payload; std::string data = _attributes.body.dump(4); int data_length = data.size(); if (data_length) { _attributes.headers["Content-Length"] = std::to_string(data_length); } current_payload += _attributes.version + " " + std::to_string((int) _attributes.code) + " " + HttpStatus::getReasonPhrase(_attributes.code) + "\r\n"; std::unordered_map&lt;std::string, std::string&gt;::iterator iterator; for (iterator = _attributes.headers.begin(); iterator != _attributes.headers.end(); iterator++){ std::string key = iterator-&gt;first; std::string value = iterator-&gt;second; current_payload += key + ": " + value + "\r\n"; } if (data_length) current_payload += "\r\n" + data + "\r\n\r\n"; payload = current_payload; return true; } </code></pre> <h3>Routes</h3> <pre><code>#pragma once #include &lt;iostream&gt; #include &lt;string&gt; #include &lt;vector&gt; #include "Server/Request.h" #include "Server/Response.h" class Routes { public: Routes(); ~Routes(); struct Route { std::string path; Struct::Methods method; void (*callback)(Request*, Response*); bool isValid() { if (!path.length()) return false; if (method &lt; Struct::Methods::FIRST || method &gt; Struct::Methods::LAST) return false; if (callback == nullptr) return false; return true; } }; bool setRoute(std::string path, Struct::Methods method, void (*callback)(Request*, Response*)); bool getRoute(std::string path, Struct::Methods method, Route&amp; route); private: std::vector&lt;Route&gt; _routes; int _getRouteIndex(std::string path, Struct::Methods method); }; </code></pre> <hr> <pre><code>#include "Routes.h" Routes::Routes() { } Routes::~Routes() { } bool Routes::setRoute(std::string path, Struct::Methods method, void (*callback)(Request*, Response*)) { if (path.length() &lt; 1) return false; if (_getRouteIndex(path, method) &gt;= 0) return false; if (method &lt; Struct::Methods::FIRST || method &gt; Struct::Methods::LAST) return false; if (callback == nullptr) return false; Routes::Route route = {path, method, callback}; _routes.push_back(route); return true; } bool Routes::getRoute(std::string path, Struct::Methods method, Routes::Route&amp; route) { int index = _getRouteIndex(path, method); if (index &lt; 0) return false; route = _routes[index]; return true; } int Routes::_getRouteIndex(std::string path, Struct::Methods method) { for (size_t i = 0; i &lt; _routes.size(); i++) { Route* route = &amp;_routes[i]; if (route-&gt;path == path &amp;&amp; route-&gt;method == method) { return i; } } return -1; } </code></pre> <h3>Struct and StatusCode</h3> <p><strong>StatusCode</strong></p> <p><a href="https://github.com/j-ulrich/http-status-codes-cpp" rel="nofollow noreferrer">http-status-codes-cpp</a></p> <p><strong>Struct</strong></p> <pre><code>#pragma once #include &lt;json.hpp&gt; #include "Server/StatusCode.h" using json = nlohmann::json; class Struct { public: enum class Methods { NONE = 0, GET = 1, POST = 2, FIRST = GET, LAST = POST }; struct Attributes { const std::string version = "HTTP/1.1"; std::string path; Methods method; HttpStatus::Code code; std::unordered_map&lt;std::string, std::string&gt; headers; json body; Attributes() { code = HttpStatus::Code::InternalServerError; body = json::value_t::object; } bool isValidRequest() { if (!path.length()) return false; if (method &lt; Methods::FIRST || method &gt; Methods::LAST) return false; if (!headers.size()) return false; return true; } bool isValidResponse() { if (!headers.size()) return false; return true; } }; static Methods doParseHttpMethod(std::string value) { Methods target = Methods::NONE; if (value == "GET") target = Methods::GET; if (value == "POST") target = Methods::POST; return target; } private: }; </code></pre> <h2>Main (usage):</h2> <pre><code>#include "Server/Server.h" void exec(Request* request, Response* response) { json body; body["foo"] = 123; body["bar"] = true; response-&gt;setBody(body); response-&gt;doSendSuccess(); } int main(int argc, char* argv[]) { Server* server = new Server(5000); server-&gt;setRoute("/getStatus", Struct::Methods::GET, exec); server-&gt;setRoute("/postStatus", Struct::Methods::POST, exec); server-&gt;doListen(); // let threads live for some time before they eternaly be gone /* actually I'm stuck with this sleep, I don't know how to hold this until caller call doStop() without using while and consuming process power */ sleep(30); delete server; return 1; } </code></pre> <h3>Compile</h3> <hr> <pre><code>#!/bin/bash sudo g++ \ main.cpp \ -I lib \ ./lib/json.hpp \ -I src \ ./src/Server/Server.h ./src/Server/Server.cpp \ ./src/Server/Request.h ./src/Server/Request.cpp \ ./src/Server/Response.h ./src/Server/Response.cpp \ ./src/Server/Routes.h ./src/Server/Routes.cpp \ ./src/Server/Struct.h \ ./src/Server/StatusCode.h \ ./src/Tools/Logger.h \ -pthread \ -o main.exe sudo chmod +x main.exe sudo ./main.exe </code></pre> <p>Basically I'm mirroring NodeJS express API Usage: <code>server.setRoute(path, route, callback);</code></p> <p>So, what can be done to improve my code in terms of optimization and efficiency?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-22T00:23:23.347", "Id": "421557", "Score": "1", "body": "Why `sudo g++` instead of a simple `g++`? Why `chmod` at all? And where is the obligatory `-Werror -Wall -Wextra -O2`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-22T00:41:06.550", "Id": "421561", "Score": "0", "body": "@RolandIllig I don't know man, should I use those things? I always use sudo to avoid those anoying errors, and chmod is to make file executable (this is the way that I learnt -- all from google, including english and code, I don't take classes, so probably I don't know many things)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-22T00:50:18.093", "Id": "421563", "Score": "0", "body": "@RolandIllig you can edit if you want, probably I won't know the best approach." } ]
[ { "body": "<p><em>Note: This review focuses on the use of C++, rather than the functionality.</em></p>\n\n<hr>\n\n<p>Naming:</p>\n\n<ul>\n<li>IMHO, the use of \"do\" at the start of function names is unnecessary and makes the code harder to read. The names would be fine without it (e.g. <code>sendSuccess</code>, <code>sendError</code>, <code>createSocket</code> all make perfect sense).</li>\n</ul>\n\n<hr>\n\n<p>Server:</p>\n\n<ul>\n<li><p>If the port must always fit in a 16 bit unsigned int, we can use <code>std::uint16_t</code> (from the <code>&lt;cstdint&gt;</code> header) instead of an <code>unsigned int</code>.</p></li>\n<li><p>The <code>new</code> keyword should almost never be used in modern C++. If we need to create it on the heap, <code>_routes</code> should be a <code>std::unique_ptr</code> (from <code>&lt;memory&gt;</code>), which will be cleaned up automatically for us. In this case it looks like the variable could just be created on the stack (i.e. declared as <code>Routes _routes;</code>).</p></li>\n<li><p><code>_doCreateSocket()</code> returns a bool, but the <code>Server</code> constructor uses an <code>int</code> to hold the return type.</p></li>\n<li><p>It's better to use the constructor's member initializer list to initialize variables where possible (it's neater, and we don't have to worry about initializing objects twice), e.g.:</p>\n\n<pre><code>Server::Server(std::uint16_t port, unsigned int max_connections, unsigned int thread_count):\n _port(port),\n _max_connections(max_connections),\n _thread_count(thread_count),\n _signal(false),\n _thread_consume(nullptr),\n _thread_process(nullptr),\n _routes(nullptr),\n _socket(-1), // or something\n _listen(false)\n{\n if (max_connections &lt; 1) {\n Logger::doSendMessage(Logger::TYPES::ERROR, \"Max connections can't be lower than 1 on Server::Constructor.\");\n }\n\n if (!_doCreateSocket(_socket)) {\n Logger::doSendMessage(Logger::TYPES::ERROR, \"Failed to create socket on Server::Constructor.\");\n }\n\n if (!_doBindSocket(_socket)) {\n Logger::doSendMessage(Logger::TYPES::ERROR, \"Failed to bind socket on Server::Constructor.\");\n }\n}\n</code></pre></li>\n<li><p>Note that plain data variables (e.g. pointers, ints) are left uninitialized (and may contain any random value) unless we explicitly initialize them. It's safest to always set them to a known value in the constructor.</p></li>\n<li><p><code>_thread_consume</code> can also be created on the stack (the <code>std::thread</code> default constructor doesn't launch a new thread), and <code>_thread_process</code> can be a <code>std::vector&lt;std::thread&gt;</code>. This saves us from having to do any manual memory management.</p></li>\n<li><p>Prefer to use <code>std::function</code> from the <code>&lt;functional&gt;</code> header, instead of raw function pointers. (e.g. <code>std::function&lt;void(Request*, Response*)&gt;</code>).</p></li>\n<li><p>The <code>request</code> and <code>response</code> variables in <code>Server::_doProcessSocket</code> should be created on the stack. We can still pass them by pointers if necessary by taking their addresses (<code>_doProcessRequest(&amp;request, &amp;response)</code>), or (better) we could pass them by reference.</p></li>\n<li><p>The status code returned by <code>Server::_doProcessRequest()</code> isn't used.</p></li>\n<li><p>In <code>Server::_doProcessRequest()</code>, the <code>if (route.method != method)</code> check is unnecessary, since we used the <code>method</code> while finding the route.</p></li>\n<li><p>The forwarding from <code>doStop</code> to <code>_doStop</code> is unnecessary.</p></li>\n<li><p>This class is doing several things. It manages a thread pool, as well as doing raw socket stuff. We could definitely split the socket functionality into a separate class.</p></li>\n</ul>\n\n<hr>\n\n<p>Request:</p>\n\n<ul>\n<li><p>Member functions that don't alter the member variables of a class should be declared <code>const</code>, e.g.: <code>bool isValid() const;</code>. This means we can make proper use of <code>const</code> and <code>const&amp;</code> variables, allowing the compiler to perform better optimisations, and preventing programmer error.</p></li>\n<li><p>The getter functions in this class all return by value. This probably results in some unnecessary copies being made, which may be expensive where the objects require allocation of memory (e.g. copying the <code>unordered_map</code> / <code>string</code>s). It might be better to return by <code>const&amp;</code> instead, e.g.: <code>std::unordered_map&lt;std::string, std::string&gt; const&amp; getHeaders();</code>. This still prevents the caller from altering referenced variable, but allows them to decide whether to copy it, copy part of it, or not copy it at all.</p></li>\n<li><p>In <code>Request::_doReceiveData</code>, we can use a <code>std::vector&lt;char&gt;</code> for the buffer rather than doing manual memory management. (It's guaranteed to provide contiguous memory, which we can access using the <code>.data()</code> member function).</p></li>\n</ul>\n\n<hr>\n\n<p>Routes:</p>\n\n<ul>\n<li><p><code>Routes::setRoute</code> should probably use the <code>Route::isValid</code> method, rather than duplicating the checks.</p></li>\n<li><p>There's some unnecessary <code>string</code> copies in <code>getRoute</code>. We should pass the variable as a reference: <code>const std::string&amp; path</code> instead.</p></li>\n<li><p>Using iterators and the standard library search algorithms is more idiomatic C++ than indices. e.g.:</p>\n\n<pre><code>auto route = std::find_if(_routes.begin(), routes.end(), \n [] (Route const&amp; route) { return (route.path == path) &amp;&amp; (route-&gt;method == method); });\n\nif (route == routes.end()) // route not found!\n</code></pre></li>\n<li><p>(Unless it's reused elsewhere, I'd be inclined to remove the <code>Routes</code> class in favor of a <code>std::vector&lt;Route&gt; _routes;</code> in the <code>Server</code> class.)</p></li>\n</ul>\n\n<hr>\n\n<p>Main:</p>\n\n<ul>\n<li><p>(Use <code>std::this_thread::sleep_for</code> for a portable sleep function.)</p></li>\n<li><p>I think <a href=\"https://en.cppreference.com/w/cpp/thread/condition_variable/wait\" rel=\"noreferrer\"><code>std::condition_variable::wait()</code></a> may be what you're looking for.</p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-21T02:12:35.580", "Id": "421441", "Score": "0", "body": "Thank you for the review! I'm learning so much with that. So, basically, should I avoid most of non-std items? I know that is better to let something handle a situation than you by hand, but in terms of practise and personal development as a programmer, Is it all bad? Probably i will remove routes class and make a Route vector. Thank you so much! I will certainly take your advices." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-20T20:35:36.057", "Id": "217794", "ParentId": "217783", "Score": "9" } }, { "body": "<p>It's not bad code for someone new to C++. Here are some observations and suggestions that may help you improve your code.</p>\n\n<h2>Avoid relative paths in <code>#include</code>s</h2>\n\n<p>Generally it's better to omit relative path names from <code>#include</code> files and instead point the compiler to the appropriate location. So instead of this:</p>\n\n<pre><code>#include \"Server/Routes.h\"\n#include \"Tools/Logger.h\"\n</code></pre>\n\n<p>write this:</p>\n\n<pre><code>#include \"Routes.h\"\n#include \"Logger.h\"\n</code></pre>\n\n<p>For <code>gcc</code>, you'd use <code>-I</code> to tell the compiler where to find these files. This makes the code less dependent on the actual file structure, and leaving such details in a single location: a <code>Makefile</code> or compiler configuration file. With <code>cmake</code>, we can use <code>include_directories</code>. </p>\n\n<h2>Prefer to avoid using <code>new</code> and <code>delete</code> directly</h2>\n\n<p>The <code>server</code> variable within the <code>main()</code> function doesn't really need to be allocated via <code>new</code>. The same is true of the <code>_routes</code> member of <code>Server</code> and probably some other places as well. That way, it is automatically created with the correct length and then discarded when the function is complete or the owning object is deleted. </p>\n\n<h2>Avoid leading underscores in names</h2>\n\n<p>Anything with a leading underscore is a <em>reserved name</em> in C++ (and in C) in certain scopes. See <a href=\"http://stackoverflow.com/questions/228783/what-are-the-rules-about-using-an-underscore-in-a-c-identifier\">this question</a> for details.</p>\n\n<h2>Prefer modern initializers for constructors</h2>\n\n<p>The constructor use the more modern initializer style rather than the old style you're currently using. Instead of this:</p>\n\n<pre><code>Response::Response(int socket_in) {\n _socket = socket_in;\n _sent = false;\n}\n</code></pre>\n\n<p>one could write this:</p>\n\n<pre><code>Response::Response(int socket_in) :\n _socket{socket_in},\n _sent{false}\n{}\n</code></pre>\n\n<h2>Let the compiler create default destructor</h2>\n\n<p>The compiler will create a destructor by default which is essentially identical to what you've got in several places, so you can simply omit both the declaraton and implementation from your code.</p>\n\n<h2>Fix the bug</h2>\n\n<p>This is a very subtle bug, but a bug nonetheless. Within <code>Server::setRoute()</code> three threads are created, two of which take <code>this</code> as a parameter. The problem is that there's no guarantee that the object still exists for the duration of the launched threads. What you need is to use <code>enable_shared_from_this</code> with the class and then use a <code>shared_ptr</code>. <a href=\"https://stackoverflow.com/questions/712279/what-is-the-usefulness-of-enable-shared-from-this\">This question</a> explains a bit more. Generally speaking, it is somewhat difficult to write robust multithreaded code in C++ because there are many ways to create subtle bugs like this.</p>\n\n<h2>Avoid needless casts and variables</h2>\n\n<p>The current code contains these two lines:</p>\n\n<pre><code>void (*callback)(Request*, Response*) = route.callback;\ncallback(request, response);\n</code></pre>\n\n<p>But this could be much more simply written like this:</p>\n\n<pre><code>route.callback(request, response);\n</code></pre>\n\n<h2>Use <code>const</code> where practical</h2>\n\n<p>The <code>Request::isValid()</code> and <code>Routes::_getRouteIndex</code> member functions do not alter the underlying objects and therefore should be declared <code>const</code>. That is, the declaration should be:</p>\n\n<pre><code>int _getRouteIndex(std::string path, Struct::Methods method) const;\n</code></pre>\n\n<h2>Use \"range <code>for</code>\" and simplify your code</h2>\n\n<p>The current <code>Routes::_getRouteIndex</code> looks like this:</p>\n\n<pre><code>int Routes::_getRouteIndex(std::string path, Struct::Methods method) {\n for (size_t i = 0; i &lt; _routes.size(); i++) {\n Route* route = &amp;_routes[i];\n if (route-&gt;path == path &amp;&amp; route-&gt;method == method) {\n return i;\n }\n }\n return -1;\n}\n</code></pre>\n\n<p>Using a range <code>for</code> it could be written like this:</p>\n\n<pre><code>int Routes::_getRouteIndex(std::string path, Struct::Methods method) const {\n int i{0};\n for (const auto &amp;r : _routes) {\n if (r.path == path &amp;&amp; r.method == method) {\n return i;\n }\n ++i;\n }\n return -1;\n}\n</code></pre>\n\n<p>However, even better in this instance, use the next suggestion.</p>\n\n<h2>Use library functions where appropriate</h2>\n\n<p>The code for <code>Routes</code> currently stores each <code>Route</code> in a <code>std::vector</code> and then goes through some machinations to recover the index. This could be done more simply by using a <code>std::unordered_map</code>. Also, it may be sufficient just to use the <code>path</code> as an index because the calling code checks that the method matches. Right now, it's not possible to trigger the \"Method invalid/not found\" error because <code>getRoute</code> only returns true if both the <code>path</code> and the <code>method</code> match.</p>\n\n<h2>Omit unused variables</h2>\n\n<p>Because <code>argc</code> and <code>argv</code> are unused, you could use the alternative form of <code>main</code>:</p>\n\n<pre><code>int main ()\n</code></pre>\n\n<p>There are also a number of other places in which passed variables are unused.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-20T23:16:29.897", "Id": "421436", "Score": "1", "body": "I disagree with your first item. And your third item is plain incorrect." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-21T02:17:28.110", "Id": "421442", "Score": "0", "body": "Thank you for the review! I'm using g++ -I to include paths, but I let the folder's name to be more clarifying, am I wrong? I will make some repairs and I will certainly take your advices, thank you so much!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-21T02:45:43.530", "Id": "421443", "Score": "1", "body": "Having paths in include files isn’t *wrong* necessarily but it makes the code less flexible and harder to maintain because it imposes a directory structure that is harder to change. I find it’s better to put that directory structure in one place (e.g. the `Makefile`) than spread across every file." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-21T22:32:26.757", "Id": "421549", "Score": "0", "body": "@Edward Do you also use `-I/usr/include/sys` so you don't have to write `#include <sys/types.h>` anymore? In another example, `#include <boost/...>` clearly says from which project the include file comes. How do you known which of the 50 dependencies provides the `<common.h>` header?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-21T23:46:24.527", "Id": "421556", "Score": "1", "body": "@RolandIllig Project (e.g. `boost`) and system (e.g. `sys`) are different because they are well known, widely available and stable. I am referring to files that one writes for one's own particular project. I tend to aggregate logical portions of my projects into either shared or static libraries. I find that this makes them easier to thoroughly unit test. For those reason, If I had a file with 50 dependencies, or a project include file named `common.h`, I would consider it an design failure or an implementation flaw and would rewrite into more granular, better named pieces." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-20T22:50:38.697", "Id": "217800", "ParentId": "217783", "Score": "6" } }, { "body": "<p>When programming in C or C++, there are really many ways to shoot yourself in the foot. To prevent at least some of them, the compilers can produce warnings if they see typical mistakes. But you, as the programmer, have to tell the compiler to give you these warnings.</p>\n\n<p>For GCC, the basic warning level is <code>-Wall</code>. It issues many useful warnings. So instead of running <code>g++ myfile.cpp</code>, run <code>g++ -Wall myfile.cpp</code>.</p>\n\n<p>When you have understood the warnings and have fixed them (in this order), it's time for the next level:</p>\n\n<pre><code>g++ -Wall -O2\n</code></pre>\n\n<p>The <code>-O2</code> option enables optimizations. This will make your code run faster, and it also generates new warnings. This is because some of the warnings (like \"unused variable\") are generated as a byproduct of the optimizations.</p>\n\n<p>The next level is:</p>\n\n<pre><code>g++ -Wall -Wextra -O2\n</code></pre>\n\n<p>Surprise: the <code>-Wall</code> option doesn't enable all warnings (even if its name suggests so). There are some additional warnings. And even now, you don't get all available warnings.</p>\n\n<pre><code>g++ -Wall -Wextra -pedantic -std=c17\n</code></pre>\n\n<p>If you are at this stage and have understood and fixed all the warnings, your code is in a good shape. Now try the next compiler, CLang:</p>\n\n<pre><code>clang -Wall -Weverything -O2\n</code></pre>\n\n<p>If you are developing on Solaris, try SUNPro, if you are developing on IRIX, use MIPSPro.</p>\n\n<p>So far for the compiler.</p>\n\n<hr>\n\n<p>The <code>chmod</code> command is redundant. A compiler's job is to produces executable files, therefore it will make the file executable. You don't need to do that yourself.</p>\n\n<p>The advice for running <code>chmod +x</code> comes from a different scenario. When you write programs in a programming language where the source code is executed directly, instead of being compiled, there's no program that transforms your written code into machine-executable code. These two kinds of code are in the same file. And only because your text editor does not make the file executable do you have to do this yourself. Examples for such programming languages are Python, Perl, Bash.</p>\n\n<hr>\n\n<p>You can remove the <code>sudo</code> command completely from your installation program. I'm assuming that all these files are somewhere in your home directory, probably <code>/home/username</code> or <code>/Users/username</code>. In these directories you have all the permissions you need to create files and to execute them.</p>\n\n<p>The sudo command is only needed if you want to do things that affect <em>all</em> users of the computer, such as configuring the wifi or updating the system programs or installing your own programs in <code>/usr/bin</code>.</p>\n\n<p>Don't use <code>sudo</code> unless it is really necessary. When you get error messages, try to understand them.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-22T12:58:42.420", "Id": "421622", "Score": "2", "body": "You might also want to suggest that `make` or `CMake` are purpose built for the task of compiling programs and are likely better and more portable tools than a `bash` script for that purpose." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-22T13:13:08.277", "Id": "421624", "Score": "0", "body": "I did not understand some of those options before, mostly the purpose and usage. Thank you so much for clarifying this for me, certainly it will be so helpful to others as was to me." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-22T06:14:54.440", "Id": "217869", "ParentId": "217783", "Score": "3" } } ]
{ "AcceptedAnswerId": "217794", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-20T16:08:50.410", "Id": "217783", "Score": "14", "Tags": [ "c++", "multithreading", "http", "socket", "server" ], "Title": "Simple HTTP Server" }
217783
<p>This is the third iteration of my venture on creating an encryption/decryption solution. I asked a <a href="https://codereview.stackexchange.com/questions/217271/encrypts-using-aes-with-random-initialization-vector-meant-for-data-with-limited/217283#217283">question here</a>, which led to this <a href="https://crypto.stackexchange.com/questions/68735/i-need-help-determining-the-best-encryption-options-based-on-system-security-cry">question here</a>, which led to this <a href="https://crypto.stackexchange.com/a/68740/67424">answer here</a>, which led me to introducing <a href="https://www.bouncycastle.org" rel="nofollow noreferrer">Bouncy Castle</a> into my solution to gain better security under the circumstances and application requirements.</p> <p>Requirements: To encrypt and decrypt a string using AES 256 with a password/key (stored in web.config) in an ASP.net application. </p> <p>History: If you follow the above links you'll find that I originally tried to stick with the core .net provided solutions without the inclusion of any additional libraries. This requirement has changed and I've added <a href="https://www.bouncycastle.org" rel="nofollow noreferrer">Bouncy Castle</a> to my solution.</p> <p>Thanks to @SEJPM regularly pointing me in the right direction I decided to implement AES GCM and ditch my previous attempts. </p> <p>I found this <a href="https://gist.github.com/jbtule/4336842" rel="nofollow noreferrer">example here</a> from @jbtule who seems to have a pretty good handle on things, and honestly I didn't change a thing other than convert it to VB. However, based on previous suggestions given to me to use Argon2, I read that Bouncy Castle supports this now but I'm currently uncertain as how to properly implement it. </p> <p>Although my code is essentially a copy @jbtule's original post on CodeReview, that was 6 years ago.</p> <p>So based on the fact that I pull the encryption key/pass from web.config and I need simple encrypt/decrypt, how does this solution stack up?</p> <p>Usage:</p> <pre><code>Dim password = RetrieveFromWebConfig() Dim plainText = "Hello World" Dim encrypted = SimpleEncryptWithPassword(plainText, password) Dim decrypted = SimpleDecryptWithPassword(encrypted, password) </code></pre> <p>Code:</p> <pre><code>Imports System Imports System.IO Imports System.Text Imports Org.BouncyCastle.Crypto Imports Org.BouncyCastle.Crypto.Engines Imports Org.BouncyCastle.Crypto.Generators Imports Org.BouncyCastle.Crypto.Modes Imports Org.BouncyCastle.Crypto.Parameters Imports Org.BouncyCastle.Security Namespace Utilities.Encryption Public Class Aesgcm Public Shared ReadOnly Random As SecureRandom = New SecureRandom() Public Shared ReadOnly NonceBitSize As Integer = 128 Public Shared ReadOnly MacBitSize As Integer = 128 Public Shared ReadOnly KeyBitSize As Integer = 256 Public Shared ReadOnly SaltBitSize As Integer = 128 Public Shared ReadOnly Iterations As Integer = 10000 Public Shared ReadOnly MinPasswordLength As Integer = 12 Shared Function SimpleEncryptWithPassword(secretMessage As String, password As String, ByVal Optional nonSecretPayload As Byte() = Nothing) As String If String.IsNullOrEmpty(secretMessage) Then Throw New ArgumentException("Secret Message Required!", "secretMessage") Dim plainText = Encoding.UTF8.GetBytes(secretMessage) Dim cipherText = SimpleEncryptWithPassword(plainText, password, nonSecretPayload) Return Convert.ToBase64String(cipherText) End Function Shared Function SimpleDecryptWithPassword(encryptedMessage As String, password As String, ByVal Optional nonSecretPayloadLength As Integer = 0) As String If String.IsNullOrWhiteSpace(encryptedMessage) Then Throw New ArgumentException("Encrypted Message Required!", "encryptedMessage") Dim cipherText = Convert.FromBase64String(encryptedMessage) Dim plainText = SimpleDecryptWithPassword(cipherText, password, nonSecretPayloadLength) Return If(plainText Is Nothing, Nothing, Encoding.UTF8.GetString(plainText)) End Function Shared Function SimpleEncrypt(secretMessage As Byte(), key As Byte(), ByVal Optional nonSecretPayload As Byte() = Nothing) As Byte() If key Is Nothing OrElse key.Length &lt;&gt; KeyBitSize / 8 Then Throw New ArgumentException($"Key needs to be {KeyBitSize} bit!", "key") If secretMessage Is Nothing OrElse secretMessage.Length = 0 Then Throw New ArgumentException("Secret Message Required!", "secretMessage") nonSecretPayload = If(nonSecretPayload, New Byte() {}) Dim nonce = New Byte(CInt(NonceBitSize / 8 - 1)) {} Random.NextBytes(nonce, 0, nonce.Length) Dim cipher = New GcmBlockCipher(New AesEngine()) Dim parameters = New AeadParameters(New KeyParameter(key), MacBitSize, nonce, nonSecretPayload) cipher.Init(True, parameters) Dim cipherText = New Byte(cipher.GetOutputSize(secretMessage.Length) - 1) {} Dim len = cipher.ProcessBytes(secretMessage, 0, secretMessage.Length, cipherText, 0) cipher.DoFinal(cipherText, len) Using combinedStream = New MemoryStream() Using binaryWriter = New BinaryWriter(combinedStream) binaryWriter.Write(nonSecretPayload) binaryWriter.Write(nonce) binaryWriter.Write(cipherText) End Using Return combinedStream.ToArray() End Using End Function Shared Function SimpleDecrypt(encryptedMessage As Byte(), key As Byte(), ByVal Optional nonSecretPayloadLength As Integer = 0) As Byte() If key Is Nothing OrElse key.Length &lt;&gt; KeyBitSize / 8 Then Throw New ArgumentException($"Key needs to be {KeyBitSize} bit!", "key") If encryptedMessage Is Nothing OrElse encryptedMessage.Length = 0 Then Throw New ArgumentException("Encrypted Message Required!", "encryptedMessage") Using cipherStream = New MemoryStream(encryptedMessage) Using cipherReader = New BinaryReader(cipherStream) Dim nonSecretPayload = cipherReader.ReadBytes(nonSecretPayloadLength) Dim nonce = cipherReader.ReadBytes(CInt(NonceBitSize / 8)) Dim cipher = New GcmBlockCipher(New AesEngine()) Dim parameters = New AeadParameters(New KeyParameter(key), MacBitSize, nonce, nonSecretPayload) cipher.Init(False, parameters) Dim cipherText = cipherReader.ReadBytes(encryptedMessage.Length - nonSecretPayloadLength - nonce.Length) Dim plainText = New Byte(cipher.GetOutputSize(cipherText.Length) - 1) {} Try Dim len = cipher.ProcessBytes(cipherText, 0, cipherText.Length, plainText, 0) cipher.DoFinal(plainText, len) Catch unusedInvalidCipherTextException1 As InvalidCipherTextException Return Nothing End Try Return plainText End Using End Using End Function Shared Function SimpleEncryptWithPassword(secretMessage As Byte(), password As String, ByVal Optional nonSecretPayload As Byte() = Nothing) As Byte() nonSecretPayload = If(nonSecretPayload, New Byte() {}) If String.IsNullOrWhiteSpace(password) OrElse password.Length &lt; MinPasswordLength Then Throw New ArgumentException($"Must have a password of at least {MinPasswordLength} characters!", "password") If secretMessage Is Nothing OrElse secretMessage.Length = 0 Then Throw New ArgumentException("Secret Message Required!", "secretMessage") Dim generator = New Pkcs5S2ParametersGenerator() Dim salt = New Byte(CInt(SaltBitSize / 8 - 1)) {} Random.NextBytes(salt) generator.Init(PbeParametersGenerator.Pkcs5PasswordToBytes(password.ToCharArray()), salt, Iterations) Dim key = CType(generator.GenerateDerivedMacParameters(KeyBitSize), KeyParameter) Dim payload = New Byte(salt.Length + nonSecretPayload.Length - 1) {} Array.Copy(nonSecretPayload, payload, nonSecretPayload.Length) Array.Copy(salt, 0, payload, nonSecretPayload.Length, salt.Length) Return SimpleEncrypt(secretMessage, key.GetKey(), payload) End Function Shared Function SimpleDecryptWithPassword(encryptedMessage As Byte(), password As String, ByVal Optional nonSecretPayloadLength As Integer = 0) As Byte() If String.IsNullOrWhiteSpace(password) OrElse password.Length &lt; MinPasswordLength Then Throw New ArgumentException($"Must have a password of at least {MinPasswordLength} characters!", "password") If encryptedMessage Is Nothing OrElse encryptedMessage.Length = 0 Then Throw New ArgumentException("Encrypted Message Required!", "encryptedMessage") Dim generator = New Pkcs5S2ParametersGenerator() Dim salt = New Byte(CInt(SaltBitSize / 8 - 1)) {} Array.Copy(encryptedMessage, nonSecretPayloadLength, salt, 0, salt.Length) generator.Init(PbeParametersGenerator.Pkcs5PasswordToBytes(password.ToCharArray()), salt, Iterations) Dim key = CType(generator.GenerateDerivedMacParameters(KeyBitSize), KeyParameter) Return SimpleDecrypt(encryptedMessage, key.GetKey(), salt.Length + nonSecretPayloadLength) End Function End Class End Namespace </code></pre>
[]
[ { "body": "<p>This is probably not a good idea:</p>\n\n<pre><code>Public Shared ReadOnly NonceBitSize As Integer = 128\n</code></pre>\n\n<p>as the default nonce for GCM is 12 bytes or 96 bits. A different size nonce requires additional calculations and may not always be supported by API's (although they generally do).</p>\n\n<hr>\n\n<p>The iteration count for key derivation is on the low side, say 40K is more recommended, but the actual value should simply be as high as you can manage within your limitations.</p>\n\n<hr>\n\n<pre><code>If String.IsNullOrEmpty(secretMessage) Then Throw New ArgumentException(\"Secret Message Required!\", \"secretMessage\")\n</code></pre>\n\n<p>Generally we think that empty messages are OK (when it comes to the encryption layer). Now you could not send a message that is only protected for integrity / authenticity. it's good that you test for <code>null</code> of course.</p>\n\n<hr>\n\n<pre><code>Dim payload = New Byte(salt.Length + nonSecretPayload.Length - 1) {}\n</code></pre>\n\n<p>After this I would presume that you first copy the <code>salt</code> and then the <code>nonSecretPayload</code>, instead of the other way around. The name <code>payload</code> is confusing, because you would expect this to include the payload that also needs to be encrypted.</p>\n\n<hr>\n\n<pre><code>generator.Init(PbeParametersGenerator.Pkcs5PasswordToBytes(password.ToCharArray()), salt, Iterations)\n</code></pre>\n\n<p>the reason why the password is delivered as a character array is that you can zero an array. Commonly password interface elements will also return a char array for the same reason. Converting it from string doesn't make all that much sense - at least not at this level.</p>\n\n<hr>\n\n<p>There is no need to convert back and forth to a <code>KeyParameter</code>. Once you have a <code>KeyParameter</code>, use it, possibly as private method from several public methods.</p>\n\n<hr>\n\n<pre><code> Catch unusedInvalidCipherTextException1 As InvalidCipherTextException\n Return Nothing\n</code></pre>\n\n<p>This is a big no-no. Never return <code>Nothing</code> or similar and sweep the exception under the carpet. If you don't know what to do, then wrap the exception in a more generic exception.</p>\n\n<hr>\n\n<p>During decryption you're passing the length of the <code>nonSecretPayload</code> and you're never returning the data itself. That's a weird decision: you need to do handle the contents of this payload some way or another. It's not clear how you would retrieve or handle it currently.</p>\n\n<hr>\n\n<p>Other protocol related notes:</p>\n\n<ul>\n<li>Your scheme doesn't include a version number. You could use one of those to upgrade to a different scheme (or to up the iteration count) later on.</li>\n<li>In general, if you derive the wrong key then decryption would fail. As such, there is no pressing need to include the salt in the additional authenticated data. I would not call that <em>wrong</em> though.</li>\n<li>Currently you need to know the size of the AAD in advance; you could think of a way to send the AAD length within your protocol.</li>\n<li>You could derive both the key and nonce as you're using a random salt anyway. Again, I would not call that wrong in any sense.</li>\n</ul>\n\n<hr>\n\n<p>Conclusion: there is nothing particularly wrong if you use this for password based encryption, but there are a lot of small things that can be adjusted, with the version indicator and the nonce size being the main issues. The exception handling is not up to par.</p>\n\n<p>I'd strongly recommend to write a small protocol description, so you can show what you implement without others having to read through your code to find out.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-23T18:25:52.247", "Id": "217977", "ParentId": "217784", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-20T16:17:52.020", "Id": "217784", "Score": "2", "Tags": [ "security", "asp.net", "cryptography", "vb.net", "aes" ], "Title": "Encrypts using AES GCM for data with limited visibility and long rest" }
217784
<p><strong>The task</strong></p> <blockquote> <p>Determine whether there exists a one-to-one character mapping from one string s1 to another s2.</p> <p>For example, given s1 = abc and s2 = bcd, return true since we can map a to b, b to c, and c to d.</p> <p>Given s1 = foo and s2 = bar, return false since the o cannot map to two characters.</p> </blockquote> <p>The task is ambiguous. Here are my interpretations of the task and the corresponding solution:</p> <p><strong>Interpretation 1:</strong></p> <p>For every letter in one string there exists exactly one in the other. (order and position of the corresponding letter are irrelevant)</p> <p><strong>My solution</strong></p> <pre><code>const s1 = "foo"; const s2 = "bar"; const isMappable = (s1, s2) =&gt; { if (s1.length !== s2.length) { return false; } const createOrderedMap = str =&gt; Object.values([...str] .reduce((map, s) =&gt; { map[s] = map[s] ? map[s] + 1 : 1; return map; }, {})).sort(); const o1 = createOrderedMap(s1); const o2 = createOrderedMap(s2); if (o1.length !== o2.length) { return false; } for (let i = 0, len = o1.length; i &lt; len; i++) { if (o1[i] !== o2[i]) { return false; } } return true; }; console.log(isMappable(s1, s2)); </code></pre> <p><strong>Interpretation 2:</strong></p> <p>For every letter in one string there exists exactly one in the other at the exact order and position of the corresponding letter.</p> <p><strong>My solution</strong></p> <pre><code>const s1 = "aab"; const s2 = "cdc"; const isMappable = (s1, s2) =&gt; { if (s1.length !== s2.length) { return false; } const map1 = new Map(); const map2 = new Map(); return [...s1].every((s, i) =&gt; { if (!map1.has(s) &amp;&amp; !map2.has(s2[i])) { map2.set(s2[i], s); map1.set(s, s2[i]); } return map1.get(s) === s2[i] &amp;&amp; map2.get(s2[i]) === s; }); }; console.log(isMapable(s1, s2)); </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-20T19:08:02.247", "Id": "421422", "Score": "0", "body": "Is there a mapping between `abbb` and `cdcd`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-20T22:21:56.493", "Id": "421434", "Score": "0", "body": "@vpn You are right. Fixed." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-21T09:34:34.937", "Id": "421460", "Score": "0", "body": "returns true for `aab`,`xyx`; seems incorrect to me? I read this problem as \"*can string A be transformed to string B by substitution cipher?*\"" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-21T09:35:43.867", "Id": "421461", "Score": "0", "body": "a can be mapped to one x, the other a to the other x, and b can be mapped to y? @OhMyGoodness" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-21T09:42:07.933", "Id": "421463", "Score": "0", "body": "you responded faster than I could edit, but I understand your reading of the problem. Depends on what they meant by \"mapping\", I guess." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-21T09:44:34.987", "Id": "421465", "Score": "0", "body": "@OhMyGoodness I also get your point. This task may be indeed in a realm of encryption. And it would be more challenging to do it your way. I’ll try to solve the task the way you understood it" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-21T10:22:12.670", "Id": "421471", "Score": "0", "body": "Updated @OhMyGoodness" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-21T16:55:58.700", "Id": "421510", "Score": "1", "body": "update only checks one direction `isMapable(\"abc\",\"ddd\")` should be false (is many-to-one instead of one-to-one). And mappable is spelled with 2 p's :)" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-20T17:37:43.647", "Id": "217788", "Score": "2", "Tags": [ "javascript", "algorithm", "programming-challenge", "functional-programming", "ecmascript-6" ], "Title": "Determine whether there exists a one-to-one character mapping from one string to another" }
217788
<p>I created this simple one line calculator for two numbers only where user can input any two numbers and and operator in between</p> <p>for example 20+45 and computer will return result of 65.</p> <pre><code>using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; namespace SimpleCalculator { class Program { static void Main(string[] args) { ShowOutput(); string user_input = UserInput(); int result = PerformCalculation(InputToList(user_input)); Console.WriteLine($"{user_input}={result}"); Console.Read(); } static void ShowOutput() { Console.WriteLine("Enter numbers followed by operation eg. 1+2-4"); } static string UserInput() { string User_input = Console.ReadLine(); return User_input; } static string[] InputToList(string input) { string number1 = ""; string number2 = ""; string Oprt = ""; //Mathematical operator string[] Arithmetic = new string[3]; int n = 0; foreach (char charecter in input) { int num; bool isNumerical = int.TryParse(charecter.ToString(), out num); n += 1; if (isNumerical) { number1 += num; } else { Oprt = charecter.ToString(); Arithmetic[0] = number1; Arithmetic[1] = Oprt; for(int i = n; i &lt;= input.Length - 1; i++) { number2 += input[i]; } Arithmetic[2] = number2; } } return Arithmetic; } static int PerformCalculation(string[] Input) { int result = 0; switch (Input[1]) { case "+": result = Int32.Parse(Input[0]) + Int32.Parse(Input[2]); break; case "-": result = Int32.Parse(Input[0]) - Int32.Parse(Input[2]); break; case "*": result = Int32.Parse(Input[0]) * Int32.Parse(Input[2]); break; case "/": result = Int32.Parse(Input[0]) / Int32.Parse(Input[2]); break; } return result; } } } </code></pre>
[]
[ { "body": "<p>In <code>PerformCalculation</code> function, you are repeating argument parsing several times. You should really apply processing only once, for the sake of code maintenance:</p>\n\n<pre><code>static int PerformCalculation(string[] Input)\n{\n int left = int.Parse(Input[0]);\n int right = int.Parse(Input[2]);\n switch (Input[1])\n {\n case \"+\": return left + right;\n case \"-\": return left - right;\n case \"*\": return left * right;\n default: return left / right; // Mind possible division by zero\n }\n}\n</code></pre>\n\n<p>Mind that the <code>switch</code> is more compact if it returns results (without <code>break</code>).</p>\n\n<p>Also, note that the <code>InputToList</code> method an be made much more compact if you know the format of the expression:</p>\n\n<pre><code>static string[] InputToList(string input)\n{\n int opIndex = input.IndexOfAny(new[] {'+', '-', '*', '/'});\n return new[]\n {\n input.Substring(0, opIndex), \n input.Substring(opIndex, 1), \n input.Substring(opIndex + 1)\n };\n}\n</code></pre>\n\n<p>The <code>IndexOfAny</code> method is returning the first index inside string at which any of the listed characters appears.</p>\n\n<p>The <code>Substring</code> method returns a new string which is the section of the original string. Please refer to documentation: <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.string.substring?view=netframework-4.8\" rel=\"nofollow noreferrer\">https://docs.microsoft.com/en-us/dotnet/api/system.string.substring?view=netframework-4.8</a></p>\n\n<p>It is tempting to use the <code>string.Split()</code> method for this same purpose:</p>\n\n<pre><code>static string[] InputToList(string input) =&gt;\n input.Split('+', '-', '*', '/');\n</code></pre>\n\n<p>However, <code>Split</code> actually drops the delimiter. Hence, the string <code>\"25+36\"</code> would produce an array <code>[\"25\", \"36\"]</code>, and the operator would be lost.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-21T10:46:04.023", "Id": "421473", "Score": "0", "body": "Thanks for reviewing, can you explain more about how you used Substring method, is it like splicing a string into array?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-21T12:57:22.200", "Id": "421485", "Score": "0", "body": "@AMJ I've added some explanations regarding substrings in the answer." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-22T12:07:27.607", "Id": "421610", "Score": "0", "body": "Thank you for explanation, from what I understood i created the following test code (I dont have access to visual studio right now so i used online compiler) I will tweak the actual code later.\n`" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-20T20:58:16.197", "Id": "217796", "ParentId": "217792", "Score": "3" } }, { "body": "<p>I'll go through your program from top to bottom, mentioning some details.</p>\n\n<pre><code>static void Main(string[] args)\n{\n ShowOutput();\n string user_input = UserInput();\n int result = PerformCalculation(InputToList(user_input));\n Console.WriteLine($\"{user_input}={result}\");\n Console.Read(); \n}\n</code></pre>\n\n<p>Starting with the <code>Main</code> method is good practice. The reader gets an overview about what the whole program is supposed to do.</p>\n\n<p>Starting the program with <code>ShowOutput()</code> is confusing. The usual sequence of events is: Input — Processing — Output. By showing the output first, you are reversing this usual sequence of events.</p>\n\n<pre><code>static void ShowOutput()\n{\n Console.WriteLine(\"Enter numbers followed by operation eg. 1+2-4\");\n}\n</code></pre>\n\n<p>Instead of <code>ShowOutput</code> this method should better be named <code>ShowPrompt</code>. This is more specific, and prompting the user clearly belongs to the input phase.</p>\n\n<pre><code>static string UserInput()\n{\n string User_input = Console.ReadLine();\n return User_input;\n}\n</code></pre>\n\n<p>Typically method names start with a verb, like in <code>ShowOutput</code> above. The method <code>UserInput</code> should rather be called <code>ReadLine</code> since that is exactly what happens here.</p>\n\n<pre><code>static string[] InputToList(string input)\n{\n string number1 = \"\";\n string number2 = \"\"; \n string Oprt = \"\"; //Mathematical operator\n string[] Arithmetic = new string[3];\n</code></pre>\n\n<p>Now it is getting more complicated, and inconsistencies appear. Some of your variables start with a lowercase letter, some with an uppercase letter. They should all start with a lowercase letter. That's by convention.</p>\n\n<p>The usual abbreviation for <code>operator</code> is <code>op</code>. The letters <code>prt</code> remind me of the PrtScr key on the keyboard, which means Print Screen.</p>\n\n<p>From reading the code until here, I have no idea what the variable <code>Arithmetic</code> might be. Granted, it's not easy to find a name for it. It could be something like \"calculation atoms\", \"calculation parts\", \"words\", \"things\", \"tokens\". When continuing to read the program, a better name might become apparent. This variable should then be renamed.</p>\n\n<pre><code> int n = 0;\n foreach (char charecter in input)\n {\n int num;\n bool isNumerical = int.TryParse(charecter.ToString(), out num);\n n += 1;\n if (isNumerical)\n {\n number1 += num;\n }\n else\n {\n Oprt = charecter.ToString();\n Arithmetic[0] = number1;\n Arithmetic[1] = Oprt;\n for(int i = n; i &lt;= input.Length - 1; i++)\n {\n number2 += input[i];\n }\n Arithmetic[2] = number2;\n }\n }\n</code></pre>\n\n<p>This code is long and tricky and fragile. In the upper part you parse <code>number1</code> until you find a character (not charecter) that is not numeric. In that moment you save the current <code>number1</code> into the result array. You can be lucky that you do this in exactly this moment, because later the variable <code>number1</code> will be overwritten again, as soon as the <code>number2</code> is parsed.</p>\n\n<pre><code> return Arithmetic;\n}\n</code></pre>\n\n<p>There must be some simpler way of expressing this idea. Imagine you explain this to a human friend. You would hopefully not choose to explain the code above, but some simpler code. To parse an expression that consists of numbers and operators:</p>\n\n<ol>\n<li>parse a number</li>\n<li>parse an operator</li>\n<li>parse a number</li>\n<li>continue with step 2</li>\n</ol>\n\n<p>This is a high-level view on the whole topic of parsing an expression. That's how your code should look. The method should be called <code>TryParseExpr</code>. The current name <code>InputToList</code> is too unspecific.</p>\n\n<pre><code>static int PerformCalculation(string[] Input)\n</code></pre>\n\n<p>As Zoran already mentioned in his answer, performing a calculation on strings is inefficient and sounds strange. Calculations should be performed on numbers.</p>\n\n<p>Converting the string parts into numbers and operators should be done by the <code>TryParseExpr</code> method I suggested above.</p>\n\n<pre><code>{\n int result = 0;\n switch (Input[1])\n {\n case \"+\":\n result = Int32.Parse(Input[0]) + Int32.Parse(Input[2]);\n break;\n case \"-\":\n result = Int32.Parse(Input[0]) - Int32.Parse(Input[2]);\n break;\n case \"*\":\n result = Int32.Parse(Input[0]) * Int32.Parse(Input[2]);\n break;\n case \"/\":\n result = Int32.Parse(Input[0]) / Int32.Parse(Input[2]);\n break;\n }\n return result;\n}\n</code></pre>\n\n<p>This style of <code>int result = 0; ...; result = the actual result; ...; return result;</code> leads to long code. In most cases the code becomes easier to understand when the result is not saved in a variable but returned directly. Such as in:</p>\n\n<pre><code>static int Calculate(int left, char op, int right)\n{\n switch (op)\n {\n case '+':\n return left + right;\n case '-':\n return left - right;\n case '*':\n return left * right;\n case '/':\n return left / right;\n default:\n throw new ArgumentException($\"unknown operator {op}\");\n }\n}\n</code></pre>\n\n<p>This is as simple as it gets. There are no unnecessary arrays, and each parameter has the correct data type.</p>\n\n<p>In your original code you suggest to the user that they may enter <code>1+2-4</code>, but this is something your current code cannot handle. Given the above <code>Calculate</code> method, it's not too difficult to extend the calculation to an arbitrary amount of numbers and operators:</p>\n\n<pre><code>static int Calculate(IReadOnlyList&lt;int&gt; nums, IReadOnlyList&lt;char&gt; ops)\n{\n int res = nums[0];\n for (int i = 0; i &lt; ops.Count; i++)\n res = Calculate(res, ops[i], nums[i + 1]);\n\n return res;\n}\n</code></pre>\n\n<p>In this method the calculation is performed strictly from left to right. The usual operator precedence (<code>*</code> before <code>+</code>) is ignored. That's only for simplicity. It could be added later.</p>\n\n<p>This extended <code>Calculate</code> method can be used like this:</p>\n\n<pre><code>// 1 + 2 - 4\nConsole.WriteLine(Calculate(new List&lt;int&gt; {1, 2, 4}, new List&lt;char&gt; {'+', '-'}));\n</code></pre>\n\n<p>Now the remaining task is to let the user enter a line and convert this line into these two lists of numbers and operators. This is the job of a lexer. A lexer takes a string (or another input source) and repeatedly looks at the beginning to split off a small piece of data, such as a number or an operator.</p>\n\n<p>The general idea I outlined above in the 4 steps can be written in C# like this:</p>\n\n<pre><code>public bool TryParseExpr(out List&lt;int&gt; nums, out List&lt;char&gt; ops)\n{\n nums = new List&lt;int&gt;();\n ops = new List&lt;char&gt;();\n\n if (!TryParseInt(out int firstNum))\n return false;\n nums.Add(firstNum);\n\n while (TryParseOp(out char op))\n {\n ops.Add(op);\n\n if (!TryParseInt(out int num))\n return false;\n nums.Add(num);\n }\n\n return true;\n}\n</code></pre>\n\n<p>Each of the paragraphs in this method corresponds roughly to one of the steps from above. Here they are again, for comparison:</p>\n\n<ol>\n<li>parse a number</li>\n<li>parse an operator</li>\n<li>parse a number</li>\n<li>continue with step 2</li>\n</ol>\n\n<p>Now the only missing part are the basic building blocks, <code>TryParseInt</code> and <code>TryParseOp</code>. These I present together with the whole program that I built from your code:</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing Microsoft.VisualStudio.TestTools.UnitTesting;\n\nnamespace Tests\n{\n [TestClass]\n public class Program\n {\n [TestMethod]\n public void Test()\n {\n TestOk(\"1\", 1);\n TestOk(\"12345\", 12345);\n TestOk(\"12345+11111\", 23456);\n TestOk(\"2147483647\", int.MaxValue);\n TestOk(\"1+2+3+4+5+6\", 21);\n TestOk(\"1+2-3+4-5+6*5\", 25);\n\n TestError(\"2147483648\", \"2147483648\");\n TestError(\"a\", \"a\");\n TestError(\"1+2+3+4+5+a\", \"a\");\n }\n\n static void TestOk(string input, int expected)\n {\n Lexer lexer = new Lexer(input);\n Assert.AreEqual(true, lexer.TryParseExpr(out List&lt;int&gt; nums, out List&lt;char&gt; ops));\n int result = Calculate(nums, ops);\n Assert.AreEqual(expected, result);\n }\n\n static void TestError(string input, string expectedRest)\n {\n Lexer lexer = new Lexer(input);\n Assert.AreEqual(false, lexer.TryParseExpr(out List&lt;int&gt; nums, out List&lt;char&gt; ops));\n Assert.AreEqual(expectedRest, lexer.Rest);\n }\n\n static int Calculate(IReadOnlyList&lt;int&gt; nums, IReadOnlyList&lt;char&gt; ops)\n {\n int res = nums[0];\n for (int i = 0; i &lt; ops.Count; i++)\n res = Calculate(res, ops[i], nums[i + 1]);\n\n return res;\n }\n\n static int Calculate(int left, char op, int right)\n {\n switch (op)\n {\n case '+':\n return left + right;\n case '-':\n return left - right;\n case '*':\n return left * right;\n case '/':\n return left / right;\n default:\n throw new ArgumentException($\"unknown operator {op}\");\n }\n }\n }\n\n // The lexer takes a string and repeatedly converts the text at the\n // current position into a useful piece of data, like a number or an\n // operator.\n //\n // To do this, it remembers the whole text and the current position\n // of the next character to read. It also remembers the length of the\n // text, but this is only for performance reasons, to avoid asking for\n // text.Length again and again.\n class Lexer\n {\n private readonly string text;\n private int pos;\n private readonly int end;\n\n public Lexer(string text)\n {\n this.text = text;\n end = text.Length;\n }\n\n public string Rest =&gt; text.Substring(pos);\n\n public void SkipSpace()\n {\n while (pos &lt; end &amp;&amp; char.IsWhiteSpace(text[pos]))\n pos++;\n }\n\n public bool TryParseInt(out int num)\n {\n int i = pos;\n\n // The number may have a single sign.\n if (i &lt; end &amp;&amp; (text[i] == '-' || text[i] == '+'))\n i++;\n\n // After that, an arbitrary number of digits.\n while (i &lt; end &amp;&amp; char.IsDigit(text[i]))\n i++;\n\n // The TryParse handles the case of too many digits (overflow).\n bool ok = int.TryParse(text.Substring(pos, i - pos), out num);\n if (ok)\n pos = i;\n\n return ok;\n }\n\n public bool TryParseOp(out char op)\n {\n if (pos &lt; end)\n {\n switch (text[pos])\n {\n case '+':\n case '-':\n case '*':\n case '/':\n op = text[pos];\n pos++;\n return true;\n }\n }\n\n op = '\\0';\n return false;\n }\n\n public bool TryParseExpr(out List&lt;int&gt; nums, out List&lt;char&gt; ops)\n {\n nums = new List&lt;int&gt;();\n ops = new List&lt;char&gt;();\n\n if (!TryParseInt(out int firstNum))\n return false;\n nums.Add(firstNum);\n\n while (TryParseOp(out char op))\n {\n ops.Add(op);\n\n if (!TryParseInt(out int num))\n return false;\n nums.Add(num);\n }\n\n return true;\n }\n }\n}\n</code></pre>\n\n<p>You can play around with this code by adding more and more test cases. There's also a method called <code>SkipSpace</code> that is currently unused. To allow the user to enter <code>1 + 2 - 4</code> as well, your parsing code should skip the space before and after each number or operator.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-21T10:46:42.567", "Id": "421474", "Score": "0", "body": "Thank you for in depth review :), will check that and come back with comment." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-22T14:27:03.613", "Id": "421630", "Score": "0", "body": "Thanks again for reviewing, I've been through your comments everything is understood but got few questions. in the function `TryParseInt` which return bool, how could it be possible to test if that function is true of false in the function itself, as in the expression `TryParseInt(out int firstNum)`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-22T16:42:51.773", "Id": "421650", "Score": "1", "body": "I'm not sure I understand your question correctly, I'll try to answer anyway. Inside the `TryParseInt` function, there is only a single `return` statement. To see whether the function returns `true` or `false`, you can look at the `ok` variable, as I have done already in the code. The `if (ok) pos = i;` is exactly such a test. In depth, it means: only if the `TryParseInt` function succeeds, does the state of the lexer change. If it fails, the lexer is left completely unchanged, so that the caller code could try some other parsing function." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-24T14:29:23.823", "Id": "423008", "Score": "0", "body": "Can you please tell what is `=>` called and what it does in `rest` field" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-24T16:27:48.573", "Id": "423041", "Score": "0", "body": "The `public Rest => \"\"` defines a property called `Rest`. Whenever the expression `lexer.Rest` is evaluated, the code to the right of the `=>` is executed and returned. These properties can be used instead of methods. The common expectation is that evaluating a property is very fast and does not have side effects. Its value usually changes only when you modify something else in the class defining the property. Therefore, just as an example, having a property called `Random` is a bad idea." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-20T22:10:03.850", "Id": "217797", "ParentId": "217792", "Score": "7" } }, { "body": "<p>To add some details to the other great answers:</p>\n\n<ol>\n<li><p>In modern C# it's common to use <code>var</code> to initalize local variables (<code>var i = 0;</code> instead of <code>int i = 0;</code>).</p></li>\n<li><p>Don't mix different naming styles. Snake case (<code>user_input</code>) is uncommon and doesn't match the official C# code style. For classes, methods and properties use UpperCamelCase and for local variables use lowerCamelCase.</p></li>\n<li><p>You got a typo in your foreach loop. I'd write it this way: <code>for (var character in input) {...}</code></p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-22T08:09:21.617", "Id": "421592", "Score": "1", "body": "`for (var char in input)` - this won't work because `char` is a reserved keyword." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-22T14:30:27.963", "Id": "421631", "Score": "0", "body": "can i assign any value to `var` type variable ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-22T16:28:26.683", "Id": "421646", "Score": "0", "body": "@t3chb0t thank you. Fixed." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-22T16:29:36.953", "Id": "421647", "Score": "1", "body": "@AMJ, yes, apart from null values. If the type is clear, it works. For null it cannot derive the type so you have to explicitly define it. However var is not a type itself, it's just a way to shorten verbose code." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-21T13:46:28.920", "Id": "217832", "ParentId": "217792", "Score": "2" } }, { "body": "<p>I would use <em>regular expressions</em> to make a simple calculator that can only perform one binary operation. There is less overhead with <em>tokenizing</em> and <em>casting</em>. If you do decide to keep making calculator more and more complex, I suggest using the <a href=\"https://stackoverflow.com/questions/2842809/lexers-vs-parsers\">lexer-parser</a> approach instead.</p>\n\n<pre><code>using System;\nusing System.Linq;\nusing System.Text;\nusing System.Collections.Generic;\nusing System.Globalization;\nusing System.Text.RegularExpressions;\n\npublic class Program\n{\n public static void Main()\n {\n Console.WriteLine(\"1+4 = \" + Evaluate(\"1+4\"));\n Console.WriteLine(\"1-4 = \" + Evaluate(\"1-4\"));\n Console.WriteLine(\"1*4 = \" + Evaluate(\"1*4\"));\n Console.WriteLine(\"1/4 = \" + Evaluate(\"1/4\"));\n\n Console.ReadKey();\n }\n\n public static decimal Evaluate(string expression) \n {\n var tokens = Regex.Match(expression, @\"^(?&lt;leftoperand&gt;\\d+)(?&lt;operator&gt;[+-/*])(?&lt;rigthoperand&gt;\\d+)$\");\n var leftoperandToken = tokens.Groups[\"leftoperand\"];\n var operatorToken = tokens.Groups[\"operator\"];\n var rigthoperandToken = tokens.Groups[\"rigthoperand\"];\n\n if (!leftoperandToken.Success) {\n throw new FormatException(\"left operand could not be parsed\");\n }\n\n if (!operatorToken.Success) {\n throw new FormatException(\"operator could not be parsed\");\n }\n\n if (!rigthoperandToken.Success) {\n throw new FormatException(\"right operand could not be parsed\");\n }\n\n // at this point, the operands can be safe-casted to integers\n\n var left = int.Parse(leftoperandToken.Value);\n var right = int.Parse(rigthoperandToken.Value);\n var result = 0m;\n\n switch (operatorToken.Value) {\n case \"*\":\n result = left * right;\n break;\n case \"/\":\n result = Convert.ToDecimal(left) / right;\n break;\n case \"-\":\n result = left - right;\n break;\n case \"+\":\n result = left + right;\n break;\n default:\n // a little bit forward-compatible\n throw new FormatException(operatorToken.Value + \" is an invalid operator\");\n }\n\n return result;\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-18T12:31:17.817", "Id": "220463", "ParentId": "217792", "Score": "2" } } ]
{ "AcceptedAnswerId": "217797", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-20T19:47:25.720", "Id": "217792", "Score": "4", "Tags": [ "c#", "beginner" ], "Title": "two integers one line calculator" }
217792
<blockquote> <p>There are N gas stations along a circular route, where the amount of gas at station i is gas[i].</p> <p>You have a car with an unlimited gas tank and it costs cost[i] of gas to travel from station i to its next station (i+1). You begin the journey with an empty tank at one of the gas stations.</p> <p>Return the starting gas station's index if you can travel around the circuit once in the clockwise direction, otherwise return -1.</p> <p>Note:</p> <p>If there exists a solution, it is guaranteed to be unique. Both input arrays are non-empty and have the same length. Each element in the input arrays is a non-negative integer. Example 1:</p> <p>Input: gas = [1,2,3,4,5] cost = [3,4,5,1,2]</p> <p>Output: 3</p> <p>Explanation: Start at station 3 (index 3) and fill up with 4 unit of gas. Your tank = 0 + 4 = 4 Travel to station 4. Your tank = 4 - 1 + 5 = 8 Travel to station 0. Your tank = 8 - 2 + 1 = 7 Travel to station 1. Your tank = 7 - 3 + 2 = 6 Travel to station 2. Your tank = 6 - 4 + 3 = 5 Travel to station 3. The cost is 5. Your gas is just enough to travel back to station 3. Therefore, return 3 as the starting index. Example 2:</p> <p>Input: gas = [2,3,4] cost = [3,4,3]</p> <p>Output: -1</p> <p>Explanation: You can't start at station 0 or 1, as there is not enough gas to travel to the next station. Let's start at station 2 and fill up with 4 unit of gas. Your tank = 0 + 4 = 4 Travel to station 0. Your tank = 4 - 3 + 2 = 3 Travel to station 1. Your tank = 3 - 3 + 3 = 3 You cannot travel back to station 2, as it requires 4 unit of gas but you only have 3. Therefore, you can't travel around the circuit once no matter where you start.</p> </blockquote> <p>Here is my solution:</p> <pre><code>public class Solution { public int CanCompleteCircuit(int[] gas, int[] cost) { int startIndex = 0; int tank = 0; int diff= 0; int sum =0; for(int i=0;i &lt; gas.Length; i++) { diff = gas[i] - cost[i]; sum += diff; if(tank + diff &lt; 0) { startIndex = i+1; tank = 0; } else { tank += diff; } } if(sum &lt; 0) { return -1; } else { return startIndex; } } } </code></pre> <p>Please review code runtime and memory. Any other comments are welcome!</p>
[]
[ { "body": "<p>Your code nicely exploits all the constraints from the instructions.</p>\n\n<p>It runs in linear time, which is much better than the naive approach, which would run in quadratic time.</p>\n\n<p>It doesn't need any space other than a few local variables. Perfect.</p>\n\n<p>Without further explanation the code is a bit hard to follow because of the many variables, and it is not entirely clear what <code>sum</code> and <code>diff</code> are exactly. Sure, <code>sum</code> holds a sum, but <em>of what</em>?</p>\n\n<p>The <code>diff</code> variable should move inside the <code>for</code> loop since it is only needed there.</p>\n\n<p>Instead of <code>tank + diff &lt; 0</code>, you could also write <code>tank &lt; diff</code>, but since you later compute <code>tank + diff</code>, having this common subexpression in the code is actually useful. You could also combine the expressions: just execute <code>tank += diff</code>, and if there's a negative amount of gas in the tank after that, reset it to zero. It's impossible in the real world to have negative amounts of gas in the tank, but it would make the code shorter.</p>\n\n<p>For understanding the algorithm I would have preferred a variant that has two <code>for</code> loops. In the first loop, just compute the sum. In the second loop, determine the starting index. That way, there's fewer variables who can confuse me, the human reader. But if you're going for execution speed, you approach is perfect, again.</p>\n\n<p>I would have preferred a short introduction about how you constructed your algorithm. Learning the ideas and then going from ideas to code is often easier than going backwards from the code to the underlying ideas.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-22T08:04:47.710", "Id": "217872", "ParentId": "217793", "Score": "1" } } ]
{ "AcceptedAnswerId": "217872", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-20T20:16:55.823", "Id": "217793", "Score": "3", "Tags": [ "c#", "programming-challenge" ], "Title": "LeetCode gas station implementation" }
217793
<p>I have a Document Name Table in my SQL database and Files in the Content folder. I have two lists: <code>ListOfFileNamesSavedInTheDB</code> and <code>ListOfFileNamesInTheFolder</code>.</p> <p>Basically, I am getting all file names saved in the Database and checking if it exists in the Folder, and if not, delete the file name from the database.</p> <pre><code> var clientDocList = documentRepository.Documents.Where(c =&gt; c.ClientID == clientID).ToList(); if (Directory.Exists(directoryPath)) { string[] fileList = Directory.GetFiles(directoryPath).Select(Path.GetFileName).ToArray(); bool fileNotExist = false; foreach (var file in fileList) { foreach(var clientDoc in clientDocList) { if (clientDoc.DocFileName.Trim().ToUpper()==file.ToUpper().Trim()) { fileNotExist = false; break; } } if (fileNotExist) { //Delete file name from Database } } } </code></pre> <p>The code I have written works fine, this inquiry being purely for educational purposes. I want to know how others would do this better and cleaner. I especially hate the way I use two <code>for</code> loops to get data. There has to be a more efficient way.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-21T08:08:44.803", "Id": "421453", "Score": "0", "body": "The title of your question is misleading because the code that is necessary to delete something isn't posted. This means that your question lacks context, consequently I vote-to-close it. Please post the complete method." } ]
[ { "body": "<p>First thing I'd suggest is make the 2 lists the same type(string). Now the file list can be an exclusion list that contains only the filenames that aren't in the database. Something like this should work:</p>\n\n<pre><code> var clientDocList = documentRepository\n .Documents\n .Where(c =&gt; c.ClientID == clientID)\n .Select(d =&gt; d.DocFileName\n .Trim()\n .ToUpper()).ToList();\n\n var fileExclusionList = Directory\n .GetFiles(directoryPath)\n .Select(x =&gt; Path.GetFileName(x)\n .Trim()\n .ToUpper())\n .Except(clientDocList).ToArray();\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-21T06:10:17.637", "Id": "421449", "Score": "1", "body": "This code would be easier to understand if it were split into several lines." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-21T07:58:37.287", "Id": "421451", "Score": "0", "body": "Thank you for your help Tinstaafl, but it is not working. is says 'Path.GetFileName(string)' is a method, which is not valid in the given context. I tried this var fileExclusionList = Directory.GetFiles(directoryPath).Select(Path.GetFileName).Except(clientDocList).ToArray(); But it says IEnumerable<string>' does not contain a definition for 'Except' and the best extension method overload" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-21T11:04:40.300", "Id": "421477", "Score": "0", "body": "@AliAzra - It looks to me the problem is with using `Path.GetFileName` without passing in a string. My original code just copied yours and I didn't see that bug. I've corrected my code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-21T11:04:57.513", "Id": "421478", "Score": "0", "body": "@RolandIllig - done." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-21T13:06:50.083", "Id": "421488", "Score": "0", "body": "Thank you Tinstaffl, I really appreciate all your help but still, I am having the same problem. Query return type is IEnumerable<string>' and Except(clientDocList) is not defined with IEnumerable. I used ToList() and it worked." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-21T17:22:21.640", "Id": "421511", "Score": "0", "body": "@AliAzra - I think you're using older version of the library. In the newest version IEnumerable<string> does have Except extension method." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-21T01:20:33.577", "Id": "217806", "ParentId": "217799", "Score": "0" } } ]
{ "AcceptedAnswerId": "217806", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-20T22:41:54.827", "Id": "217799", "Score": "0", "Tags": [ "c#", "linq", "file-system" ], "Title": "LINQ or Lambda for two foreach query" }
217799
<p>In React, it is quite common for me to have something similar to the following.</p> <pre><code>async componentDidMount() { try { this.setState({ isLoading: true }) const { data } = await axios.get('...') this.setState({ data }) } catch(error) { handleError(error) } finally { this.setState({ isLoading: false }) } } </code></pre> <p>This is great because the cleanup code (<code>isLoading: false</code>) is DRY. That is, until I try to cancel network requests on unmount. That code would look like this:</p> <pre><code>async componentDidMount() { try { this.axiosCancelTokenSource = axios.CancelToken.source() this.setState({ isLoading: true }) const { data } = await axios.get('...', { cancelToken: this.axiosCancelTokenSource.token, }) this.setState({ data }) } catch(error) { if (axios.isCancel(error)) return handleError(error) } finally { this.setState({ isLoading: false }) } } componentWillUnmount() { if (this.axiosCancelTokenSource) this.axiosCancelTokenSource.cancel() } </code></pre> <p>The problem with this is that it will <code>setState</code> after the component unmounts, which React will warn againts.</p> <p>As far as I see it, these are my options for dealing with this:</p> <ol> <li><p>Ignore the warning. React gives a warning when you <code>setState</code> after unmount because it indicates a memory leak (in this case, the lingering network request, if not cancelled). If the network request is cancelled, there is still a <code>setState</code> after unmount, but just to set a flag. There is no more lingering network request. It should be safe to ignore the warning in this case, but it doesn't feel right.</p></li> <li><p>Check what error was thrown in the <code>finally</code> block and add the same <code>if</code> statement as the <code>catch</code> block. This seems incredibly hacky and would require extra code to save the error from the catch block.</p></li> <li><p>Check if the component is mounted in the <code>finally</code> block. This is also hacky and requires boilerplate code to update a <code>this.isMounted</code> flag.</p></li> <li><p>Put the cleanup code at the end of <code>try</code> and after the condition in <code>catch</code>. This is not DRY. Humans are also very forgetful; I cannot count how many times I have forgotten to set <code>isLoading = false</code> in catch.</p></li> <li><p>Define a <code>cleanup()</code> function before the <code>try</code> and call it in <code>try</code> and <code>catch</code>. This is a decent option, but requires extra function calls, making it harder to follow.</p></li> </ol> <p>So far, it looks like the first or fifth options are best, depending on how much you care about seeing warning messages. Am I missing any good options?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-29T09:20:29.160", "Id": "423700", "Score": "0", "body": "IMHO 5th option but that's just personal opinion" } ]
[ { "body": "<blockquote>\n <p>Ignore the warning. React gives a warning when you setState after\n unmount because it indicates a memory leak (in this case, the\n lingering network request, if not canceled). If the network request\n is canceled, there is still a setState after unmount, but just to set\n a flag. There is no more lingering network request. It should be safe\n to ignore the warning in this case, but it doesn't feel right.</p>\n</blockquote>\n\n<p>Bad idea. Thing is, by the time the request will resolve, setState might be triggered on an unmounted component. And warning turns to error.</p>\n\n<blockquote>\n <p>Check what error was thrown in the finally block and add the same if\n statement as the catch block. This seems incredibly hacky and would\n require extra code to save the error from the catch block.</p>\n</blockquote>\n\n<p>Meh :\\</p>\n\n<blockquote>\n <p>Check if the component is mounted in the finally block. This is also\n hacky and requires boilerplate code to update a this.isMounted flag.</p>\n</blockquote>\n\n<p><a href=\"https://reactjs.org/blog/2015/12/16/ismounted-antipattern.html\" rel=\"nofollow noreferrer\">It's an Anti-pattern</a></p>\n\n<p><a href=\"https://i.stack.imgur.com/IRJFw.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/IRJFw.jpg\" alt=\"enter image description here\"></a></p>\n\n<blockquote>\n <p>Put the cleanup code at the end of try and after the condition in\n catch. This is not DRY. Humans are also very forgetful; I cannot count\n how many times I have forgotten to set isLoading = false in catch.</p>\n</blockquote>\n\n<p>This</p>\n\n<blockquote>\n <p>Define a cleanup() function before the try and call it in try and\n catch. This is a decent option, but requires extra function calls,\n making it harder to follow.</p>\n</blockquote>\n\n<p>And that, are pretty much taking the same turn with different gear.</p>\n\n<p><strong>Suggestion from <a href=\"https://reactjs.org/blog/2015/12/16/ismounted-antipattern.html\" rel=\"nofollow noreferrer\">React Blog</a></strong></p>\n\n<p>If you use ES6 promises, you may need to wrap your promise in order to make it cancelable.</p>\n\n<pre><code>const cancelablePromise = makeCancelable(\n new Promise(r =&gt; component.setState({...}))\n);\n\ncancelablePromise\n .promise\n .then(() =&gt; console.log('resolved'))\n .catch((reason) =&gt; console.log('isCanceled', reason.isCanceled));\n\ncancelablePromise.cancel(); // Cancel the promise\n</code></pre>\n\n<p>Where makeCancelable was originally defined by @istarkov as:</p>\n\n<pre><code>const makeCancelable = (promise) =&gt; {\n let hasCanceled_ = false;\n\n const wrappedPromise = new Promise((resolve, reject) =&gt; {\n promise.then(\n val =&gt; hasCanceled_ ? reject({isCanceled: true}) : resolve(val),\n error =&gt; hasCanceled_ ? reject({isCanceled: true}) : reject(error)\n );\n });\n\n return {\n promise: wrappedPromise,\n cancel() {\n hasCanceled_ = true;\n },\n };\n};\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-30T00:43:31.880", "Id": "423815", "Score": "0", "body": "Your answer might be better if you provided at least a small part of the anti-pattern link in your own words around the line." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-30T17:51:19.050", "Id": "423924", "Score": "0", "body": "Thanks for the answer! Under what circumstances will the \"setState in unmounted component\" throw an error not a warning? You say it's when the component is not mounted, but that's the whole point of the warning. I fail to see when it becomes an error. Also, where's the shame in considering an anti-pattern and deciding against it?" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-29T20:29:02.770", "Id": "219391", "ParentId": "217802", "Score": "2" } }, { "body": "<h2>Finally only for unconditional execution</h2>\n\n<p>I am not a React user, and as such I may be missing something unique to the React way. </p>\n\n<p>It seams very strange that you use a <code>finally</code> block to execute code you don't want to guarantee execution.</p>\n\n<blockquote>\n <p>As far as I see it, these are my options for dealing with this:</p>\n</blockquote>\n\n<p>You list 5 options... Why not a 6th?</p>\n\n<ol start=\"6\">\n<li>Remove the <code>finally { ... }</code> block setting the is loading state after the <code>try catch</code> and having the catch return if unmounted.</li>\n</ol>\n\n<p>If I ignore React the <em>\"Idomatic way to ignore <code>finally</code> block...\"</em> is to remove it.</p>\n\n<p>eg</p>\n\n<pre><code>async componentDidMount() {\n try {\n this.axiosCancelTokenSource = axios.CancelToken.source()\n this.setState({ isLoading: true })\n const { data } = await axios.get('...', {\n cancelToken: this.axiosCancelTokenSource.token,\n })\n this.setState({ data })\n } catch(error) {\n if (axios.isCancel(error)) return\n handleError(error)\n }\n this.setState({ isLoading: false })\n}\n</code></pre>\n\n<h3>Catch only known exceptions</h3>\n\n<p><code>try ... catch</code> should only be used to wrap code that is known to throw a known set of exceptions (in this case network, data, or forced exceptions related to <code>axios.get</code>). </p>\n\n<p>Wrapping all code automatically in a <code>try catch</code> means that it is possible to catch unknown exceptions (AKA BUGS) effectively hiding/obscuring the erroneous behavior during the development cycle.</p>\n\n<h3>Example</h3>\n\n<p>Removing the <code>try</code> from around known safe code, catching only exceptions related to the functions role.</p>\n\n<pre><code>// pseudo code as example only\nasync mount() {\n loading = (isLoading = true) =&gt; this.setState({isLoading});\n cancelToken = axios.CancelToken.source();\n loading();\n try {\n this.setState({data: (await axios.get(\"...\", {cancelToken})).data});\n } catch (e) {\n if (axios.isCancel(e)) { return }\n handleError(e);\n } \n loading(false);\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-30T17:46:42.893", "Id": "423923", "Score": "0", "body": "Can't believe I didn't think of this." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-30T15:40:38.640", "Id": "219439", "ParentId": "217802", "Score": "1" } } ]
{ "AcceptedAnswerId": "219439", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-20T23:30:53.350", "Id": "217802", "Score": "3", "Tags": [ "javascript", "react.js", "axios" ], "Title": "Idomatic way to ignore `finally` block after cancelling network request" }
217802
<p>I have implemented a min heap in C++, and I want to improve it in every possible way. Could you please review it and let me know your suggestions/comments?</p> <pre><code>#include &lt;iostream&gt; #include &lt;vector&gt; #include &lt;algorithm&gt; // std::swap class MinHeap { private: std::vector&lt;int&gt; heap; void heapify(int); int parent(int); int left(int); int right(int); public: void insert(int); int extractMin(); }; // heapifies down the index-i void MinHeap::heapify(int i) { int l = left(i); int r = right(i); // find the smallest amongst the parent, it's left &amp; right child int smallest; smallest = (l != -1 &amp;&amp; heap[l] &lt; heap[i]) ? l : i; smallest = (r != -1 &amp;&amp; heap[r] &lt; heap[smallest]) ? r : smallest; // If heap[i] (parent) is the smallest, then it is already a Heap! if (smallest != i) { std::swap(heap[i], heap[smallest]); heapify(smallest); } } // Returns the index of the left-child of the ith element // Returns -1 if the index &gt; heap size int MinHeap::left(int i) { int l = (((2 * i) + 1) &lt; heap.size() - 1) ? (2 * i) + 1 : -1; return l; } // Returns the index of the Right-child of the ith element // Returns -1 if the index &gt; heap size int MinHeap::right(int i) { int r = (((2 * i) + 2) &lt; heap.size() - 1)? (2 * i) + 2 : -1; return r; } // Returns the index of the Parent of the ith element // Returns -1 if parent-index &lt; 0 int MinHeap::parent(int i) { int p = (((i - 1) / 2) &gt;= 0)? (i - 1) / 2 : -1; return p; } // Returns the minimum element from the heap and also deletes it from the heap int MinHeap::extractMin() { // back-up the root, it's the min value int min = heap[0]; // copy the value of the very-last element into the root and delete the last element heap[0] = heap.back(); heap.pop_back(); // heapify-down the root heapify(0); return min; } // inserts a value at the right-spot in the heap, ensures the heap property is maintained. void MinHeap::insert(int value) { // insert the new element at the end of heap heap.push_back(value); // bubble-up the new value to its right position, thus maintaining the heap property int i = heap.size() - 1; while (heap[parent(i)] &gt; heap[i]) { std::swap(heap[parent(i)], heap[i]); i = parent(i); } } </code></pre>
[]
[ { "body": "<ul>\n<li><p>Overall, LGTM.</p></li>\n<li><p>A protection against negative indices being passed to <code>parent</code> doesn't worth the effort. <code>parent</code> is a private method, so you are in control of the indices at all times. A strong indication that the protection is not needed is the fact that <code>insert</code> doesn't bother to test the return value for validity.</p></li>\n<li><p>Along the same line, <code>left()</code> and <code>right()</code> returning <code>-1</code> doesn't look like a good idea. Effectively, you test the same condition twice: <code>((2 * i) + 1) &lt; heap.size() - 1</code> in <code>left</code>, and <code>l != -1</code> in <code>heapify</code>. </p></li>\n<li><p>Notice that anytime <code>right</code> is valid, <code>left</code> is also valid. That allows a certain optimization (see below).</p></li>\n<li><p>C++ is very good in recognizing tail recursion and optimizing it out. I strongly recommend to do it explicitly anyway.</p></li>\n<li><p>Combining the three bullets above, consider</p>\n\n<pre><code>void heapify(int i)\n{\n while ((r = right(i)) &lt; heap.size()) {\n follow your swapping logic\n }\n\n if ((l = left(i)) &lt; heap_size()) { // No need to loop - it may only happen once!\n if (heap[l] &lt; heap[i]) {\n std::swap(heap[i], heap[l]);\n }\n }\n}\n</code></pre></li>\n<li><p><code>MinHeap::heapify</code> is a misnomer, and somewhat confusing. Usually <code>heapify</code> refers to the process of turning an array into a heap. Your method is normally called <code>sift_down</code>.</p></li>\n<li><p>Too many comments to my taste.</p></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-21T05:34:25.467", "Id": "217816", "ParentId": "217803", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-21T00:31:55.553", "Id": "217803", "Score": "4", "Tags": [ "c++", "c++11", "heap" ], "Title": "Min heap C++ implementation" }
217803
<p>When initializing a struct in C, we can allocate memory inside the <code>main</code> function or within another function and return a pointer to the newly created struct. This first example shows the latter; memory is allocated in <code>Buffer_create</code> and a pointer is returned:</p> <pre><code>#include &lt;stdio.h&gt; #include "buffer.h" int main(int argc, char *argv[]) { struct Buffer *tx_buffer = Buffer_create(8); Buffer_destroy(tx_buffer); return 0; } </code></pre> <p>And this one shows how all memory allocations can be done within the <code>main</code> function:</p> <pre><code>#include &lt;stdio.h&gt; #include "buffer.h" int main(int argc, char *argv[]) { uint8_t *ptr_rx_buffer = malloc(sizeof(uint8_t)*8); struct Buffer *rx_buffer = malloc(sizeof(struct Buffer)); Buffer2_create(rx_buffer, ptr_rx_buffer, 8); Buffer2_destroy(rx_buffer); return 0; } </code></pre> <p>And here are the contents of the header file <code>buffer.h</code>:</p> <pre><code>#ifndef _buffer_h #define _buffer_h #include &lt;stdint.h&gt; #include &lt;stdlib.h&gt; struct Buffer { uint8_t *buffer; size_t size; }; struct Buffer *Buffer_create(size_t size); void Buffer_destroy(struct Buffer *who); void Buffer2_create(struct Buffer *who, uint8_t *buffer, size_t size); void Buffer2_destroy(struct Buffer *who); #endif </code></pre> <p>And <code>buffer.c</code>:</p> <pre><code>#include &lt;stdint.h&gt; #include &lt;assert.h&gt; #include &lt;stdlib.h&gt; #include "buffer.h" struct Buffer *Buffer_create(size_t size) { struct Buffer *who = malloc(sizeof(struct Buffer)); assert(who != NULL); who-&gt;buffer = malloc(sizeof(uint8_t)*size); who-&gt;size = size; return who; } void Buffer_destroy(struct Buffer *who) { assert(who != NULL); free(who-&gt;buffer); free(who); } void Buffer2_create(struct Buffer *who, uint8_t *buffer, size_t size) { assert(who != NULL); who-&gt;buffer = buffer; who-&gt;size = size; } void Buffer2_destroy(struct Buffer *who) { assert(who != NULL); free(who-&gt;buffer); free(who); } </code></pre> <p><strong>The Result</strong></p> <p>Both approaches work and the executable files for both end up being the same size.</p> <p><strong>My Question</strong></p> <p>Will either of these approaches result in memory leaks or poor performance?</p>
[]
[ { "body": "<p>Looking at the performance, the two versions should perform just about identically. The second version has one less call/return, which can save a couple of CPU cycles, but if you have it multiple places in your code the additional code bytes and cache misses can overshadow that. Either way you probably won't notice a difference.</p>\n\n<p>Looking at readability and maintainability, the first version is much better. You know at a glance what it is doing (rather than looking at several lines to figure it all out), you won't forget any important steps, and error checking is much easier since most of it can be handled in one place (excepting the last check for successful creation of the buffer). Debugging can also be easier, since you can set a breakpoint on the creation or destruction functions if necessary.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-21T04:56:18.007", "Id": "217812", "ParentId": "217807", "Score": "11" } }, { "body": "<p>In the first case, the caller is not given any control over allocation. This limits freedom and (therefore) performance: there is no control over the number of dynamic allocations or over which memory is used for what purpose, and there are limits on how the handle to the buffer can be stored (the returned pointer to <code>Buffer</code> must be kept around somehow, even if we would really just want to store the <code>Buffer</code> by value and avoid some unnecessary double-indirection).</p>\n\n<p>In the second case, the caller does have control, but <code>Buffer2_destroy</code> makes a very limiting assumption about how the memory was allocated so in the end the caller still has no choice. Of course by looking into the implementation details, one could see that simply not calling <code>Buffer2_destroy</code> enables some freedom again, but this would probably be considered a hack. All in all this approach violates the guideline \"allocate and free memory in the same module, at the same level of abstraction\", and doesn't get much in return.</p>\n\n<p>Practically what a user of some buffer may want to do is for example:</p>\n\n<ul>\n<li>Having the <code>Buffer</code> as a local variable but its data <code>malloc</code>-ed.</li>\n<li>Having the <code>Buffer</code> as a local variable and making its data refer to a local array.</li>\n<li>Save the <code>Buffer</code> into some other struct or array (by value, not a pointer to a <code>Buffer</code> which then points to the data).</li>\n<li>Using (part of) a static array as the data.</li>\n<li>Various other such combinations..</li>\n<li>Allocate both the buffer data and the instance of <code>Buffer</code> in the same allocation.</li>\n</ul>\n\n<p>Which is why a common advice is, where possible, do not allocate or deallocate memory, use memory supplied by the caller. This applies especially to performance-sensitive settings, where \"secret <code>malloc</code>\" is not appreciated, and custom allocators are commonly used.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-21T08:26:17.223", "Id": "421454", "Score": "0", "body": "I think this answer would benefit greatly from a code example." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-21T08:38:42.150", "Id": "421455", "Score": "0", "body": "@Marc.2377 what would you like to see?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-21T09:30:43.620", "Id": "421458", "Score": "0", "body": "Thank you so much for your answer @harold. I am not sure if I follow with the issue of double-indirection: I need to pass this buffer around other functions to manipulate it, and I thought it would be best to pass it as a `struct` and \"unpack\" it inside each function that uses it, rather than passing both a pointer to the data (the array) and a pointer to the size of the array to each function that uses the buffer. I can add an example to clarify my question if you wish." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-21T09:33:11.610", "Id": "421459", "Score": "0", "body": "@harold, furthermore, I understand that the principles you suggest ensure more flexibility, but by allocating and freeing memory in `main` instead of using these `Buffer_create` and `Buffer_destroy` functions, won't I be repeating myself too often, resulting in more lines of code and more chances of errors?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-21T10:21:43.510", "Id": "421470", "Score": "1", "body": "@David passing it around as a struct does not necessarily imply passing around a pointer to it, it could be passed around by value, or more importantly, accessed without an extraneous level of indirection when buffers are stored in other data structures (but maybe that's not a concern here, it depends). The surface area for bugs would increase yes, such is the price for the flexibility and its performance benefits, unfortunately." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-21T11:04:14.430", "Id": "421476", "Score": "0", "body": "@harold, what do you mean by `passed around by value`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-21T11:06:53.350", "Id": "421479", "Score": "0", "body": "@David I mean working with `struct Buffer` rather than `struct Buffer*`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-21T11:14:40.287", "Id": "421480", "Score": "0", "body": "@harold, but isn't it better in general to pass a struct through a pointer rather than by value?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-21T11:45:14.227", "Id": "421482", "Score": "2", "body": "@David well it depends, obviously it is not so good to copy large structs, but this struct is small. Returning by value is good (avoids allocation), storing the value itself is good (avoids indirection), and then you still have the choice to pass its address to some other function" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-21T16:53:47.150", "Id": "421509", "Score": "0", "body": "@harold, thank you for thoroughly explaining the pros and cons of the different solutions." } ], "meta_data": { "CommentCount": "10", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-21T05:06:35.190", "Id": "217813", "ParentId": "217807", "Score": "4" } }, { "body": "<p>In C, <a href=\"https://wiki.sei.cmu.edu/confluence/plugins/servlet/mobile?contentId=87152150#content/view/87152150\" rel=\"noreferrer\">initialization and destruction should be done at the same level of abstraction</a>. This is important because it defines who is responsible for the memory.</p>\n\n<p>There are two good ways to follow this guideline:</p>\n\n<ul>\n<li><p>Allocate and deallocate in the API's init/destroy functions (your first code example). <code>fopen</code> does this although it maps files rather than regular memory.</p>\n\n<pre><code>type *t = CHECK(init_t());\n...\nCHECK(destroy_t(t));\n</code></pre></li>\n<li><p>Allocate and deallocate at the call site before/after the API calls. <code>pthread_mutex_create</code> does this.</p>\n\n<pre><code>type t;\nCHECK(init_t(&amp;t));\n...\nCHECK(destroy_t(&amp;t));\n</code></pre></li>\n</ul>\n\n<p>It is <strong>not</strong> acceptable to allocate in an initializer and then free outside. There are many examples of this pattern in the Windows API, and it is extremely error prone. You have to check the docs for which deallocation function needs to be called each time.</p>\n\n<p>I personally prefer to allocate/deallocate outside the API. That way I can use automatic variables and the return value of the initializer can be a specific error code.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-21T09:36:06.667", "Id": "421462", "Score": "0", "body": "Thank you for your answer. In my example, which would be the API? The `main` function, or the functions provided by `buffer.h`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-21T09:42:35.007", "Id": "421464", "Score": "0", "body": "You are writing a programming interface for a buffer, so the buffer is the API. main is the application that uses the API." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-21T09:48:19.687", "Id": "421466", "Score": "0", "body": "Thank you for further clarifying it. If I understand correctly, by freeing up the return value for an error code, you're suggesting that I could make `Buffer2_create` and `Buffer2_destroy` of type `int` instead of `void` and in the end return a `0` or some error code?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-21T09:58:27.907", "Id": "421467", "Score": "1", "body": "@David that's right. Retuning an error code is a simple and proven idiom in C. In general, it's best to separate your successful return value and your error output value." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-21T23:12:11.053", "Id": "421553", "Score": "0", "body": "In other words, something like `statvfs(argv[1],&fs_usage);`, where in main code we'd declare `fs_usage` of type `struct statvfs` but `statvfs` would allocate memory for that - that's the proper way to do it, correct ? Function takes an argument what to allocate and returns exit status" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-21T09:33:31.353", "Id": "217822", "ParentId": "217807", "Score": "10" } } ]
{ "AcceptedAnswerId": "217822", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-21T02:12:46.077", "Id": "217807", "Score": "7", "Tags": [ "performance", "c", "comparative-review", "memory-management", "pointers" ], "Title": "malloc in main() or malloc in another function: allocating memory for a struct and its members" }
217807
<p>I am working on this question and have my answer as following?</p> <blockquote> <p>A string is encoded by performing the following sequence of actions:</p> <ol> <li>Replace each character with its ASCII value representation.</li> <li>Reverse the string.</li> </ol> <p>For example, the table below shows the conversion from the string &quot;<code>HelloWorld</code>&quot; to the ASCII string &quot;<code>7210110810811187111114108100</code>&quot;:</p> <pre><code>Character H e l l o W o r l d ASCII Value 72 101 108 108 111 87 111 114 108 100 </code></pre> <p>The ASCII string is then reversed to get the encoded string &quot;<code>0018014111117811180180110127</code>&quot;.</p> <p>The characters in encoded string are within the range 10 - 126 which include special characters.</p> </blockquote> <p><strong>Example:</strong><br/> <code>asciidecode('111111')</code> =&gt; <code>'\x0b\x0b\x0b'</code> or <code>'oo'</code><br> because we can split the input <code>111111</code> (after reverse back: '111111') like <code>11,11,11</code> or <code>111,111</code></p> <pre><code>from typing import List def asciidecode(self, s: str) -&gt; List: if not s: return '' s = s[::-1] n = len(s) ch_map = {str(i): chr(i) for i in range(10, 127)} dp = [[''] for _ in range(n + 1)] dp[2] = [ch_map[s[:2]]] if s[:2] in ch_map else '' dp[3] = [ch_map[s[:3]]] if s[:3] in ch_map else '' dp[4] = [dp[2][0] + ch_map[s[2:4]]] if s[2:4] in ch_map else '' for i in range(5, n + 1): p1 = s[i - 2: i] p2 = s[i - 3: i] tmp = [] if p1 in ch_map: tmp += [i + ch_map[p1] for i in dp[i - 2]] if p2 in ch_map: tmp += [i + ch_map[p2] for i in dp[i - 3]] dp[i] = tmp return dp[-1] </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-21T19:51:49.743", "Id": "421523", "Score": "0", "body": "`print(asciiencode('HelloWorld'))` doesn't work at all!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-21T20:01:06.493", "Id": "421525", "Score": "0", "body": "the question is input from a decode asciicode like \"0018014111117811180180110127\", need to write a function to get original string, but i will update question to make more clear" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-21T20:10:27.200", "Id": "421526", "Score": "0", "body": "Sorry for the misunderstanding. I would have expected the decoding function to be called `asciidecode()` instead." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-21T20:37:24.810", "Id": "421529", "Score": "0", "body": "i see. wil update my code" } ]
[ { "body": "<ol>\n<li><code>return ''</code> doesn't have the type <code>List</code>.</li>\n<li><code>List</code> means <code>List[Any]</code>, you should use <code>List[str]</code>.</li>\n<li><p>Your variable names are garbage.</p>\n\n<ul>\n<li><code>s</code> -> <code>string</code></li>\n<li><code>n</code> -> <code>length</code></li>\n<li><code>ch_map</code> -> <code>char_map</code> or <code>character_map</code></li>\n<li><code>dp</code> -> what does this even mean?</li>\n<li><code>p1</code> -> <code>position_1</code>?</li>\n</ul></li>\n<li><p>Don't put <code>return</code> statements on the same line as an <code>if</code>.</p></li>\n<li>Again strings shouldn't be assigend to lists, yes you can iterate over them because they're both sequences. But they're not the same type. <code>[ch_map[s[:2]]] if s[:2] in char_map else ''</code></li>\n<li><code>ch_map</code> should be a constant outside the function.</li>\n<li>It's far easier to understand your code if it's written using recursion.</li>\n<li>Recursion has some problems, and so it should be written in a way that allows you to easily convert it to a while loop.</li>\n</ol>\n\n\n\n<pre><code>CHAR_MAP = {str(i): chr(i) for i in range(10, 127)}\n\n\ndef asciidecode(string: str) -&gt; List[str]:\n if not string:\n return []\n string = string[::-1]\n length = len(string)\n\n def inner(index):\n if index == length:\n yield ''\n else:\n for size in (2, 3):\n if length &lt; index + size:\n break\n letter = CHAR_MAP.get(string[index:index + size])\n if letter is not None:\n for word in inner(index + size):\n yield letter + word\n return list(inner(0))\n\n\ndef asciidecode_pre_while(string: str) -&gt; List[str]:\n if not string:\n return []\n string = string[::-1]\n length = len(string)\n output = []\n\n def inner(index, word):\n if index == length:\n output.append(word)\n return\n\n for size in (2, 3):\n if length &lt; index + size:\n break\n letter = CHAR_MAP.get(string[index:index + size])\n if letter is not None:\n inner(index + size, word + letter)\n inner(0, '')\n return output\n</code></pre>\n\n<p>From the second one it's easy to convert it to a while loop:</p>\n\n<pre><code>CHAR_MAP = {str(i): chr(i) for i in range(10, 127)}\n\n\ndef asciidecode(string: str) -&gt; List[str]:\n if not string:\n return []\n string = string[::-1]\n length = len(string)\n output = []\n\n stack = [(0, '')]\n while stack:\n index, word = stack.pop()\n if index == length:\n output.append(word)\n continue\n\n for size in (2, 3):\n if length &lt; index + size:\n break\n letter = CHAR_MAP.get(string[index:index + size])\n if letter is not None:\n stack.append((index + size, word + letter))\n return output\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-24T18:50:02.387", "Id": "423070", "Score": "0", "body": "so what is time complexity?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-24T18:56:28.473", "Id": "423071", "Score": "0", "body": "@A.Lee When did you or I say anything about time complexity?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-24T19:00:22.030", "Id": "423073", "Score": "0", "body": "i mean for your while loop solution what is time complexity? O(2 ^ n)?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-24T19:01:46.147", "Id": "423074", "Score": "0", "body": "@A.Lee You've not answered my question." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-24T19:24:08.287", "Id": "423078", "Score": "0", "body": "i do not think I mention anything about time complexity on my post but want to know what is it for your while loop solution" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-24T20:00:33.460", "Id": "423084", "Score": "0", "body": "@A.Lee It's complexities are time-\\$O(2^d)\\$ and memory-\\$O(d^2)\\$, where \\$d\\$ is the size of the largest decoded string." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-24T20:15:47.400", "Id": "423087", "Score": "0", "body": "i see, thank you" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-24T20:42:01.143", "Id": "423091", "Score": "0", "body": "@A.Lee Actually that's wrong. My memory is \\$O(d2^d)\\$ as the maximum output is \\$2^d\\$ values, each with a size of \\$d\\$. Your complexities are time-\\$O(n\\sqrt{2}^n)\\$, memory-\\$O(n^2 \\sqrt{2}^n)\\$. Converting mine in terms of \\$n\\$, for comparison, makes them time-\\$O(\\sqrt{2}^n)\\$ and memory-\\$O(n\\sqrt{2}^n)\\$." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-24T21:12:16.800", "Id": "423092", "Score": "0", "body": "why my complexities is (2‾√)? i loop through 0 to n the worst case is I can only split 2 digit each time until end...running time is O(n/2) => O(n), no?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-24T21:28:47.133", "Id": "423093", "Score": "0", "body": "@A.Lee For short hand `a:b` means \"`dp[a]`'s worst case is b\". Worst case sizes are `2:1`, `3:1`, `4:1`, `5:2`, `6:2`, `7:3`, `8:4`, `9:5`, `10:7`, `11:9`... Simplifying the pattern by changing segments of 3 to 2, you get `2:1`, `4:2`, `6:4`, `8:8`, `10:16`. Which is \\$2^\\frac{n}{2}\\$ aka \\$\\sqrt{2}^n\\$. Whilst this ignores segments of 3, it's still accurate in telling the magnitude. Since the worst case of `dp` is `dp[-1]` so \\$O(\\sqrt{2}^n)\\$ and you loop through this list \\$n\\$ times it becomes \\$O(n\\sqrt{2}^n)\\$." } ], "meta_data": { "CommentCount": "10", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-24T12:55:01.277", "Id": "219015", "ParentId": "217808", "Score": "5" } } ]
{ "AcceptedAnswerId": "219015", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-21T02:40:55.940", "Id": "217808", "Score": "5", "Tags": [ "python", "python-3.x" ], "Title": "ASCII code decode to string" }
217808
<p>I would like a review on just a single class today. More important to me than a review on the class itself, however, is a review of the unit-tests I wrote for it. You see this is my first attempt at writing unit tests with a full test framework.</p> <p>The class in question is called <code>UpgradeButton</code> and is exactly that. It is a button for representing upgrades in my resource management game. The buttons look like this:</p> <p><a href="https://i.stack.imgur.com/lofaZ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/lofaZ.png" alt="picture of button, with green and red lights and text &#39;Oil Production&#39;"></a></p> <p>The boxes along the bottom are updated programatically through the <code>input()</code> and <code>update()</code> functions that indicate what level you are at and what you can purchase. The number of tiers is assigned in the constructor, as is the label.</p> <p><strong><code>UpgradeButton.h</code></strong></p> <pre><code>#pragma once #include "Expressions.h" #include &lt;SFML\Graphics.hpp&gt; #include &lt;string&gt; namespace fleet { class UpgradeButton : public sf::Drawable { public: explicit UpgradeButton(const std::string&amp; newLabel, const sf::Font&amp; font, unsigned short numUpgrades); void setPosition(float x, float y); void setPosition(const sf::Vector2f&amp; position); void setLabelString(const std::string&amp; string); void setCharacterSize(unsigned newSize); void setTextFillColor(const sf::Color&amp; color); const sf::Vector2f&amp; getPosition() const { return button.getPosition(); } const sf::String&amp; getLabelString() const { return label.getString(); } unsigned getCharacterSize() const { return label.getCharacterSize(); } const sf::Color&amp; getTextFillColor() const { return label.getFillColor(); } bool input(const sf::Vector2f&amp; mousePos, bool canAfford); void update(const sf::Vector2f&amp; mousePos, unsigned currentLevel, bool canAfford); private: sf::RectangleShape button{ sf::Vector2f(default_upgrade_width, default_upgrade_height) }; sf::Text label; std::vector&lt;sf::RectangleShape&gt; indicators; void draw(sf::RenderTarget&amp; target, sf::RenderStates states) const override; }; } </code></pre> <p><code>Expressions.h</code> is just a header of <code>constexpr</code> for replacing magic numbers, and as you can see I am using SFML. Version 2.4.2 if it matters. I'd also like to point out that I am aware of the difference between <code>#pragma once</code> and include gaurds. I chose the former because they are less verbose and support by the major compilers. Lastly, it is a small personal project, completely in my control. </p> <p><strong><code>UpgradeButton.cpp</code></strong></p> <pre><code>#include "UpgradeButton.h" namespace fleet { UpgradeButton::UpgradeButton(const std::string&amp; newLabel, const sf::Font&amp; font, unsigned short numUpgrades) : label{ newLabel, font } { float indicatorWidth = default_upgrade_width / numUpgrades; for (unsigned i = 0; i &lt; numUpgrades; ++i) { indicators.emplace_back(sf::RectangleShape(sf::Vector2f(indicatorWidth, default_indicator_height))); } button.setFillColor(sf::Color::Cyan); button.setOutlineThickness(upgrade_button_outline); for (auto&amp; indicator : indicators) { indicator.setFillColor(sf::Color::Cyan); indicator.setOutlineThickness(upgrade_button_outline); } } void UpgradeButton::setPosition(float x, float y) { button.setPosition(x, y); float indicatorX = x; float indicatorY = y + (default_upgrade_height - default_indicator_height); for (auto&amp; indicator : indicators) { indicator.setPosition(indicatorX, indicatorY); indicatorX += indicator.getSize().x; } float labelY = y + default_upgrade_height + upgrade_label_y_offset; label.setPosition(x, labelY); } void UpgradeButton::setPosition(const sf::Vector2f&amp; position) { setPosition(position.x, position.y); } void UpgradeButton::setLabelString(const std::string&amp; string) { label.setString(string); } void UpgradeButton::setCharacterSize(unsigned newSize) { label.setCharacterSize(newSize); } void UpgradeButton::setTextFillColor(const sf::Color&amp; color) { label.setFillColor(color); } bool UpgradeButton::input(const sf::Vector2f&amp; mousePos, bool canAfford) { return canAfford &amp;&amp; button.getGlobalBounds().contains(mousePos); } void UpgradeButton::update(const sf::Vector2f&amp; mousePos, unsigned currentLevel, bool canAfford) { for (unsigned i = 0; i &lt; currentLevel &amp;&amp; i &lt; indicators.size(); ++i) { indicators[i].setFillColor(sf::Color::Green); } for (unsigned i = currentLevel; i &lt; indicators.size(); ++i) { indicators[i].setFillColor(sf::Color::Cyan); } if (currentLevel == indicators.size()) { return; } if (button.getGlobalBounds().contains(mousePos)) { if (canAfford) { indicators[currentLevel].setFillColor(sf::Color::Green); } else { indicators[currentLevel].setFillColor(sf::Color::Red); } } else { indicators[currentLevel].setFillColor(sf::Color::Cyan); } } void UpgradeButton::draw(sf::RenderTarget&amp; target, sf::RenderStates states) const { target.draw(button, states); for (auto&amp; indicator : indicators) { target.draw(indicator, states); } target.draw(label, states); } } </code></pre> <p>Lastly are the tests. I tried to test each of the public functions. The exception was the <code>update()</code> function. It's entire purpose is to update internal unexposed implementation details, so I was unsure how to test it. Or rather uncertain if I even should. I'm using Google Test for my framework and I'm using a test fixture class to construct a default object to test on. My tests all pass.</p> <p><strong><code>UpgradeButtonTests.cpp</code></strong></p> <pre><code>#include "gtest/gtest.h" #include "UpgradeButton.h" #include &lt;SFML\Graphics.hpp&gt; namespace fleet { class UpgradeButtonTest : public testing::Test { protected: UpgradeButton button{ "Test Button", sf::Font(), 5 }; }; TEST_F(UpgradeButtonTest, setPosition) { sf::Vector2f position{ 0.F, 0.F }; button.setPosition(position); ASSERT_FLOAT_EQ(position.x, button.getPosition().x); ASSERT_FLOAT_EQ(position.y, button.getPosition().y); button.setPosition(0.f, 0.f); ASSERT_FLOAT_EQ(position.x, button.getPosition().x); ASSERT_FLOAT_EQ(position.y, button.getPosition().y); button.setPosition(sf::Vector2f()); ASSERT_FLOAT_EQ(position.x, button.getPosition().x); ASSERT_FLOAT_EQ(position.y, button.getPosition().y); button.setPosition(200.F, 200.F); ASSERT_NE(position.x, button.getPosition().x); ASSERT_NE(position.y, button.getPosition().y); } TEST_F(UpgradeButtonTest, setLabelString) { std::string test_string{ "Test Pass" }; ASSERT_STREQ("Test Button", button.getLabelString().toAnsiString().c_str()) &lt;&lt; "Not named Test Button"; button.setLabelString(test_string); ASSERT_STREQ("Test Pass", button.getLabelString().toAnsiString().c_str()) &lt;&lt; test_string &lt;&lt; " not assigned properly"; ASSERT_STREQ(test_string.c_str(), button.getLabelString().toAnsiString().c_str()) &lt;&lt; test_string &lt;&lt; " not assigned properly pt2"; button.setLabelString(""); ASSERT_STREQ("",button.getLabelString().toAnsiString().c_str()) &lt;&lt; "Breaking on empty string"; ASSERT_STRNE(test_string.c_str(), button.getLabelString().toAnsiString().c_str()) &lt;&lt; "Breaking on inequality test"; } TEST_F(UpgradeButtonTest, setCharacterSize) { unsigned test_size{ 52 }; ASSERT_EQ(30, button.getCharacterSize()); ASSERT_NE(test_size, button.getCharacterSize()); button.setCharacterSize(test_size); ASSERT_EQ(52, button.getCharacterSize()); } TEST_F(UpgradeButtonTest, setTextFillColor) { sf::Color color{ sf::Color::Green }; ASSERT_NE(color, button.getTextFillColor()); ASSERT_EQ(sf::Color::White, button.getTextFillColor()); button.setTextFillColor(color); ASSERT_EQ(sf::Color::Green, button.getTextFillColor()); button.setTextFillColor(sf::Color()); ASSERT_EQ(sf::Color::Black, button.getTextFillColor()); } TEST_F(UpgradeButtonTest, input) { ASSERT_TRUE(button.input(sf::Vector2f(), true)); ASSERT_FALSE(button.input(sf::Vector2f(), false)); ASSERT_FALSE(button.input(sf::Vector2f(500.F, 900.F), true)); } } </code></pre>
[]
[ { "body": "<p>I'd suggest that the most important things to test are the constructor, and the <code>update()</code> function. These functions do more complicated things, and have some (currently hidden) requirements that we need to be careful with. </p>\n\n<p>The other functions are mainly setter / getter functions (which we could arguably skip testing entirely), or only easily testable by visual inspection (<code>setPosition()</code>, <code>draw()</code>).</p>\n\n<hr>\n\n<p>When testing the constructor, we should think about the following:</p>\n\n<ul>\n<li><p>The label string: is an empty string ok? Is there a max string size? Do we need to do something special with the text (cut it off, scale it down, or just render the whole thing?).</p>\n\n<p>Assuming the constructor already does what we want, we don't actually need to touch the constructor code. However, adding a test case with an empty string and a test case with a long string is a good idea. This documents the behavior, and proves that it works.</p></li>\n<li><p><code>numUpgrades</code> is used in calculations in the constructor. If it's zero, we'll divide by zero! Also, should there be an upper limit (e.g. a global <code>max_upgrades</code>)?</p>\n\n<p>We can at least guard against a zero argument in the constructor code by throwing an exception, <code>assert</code>ing, terminating the program, or breaking to the debugger. And we should then add a test case to document the behavior. (GTest has <code>ASSERT_DEATH</code> / <code>EXPECT_DEATH</code> and <code>ASSERT_THROW</code> / <code>EXPECT_THROW</code> for such things).</p></li>\n</ul>\n\n<hr>\n\n<p>The <code>input</code> test looks fine, but to be comprehensive we should also test with both parameters resulting in a negative result, i.e.:</p>\n\n<pre><code>ASSERT_FALSE(button.input(sf::Vector2f(500.F, 900.F), false));\n</code></pre>\n\n<hr>\n\n<p>For <code>setPosition()</code> there's not a whole lot else we can test. Checking the position of the label and indicators would just be typing that same code again, which isn't very helpful.</p>\n\n<hr>\n\n<p>We can definitely test the <code>update()</code> function. Looking at each parameter in turn:</p>\n\n<ul>\n<li><p>For <code>mousePos</code>, any valid float is ok (checking for NaN / infinity is probably overkill). So we just need to test the logic that uses it (i.e. cases where the mouse is inside and outside of the button).</p></li>\n<li><p>For <code>currentLevel</code>, we need to establish valid bounds. What if it's zero? What if it's equal to <code>indicatorSize</code>? What if it's greater than indicator size (doing <code>indicators[currentLevel]</code> seems like a bad idea...)? So it looks like we need to add some <code>assert</code>s to the code, and test these cases.</p></li>\n<li><p>For <code>canAfford</code>, we just need to test the logic.</p></li>\n</ul>\n\n<p>To check the logic, we need access to the results, so we might add a <code>std::vector&lt;sf::RectangleShape&gt; const&amp; getIndicators() const;</code> function.</p>\n\n<p>It would also be useful to define constants for the colors, e.g. <code>current_affordable_upgrade_color</code> <code>current_unaffordable_upgrade_color</code>, etc.</p>\n\n<hr>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-21T19:02:44.553", "Id": "421520", "Score": "0", "body": "What would be the best way to handle numUpgrades being zero in the constructor? An exception seems ideal but I'm uncertain." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-21T20:29:41.027", "Id": "421528", "Score": "1", "body": "Exceptions are fine if we're prepared to handle the exception and recover from it. Otherwise there's no benefit over simply terminating the program. Personally I'd go with an `assert` (or an equivalent that also triggers in release builds). If `numUpgrades` is loaded from data, the loading code should ensure that we have a valid value. That way we catch the problem as soon as possible." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-26T03:09:27.737", "Id": "423285", "Score": "0", "body": "I hate not giving you a check as well. I accepted the other answer because it changed my entire approach to unit-testing. I still learned a lot from your answer and appreciate it. Thank you." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-21T17:53:20.673", "Id": "217839", "ParentId": "217810", "Score": "3" } }, { "body": "<p>I would like to talk about two basic topics regarding your tests: test scope and testing what is interesting.</p>\n\n<p>Let me start with the point commonly encountered in tests by people just starting out with testing. Each test seems to test one public method instead of testing one expected behaviour per test. </p>\n\n<p>Should one of your tests fail, you know that something is wrong with a specific method. However, you generally do not know which behaviour or contract is broken. This is especially problematic since a failure of a later Assert might actually be the root cause for the failure of an earlier one. Moreover, your test do not really tell what they test. </p>\n\n<p>Usually, it is a better idea to have one test per expected behaviour and to name it in the Form <code>&lt;situation&gt;_&lt;expected outcome&gt;</code>. E.g. you could have <code>initialfillColor_White</code> or <code>setColor_hasColor</code>.</p>\n\n<p>This way, you know from the test output which behaviour is broken. </p>\n\n<p>Now, regarding what to test. Although testing everything is a good goal, I think that testing trivial logic like a setter that simply forwards to a backing field together with a getter that reads that field is not worth the effort to write the tests. \nWhat should be tested is all interesting behaviour, i.e. the non-trivial behaviour that can be observed from the outside. Unfortunately, that is the behaviour you do not test. It is contained in the <code>setPosition</code> method after the first line and in the <code>update</code> method. Although these methods only change internal state, this state is very visible via the <code>draw</code> method.</p>\n\n<p>I think exposing state via the screen, is generally a problem for ubit testing UI components. The approach I have seen the most so far is to not wrote unit test for displayed components at all and instead to make the view trivial.</p>\n\n<p>One more thing I realized regarding your tests is that they focus on the happy path. It might be good to document in the tests what you expect for the cases of <code>0</code>, <code>0.2</code> and <code>NaN</code> for <code>numUpgrades</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-21T18:18:49.283", "Id": "217840", "ParentId": "217810", "Score": "3" } } ]
{ "AcceptedAnswerId": "217840", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-21T03:15:24.337", "Id": "217810", "Score": "6", "Tags": [ "c++", "unit-testing", "gui", "sfml" ], "Title": "GUI Button Element with Unit Tests" }
217810
<p>C++20 added the <code>span</code> library under the header <code>&lt;span&gt;</code>. As voluntary exercise (not homework!), I spent approximately 1.5 hours implement it under <strong>C++17</strong>. Please tell me if I used stuff that is not available under C++17.</p> <p>Most stuff is in the namespace <code>::my_std</code>, but <code>tuple_size</code>, etc. are in the namespace <code>::std</code>, otherwise they are useless. The <code>::my_std::span_detail</code> namespace contains implementation details that are not to be exposed. </p> <p>I used <a href="http://eel.is/c++draft/span.overview" rel="noreferrer">the C++ standard draft, HTML version</a> as a reference.</p> <p>Here is my code, within 400 lines:</p> <pre><code>// a C++17 implementation of &lt;span&gt; #ifndef INC_SPAN_HPP_c2GLAK6Onz #define INC_SPAN_HPP_c2GLAK6Onz #include &lt;array&gt; // for std::array, etc. #include &lt;cassert&gt; // for assert #include &lt;cstddef&gt; // for std::size_t, etc. #include &lt;iterator&gt; // for std::reverse_iterator, etc. #include &lt;type_traits&gt; // for std::enable_if, etc. #define CONSTRAINT(...) \ std::enable_if_t&lt;(__VA_ARGS__), int&gt; = 0 #define EXPECTS(...) \ assert((__VA_ARGS__)) namespace my_std { // constants // equivalent to std::numeric_limits&lt;std::size_t&gt;::max() inline constexpr std::size_t dynamic_extent = -1; // class template span template &lt;class T, std::size_t N = dynamic_extent&gt; class span; namespace span_detail { // detect specializations of span template &lt;class T&gt; struct is_span :std::false_type {}; template &lt;class T, std::size_t N&gt; struct is_span&lt;span&lt;T, N&gt;&gt; :std::true_type {}; template &lt;class T&gt; inline constexpr bool is_span_v = is_span&lt;T&gt;::value; // detect specializations of std::array template &lt;class T&gt; struct is_array :std::false_type {}; template &lt;class T, std::size_t N&gt; struct is_array&lt;std::array&lt;T, N&gt;&gt; :std::true_type {}; template &lt;class T&gt; inline constexpr bool is_array_v = is_array&lt;T&gt;::value; // ADL-aware data() and size() using std::data; using std::size; template &lt;class C&gt; constexpr decltype(auto) my_data(C&amp; c) { return data(c); } template &lt;class C&gt; constexpr decltype(auto) my_size(C&amp; c) { return size(c); } // detect container template &lt;class C, class = void&gt; struct is_cont :std::false_type {}; template &lt;class C&gt; struct is_cont&lt;C, std::void_t&lt; std::enable_if_t&lt;!is_span_v&lt;C&gt;&gt;, std::enable_if_t&lt;!is_array_v&lt;C&gt;&gt;, std::enable_if_t&lt;!std::is_array_v&lt;C&gt;&gt;, decltype(data(std::declval&lt;C&gt;())), decltype(size(std::declval&lt;C&gt;())) &gt;&gt; :std::true_type {}; template &lt;class C&gt; inline constexpr bool is_cont_v = is_cont&lt;C&gt;::value; } template &lt;class T, std::size_t N&gt; class span { public: // constants and types using element_type = T; using value_type = std::remove_cv_t&lt;T&gt;; using index_type = std::size_t; using difference_type = std::ptrdiff_t; using pointer = T*; using const_pointer = const T*; using reference = T&amp;; using const_reference = const T&amp;; using iterator = T*; using const_iterator = const T*; using reverse_iterator = std::reverse_iterator&lt;iterator&gt;; using const_reverse_iterator = std::reverse_iterator&lt;const_iterator&gt;; static constexpr index_type extent = N; // constructors, copy, and assignment // LWG 3198 applied constexpr span() noexcept : size_{0}, data_{nullptr} { static_assert(N == dynamic_extent || N == 0); } constexpr span(T* ptr, index_type n) : size_{n}, data_{ptr} { EXPECTS(N == dynamic_extent || N == n); } constexpr span(T* first, T* last) : size_{last - first}, data_{first} { EXPECTS(N == dynamic_extent || last - first = N); } template &lt;std::size_t M, CONSTRAINT(N == dynamic_extent || N == M &amp;&amp; std::is_convertible_v&lt;std::remove_pointer_t&lt;decltype(span_detail::my_data(std::declval&lt;T(&amp;)[M]&gt;()))&gt;(*)[], T(*)[]&gt;)&gt; constexpr span(T (&amp;arr)[M]) noexcept : size_{M}, data_{arr} { } template &lt;std::size_t M, CONSTRAINT(N == dynamic_extent || N == M &amp;&amp; std::is_convertible_v&lt;std::remove_pointer_t&lt;decltype(span_detail::my_data(std::declval&lt;T(&amp;)[M]&gt;()))&gt;(*)[], T(*)[]&gt;)&gt; constexpr span(std::array&lt;value_type, M&gt;&amp; arr) noexcept : size_{M}, data_{arr.data()} { } template &lt;std::size_t M, CONSTRAINT(N == dynamic_extent || N == M &amp;&amp; std::is_convertible_v&lt;std::remove_pointer_t&lt;decltype(span_detail::my_data(std::declval&lt;T(&amp;)[M]&gt;()))&gt;(*)[], T(*)[]&gt;)&gt; constexpr span(const std::array&lt;value_type, M&gt;&amp; arr) noexcept : size_{M}, data_{arr.data()} { } template &lt;class Cont, CONSTRAINT(N == dynamic_extent &amp;&amp; span_detail::is_cont_v&lt;Cont&gt; &amp;&amp; std::is_convertible_v&lt;std::remove_pointer_t&lt;decltype(span_detail::my_data(std::declval&lt;Cont&gt;()))&gt;(*)[], T(*)[]&gt;)&gt; constexpr span(Cont&amp; c) : size_{span_detail::my_size(c)}, data_{span_detail::my_data(c)} { } template &lt;class Cont, CONSTRAINT(N == dynamic_extent &amp;&amp; span_detail::is_cont_v&lt;Cont&gt; &amp;&amp; std::is_convertible_v&lt;std::remove_pointer_t&lt;decltype(span_detail::my_data(std::declval&lt;Cont&gt;()))&gt;(*)[], T(*)[]&gt;)&gt; constexpr span(const Cont&amp; c) : size_{span_detail::my_size(c)}, data_{span_detail::my_data(c)} { } constexpr span(const span&amp; other) noexcept = default; template &lt;class U, std::size_t M, CONSTRAINT(N == dynamic_extent || N == M &amp;&amp; std::is_convertible_v&lt;U(*)[], T(*)[]&gt;)&gt; constexpr span(const span&lt;U, M&gt;&amp; s) noexcept : size_{s.size()}, data_{s.data()} { } ~span() noexcept = default; constexpr span&amp; operator=(const span&amp; other) noexcept = default; // subviews template &lt;std::size_t Cnt&gt; constexpr span&lt;T, Cnt&gt; first() const { EXPECTS(Cnt &lt;= size()); return {data(), Cnt}; } template &lt;std::size_t Cnt&gt; constexpr span&lt;T, Cnt&gt; last() const { EXPECTS(Cnt &lt;= size()); return {data() + (size() - Cnt), Cnt}; } template &lt;std::size_t Off, std::size_t Cnt = dynamic_extent&gt; constexpr auto subspan() const { EXPECTS(Off &lt;= size() &amp;&amp; (Cnt == dynamic_extent || Off + Cnt &lt;= size())); if constexpr (Cnt != dynamic_extent) return span&lt;T, Cnt&gt;{data() + Off, Cnt}; else if constexpr (N != dynamic_extent) return span&lt;T, N - Off&gt;{data() + Off, size() - Off}; else return span&lt;T, dynamic_extent&gt;{data() + Off, size() - Off}; } constexpr span&lt;T, dynamic_extent&gt; first(index_type cnt) const { EXPECTS(cnt &lt;= size()); return {data(), cnt}; } constexpr span&lt;T, dynamic_extent&gt; last(index_type cnt) const { EXPECTS(cnt &lt;= size()); return {data() + (size() - cnt), cnt}; } constexpr span&lt;T, dynamic_extent&gt; subspan(index_type off, index_type cnt = dynamic_extent) const { EXPECTS(off &lt;= size() &amp;&amp; (cnt == dynamic_extent || off + cnt &lt;= size())); return {data() + off, cnt == dynamic_extent ? size() - off : cnt}; } // observers constexpr index_type size() const noexcept { return size_; } constexpr index_type size_bytes() const noexcept { return size() * sizeof(T); } [[nodiscard]] constexpr bool empty() const noexcept { return size() == 0; } // element access constexpr reference operator[](index_type idx) const { EXPECTS(idx &lt; size()); return *(data() + idx); } constexpr reference front() const { EXPECTS(!empty()); return *data(); } constexpr reference back() const { EXPECTS(!empty()); return *(data() + (size() - 1)); } constexpr pointer data() const noexcept { return data_; } // iterator support constexpr iterator begin() const noexcept { return data(); } constexpr iterator end() const noexcept { return data() + size(); } constexpr const_iterator cbegin() const noexcept { return data(); } constexpr const_iterator cend() const noexcept { return data() + size(); } constexpr reverse_iterator rbegin() const noexcept { return reverse_iterator{end()}; } constexpr reverse_iterator rend() const noexcept { return reverse_iterator{begin()}; } constexpr const_reverse_iterator crbegin() const noexcept { return reverse_iterator{cend()}; } constexpr const_reverse_iterator crend() const noexcept { return reverse_iterator{cbegin()}; } friend constexpr iterator begin(span s) noexcept { return s.begin(); } friend constexpr iterator end(span s) noexcept { return s.end(); } private: pointer data_; index_type size_; }; // deduction guide template &lt;class T, std::size_t N&gt; span(T (&amp;)[N]) -&gt; span&lt;T, N&gt;; template &lt;class T, std::size_t N&gt; span(std::array&lt;T, N&gt;&amp;) -&gt; span&lt;T, N&gt;; template &lt;class T, std::size_t N&gt; span(const std::array&lt;T, N&gt;&amp;) -&gt; span&lt;const T, N&gt;; template &lt;class Cont&gt; span(Cont&amp;) -&gt; span&lt;typename Cont::value_type&gt;; template &lt;class Cont&gt; span(const Cont&amp;) -&gt; span&lt;const typename Cont::value_type&gt;; // views of objects representation template &lt;class T, std::size_t N&gt; auto as_bytes(span&lt;T, N&gt; s) noexcept -&gt; span&lt;const std::byte, N == dynamic_extent ? dynamic_extent : sizeof(T) * N&gt; { return {reinterpret_cast&lt;const std::byte*&gt;(s.data()), s.size_bytes()}; } template &lt;class T, std::size_t N, CONSTRAINT(!std::is_const_v&lt;T&gt;)&gt; auto as_writable_bytes(span&lt;T, N&gt; s) noexcept -&gt; span&lt;std::byte, N == dynamic_extent ? dynamic_extent : sizeof(T) * N&gt; { return {reinterpret_cast&lt;std::byte*&gt;(s.data()), s.size_bytes()}; } } namespace std { // tuple interface // the primary template declarations are included in &lt;array&gt; template &lt;class T, std::size_t N&gt; struct tuple_size&lt;my_std::span&lt;T, N&gt;&gt; : std::integral_constant&lt;std::size_t, N&gt; {}; // not defined template &lt;class T&gt; struct tuple_size&lt;my_std::span&lt;T, my_std::dynamic_extent&gt;&gt;; template &lt;std::size_t I, class T, std::size_t N&gt; struct tuple_element&lt;I, my_std::span&lt;T, N&gt;&gt; { static_assert(N != my_std::dynamic_extent &amp;&amp; I &lt; N); using type = T; }; template &lt;std::size_t I, class T, std::size_t N&gt; constexpr T&amp; get(my_std::span&lt;T, N&gt; s) noexcept { static_assert(N != my_std::dynamic_extent &amp;&amp; I &lt; N); return s[I]; } } #undef CONSTRAINT #undef EXPECTS #endif </code></pre> <p>Constructive criticism is highly appreciated!</p>
[]
[ { "body": "<p>Well, it looks quite nice. But now let's try to find all the corners which can still be improved:</p>\n\n<ol>\n<li><p>I'm not quite sure why you list a few members of each include you added. But, at least it simplifies checking for extraneous includes, and they are sorted.</p></li>\n<li><p>Simply restating the code in vaguer words, or otherwise restating the obvious, is an abuse of comments. They just detract from anything relevant.</p>\n\n<p>Well, at least some of them could be justified as breaking long blocks of declarations and definitions into easier digestible logical chunks.</p></li>\n<li><p>Conversion to and arithmetic using unsigned types being done using modulo-arithmetic should not be a surprise to any reviewer and/or maintainer. If it is, they lack basic knowledge, and your sources should not be a basic language-primer.</p></li>\n<li><p>You had extraneous whitespace at the end of some lines. An automatic formatter, or format-checker, either of which can be put in a commit-hook, would have fixed or at least found them.</p></li>\n<li><p>You use your macro <code>CONSTRAINT</code> seven times, leading to a total saving of <span class=\"math-container\">\\$((40-13)-(15-3)) \\times 7 - 71 - 19 = 15 \\times 7 - 90 = 15\\$</span> bytes. That's quite a paltry compensation for adding this cognitive burden on any maintainer, and breaking any user-code defining <code>CONSTRAINT</code> before the include. At least the damage is limited due to you undefining it too.</p></li>\n<li><p>Your use of the macro <code>EXPECTS</code> does not even have that silver lining, as it expanded your code by <span class=\"math-container\">\\$((12-3)-(21-13)) \\times 11 + 49 + 16 = 1 \\times 11 + 65 = 76\\$</span> bytes. And it leaves me even more puzzled as you should have just used <code>assert()</code> directly, that's exactly what it's for.</p></li>\n<li><p>You use an extra template-parameter for SFINAE of a function once. While ctors have to do SFINAE there or not at all, functions can avoid any potential extra-cost by using the return-type for that.</p></li>\n<li><p>If you were actually writing part of the standard library, or had C++20 with it customisation-points, <code>my_size()</code> and <code>my_data()</code> would be pointless. Even though you don't actually need it, I would suggest enabling their use for SFINAE.</p></li>\n<li><p>You aren't currently optimizing the case of non-dynamic extent. Not too surprising, as you go down to the metall everywhere. Just always delegate to <code>span::span(T*, std::size_t)</code> (at least ultimately), and see everything get magically easier. Yes, when you conditionally remove the backing-field for size, you need to adapt <code>.size()</code>.</p></li>\n<li><p>Unifying the ctors <code>span::span(Container&amp;)</code> and <code>span::span(Container const&amp;)</code> is simplicity itself:</p>\n\n<pre><code>template &lt;class Container, class = std::enable_if_t&lt;\n !std::is_rvalue_reference_v&lt;Container&amp;&amp;&gt;\n &amp;&amp; previous_constraint&gt;&gt;\nspan(Container&amp;&amp; c)\n</code></pre></li>\n<li><p>Building on the above, you only have one point left interested in whether you have a non-<code>std::array</code>, non-<code>span</code>, container. Thus, you can simplify all the machinery to detect that, unify detection of <code>std::array</code> and <code>span</code>, and inline it all:</p>\n\n<pre><code>template &lt;class T, template &lt;auto&gt; class TT&gt;\nstruct is_template_instantiation : std::false_type {};\ntemplate &lt;template &lt;auto&gt; class TT, auto N&gt;\nstruct is_template_instantiation&lt;TT&lt;N&gt;, TT&gt; : std::true_type {};\n\ntemplate &lt;class Container, class = std::enable_if_t&lt;\n !std::is_rvalue_reference_v&lt;Container&amp;&amp;&gt;\n &amp;&amp; !span_detail::is_template_instantiation&lt;std::decay_t&lt;Container&gt;, span&gt;()\n &amp;&amp; !span_detail::is_template_instantiation&lt;std::decay_t&lt;Container&gt;, std::array&gt;()\n &amp;&amp; !std::is_array&lt;std::decay_t&lt;Container&gt;&gt;(), decltype(\n span_detail::my_size(std::declval&lt;Container&amp;&gt;()), void(),\n span_detail::my_data(std::declval&lt;Container&amp;&gt;()), void())&gt;&gt;\nspan(Container&amp;&amp; c)\n: span(span_detail::my_data(c), span_detail::my_size(c))\n{}\n</code></pre></li>\n<li><p>I suggest adding computed <code>noexcept</code> even where not mandated. Doing so even allows you to unify more members.</p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-22T02:24:57.767", "Id": "421568", "Score": "0", "body": "Hi Deduplicator! Thank you for your detailed review! Well, let me find some excuses: the points 2, 3, 9, and 10 are consequences of my trying to align with the standard as much as possible ... And about points 5 and 6: I appreciate your enthusiasm in math! I deliberately did that, not for saving characters. In case I adapt this for C++20, all instances of `CONSTRAINT` should be replaced by `requires` and `EXPECTS` by `[[ expects : ... ]]`. Thank you again!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-22T15:11:34.993", "Id": "421636", "Score": "1", "body": "@L.F. You are welcome. Regarding aligning with the standard: Remember that \"Exposition Only\" means that using it simplifies the explanation, reality might differ." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-21T19:45:31.820", "Id": "217845", "ParentId": "217814", "Score": "5" } } ]
{ "AcceptedAnswerId": "217845", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-21T05:09:02.413", "Id": "217814", "Score": "10", "Tags": [ "c++", "reinventing-the-wheel", "template-meta-programming", "c++17", "c++20" ], "Title": "C++17 <span> implementation" }
217814
<p>I have been working on this hangman game for a little while trying to get familiar with C programming. The game seems to work fine but I am looking for some pointers on my code. Are the global variables ok or should I have made them local? Should I have used more functions to make the code more readable? Is my commenting style acceptable or should I stay away from the big box style comments?</p> <pre><code>///////////////////////////////////////////////// /// Title: Hangman /// Author: /// Date: 4/19/2019 /// Description: Hangman Game ///////////////////////////////////////////////// #include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;time.h&gt; #include &lt;string.h&gt; //Global Strings char word [50]; char guessed_letters[20]; char user_guess[] = ""; char blank[1] = "-"; //Global Integers int random_number; int word_len; int user_input; int attempts = 10; //Function Declarations void start_game(); void get_input(); void print_blanks(); void draw_platform(); void get_word(); int main(void) { //Game Loop while(1) { start_game(); while(attempts &gt; 0) { system("cls"); //If they have guessed all the letters they win if(strlen(guessed_letters) == word_len - 1) { print_blanks(); break; } //Else, decr attempts and try again else { printf("Attempts Remaining: %i\n", attempts); print_blanks(); get_input(); } } system("cls"); //If they won if(attempts &gt; 0) { print_blanks(); printf("You Won! Play again?\n"); } //If they lost else { draw_platform(); printf("You Lost! The word was %s, Play again?\n", word); } scanf("%i", &amp;user_input); switch(user_input) { case 0: return 0; default: continue; } } } void start_game() { //Initializes Game get_word(); word_len = strlen(word); memset(guessed_letters, 0, sizeof guessed_letters); attempts = 10; } void get_input() { //Gets guess from user and checks //To see if that letter is in the word int i; int letter_hit = 0; //Used to tell if the guess letter is in the word printf("\nYour guess: \n"); scanf(" %c", user_guess); for(i=0; i &lt; word_len; i++) { if(user_guess[0] == word[i]) { guessed_letters[i] = user_guess[0]; letter_hit ++; } } if(letter_hit &gt; 0) { return; } else { attempts --; } } void print_blanks() { ///////////////////////////////////////////////// /// Prints out a number of blanks equal to the /// Length of the word /// Then fills the blanks with the guessed letters ///////////////////////////////////////////////// int i, j; draw_platform(); for(i=0; i&lt;word_len; i++) { printf("%c", guessed_letters[i]); printf(" "); } printf("\n"); for(j=0; j&lt;word_len - 1; j++) { printf("%s", blank); printf(" "); } printf("\n"); } void draw_platform() { ///////////////////////////////////////////////// /// Draws a new segment onto /// The platform every time /// The user gets a wrong guess ///////////////////////////////////////////////// char *platform[]={ " ===\n", " |\n" " |\n" " |\n" " ===\n", " =====|\n" " |\n" " |\n" " |\n" " ===\n", " |=====|\n" " |\n" " |\n" " |\n" " ===\n", " |=====|\n" " O |\n" " |\n" " |\n" " ===\n", " |=====|\n" " O |\n" " | |\n" " |\n" " ===\n", " |=====|\n" " O |\n" " |- |\n" " |\n" " ===\n", " |=====|\n" " O |\n" " -|- |\n" " |\n" " ===\n", " |=====|\n" " O |\n" " -|- |\n" " | |\n" " ===\n", " |=====|\n" " O |\n" " -|- |\n" " // |\n" " ===\n" }; switch(attempts) { case 9: printf("\n\n%s\n", platform[0]); break; case 8: printf("\n\n%s\n", platform[1]); break; case 7: printf("\n\n%s\n", platform[2]); break; case 6: printf("\n\n%s\n", platform[3]); break; case 5: printf("\n\n%s\n", platform[4]); break; case 4: printf("\n\n%s\n", platform[5]); break; case 3: printf("\n\n%s\n", platform[6]); break; case 2: printf("\n\n%s\n", platform[7]); break; case 1: printf("\n\n%s\n", platform[8]); break; case 0: printf("\n\n%s\n", platform[9]); break; } } void get_word() { ///////////////////////////////////////////////// /// Scans a file to get the total number of lines /// The line total is then used as a max range /// For the random number /// The word that is on the random line is the word /// That will be used for the game ///////////////////////////////////////////////// FILE *fp; int line_number = 0; char current_word[50]; fp = fopen("dictionary.txt","r"); if(fp == NULL) { perror("Error in opening file"); } //While not end of file, incr line number while(fgets(current_word, 50, fp) != NULL) { line_number++; } random_number = rand() % line_number; //Start from top of file rewind(fp); //Goes to whatever line the random number equals to find the //Random word for(line_number = 0; line_number != random_number; line_number++) { fgets(current_word, 50, fp); } strcpy(word, current_word); fclose(fp); } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-22T11:22:06.350", "Id": "421598", "Score": "0", "body": "Your `switch` statement can be simplified to just `printf(\"\\n\\n%s\\n\", platform[9 - attempts]);`" } ]
[ { "body": "<p><strong>Typo or Bug</strong><br>\nAny time a array of characters is to be used as a string the length of the array <strong>MUST</strong> be 1 + the expected length of the string to allow for the NULL value that terminates the string.</p>\n\n<pre><code>char blank[1] = \"-\";\n</code></pre>\n\n<p>Code such the line above can cause the program to either terminate abnormally or cause all kinds of interesting problems.</p>\n\n<p><strong>Global Variables</strong><br>\nSome people say global variables are evil and never use them, they are not quite correct, but in this case there are multiple ways around using global variables. Some of the functions could return values rather than void, variables can be passed into some functions by either by value or by reference.</p>\n\n<p>Pass By Value means that a copy of the variable is used within the function and any changes made to the variable within the function won't change the value in the rest of the program. Pass By Reference means that the address of the variable is passed into the function and any changes made to the variable will change in the rest of the program. In C the contents of an array all always pass by reference because an array is a memory address.</p>\n\n<p>Global variables make programs much harder to debug because it is hard to find where the variable is changed within the program, this is true even when the program is a single file such as this one, but with multiple source files it is much harder.</p>\n\n<p>If you declared any of these global variable in multiple files the linking phase would report multiple definitions and then quit. If a variable needs to be global within a single file and not elsewhere it should be declared as a static variable.</p>\n\n<p>It is best to limit the scope of a variable to just where it is needed. If a variable is only used in a for loop, declare it in that for loop. The variable <code>random_number</code> should be declared in the <code>get_word()</code> function because it is only referenced in that function.</p>\n\n<p>It would be best if get_word returned a character array rather than setting a global variable.</p>\n\n<p><strong>Complexity</strong><br>\nThere is a good start on creating functions in the program, but <code>main()</code> is still too complex. In large programs main is used to set up for processing, call the processing function(s) and clean up. It might be a good practice to always limit the code in <code>main()</code> to this functionality. Perhaps a function called <code>run_game()</code> could contain most of the code in <code>main()</code> including the call to <code>start_game()</code>.</p>\n\n<p><strong>Performance</strong><br>\nThe program might be faster if it read all the strings into an array of strings (char **words). The random number can then be used as an index into the array of strings rather than rereading some or all of the file. Multiple passes through a file are time consuming and should be avoided when possible. The functions <code>fopen()</code>, <code>fclose()</code>, <code>fgets()</code> and <code>rewind()</code> are all system calls and cause the program to be swapped out when they are called.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-22T11:18:17.293", "Id": "421597", "Score": "0", "body": "\"Code such as line 23\" Please mention the line as there are no line numbers here" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-22T11:25:50.757", "Id": "421600", "Score": "0", "body": "Also, you should mention that `char blank[1] = \"-\";` should be `char blank = '-';` as it doesn't make sense to have a array to store a character. Note that `char blank[1] = \"-\";` is valid though. Just the NUL-terminator won't be appended to the array which causes UB when it gets printed using `%s`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-22T12:24:38.100", "Id": "421614", "Score": "0", "body": "@Spikatrix Changed line 23 to the line above. My view is that we are here to help the user not get UB." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-22T12:49:55.067", "Id": "421621", "Score": "0", "body": "Kinda misleading. That line is perfectly valid as I said in my previous comment. UB occurs only when the user prints it using `%s` in `printf`." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-21T15:28:11.797", "Id": "217835", "ParentId": "217820", "Score": "3" } } ]
{ "AcceptedAnswerId": "217835", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-21T07:18:08.103", "Id": "217820", "Score": "2", "Tags": [ "beginner", "c", "hangman" ], "Title": "Beginning C, hangman" }
217820
<p>I tried(trying...) to solve the <strong>SPOJ prime number problem</strong> <a href="https://www.spoj.com/problems/PRIME1/" rel="nofollow noreferrer">PRIME1</a> so i learned and implemented Segmented Sieve correctly but this program works in time for 10^8 but getting Time limit exceeded (TLE) for 10^9 input integer. can someone help me reduce complexity within my code please. </p> <pre><code>/* followed this tutorial https://medium.com/@agilanbtdw/prime-number-generation-in-java-using-segmented-sieve-of-eratosthenes-187af1dcd051 */ #include &lt;iostream&gt; #include &lt;math.h&gt; #include &lt;vector&gt; #include &lt;fstream&gt; using std::cin; using std::ifstream; using std::vector; using std::cout; using std::ios_base; int main() { ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL); //ifstream in("inp.txt"); short int t; unsigned long int n ,q; cin &gt;&gt; t; while(t--){ cin &gt;&gt;q &gt;&gt; n; vector&lt;bool&gt; a(n,true); unsigned long int m = sqrt(n); a[0] = false; a[1] = false; // find primes till sqrt for(unsigned long int i = 2 ; i &lt;= m ; i++ ){ if(a[i]){ for(unsigned long int j = i*i ; j &lt;= m ; j+=i ){ a[j] = false; } } } // store the primes upto m vector&lt;unsigned long int&gt; primes; for(unsigned long int i = 2 ; i &lt;= m ; i++ ){ if(a[i]){ primes.push_back(i);} } unsigned long int temp; for (unsigned long int x : primes) { temp = q/x; temp*=x; // from primes arrays increment each prime with that num , set the index as false for(unsigned long int y = temp ; y &lt;=n ; y+=x){ a[y] = false; } } // set the falsed indexes in previous primes arrays to true for(unsigned long int i = 0 ; i &lt; primes.size() ;++i){ a[primes[i]] = true; } for(unsigned long int i =q ; i &lt;= n ; i++ ){ if(a[i]) {cout &lt;&lt; i &lt;&lt; " ";} } cout &lt;&lt; "\n"; } return 0; } </code></pre> <blockquote> <p>my repl link - <a href="https://repl.it/repls/UnrulyMotherlyTransformation" rel="nofollow noreferrer">https://repl.it/repls/UnrulyMotherlyTransformation</a></p> </blockquote>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-21T16:23:02.127", "Id": "421507", "Score": "1", "body": "der bender is correct about 1 thing, using types such as short or short int will impact performance, using int would be better because int is guaranteed to use the native word size of the computer." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-21T18:06:55.387", "Id": "421513", "Score": "0", "body": "@pacmaninbw oh okk thankyou sir i learned something new." } ]
[ { "body": "<p><strong>Reducing Complexity</strong><br>\nThe first thing to do for reduced complexity is to break up the code into multiple functions. This would allow you to profile the code and see where it spends the most time. This also makes it easier to read, write and debug the code. There are possibly 5 functions in main. As programs get more complex it is generally better to limit the <code>main()</code> function to set up and clean up and do all other processing in sub functions.</p>\n\n<p>This would be applying the <a href=\"https://en.wikipedia.org/wiki/Single_responsibility_principle\" rel=\"nofollow noreferrer\">Single Responsibility Principle</a> to the code which is the first pillar of <a href=\"https://en.wikipedia.org/wiki/SOLID\" rel=\"nofollow noreferrer\">SOLID</a> object oriented programming. The Single Responsibility Principle states <code>The single responsibility principle is a computer programming principle that states that every module, class, or function[1] should have responsibility over a single part of the functionality provided by the software ...</code></p>\n\n<p><strong>Variable Names</strong><br>\nGenerally single character variable names make code harder to read and debug. It is unclear what the variables <code>t</code>, <code>n</code>, <code>q</code> or <code>m</code> are or do.</p>\n\n<p><strong>Use Explict Casts</strong><br>\nThe line of code </p>\n\n<pre><code>unsigned long int m = sqrt(n);\n</code></pre>\n\n<p>is an implicit cast and generates warning messages in some compilers. C++ attempts to be type safe and casts should be explict, in this particular case it would be better to use a <a href=\"https://en.cppreference.com/w/cpp/language/static_cast\" rel=\"nofollow noreferrer\">static_case</a>.</p>\n\n<p><strong>Performance</strong><br>\nIt looks like this code checks all numbers in a range, there is no reason to process even numbers except for 2 since all even numbers greater than 2 can't be prime numbers because they are divisible by 2.</p>\n\n<p><strong>Indentation</strong><br>\nThe code is improperly indented immediately after the <code>while</code> statement. This makes it much harder to read the code.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-21T14:49:29.250", "Id": "421496", "Score": "0", "body": "ok thankyou sir i got the solution to the problem thankyou for your time and help" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-21T13:54:13.133", "Id": "217833", "ParentId": "217825", "Score": "1" } }, { "body": "<p>following the advice to make the main function smaller and outsource (quite literally) as much as possible in seperate functions i came up with this:</p>\n\n<pre><code>// spoj.cpp: Definiert den Einstiegspunkt für die Konsolenanwendung.\n//\n\n#include \"stdafx.h\" //vc++ specific may be ommitted\n\n#include &lt;iostream&gt;\n#include &lt;math.h&gt;\n#include &lt;vector&gt;\n#include &lt;fstream&gt;\n\n#include &lt;stdint.h&gt;\n\nusing std::cin;\nusing std::cout;\nusing std::ifstream;\nusing std::vector;\nusing std::ios_base;\n\nvoid findPrimesUponTillSqrtN(uint64_t sqrtN, vector&lt;bool&gt; * Flag)\n{ \n for (register uint64_t i = 2; i &lt;= sqrtN; i++) \n {\n if ((*Flag)[i]) \n {\n for (register uint64_t j = i * i; j &lt;= sqrtN; j += i) \n {\n (*Flag)[j] = false;\n }\n }\n }\n}\n\nvoid storePrimesUponTillSqrtN(uint64_t sqrtOfN, vector&lt;uint64_t&gt; * primes, vector&lt;bool&gt; * Flag)\n{\n for (register uint64_t i = 2; i &lt;= sqrtOfN; i++) \n {\n if ((*Flag)[i]) \n {\n (*primes).push_back(i); \n }\n }\n}\nvoid primesManipulation(vector&lt;uint64_t&gt; * primes, vector&lt;bool&gt; * Flag,uint64_t n, uint64_t q)\n{\n for (uint64_t x : (*primes)) \n {\n uint64_t temp;\n temp = q / x;\n temp *= x;\n // from primes arrays increment each prime with that num , set the index as false\n for (register uint64_t y = temp; y &lt;= n; y += x) \n {\n (*Flag)[y] = false;\n }\n }\n}\n\nvoid flagMultiplesOfFoundPrimes(vector&lt;bool&gt; * Flag, vector&lt;uint64_t&gt; * primes)\n{\n // set the falsed indexes in previous primes arrays to true\n register const uint64_t sizeOfPrimes = (*primes).size();\n for (register uint64_t i = 0; i &lt; sizeOfPrimes; ++i) \n {\n (*Flag)[(*primes)[i]] = true;\n }\n}\n\nvoid printFoundPrimes(uint64_t q, uint64_t n, vector&lt;bool&gt; * Flag)\n{\n for (register uint64_t i = q; i &lt;= n; i++) \n {\n if ((*Flag)[i])\n {\n cout &lt;&lt; i &lt;&lt; \" \"; \n }\n }\n cout &lt;&lt; \"\\n\";\n}\nvoid sieve(int64_t t, uint64_t q, uint64_t n)\n{\n while (t--) \n {\n cin &gt;&gt; q &gt;&gt; n;\n vector&lt;bool&gt; Flag(n, true);\n Flag[0] = false;\n Flag[1] = false;\n uint64_t sqrtOfN = sqrt(n);\n\n findPrimesUponTillSqrtN(sqrtOfN,&amp;Flag); \n\n vector&lt;uint64_t&gt; primes;\n storePrimesUponTillSqrtN(sqrtOfN, &amp;primes, &amp;Flag);\n\n primesManipulation(&amp;primes, &amp;Flag, n, q);\n\n flagMultiplesOfFoundPrimes(&amp;Flag, &amp;primes);\n\n printFoundPrimes(q, n, &amp;Flag);\n }\n}\n\nint main() \n{\n ios_base::sync_with_stdio(false); \n cin.tie(NULL); \n cout.tie(NULL);\n //ifstream in(\"inp.txt\");\n int64_t t;\n uint64_t n, q;\n cin &gt;&gt; t;\n sieve(t, q, n);\n return 0;\n}\n</code></pre>\n\n<p>explaination / thoughts / Input / Food for thought:</p>\n\n<ol>\n<li>renamed Array/vector <code>a</code> to <code>Flag</code> (according to the link given in your Code)</li>\n<li>changed type of just About everything to <code>uint64_t</code> this is what modern x64 processors should be optimized for and if Nothing else it does save you some keystrokes in the Long run.</li>\n<li>often used variables get the Register qualifier to state that this variable is intended to be stored in a Register. the Compiler may or may not place them in Registers but if he does it Speeds up your Code significantly.</li>\n<li>as i dont know of top if vectors are passed to functions as pointers per Default i pass over a pointer to them to ensure that. Maybe this is not at all necessary.</li>\n<li>naming convention: it does not cost you anything (not even Computational power) to give variables and functions meaningful names. this helps others (like me, who had a hard time figuring out the meaning of your variables) to grasp your algorithm faster and makes some comments completely unneccessary</li>\n<li>using sqrt Returns a double and you store that in an integer variable of some sort!!! this is at best horrible style there is an sqrtl function available!!!</li>\n<li>your temp variable is only used inside that one Codeblock that can easily refactored in a new function so making it local instead may bring some Advantages...</li>\n<li><code>temp = q/x; temp*= x;</code> yields q if q/x is not fractional… and therefor this can surely be optimized</li>\n<li>the lenght of your <code>primes</code> Vector is constant (or at least it is for the time you call your for loop that flags all the multiples of found primes) therefor there is no Need to retrieve that Information over and over again. store it in a variable declare it constant and tell the Compiler to store it in Registers if he is in the mood to do so. </li>\n<li>some Parameters that are asked for during the runtime like the Limits are not neccessarily to be asked there. they can be given at the time the Program is called using commandline paramameters for instance. this may reduce runtime a Little bit because the whole <code>cin</code> Thing has not to be executed.</li>\n<li>further improvements may result from not using <code>cout</code> or <code>printf</code> or the like and immediately print to stdout without traversing the same dozen layers of abstraction everytime.</li>\n<li>vectors as such may be slow as they allow to add and remove Elements and therefor are basically variable lenght Arrays. internally they are most likely not more than linked lists which are known for their slowness and thus should be avoided.</li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-21T15:50:12.057", "Id": "421506", "Score": "0", "body": "if your interested in how to make any Code more efficent / faster there are a Ton of good Videos of highly proficent People giving talks on the subject at cppcon and other places (chandeler caruth (im sure i misspelled that) is a very good Person to look for in that case (look for the Compiler optimization talk and the like.))" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-21T15:44:55.910", "Id": "217837", "ParentId": "217825", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-21T10:33:55.227", "Id": "217825", "Score": "1", "Tags": [ "c++", "performance", "programming-challenge", "primes" ], "Title": "Segmented Sieve Spoj" }
217825
<p><strong>The task</strong></p> <blockquote> <p>Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward.</p> <p>Example 1:</p> <p>Input: 121 Output: true </p> <p>Example 2:</p> <p>Input: -121 Output: false Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome. </p> <p>Example 3:</p> <p>Input: 10 Output: false Explanation: Reads 01 from right to left. Therefore it is not a palindrome. Follow up:</p> <p>Could you solve it without converting the integer to a string?</p> </blockquote> <p><strong>My solution</strong> with converting number to string</p> <pre><code>const isPalindrome = n =&gt; n &gt;= 0 &amp;&amp; Number([...`${n}`].reverse().join("")) === n; console.log(isPalindrome(121)); </code></pre> <p><strong>My solution</strong> without converting number to string</p> <pre><code>const isPalindrome2 = n =&gt; { if (n &lt; 0) { return false; } let num = Math.abs(n); const arr = []; let i = 1; while (num &gt; 0) { const min = num % (10 ** i); num = num - min; i++; arr.push(min); } i = i - 2; let j = 0; return n === arr.reduce((res, x) =&gt; { const add = (x/ (10 ** j)) * (10 ** i); res += add; i--; j++; return res; }, 0); }; console.log(isPalindrome2(121)); </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-21T11:44:04.520", "Id": "421481", "Score": "1", "body": "That's an awfully convoluted way to check for your objective. Can you tell us more about why you did it this way?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-21T11:56:06.523", "Id": "421483", "Score": "0", "body": "I wanted to solve it without converting the number to a string. @Mast" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-21T13:01:00.027", "Id": "421487", "Score": "0", "body": "That explains it in part, but it's still an odd way to do it. I hope my answer points out why I was so surprised." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-21T18:57:53.310", "Id": "421517", "Score": "0", "body": "@thadeuszlay Palindrome is not defined on numbers, it's defined on strings. In this case you want decadic string representing the given number. You *have* to convert it to a string or a similar representation (e.g. array of decadic digits)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-21T18:59:39.213", "Id": "421518", "Score": "0", "body": "@Sulthan the Point is not to use strings (as described in the task)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-21T19:08:07.353", "Id": "421521", "Score": "0", "body": "@thadeuszlay In my opinion it's a bad question. You will use a String anyway, even if it's in a roundabout way." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-21T22:00:15.473", "Id": "421539", "Score": "2", "body": "@Sulthan well, you don't necessarily need an array or string. The answers show how you can do this without splitting up the digits. But it _is_ true that you need to know the base, and that a fully explicit version of the question should ask whether the base-10 (or whatever) representation of the integer is a palindrome, since that's a property of the representation but not of the integer itself." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-21T22:17:46.177", "Id": "421547", "Score": "0", "body": "\"10\" is a palindrome. While standard representations are made of symbols (\"convert to string\") \"010\" is still a valid and correct representation of \"10\". So, either convert to string is the valid approach, or the concept of the number is the valid approach - the latter means numbers like \"10\", \"200\" etc are valid palindromes." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-22T06:19:05.120", "Id": "421572", "Score": "0", "body": "@AJD this is Javascrpit as such 010 is prefixed with 0 making it an octal which represents the base 10 value 8. Most computer languages prefix or post fix numbers to define the base. In javascript without a prefix all numbers are base 10, `0x` for hex, `0` for octal, `0b` for binary, and postfix `n` for big ints (AKA dec strings). The problem shows no prefix, thus the solution is clearly a decimal one (base 10)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-22T08:37:19.837", "Id": "421594", "Score": "0", "body": "@Blindman67: You missed the point. Any representation of a number uses symbols and 010 is as valid as the representation for \"ten\" (decimal) as 10 is. Yes, if this was in a line of code then 010 could represent Octal - but it is not, it is in user input and users of an application or function will (well, may) be blissfully unaware of the vagaries of any particular language. However, this does go to support the earlier comment that this is a poorly considered task. My key point - palindromes are about symbols (strings) and can only be about symbols, not abstract concepts like numbers or words." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-22T13:24:56.687", "Id": "421626", "Score": "0", "body": "@AJD the problem as stated in the question \"Determine whether an integer is a palindrome\" would suggest that palindromes can be about numbers (as my answer demonstrates without the use of symbols). But to take your argument further, computers use charge to hold states and process those states, the whole concept of numbers in computers is already highly abstract. You can selectively draw a line to what level of abstraction should apply, however the question put that line down for all to see." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-22T19:56:42.643", "Id": "421698", "Score": "0", "body": "@Blindman67: No, the problem is that the question is implying that the search is on a number (an abstract concept), not the representation of a number according to rules. The task description uses \"01\" as an example, so \"010\" is also legal (i.e. leading zeroes to be counted). Representations count - is the number \"5\", \"5.0\" or \"101\"? An additional point - the task is language agnostic, so your other comments regarding Java-specific encoding are not valid." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-22T20:19:38.663", "Id": "421701", "Score": "0", "body": "@AJD There are 10 types of people. Those that read binary and those that don't. Its funny only to those that do, but only because we all read it as ten until prompted to read two. Common use defines the standard, specialist use requires explicit definition." } ]
[ { "body": "<p>Your second solution is awfully complicated for something simple.</p>\n\n<p>You start out alright. No negative number can be a palindrome, so we can discount those. However, 0 is always a palindrome, so you're discounting that while you shouldn't.</p>\n\n<p>You do a lot of complicated math <em>and</em> use an array. You could use either, but shouldn't use both. There are a couple of mathematical approaches to solve this, but you should be able to use those without iterating over the individual numbers or splitting it up at all. The most obvious solution however, is using an array and direct comparisons, without any math.</p>\n\n<p>Say we got <code>1221</code>. Split it up. <code>[1, 2, 2, 1]</code>. Iterate over the array, comparing every nth character to the last-nth character. 0th to 3rd. 1st to 2nd.</p>\n\n<p>Say we got <code>92429</code>. Split it up. <code>[9, 2, 4, 2, 9]</code>. Ignore the middle character. Handle the rest like it's an even-length number.</p>\n\n<p>Based on those 2 cases, you should be able to figure out a much simpler algorithm.</p>\n\n<p><strong>Note:</strong> This answers the explicit question. Implicitly, you should wonder whether arrays should be allowed for this challenge. After all, iterating over a string or an array, it's not that different. I strongly suspect they want you to use the math-only approach.</p>\n\n<p>Another approach, which is somewhat math-based and you should beware of overflows, is simply reversing the number.\nIn pseudo-code, that would look something like this:</p>\n\n<pre><code>reverse = 0\nwhile (number != 0) {\n reverse = reverse * 10 + number % 10;\n number /= 10;\n}\n</code></pre>\n\n<p>Check the input versus its reversed number. If they are the same, it's a palindrome.</p>\n\n<p>But this still uses extra memory to hold the additional integer we just created.</p>\n\n<p>Can it be done without? Absolutely. But I'll leave that as an exercise for you.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-21T16:23:56.230", "Id": "421508", "Score": "0", "body": "How would you split it up?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-21T19:01:47.783", "Id": "421519", "Score": "0", "body": "You are converting the number to a string anyway, even if you don't store the string anywhere. A number is an abstract concept. To represent it, you need a string, either binary or a decadic (or any other base). When you start working with decimal representation, you are using a string representation. You cannot define palindrome without a string." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-21T20:26:30.230", "Id": "421527", "Score": "0", "body": "@Sulthan Yes, but that's a philosophical discussion, not a review." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-21T22:13:19.603", "Id": "421546", "Score": "1", "body": "You could modify the last approach to stop when reverse >= number, and then evaluate. Voila, no danger of overflow." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-22T06:36:11.323", "Id": "421575", "Score": "0", "body": "@Deduplicator when using your approach to test `121` and `1221`, the code needs two separate tests. One for odd number of digits, one for even. Or did I miss something?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-22T14:46:36.897", "Id": "421634", "Score": "0", "body": "@RolandIllig Right, the final determination is a two-part test, allowing for a simpler loop." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-21T12:58:57.517", "Id": "217830", "ParentId": "217827", "Score": "5" } }, { "body": "<h2>Count digits in positive integer</h2>\n\n<p>You can get the number of digits using <code>log10</code></p>\n\n<p>eg </p>\n\n<pre><code>Math.log10(13526); // is 4.131169383089324\nconst digits = Math.ceil(Math.log10(13526)); // 5\n</code></pre>\n\n<p>You can get the unit value eg 423 is 100 or 256378 is 100000 by raising 10 to the power of the number of digits minus one. Well not for powers of 10</p>\n\n<p>eg</p>\n\n<pre><code>unit = 10 ** (Math.ceil(Math.log10(13526)) -1); // 10000\nunit = 10 ** (Math.ceil(Math.log10(10000)) -1); // 1000 wrong for power of 10 number\n</code></pre>\n\n<p>To get the value we want we need to floor the log first</p>\n\n<pre><code>unit = 10 ** Math.floor(Math.log10(10000)); // 10000\nunit = 10 ** Math.floor(Math.log10(13526)); // 10000 correct\n</code></pre>\n\n<p>or</p>\n\n<pre><code>unit = 10 ** (Math.log10(10000) | 0); // 10000\nunit = 10 ** (Math.log10(13526) | 0); // 10000 \n</code></pre>\n\n<h2>Get digit at position of positive integer</h2>\n\n<p>To get the digit at any position in a number divide it by 10 raised to the power of the digit position get the remainder of that divided by 10 and floor it.</p>\n\n<pre><code>const digitAt = (val, digit) =&gt; Math.floor(val / 10 ** digit % 10);\n</code></pre>\n\n<p>or</p>\n\n<pre><code>const digitAt = (val, digit) =&gt; val / 10 ** digit % 10 | 0;\n\n// Note brackets added only to clarify order and are not needed\n// ((val / (10 ** digit)) % 10) | 0;\n\ndigitAt(567, 0); // 7\ndigitAt(567, 1); // 6\ndigitAt(567, 2); // 5\n</code></pre>\n\n<h2>Positive integer a palindrome in <span class=\"math-container\">\\$O(1)\\$</span> space</h2>\n\n<p>With that info you can then build a function that does test in <span class=\"math-container\">\\$O(1)\\$</span> space, as you do not need to store the digits in an array for later comparison.</p>\n\n<p>To keep performance up we can avoid the slower versions of some operation. For <code>floor</code> we can <code>| 0</code> (note that for large numbers > 2**31-1 you must use <code>floor</code>) and for <code>**</code> use <code>Math.pow</code> </p>\n\n<p>Rather than do the full calculation to get the digit we can store the unit value of the digit we want for the top and bottom and multiply by 10 to move up and divide by 10 to move down.</p>\n\n<pre><code>function isPalindrome(num) {\n var top = Math.pow(10, Math.log10(num) | 0), bot = 1;\n while (top &gt;= bot) {\n if ((num / top % 10 | 0) !== (num / bot % 10 | 0)) { return false }\n top /= 10;\n bot *= 10;\n }\n return true;\n}\n</code></pre>\n\n<ul>\n<li>The function will returns <code>false</code> for negative numbers but is not optimized for them</li>\n<li>The function only works on integer values less than <code>Number.MAX_SAFE_INTEGER</code> which is <code>9007199254740991</code></li>\n</ul>\n\n<p>In terms of performance the above function is 5 times faster for a 16 digit palindrome <code>2192123993212912</code> and 10-11 times faster for a non palindrome of 16 digits</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-21T22:39:03.263", "Id": "421551", "Score": "2", "body": "Don't suggest floating-point arithmetic when solving integer problems." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-22T05:52:05.593", "Id": "421570", "Score": "0", "body": "@RolandIllig Really??? Are you unfamiliar with Javascript? . Using math operators `/`, `*`, `%` evaluate as doubles, Meaning that what you are saying is dont use math operators to solve integer problems," }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-22T06:23:08.150", "Id": "421573", "Score": "0", "body": "The crucial point is that IEEE 754-2008 guarantees that the `+`, `-`, `*`, `/` and `sqrt` operators produce results that are as close to the mathematical truth as possible. There is no such guarantee for `log10` or `sin`, and thus using these functions may introduce rounding errors." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-22T06:25:30.453", "Id": "421574", "Score": "0", "body": "Besides this, my advice also applies to all those who will copy this code into the language of their choice and just set the type to `int64_t`. The algorithm and the code should be so fundamentally correct that they work with any integer type." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-22T06:42:35.353", "Id": "421576", "Score": "1", "body": "@RolandIllig What??? You are saying, all answers no matter what the tag must be language neutral, I think I will avoid that complication. Anyways the | operator converts to int 32 and Math.log10 in javascript will never let `(Math.log10(n)|0) !== (Math.log10(n+1)|0)` be true, where n is positive int (excluding 9, 99, 999, 9999, 99999... ). So prove me wrong, all you need is a number for `n`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-22T06:46:33.533", "Id": "421577", "Score": "1", "body": "@RolandIllig By the way did you read my answer \"only works on integer values less than `Number.MAX_SAFE_INTEGER`\" a clear warning regarding possible rounding errors" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-22T06:48:56.580", "Id": "421579", "Score": "0", "body": "@RolandIllig read my comment again" } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-21T19:53:24.653", "Id": "217846", "ParentId": "217827", "Score": "2" } }, { "body": "<p>Are you sure you should generate all those objects and arrays?<br>\nAnd the second code additionally looks quite complex.</p>\n\n<p>Testing whether a number is palindromic is actually quite simple:</p>\n\n<pre><code>function isPalindrome(num) {\n if (num % 10 == 0) {\n return num == 0\n }\n var rev = 0\n while (rev &lt; num) {\n rev = rev * 10 + num % 10\n num /= 10\n }\n return rev == num || rev / 10 == num\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-22T16:36:31.303", "Id": "421649", "Score": "0", "body": "This is JavaScript, therefore it's better to compare using `===` instead of `==`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-25T22:10:51.873", "Id": "469573", "Score": "0", "body": "This doesn't work for an input of `10`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-25T22:28:23.413", "Id": "469574", "Score": "0", "body": "@mph85 Fixed trailing zeros, thanks." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-22T14:52:46.737", "Id": "217889", "ParentId": "217827", "Score": "3" } } ]
{ "AcceptedAnswerId": "217846", "CommentCount": "13", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-21T11:23:17.540", "Id": "217827", "Score": "6", "Tags": [ "javascript", "algorithm", "programming-challenge", "ecmascript-6", "palindrome" ], "Title": "Determine whether an integer is a palindrome" }
217827
<p>I am working on one question, <a href="https://www.geeksforgeeks.org/find-maximum-path-sum-two-leaves-binary-tree/" rel="nofollow noreferrer">Find max path sum from two leaves</a></p> <blockquote> <p>Given a binary tree in which each node element contains a number. Find the maximum possible sum from one leaf node to another.</p> </blockquote> <pre class="lang-py prettyprint-override"><code>class TreeNode: def __init__(self, x=None): self.val = x self.left = None self.right = None def maxPathSum(root: TreeNode) -&gt; int: res = float('-inf') def traversal(node, pathsum): nonlocal res if node is None: return 0 if node.left is None and node.right is None: return node.val ln_value = traversal(node.left, pathsum) rn_value = traversal(node.right, pathsum) if node.left is not None and node.right is not None: res = max(res, node.val + ln_value + rn_value) return max(ln_value, rn_value) + node.val if node.left is None: return rn_value + node.val else: return ln_value + node.val traversal(root, res) return res </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-21T20:00:28.290", "Id": "421524", "Score": "0", "body": "This code won't work on the example given behind your link. (Or any example with a half-full node.) Perhaps you should debug it more before asking for a review." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-21T21:10:12.720", "Id": "421530", "Score": "0", "body": "my bad post the wrong code. updated already. any good idea how to handle to res if not using nonlocal?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-21T22:54:46.917", "Id": "421552", "Score": "0", "body": "Return a tuple. And it still doesn't work, I think. What if your tree is (10, (-1), (-1))?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-22T19:47:28.317", "Id": "421692", "Score": "0", "body": "what do you mean return a tuple?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-22T19:49:17.143", "Id": "421693", "Score": "0", "body": "A [`tuple`](https://docs.python.org/3/library/stdtypes.html?highlight=tuple#tuple) is a built-in Python type. There is syntactic sugar for constructing them, so you can do something like: `return (1, 2)`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-22T20:54:58.960", "Id": "421707", "Score": "0", "body": "yes..but how does that to do with my code?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-22T21:10:51.250", "Id": "421712", "Score": "0", "body": "You asked about other ways to handle `res`. I suggest returning two values: the best \"internal\" score (res) and the highest \"external\" score (the current return value)" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-21T16:03:59.460", "Id": "217838", "Score": "1", "Tags": [ "python", "python-3.x" ], "Title": "Find max path sum from two leaves" }
217838
<p>I made an implementation of <a href="https://en.cppreference.com/w/cpp/experimental/observer_ptr" rel="noreferrer">std::experimental::observer_ptr</a> (library fundamentals TS v2). <code>observer_ptr</code> basically behaves like a normal pointer and does no management of its target whatsoever (unlike <code>std::unique_ptr</code> or <code>std::shared_ptr</code>). It's usage is solely to indicate that it takes no ownership of the target object (it only observes it).</p> <p>The implementation is simple and straight forward.</p> <pre><code>#include &lt;cstddef&gt; #include &lt;type_traits&gt; #include &lt;memory&gt; namespace tb { template &lt;typename T&gt; class observer_ptr { public: using element_type = T; constexpr observer_ptr() noexcept = default; constexpr observer_ptr(std::nullptr_t) noexcept { } template &lt;typename U, typename = std::enable_if&lt;!std::is_same_v&lt;element_type, U&gt; &amp;&amp; std::is_convertible_v&lt;U*, element_type*&gt;&gt;&gt; observer_ptr(observer_ptr&lt;U&gt; const&amp; other) : observer_ptr(static_cast&lt;element_type*&gt;(other.get())) {} explicit observer_ptr(element_type* ptr) : _data(ptr) { } constexpr element_type* release() noexcept { auto* ptr = _data; _data = nullptr; return ptr; } constexpr void reset(element_type* p = nullptr) noexcept { _data = p; } constexpr void swap(observer_ptr&amp; other) noexcept { using std::swap; swap(_data, other._data); } constexpr friend void swap(observer_ptr&amp; lhs, observer_ptr&amp; rhs) noexcept { lhs.swap(rhs); } [[nodiscard]] constexpr element_type* get() const noexcept { return _data; } [[nodiscard]] constexpr std::add_lvalue_reference_t&lt;element_type&gt; operator*() const { return *get(); } [[nodiscard]] constexpr element_type* operator-&gt;() const noexcept { return get(); } [[nodiscard]] constexpr explicit operator bool() const noexcept { return _data == nullptr; } [[nodiscard]] constexpr explicit operator element_type*() const noexcept { return get(); } private: element_type* _data = nullptr; }; template &lt;typename T&gt; [[nodiscard]] observer_ptr&lt;T&gt; make_observer(T* ptr) noexcept { return observer_ptr&lt;T&gt;(ptr); } template &lt;typename T1, typename T2&gt; [[nodiscard]] bool operator==(observer_ptr&lt;T1&gt; const&amp; p1, observer_ptr&lt;T2&gt; const&amp; p2) { return p1.get() == p2.get(); } template &lt;typename T1, typename T2&gt; [[nodiscard]] bool operator!=(observer_ptr&lt;T1&gt; const&amp; p1, observer_ptr&lt;T2&gt; const&amp; p2) { return !(p1 == p2); } template &lt;typename T&gt; [[nodiscard]] bool operator==(observer_ptr&lt;T&gt; const&amp; p, std::nullptr_t) noexcept { return static_cast&lt;bool&gt;(p); } template &lt;typename T&gt; [[nodiscard]] bool operator==(std::nullptr_t, observer_ptr&lt;T&gt; const&amp; p) noexcept { return static_cast&lt;bool&gt;(p); } template &lt;typename T&gt; [[nodiscard]] bool operator!=(observer_ptr&lt;T&gt; const&amp; p, std::nullptr_t) noexcept { return !p; } template &lt;typename T&gt; [[nodiscard]] bool operator!=(std::nullptr_t, observer_ptr&lt;T&gt; const&amp; p) noexcept { return !p; } template &lt;typename T1, typename T2&gt; [[nodiscard]] bool operator&lt;(observer_ptr&lt;T1&gt; const&amp; p1, observer_ptr&lt;T2&gt; const&amp; p2) { return p1.get() &lt; p2.get(); } template &lt;typename T1, typename T2&gt; [[nodiscard]] bool operator&gt;(observer_ptr&lt;T1&gt; const&amp; p1, observer_ptr&lt;T2&gt; const&amp; p2) { return p2 &lt; p1; } template &lt;typename T1, typename T2&gt; [[nodiscard]] bool operator&lt;=(observer_ptr&lt;T1&gt; const&amp; p1, observer_ptr&lt;T2&gt; const&amp; p2) { return !(p2 &lt; p1); } template &lt;typename T1, typename T2&gt; [[nodiscard]] bool operator&gt;=(observer_ptr&lt;T1&gt; const&amp; p1, observer_ptr&lt;T2&gt; const&amp; p2) { return !(p1 &lt; p2); } } </code></pre> <h2>Edit</h2> <p>Here is a sample usage</p> <pre><code>#include &lt;vector&gt; #include &lt;iostream&gt; struct A { void hello() const { std::cout &lt;&lt; "hello\n"; } }; // indicates that foo won't take ownership void foo(tb::observer_ptr&lt;A&gt; const&amp; ptr) { ptr-&gt;hello(); } // does foo take ownership of ptr (especially if it were a member function)? void foo(A* ptr) { ptr-&gt;hello(); } int main() { std::vector&lt;std::unique_ptr&lt;A&gt;&gt; manager; manager.emplace_back(new A); manager.emplace_back(new A); manager.emplace_back(new A); for (auto&amp; a : manager) { foo(tb::observer_ptr(a.get())); foo(a.get()); } return 0; } </code></pre> <p>Some question that came to my mind:</p> <ol> <li>Should I add constructor overloads for <code>std::unique_ptr</code> and <code>std::shared_ptr</code> (for convenience)?</li> <li>I'm usually not a fan of implicit conversions but in this case I'm thinking about making the constructors implicit. This is justified by (a) <code>observer_ptr</code> is a fairly light weight type and (b) it doesn't change the behavior or affect the underlying pointer in any way. What do you think about that?</li> </ol>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-21T21:44:23.977", "Id": "421536", "Score": "0", "body": "Could you provide examples of usage?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-22T12:36:42.077", "Id": "421616", "Score": "0", "body": "@pacmaninbw added an example." } ]
[ { "body": "<p>Some suggestions:</p>\n\n<ol>\n<li><p>Don't prefix the data member with an underscore. The rule about identifiers starting with an underscore are easy to get wrong. In this case, just name it <code>data</code>.</p></li>\n<li><p>You did not make the converting constructor and the raw pointer constructor <code>noexcept</code>. They are <code>noexcept</code> according to the spec.</p></li>\n<li><p>Don't use <code>element_type</code> everywhere, it's too long. Just use <code>T</code>.</p></li>\n<li><p>Don't breach the 80 character limit. Scrolling is a bit annoying.</p>\n\n<blockquote>\n<pre><code>template &lt;typename U, typename = std::enable_if&lt;!std::is_same_v&lt;element_type, U&gt; &amp;&amp; std::is_convertible_v&lt;U*, element_type*&gt;&gt;&gt;\nobserver_ptr(observer_ptr&lt;U&gt; const&amp; other)\n</code></pre>\n</blockquote>\n\n<p>The long line can be broken down. <code>typename = std::enable_if</code> is useless &mdash; you probably meant <code>typename = std::enable_if_t</code>. And the <code>!std::is_same_v&lt;T, U&gt;</code> is redundant because the copy constructor will always take precedence over this constructor:</p>\n\n<pre><code>template &lt;typename U, typename = std::enable_if_t&lt;std::is_convertible_v&lt;U*, T*&gt;&gt;&gt;\nobserver_ptr(obverser_ptr&lt;U&gt; other) noexcept\n :data{other.get()}\n{\n}\n</code></pre></li>\n<li><p>The <code>release</code> function can be simplified with <code>std::exchange</code>:</p>\n\n<pre><code>return std::exchange(data, nullptr);\n</code></pre></li>\n<li><p>The <code>operator bool</code> is getting the logic wrong &mdash; it should return <code>data != nullptr</code> instead.</p></li>\n<li><p>The lines are getting a bit long for the observers. I prefer writing them on separate lines:</p>\n\n<pre><code>[[nodiscard]] constexpr std::add_lvalue_reference_t&lt;T&gt; operator*() const\n{\n return *get();\n}\n[[nodiscard]] constexpr T* operator-&gt;() const noexcept\n{\n return get();\n}\n</code></pre></li>\n<li><p>According to the spec, <code>operator&lt;</code> should use <code>std::less</code> of the <a href=\"https://timsong-cpp.github.io/cppwp/n4659/expr#def:composite_pointer_type\" rel=\"nofollow noreferrer\">composite pointer type</a> instead of the builtin <code>&lt;</code> on pointers because the latter does not provide a strict total order. So:</p>\n\n<pre><code>template &lt;typename T1, typename T2&gt;\n[[nodiscard]] bool operator&lt;(observer_ptr&lt;T1&gt; const&amp; p1, observer_ptr&lt;T2&gt; const&amp; p2)\n{\n using CP = /* work out the composite pointer type of T1* and T2* */;\n return std::less&lt;CP&gt;;\n}\n</code></pre></li>\n<li><p>Where's <code>std::hash</code>? You need to specialize it.</p></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-31T13:02:52.653", "Id": "227218", "ParentId": "217847", "Score": "4" } } ]
{ "AcceptedAnswerId": "227218", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-21T20:12:18.793", "Id": "217847", "Score": "5", "Tags": [ "c++", "pointers", "c++17" ], "Title": "Implementation of std::experimental::observer_ptr (library fundamentals TS v2)" }
217847
<blockquote> <h2>Problem Statement</h2> <p>Following are the various scenarios to be considered</p> <ol> <li><p><strong>Track energy</strong> - Track consumption of water, gas and electricity. We should be able extend to capture other type of energies as well (e.g., fuel for vehicles). Apart from storing the consumption and time interval, also look into possibilities of capturing additional attributes for each type and extend it with ease.</p></li> <li><p><strong>Sustainability goals</strong> - Build a construct to provide an ability for users to capture sustainability goals, such as use x amount of alternate energy (wind or solar), cut down the usage by x, shift usage of certain energy to a non-peak time (e.g., running washing machine).</p></li> <li><p><strong>Savings</strong> - Based on goals, project savings ahead of time as well compute them for every given timeframe.</p></li> <li><p><strong>Suggest goals</strong> - Design a mechanism to suggest goals so that folks can pick from existing goals/template and tweak if needed to create their own.</p></li> <li><p><strong>Other scenarios to keep in mind</strong></p> <ol> <li>Sustainability score - to build a score for every home</li> <li>Badges - Provide badges or incentives for people when they achieve goals</li> <li>Incentives - Provide incentives when people achieve certain goals</li> </ol></li> </ol> <p><strong>Evaluation Criteria</strong></p> <p>Pay attention to the following for this exercise for design </p> <ol> <li>Scalable design </li> <li>Data extensibility - ability to quickly extend attributes to consider additional scenarios. </li> <li>For all devices - build the application to scale into using any devices or integrate with third party systems</li> </ol> </blockquote> <h2>My Implementation</h2> <p><strong>Sequence Diagram</strong> <a href="https://i.stack.imgur.com/dy9jb.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/dy9jb.jpg" alt="Sequence diagram"></a></p> <p><strong>Code Structure</strong></p> <p><a href="https://i.stack.imgur.com/B7LwP.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/B7LwP.png" alt="Directory listing"></a></p> <h1>Code</h1> <p><a href="https://github.com/arnab30dutta/HouseEnergyOptimizationApp/tree/5a97f0cdd8ea85c3639b6488ea1547789923ccda" rel="nofollow noreferrer">Git repository</a> </p> <p><strong><em>Appliance</em></strong></p> <pre><code>package heca; import java.sql.Time; public class Appliance{ String applianceCategory; //e.g Electricity ApplianceType applianceType; //e.g StrictAppliance like Refrigerator String applianceName; //e.g WashingMachine int usageTime; Time scheduledTime; public Appliance(String applianceCategory, ApplianceType applianceType, String applianceName, int usageTime,Time scheduledTime) { this.applianceCategory = applianceCategory; this.applianceType = applianceType; this.applianceName = applianceName; this.usageTime = usageTime; this.scheduledTime = scheduledTime; } } </code></pre> <p><strong><em>Attribute</em></strong></p> <pre><code>package heca; public class Attribute{ String attibuteName; //e.g WindPower double perUnitWeight; int consumed; int limit; public static class Builder { //required private String attibuteName; //optional private double perUnitWeight; private int consumed; private int limit; public Builder(String size) { this.attibuteName = size; } public Builder perUnitWeight(double value) { perUnitWeight = value; return this; } public Builder consumed(int value) { consumed = value; return this; } public Builder limit(int value) { limit = value; return this; } public Attribute build() { return new Attribute(this); } } private Attribute(Builder builder) { attibuteName = builder.attibuteName; perUnitWeight = builder.perUnitWeight; consumed = builder.consumed; limit = builder.limit; } public Attribute(String a){ this(a, 0.0, 0, (int)1e6); } public Attribute(String a, double w, int m, int l){ attibuteName = a; perUnitWeight = w; consumed = m; limit = l; } public String toString(){ StringBuilder sb = new StringBuilder(); sb.append("\n\tattibute : "+this.attibuteName+"\tConsumed :"+ this.consumed + "\tLimit : "+ this.limit); return sb.toString(); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((attibuteName == null) ? 0 : attibuteName.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Attribute other = (Attribute) obj; if (attibuteName == null) { if (other.attibuteName != null) return false; } else if (!attibuteName.equals(other.attibuteName)) return false; return true; } } </code></pre> <p><strong><em>Controller</em></strong> </p> <pre><code>package heca; import java.sql.Time; import java.util.List; import java.util.Map; public interface Controller { public String createUser(String userName); public boolean addAppliance(String userId,String applianceCategory); public boolean addAppliance(String userId, String applianceCategory,List&lt;Attribute&gt; attribs); public void addAttribute(String userId,String applianceCategory,String attributeName); public void updateConsumption(String userId,String applianceCategory,String attributeName,int updatedValue); public List&lt;Attribute&gt; getMAXExpenses(String userId); public List&lt;Attribute&gt; getMINExpenses(String userId); public Map&lt;String,List&lt;Attribute&gt;&gt; getAllConsumptionDetails(String userId); public List&lt;Attribute&gt; getSpecificConsumptionDetails(String userId,String applianceCategory); public Score getScore(); public Badge getBadge(); public List&lt;Attribute&gt; getSuggestedOptimizedGoal(String userId,String applianceCategory,int target); public boolean modifyGoal(String userId,String applianceCategory,String attributeName,int targetValue); public boolean scheduleFlexibleAppliance(String userId,String applianceCategory, Appliance applianceName,Time schedule); } </code></pre> <p><strong><em>CostComparator</em></strong> </p> <pre><code>package heca; import java.util.Comparator; public class CostComparator implements Comparator&lt;Attribute&gt;{ // fractional knapsack comparator having only Weight(weight per unit) but all items are unbounded..same Value...Hence value ignored @Override public int compare(Attribute o1, Attribute o2) { return ((o1.limit -o1.consumed)*(int)o1.perUnitWeight ) - ((o2.limit -o2.consumed)*(int)o2.perUnitWeight ) &gt; 0 ? 1:0 ; } } </code></pre> <p><strong><em>EnergyTracker</em></strong></p> <pre><code>package heca; import java.util.ArrayList; import java.util.List; import java.util.PriorityQueue; import java.util.Queue; import java.util.concurrent.ConcurrentHashMap; public class EnergyTracker{ ConcurrentHashMap&lt;String,List&lt;Attribute&gt;&gt; appliances = new ConcurrentHashMap&lt;&gt;(); //AdjacencyMatrix Queue&lt;Attribute&gt; maxExpenseHeap = new PriorityQueue&lt;&gt;(20, new CostComparator()); Queue&lt;Attribute&gt; minExpenseHeap = new PriorityQueue&lt;&gt;(20, new CostComparator().reversed()); public List&lt;Attribute&gt; getApplianceDetails(String aplianceName){ if(appliances.containsKey(aplianceName))return appliances.get(aplianceName); else return new ArrayList&lt;&gt;(); } public void setApplianceDetails(String aplianceName,List&lt;Attribute&gt; attribs){ List&lt;Attribute&gt; renewedAttribs = appliances.get(aplianceName); if(renewedAttribs==null || renewedAttribs.isEmpty()) renewedAttribs = attribs; else if(appliances.containsKey(aplianceName)){ renewedAttribs.addAll(attribs); } appliances.put(aplianceName,renewedAttribs); renewedAttribs.forEach((attrib )-&gt; this.maxExpenseHeap.offer(attrib)); renewedAttribs.forEach((attrib )-&gt; this.minExpenseHeap.offer(attrib)); } public ConcurrentHashMap&lt;String,List&lt;Attribute&gt;&gt; getALLApplianceDetails() { return appliances; } public List&lt;Attribute&gt; get_TopK_MINConsumptionAppliance(int K){ ArrayList&lt;Attribute&gt; top5minConsumption = new ArrayList&lt;&gt;(K); Attribute temp =null; for( int i =0; i&lt;K &amp;&amp; K&lt; minExpenseHeap.size() &amp;&amp; i &lt; minExpenseHeap.size(); ){ temp = minExpenseHeap.poll(); top5minConsumption.add(temp); minExpenseHeap.offer(temp); i++; } return top5minConsumption; } public List&lt;Attribute&gt; get_TopK_MAXConsumptionAppliance(int K){ ArrayList&lt;Attribute&gt; top5minConsumption = new ArrayList&lt;&gt;(K); Attribute temp =null; for( int i =0; i&lt;K &amp;&amp; K&lt; maxExpenseHeap.size() &amp;&amp; i &lt; maxExpenseHeap.size(); ){ temp = maxExpenseHeap.poll(); top5minConsumption.add(temp); maxExpenseHeap.offer(temp); } return top5minConsumption; } } </code></pre> <p><strong><em>HomeUser</em></strong></p> <pre><code>package heca; public class HomeUser{ String userId; EnergyTracker targetExpenseTracker = new EnergyTracker(); EnergyTracker actualExpenseTracker = new EnergyTracker(); int targetExpenseGoal, monthlyBudget, tillNowExpense; public HomeUser(String uID){ userId = uID; } /* &lt;TODO&gt; calculate based on : getSavings() getGoalAchieved() */ public Badge showBadgesAndIncentives(){ return Badge.SILVER; } /* &lt;TODO&gt; judge based on total consumption cost of all Appliances -&gt; Attribute -&gt; consumed*perUnitWeight */ public Score getScore(){ return Score.CONSUMES_MEDIUM; } private int getGoalAchieved(){ return targetExpenseGoal; } private int getSavings(){ return monthlyBudget - tillNowExpense; } //setters public void setTargetExpenseGoal(int targetExpenseGoal) { this.targetExpenseGoal = targetExpenseGoal; } public void setMonthlyBudget(int monthlyBudget) { this.monthlyBudget = monthlyBudget; } public void setTillNowExpense(int tillNowExpense) { this.tillNowExpense = tillNowExpense; } } </code></pre> <p><strong><em>UserDB</em></strong></p> <pre><code>package heca; import java.util.HashMap; public class UserDB{ HashMap&lt;String,HomeUser&gt; usserMap = new HashMap&lt;&gt;(); public void addUser(String userId,HomeUser u){ usserMap.put(userId, u); } public HomeUser getUser(String userId){ return usserMap.get(userId); } } </code></pre> <p><strong><em>DesignHECA</em></strong></p> <pre><code>package heca; import java.sql.Time; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; public class DesignHECA implements Controller { private UserDB userDB = new UserDB(); @Override public String createUser(String userName) { String userId = userName+ new java.util.Random(); HomeUser u = new HomeUser(userId); userDB.addUser(userId,u); return userId ; } public HomeUser getUser(String userId) { return userDB.getUser(userId); } /*----------------------- addAppliance ----------------------------------------*/ @Override public boolean addAppliance(String userId, String applianceCategory) { if(applianceCategory == null || applianceCategory.isEmpty()) return false; else getUser(userId).actualExpenseTracker.setApplianceDetails(applianceCategory,new ArrayList&lt;&gt;()); //telescoping return true; } @Override public boolean addAppliance(String userId, String applianceCategory,final List&lt;Attribute&gt; attribs){ // not to be leaked to Client HomeUser user = getUser(userId); if(applianceCategory == null || applianceCategory.isEmpty()) return false; else if(!user.actualExpenseTracker.appliances.containsKey(applianceCategory)){ user.actualExpenseTracker.setApplianceDetails(applianceCategory,attribs); //defensive copy }else{ List&lt;Attribute&gt; prev = user.actualExpenseTracker.appliances.getOrDefault(applianceCategory, new ArrayList&lt;&gt;()); prev.addAll(attribs); //handling override left for brevity user.actualExpenseTracker.setApplianceDetails(applianceCategory,prev); } return true; } /*----------------------- addAttribute ----------------------------------------*/ @Override public void addAttribute(String userId, String applianceCategory, String attributeName) { List&lt;Attribute&gt; attribs = new ArrayList&lt;&gt;(); Attribute attribute = new Attribute(attributeName); attribs.add(attribute); addAppliance(userId, applianceCategory,attribs); } /*----------------------- updateConsumption ----------------------------------------*/ @Override public void updateConsumption(String userId, String applianceCategory, String attributeName, int tillNowConsumed) { //left intentionally for brevity } /*----------------------- getMAXExpenses ----------------------------------------*/ @Override public List&lt;Attribute&gt; getMAXExpenses(String userId) { HomeUser user = getUser(userId); return user.actualExpenseTracker.get_TopK_MAXConsumptionAppliance(10); } /*----------------------- getMINExpenses ----------------------------------------*/ @Override public List&lt;Attribute&gt; getMINExpenses(String userId) { HomeUser user = getUser(userId); return user.actualExpenseTracker.get_TopK_MINConsumptionAppliance(10); } /*----------------------- getAllConsumptionDetails ----------------------------------------*/ @Override public Map&lt;String, List&lt;Attribute&gt;&gt; getAllConsumptionDetails(String userId) { HomeUser user = getUser(userId); return user.actualExpenseTracker.getALLApplianceDetails(); } /*----------------------- getSpecificConsumptionDetails ----------------------------------------*/ @Override public List&lt;Attribute&gt; getSpecificConsumptionDetails(String userId, String applianceCategory) { HomeUser user = getUser(userId); //checks omitted for brevity return user.actualExpenseTracker.getApplianceDetails(applianceCategory); } /*----------------------- modifyGoal - lets user to newly calibrate his target expenses ---*/ @Override public boolean modifyGoal(String userId, String applianceCategory, String attributeName, int newlimit) { HomeUser user = getUser(userId); List&lt;Attribute&gt; attribs = user.targetExpenseTracker.getApplianceDetails(applianceCategory); Attribute temp =null; for(int i=0; i&lt;attribs.size();i++){ if(attributeName.equals(attribs.get(i).attibuteName)){ temp =attribs.remove(i); temp.limit = newlimit; attribs.add(temp); user.targetExpenseTracker.setApplianceDetails(applianceCategory,attribs); return true; } } return false; } /*---------------------- getSuggestedOptimizedGoals ------------------------------ * This method Suggests optimized path(Top 5 MIN Expense) for Goal if calibration set by User predicted to meet target * */ @Override public List&lt;Attribute&gt; getSuggestedOptimizedGoal(String userId,String applianceCategory,int target) { HomeUser user = getUser(userId); List&lt;Attribute&gt; attribs = user.actualExpenseTracker.getApplianceDetails(applianceCategory); /* e.g "PowerSupply",340,880 "WindPower",120,1 "SolarEnergy",10,2 int[] w ={880,1,2}; int[] c ={340,120,10}; if( this.canProduce(c,w,user.monthlyBudget -user.tillNowExpense) &gt; 0){ //optimiseed combination return this.getMINExpenses(userId); } else return new ArrayList&lt;&gt;(); */ return this.getMINExpenses(userId); } public int canProduce(int[] c,int[] w, int W){ return min_cost(c.length,W,c,w); } // Dynamic programming to compute Minimum Cost Path for fixed Weight public int min_cost(int N, int W,int[] c, int[] w){ // min_cost(i, W) = min(min_cost(i+1, W), min_cost(i, W - w[i]) + c[i]) int[][] dp = new int[N][W]; int i=0; //base cases if(dp[i][0] == 0 ) return 1; // We already reached our goal if(W &lt; 0 || i &gt; N) dp[i][W] = Integer.MIN_VALUE; // if (W &lt; 0 or i &gt; N) then we can't get to W dp[i][ W] = Math.min(min_cost(i+1, W,c,w), min_cost(i, W - w[i],c,w) + c[i]); if(dp[N][ W] &lt;= W) return dp[N][ W]; else return 0;//impossible --need to re calibrate } @Override public boolean scheduleFlexibleAppliance(String userId,String applianceCategory, Appliance applianceName,Time schedule) { // TODO omitted for brevity return false; } @Override public Score getScore() { // TODO omitted for brevity return null; } @Override public Badge getBadge() { // TODO omitted for brevity return null; } /*------------Driver Program -----------------------------------------------------------*/ public static void main(String args[] ) throws Exception { DesignHECA d = new DesignHECA(); String userId = d.createUser("Chandra"); /** Create Attribute */ List&lt;Attribute&gt; attributeList1 = new ArrayList&lt;&gt;(); attributeList1.add( new Attribute.Builder("CarOil").perUnitWeight(80.0).consumed(20).limit(60).build()); attributeList1.add( new Attribute.Builder("CookingOil").perUnitWeight(60.0).consumed(4).limit(12).build()); attributeList1.add( new Attribute.Builder("CandleOil").perUnitWeight(12.0).consumed(2).limit(10).build()); List&lt;Attribute&gt; attributeList2 = new ArrayList&lt;&gt;(); attributeList2.add( new Attribute.Builder("CrudeOil").perUnitWeight(12.0).consumed(10).limit(80).build()); List&lt;Attribute&gt; attributeList3 = new ArrayList&lt;&gt;(); attributeList3.add( new Attribute("PowerSupply",340.0,880,60)); attributeList3.add( new Attribute("WindPower",120.0,1,2)); List&lt;Attribute&gt; attributeList4 = new ArrayList&lt;&gt;(); attributeList4.add( new Attribute("SolarEnergy",0.0,0,2)); /** Create ApplapplianceCategorydd Attributes */ d.addAppliance(userId,"Fuel",attributeList1); d.addAppliance(userId,"Fuel",attributeList2); d.addAppliance(userId,"Electricity",attributeList3); d.addAppliance(userId,"Electricity",attributeList4); /** Optimize Electric Consumption */ /*------------show Electric consumption ----------------------------------------------------------------*/ d.getAllConsumptionDetails(userId).forEach((k,v)-&gt; System.out.println(k+" : "+v)); /*------------show Suggested Paths ----------------------------------------------------------------------*/ System.out.println(d.getSpecificConsumptionDetails(userId,"Electricity")); System.out.println(d.getSuggestedOptimizedGoal(userId,"Electricity",9000)); //DP based on Graph /*------------user can opt to re-calibrating his target ---------------------------------------------------*/ d.modifyGoal(userId,"Electricity","PowerSupply", 600); /*------------user can opt to schedule Washing Machine ---------------------------------------------------*/ //d.scheduleFlexibleAppliance(userId,"Electricity", "WashingMachine", new Time(11,30,20)); } /* ********************************************* &lt;TODO&gt; : Implement following Business Methods ============================================= --remmoveAppliance() --getTargetGoal() --getProjectSavings() --getBadgesAndIncentives() --calculateDeviation() --getSuggestedOptimizedGoals("Electric") DP based on Graph */ /*----Constructor-------------*/ public DesignHECA(){ init(); } /*----Utility &amp; Loaders-------*/ public void init() { } //can be populated from File system } enum ApplianceType{ STRICT, FLEXIBLE; } enum Goal{ EXCELLENT,GOAL_ACHIEVED,EXCEEDED; } enum Badge{ // Badge with Incentive COPPER(100),SILVER(300),GOLD(800); private int intValue; private String abbreviation; private Badge(final int intValue) { this.intValue = intValue; } private Badge(String value) { this.abbreviation = value; } //lookup a Java enum from its ordinals private static Badge[] values = Badge.values(); public static Badge getByID(int i) { return (values[i - 1] != null)? values[i - 1] : Badge.values()[i]; } } enum Score{ CONSUMES_LOW, CONSUMES_MEDIUM, CONSUMES_HIGH, CONSUMES_PEAK; } </code></pre> <h2>My Stake</h2> <p>I have <em>tried</em> implementing a very minimal viable program. Its incomplete and I was rejected - obvious isn't it? I know the interviewer was not expecting a full fledged implementation though. I shared my Code and design. I need the help of experts here to help me correct myself, so that in future I have a rough idea of my shortcomings.</p> <h2>What I need help on:</h2> <ol> <li>What would be experts Object Oriented Class Design </li> <li>Where would experts prefer Generics to make polymorphic Algo...</li> <li>Where would experts might like to use MutliThread / Concurrency here.</li> <li>What all design patterns (eg. strategy) may be applied to which scenarios</li> <li>How would expert implement some features like: Track energy, time interval, Savings, Suggest goals, WashingMachine rescheduling...etc </li> <li>How should this app be designed to facilitate unit testing?</li> </ol>
[]
[ { "body": "<p>When scanning through your code, the first thing I noticed was:</p>\n\n<p>Your code is inconsistent regarding its formatting. </p>\n\n<p>To fix this in Eclipse, select Window > Preferences from the main menu, search for \"Save actions\" and activate the \"Format Code\" and \"Organize Imports\" items. Then right-click on your complete project and select \"Format Source\" (or similar).</p>\n\n<hr>\n\n<p>You do use a version control system like Git or Mercurial, so that you could undo every change quickly and without risk, do you? If not, start using it. It's worth it. Just learn the basics:</p>\n\n<ul>\n<li>initialize a repository</li>\n<li>commit changes</li>\n</ul>\n\n<p>If you only learn these 2 things, you have a fully working backup and can ask knowledgeable people to help you out, whatever happens.</p>\n\n<hr>\n\n<p>There's a lot of boilerplate code in the <code>Appliance</code> class. You should either use Lombok or Kotlin to reduce the amount of code you have to write yourself.</p>\n\n<p>When using Lombok, the code becomes:</p>\n\n<pre><code>@lombok.Data\npublic class Appliance {\n private final String applianceCategory; //e.g Electricity\n private final ApplianceType applianceType; //e.g StrictAppliance like Refrigerator\n private final String applianceName; //e.g WashingMachine\n private final int usageTime;\n private final Time scheduledTime;\n}\n</code></pre>\n\n<p>When using Kotlin, the code becomes:</p>\n\n<pre><code>data class Appliance(\n val category: String, //e.g Electricity\n val type: ApplianceType, //e.g StrictAppliance like Refrigerator\n val name: String, //e.g WashingMachine\n val usageTime: int,\n val scheduledTime: Time)\n</code></pre>\n\n<p>In both styles you don't need to write down the redundant code for the constructor.</p>\n\n<p>It is even more useful for the <code>Attribute</code> type since both of these styles generate the equals and hashCode methods for you, so you don't have to think about them anymore.</p>\n\n<p>When you program the code that creates the <code>Attribute</code> objects in Kotlin, you don't need the builder anymore since in Kotlin you have named parameters. Instead of</p>\n\n<pre><code>new Attribute(\"WindPower\", 3.4, 13, 500)\n</code></pre>\n\n<p>you would write:</p>\n\n<pre><code>Appliance(\n category = \"Electricity\",\n type = ApplianceType.StrictAppliance,\n name = \"WashingMachine\",\n usageTime = 13,\n scheduledTime = Time(1234L))\n</code></pre>\n\n<p>Now there is no chance anymore to mix up the order of the arguments. No builder needed.</p>\n\n<hr>\n\n<p>The method <code>addAppliance</code> returns <code>false</code> if it fails to do anything, but you never check that. The established way of signalling programming errors in Java is to <code>throw new IllegalArgumentException(\"reason\")</code>. When you use that style, you cannot accidentally forget to check for errors.</p>\n\n<hr>\n\n<p>Indeed, you need to write unit tests. Especially for the more tricky algorithms like <code>min_cost</code>. That may seem still simple, but even after 25 years of experience my code contains awfully many bugs when I initially write it, and unit tests help a lot.</p>\n\n<p>You should even extract the interesting algorithms into separate files, to make them easily testable. Currently <code>min_cost</code> is part of <code>DesignHECA</code>, but I doubt that this coupling is necessary. If you place the <code>min_cost</code> in a utility class called <code>Algorithms</code> instead, this makes it immediately clear that the algorithm is independent from your home energy management system.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-21T22:21:01.913", "Id": "421548", "Score": "0", "body": "Appreciate a lot . I would definitely walk the line you suggested :) \nWill put those in my git with lombok. Exception handling we can ignore as this is more of a interview just identifying edge cases is adequate I would guess. Meanwhile please keep suggesting. Let me know if you are waiting on something more from me :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-22T11:33:43.300", "Id": "421605", "Score": "0", "body": "shared my Git repo. \nHope You and other knowledgeable pexperts can help me further to refine." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-21T22:06:44.110", "Id": "217854", "ParentId": "217849", "Score": "0" } }, { "body": "<h1>Initial impressions</h1>\n\n<p>These are my initial impressions just reading from top to bottom:</p>\n\n<h2>Sequence diagram</h2>\n\n<p>I look at your sequence diagram and I think, \"this isn't a sequence diagram!\"</p>\n\n<p>You have an actor with no identity, interacting with an unidentified first entity, doing various unrelated things. I assume this means you are merging several sequence diagrams into one.</p>\n\n<p>All of your interactions ignore the <code>HomeUser,</code> so why is it even on there? </p>\n\n<p>All of your interactions (save one) are identical. So what is the point of showing them all? Also, if they are all identical, does that not suggest to you that either your design is wrong, or perhaps there is a greater pattern that you are missing? </p>\n\n<h2>class <code>Appliance</code></h2>\n\n<p>You defined this class. And from what I can see, you never use it. Everything afterwards is just a list of <code>Attribute</code>? So what's the point of the class?</p>\n\n<h2>class <code>Attribute</code></h2>\n\n<p>Every attribute has a name, a weight, consumed, and limit? What do those mean? Especially considering that everything else in the system depends on a list of attributes, could you provide more detail in a class documentation comment or example code?</p>\n\n<p>And is <code>List&lt;Attribute&gt;</code> really the best structure? Is there no minimum requirement for contents, no constructor, no validation for this?</p>\n\n<h2><code>DesignHECA</code></h2>\n\n<p>First, why is there a <code>Controller</code> interface? This seems like the one class which will not have more than a single implementation. So why does it need to conform to any interface?</p>\n\n<p>Next, what is the <a href=\"https://en.wikipedia.org/wiki/Single_responsibility_principle\" rel=\"nofollow noreferrer\">Single Responsibility</a> of this class? It looks like you're trying to make this class the user interface of your project. But ... there's no UI. </p>\n\n<h1>Evaluation</h1>\n\n<p>Now let's take a look at the stated objectives:</p>\n\n<blockquote>\n <h2>Problem Statement</h2>\n \n <p>Following are the various scenarios to be considered</p>\n \n <ol>\n <li><p><strong>Track energy</strong> - Track consumption of water, gas and electricity. We should be able extend to capture other type of energies as well\n (e.g., fuel for vehicles). Apart from storing the consumption and time\n interval, also look into possibilities of capturing additional\n attributes for each type and extend it with ease.</p></li>\n <li><p><strong>Sustainability goals</strong> - Build a construct to provide an ability for users to capture sustainability goals, such as use x amount of\n alternate energy (wind or solar), cut down the usage by x, shift usage\n of certain energy to a non-peak time (e.g., running washing machine).</p></li>\n <li><p><strong>Savings</strong> - Based on goals, project savings ahead of time as well compute them for every given timeframe.</p></li>\n <li><p><strong>Suggest goals</strong> - Design a mechanism to suggest goals so that folks can pick from existing goals/template and tweak if needed to\n create their own.</p></li>\n <li><p><strong>Other scenarios to keep in mind</strong></p>\n \n <ol>\n <li>Sustainability score - to build a score for every home</li>\n <li>Badges - Provide badges or incentives for people when they achieve goals</li>\n <li>Incentives - Provide incentives when people achieve certain goals</li>\n </ol></li>\n </ol>\n \n <p><strong>Evaluation Criteria</strong></p>\n \n <p>Pay attention to the following for this exercise for design </p>\n \n <ol>\n <li>Scalable design </li>\n <li>Data extensibility - ability to quickly extend attributes to consider additional scenarios. </li>\n <li>For all devices - build the application to scale into using any devices or integrate with third party systems</li>\n </ol>\n</blockquote>\n\n<h2>1. Track Energy</h2>\n\n<p>I don't see any mechanism for this. Your <code>Attribute</code> class provides no clear way to do this, since attribute names are totally arbitrary. If someone creates an attribute \"CarOil\" and someone else creates an attribute \"Motor Oil\", are they the same or different? Are \"Cooking Oil\" and \"Canola Oil\" and \"Vegetable Oil\" and \"Peanut Oil\" the same for tracking purposes? Can user \"Mom\" track \"Gas\" while user \"Dad\" tracks \"Gasoline\" and \"LittleSister\" tracks \"Exxon\"?</p>\n\n<h3>Tracking</h3>\n\n<p>There are two possible mechanisms for this: first, if your application is sitting on an extensible database, you might use the database key from the <code>resources</code> table to classify usage. Otherwise, with no database or a mapping layer above the database, you might have an <code>enum</code> identifying your resources. \nYou don't do either one of these, so that's a fail from me.</p>\n\n<h3>Extending</h3>\n\n<p>Can you \"extend to capture other type of energies as well\"? No, since you can't track anything consistently. </p>\n\n<p>Can you explore \"capturing additional attributes for each type and extend it with ease\"? No. You have no explicit identification of energy or resource types, and no relation between activities and resources. So there's no way you can do this.</p>\n\n<h3>Alternate solutions</h3>\n\n<p>Create a \"table\" for your resource types. Look into cost models of all the resources in your area (where you live). How are they billed? In my area, electricity and natural gas are billed in two bands: the initial quantity units used costs differently than additional units over the amount. (There might also be a amount, Y>X, that bills more, but I don't use that much.) There is <em>also</em> a time component: peak hours versus off-peak hours. Using electricity during peak hours costs more. (Gas is the same cost always.)</p>\n\n<p>So how can you model just those details? You'll need to know the time-of-day for any activity. You'll need to know the \"monthly usage\" prior to an activity, or you'll want to only present cost data in monthly aggregate form. (That's two possibilities- you'll have to decide what makes more sense for your application.)</p>\n\n<p>What about water? What about firewood or charcoal? Consider the possibility that some energy sources might get cheaper in volume: if one is buying small LP gas tanks to power a stove, and switches to larger tanks, the cost might go down! How can you store that data? (Hint: I don't think a single class can support all these options. It might be time for an interface...or two.)</p>\n\n<h2>2. Sustainability Goals</h2>\n\n<h3>Different sources</h3>\n\n<p>How can you identify these things? For example, how can I tell if I'm using \"wind power\" versus \"solar\" versus \"nuclear?\" My household doesn't have different outlets for different kinds of electricity!</p>\n\n<p>Again, there are a couple of options: some places support energy markets, so you can buy your electricity from a \"solar\" provider. The electricity comes from the grid, but you're paying someone to put solar-generated electricity into the grid and pretending that you take out what they put in.</p>\n\n<p>Or maybe you have a solar panel array on your house, producing power during certain hours of the day. There are systems that just feed household demand, and systems that \"sell back\" power into the grid. For a local-only system, use only counts as solar if it happens when the sun is shining. </p>\n\n<h3>Reducing usage</h3>\n\n<p>This one you almost have a handle on, running an \"actual\" vs \"target\" model. But I don't see any indication of month-on-month or year-on-year tracking. Comparing my heating bill in April with my heating bill in March is going to show <strong>dramatic improvements!</strong> But it would be better to compare my heating bill in April 2019 with my heating bill from April 2018, since heating is a seasonal thing. </p>\n\n<p>Other things may be seasonal, or not. Laundry is probably not seasonal for some people, and seasonal for others (the kids! the sports! the laundry!). </p>\n\n<h3>Time-shifting</h3>\n\n<p>Every usage needs to have a timestamp associated, or needs to be an \"ongoing\" expense. For example, my gas range connects to the gas line, but there's also an electric plug to power the display (and the lights). The display shows the current time, except when I'm programming the oven. So the electric expense is pretty much constant, while the gas usage only happens when I'm using the stovetop or oven.</p>\n\n<p>Tracking that seems to mean there's at least two kinds of usage: on-demand or continuing. Another field.</p>\n\n<h3>Alternate solutions</h3>\n\n<p>Appliances can consume more than one kind of resource. A washing machine will consume water and electricity. And possibly hot water, which means it might trigger costs from a water heater. A range can consume electricity and natural gas or LP gas. A home heating system can consume electricity and hot water.</p>\n\n<p>Consumption can be fixed: some power is required to run the little green light on the front of every electric device. But consumption can also be on-demand. Some costs might be best modeled as constant even if they are not: a refrigerator usually turns itself on and off as needed, making it a \"demand\" type appliance, but you don't have any control over when the demand happens (except not opening the door!) so you should model it as a fixed cost.</p>\n\n<p>This says to me that an appliance object would not contain cost data. It's too complicated. Instead, there should be a separate costing mechanism that appliances refer to.</p>\n\n<p>Appliances can vary in \"intensity\" by use. I can wash dark colors which uses cold water, or I can wash white cotton using hot water. I can wash a small or large load of clothes. I can cook pizza at high heat, or I can re-heat leftovers at low heat. So the activity needs to account for this, and the costing function needs to allow for some variable in its operation.</p>\n\n<p>So you have <code>appliances</code> that use <code>resources</code> in continuing or on-demand costs. You don't specify how you are gathering information. If the information is entered by hand, I'd suggest you provide some kind of <code>activity</code> template for the user: \"Took a hot shower. Duration X minutes.\" This is probably easer than trying to enter \"Hot water heater: 2.2 gpm @ X minutes\" and \"Cold water: 0.4 gpm @ X minutes\". </p>\n\n<p>On the other hand, if you are gather data via sensors, there won't necessarily be any association between the activities and the expenses. (The water heater ran for 18 minutes this morning.) That will make it harder to suggest improvement goals.</p>\n\n<h2>3. Savings</h2>\n\n<p>This is relatively straightforward, if you have concrete, numerical goals and categories. There's no real evidence of this in your design. You have a <code>budget - actual</code> computation, but nothing more. </p>\n\n<p>You would need to have strong support for resource types first, in order to have a resource budget, then resource savings. If I want to reduce my water consumption, I need to be tracking water use. If I just want to reduce my monthly monetary outlay, your mechanism probably works. I give this a 'C'.</p>\n\n<h2>4. Suggest Goals</h2>\n\n<p>This is interesting, because it's not the goals that are important, but the suggesting. How do you know what goals to suggest?</p>\n\n<p>The spec suggests that a \"template\" mechanism might exist, with some kind of user editing facility.</p>\n\n<p>I don't see any of that in your design. This is a fail.</p>\n\n<p>How could you implement this?</p>\n\n<p>Create some templates and meta-templates. For example, if a resource has a time-cost element, then time-shifting resource use is a viable goal. If a resource has a cost breakpoint, then reducing or increasing resource usage towards that breakpoint can make sense if the overall costs balance out.</p>\n\n<p>Consider:</p>\n\n<ul>\n<li><p>If electricity has peak/off-peak costing, then it makes sense to suggest time-shifting the use of appliances like the washing machine or electric range. </p></li>\n<li><p>If sustainability is a goal, it makes sense to suggest favoring charcoal or wood over gas or electric.</p></li>\n<li><p>If carbon footprint is a goal, it makes sense to suggest gas over electric over charcoal, wood, and peat.</p></li>\n<li><p>If gas has a low initial consumption charge with a higher charge after some threshold, then it makes sense to suggest lowering gas consumption if the household is close to (but over) that threshold. It makes no sense to suggest lowering consumption if the threshold is 150 but the household is using 2000. But if the household uses 2100 and the threshold is 2000, they might see good savings by reducing that 100 units to get out of the high-cost range.</p></li>\n</ul>\n\n<p>So you should classify possible goals according to things like \"cost-saving\", \"sustainability\", \"carbon footprint\". Then allow these categories to be prioritized or disabled. Finally, each goal should be evaluated with regard to applicability (do not suggest reducing gas consumption in an all-electric household), reachability, and value. If a goal does not apply, or cannot be reached, or will not provide useful value, don't suggest it. </p>\n\n<p>Otherwise, rank the goals in some order, and suggest them. You might want to include a seasonal component: if you suggest using more charcoal during the summer, I'll grab a beer and some bratwursts and head outside. If you suggest using more charcoal when there's 8 inches of snow on the ground, I'll make fun of you on social media and uninstall the app.</p>\n\n<h2>5. Other scenarios</h2>\n\n<p>I'm going to skip these.</p>\n\n<h2>Evaluation criteria</h2>\n\n<p>You haven't picked an application model, as far as I can tell. Is your application intended to run on an embedded device, as an Android app, on a desktop, or on the web?</p>\n\n<p>That choice is going to affect pretty much all the options listed in the spec. Does it make sense to store data in a database versus in-memory? Should you use flat files? Can you add a jar file with some extra classes later, or download an update from the app store? </p>\n\n<h3>Alternate solutions</h3>\n\n<p>If you have a database, then a lot of items can be referenced using <code>id</code> fields. Maybe those are strings, maybe they are integers. But if they are unique ids, it doesn't matter. </p>\n\n<p>If you don't have a database, should you use <code>enum</code> types? Doing so reduces your ability to extend, since you'd have to rebuild if you add to the enum. That's possible for web and android apps, since the cost of deployment is low.</p>\n\n<p>If you are integrating with 3rd-party systems, what kind? It might be trivial to add support for cost data from the local utility, or incredibly difficult to get usage data from a smart switch.</p>\n\n<p>Also, what kind of integrations will you support. If you have sensors detecting the flow of resources, that's somewhat useful. But \"gas is being used\" or \"electric usage went up\" isn't as granular as \"I turned on the stove burner high for 20 minutes\". You'll want to be careful about what kind of data you collect, and how you use it. I'd suggest listing example integrations you think would obviously work, and leave it at that.</p>\n\n<p>For \"complicated\" mechanisms, an interface is the go-to solution in Java. It's up to you to define where. Computation of costs seems obvious, but there might be others. You should specify a mechanism for things like plug-ins that can be used to add additional support for these interfaces. Can you add a new electricity-costing plugin for a new provider? </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-02T20:56:45.443", "Id": "432863", "Score": "0", "body": "visiting after a long time...but Really Thankful!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-02T20:58:34.873", "Id": "432867", "Score": "0", "body": "I feel there is a necessity for System-design tag in stackexchange.\nWould you mind doing that ?" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-01T15:40:05.173", "Id": "219507", "ParentId": "217849", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-21T21:05:07.640", "Id": "217849", "Score": "3", "Tags": [ "java", "object-oriented", "interview-questions" ], "Title": "Design a sustainable home tracker and calibrater for power, water, gas to minimize the expense" }
217849
<p>I run a program of simulation N times (I use each time a different random numbers to initialize it). The results of the program are stored in 2N directories: every run produces two approximations. The directories contain the same files and have the following structure:</p> <blockquote> <p>def-risultati-i, i = 1, ... , N</p> <p>exc-risultati-i, i = 1, ... , N</p> </blockquote> <p>Where def and exc are test names of the approximations. In each one of the directories there are histograms files (file-a.dat, file-b.dat, ...)</p> <blockquote> <p>bin_left bin_right weight error</p> </blockquote> <p>Where each bin is identified by the values of beginning and end.</p> <p>I've written a program that takes a file from every directory and produces the average of the corresponding histogram. So for instance I take the file risultati.dat from</p> <blockquote> <p>def-risultati-1, def-risultati-2, ... , def-risultati-N,</p> </blockquote> <p>The code works fine but I'd like to improve the structure of the function that does all the job. There are some redundant passages (e.g. I store the values of the bins for the files taken from every directory, even though they are the same for every run of the program) and my c++ skills are rusty. I'm not sure about those nested for loops on a vector of vectors...</p> <p>Here it is a &quot;demo&quot; of the program:</p> <pre><code>#include &lt;iostream&gt; #include &lt;fstream&gt; #include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;vector&gt; #include &lt;cmath&gt; void merge(int N, std::string appr, std::string title) { double a; std::string fin_dir = appr + &quot;-totale&quot;; std::string init_dir = appr + &quot;-risultati-&quot;; std::string num, dir; std::ifstream ri; std::ofstream out(fin_dir+title); std::vector&lt;std::vector&lt;double&gt;&gt; v_ri; for(int j=1; j&lt;=N; j++){ num = std::to_string(j); dir = init_dir+num+title; ri.open(dir); std::vector&lt;double&gt; v; while(ri &gt;&gt; a){ v.push_back(a); } v_ri.push_back(v); ri.close(); } a=0; std::vector&lt;double&gt; weight; for(int k=2; k&lt;v_ri[0].size(); k=k+4){ for(int j=0; j&lt;v_ri.size(); j++){ a = a+v_ri[j][k]/double(N); } weight.push_back(a); a=0; } a=0; std::vector&lt;double&gt; err; for(int k=3; k&lt;v_ri[0].size(); k=k+4){ for(int j=0; j&lt;v_ri.size(); j++){ a = a+pow(v_ri[j][k], 2)/double(N); } a = sqrt(a); err.push_back(a); a=0; } int cont = 0; for(int i=0; i&lt;v_ri[0].size(); i=i+4){ out &lt;&lt; std::scientific &lt;&lt; v_ri[0][i] &lt;&lt; &quot; &quot; &lt;&lt; v_ri[0][i+1] &lt;&lt; &quot; &quot;; out &lt;&lt; std::scientific &lt;&lt; weight[cont] &lt;&lt; &quot; &quot; &lt;&lt; err[cont] &lt;&lt; std::endl; cont++; } } int main(){ //merge(numeber_of_directories, &quot;exc&quot;/&quot;def&quot;, title) //title: /namefile.dat int N=3; merge(N, &quot;exc&quot;, &quot;/ris.dat&quot;); merge(N, &quot;def&quot;, &quot;/ris.dat&quot;); return 0; } </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-21T21:12:25.917", "Id": "217850", "Score": "1", "Tags": [ "c++", "strings", "c++11", "file-system", "vectors" ], "Title": "Average histogram combining multiple files and vector of vectors (in c++)" }
217850
<p>Out of curiosity I was discovering the potential of the <code>Ellipsis</code> object in Python (<code>...</code>), and I discovered it doesn't do a whole lot except for a handful of minor features. In an effort to make it useful, I decided to create the most fancy-pants constructor for a list that I could.</p> <p>The function, <code>super_list</code>, takes an arbitrary number of arguments to be added to the list. Here are the features:</p> <ul> <li><p><code>super_list(multiple, arguments, provided) -&gt;</code> Generates a list using the arguments provided. If an argument doesn't follow any of the special features below, it is just appended to the array at the proper nesting level. This example returns <code>[multiple, arguments, provided]</code>, a list of the arguments.</p></li> <li><p><code>super_list(5, ..., 9) -&gt;</code> Takes advantage of the <code>Ellipsis</code> object to create something that looks like "x to y", or a range. This particular example would produce a list containing <code>[5,6,7,8,9]</code>, the number between 5 and 9.</p></li> <li><p><code>super_list(arg, array.move_up, higher_arg, array.move_down, lower_arg) -&gt;</code> Sets the nesting level inside the list. Including <code>array.move_up</code> or <code>array.move_down</code> moves up or down one level of nesting in the list. This example produces <code>[arg, [higher_arg], lower_arg]</code>, moving up and down the array chain with <code>array.move_up</code> and <code>array.move_down</code>.</p></li> </ul> <p>One last big example:</p> <pre><code>super_list("first level", 5, ..., 9, array.move_up, array.move_up, "second level", 10, ..., 15, array.move_down, "down one level") </code></pre> <p>produces</p> <pre><code>['first level', 5, 6, 7, 8, 9, [['second level', 10, 11, 12, 13, 14, 15], 'down one level']] </code></pre> <p>So this is my current implementation:</p> <pre><code>def get_in_list(lst, indexes): """Gets an item in a nested list by a list of indexes.""" return functools.reduce(operator.getitem, indexes, lst) def super_list(*args): """Special initialization syntax for lists.""" curr_index = [] result = [] for index, item in enumerate(args): # Iterate over args with indexes el_type = type(...) # Type of the Ellipsis object if isinstance(item, el_type): # Case: Ellipsis range generator if index == 0: get_in_list(result, curr_index).append(item) else: get_in_list(result, curr_index).extend(list(range(args[index-1]+1, args[index+1]))) elif item == array.move_up: # Case: move up one level in list get_in_list(result, curr_index).append([]) curr_index.append(len(get_in_list(result, curr_index))-1) elif item == array.move_down: # Case: move down one level in list try: curr_index.pop() except IndexError: # Silently catch if user tries to move down too far in the list pass else: # Case: No special syntax - regularly append item to list get_in_list(result, curr_index).append(item) return result </code></pre> <p><code>get_in_list</code> is a function used to get an item at a list of indexes. This means that <code>a[0][1] == get_in_list(a, [0, 1])</code>.</p> <p>My questions:</p> <ul> <li><p>Is it too messy?</p></li> <li><p>Is anything too long and could be implemented in a shorter way?</p></li> <li><p>Is the program too confusing, and do you think it could be more verbose?</p></li> </ul> <p>And obviously, any other comments you may want to add are appreciated. Thanks in advance!</p>
[]
[ { "body": "<p>I'm severely confused by <code>array.move_down</code>, because I don't see any array or anything moving anywhere. If you are doing a <code>super_list</code>, wouldn't it be more readable to have <code>sublist.begin</code> and <code>sublist.end</code>?</p>\n\n<p>Also I don't like fail-later approach with hiding an exception. If user makes an error in nesting lists, I would fail fast instead. It's a common behavior of all the languages I know (with an exception of early/ancient HTML).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-21T22:01:20.047", "Id": "421540", "Score": "0", "body": "\"Moving\" is going up or down to the next level of array nesting (`move_up` from `[1,0]` is doing `[1,0,[]]`)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-21T22:02:08.863", "Id": "421541", "Score": "0", "body": "And I used array to not name-mangle with the builtin `list` type, because that's bad practice." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-21T22:04:14.927", "Id": "421542", "Score": "0", "body": "I understand your motive, but it's confusing to me. In OOP, `array.move_down` means I intend to move the array down - I would never have guessed that it starts a nested sublist. Oh, sorry... ends a sublist?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-21T22:07:02.420", "Id": "421543", "Score": "0", "body": "I understand your point. What do you think I should change it to? I'd like to keep it short, if possible. Maybe `new_list` and `end_list`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-21T22:10:59.660", "Id": "421544", "Score": "0", "body": "How about `sublist` and `endsub`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-21T22:11:24.997", "Id": "421545", "Score": "0", "body": "That's a good idea, I think I'll implement that, Thanks a lot!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-22T13:46:28.033", "Id": "421628", "Score": "0", "body": "Why not use an Enum?" } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-21T21:58:50.083", "Id": "217853", "ParentId": "217852", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-21T21:22:37.827", "Id": "217852", "Score": "4", "Tags": [ "python", "python-3.x", "array", "constructor" ], "Title": "Super fancy list constructing in Python" }
217852
<p>In my Uni, my scientific professor asked me to make some researches about the extreme points of polyhedrals. And I did them. I found that there is still no code in public for searching extreme points for polyhedral with n dimensions (n - x's), but polyhedrons are everywhere (CV, game theories, etc.). I wrote a function for this task and made a python library (also there are matrix and array combination maker functions).</p> <p>All I want is to make this code more optimal and compatible for all python versions (I have some troubles that some times happen when I install it by "pip install lin", but other times no). I want to make the life of people easier and make it more comfortable.</p> <p>I am asking for you to test this function on your computer and write if you have any bugs, fails or thoughts on how to make it better. I am open to constructive criticism and non-constructive too (it will help to understand if somebody needs it or that is just a waste of time).</p> <p>All the examples, instructions and code on my GitHub: <a href="https://github.com/r4ndompuff/polyhedral_set/tree/c61eb1264a937cd0c87771bdb3a61c452455a314" rel="nofollow noreferrer">https://github.com/r4ndompuff/polyhedral_set</a></p> <pre class="lang-py prettyprint-override"><code>import numpy as np import itertools as it import math import re def permutation(m,n): return math.factorial(n)/(math.factorial(n-m)*math.factorial(m)) def matrix_combinations(matr,n): timed = list(map(list, it.combinations(matr, n))) for i in range(n): timed[i][i][i] = np.asscalar(timed[i][i][i]) all = np.array(list(timed)) return all def array_combinations(arr,n): timed = list(map(list, it.combinations(arr, n))) for i in range(n): timed[i][i] = np.asscalar(timed[i][i]) all = np.array(list(timed)) return all def check_extreme(matr, arr, x, sym_comb, m): sym_comb = sym_comb.replace(']', '') sym_comb = sym_comb.replace('[', '') sym_comb = re.split("[ ,]", sym_comb) for i in range(m): td_answer = sum(matr[i]*x) if sym_comb[i] == '&gt;': if td_answer &lt;= arr[i]: return 0 elif sym_comb[i] == '&gt;=': if td_answer &lt; arr[i]: return 0 elif sym_comb[i] == '&lt;': if td_answer &gt;= arr[i]: return 0 elif sym_comb[i] == '&lt;=': if td_answer &gt; arr[i]: return 0 elif sym_comb[i] == '=': if td_answer != arr[i]: return 0 elif sym_comb[i] == '!=': if td_answer == arr[i]: return 0 else: return 0 return 1 def extreme_points(m,n,A,b,sym_comb): # Input A = np.array(A).reshape(m,n) b = np.array(b).reshape(m,1) # Proccess ans_comb = np.zeros((1,n)) arr_comb = array_combinations(b,n) matr_comb = matrix_combinations(A,n) for i in range(int(permutation(n,m))): if np.linalg.det(matr_comb[i]) != 0: x = np.linalg.solve(matr_comb[i],arr_comb[i]) ans_comb = np.vstack([ans_comb,x]) ans_comb = np.delete(ans_comb, (0), axis=0) j = 0 for i in range(len(ans_comb)): if check_extreme(A, b, ans_comb[j], sym_comb, m): ans_comb = ans_comb j = j + 1 else: ans_comb = np.delete(ans_comb, (j), axis=0) # Output return ans_comb </code></pre> <p>And I am uploading some more tests. <a href="https://imgur.com/mjweDyy" rel="nofollow noreferrer">https://imgur.com/mjweDyy</a></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-21T23:21:29.250", "Id": "421554", "Score": "0", "body": "Can you provide some more information on what exactly is going on, from a math standpoint? Is this actually a polyhedron, or a polytope? In how many dimensions? By \"extreme\", what do you mean? Euclidean norm from (the origin, an arbitrary point)?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-21T23:22:17.780", "Id": "421555", "Score": "0", "body": "\"there is still no code in public for searching extreme points for polyhedral with n dimensions\" - I can nearly guarantee that that isn't the case." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-22T00:32:26.463", "Id": "421558", "Score": "2", "body": "@Reinderien I am still in the process of deciphering the question. I have a math background, and I share the mother tongue with OP. My impression is that by extremal points OP means the vertices of a simplex where a certain linear form (defined by `A`, `b`, and the condition) achieves an extremum. I could be wrong." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-22T00:33:45.810", "Id": "421559", "Score": "0", "body": "@vnp That's kind of what I guessed, and if that's the case, linear programming is a quite well-established field already - with some stuff built right into scipy." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-22T00:34:46.883", "Id": "421560", "Score": "0", "body": "@Reinderien Agreed. Still deciphering." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-22T00:48:39.810", "Id": "421562", "Score": "0", "body": "@AndrewLovyagin When I run, I get this error: `TypeError: No loop matching the specified signature and casting\nwas found for ufunc solve1`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-22T00:52:46.737", "Id": "421564", "Score": "0", "body": "This occurs for both Python 3.7 and 2.7. However, I'm using numpy-1.16.2, which I strongly suggest you adopt." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-22T07:11:31.020", "Id": "421582", "Score": "0", "body": "@Reinderien\nI was using this article (https://www.cs.bgu.ac.il/~ilp152/wiki.files/hwk2.pdf) to understand what is polyhedron.\nAnd I am using n-dimensions (that means you can put any positive integer number in the first and second argument of the function). \nFor the solving system of equations (Ax=b) I am using numpy.linalg.solve(), but before I am checking if matrix A, not a degenerate matrix.\nI don't know what is polytope, but I google it, and now I am interested :0" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-22T07:12:30.040", "Id": "421583", "Score": "0", "body": "@vnp\nI was using this article to understand it from math point: https://www.cs.bgu.ac.il/~ilp152/wiki.files/hwk2.pdf" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-22T07:13:15.917", "Id": "421584", "Score": "0", "body": "I'm fairly certain it's linear programming" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-22T07:17:02.523", "Id": "421585", "Score": "0", "body": "@Reinderien\nThank you for your report. I will try to update this program to work with latest preinstalled numpy (mine is 1.15.4).\n\nFrom the math point: I am making all combinations of matrix A NxN (where N is a number of dimensions). Then I am solving each system of equations for the same combinations of vector b and checking the answers if they are really an extreme points." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-22T16:19:27.620", "Id": "421643", "Score": "0", "body": "Can you explicitly define `w`, `x`, `u` and `U` as seen in your docs?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-22T19:50:48.970", "Id": "421694", "Score": "0", "body": "Look up \"convex hull\" to find examples of getting the boundaries (extreme points) of a series of points (e.g. the vertices of your polyhedral)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-22T21:10:23.773", "Id": "421711", "Score": "0", "body": "@Reinderien I wrote it by hand on example to made it more explicit: https://imgur.com/oZF9uf4" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-22T21:21:28.737", "Id": "421714", "Score": "0", "body": "@AJD Yep, I was reading about it, when was writing the code, thank you. I will try to dig deeper into this theme." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-22T21:36:52.733", "Id": "421716", "Score": "0", "body": "Given the number of comments already, let's please continue this at https://chat.stackexchange.com/rooms/92760/searching-extreme-points-of-polyhedron" } ]
[ { "body": "<p>I created a rudimentary pull request to your GitHub repo. I won't show all of the content here except for the main file:</p>\n\n<pre><code>import numpy as np\nimport itertools as it\nfrom math import factorial\nimport re\n\n\ndef permutation(m, n):\n return factorial(n) / (factorial(n - m) * factorial(m))\n\n\ndef matrix_combinations(matr, n):\n timed = list(map(list, it.combinations(matr, n)))\n return np.array(list(timed))\n\n\ndef array_combinations(arr, n):\n timed = list(map(list, it.combinations(arr, n)))\n return np.array(list(timed))\n\n\ndef check_extreme(matr, arr, x, sym_comb, m):\n sym_comb = sym_comb.replace(']', '')\n sym_comb = sym_comb.replace('[', '')\n sym_comb = re.split(\"[ ,]\", sym_comb)\n for i in range(int(m)):\n td_answer = sum(matr[i] * x)\n if sym_comb[i] == '&gt;':\n if td_answer &lt;= arr[i]:\n return 0\n elif sym_comb[i] == '&gt;=':\n if td_answer &lt; arr[i]:\n return 0\n elif sym_comb[i] == '&lt;':\n if td_answer &gt;= arr[i]:\n return 0\n elif sym_comb[i] == '&lt;=':\n if td_answer &gt; arr[i]:\n return 0\n elif sym_comb[i] == '=':\n if td_answer != arr[i]:\n return 0\n elif sym_comb[i] == '!=':\n if td_answer == arr[i]:\n return 0\n else:\n return 0\n return 1\n\n\ndef extreme_points(A, b, sym_comb):\n # Input\n A = np.array(A)\n b = np.array(b)\n m, n = A.shape\n # Process\n ans_comb = np.zeros((1, n))\n arr_comb = array_combinations(b, n)\n matr_comb = matrix_combinations(A, n)\n for i in range(int(permutation(n, m))):\n if np.linalg.det(matr_comb[i]) != 0:\n x = np.linalg.solve(np.array(matr_comb[i], dtype='float'),\n np.array(arr_comb[i], dtype='float'))\n ans_comb = np.vstack([ans_comb, x])\n ans_comb = np.delete(ans_comb, 0, axis=0)\n j = 0\n for i in range(len(ans_comb)):\n if check_extreme(A, b, ans_comb[j], sym_comb, m):\n ans_comb = ans_comb\n j += 1\n else:\n ans_comb = np.delete(ans_comb, j, axis=0)\n # Output\n return ans_comb\n</code></pre>\n\n<p>Notable changes:</p>\n\n<ul>\n<li>Do a direct import of <code>factorial</code></li>\n<li>Don't call <code>asscalar</code>, since it's both unneeded and deprecated</li>\n<li>Don't call a variable <code>all</code>, since that shadows a Python built-in</li>\n<li>Don't need to explicitly pass array dimensions, nor do you need to reshape the arrays</li>\n<li>Drop redundant parens around some expressions</li>\n<li>Use <code>+=</code> where applicable</li>\n<li>Fix up almost all PEP8 issues, except for your capital letter <code>A</code>, which is fine in context</li>\n</ul>\n\n<p>This doesn't solve the bigger issue that you should replace 99% of this with a call to scipy. I'll do that separately (I suspect that @vnp is, as well).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-22T07:57:11.740", "Id": "421591", "Score": "1", "body": "Thank you!\nIn meantime I made it work with any NumPy version now (about loop error you report)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-22T08:17:48.957", "Id": "421593", "Score": "0", "body": "Sorry, but I can't find the same function in scipy. Can you provide me the name of function?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-22T16:18:13.270", "Id": "421642", "Score": "0", "body": "@AndreyLovyagin https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.linprog.html" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-22T20:39:42.417", "Id": "421703", "Score": "0", "body": "Thank you very much for all that you have done!\nAlso, I checked scipy.optimize.linprog() function and I can't really understand how it can replace much of the code. I will learn and read more about it, but on first sight, it looks like it can't solve non-equational system (I mean not '=', but any sign, e.g. '>='), that is why I can't see how I can find extreme points by it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-22T20:40:28.623", "Id": "421704", "Score": "0", "body": "Read about the A_ub, b_ub arguments." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-25T14:46:52.347", "Id": "423196", "Score": "0", "body": "Okay, I have checked it fully. Scipy functions didn't do the same. Scipy very useful for optimizing, but my task not only linear programming but also math programming, that's why A_ub and b_ub didn't help (I checked link examples, their answers are not extreme points for any inequality or equality." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-25T15:14:20.393", "Id": "423201", "Score": "0", "body": "My mistake. They are able to find an extreme points, but only one (cuz optimization). In an example, in scipy docs there are 2 more extreme points, but they output only one." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-22T00:46:47.277", "Id": "217860", "ParentId": "217855", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "16", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-21T22:57:06.193", "Id": "217855", "Score": "6", "Tags": [ "python", "algorithm", "numpy", "homework", "computational-geometry" ], "Title": "Searching extreme points of polyhedron" }
217855
<p>This code uses a single Mastermind class to hold everything needed as a tkinter widget that inherits from tk.Frame. Is this the best way of organising something like this or would it be better to use two classes - one for the game logic and one for the GUI?</p> <p>The code itself seems messy, although I have no experince with tkinter applications larger than a Hello World script, so ways to clean it up and/or reorganise it would be greatly appreciated.</p> <pre><code>import tkinter as tk from random import choices import itertools as it class Mastermind(tk.Frame): def __init__(self, master, holes=5, colours=8, guesses=12, bg="white", fg="black", **kwargs): self.numberOfHoles = holes self.numberOfColours = colours self.numberOfGuesses = guesses self.bg = bg self.fg = fg self.master = master self.colours = ["#9E5D00", "#FF0000", "#FF7F00", "#FFFF00", "#00FF00", "#0000FF", "#FF00FF", "#8C44FF", "#FFFFFF", "#000000"][:self.numberOfColours] self.reset_cycles() self.answer = choices(self.colours, k=self.numberOfHoles) super().__init__(self.master, bg=self.bg, **kwargs) print(self.answer) self.create_gui() def create_gui(self): self.allGuesses = [tk.Frame(self, bg=self.bg) for _ in range(self.numberOfGuesses)] self.allMarks = [tk.Frame(self, bg=self.bg) for _ in range(self.numberOfGuesses)] self.answerFrame = tk.Frame(self, bg=self.bg) self.answerCover = tk.Frame(self, bg=self.fg, relief=tk.RAISED) self.allGuessPins = [[tk.Label(self.allGuesses[i], width=2, height=1, bg="grey", relief=tk.SUNKEN) for _ in range(self.numberOfHoles)] for i in range(self.numberOfGuesses)] self.allMarkPins = [[tk.Label(self.allMarks[i], width=1, height=1, bg="lightgrey", relief=tk.SUNKEN) for _ in range(self.numberOfHoles)] for i in range(self.numberOfGuesses)] self.answerPins = [tk.Label(self.answerFrame, width=2, height=1, bg=colour, relief=tk.RAISED) for colour in self.answer] self.guessBtn = tk.Button(self, text="Guess", command=self.next_guess, bg=self.bg, fg=self.fg) self.activeGuess = 0 for rowIndex in range(self.numberOfGuesses): for holeIndex in range(self.numberOfHoles): self.allGuessPins[rowIndex][holeIndex].grid(row=0, column=holeIndex, padx=1, pady=4) self.allMarkPins[rowIndex][holeIndex].grid(row=0, column=holeIndex, padx=1, pady=4) tk.Label(self, text=str(rowIndex+1), bg=self.bg, fg=self.fg).grid(row=self.numberOfGuesses-rowIndex, column=0) self.allGuesses[rowIndex].grid(row=rowIndex+1, column=1) self.allMarks[rowIndex].grid(row=rowIndex+1, column=3) for i, a in enumerate(self.answerPins): a.grid(row=0, column=i, padx=1) tk.Label(self, text=" ", bg=self.bg).grid(row=0, column=2) tk.Label(self, text=" ", bg=self.bg).grid(row=0, column=4) for a in [tk.Label(self.answerCover, width=2, height=1, bg=self.fg) for _ in range(self.numberOfHoles)]: a.pack(side=tk.LEFT, padx=1) self.answerCover.grid(row=0, column=1, pady=15) self.guessBtn.grid(column=1, row=999, pady=10) self.next_guess(start=True) def next_guess(self, start=False): # Check there are no blanks for colour in self.get_pin_colours(): if colour == "grey" and not start: return None # Stop responding to mouse button and remove highlighting self.reset_cycles() self.allGuesses[self.activeGuess].config(bg=self.bg) for pin in self.allGuessPins[self.activeGuess]: pin.unbind("&lt;1&gt;") pin["cursor"] = "" # Add the mark pins for the guess score = self.score_guess(self.get_pin_colours(), self.answer) if not start and len(score) != 0: score = self.score_guess(self.get_pin_colours(), self.answer) for i, pin in enumerate(self.allMarkPins[self.activeGuess]): if i &gt; len(score)-1: break pin.config(bg=score[i], relief=tk.RAISED) # Check for a win if score == ["Black" for _ in range(self.numberOfHoles)]: self.answerCover.grid_forget() self.answerFrame.grid(row=0, column=1, pady=15) self.guessBtn["command"] = None return None # Move the guess up 1, bind mouse button and highlight row try: self.activeGuess -= 1 self.allGuesses[self.activeGuess].config(bg=self.fg) for i, pin in enumerate(self.allGuessPins[self.activeGuess]): pin.bind("&lt;1&gt;", lambda event, i=i: self.change_pin_colour(event, i)) pin["cursor"] = "hand" except IndexError: raise NotImplementedError() # add lose condition @staticmethod def score_guess(guess, answer): answer = answer.copy() blacks = ["Black" for secret, guess_item in zip(answer, guess) if secret == guess_item] whites = [] for guess_item in guess: if guess_item in answer: answer[answer.index(guess_item)] = None whites.append("White") return blacks + whites[:-len(blacks)] def get_pin_colours(self): return [pin["bg"] for pin in self.allGuessPins[self.activeGuess]] def change_pin_colour(self, event, i): event.widget.config(bg=next(self.colourCycles[i]), relief=tk.RAISED) def reset_cycles(self): self.colourCycles = it.tee(it.cycle(self.colours), self.numberOfHoles) if __name__ == "__main__": root = tk.Tk() root.title("Mastermind") x = Mastermind(root) x.pack() root.mainloop() </code></pre>
[]
[ { "body": "<p>Hello and welcome to CodeReview! (And thank you for using British spelling ;-) )</p>\n\n<p>You already identified the biggest thing -</p>\n\n<blockquote>\n <p>it [would] be better to use two classes - one for the game logic and one for the GUI</p>\n</blockquote>\n\n<p>Separation of concerns and loose coupling will be improved, in turn improving maintainability and testability, when those are separated. Other things:</p>\n\n<h2>snake_case</h2>\n\n<p><code>numberOfHoles</code>, by Python convention, should be <code>number_of_holes</code>.</p>\n\n<h2>Use type hinting</h2>\n\n<p>Take a read through <a href=\"https://www.python.org/dev/peps/pep-0484/\" rel=\"nofollow noreferrer\">PEP 484</a> and do some Googling; this will help out with program correctness and static analysis.</p>\n\n<h2>Fix up your indentation</h2>\n\n<p>You have <code>@staticmethod</code> on a top-level function. Either this shouldn't have that annotation, or it should live in the class. I think you've just failed to indent all of your member variables.</p>\n\n<h2>Repetition</h2>\n\n<pre><code>[\"Black\" for _ in range(self.numberOfHoles)]:\n</code></pre>\n\n<p>can be</p>\n\n<pre><code>[\"Black\"] * self.numberOfHoles\n</code></pre>\n\n<h2>State representation</h2>\n\n<p>You're using the strings <code>Black</code> and <code>White</code> to represent a player. There are better choices - maybe a boolean (false for black, true for white) or an enum - see <a href=\"https://docs.python.org/3/library/enum.html\" rel=\"nofollow noreferrer\">https://docs.python.org/3/library/enum.html</a></p>\n\n<p>Or, you could have two instances of a class Player, and track your state like that. But don't use a string.</p>\n\n<h2>Redundant return</h2>\n\n<pre><code>return None\n</code></pre>\n\n<p>can be deleted if it's at the end of a function, or written as <code>return</code> if it's to early-terminate a loop.</p>\n\n<h2>Simplify logic</h2>\n\n<pre><code>if i &gt; len(score)-1\n</code></pre>\n\n<p>can be</p>\n\n<pre><code>if i &gt;= len(score)\n</code></pre>\n\n<p>However, there's a bigger problem. This loop:</p>\n\n<pre><code> for i, pin in enumerate(self.allMarkPins[self.activeGuess]):\n if i &gt; len(score)-1:\n break\n pin.config(bg=score[i], relief=tk.RAISED)\n</code></pre>\n\n<p>should just be</p>\n\n<pre><code>for i, pin in enumerate(self.all_mark_pins[self.active_guess][:len(score)]):\n pin.config ...\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-22T18:36:12.023", "Id": "421679", "Score": "0", "body": "Thank you very much for this breakdown. I did just mess up the indentation when I posted the question. The reason I was using \"Black\" and \"White\" instead of True and False was that it was being passed into tkinter directly to set the pin colour. Adding something to convert True to \"Black\" etc. seemed to be pointless to me." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-22T18:39:16.820", "Id": "421680", "Score": "2", "body": "@SImon It isn't pointless; converting from business logic representation to presentation is a normal and useful thing to do." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-21T23:42:21.057", "Id": "217858", "ParentId": "217856", "Score": "3" } } ]
{ "AcceptedAnswerId": "217858", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-21T22:57:15.753", "Id": "217856", "Score": "4", "Tags": [ "python", "python-3.x", "game", "tkinter" ], "Title": "Create the logic game Mastermind using a GUI" }
217856
<p>I've been tasked with writing a simple trellis generator. The user is prompted with entering the height and width of the desired trellis, and gets a printed result of a trellis with the entered dimensions. I'm looking for code compact improvements, as I was told to use as little code as possible to generate the trellis.</p> <p><strong>script.py</strong></p> <pre><code>height = input("Enter EVEN height of trellis: ") width = input("Enter EVEN width of trellis: ") print(("--" * width) + "--" ) for i in range(height): print("|" + ("/\\" * width) + "|") print("|" + ("\\/" * width) + "|") print(("--" * width) + "--") </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-22T19:21:49.333", "Id": "421686", "Score": "0", "body": "Is it a \"hard\" requirement to support Python 2? Or can you upgrade?" } ]
[ { "body": "<p>I really don't get the <code>&quot;Enter EVEN height of trellis: &quot;</code> part.</p>\n\n<pre><code>Enter EVEN height of trellis: 3\nEnter EVEN width of trellis: 3\n--------\n|/\\/\\/\\|\n|\\/\\/\\/|\n|/\\/\\/\\|\n|\\/\\/\\/|\n|/\\/\\/\\|\n|\\/\\/\\/|\n--------\n</code></pre>\n<p>But let's continue.</p>\n<p><strong>Assumptions:</strong></p>\n<ol>\n<li>Shorten means lessen the number of characters</li>\n<li>Neatness of the code matters</li>\n</ol>\n<p>Ways to shorten the code:</p>\n<ul>\n<li>Change <code>height</code> to <code>h</code> and <code>width</code> to <code>w</code></li>\n<li>Convert <code>(&quot;--&quot; * w) + &quot;--&quot;</code> to <code>&quot;--&quot; * (w+1)</code></li>\n<li>Join the two inputs using <code>raw_input</code> and <code>map</code>:<br />\n<code>h, w = map(int, raw_input(&quot;Enter EVEN 'height width' of trellis: &quot;).split())</code></li>\n<li>Join the two <code>print</code> statements in the for loop:<br />\n<code> print (&quot;|&quot; + &quot;/\\\\&quot; * w + &quot;|&quot;) + &quot;\\n&quot; + (&quot;|&quot; + &quot;\\\\/&quot; * w + &quot;|&quot;)</code></li>\n</ul>\n<p>If neatness doesn't matter, remove all spaces and newlines in the code.</p>\n<p>My improved version:</p>\n<pre><code>h, w = map(int, raw_input(&quot;Enter EVEN 'height width' of trellis: &quot;).split())\n\nprint &quot;--&quot; * (w+1)\n\nfor i in range(h):\n print (&quot;|&quot; + &quot;/\\\\&quot; * w + &quot;|&quot;) + &quot;\\n&quot; + (&quot;|&quot; + &quot;\\\\/&quot; * w + &quot;|&quot;)\n\nprint &quot;--&quot; * (w+1)\n</code></pre>\n<p>Customize the code as you wish!</p>\n<p>That's all I can think about. Good luck!</p>\n<p><strong>Edit:</strong>\nIf python 3.x is allowed:</p>\n<pre class=\"lang-py prettyprint-override\"><code>h, w = map(int, input(&quot;Enter EVEN 'height width' of trellis: &quot;).split())\nprint('--' * (w+1), *((&quot;|&quot; + &quot;/\\\\&quot; * w + &quot;|&quot;) + '\\n' + (&quot;|&quot; + &quot;\\\\/&quot; * w + &quot;|&quot;) for _ in range(h)), '--' * (w+1), sep='\\n')\n</code></pre>\n<p>I hope it works. I haven't checked it :D</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-22T19:21:26.807", "Id": "421685", "Score": "0", "body": "`raw_input` should be avoided since it isn't compatible with Python 3. You can do an equivalent operation that will be compatible with both." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-22T19:23:21.637", "Id": "421687", "Score": "0", "body": "I also think that the gymnastics you've done with `map` are on the whole counterproductive; even if you want to \"code golf\" this thing there are saner ways." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-22T19:55:13.803", "Id": "421697", "Score": "0", "body": "Furthermore, your input isn't equivalent. You're asking the user to input a tuple, instead of inputting the height and width individually." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-23T07:20:07.507", "Id": "421754", "Score": "0", "body": "@David White wanted to make the code as small as possible. And of course, I added `Customize the code as you wish!` :D" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-23T07:22:49.493", "Id": "421755", "Score": "0", "body": "`raw_input should be avoided since it isn't compatible with Python 3.` I thought about it first too, but the question tag says `python 2.x`" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-22T09:10:47.197", "Id": "217875", "ParentId": "217857", "Score": "3" } }, { "body": "<p>Since we're playing code golf, this is passable - but please don't do it in production. It's too confusing. I've taken the liberty of using Python 3 despite the question being tagged for 2; if you really need it for 2 I can provide an alternative (that will be longer).</p>\n\n<pre><code>h, w = (int(input(f'Enter EVEN {dim} of trellis: ')) for dim in ('height', 'width'))\narrow = r'\\/'\nprint('{horz}\\n{rows}{horz}'.format(horz='--'*(w + 1),\n rows=f'|{arrow[::-1] * w}|\\n|{arrow * w}|\\n' * h))\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-22T19:53:29.457", "Id": "217905", "ParentId": "217857", "Score": "5" } } ]
{ "AcceptedAnswerId": "217875", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-21T23:32:51.230", "Id": "217857", "Score": "3", "Tags": [ "python", "python-2.x" ], "Title": "Trellis Generator" }
217857
<p>I'm working through a practice problem and am wondering if there's a more efficient way of writing my code and/or if the syntax for my pointers looks correct.</p> <p><strong>The practice problem:</strong></p> <ul> <li>Given the absolute temperatures Tc of a cold reservoir and Th of a hot reservoir (in degrees Kelvin), the coefficients of performance (cp) of the refrigeration cycle and heat pump are given by: <ul> <li>Refrig: cp = Tc / (Th - Tc)</li> <li>Heat: cp = Th / (Th - Tc)</li> </ul></li> <li>Write a program that will call a function to prompt the user for the values of Tc and Th . It then calls a function that calculates the two coefficients of performance. Finally, it calls a function to print the results.</li> </ul> <p>Here is what I have:</p> <pre><code>#include &lt;stdio.h&gt; void temperature(float *, float *); void performance(float,float,float *, float *); void PrintResults(float,float,float,float); int main() { float Tc, //cold reservoir; user input Th, //hot reservoir; user input Rcp, //refrigeration cycle coefficient of performance Hcp; // Heat pump coefficient of performance temperature(&amp;Tc,&amp;Th); //Prompts user for cold &amp; hot reservoir temperatures performance(Tc,Th,&amp;Rcp,&amp;Hcp); //Calculates the coefficients of performance PrintResults(Tc,Th,Rcp,Hcp); //Prints the coefficients of performance return 0; } void temperature(float *ptrTc, float *ptrTh) { printf("Enter the absolute temperature for a cold reservoir (in Kelvin): "); scanf("%f",&amp;*ptrTc); printf("Enter the absolute temperature for a hot reservoir (in Kelvin): "); scanf("%f",&amp;*ptrTh); } void performance(float Tc, float Th, float *ptrRcp, float *ptrHcp) { *ptrRcp = Tc/(Th-Tc); *ptrHcp = Th/(Th-Tc); } void PrintResults(float Tc, float Th, float Rcp, float Hcp) { printf("\nGiven the absolute temperatures of %.2f K for the cold reservoir",Tc); printf(" and %.2f K for the hot reservoir,",Th); printf(" the coefficient of performance for the refrigeration cycle is %.2f K",Rcp); printf(" and the coefficient of performance for the heat pump is %.2f K\n",Hcp); } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-22T07:20:28.523", "Id": "421586", "Score": "2", "body": "Use verbs for function names. `get_temp()` and `calc_temp_performance()`. Make pointers const in performance(). E.g. `void performance(float, float, float *const, float *const)` since pointers aren't and shouldn't be modified, only the data they point to is. Couple other tweaks, but some things to think about for now." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-22T07:26:07.303", "Id": "421587", "Score": "1", "body": "@ahogen as far as possible, parameters should not be modified, be it pointers or floats. Therefore it would make sense to either make all parameters `const` or none of them. I prefer the \"none of them\" variant and let a linter check that parameter variables aren't modified." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-22T07:27:52.123", "Id": "421588", "Score": "1", "body": "Is the coefficient really measured in Kelvin? It is calculated by dividing Kelvin by Kelvin, so it should be a scalar." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-22T16:27:27.037", "Id": "421645", "Score": "1", "body": "@RolandIllig Sure, but when things are passed by value, not by reference, then making it `const` doesn't do anything in terms of global data protection. I'm from embedded land, so if I can use that variable and not add something else to the stack, that's a win. My rule has been to `const` all pass-by-refs unless they must be modified. Leave pass-by-value un-const if you might use them." } ]
[ { "body": "<blockquote>\n <p>if the syntax for my pointers looks correct</p>\n</blockquote>\n\n<p>The syntax for the pointers is correct in all the function parameters, however, the pointer syntax is incorrect or unnecessary in the two scanf statements. The two output variables passed into <code>temperature(float *, float*)</code> are already addresses of variables so in this case the proper code would be</p>\n\n<pre><code> scanf(\"%f\", ptrTc);\n scanf(\"%f\", ptrTh);\n</code></pre>\n\n<p>You would only need <code>&amp;</code> if this was in the main program and Tc and Th were being read directly.</p>\n\n<pre><code> float Tc;\n scanf(\"%f\", &amp;Tc);\n</code></pre>\n\n<blockquote>\n <p>if there's a more efficient way of writing my code</p>\n</blockquote>\n\n<p>All four of the variables are related, it might be better to use a <code>struct</code> to contain them. That way if the program needed to be modified to loop through data it would be easier to build an array of all the values. Using a struct would also decrease the number of parameters for each function to one.</p>\n\n<p><strong>Error Checking</strong><br>\nA best practice is to check all input data as it comes in and report any errors, especially for user input. Users can make errors such as entering characters rather than numbers. The <code>temperature(float *, float*)</code> function could return an integer the indicated success or failure.</p>\n\n<p><strong>Separate and Initialize in Variable Declarations</strong><br>\nThere are 2 things that can be improved in the following code:</p>\n\n<pre><code> float Tc, //cold reservoir; user input\n Th, //hot reservoir; user input\n Rcp, //refrigeration cycle coefficient of performance\n Hcp; // Heat pump coefficient of performance\n</code></pre>\n\n<p>This code is hard to maintain because it is hard to add a variable to the list. </p>\n\n<p>Not initializing variables can lead to hard to debug problems later, this is especially true of the C programming language because it does not automatically initialize variables to a zero or null value as some other languages do. Of the two problems this is actually the more serious one, the other might be considered style.</p>\n\n<p>An possible example of an improved declaration is:</p>\n\n<pre><code> float Tc = 0.0; //cold reservoir; user input\n float Th = 0.0; //hot reservoir; user input\n float Rcp = 0.0; //refrigeration cycle coefficient of performance\n float Hcp = 0.0; // Heat pump coefficient of performance\n</code></pre>\n\n<p><strong>Spacing, Both Vertical and Horizontal</strong><br>\nWithin expressions is it common to put spaces between operators and operands, this makes the code more readable.</p>\n\n<p>Vertical separation of one line between functions might make the code more readable as well.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-23T17:17:51.983", "Id": "421884", "Score": "1", "body": "regarding; `float Tc = 0.0;` and similar statements: The `0.0` is a `double` value. Suggest: `float Tc = 0.0f;` Note the trailing `f` to make it a `float` rather than a `double`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-23T19:24:10.453", "Id": "421903", "Score": "0", "body": "@user3629249 Actually I think the OP should change all the floats to doubles, but I already gave the OP enough to chew on based on their skill set." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-22T12:17:31.927", "Id": "217886", "ParentId": "217862", "Score": "4" } } ]
{ "AcceptedAnswerId": "217886", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-22T01:39:43.093", "Id": "217862", "Score": "3", "Tags": [ "c" ], "Title": "Calling a Function to Calculate Multiple Coefficients" }
217862
<p>I made this function to delete a directory with all its contents recursively, <strong>will it work as expected in a production environment ? is it safe ?</strong> I don't want to wake up one day with <code>/home</code> contents is gone :D</p> <pre><code>public static function delTree($dir) { if(!is_dir($dir)){return false;}; $files = scandir($dir);if(!$files){return false;} $files = array_diff($files, array('.','..')); foreach ($files as $file) { (is_dir("$dir/$file")) ? SELF::delTree("$dir/$file") : unlink("$dir/$file"); } return rmdir($dir); } </code></pre> <p>Note: I use this function internally, meaning there are no client parameters like directory names is taken from the client before I call it, so there is no chance for traversal attacks, and I check the base path with another function before I call it, for example to delete a client folder I do something like this</p> <pre><code>$clientsFolderPath = $_SERVER['DOCUMENT_ROOT'] . "/../clients" $clientFolderPath = "$clientsFolderPath/$clientId"; $realBase = realpath($clientsFolderPath); $realClientDir = realpath($clientFolderPath); if ( !$realBase || !$realClientDir || strpos($realClientDir, $realBase) !== 0 ){ //error, log , and exit; } else { ExtendedSystemModel::delTree($clientFolderPath); } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-22T06:54:45.050", "Id": "421580", "Score": "0", "body": "It seems you have already found https://stackoverflow.com/q/3349753/2943403 There is plenty of discussion about security / safety concerns and performance." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-22T07:34:48.680", "Id": "421589", "Score": "0", "body": "@mickmackusa oh, I was having this function in my files for [3 years](https://screenshots.firefox.com/1dZUCILLbsFCAb2S/stackoverflow.com), and now I wanted to use it in a production environment, I thought I wrote it in the past, but it looks like I took it exactly from [here](https://stackoverflow.com/a/41470290/5407848) and forgot. Sorry for that, 3 years in coding should had impact my memory :) . Any way I don't know should I delete the question or what, if it got reviews, that still can help me as I'm using it now." } ]
[ { "body": "<p>As indicated by the scattered comments on <a href=\"https://stackoverflow.com/q/3349753/2943403\">https://stackoverflow.com/q/3349753/2943403</a>, your approach is trustworthy.</p>\n\n<p><code>scandir()</code> has an advantage over <code>glob()</code> (which is normally handy when trying to ignore <code>.</code> and <code>..</code>) because <code>glob()</code> will not detect hidden files.</p>\n\n<p>The RecursiveIterator methods are powerful, but it is my opinion that fewer developers possess the ability to instantaneously comprehend all of the calls and flags (and I believe that should weigh in on your decision).</p>\n\n<p>As for your snippet, I would like to clean it up a little.</p>\n\n<pre><code>public static function delTree($dir) {\n if (!is_dir($dir)) {\n return false;\n }\n\n $files = scandir($dir);\n if (!$files) {\n return false;\n }\n $files = array_diff($files, ['.', '..']);\n\n foreach ($files as $file) {\n if (is_dir(\"$dir/$file\")) {\n SELF::delTree(\"$dir/$file\");\n } else {\n unlink(\"$dir/$file\");\n }\n }\n\n return rmdir($dir);\n}\n</code></pre>\n\n<p>I don't use ternary operators when I am not assigning something in that line. For this reason, a classic <code>if-else</code> is cleaner in my opinion.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-22T08:05:53.840", "Id": "217873", "ParentId": "217863", "Score": "1" } } ]
{ "AcceptedAnswerId": "217873", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-22T03:11:43.893", "Id": "217863", "Score": "0", "Tags": [ "php", "recursion", "security", "file-system" ], "Title": "Delete directory tree function" }
217863
<p>Am simply wondering if I made any egregious mistakes while implementing the <a href="https://en.wikipedia.org/wiki/Alias_method" rel="nofollow noreferrer">Alias Method</a> as an <code>IEnumerator&lt;TElement&gt;</code>; would also like to know if there are any sorts of general improvements that can be made to the design of the class.</p> <p><strong>Usage:</strong></p> <pre><code>var seed = SecureRandom.Default.NextUInt32(); var rng = Pcg32XshRr.New(seed, 1U); var generator = ProbabilisticEnumerator .New( elementWeights: new Dictionary&lt;string, int&gt; { { "A", 1 }, { "B", 2 }, { "C", 4 } }, randomNumberGenerator: rng ); var summary = generator .Take(100000) .GroupBy(item =&gt; item) .Select(item =&gt; new { Element = item.Key, Count = item.Count(), }) .OrderBy(item =&gt; item.Element); foreach (var item in summary) { Console.WriteLine($"{item.Element} | {item.Count}"); } </code></pre> <p><strong>Code:</strong></p> <p><a href="https://www.nuget.org/packages/ByteTerrace.Maths.Probability.ProbabilisticEnumerator/" rel="nofollow noreferrer">Nuget Package</a></p> <p><a href="https://dev.azure.com/byteterrace/CSharp/_git/ByteTerrace.Maths.Probability.ProbabilisticEnumerator" rel="nofollow noreferrer">Source Repository</a></p> <pre><code>/// &lt;summary&gt; /// Represents an enumerator that yields elements in accordance with the rules descibed by a probability table; relies on Michael D Vose's implementation of &lt;a href="https://en.wikipedia.org/wiki/Alias_method"&gt;Walker's Alias Method.&lt;/a&gt; /// &lt;/summary&gt; /// &lt;typeparam name="TElement"&gt;The type of elements encapsulated by the enumerator.&lt;/typeparam&gt; /// &lt;remarks&gt; /// Derived from https://github.com/BlueRaja/Weighted-Item-Randomizer-for-C-Sharp. /// &lt;/remarks&gt; public class ProbabilisticEnumerator&lt;TElement&gt; : IEnumerable&lt;TElement&gt;, IEnumerator&lt;TElement&gt; { private readonly struct ElementMetadata { public int ActualIndex { get; } public int AliasedIndex { get; } public int Threshold { get; } public ElementMetadata(int actualIndex, int aliasedIndex, int biasAreaSize) { ActualIndex = actualIndex; AliasedIndex = aliasedIndex; Threshold = biasAreaSize; } } private readonly ElementMetadata[] m_elementMetadata; private readonly TElement[] m_elements; private readonly int m_heightPerRectangle; private readonly IUniformlyDistributedRandomNumberGenerator m_randomNumberGenerator; /// &lt;summary&gt; /// Gets the next random element. /// &lt;/summary&gt; public TElement Current { get { var elementMetadata = m_elementMetadata; var elements = m_elements; var heightPerRectangle = m_heightPerRectangle; var randomNumberGenerator = m_randomNumberGenerator; var randomHeight = randomNumberGenerator.NextInt32(0, heightPerRectangle); var randomMetadata = elementMetadata[randomNumberGenerator.NextInt32(0, (elementMetadata.Length - 1))]; return ((randomHeight &lt;= randomMetadata.Threshold) ? elements[randomMetadata.ActualIndex] : elements[randomMetadata.AliasedIndex]); } } /// &lt;summary&gt; /// Gets the next random element. /// &lt;/summary&gt; object IEnumerator.Current =&gt; Current; /// &lt;summary&gt; /// Initializes a new instance of the &lt;see cref="ProbabilisticEnumerator{TElement}"/&gt; class. /// &lt;/summary&gt; /// &lt;param name="elementWeights"&gt;The collection of element-to-weight pairs that defines the rules for the table.&lt;/param&gt; /// &lt;param name="randomNumberGenerator"&gt;The source of random numbers that will be used to perform extract elements from the table.&lt;/param&gt; private ProbabilisticEnumerator(IReadOnlyDictionary&lt;TElement, int&gt; elementWeights, IUniformlyDistributedRandomNumberGenerator randomNumberGenerator) { if (elementWeights.IsNull()) { throw new ArgumentNullException(paramName: nameof(elementWeights)); } var count = unchecked((ulong)elementWeights.Count); var elements = new TElement[count]; var index = 0; var totalWeight = 0UL; foreach (var kvp in elementWeights) { var element = kvp.Key; var weight = kvp.Value; if (0 &gt; weight) { throw new ArgumentOutOfRangeException(actualValue: weight, message: "weight must be a positive integer", paramName: nameof(weight)); } elements[index++] = element; totalWeight += unchecked((ulong)weight); } var gcd = BitwiseHelpers.GreatestCommonDivisor(count, totalWeight); var heightPerRectangle = checked((int)(totalWeight / gcd)); var weightMultiplier = checked((int)(count / gcd)); m_elementMetadata = InitializeMetadata(elementWeights, weightMultiplier, heightPerRectangle); m_elements = elements; m_heightPerRectangle = heightPerRectangle; m_randomNumberGenerator = randomNumberGenerator; } /// &lt;summary&gt; /// Releases all resources used by this &lt;see cref="ProbabilisticEnumerator{TElement}"/&gt; instance. /// &lt;/summary&gt; public void Dispose() { } /// &lt;summary&gt; /// Returns an enumerator that yields a random element from the table. /// &lt;/summary&gt; public IEnumerator&lt;TElement&gt; GetEnumerator() =&gt; this; /// &lt;summary&gt; /// Returns an enumerator that yields a random element from the table. /// &lt;/summary&gt; IEnumerator IEnumerable.GetEnumerator() =&gt; GetEnumerator(); /// &lt;summary&gt; /// Returns true. /// &lt;/summary&gt; public bool MoveNext() =&gt; true; /// &lt;summary&gt; /// Throws &lt;see cref="NotSupportedException"/&gt;. /// &lt;/summary&gt; public void Reset() =&gt; new NotSupportedException(); private static ElementMetadata[] InitializeMetadata(IReadOnlyDictionary&lt;TElement, int&gt; elementWeights, int weightMultiplier, int heightPerRectangle) { var count = elementWeights.Count; var elementMetadata = new ElementMetadata[count]; var index = 0; var stackLarge = new Stack&lt;KeyValuePair&lt;int, int&gt;&gt;(); var stackSmall = new Stack&lt;KeyValuePair&lt;int, int&gt;&gt;(); foreach (var kvp in elementWeights) { var newWeight = (kvp.Value * weightMultiplier); if (newWeight &gt; heightPerRectangle) { stackLarge.Push(new KeyValuePair&lt;int, int&gt;(index++, newWeight)); } else { stackSmall.Push(new KeyValuePair&lt;int, int&gt;(index++, newWeight)); } } while (0 &lt; stackLarge.Count) { var largeItem = stackLarge.Pop(); var smallItem = stackSmall.Pop(); largeItem = new KeyValuePair&lt;int, int&gt;(largeItem.Key, (largeItem.Value - (heightPerRectangle - smallItem.Value))); if (largeItem.Value &gt; heightPerRectangle) { stackLarge.Push(largeItem); } else { stackSmall.Push(largeItem); } elementMetadata[--count] = new ElementMetadata(smallItem.Key, largeItem.Key, smallItem.Value); } while (0 &lt; stackSmall.Count) { var smallItem = stackSmall.Pop(); elementMetadata[--count] = new ElementMetadata(smallItem.Key, smallItem.Key, heightPerRectangle); } return elementMetadata; } /// &lt;summary&gt; /// Initializes a new instance of the &lt;see cref="ProbabilisticEnumerator{TElement}"/&gt; class. /// &lt;/summary&gt; /// &lt;param name="elementWeights"&gt;The collection of element-to-weight pairs that defines the rules for the table.&lt;/param&gt; /// &lt;param name="randomNumberGenerator"&gt;The source of random numbers that will be used to perform extract elements from the table.&lt;/param&gt; public static ProbabilisticEnumerator&lt;TElement&gt; New(IReadOnlyDictionary&lt;TElement, int&gt; elementWeights, IUniformlyDistributedRandomNumberGenerator randomNumberGenerator) =&gt; new ProbabilisticEnumerator&lt;TElement&gt;(elementWeights, randomNumberGenerator); } /// &lt;summary&gt; /// A collection of methods that directly or indirectly augment the &lt;see cref="ProbabilisticEnumerator{TElement}"/&gt; class. /// &lt;/summary&gt; public static class ProbabilisticEnumerator { /// &lt;summary&gt; /// Initializes a new instance of the &lt;see cref="ProbabilisticEnumerator{TElement}"/&gt; class. /// &lt;/summary&gt; /// &lt;param name="elementWeights"&gt;The collection of element-to-weight pairs that defines the rules for the table.&lt;/param&gt; /// &lt;param name="randomNumberGenerator"&gt;The source of random numbers that will be used to perform extract elements from the table.&lt;/param&gt; public static ProbabilisticEnumerator&lt;TElement&gt; New&lt;TElement&gt;(IReadOnlyDictionary&lt;TElement, int&gt; elementWeights, IUniformlyDistributedRandomNumberGenerator randomNumberGenerator) =&gt; ProbabilisticEnumerator&lt;TElement&gt;.New(elementWeights, randomNumberGenerator); } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-22T13:28:53.837", "Id": "421627", "Score": "0", "body": "Where can I find some of the _missing_ types like `BitwiseHelpers` or the `IUniformlyDistributedRandomNumberGenerator`? Are these azure-related are they some utilities of yours? I didn't find them in your repository..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-22T16:09:58.323", "Id": "421641", "Score": "1", "body": "@t3chb0t Sorry, I didn't include them since they didn't seem necessary for the review. They're in the same Azure DevOps project (just different repositories), here ya go: [BitwiseHelpers](https://dev.azure.com/byteterrace/CSharp/_git/ByteTerrace.Maths.BitwiseHelpers), [UniformDistribution](https://dev.azure.com/byteterrace/CSharp/_git/ByteTerrace.Maths.Probability.UniformDistribution)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-22T17:39:15.263", "Id": "421668", "Score": "0", "body": "Thanks; for the review probably not but I'd like to try to run it and maybe find other interesting stuff - perfect, it's working ;-)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-22T17:45:59.593", "Id": "421669", "Score": "0", "body": "@t3chb0t Ah, NP. Just FYI, the NuGet package will include those dependencies for you but one totally understands if you don't trust it and want to cobble things together yourself." } ]
[ { "body": "<blockquote>\n<pre><code> public static ulong GreatestCommonDivisor(ulong x, ulong y)\n {\n if (x == 0) { return y; }\n if (y == 0) { return x; }\n\n var g = ((int)CountTrailingZeros(x | y));\n\n x &gt;&gt;= ((int)CountTrailingZeros(x));\n\n do\n {\n y &gt;&gt;= ((int)CountTrailingZeros(y));\n\n if (x &gt; y)\n {\n var z = x;\n\n x = y;\n y = z;\n }\n\n y = (y - x);\n } while (0 != y);\n\n return (x &lt;&lt; g);\n }\n</code></pre>\n</blockquote>\n\n<p>This can be done a lot easier and with fewer iterations by using Euclid's algorithm:</p>\n\n<pre><code>static ulong gcd(ulong x, ulong y)\n{\n if (x == 0) { return y; }\n if (y == 0) { return x; }\n\n ulong d = 0;\n\n while (x &gt; 0)\n {\n d = x % y;\n if (d == 0)\n return y;\n x = y;\n y = d;\n }\n\n return 1;\n}\n</code></pre>\n\n<hr>\n\n<p>I haven't studied your implementation of the initialization in details, but at first sight it looks a lot more complicated than the implementation provided in <a href=\"https://web.archive.org/web/20140401082840/http://web.eecs.utk.edu/~vose/Publications/random.pdf\" rel=\"nofollow noreferrer\">this paper</a>. It seems that you're trying to avoid floating point numbers?</p>\n\n<hr>\n\n<pre><code>int count = 10000;\n Dictionary&lt;string, long&gt; stats = new Dictionary&lt;string, long&gt;\n {\n {\"A\", 0},\n {\"B\", 0},\n {\"C\", 0},\n };\n\n for (int i = 0; i &lt; count; i++)\n {\n\n var rng = Pcg32XshRr.New(0, 1);\n\n\n var generator = ProbabilisticEnumerator\n .New(\n elementWeights: new Dictionary&lt;string, int&gt; {\n { \"A\", 1 },\n { \"B\", 2 },\n { \"C\", 4 }\n },\n randomNumberGenerator: rng\n )\n .Take(500);\n\n var summary = generator\n .GroupBy(item =&gt; item)\n .Select(item =&gt; new\n {\n Element = item.Key,\n Count = item.Count(),\n })\n .OrderBy(item =&gt; item.Element);\n\n foreach (var item in summary)\n {\n stats[item.Element] += item.Count;\n //Console.WriteLine($\"{item.Element} | {item.Count}\");\n }\n }\n\n Console.WriteLine();\n foreach (var entry in stats)\n {\n Console.WriteLine($\"{entry.Key} : {entry.Value / count}\");\n }\n</code></pre>\n\n<p>When I run this distribution 100000, I get an average distribution as:</p>\n\n<pre><code>A : 70\nB : 169\nC : 261\n</code></pre>\n\n<p>I initialize like this: <code>Pcg32XshRr.New(0, 1);</code> which caused it to start the same sequence each time, but trying with this initialization: <code>var rng = Pcg32XshRr.New(DateTime.Now.Ticks, DateTime.Now.Ticks / 10000);</code> it gets worse:</p>\n\n<pre><code>A : 83\nB : 145\nC : 270\n</code></pre>\n\n<p>I would expect it to be more like:</p>\n\n<pre><code>A: 71 (1 / 7) * 500\nB: 142\nC: 285 \n</code></pre>\n\n<p>Or maybe I misunderstand the concept?.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> var count = unchecked((ulong)elementWeights.Count);\n</code></pre>\n</blockquote>\n\n<p>This seems strange. By default a C# assemblies are compiled unchecked, so it should not be necessary, unless you compile with the check flag set? (But if I try, running it in a checked environment, <code>Pcg32XshRr.Sample()</code> throws an <code>OverflowException</code> in this line:</p>\n\n<blockquote>\n <p><code>uint threshold = ((((uint)(-exclusiveHigh)) % exclusiveHigh));</code></p>\n</blockquote>\n\n<hr>\n\n<blockquote>\n <p><code>IEnumerable&lt;TElement&gt;, IEnumerator&lt;TElement&gt;</code></p>\n</blockquote>\n\n<p>There is rarely reasons for implementing both these interfaces, and I don't see the need in this class either. <code>IEnumerable&lt;T&gt;</code> should be sufficient and can cover most needs.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> elementWeights: new Dictionary&lt;string, int&gt; {\n { \"A\", 1 },\n { \"B\", 2 },\n { \"C\", 4 }\n</code></pre>\n</blockquote>\n\n<p>Requiring input data in this way may be a little cumbersome in real life, because you most often will have the data and the probabilities in separate sets, so I would take two arguments - a data set and its corresponding probabilities. You should then of course check the length etc... </p>\n\n<hr>\n\n<p>I think, the one class do too much, and I would split it all into more classes in order to make it all a little more SOLID. A design could be as the below, but there may be others as well:</p>\n\n<pre><code>public interface IUniformRandomGenerator\n{\n double Next(int max);\n}\n\npublic interface IBiasedRandomGenerator\n{\n int Next { get; }\n}\n\npublic class IBiasedRandomGenerator : IRandomGenerator\n{\n public BiasedRandomGenerator(IList&lt;double&gt; probabilities, IUniformRandomGenerator uniformGenerator)\n {\n // TODO Initialize\n }\n\n public int Next\n {\n get\n {\n return default;\n }\n }\n}\n\npublic class BiasedRandomEnumerator&lt;TElement&gt; : IEnumerable&lt;TElement&gt;\n{\n private readonly IList&lt;TElement&gt; m_elements;\n private readonly IBiasedRandomGenerator m_random;\n\n public BiasedRandomEnumerator(IList&lt;TElement&gt; elements, IList&lt;double&gt; probabilities, int seed)\n {\n ValidateInput(elements, probabilities);\n\n m_elements = elements;\n m_random = new BiasedRandomGenerator(probabilities, new UniformRandomGenerator(seed));\n }\n\n public BiasedRandomEnumerator(IList&lt;TElement&gt; elements, IBiasedRandomGenerator random)\n {\n m_elements = elements;\n m_random = random;\n }\n\n private void ValidateInput(IList&lt;TElement&gt; elements, IList&lt;double&gt; probabilities)\n {\n // TODO\n }\n\n public IEnumerator&lt;TElement&gt; GetEnumerator()\n {\n while (true)\n {\n yield return m_elements[m_random.Next];\n }\n }\n\n IEnumerator IEnumerable.GetEnumerator()\n {\n return GetEnumerator();\n }\n}\n</code></pre>\n\n<p>In this way each class has only one responsibility, and the interfaces secures loose couplings between them. I have experimented a little with the names, but I won't defend them to the end of times.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-22T19:30:57.687", "Id": "421689", "Score": "0", "body": "Can you share the code you used to test the distribution; in addition to the possible bugs, I can imagine a few legitimate ways for you to have ended up with a \"fixed random distribution\" instead of a \"random random distribution.\"" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-22T19:53:08.153", "Id": "421695", "Score": "0", "body": "Good call on the `GCD` function, it is a remnant of some research that I was doing; the current implementation is far from ideal since I don't have access to a single instruction `CTZ` function. Just did some performance testing that I have been meaning to do and confirmed that my binary version is 5x slower than the one that simply relies on `mod`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-22T19:54:18.170", "Id": "421696", "Score": "0", "body": "@Kittoes0124: See my update of the section. You're right I was only running a \"random distribution\". Please tell me how to do it right." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-22T20:08:18.183", "Id": "421700", "Score": "1", "body": "I made an edit that generates a random seed. Also, it looks like there is a bug in my translation since the result gets even more skewed with randomized seed; I suspect it is some sort of \"off by 1\" error that probably happens in the initialization. Have confirmed that the bug isn't in the `Pcg32XshRr` generator by using `SecureRandom.New()` (which is much slower, but guaranteed random)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-22T21:09:50.750", "Id": "421709", "Score": "1", "body": "Found it, `randomHeight = randomNumberGenerator.NextInt32(0, heightPerRectangle)` should actually be `randomHeight = randomNumberGenerator.NextInt32(1, heightPerRectangle)`. Most references depend on a generator with an exclusive upper bound; my implementation is inclusive and I failed to properly adjust." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-23T03:46:20.760", "Id": "421738", "Score": "0", "body": "@Kittoes0124: OK, with `1` it works as expected :-)" } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-22T19:19:42.010", "Id": "217902", "ParentId": "217864", "Score": "2" } } ]
{ "AcceptedAnswerId": "217902", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-22T03:20:00.783", "Id": "217864", "Score": "3", "Tags": [ "c#", "random" ], "Title": "Generating Biased Random Values (Walker's Alias Method)" }
217864
<p>Similar to this question <a href="https://codereview.stackexchange.com/questions/134435/hackerrank-new-year-chaos">but this is for Python</a></p> <p><a href="https://www.hackerrank.com/challenges/new-year-chaos/problem" rel="nofollow noreferrer">Original problem with description on hacker rank</a></p> <p>I am currently trying to iterate through a large number of arrays and count how many times numbers have been swapped.</p> <p>A sorted array looks like this: <code>[1,2,3,4,5]</code> and a number can be swapped only towards the front (counting down to 0) twice.</p> <p>If a number is more than 2 out of order the array is deemed 'Too chaotic' and the process should stop.</p> <p>Instead of bubble sorting I am simply going through and counting the actual swaps. As a sorted array is not actually required, my code works except for a couple of the tests where it times out due to large arrays.</p> <p>Any ideas on how to speed this process up?</p> <pre><code>function minimumBribes(q) { console.log(sort(q)); function sort(items) { let bribes = 0; for (let i = 0; i &lt; items.length; i++) { if (items[i] - (i + 1) &gt; 2) return "Too chaotic"; for (let j = 0; j &lt; i; j++) { if (items[j] &gt; items[i]) bribes++; } } return bribes; } } </code></pre>
[]
[ { "body": "<p>You don't need to compare any two elements. Just compare the array values (the sticker) with the index of the array. Keep in mind that the sticker is one-based and the index is zero-based.</p>\n\n<pre><code>minimumBribes = q =&gt; {\n const bribes = q.reduce( (bribes, assigned, actual, too_chaotic) =&gt; { \n const distance = assigned - 1 - actual\n if (distance&gt;2) too_chaotic=true\n else return bribes + distance*(distance&gt;0)\n }, 0);\n return isNaN(bribes) ? \"Too chaotic\" : bribes;\n}\n</code></pre>\n\n<p>The break-out-of-reduce trick is taken from <a href=\"https://stackoverflow.com/questions/36144406/how-to-break-on-reduce-method\">this highly informative post</a>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-22T11:25:27.437", "Id": "421599", "Score": "0", "body": "Do you only set too_chaotic to true so you would not have an empty if bracket? From what I can tell it doesn't change the code..\nAlso never knew about this hack, very interesting" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-22T11:38:58.920", "Id": "421608", "Score": "0", "body": "FYI this answer is actually a little off, array [1, 2, 5, 3, 7, 8, 6, 4] is meant to return 7, your solution returns 6.\nWorks for several other use cases though" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-22T12:22:48.480", "Id": "421613", "Score": "1", "body": "4th argument to reduce is source array `q`. Changing it terminates reduce immediately. If you simply return nothing (without changing q), the reduce runs to completion instead (slower). You could name it `orderly`, set false on chaos, then the final condition would be `return q ? bribes : \"Too chaotic\"`, as q-the-array is always true while your assigned value is always false. I see what you mean that someone who pays bribes but accepts more than paid will be uncounted. You can still avoid comparisons: when you get to 6 you know you're supposed to be seeing 4 and thus there's another bribe." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-22T15:44:19.647", "Id": "421639", "Score": "0", "body": "Your break out does not work. You need to mutate the array. `too_chaotic` is a reference, assigning a new value to it does not mutate the array, it just overwrites the reference. To breakout you can change the array size to `<= actual` (also the sign of `distance` is neg) Thus to break out you need to mutate the array with `if(distance <= -2) { too_chaotic.length = 0 }` Also very poor name selection for array reference, random semicolon use, and the fact the function fails to return the correct result and I would -1 if the answer was not to be corrected" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-23T17:42:25.243", "Id": "421894", "Score": "0", "body": "-1, your approach is incorrect for 1 2 5 3 7 8 6 4, it should return 7 but returns 6" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-23T17:51:18.930", "Id": "421899", "Score": "0", "body": "Update: when I do this manually I get to 6 as well. I will fake edit and give back the point." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-22T09:30:17.943", "Id": "217876", "ParentId": "217867", "Score": "3" } }, { "body": "<h2>Reduce the inner loops iteration count.</h2>\n<p>The problem is the inner loop is looping over too many items. The result is that you spend too much time processing data you know is irrelevant.</p>\n<p>As the function should exit if it detects a position has made over 2 bribes, you need only have the inner loop check positions down 2 from the item you are checking, and not from the start of the line.</p>\n<h2>Quicker solution</h2>\n<p>It only requires a slight modification of your code, but as you have complicated the situation by calling an inner function <code>sort</code> the example has just removed the inner function.</p>\n<p>The line <code>for (j = pos-2; j &lt; i; j++) {</code> is where the improvement is with <code>pos</code> being <code>item[i]</code> in your function.</p>\n<pre><code>function minBribe(queue) {\n var bribes = 0, i, j;\n for (i = 0; i &lt; queue.length; i++) {\n const pos = queue[i], at = i + 1;\n if (pos - at &gt; 2) { return &quot;Too chaotic&quot; } \n for (j = Math.max(0, pos - 2); j &lt; i; j++) {\n if (queue[j] &gt; pos) { bribes++ }\n }\n } \n return bribes;\n}\n</code></pre>\n<p>This brings the solution down from <span class=\"math-container\">\\$O(n^2)\\$</span> to near <span class=\"math-container\">\\$O(n)\\$</span> however the number of bribes is a factor so its closer to <span class=\"math-container\">\\$O(n + (m^{0.5}/2))\\$</span> where <span class=\"math-container\">\\$m\\$</span> is the number of bribes. (this is only an approximation)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-05T20:11:02.793", "Id": "507021", "Score": "0", "body": "Adding one clarification why J will start from j = Math.max(0, pos - 2) is that, in any case numbers which are greater to current one can jump only two position ahead of actual position of current number." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-23T15:54:38.463", "Id": "217971", "ParentId": "217867", "Score": "5" } } ]
{ "AcceptedAnswerId": "217971", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-22T05:49:46.203", "Id": "217867", "Score": "4", "Tags": [ "javascript", "programming-challenge", "sorting", "time-limit-exceeded" ], "Title": "New Year Chaos JavaScript, needs to be sped up" }
217867
<p><strong>The task</strong></p> <blockquote> <p>You're given strings J representing the types of stones that are jewels, and S representing the stones you have. Each character in S is a type of stone you have. You want to know how many of the stones you have are also jewels.</p> <p>The letters in J are guaranteed distinct, and all characters in J and S are letters. Letters are case sensitive, so "a" is considered a different type of stone from "A".</p> <p>Example 1:</p> <p>Input: J = "aA", S = "aAAbbbb" Output: 3 </p> <p>Example 2:</p> <p>Input: J = "z", S = "ZZ" Output: 0 </p> <p>Note:</p> <p>S and J will consist of letters and have length at most 50. The characters in J are distinct.</p> </blockquote> <p><strong>My functional solution</strong></p> <pre><code>const findNumberOfJewels = (j,s) =&gt; [...s].reduce((num, x) =&gt; [...j].includes(x) ? num + 1 : num , 0); console.log(findNumberOfJewels("aA", "aAAbbbb")); </code></pre> <p><strong>My imperative solution</strong></p> <pre><code>function findNumberOfJewels2(j,s) { let res = 0; const set = new Set(j); for (const x of s) { if (set.has(x)) { ++res; } } return res; }; console.log(findNumberOfJewels2("aA", "aAAbbbb")); </code></pre>
[]
[ { "body": "<p>The functional approach is almost certainly faster despite having worse big-O — <span class=\"math-container\">\\$O(j \\cdot s)\\$</span> functional vs <span class=\"math-container\">\\$O(j + s)\\$</span> imperative — because linear searches of small arrays are <a href=\"https://stackoverflow.com/a/48031382/2570502\">very fast</a>. </p>\n\n<p>You don't need to destructure <code>j</code> and adding a boolean to a number coerces the boolean to 0 or 1. </p>\n\n<p><code>sum</code> is a better name than <code>num</code> and <code>c</code> is a good name for a character iterator.</p>\n\n<pre><code>const findNumberOfJewels = (j,s) =&gt; [...s].reduce( (sum, c) =&gt; sum + j.includes(c), 0 );\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-22T14:37:12.507", "Id": "421632", "Score": "0", "body": "+1 Be careful when making assumptions about JS performance.Running both OPs solutions over a wide range of inputs, the functional solution is from 25% -75% the speed `fastTime / slowTime` of the imperative. Your modified version is a significant improvement over the OP's, under specific circumstances can be much faster then the imp version (also much slower ). But the alloc of `[...s]` and coercion of `j.includes` to `Number` means it will always be slower (by ~10%) than `findJ(j,s) {var r=0,i=s.length;while(i--){j.includes(s[i])&&r++}return r}` (Note that GC cost of `[...s]` is not timed)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-22T22:06:27.903", "Id": "421721", "Score": "0", "body": "Were you able to get those results within the given size constraints? I couldn't find valid inputs that make the imperative version beat a linear search. The whole string sits in L1 cache and I'm skeptical that it's possible for Set's lookup characteristics to repay its setup time." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-22T07:32:59.090", "Id": "217871", "ParentId": "217870", "Score": "3" } } ]
{ "AcceptedAnswerId": "217871", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-22T06:45:54.640", "Id": "217870", "Score": "0", "Tags": [ "javascript", "algorithm", "programming-challenge", "functional-programming", "ecmascript-6" ], "Title": "Items also occurs in a set" }
217870
<p>I have a dictionary:</p> <pre><code>x = {'a': [1, 2, 3], 'b': [4, 5, 6]} </code></pre> <p>and I have to extract a key based on an input. For example assume it is <code>3</code>, so my output should be <code>'a'</code>.</p> <p>Here's my code:</p> <pre><code>x = {'a': [1, 2, 3], 'b': [4, 5, 6]} n = 3 output = [k for k, v in x.items() if n in v] print(output[0]) </code></pre> <p>Can it be done more efficiently?</p> <p>Elements in the lists are unique, i.e. the value <code>3</code> will only be in one list.</p>
[]
[ { "body": "<p>Given that you only want the first match, it would be more efficient to stop when you reach it:</p>\n\n<pre><code>output = next(key for key, value in x.items() if n in value)\n</code></pre>\n\n<p>Note that this will throw a <code>StopIteration</code> exception if there is no matching key, rather than the <code>IndexError</code> your current code throws.</p>\n\n<p>If you need to do this multiple times, you could build a reverse map:</p>\n\n<pre><code>x_reversed = {num: key for key, value in x.items() for num in value}\n</code></pre>\n\n<p>then the lookup is a trivial <code>x_ reversed[n]</code> However, note the error case changes again, to <code>KeyError</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-22T11:14:24.413", "Id": "421596", "Score": "0", "body": "Thanks. As I have to do it only once, I would go for the first solution." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-22T10:58:32.617", "Id": "217881", "ParentId": "217874", "Score": "6" } } ]
{ "AcceptedAnswerId": "217881", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-22T08:24:01.763", "Id": "217874", "Score": "0", "Tags": [ "python", "python-3.x" ], "Title": "Finding a key from values (which are list) in dict" }
217874
<p><strong>The task</strong> is taken from <a href="https://leetcode.com/problems/n-repeated-element-in-size-2n-array/" rel="nofollow noreferrer">leetcode</a></p> <blockquote> <p>In a array A of size 2N, there are N+1 unique elements, and exactly one of these elements is repeated N times.</p> <p>Return the element repeated N times.</p> <p>Example 1:</p> <p>Input: [1,2,3,3] Output: 3 </p> <p>Example 2:</p> <p>Input: [2,1,2,5,3,2] Output: 2 </p> <p>Example 3:</p> <p>Input: [5,1,5,2,5,3,5,4] Output: 5 </p> <p>Note:</p> <p>4 &lt;= A.length &lt;= 10000 0 &lt;= A[i] &lt; 10000 A.length is even</p> </blockquote> <p><strong>My solution</strong></p> <pre><code>var repeatedNTimes = function(A) { const set = new Set(); for (const n of A) { if (set.has(n)) { return n; } set.add(n); } }; </code></pre> <p>I didn't do much with the information <code>size 2N, there are N+1 unique elements, and exactly one of these elements is repeated N times.</code> I think these information is not needed to solve the problem efficiently. I also wonder whether there is a bitwise or purely math based solution to the task.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-22T15:02:59.660", "Id": "421635", "Score": "0", "body": "Your solution is optimal.All that could be improved is the hashing of each item, In JS you can not write low level and thus improve the hashing (with exception of webAsm (if you consider it JS) but that is still very immature and would only give advantage for very large data sets)" } ]
[ { "body": "<p>In the worst case (the repeated element occupies the second half of the array), the set will accommodate all N non-repeated elements, therefore the space complexity of the solution is <span class=\"math-container\">\\$O(N)\\$</span>.</p>\n\n<p>Your intuition is correct; the solution doesn't use the important information. It is used to find out how far apart the repeated elements are. If a distance between them is at least <span class=\"math-container\">\\$d\\$</span>, the array would be at least <span class=\"math-container\">\\$d\\cdot(N-1) + 1\\$</span> long. Since we know that it is <span class=\"math-container\">\\$2N\\$</span> long, we can conclude that <span class=\"math-container\">\\$d \\le \\dfrac{2N-1}{N-1}\\$</span>, which is effectively 2 for N > 2. It is enough to compare each <code>a[i]</code> with <code>a[i+1]</code> and <code>a[i+2]</code>. The space complexity is now constant.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-03T19:19:31.623", "Id": "495246", "Score": "1", "body": "Beware that there is one exception to this, when the length of an array is 4, and both repeating elements are on the edges like this: [3, 1, 2, 3], then the distance is 3. In all other cases (array length even & 6+), the maximum distance is indeed 2. So it makes sense to check for `if len(arr) == 4 && arr[0] == arr[3] { return arr[0] }` first before the for loop, and only then proceed in checking for `arr[i] == arr[i+1] || arr[i] == arr[i+2]`" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-22T17:20:37.737", "Id": "217895", "ParentId": "217877", "Score": "6" } }, { "body": "<p>I see in <a href=\"https://codereview.stackexchange.com/posts/217877/revisions#rev-arrow-9b4bd84e-513d-4972-8f21-7e20e9aa1676\">revision 3</a> that the <code>else</code> keyword and block was replaced by the single line that was in the block. That is a good simplification. Some developers aim to avoid the <code>else</code> keyword with techniques like returning early (like this code) and other similar techniques.</p>\n<hr />\n<p>The function declaration uses the <code>var</code> keyword. Unless the scope needs to be broader or it needs to be re-assigned, <code>const</code> could have been used.</p>\n<hr />\n<p>The suggestion in <a href=\"https://codereview.stackexchange.com/a/217895/120114\">vnp's answer</a> to check each element with the following two is a good one to reduce the space complexity. Another technique to do so would be to utilize <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf\" rel=\"nofollow noreferrer\"><code>Array.prototype.indexOf()</code></a> passing the current index + 1 as the second argument (i.e. <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf#Parameters\" rel=\"nofollow noreferrer\"><code>fromIndex</code></a>). If that returns a value greater than -1 (or even the current index) then you would know the value is repeated. However this may be sub-optimal because it would require an extra function call.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-22T18:48:09.490", "Id": "217900", "ParentId": "217877", "Score": "2" } }, { "body": "<p><strong>Beware</strong>: the above answers and comments are not optimal! (although VNP above provides a good mathematical explanation of the following)</p>\n<p>Using the Boyer-Moore Voting algorithm, a solution can be determined in O(n) time but also <strong>O(1) space.</strong> Any repeated digit will be the answer. Therefore, spreading out the N digits of the repeated value results in two cases:</p>\n<ol>\n<li>The two values are side-by-side: in that case check every tuple for equality (when A[i] == A[i + 1] your answer is at A[i]).</li>\n<li>The repeated digit is spread out evenly (this occurs at most every second value, therefore, if the above fails, check A[i] == A[i + 2]).</li>\n</ol>\n<p>This algorithm is a rough explanation, but crucially eliminates the need for a set. There is one edge case when the length of the values is four and the majority item is spread out on the edges.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-13T20:06:32.907", "Id": "519140", "Score": "3", "body": "That seems to be the same as [vnp's suggested improvement](/a/217895/75307). What's different, other than your observation that it can fail with N==2?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-16T02:02:50.547", "Id": "519349", "Score": "0", "body": "Whoops, didn't see their submission. Just adding some extra information about efficiency and more intuition." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-18T08:53:00.627", "Id": "519565", "Score": "1", "body": "Not sure which answers you mean by \"above\", as that set changes according to how each reader sorts the answers." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-13T17:29:47.983", "Id": "263004", "ParentId": "217877", "Score": "2" } } ]
{ "AcceptedAnswerId": "217895", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-22T09:51:33.310", "Id": "217877", "Score": "4", "Tags": [ "javascript", "algorithm", "programming-challenge", "ecmascript-6", "iteration" ], "Title": "N-Repeated Element in Size 2N Array" }
217877
<p>I'm designing an modular exception class hierarchy to use in various projects. I intend to inherit from <code>std::exception</code> in order to be maximally compatible with any exception-handling code. A design goal is that each exception's <code>what()</code> method returns a string which contains a base message, which is dependent on the object's most specific class (i.e. equal for all objects of the class), and an optional instance-specific details message which specifies the origin of the exception.</p> <p>The two main goals are ease of use (as in when throwing the exceptions), as well as ensuring that writing another exception subclass is as simple and repetition-free as possible.</p> <p><br></p> <h1>Base class</h1> <p>The base exception class I wrote is the following. It is <em>conceptually</em> an abstract class, but not syntactically, since I don't have any virtual method to make pure virtual. So, as an alternative, I made all constructors protected.</p> <pre class="lang-cpp prettyprint-override"><code>/** * Base class for all custom exceptions. Stores a message as a string. * Instances can only be constructed from within a child class, * since the constructors are protected. */ class BaseException : public std::exception { protected: std::string message; ///&lt; message to be returned by what() BaseException() = default; /** * Construct a new exception from a base message and optional additional details. * The base message is intended to be class-specific, while the additional * details string is intended to be instance-specific. * * @param baseMessage generic message for the kind of exception being created * @param details additional information as to why the exception was thrown */ BaseException(const std::string &amp;baseMessage, const std::string &amp;details = "") { std::ostringstream oss(baseMessage, std::ios::ate); if (not details.empty()) oss &lt;&lt; " (" &lt;&lt; details &lt;&lt; ')'; message = oss.str(); } public: /// `std::exception`-compliant message getter const char *what() const noexcept override { return message.c_str(); } }; </code></pre> <p>The intention of the above design is that any subclass of <code>BaseException</code> defines a constructor that passes a class-specific base message (as the <code>baseMessage</code> paramter) and an optional detail-specifier (as the <code>details</code> parameter) as arguments to <code>BaseException</code>'s constructor.</p> <h2>Errors &amp; warnings</h2> <p>Since I want to be able to differentiate between general exception "types", e.g. errors vs. warnings, I've made the following two virtually-inherited bases:</p> <pre><code>class Error: public virtual BaseException {}; class Warning : public virtual BaseException {}; </code></pre> <p><br> <br></p> <hr> <h1>Examples</h1> <p>Here are some (project-specific) examples of implementing concrete exception subclasses with this design:</p> <pre><code>/// Indicates that a command whose keyword is unknown was issued class UnknownCommand : public Error { public: static constexpr auto base = "unrecognized command"; UnknownCommand(const std::string &amp;specific = "") : BaseException(base, specific) {} }; /// Indicates an error in reading or writing to a file class IOError : public Error { public: static constexpr auto base = "unable to access file"; IOError(const std::string &amp;specific = "") : BaseException(base, specific) {} }; /// Indicates that an algorithm encountered a situation in which it is not well-defined; /// i.e., a value that doesn't meet a function's prerequisites was passed. class ValueError : public Error { public: static constexpr auto base = "invalid value"; ValueError(const std::string &amp;specific = "") : BaseException(base, specific) {} }; # [...] </code></pre> <p>As you can see, the common pattern is</p> <pre class="lang-cpp prettyprint-override"><code>class SomeException : public Error /* or Warning */ { public: static constexpr auto base = "some exception's generic description"; SomeException(const std::string &amp;details) : BaseException(base, details) {} } </code></pre> <h3>Usage example</h3> <p>Taking the previous <code>IOError</code> class as an example:</p> <pre class="lang-cpp prettyprint-override"><code>#include &lt;iostream&gt; #include &lt;fstream&gt; #include "exceptions.h" // all of the previous stuff void cat(const std::string &amp;filename) { std::ifstream file(filename); if (not file.is_open()) throw IOError(filename); std::cout &lt;&lt; file.rdbuf(); } int main(int argc, char **argv) { for (int i = 1; i &lt; argc; ++i) { try { cat(argv[i]); } catch (std::exception &amp;e) { std::cerr &lt;&lt; e.what() &lt;&lt; '\n'; } } } </code></pre> <p>In case of calling the program with an inaccessible file path, e.g. the path "foo", it should output</p> <pre><code>unable to access file (foo) </code></pre>
[]
[ { "body": "<ol>\n<li><p>Using a <code>std::ostringstream</code> to concatenate strings is like using a DeathStar to kill a sparrow.</p></li>\n<li><p>Don't use <code>std::string</code> for the stored message. Copying it is not guaranteed to never throw, and you only need a very small sliver of its capabilities anyway.<br>\nA <code>std::shared_ptr&lt;const char[]&gt;</code> fits the bill much better, though even that is overkill.</p></li>\n<li><p>Avoid using <code>std::string</code> at all, so you don't risk short-lived but costly dynamic allocations. Prefer <code>std::string_view</code> for the interface.</p></li>\n<li><p><code>BaseException</code> seems to be purely an implementation-help, adding storing of an arbitrary exception-message on top of <code>std::exception</code>. That's fine, only a pitty it wasn't already in the base.</p></li>\n<li><p>Still, marking the additions as <code>protected</code> doesn't make any sense, <code>message</code> should really be <code>private</code>, and why shouldn't the ctors be <code>public</code>?<br>\nIf the aim of that exercise is forbidding objects of most derived class <code>BaseException</code>, just make the ctor pure virtual:</p>\n\n<pre><code>// Declaration in the class:\nvirtual ~BaseException() = 0;\n// Definition in the header-file:\ninline BaseException::~BaseException() = default;\n</code></pre></li>\n</ol>\n\n<p>Applying that:</p>\n\n<pre><code>template &lt;class... Ts&gt;\nauto shared_message(Ts... ts)\n-&gt; std::enable_if_t&lt;(std::is_same_v&lt;Ts, std::string_view&gt; ... &amp;&amp;),\n std::shared_ptr&lt;const char[]&gt;&gt; {\n auto r = std::make_shared_default_init&lt;char[]&gt;(1 + ... + ts.size());\n auto p = &amp;r[0];\n ((std::copy_n(&amp;ts[0], ts.size(), p), p += ts.size()), ...);\n *p = 0;\n return r;\n}\n\ntemplate &lt;class... Ts&gt;\nauto shared_message(Ts&amp;&amp;... ts)\n-&gt; std::enable_if_t&lt;!(std::is_same_v&lt;std::decay_t&lt;Ts&gt;, std::string_view&gt; ... &amp;&amp;),\n decltype(shared_message(std::string_view{ts}...))&gt;\n{ return shared_message(std::string_view{ts}...); }\n\nclass BaseException : std::exception {\n decltype(shared_message()) message;\npublic:\n const char* what() const noexcept final override\n { return &amp;message[0]; }\n virtual ~BaseException() = 0;\n template &lt;class... Ts, class = decltype(shared_message(std::declval&lt;Ts&amp;&gt;()...))&gt;\n BaseException(Ts&amp;&amp;... ts)\n : message(shared_message(ts...))\n {}\n};\n\ninline BaseException::~BaseException() = default;\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-05T09:39:40.020", "Id": "424414", "Score": "0", "body": "Thanks for your feedback! Conceptually speaking, `BaseException` is an abstract class -- although not syntactically, since there is no method to make pure virtual; so, as an alternative, I made the constructors `protected`. Regarding the use of `shared_pointer`, a copy must still be made, to avoid dangling pointer issues, right? In this case, would the \"manual\" copy potentially throw? And would switching to `shared_pointer` or a more \"basic\" string type be worth it if the thrower actually passes a `std::string` as the \"details\" (so the `std::string` would already have been constructed)?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-05T10:55:45.823", "Id": "424441", "Score": "1", "body": "If `BaseException` is conceptually abstract, simply make it mechanically abstract too, look at the edit. Copying a `shared_ptr` cannot throw, as it just involves incrementing a reference-count. And dealing with `std::string`s at all won't save an allocation: `std::make_shared` generally allocates the shared object, and the reference-counts, in one piece. Of Course it doesn't matter whether the used string-type is \"basic\", as long as it does copy-on-write, which is forbidden for `std::string`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-05T19:09:50.617", "Id": "424489", "Score": "0", "body": "I meant copying the characters, as in `std::copy_n(&ts[0], ts.size(), p)`. Regarding the `std::string`: suppose there are throw clauses that construct a `std::string` as the `details` message: `throw IOError(filename + \"!\")` (`filename` is a `std::string`, as in the example above). If such uses were frequent, wouldn't taking the string as a `const std::string &` be better than having to force the thrower to give a `char *` (`throw IOError(filename.c_str())`) and then copy all of the characters in a newly allocated `char[]` (through `make_shared`)? Maybe I missed something about what you said." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-05T19:25:47.223", "Id": "424492", "Score": "1", "body": "@Anakhand Prefer `std::string_view` over `std::string const&` as a function-argument, wherever you don't need the 0-terminator. You can cheaply construct the view even in many cases where you would have to allocate for a temporary std::string. And the only part in my replacement that can throw is the call to `std::make_shared`, because *some* dynamic memory is needed." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-04T10:16:59.037", "Id": "219692", "ParentId": "217879", "Score": "2" } } ]
{ "AcceptedAnswerId": "219692", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-22T10:30:19.683", "Id": "217879", "Score": "5", "Tags": [ "c++", "object-oriented", "inheritance", "exception" ], "Title": "\"Detailed\" exception class hierarchy" }
217879
<p>I have been working on creating maintainable networking layer for our Asp.Net Core Web Api project. Right now I have created Generic methods for <em>Get, Post, Put</em> like this.</p> <pre><code> public class BaseClient { private HttpClient _client; private ILogger&lt;BaseClient&gt; _logger; private string AuthToken; public BaseClient(HttpClient client, ILogger&lt;BaseClient&gt; logger, AuthenticationHeader authHeader) { _client = client; client.BaseAddress = new Uri("url/"); client.DefaultRequestHeaders.Add("Accept", "application/json"); _logger = logger; AuthToken = authHeader.AuthHeader; } public async Task&lt;FailureResponseModel&gt; GetFailureResponseModel(HttpResponseMessage response) { FailureResponseModel failureModel = await response.Content.ReadAsAsync&lt;FailureResponseModel&gt;(); failureModel.ResponseStatusCode = Convert.ToInt32(response.StatusCode); _logger.LogError("Request Failed: {Error}", failureModel.ResultDetails); return failureModel; } public async Task&lt;object&gt; ProcessAsync&lt;T&gt;(HttpRequestMessage request, NamingStrategy namingStrategy) { if (!string.IsNullOrEmpty(AuthToken)) { request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", AuthToken); } HttpResponseMessage response = await _client.SendAsync(request); if (response.IsSuccessStatusCode) { _logger.LogInformation("Request Succeeded"); var dezerializerSettings = new JsonSerializerSettings { ContractResolver = new DefaultContractResolver { NamingStrategy = namingStrategy } }; T responseModel = JsonConvert.DeserializeObject&lt;T&gt;(await response.Content.ReadAsStringAsync(), dezerializerSettings); return responseModel; } else { return await GetFailureResponseModel(response); } } public async Task&lt;object&gt; GetAsync&lt;T&gt;(string uri) { return await GetAsync&lt;T&gt;(uri, new DefaultNamingStrategy()); } public async Task&lt;object&gt; GetAsync&lt;T&gt;(string uri, NamingStrategy namingStrategy) { using (var requestMessage = new HttpRequestMessage(HttpMethod.Get, uri)) { return await ProcessAsync&lt;T&gt;(requestMessage, namingStrategy); } } public async Task&lt;object&gt; PostAsync&lt;T1, T2&gt;(string uri, T2 content) { return await PostAsync&lt;T1, T2&gt;(uri, content, new DefaultNamingStrategy()); } public async Task&lt;object&gt; PostAsync&lt;T1, T2&gt;(string uri, T2 content, NamingStrategy namingStrategy) { using (var requestMessage = new HttpRequestMessage(HttpMethod.Post, uri)) { var json = JsonConvert.SerializeObject(content); using (var stringContent = new StringContent(json, Encoding.UTF8, "application/json")) { requestMessage.Content = stringContent; return await ProcessAsync&lt;T1&gt;(requestMessage, namingStrategy); } } } public async Task&lt;object&gt; PutAsyc&lt;T1, T2&gt;(string uri, T2 content) { return await PutAsyc&lt;T1, T2&gt;(uri, content, new DefaultNamingStrategy()); } public async Task&lt;object&gt; PutAsyc&lt;T1, T2&gt;(string uri, T2 content, NamingStrategy namingStrategy) { using (var requestMessage = new HttpRequestMessage(HttpMethod.Put, uri)) { var json = JsonConvert.SerializeObject(content, Formatting.None, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore }); using (var stringContent = new StringContent(json, Encoding.UTF8, "application/json")) { requestMessage.Content = stringContent; return await ProcessAsync&lt;T1&gt;(requestMessage, namingStrategy); } } } </code></pre> <p>As it can be seen I have to write 2 Methods for Get, Post and Put due to SnakeCase and CamelCase Naming Strategies as some response consist of <strong>SnakeCase</strong> and some responses are in <strong>CamelCase</strong></p> <p>I have created ApiManager kinda class which calls above Class methods like this.</p> <pre><code> public class ClubMatasClient { private BaseClient _client; private ILogger&lt;ClubMatasClient&gt; _logger; private string AuthToken; public ClubMatasClient(BaseClient client, ILogger&lt;ClubMatasClient&gt; logger, AuthenticationHeader authHeader) { _client = client; _logger = logger; AuthToken = authHeader.AuthHeader; } public async Task&lt;object&gt; GetShops(string category) { _logger.LogInformation("ClubMatas outgoing request: {RequestName}", nameof(GetShops)); return await _client.GetAsync&lt;ShopsResponseModel&gt;($"v2/shops?category={WebUtility.UrlEncode(category)}"); } public async Task&lt;object&gt; PostLogin(LoginRequestModel form) { _logger.LogInformation("ClubMatas outgoing request: {RequestName}", nameof(PostLogin)); return await _client.PostAsync&lt;LoginResponseModel, LoginRequestModel&gt;("v2/login", form, new SnakeCaseNamingStrategy()); } } </code></pre> <p>And this class in being injected in my Controllers and I am using this ApiManager like this to call api and return response.</p> <pre><code> public async Task&lt;ActionResult&lt;object&gt;&gt; GetShops([FromQuery(Name = "category")]string category) { var response = await _httpClient.GetShops(category); return ParseResponse&lt;ShopsResponseModel&gt;(response); } </code></pre> <p><strong>ParseResponse</strong> is helper Generic method which either return SuccessModel (passed as T) or failure response Model.</p> <pre><code> protected ActionResult&lt;object&gt; ParseResponse&lt;T&gt;(object response) { if (response.GetType() == typeof(T)) { return Ok(response); } else { return Error(response); } } </code></pre> <p>Now my question is as I am fairly new to C#/ASP.net Core , is my current flow/architecture is fine, and how can I make it more elegant and more flexible.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-22T17:17:20.330", "Id": "421662", "Score": "0", "body": "I suggest that you look into the [IHttpClientFactory interface](https://docs.microsoft.com/en-us/aspnet/core/fundamentals/http-requests?view=aspnetcore-2.2); it was designed to accomplish exactly what you're doing here but has more features and is maintained by Microsoft =D." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-22T18:48:04.267", "Id": "421682", "Score": "0", "body": "Well I am using the same the only difference is i am using TypedClient" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-22T18:51:43.150", "Id": "421683", "Score": "0", "body": "Ah sorry, the `BaseClient` class threw me off; give me some time and I'll supply a proper refactor as an answer." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-12T16:32:09.800", "Id": "434492", "Score": "0", "body": "You have a typo _PutAsyc_ (I think)" } ]
[ { "body": "<p>I thought that what you have is actually quite solid; my only suggestion is that you should take advantage of C#'s features in order to slightly clean things up. First, let's create an options object to hold the various items that you're injecting into the class:</p>\n\n<pre><code>public class HttpServiceOptions&lt;TLogger&gt;\n{\n public string AuthenticationToken { get; set; }\n public ILogger&lt;TLogger&gt; Logger { get; set; }\n}\n</code></pre>\n\n<p>This should make it much simpler to add/remove dependencies to the \"system\" since everything is injected via a single \"container\". Now, let's make your base class abstract and refactor it to accept our options object:</p>\n\n<pre><code>public abstract class AbstractHttpService&lt;TLogger&gt;\n{\n private readonly string _authToken;\n private readonly HttpClient _client;\n\n public ILogger&lt;TLogger&gt; Logger { get; }\n\n public AbstractHttpService(HttpClient httpClient, IOptions&lt;HttpServiceOptions&lt;TLogger&gt;&gt; options) {\n var optionsValue = options.Value;\n var client = httpClient;\n\n client.BaseAddress = new Uri(\"url/\");\n client.DefaultRequestHeaders.Add(\"Accept\", \"application/json\");\n\n _authToken = optionsValue.AuthenticationToken;\n _client = client;\n\n Logger = optionsValue.Logger;\n }\n\n public async Task&lt;FailureResponseModel&gt; GetFailureResponseModel(HttpResponseMessage response) {\n var failureModel = await response.Content.ReadAsAsync&lt;FailureResponseModel&gt;();\n\n failureModel.ResponseStatusCode = Convert.ToInt32(response.StatusCode);\n\n Logger.LogError(\"Request Failed: {Error}\", failureModel.ResultDetails);\n\n return failureModel;\n }\n public async Task&lt;object&gt; ProcessAsync&lt;T&gt;(HttpRequestMessage request, NamingStrategy namingStrategy) {\n var authToken = _authToken;\n\n if (!string.IsNullOrEmpty(authToken)) {\n request.Headers.Authorization = new AuthenticationHeaderValue(\"Bearer\", authToken);\n }\n\n var response = await _client.SendAsync(request);\n\n if (response.IsSuccessStatusCode) {\n Logger.LogInformation(\"Request Succeeded\");\n\n var dezerializerSettings = new JsonSerializerSettings {\n ContractResolver = new DefaultContractResolver {\n NamingStrategy = namingStrategy\n }\n };\n var responseModel = JsonConvert.DeserializeObject&lt;T&gt;(await response.Content.ReadAsStringAsync(), dezerializerSettings);\n\n return responseModel;\n }\n else {\n return await GetFailureResponseModel(response);\n }\n }\n public async Task&lt;object&gt; GetAsync&lt;T&gt;(string uri) {\n return await GetAsync&lt;T&gt;(uri, new DefaultNamingStrategy());\n }\n public async Task&lt;object&gt; GetAsync&lt;T&gt;(string uri, NamingStrategy namingStrategy) {\n using (var requestMessage = new HttpRequestMessage(HttpMethod.Get, uri)) {\n return await ProcessAsync&lt;T&gt;(requestMessage, namingStrategy);\n }\n }\n public async Task&lt;object&gt; PostAsync&lt;T1, T2&gt;(string uri, T2 content) {\n return await PostAsync&lt;T1, T2&gt;(uri, content, new DefaultNamingStrategy());\n }\n public async Task&lt;object&gt; PostAsync&lt;T1, T2&gt;(string uri, T2 content, NamingStrategy namingStrategy) {\n using (var requestMessage = new HttpRequestMessage(HttpMethod.Post, uri)) {\n var json = JsonConvert.SerializeObject(content);\n\n using (var stringContent = new StringContent(json, Encoding.UTF8, \"application/json\")) {\n requestMessage.Content = stringContent;\n return await ProcessAsync&lt;T1&gt;(requestMessage, namingStrategy);\n }\n }\n }\n public async Task&lt;object&gt; PutAsyc&lt;T1, T2&gt;(string uri, T2 content) {\n return await PutAsyc&lt;T1, T2&gt;(uri, content, new DefaultNamingStrategy());\n }\n public async Task&lt;object&gt; PutAsyc&lt;T1, T2&gt;(string uri, T2 content, NamingStrategy namingStrategy) {\n using (var requestMessage = new HttpRequestMessage(HttpMethod.Put, uri)) {\n var json = JsonConvert.SerializeObject(\n value: content,\n formatting: Formatting.None,\n settings: new JsonSerializerSettings {\n NullValueHandling = NullValueHandling.Ignore\n }\n );\n\n using (var stringContent = new StringContent(json, Encoding.UTF8, \"application/json\")) {\n requestMessage.Content = stringContent;\n\n return await ProcessAsync&lt;T1&gt;(requestMessage, namingStrategy);\n }\n }\n }\n}\n</code></pre>\n\n<p><br>\nWe also need to implement the <code>ClubMatasHttpService</code> by deriving from the abstract class: </p>\n\n<pre><code>public sealed class ClubMatasHttpService : AbstractHttpService&lt;ClubMatasHttpService&gt;\n{\n public ClubMatasHttpService(HttpClient httpClient, IOptions&lt;HttpServiceOptions&lt;ClubMatasHttpService&gt;&gt; options) : base(httpClient, options) { }\n\n public async Task&lt;object&gt; GetShops(string category) {\n Logger.LogInformation(\"ClubMatas outgoing request: {RequestName}\", nameof(GetShops));\n\n return await GetAsync&lt;ShopsResponseModel&gt;($\"v2/shops?category={WebUtility.UrlEncode(category)}\");\n }\n public async Task&lt;object&gt; PostLogin(LoginRequestModel form) {\n Logger.LogInformation(\"ClubMatas outgoing request: {RequestName}\", nameof(PostLogin));\n\n return await PostAsync&lt;LoginResponseModel, LoginRequestModel&gt;(\"v2/login\", form, new SnakeCaseNamingStrategy());\n }\n}\n</code></pre>\n\n<p>Finally, we write a couple of extension methods to help configure everything:</p>\n\n<pre><code>public static class IServiceCollectionExtensions\n{\n public static IHttpClientBuilder AddClubMatasHttpService(this IServiceCollection services, Action&lt;HttpServiceOptions&lt;ClubMatasHttpService&gt;&gt; configureOptions) {\n if (null == services) { throw new ArgumentNullException(nameof(services)); }\n if (null == configureOptions) { throw new ArgumentNullException(nameof(configureOptions)); }\n\n services.Configure(configureOptions);\n\n return services.AddHttpClient&lt;ClubMatasHttpService&gt;();\n }\n public static IHttpClientBuilder AddClubMatasHttpService(this IServiceCollection services, IConfiguration configuration) {\n return services.AddClubMatasHttpService(configuration.Bind);\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-22T19:30:42.897", "Id": "421688", "Score": "0", "body": "Thank you so much, it really cleanup stuff :) Just one question which is really bugging me, you can as i am expecting 2 different models in case of success and failure, i am setting return type as `object`. Is there any other elegant way to fix this?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-22T19:34:22.223", "Id": "421690", "Score": "0", "body": "@Shabirjan I think we can, once I finish up some actual work here I'll play around with the code a bit more and see what happens." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-22T19:35:12.347", "Id": "421691", "Score": "0", "body": "Sure and thanks again :) waiting to hear from you soon" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-23T05:27:40.640", "Id": "421744", "Score": "0", "body": "A question how would I register and inject dependencies by using that options class?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-23T05:34:09.693", "Id": "421749", "Score": "0", "body": "@Shabirjan Sorry for the delay, busy with other things but I promise I will get back to ya on that; in addition to the generic stuffs." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-12T16:12:46.530", "Id": "434490", "Score": "1", "body": "@Shabirjan I have updated my answer so that configuration is handled through ASP.NET's DI system and added some extensions that demo possible usage." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-22T19:24:42.570", "Id": "217903", "ParentId": "217883", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-22T11:33:37.787", "Id": "217883", "Score": "4", "Tags": [ "c#", "asp.net-core" ], "Title": "Asp.net networking/restclient layer" }
217883
<p>I've been using my <a href="https://codereview.stackexchange.com/questions/177172/compiling-and-throwing-simple-dynamic-excepitons-at-runtime">Dynamic Exception</a> with <code>C#</code> for quite some time already and it saved me a lot of time. This means, I don't have to create a new exception <code>class</code> for each and every case. I wanted to have the same functionality on <code>Android</code> and in <code>kotlin/java</code> so I can do this:</p> <pre><code>fun main() { throw dynamicException("My", "Hallo exception!") // throws MyException } </code></pre> <hr> <p>The <code>DynamicException.kt</code> file contains most of the code where the <code>dynamicException</code> function first initializes the source-code for the new exception by formatting a <code>String</code> then it uses the <code>JavaCompiler</code> to build the class and call the appropriate construtor. Either with or without the inner exception.</p> <pre><code>import java.io.File import java.lang.reflect.Constructor import java.net.URI import java.net.URL import java.net.URLClassLoader import java.util.* import javax.tools.DiagnosticCollector import javax.tools.JavaFileObject import javax.tools.SimpleJavaFileObject import javax.tools.ToolProvider fun dynamicException(name: String, message: String, inner: Throwable? = null): java.lang.Exception { val javaCompiler = ToolProvider.getSystemJavaCompiler() val diagnosticCollector = DiagnosticCollector&lt;JavaFileObject&gt;() val values = TreeMap&lt;String, String&gt;(String.CASE_INSENSITIVE_ORDER) values["name"] = name var sourceCode = SourceCodeJavaFileObject( "com.he-dev.${name}Exception", dynamicExceptionSourceCode.smartFormat(values) ) javaCompiler.getTask( null, null, diagnosticCollector, null, null, arrayListOf(sourceCode) ).call() val classLoader = URLClassLoader.newInstance(arrayOf&lt;URL&gt;(File("").toURI().toURL())) var getCtor: () -&gt; Constructor&lt;out Any&gt; = { val cls = Class.forName("${name}Exception", true, classLoader) val ctor = if (inner == null) { cls.getConstructor(String::class.java) } else { cls.getConstructor(String::class.java, Throwable::class.java) } ctor.makeAccessible() } return if (inner == null) { getCtor().newInstance(message) as java.lang.Exception } else { getCtor().newInstance(message, inner) as java.lang.Exception } } fun Constructor&lt;out Any&gt;.makeAccessible(): Constructor&lt;out Any&gt; { this.isAccessible = true return this } val dynamicExceptionSourceCode: String = """ public class {Name}Exception extends java.lang.Exception { public {Name}Exception(java.lang.String message) { super(message); } public {Name}Exception(java.lang.String message, java.lang.Throwable inner) { super(message, inner); } } """.trimIndent() class SourceCodeJavaFileObject : SimpleJavaFileObject { private val sourceCode: CharSequence constructor(className: String, sourceCode: CharSequence) : super( URI.create("string:///" + className.replace('.', '/') + JavaFileObject.Kind.SOURCE.extension), JavaFileObject.Kind.SOURCE ) { this.sourceCode = sourceCode } override fun getCharContent(ignoreEncodingErrors: Boolean): CharSequence { return sourceCode } } </code></pre> <p>The string formatting is done with a string extension that can replace patterns. I based it on my <a href="https://codereview.stackexchange.com/questions/109858/named-string-interpolation"><code>C#</code> formatter</a>. However, it's simpler because it doesn't not support value formatting.</p> <pre><code>import java.util.* fun String.smartFormat(values: TreeMap&lt;String, String&gt;): String { val regex = Regex("""\{(?&lt;name&gt;[a-z][a-z0-9_.-]*)\}""", RegexOption.IGNORE_CASE) return regex.replace(this) { var key = it.groups["name"]?.value if (values.containsKey(key)) values[key]!! else it.value } } </code></pre> <hr> <p>Is there anything that can be simplified or made even cleaner?</p> <hr> <p><strong>Disclaimer</strong>: Please let's not make it about whether this utility is a good or bad practice. I've used it many projects already and it stands the test of being super-helpful and super-efficient. I can discuss it on Software Engineering if you'd like to know more but here I'm only interested in improving the code.</p> <blockquote> <p><strong>Mod Note:</strong> The original asker added an extended explanation for their use of this pattern as a <a href="https://codereview.stackexchange.com/a/217967/37660">community wiki answer</a> on the linked previous implementation of this code in C#.</p> </blockquote>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-22T12:43:58.460", "Id": "421617", "Score": "0", "body": "Given how easy and compact it is to create classes in Kotlin, I don't see the point for why you would want to do this. It will be completely impossible to catch those exceptions for example." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-22T12:46:40.750", "Id": "421618", "Score": "1", "body": "@SimonForsberg true, it's easy but still, you have to write them. With this, you just throw exceptions... and catching them... mhmmm... I never knew why one would want to this ;-] It's for information purposes and for easier debugging, 99.99% there is nothing one can do about an exception but log it and break or repeat the operation so I see no value in catching anything but `Exception`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-22T13:02:57.513", "Id": "421623", "Score": "0", "body": "@SimonForsberg for example currently in one of my `C#` projects I would usually have to create four exceptions, one for each of the common http-methods when I would like to throw exceptions like `GetMethodNotSupported` or some less helpful generic one as `MethodNotSupported`. I find it's more helpful and much more efficient to simply do `DynamicException.Create($\"ExtractMethodName(memberName)}NotSupported\", ...)` instead." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-22T16:21:07.890", "Id": "421644", "Score": "9", "body": "That's exactly what the message is for. You don't need to have one kind of exception for every possible method name that can be missing, just have one generic class for `MethodNotSupported` and use an appropriate message on it for all the details that you need to indicate what went wrong and how to reproduce it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-22T16:33:34.443", "Id": "421648", "Score": "11", "body": "If you don't want to catch specific exceptions, identified by their type, why would you want to introduce different exception types? Different messages will do the job of producing useful log entries. Your approach of invoking the compiler at runtime seems like a very complex solution to a problem that doesn't really exist." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-22T16:55:47.083", "Id": "421655", "Score": "0", "body": "@RalfKleberhoff in a perfect world, maybe, but in this world the software is not perfect and often all you've got is the name of the exception (message got lost, the logger is configured the wrong way, the debugger does not show the message etc) so also the name of the exception needs to be of maximum usefulness, otherwise there is no need to have them. How helpful is an exception like `UnsupportedOperationException` vs `GetMethodNotSupportedException`? You don't even need a message for that one or you can use it for other details etc. You look at it and you instantly know what is going on." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-22T17:10:47.473", "Id": "421659", "Score": "0", "body": "I'm actually very happy about (all of) you not liking it because it means that this utility is challenging the dogma of working with exceptions or others topics in my other questions :-]" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-22T20:02:38.060", "Id": "421699", "Score": "7", "body": "@t3chb0t If all you've got is the name of the exception, then you are doing something else wrong. If you want maximum usefulness of the name of your exception, why don't your name your exception `BackgroundNotFound_C_Users_t3chb0t_Desktop_filename_png` ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-23T01:38:55.710", "Id": "421729", "Score": "0", "body": "Have to -1 because it appears that you're basically trying to create a subtype by folding a `string`-field's content into the subtype's name. Also, [obligatory xkcd](https://xkcd.com/1172/)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-23T07:31:51.220", "Id": "421758", "Score": "1", "body": "I don't know why this question is getting downvotes, its just code that should be reveiwed, it doesn't say anything inside the rules that you should downvote code you don't agree with." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-23T08:32:33.277", "Id": "421775", "Score": "3", "body": "I have downvoted this question because I don't consider it having a good enough motivation for why this code exist, which is an important part of [posting a good question](https://codereview.meta.stackexchange.com/a/6429/31562). The OP claims that they know the code is good, while my answer and the votes on my answer says otherwise." } ]
[ { "body": "<blockquote>\n<p>Is there anything that can be simplified or made even cleaner?</p>\n</blockquote>\n<p>Yes, don't invoke the Java compiler at runtime.</p>\n<p>From your examples in a comment:</p>\n<p><code>DynamicException.Create($&quot;ExtractMethodName(memberName)}NotSupported&quot;, ...)</code></p>\n<p>From an example on <a href=\"https://codereview.stackexchange.com/questions/177172/compiling-and-throwing-simple-dynamic-excepitons-at-runtime\">your earlier post (in C#)</a></p>\n<blockquote>\n<p><code>throw (&quot;SettingNotFoundException&quot;, $&quot;Setting {fullName.ToString().QuoteWith(&quot;'&quot;)} not found.&quot;).ToDynamicException())</code></p>\n<p><code>public BackgroundImageNotFoundException(string fileName) : base($&quot;Where is the '{fileName}' image?&quot;) { }</code></p>\n</blockquote>\n<p>Replace these with:</p>\n<ul>\n<li><code>throw new MethodNotSupported(extractMethodName(memberName))</code></li>\n<li><code>throw new UnsupportedOperationError(extractMethodName(memberName))</code></li>\n<li><code>throw new IllegalStateException(&quot;Setting '&quot; + fullName + &quot;' not found&quot;)</code></li>\n<li><code>throw new FileNotFoundException(fileName)</code></li>\n</ul>\n<p>If you look at the subclasses of <a href=\"https://docs.oracle.com/javase/8/docs/api/java/lang/Exception.html\" rel=\"noreferrer\">Java's Exception</a> or <a href=\"https://docs.oracle.com/javase/8/docs/api/java/lang/RuntimeException.html\" rel=\"noreferrer\">RuntimeException</a> (many of which also has a Kotlin version) you can probably find an already existing exception that does what you need, and you just need to add a message to it.</p>\n<p>In a <a href=\"https://chat.stackexchange.com/transcript/message/40428901#40428901\">chat message related to your C# post</a> you wrote:</p>\n<blockquote>\n<p>In order to be able to track down a bug you need two pieces of information: The name of the exception and a message. With a generic exception I could just throw an Exception but the name of the exception should already be strong enough to tell what caused it, the message is just a hint.</p>\n<p>You should already know what happend by not even reading the message.</p>\n</blockquote>\n<p>I completely disagree with this. The message is not just a hint. To understand fully what happened and how to reproduce it you <strong>need to read the message.</strong></p>\n<hr />\n<p>As an extra bonus, here's how you define exceptions easily in Kotlin, and the approach I would recommend:</p>\n<pre><code>class MyException(message: String) : Exception(message)\nclass SomeOtherException(message: String) : Exception(message)\nclass UsefulException(message: String) : Exception(message)\nclass AnotherUsefulException(message: String) : Exception(message)\n</code></pre>\n<p>Please note that all this can be defined in the same file.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-22T16:45:37.733", "Id": "421651", "Score": "9", "body": "**Disclaimer:** This answer was written 10 seconds before the question was edited and a disclaimer was added. Either way, I still stand by this answer and I believe that your current approach is not good practice and adds unnecessary complexity." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-23T21:17:34.800", "Id": "421921", "Score": "0", "body": "Note that the original asker added an extended explanation for their use of this pattern as a [community wiki answer](https://codereview.stackexchange.com/a/217967/37660) on the linked previous implementation of this code in C#." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-22T16:44:14.860", "Id": "217893", "ParentId": "217885", "Score": "17" } }, { "body": "<h2>Setting <code>isAccessible</code> to true</h2>\n\n<p>You seem to be always settings <code>isAccessible</code> to true. This is only needed if you are accessing methods outside their \"access modifier\", for example if you are trying to access a private method from another class.</p>\n\n<p>Since you are only calling public methods (on public classes), this is not required.</p>\n\n<h2>Support for <code>javax.tools</code> is not for all android versions</h2>\n\n<p>You are using packages from <code>javax.tools</code>, this is not available on every android version, see the following SO question: <a href=\"https://stackoverflow.com/q/18007280/1542723\">NoClassDefFoundException when using javax.tools package</a>, make sure to properly test on the oldest android version you are targetting.</p>\n\n<p>To avoid these packages, manually define a class using byte arrays, and load that instead of the output of the compilation</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-23T03:31:52.820", "Id": "421735", "Score": "0", "body": "This is the kind of answer I was counting on. Thanks! Sorry for not having documented it in my code, without modifying the isAccessible the constructor cannot be called." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-22T20:22:05.570", "Id": "217906", "ParentId": "217885", "Score": "5" } } ]
{ "AcceptedAnswerId": "217906", "CommentCount": "11", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-22T11:53:09.820", "Id": "217885", "Score": "4", "Tags": [ "java", "exception", "kotlin", "compiler" ], "Title": "Compiling and throwing simple dynamic exceptions at runtime for JVM" }
217885
<p>I have to made an accordion-, respectively "zippy"-component using Angular 7. </p> <p>I'm new to Angular. Just started with it a few weeks ago. But with some Google-usage I was able to implement the required feature.</p> <p>Here's the way it looks.</p> <p><strong>In collapsed state:</strong></p> <p><a href="https://i.stack.imgur.com/OXJhE.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/OXJhE.png" alt="Closed accordion"></a></p> <p><strong>In expanded state:</strong></p> <p><a href="https://i.stack.imgur.com/8xDCI.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/8xDCI.png" alt="Opened accordion"></a></p> <p>Here's the code which I wrote for the accordion-component:</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>import { Component, OnInit, Input } from '@angular/core'; import { Title } from '@angular/platform-browser'; @Component({ selector: 'zippy', templateUrl: './zippy.component.html', styleUrls: ['./zippy.component.css'] }) export class ZippyComponent implements OnInit { @Input() title; isExpanded = false; buttonCaption = "Expand"; constructor() {} ngOnInit() {} onClickButton() { this.isExpanded = !this.isExpanded; this.buttonCaption = this.isExpanded ? "Collapse" : "Expand"; } }</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>.container { font-family: Arial, Helvetica, sans-serif; max-width: 800px; width: 100%; margin: auto 2rem; padding: 3rem 2rem; border: 1px solid #555; border-radius: 6px; text-align: left; font-size: 2rem; margin-bottom: 1rem; } nav { display: flex; justify-content: space-between; } .container a { text-decoration: none; padding: 0.4rem 0.6rem; font-size: 2rem; color: #555; } .container a:hover { cursor: pointer; } main { padding: 0.25rem 1rem; margin-top: 3rem; background-color: #eee; border-radius: 6px; font-size: 1.4rem; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class="container"&gt; &lt;nav&gt; &lt;div&gt;{{ title }}&lt;/div&gt; &lt;div&gt; &lt;a href="#" (click)="onClickButton()"&gt; &lt;i class="fas" [ngClass]="(isExpanded) ? 'fa-angle-up' : 'fa-angle-down'"&gt;&lt;/i&gt; &lt;/a&gt; &lt;/div&gt; &lt;/nav&gt; &lt;main *ngIf="isExpanded"&gt; &lt;div class="content"&gt; &lt;ng-content&gt;&lt;/ng-content&gt; &lt;/div&gt; &lt;/main&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <p>The code of 'app.component.html':</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div style="text-align:center" class="wrap"&gt; &lt;zippy title="Shipping Details"&gt; &lt;p&gt;Duo dolore sit et clita amet, aliquyam clita sed duo nonumy amet et et et. Rebum amet lorem stet est.&lt;/p&gt; &lt;p&gt;Prose and thy of have days heavenly. Parasites the not unto in so. Delphis yet friend drop cell caught mote, companie a gild favour and.&lt;/p&gt; &lt;p&gt;De quille inouies pieds blonds béni crépuscule les ravie fermentent, béhémots rutilements mer couleurs des de maries pénétra fortes folle. Je de dévorés suivi de. Impassibles liens a a papillon..&lt;/p&gt; &lt;/zippy&gt; &lt;zippy title="Billing Details"&gt; &lt;p&gt;Großer teuren gar im wie freunde du sanft wo, in du wo gar denkst weh liebe so ich dir. Kleinem zu spät du dann ort ort. Nun der denkst gesellschaft.&lt;/p&gt; &lt;/zippy&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <p>The functionality works but currently it just changes from collapsed to expanded state at once. It would be cool to have some animation or something similar when it changes. So that one has a "soft" transition.</p> <p>If someone knows how to transition that I would love to read his / her answer.</p> <p>All other hints, recommendations and critiques concerning my implementation welcomed as well. </p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-22T14:06:53.080", "Id": "217888", "Score": "2", "Tags": [ "typescript", "angular-2+" ], "Title": "Accordion component with Angular 7" }
217888
<p>I was solving a question asked in interview by Uber. It says:</p> <blockquote> <p>Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand. Find the minimum element in <span class="math-container">\$O(\log n)\$</span> time. You may assume the array does not contain duplicates.</p> </blockquote> <pre><code>#include &lt;iostream&gt; int find_smallest(int a[], int l, int r){ if (l ==r) return a[l]; else if (l+1 == r) return ((a[l] &lt; a[r]) ? a[l] : a[r]); else { int m = (l + r) / 2; int d1 = find_smallest(a, l, m); int d2 = find_smallest(a, m+1, r); return ((d1 &lt; d2) ? d1 : d2); } } int main(){ int a[] = {5,3,2,5,6,7}; std::cout &lt;&lt; find_smallest(a, 0, 5); } </code></pre> <p>Please ignore the hardcoding of values. It was just for testing. Also, is the runtime of the code <span class="math-container">\$O(\log n)\$</span>?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-22T18:51:44.967", "Id": "421684", "Score": "6", "body": "Your testing array is _not_ sorted-and-rotated. And the time complexity is _not_ \\$O(\\log n)\\$, but rather \\$O(n\\log n)\\$." } ]
[ { "body": "<p>The the approach could be as follows (with the added assumption of no duplicates that you ignored in your sample):</p>\n\n<p>1) Check if the first element is smaller than the second one. If so, either the inverted part was the single first element or the second part was inverted. Consequently return the minimum of the first and last element of the array.</p>\n\n<p>2) If not but the last element is smaller than the second-to-last, the whole array was inverted and the last element is the minimum. (not sure if this is allowed)</p>\n\n<p>3) If neither is the case, the first part of the array is decreasing, the second part is increasing and the minimum is the unique element a[i] with a[i-1] > a[i] &lt; a[i+1]. That element can be found in O(log n) implementing a binary search as opposed to your idea of checking both sides again, leading to O(n log n).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-23T09:48:20.820", "Id": "217937", "ParentId": "217897", "Score": "0" } }, { "body": "<p>The input, 1) which doesn't contain duplicates, has been 2) sorted, 3) rotated:</p>\n\n<pre><code>int a[] = {5,3,2,5,6,7};\n// removing duplicates gives\nint a[] = {5,3,2,6,7};\n// sorting gives\nint a[] = {2,3,5,6,7};\n// rotating gives (for instance):\nint a[] = {5,6,7,2,3};\n</code></pre>\n\n<p><code>log(n)</code> suggests a divide-and-conquer strategy like binary-search, as you found out by yourself. But what are you looking for in this case? Not a value, but the position where <code>a[n] &gt; a[n+1]</code>. Notice that if <code>a[n] &gt; a[n+1]</code>, then also <code>a[0] &gt; a[n+1]</code>: the \"direction change\" occurred in that range. If not, it occurred in the range <code>[a[n+1], a[len(a)])</code>.</p>\n\n<p>Divide-and-conquer is trickier than it may seem because it's really easy to access the array out-of-bounds. Iterator interfaces likes those of the C++ standard library make it easier and clearer:</p>\n\n<pre><code>template &lt;typename Iterator&gt;\nIterator find_partition_point(Iterator first, Iterator last) {\n if (first == last) return last; // empty array\n if (std::next(first) == last) return first; // one-value array\n if (*first &lt; *std::prev(last)) return first; // null/full rotation\n // so we have at least two elements and a change of direction\n auto pivot = first + std::distance(first, last) / 2;\n if (*pivot &lt; *first) { // direction change in [first, pivot]\n if (*std::prev(pivot) &gt; *pivot) return pivot;\n return find_partition_point(first, pivot);\n }\n return find_partition_point(std::next(pivot), last); // direction change in (pivot, last)\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-23T10:50:59.603", "Id": "217942", "ParentId": "217897", "Score": "3" } }, { "body": "<p>Here is my minimal solution about the problem </p>\n\n<ul>\n<li><p>the strategy is divide-and-conquer for the reasons already explained by @papagaga </p></li>\n<li><p>it is based on the idea that before the rotation the array has this structure </p></li>\n</ul>\n\n<pre><code>[m .. p P .. M]\n</code></pre>\n\n<p>with </p>\n\n<ul>\n<li><p><code>m</code> min </p></li>\n<li><p><code>M</code> max </p></li>\n<li><p><code>p</code> pivot</p></li>\n<li><p><code>P</code> next to the pivot so that <code>P&gt;p</code></p></li>\n<li><p>while after the rotation it has the following structure </p></li>\n</ul>\n\n<pre><code>[P .. M m .. p]\n</code></pre>\n\n<p>so the idea is to update the <code>l</code> left cursor and <code>r</code> right cursor so that <code>v[l] &gt; v[r]</code> with a divide and conquer strategy so to have <code>O(LogN)</code> complexity and ultimately the final condition is <code>l</code> and <code>r</code> are contiguous \nand the first identifies <code>M</code> while the second identifies <code>m</code> hence return the last one </p>\n\n<p><strong>EDIT</strong> Following @papagaga suggestion I provide 2 implementations </p>\n\n<h2>1. Index based solution</h2>\n\n<pre class=\"lang-cpp prettyprint-override\"><code>#include &lt;iostream&gt;\n#include &lt;vector&gt;\nusing namespace std;\n\nvector&lt;int&gt; a = {5,6,7,8,9,10,11, 1,2,3,4};\n\nunsigned int solve(const vector&lt;int&gt;&amp; a, unsigned int l=0, unsigned int r=0)\n{\n if(a.empty()) throw runtime_error(\"Empty\"); \n if(a.size()==1) return 0; \n if(r==0) r=a.size()-1; ///&lt; Overwrite the invalid initialization with the right value, unfortunately it is not possible to do this in function declaration \n if(a[l] &lt; a[r]) return l; ///&lt; Sorted in Ascending Order \n if(r-l==1) return r; \n const auto m = (r+l)/2; \n if(a[m] &gt; a[l]) return solve(a, m, r); \n return solve(a, l, m); \n}\n\nint main() {\n // your code goes here\n cout &lt;&lt; \"Min=\" &lt;&lt; a[solve(a)]; \n return 0;\n}\n\n</code></pre>\n\n<p>Comments </p>\n\n<ul>\n<li>Added the empty array case management using Exception </li>\n<li>An alternative could have been using Maybe Monad (a Boost Optional) to represent non meaningful results </li>\n</ul>\n\n<h2>2. Iterators based solution</h2>\n\n<pre class=\"lang-cpp prettyprint-override\"><code>#include &lt;iostream&gt;\n#include &lt;vector&gt;\n#include &lt;iterator&gt;\nusing namespace std;\n\nvector&lt;int&gt; a = {5,6,7,8,9,10,11, 1,2,3,4};\n\nvector&lt;int&gt;::iterator solve(const vector&lt;int&gt;::iterator l, const vector&lt;int&gt;::iterator r)\n{\n if(l==r) return r; ///&lt; Covers the single element array case \n if(*l &lt; *r) return l; ///&lt; Sorted in Ascending Order \n if(r-l==1) return r; \n const auto m = l + distance(l,r)/2; \n if(*m &gt; *l) return solve(m, r); \n return solve(l, m); \n}\n\nint main() {\n // your code goes here\n cout &lt;&lt; \"Min=\" &lt;&lt; *solve(a.begin(), a.end()-1); \n return 0;\n}\n\n</code></pre>\n\n<p>Comments </p>\n\n<ul>\n<li>Working with iterators allows to represent invalid values so no need for Exception and explicit Maybe Monad as the iterator type is one </li>\n<li>The first check automatically manages the one element case </li>\n<li>The empty array case should be managed before calling this function as it expects both the iterators point to valid elements </li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-23T11:52:02.750", "Id": "421802", "Score": "0", "body": "It's clearly and cleverly explained but there is a bug in your code if I'm not mistaken: it will return the maximum value if the array is sorted (e.g after a null or a full rotation) + the drawback of an index-based design: an artificial and misleading \"failure\" value (`0` isn't the minimum value in an empty range)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-23T11:59:23.533", "Id": "421806", "Score": "0", "body": "Yes, but I have specified it relies on the P>p assumption which is not verified in case the array is sorted (so null or full rotation). \nAnyway I'll close this corner case as well with a simple check at the beginning so thanks for finding this \n\nThe return 0 is not an error: if the array has 1 element then it is also the min \n\nI have not managed the a.size==0 case on purpose as I did not want to make the code slightly less readable adding a runtime_error" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-23T12:09:08.873", "Id": "421808", "Score": "0", "body": "Ok, I had misinterpreted the return value (thought it was the value, not its position). Nonetheless, it means you can't handle an empty array. Try to reformulate your code with iterators, you'll see you'll handle the corner cases better and avoid the default values gymnastics" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-23T12:13:42.093", "Id": "421810", "Score": "0", "body": "> `if(a.size()==1) return 0; \n if(r==0) r=a.size()-1;` Not sure if it's in the right order..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-23T13:46:17.317", "Id": "421832", "Score": "0", "body": "Hi @papagaga I have edited my answer showing how I’d manage the empty array case when working with index hence relying on Exception, then I have also followed your suggestion including an iterators based solution" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-23T11:31:42.617", "Id": "217949", "ParentId": "217897", "Score": "0" } }, { "body": "<p>Just to complement the answers from above with one own full example version: <a href=\"https://wandbox.org/permlink/IdsAwDRKsSdNhvB2\" rel=\"nofollow noreferrer\">Live</a>\nThe comments are in the code</p>\n\n<pre><code>#include &lt;algorithm&gt;\n#include &lt;cassert&gt;\n#include &lt;iostream&gt;\n#include &lt;iterator&gt;\n#include &lt;vector&gt;\n\ntemplate&lt;typename Container&gt;\nvoid print(const Container&amp; c)\n// helper function for printing container elements\n{\n std::cout &lt;&lt; \"[ \";\n std::copy(begin(c), end(c), std::ostream_iterator&lt;typename Container::value_type&gt;(std::cout, \" \"));\n std::cout &lt;&lt; \"]\";\n std::cout &lt;&lt; std::endl;\n}\n\ntemplate&lt;typename Iter&gt;\nvoid shift(Iter first, Iter last, std::size_t n)\n// helper function for left-shiting n-elements in range [first, last)\n// uses std::rotate from algorithm-STL\n{\n auto nn = n % std::distance(first, last); // invariant: shifting c.size() times provides the initial sequence\n auto new_first = first;\n std::advance(new_first, nn); // new first\n std::rotate(first, new_first, last);\n}\n\ntemplate&lt;typename Container&gt;\nvoid left_shift(Container&amp; c, std::size_t n)\n// helper function for left-shifting n-elements in container c\n{\n shift(begin(c), end(c), n);\n}\n\ntemplate&lt;typename Container&gt;\nvoid right_shift(Container&amp; c, std::size_t n)\n// helper function for right-shifting n-elements in container c\n{\n shift(rbegin(c), rend(c), n);\n}\n\ntemplate&lt;typename Iter&gt;\ntypename Iter::value_type\nmmin(Iter first, Iter last)\n//\n// Assuming non-empty sequence\n//\n// finds Minimum within sorted shifted container c with log-n complexity\n// Assumption:\n// 1) container c containes no duplicates\n// 2) container c is sorted in asceding order initially: c[n] &lt; c[n+1] (strict &lt; because no duplicates according to 1)\n//\n// if the sorted container c is shifted\n// then there is position k, for which: c[k] &gt; c[k+1]\n// -&gt;\n// it's not hard to show that: min = c[k+1] is the requested minimum\n// and the searched position k for which c[k] &gt; c[k+1]\n// is within range [start, end), for which: c[start] &gt; c[end-1];\n//\n// for example:\n// Initial sorted container:\n// 0 1 2 3 4 5 6 7 8 - position\n// 1 2 3 4 5 6 7 8 9 - elements\n//\n// shifting to left\n// 3 4 5 6 7 8 9 1 2 - c[6] &gt; c[7] = min(c)\n//\n// shifing to right:\n// 7 8 9 1 2 3 4 5 6 - c[2] &gt; c[3] = min(c)\n//\n// Algorithm for finding minimum:\n// we are doing binary search for c[k] &gt; c[k+1] within range [start, end) with c[start] &gt; c[end-1]\n// starting from 2 Ranges: \n// Range1: [start=first, end=(first+last)/2)\n// Range2: [start=(first+last)/2, last)\n//\n// and repeating recursively with [first, last) = one of {Range1, Range2} with c[first] &gt; c[last-1]\n{\n auto d = std::distance(first, last);\n\n assert(1 &lt;= d);\n\n auto p = first + d/2;\n\n return (d == 1) ? *first // 1 element\n : (\n (*first &gt; *std::next(first)) ? *std::next(first) // if pivot is beyond minimum\n : (\n\n (*p &gt; *std::next(p)) ? *std::next(p) // minimum\n : ( (*p &gt; *std::prev(last)) ? mmin(p, last) // recursive search within new range\n : mmin(first, p) // via divide and conquer\n )\n\n )\n );\n}\n\n\ntemplate&lt;typename SortedShiftedContainer&gt;\ntypename SortedShiftedContainer::value_type\nmmin(const SortedShiftedContainer&amp; c)\n{\n return mmin(begin(c), end(c));\n}\n\n\nint main()\n{\n std::vector&lt;int&gt; v{1, 2, 3, 4, 5};\n std::cout &lt;&lt; \"Initial array : \";\n print(v);\n\n for (std::size_t n = 1; n &lt;= v.size(); ++n)\n {\n auto vv{v};\n left_shift(vv, n);\n std::cout &lt;&lt; \"min = \" &lt;&lt; mmin(vv) &lt;&lt; \", \";\n std::cout &lt;&lt; \"for left-shifted \" &lt;&lt; n &lt;&lt; \" elements : \";\n print(vv);\n }\n\n for (std::size_t n = 1; n &lt;= v.size(); ++n)\n {\n auto vv{v};\n right_shift(vv, n);\n std::cout &lt;&lt; \"min = \" &lt;&lt; mmin(vv) &lt;&lt; \", \";\n std::cout &lt;&lt; \"for right-shifted \" &lt;&lt; n &lt;&lt; \" elements : \";\n print(vv);\n }\n\n\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-24T21:46:01.680", "Id": "219049", "ParentId": "217897", "Score": "0" } }, { "body": "<p>It ought to be clear that the algorithm inspects every element at least once. Therefore its complexity cannot be less than O(<em>n</em>).</p>\n\n<p>The variable and function names could be much more expressive. Is the interface pre-determined by the challenge, or did you assume that inputs are integers? It would be easier to use if it accepted a standard container, or an iterator pair in the usual way.</p>\n\n<p>The test is flawed, because the input is not a rotation of a sorted array. Also, a single test isn't enough - include more tests, ideally as the functionality is developed.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-29T15:07:51.080", "Id": "219368", "ParentId": "217897", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-22T17:34:30.823", "Id": "217897", "Score": "4", "Tags": [ "c++", "interview-questions", "complexity", "binary-search" ], "Title": "Find the smallest element in a sorted and rotated array" }
217897
<p>I'm working through a practice problem that is having me build and modify a linked list over a series of steps. I am particularly interested in knowing if there's a more elegant way of prompting the user to input a data value for a new element in a linked list (see step 5 below).</p> <p>I'd also like to know if there's a better way of counting and returning the number of elements in a linked list. </p> <p><strong>Practice Problem:</strong></p> <ul> <li>Step 4: Add a function trav_and_print to your program that will traverse the linked list and print the values of all of the data members.</li> <li>Step 5: Add code to your program that will add another element to the end of the linked list. Prompt the user for the data value. Call your trav_and_print function, and also from main print the value of last -> data to make sure that the element was added correctly.</li> <li>Step 6: Add another function count_elems that will traverse the linked list, count how many elements there are, and return that count. Test this function by calling it in various places in main, including before there are any elements in the linked list.</li> </ul> <p><strong>My code thus far:</strong></p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; typedef struct linked_list { int data; struct linked_list *next; } element; typedef element * elementptr; void trav_and_print(elementptr); int count_elems(elementptr); int main() { elementptr first = NULL; elementptr last = NULL; int var = 0; int NumElems = 0; /* Create a linked list with one element */ /* NOTE: the first element is always a special case */ first = (elementptr) malloc(sizeof(element)); last = first; last -&gt; data = 5; last -&gt; next = NULL; /* Add another element to the end of the list */ last -&gt; next = (elementptr) malloc(sizeof(element)); last = last -&gt; next; last -&gt; data = 12; last -&gt; next = NULL; /*Add another element to the end of the list; user generated number*/ last -&gt; next = (elementptr) malloc(sizeof(element)); last = last -&gt; next; printf("Enter the data value to add to the linked list: "); scanf("%d",&amp;var); last -&gt; data = var; last -&gt; next = NULL; trav_and_print(first); //prints the linked list NumElems = count_elems(first); //traverses and counts the elements in the linked list printf("Number of elements in the linked list: %d",NumElems); free(first); free(last); return 0; } void trav_and_print(elementptr f) { elementptr current; current = f; if(current == NULL) printf("There is no linked list!\n"); else while (current != NULL) { printf("The data value is %d\n",current-&gt;data); current = current -&gt; next; } } int count_elems(elementptr f) { int count = 0; elementptr current; current = f; while(current != NULL) { current = current-&gt;next; count++; } return count; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-23T22:39:19.693", "Id": "421929", "Score": "1", "body": "OT: regarding: `typedef element * elementptr;` it is a poor programming practice to hide a pointer in a typedef." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-23T22:42:03.010", "Id": "421930", "Score": "2", "body": "OT: regarding: `first = (elementptr) malloc(sizeof(element));` 1) the returned type (in c) is `void*` which can be assigned to any pointer. Casting just clutters the code, making it more difficult to understand, debug, etc 2) when calling any of the heap allocation functions: `malloc()` `calloc()` `realloc()` always check (!=NULL) the returned value to assure the operation was successful" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-24T01:47:59.787", "Id": "422931", "Score": "0", "body": "@user3629249 : Regarding your first comment, is it poor practice because it is uncommon to do so and reduces readability, or for some other reason? I'm not disagreeing with you, I'm just curious about the reasoning. The book I'm learning with, \"C for Matlab Programmers\" by Stormy Attaway, regularly places pointers in typedef so I assumed this was standard practice." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-24T15:14:10.883", "Id": "423018", "Score": "1", "body": "The current implementation of the program has a possible memory leak because it only deletes the head and the tail of the linked list. If an entire linked list needs to be deallocated or deleted, there should be a function that traverses the linked list and deletes each node." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-24T15:14:59.627", "Id": "423019", "Score": "1", "body": "Always test the return value of `malloc(size_t size)` to make sure it isn't NULL. The function `malloc()` returns NULL if it fails and it can fail for a variety of reasons such as not enough memory to allocate. In object oriented languages the new operator or the constructor will throw an exception in this case." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-24T15:16:55.287", "Id": "423020", "Score": "1", "body": "For procedural languages there is a design methodology called Top Down Design (also known as Step-wise Refinement) that breaks the problem into smaller and smaller parts until all the parts are atomic. With linked lists some basic operations are insert node, append node, delete node and perhaps find node. There might also be new node that creates the node from user input.\nhttps://en.wikipedia.org/wiki/Top-down_and_bottom-up_design" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-25T06:59:38.387", "Id": "423132", "Score": "1", "body": "it is poor practice to hide a pointer via a typedef because the fact that the 'type name' is not obviously a pointer. However, by NOT hiding the pointer in a typedef, then each time it is used as pointer the surrounding `&` or `*` is very obvious. Remember, one key objective when programming is for the code to be easy to read/understand" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-22T17:35:56.600", "Id": "217898", "Score": "1", "Tags": [ "c", "programming-challenge", "linked-list", "io" ], "Title": "Prompting the user to input a data value into an element in a linked list" }
217898
<p>The following code takes in two params. An array of sentences and an array of queries. Each query has one or more words. The function below prints out index of sentence for each query that has all the words in that sentence.</p> <p>This is functioning code. However, it is not optimized for large inputs because of how it is written. </p> <p>How can we make it more runtime optimized? Any ideas would be appreciated. </p> <pre><code>def textQueries(sentences, queries): sentences_sets = [set(s.split(' ')) for s in sentences] for i, words in enumerate(queries): results = '' for j, s in enumerate(sentences_sets): exists = True for word in words.split(' '): if word not in s: exists = False if exists: results += ' %d' % j if results else '%d' % j if results: print results else: print -1 </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-22T22:07:52.740", "Id": "421722", "Score": "0", "body": "Welcome to Code Review! You're talking about \"large inputs\". Can you give the reviewers a hint *how large* those inputs may be (typical number and length of sentences/queries)? You should also add some application context to better understand the code and its purpose." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-23T00:36:25.880", "Id": "421725", "Score": "0", "body": "1 < len(sentences) <= 10,000, 1 < len(queries) <= 10,000" } ]
[ { "body": "<p>Welcome to Code Review!</p>\n\n<p>So, I am assuming that <code>queries</code> is a list of words we are searching for, and any of them being found is a success. I am also assuming that sentences is a list of strings, with each element subdivide-able into a list of words.</p>\n\n<p><strong>Bugs:</strong></p>\n\n<p>I noticed that your existing code won't see \"This is a test.\" as having the word \"test\" in it, because of the period. You may need to separate out commas, periods, parentheses and so on for it to work properly, but perhaps this is by design. I am unsure.</p>\n\n<p><strong>Add a Break:</strong></p>\n\n<p>The first thing I see that could be improved is you don't need a flag. Instead of setting <code>exists = False</code> and then keep looping, just add your results if it is there, and then just break. You don't need to search the entire sentence if you have already found it, and you don't need a flag if you are doing the one operation within the loop.</p>\n\n<p>So:</p>\n\n<pre><code>for word in words.split(' '):\n if word in s:\n results += ' %d' % j if results else '%d' % j\n break\n</code></pre>\n\n<p>This will save you a few iterations for long sentences if the beginning matches.</p>\n\n<p><strong>Tries:</strong></p>\n\n<p>Now, if you want to completely rewrite the whole thing for O(n) passes, (which is the best you can possibly get for text searching), then you can use a \"Trie\" data structure. The way this works is by inserting all of your text, one character at a time per word, into a variation of a tree. This is O(n) insertion, where n is the number of characters in your input data. Then, for every search term, you go through and find, letter by letter, which words match. This is O(n) where n is the number of characters in each search term, so theoretically much less of an impact than the previous one.</p>\n\n<p>I modified the code that was posted here (under public domain): <a href=\"https://towardsdatascience.com/implementing-a-trie-data-structure-in-python-in-less-than-100-lines-of-code-a877ea23c1a1\" rel=\"nofollow noreferrer\">https://towardsdatascience.com/implementing-a-trie-data-structure-in-python-in-less-than-100-lines-of-code-a877ea23c1a1</a></p>\n\n<p>Most of it is not my own, but I modified it to fit your function.</p>\n\n<pre><code>class Node(object):\n def __init__(self, character):\n self.character = character\n self.children = []\n # A flag to say whether or not we are at the end of our current word.\n self.finished = False\n # How many times this character appeared in the addition process\n self.count = 1\n\nclass Trie(object):\n def __init__(self):\n # Create a root node with a non-character attribute so it won't be confused\n # with any of the entries.\n self.root = Node(None)\n\n def add(self, word):\n # Set our current node to the start/root.\n current_node = self.root\n for char in word:\n in_child = False\n # Search for the character in the children of the present node\n for child in current_node.children:\n if child.character == char:\n # We found it, increase the counter by 1 to keep track that another\n # word has it as well\n child.count += 1\n # And point the node to the child that contains this char\n current_node = child\n in_child = True\n break\n # We did not find it so add a new chlid\n if not in_child:\n new_node = Node(char)\n current_node.children.append(new_node)\n # And then point node to the new child\n current_node = new_node\n # Everything finished. Mark it as the end of a word.\n current_node.word_finished = True\n\n\n def find_term(self, term):\n \"\"\"\n Check and return\n 1. If the prefix exsists in any of the words we added so far\n 2. If yes then how may words actually have the prefix\n \"\"\"\n node = self.root\n # If the root node has no children, then return False.\n # Because it means we are trying to search in an empty trie\n if not self.root.children:\n return False, 0\n for char in term:\n char_not_found = True\n # Search through all the children of the present `node`\n for child in node.children:\n if child.character == char:\n # We found the char existing in the child.\n char_not_found = False\n # Assign node as the child containing the char and break\n node = child\n break\n # Return False anyway when we did not find a char.\n if char_not_found:\n return False, 0\n # Well, we are here means we have found the prefix. Return true to indicate that\n # And also the counter of the last node. This indicates how many words have this\n # prefix\n return True, node.count\n\ndef textQueries(sentences, queries):\n trie = Trie()\n sentences_list = [s.split(' ') for s in sentences]\n for sentence in sentences_list:\n for word in sentence:\n trie.add(word)\n\n for words in queries:\n words_list = words.split(' ')\n results_list = []\n for word in words_list:\n results = trie.find_term(word)\n if results[0]:\n results_list.append(results[1])\n if results_list:\n print results_list\n else: print -1\n</code></pre>\n\n<p>This will return:</p>\n\n<pre><code>Venkee Enterprises:&gt;python test.py \n[2]\n[1]\n</code></pre>\n\n<p>for my input data of:</p>\n\n<pre><code>sentences = [\"Hello world, this is a sentence.\", \"This is also a sentence.\", \"This, however, is an incomplete\"]\nqueries = [\"sentence\", \"Hello\"]\n</code></pre>\n\n<p>As it was able to find 2 words that match for the query \"sentence\" and 1 word that matched \"Hello\".</p>\n\n<p>Hope this helps.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-23T05:11:43.920", "Id": "217924", "ParentId": "217904", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-22T19:45:20.657", "Id": "217904", "Score": "5", "Tags": [ "python", "performance" ], "Title": "Text-search optimization algo" }
217904
<p>Given the following input (<code>cat i.txt</code>), I want to remove duplicate field entries in each of the first three columns and none of the others.</p> <pre><code>DLORENZ;EDDELAK;BCL;G1;2019-04-01;175 DLORENZ;EDDELAK;BRV/COV;G1;2018-01-31;165 DLORENZ;EDDELAK;BRV/COV;G2;2018-02-28;165 DLORENZ;EDDELAK;BRV/COV;WH;2018-05-29;88 DLORENZ;EDDELAK;BRV/COV;WH;2018-10-02;139 ... </code></pre> <p>The input is sorted first on column 1, then on column 2, then on column 3, then on column 4, then on column 5, then on column 6.</p> <p>That is, from here (<code>cat i.txt | column -s ';' -t</code>)</p> <pre><code>DLORENZ EDDELAK BCL G1 2019-04-01 175 DLORENZ EDDELAK BRV/COV G1 2018-01-31 165 DLORENZ EDDELAK BRV/COV G2 2018-02-28 165 DLORENZ EDDELAK BRV/COV WH 2018-05-29 88 DLORENZ EDDELAK BRV/COV WH 2018-10-02 139 DLORENZ EDDELAK BRV/COV WH 2019-01-07 140 HELMGBR GUDENDORF BCL G1 2018-04-29 600 HELMGBR GUDENDORF BCL G2 2018-05-28 580 HELMGBR GUDENDORF BCL WH 2018-11-21 600 HELMGBR GUDENDORF BOT G1 2018-07-09 600 HELMGBR GUDENDORF BOT G2 2018-08-06 600 HELMGBR GUDENDORF BOT WH 2019-02-13 600 HELMGBR GUDENDORF CHLM G1 2017-12-14 600 HELMGBR GUDENDORF CHLM G2 2018-01-11 600 HELMGBR GUDENDORF CHLM WH 2018-09-05 550 HKARSTENS KUDEN BCL G1 2019-03-11 255 HKARSTENS KUDEN BCL G2 2019-04-10 255 HSCHLADETSCH EDDELAK BCL G1 2019-03-11 213 HSCHLADETSCH EDDELAK BCL G2 2019-04-08 201 HSCHLADETSCH EDDELAK BRV/COV G1 1979-01-01 218 HSCHLADETSCH EDDELAK BRV/COV G2 1979-01-01 218 HSCHLADETSCH EDDELAK BRV/COV WH 2018-03-13 218 HSCHLADETSCH EDDELAK BRV/COV WH 2018-09-10 160 HWULFF KUDEN BCL G1 2018-02-28 244 HWULFF KUDEN BCL G2 2018-03-28 244 HWULFF KUDEN BCL WH 2018-09-20 190 HWULFF KUDEN BCL WH 2019-03-19 250 HWULFF KUDEN CHLM G1 2018-04-01 244 HWULFF KUDEN CHLM G2 2018-04-29 244 HWULFF KUDEN CHLM WH 2019-03-28 250 JMEIER EDDELAK BCL G1 2018-04-30 360 JMEIER EDDELAK BCL G2 2018-05-28 360 JPETERS KAISERWILHELMKOOG CHLM G1 2018-02-26 65 JPETERS KAISERWILHELMKOOG CHLM G2 2018-03-26 65 JPETERS KAISERWILHELMKOOG CHLM WH 2019-01-18 79 JTHODE BUCHHOLZ BCL G1 2019-03-12 253 JTHODE BUCHHOLZ BCL G2 2019-04-12 253 KMEHLERT BRUNSBUETTEL BCL G1 2018-12-13 79 KMEHLERT BRUNSBUETTEL BCL G2 2019-01-10 119 MMAGENS BARLT CHLM G1 2018-02-13 165 MMAGENS BARLT CHLM G2 2018-03-13 165 MMAGENS BARLT CHLM WH 2018-09-12 136 MMAGENS BARLT CHLM WH 2019-03-14 132 MSCHNEPEL WINDBERGEN CHLM G1 2017-10-09 205 MSCHNEPEL WINDBERGEN CHLM G2 2017-11-02 263 MSCHNEPEL WINDBERGEN CHLM WH 2018-04-10 272 MSCHNEPEL WINDBERGEN CHLM WH 2018-10-25 208 NJUNGE EDDELAK BCL G1 2018-03-07 146 NJUNGE EDDELAK BCL G2 2018-04-04 146 NJUNGE EDDELAK BCL WH 2018-08-06 100 NJUNGE EDDELAK BCL WH 2018-11-14 105 NJUNGE EDDELAK BCL WH 2019-03-12 118 SMOHR BRUNSBUETTEL CHLM G1 2018-04-30 110 SMOHR BRUNSBUETTEL CHLM G2 2018-05-28 110 SMOHR BRUNSBUETTEL CHLM WH 2018-12-18 98 </code></pre> <p>... I want to arrive at the following output (<code>cat 1fertig.txt | column -s ';' -t</code>):</p> <pre><code>DLORENZ EDDELAK BCL G1 2019-04-01 175 ---- ---- BRV/COV G1 2018-01-31 165 ---- ---- ---- G2 2018-02-28 165 ---- ---- ---- WH 2018-05-29 88 ---- ---- ---- WH 2018-10-02 139 ---- ---- ---- WH 2019-01-07 140 HELMGBR GUDENDORF BCL G1 2018-04-29 600 ---- ---- ---- G2 2018-05-28 580 ---- ---- ---- WH 2018-11-21 600 ---- ---- BOT G1 2018-07-09 600 ---- ---- ---- G2 2018-08-06 600 ---- ---- ---- WH 2019-02-13 600 ---- ---- CHLM G1 2017-12-14 600 ---- ---- ---- G2 2018-01-11 600 ---- ---- ---- WH 2018-09-05 550 HKARSTENS KUDEN BCL G1 2019-03-11 255 ---- ---- ---- G2 2019-04-10 255 HSCHLADETSCH EDDELAK BCL G1 2019-03-11 213 ---- ---- ---- G2 2019-04-08 201 ---- ---- BRV/COV G1 1979-01-01 218 ---- ---- ---- G2 1979-01-01 218 ---- ---- ---- WH 2018-03-13 218 ---- ---- ---- WH 2018-09-10 160 HWULFF KUDEN BCL G1 2018-02-28 244 ---- ---- ---- G2 2018-03-28 244 ---- ---- ---- WH 2018-09-20 190 ---- ---- ---- WH 2019-03-19 250 ---- ---- CHLM G1 2018-04-01 244 ---- ---- ---- G2 2018-04-29 244 ---- ---- ---- WH 2019-03-28 250 JMEIER EDDELAK BCL G1 2018-04-30 360 ---- ---- ---- G2 2018-05-28 360 JPETERS KAISERWILHELMKOOG CHLM G1 2018-02-26 65 ---- ---- ---- G2 2018-03-26 65 ---- ---- ---- WH 2019-01-18 79 JTHODE BUCHHOLZ BCL G1 2019-03-12 253 ---- ---- ---- G2 2019-04-12 253 KMEHLERT BRUNSBUETTEL BCL G1 2018-12-13 79 ---- ---- ---- G2 2019-01-10 119 MMAGENS BARLT CHLM G1 2018-02-13 165 ---- ---- ---- G2 2018-03-13 165 ---- ---- ---- WH 2018-09-12 136 ---- ---- ---- WH 2019-03-14 132 MSCHNEPEL WINDBERGEN CHLM G1 2017-10-09 205 ---- ---- ---- G2 2017-11-02 263 ---- ---- ---- WH 2018-04-10 272 ---- ---- ---- WH 2018-10-25 208 NJUNGE EDDELAK BCL G1 2018-03-07 146 ---- ---- ---- G2 2018-04-04 146 ---- ---- ---- WH 2018-08-06 100 ---- ---- ---- WH 2018-11-14 105 ---- ---- ---- WH 2019-03-12 118 SMOHR BRUNSBUETTEL CHLM G1 2018-04-30 110 ---- ---- ---- G2 2018-05-28 110 ---- ---- ---- WH 2018-12-18 98 </code></pre> <p>The output will be further processed into a LaTeX input file.</p> <p>The code I wrote is reasonably straightforward:</p> <p>First kill the duplicates in column 3 of input, then kill the duplicates in column 2 of the result, then kill the duplicates in column 1 of that result.</p> <p>It is even efficient enough for my needs (and I can't come up with anything substantially faster offhand, except for not writing to disk that much). But it is not readable at all.</p> <pre><code>n="$(wc -l &lt; i.txt)" rm -rfv f mkdir f cat i.txt &gt; f/i.txt cd f while IFS=';' read lbezg rest do echo "$lbezg"';'"$rest" &gt;&gt; 1lw_"$lbezg" done &lt; i.txt for file in 1lw_* do while IFS=';' read lbezg sbezg rest do echo "$lbezg"';'"$sbezg"';'"$rest" &gt;&gt; 1lw_2so_"$lbezg"_"$sbezg" done &lt; "$file" done for file in 1lw_2so_* do while IFS=';' read lbezg sbezg impfstoff rest do ii="$(echo "$impfstoff" | tr -d '/')" echo "$lbezg"';'"$sbezg"';'"$impfstoff"';'"$rest" &gt;&gt; 1lw_2so_3impfstoff_"$lbezg"_"$sbezg"_"$ii" done &lt; "$file" done for file in 1lw_2so_3impfstoff_* do awk -F';' -v OFS=';' ' {if (NR&gt;1) $3="----"; print $0}' &lt; "$file" done &gt; 3fertig.txt rm 1lw* while IFS=';' read lbezg rest do echo "$lbezg"';'"$rest" &gt;&gt; 1lw_"$lbezg" done &lt; 3fertig.txt for file in 1lw_* do while IFS=';' read lbezg sbezg rest do echo "$lbezg"';'"$sbezg"';'"$rest" &gt;&gt; 1lw_2so_"$lbezg"_"$sbezg" done &lt; "$file" done for file in 1lw_2so_* do awk -F';' -v OFS=';' ' {if (NR&gt;1) $2="----"; print $0}' &lt; "$file" done &gt; 2fertig.txt rm 1lw* while IFS=';' read lbezg rest do echo "$lbezg"';'"$rest" &gt;&gt; 1lw_"$lbezg" done &lt; 2fertig.txt for file in 1lw_* do awk -F';' -v OFS=';' ' {if (NR&gt;1) $1="----"; print $0}' &lt; "$file" done &gt; 1fertig.txt rm 1lw* ####### the rest is for nice error checking and not strictly necessary time for i in $(seq 1 "$n") do l1="$(sed -n "$i"p &lt; i.txt)" l2="$(sed -n "$i"p &lt; 1fertig.txt)" echo "$i"';'"$l1"'|'"$i"';'"$l2" done | column -s '|' -t &gt; differ.txt </code></pre> <p>I wonder how you would go about this?</p>
[]
[ { "body": "<p>The shell is usually a poor choice for processing data. Let <code>awk</code> do it for you:</p>\n\n<pre><code>#!/usr/bin/awk -f\nBEGIN { FS = OFS = \";\" }\n{\n stub=\"\"\n for (i=1;i&lt;=3;i++) if (saw[ stub = stub FS $i ]++) $i=\"----\"\n print\n}\n</code></pre>\n\n<p>If it has to be bash:</p>\n\n<pre><code>#!/bin/bash\nawk -F\\; -vOFS=\\; '{s=0; for(i=1;i&lt;=3;i++) if(saw[s=s FS $i]++) $i=\"----\"} 1' i.txt &gt; 1fertig.txt \n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-02T12:18:59.357", "Id": "424102", "Score": "0", "body": "I'm afraid this does not produce the intended output, because, for example, the first line of the output now reads\n\n` DLORENZ;EDDELAK;BRV/COV;G2;2018-02-28;165`\n\nwhich is incorrect, because there is no line above this line that has \"G1\" in the fourth field, whereas in the original output, we have\n\n` DLORENZ;EDDELAK;BRV/COV;G1;2018-01-31;165`\n\nin line 2, followed by\n\n DLORENZ;EDDELAK;BRV/COV;G2;2018-02-28;165\n\nin line 3.\n\nI'll see where I end up using your approach with arrays, though. Decorating the output of your script and re-sorting will allow me to restore the sort." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-02T22:04:18.000", "Id": "424145", "Score": "0", "body": "I think you've introduced an error somewhere, or changed your input without realizing it. Before posting, I saved your example input and output. A diff between your output and mine gave zero differences. Testing again just now, the first line of output I get is `DLORENZ;EDDELAK;BCL;G1;2019-04-01;175`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-03T08:55:09.647", "Id": "424204", "Score": "0", "body": "What awk version do you use?\n\n`\n[tdu:gimli] /tmp/tdu/work\n awk --version | head -n 2\nGNU Awk 4.1.4, API: 1.1 (GNU MPFR 4.0.1, GNU MP 6.1.2)\nCopyright (C) 1989, 1991-2016 Free Software Foundation.\n\n[tdu:gimli] /tmp/tdu/work\n head -n 1 i.txt \nDLORENZ;EDDELAK;BRV/COV;G2;2018-02-28;165;Lorenz:Dirk;DLORENZ\n\n[tdu:gimli] /tmp/tdu/work\n LC_ALL=C awk -F\\; -vOFS=\\; '{s=0; for(i=1;i<=3;i++) if(saw[s=s FS $i]++) $i=\"----\"} 1' i.txt > 1fertig.txt\n\n[tdu:gimli] /tmp/tdu/work\n head -n 1 1fertig.txt \nDLORENZ;EDDELAK;BRV/COV;G2;2018-02-28;165;Lorenz:Dirk;DLORENZ\n\n[tdu:gimli] /tmp/tdu/work\n`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-03T08:55:49.920", "Id": "424205", "Score": "0", "body": "and the backticks for `code` seem not to be suitable for several lines in a row... :(" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-03T09:25:19.543", "Id": "424207", "Score": "0", "body": "GNU Awk 4.2.1. Look at your own input. The first line is `G2` in the 4th field, and the output is the same. There's nothing in the awk code that can change the 4th field at all, let alone from G1 to G2." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-06T08:34:04.880", "Id": "424549", "Score": "0", "body": "My bad. I missed a step I added in between for easier error-checking. Your solution works perfectly once I supply the correct input." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-30T12:55:26.757", "Id": "219430", "ParentId": "217907", "Score": "2" } } ]
{ "AcceptedAnswerId": "219430", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-22T20:23:49.487", "Id": "217907", "Score": "4", "Tags": [ "reinventing-the-wheel", "bash", "csv", "awk" ], "Title": "Removing duplicate field entries from sorted csv data" }
217907
<p>I have a need to turn byte arrays into various structures.</p> <p>First version:</p> <pre><code>public static object ConvertBytesToStructure(object target, byte[] source, Int32 targetSize, int startIndex, int length) { if (target == null) return null; IntPtr p_objTarget = Marshal.AllocHGlobal(targetSize); try { Marshal.Copy(source, startIndex, p_objTarget, length); Marshal.PtrToStructure(p_objTarget, target); } catch (Exception e) { Console.WriteLine(e); } finally { Marshal.FreeHGlobal(p_objTarget); } return target; } </code></pre> <p>I have found that when i calling to the first version a lot of times in a second - i getting poor performance.</p> <p>So i trying to improve that to the version 2:</p> <pre><code> private static T ReadUsingMarshalUnsafe&lt;T&gt;(byte[] data, int startIndex, int length) { byte[] fixedData = new byte[length]; unsafe { fixed (byte* pSource = data, pTarget = fixedData) { int index = 0; for (int i = startIndex; i &lt; data.Length; i++) { pTarget[index] = pSource[i]; index++; } } fixed (byte* p = &amp;fixedData[0]) { return (T)Marshal.PtrToStructure(new IntPtr(p), typeof(T)); } } } </code></pre> <p>I have found that this version getting very good performance..</p> <p>But i want to getting your code review - maybe i'll have any memory leak? maybe i can to do this with efficent another way?</p> <p>Thanks!</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-22T22:42:13.320", "Id": "421723", "Score": "1", "body": "What version of .NET are you using? If on .NET Core 2.1 or above then one can rely on the native `MemoryMarshal` class which has a method `Read<T>` that I believe matches your needs. Alternatively, one can import the *System.Memory* NuGet package if using .NET Framework 4.5 or above; it is not as optimized but should work well." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-23T06:33:46.880", "Id": "421751", "Score": "0", "body": "Could also show the `struct`s you are using?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-23T08:59:47.540", "Id": "421783", "Score": "0", "body": "@Kittoes0124, .NETFramework 4.0 client" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-23T09:03:35.187", "Id": "421784", "Score": "0", "body": "@t3chb0t i'll attach an example" } ]
[ { "body": "<p>Expanding on my comment; below you'll find a very simple program that compares the method I suggested with your original example. The results on my machine show that the <code>MemoryMarshal</code> class is about 85x faster. You might want to experiment a bit and try running a similar test with a larger struct; maybe your method is faster for the specific problem that you're trying to solve.</p>\n\n<p><strong>Comparison Code:</strong></p>\n\n<pre><code>using BenchmarkDotNet.Attributes;\nusing BenchmarkDotNet.Running;\nusing System;\nusing System.Runtime.InteropServices;\n\npublic readonly struct SomeStruct\n{\n private readonly ulong m_x;\n private readonly ulong m_y;\n private readonly ulong m_z;\n\n public ulong X =&gt; m_x;\n public ulong Y =&gt; m_y;\n public ulong Z =&gt; m_z;\n\n public SomeStruct(ulong x, ulong y, ulong z) {\n m_x = x;\n m_y = y;\n m_z = z;\n }\n}\n\npublic class Race\n{\n private readonly byte[] m_data = new byte[] {\n 0, 0, 0, 0, 0, 0, 0, 0,\n 1, 0, 0, 0, 0, 0, 0, 0,\n 1, 255, 0, 0, 0, 0, 0, 0,\n };\n\n [Benchmark(Baseline = true)]\n public SomeStruct A() =&gt; MemoryMarshal.Read&lt;SomeStruct&gt;(m_data);\n [Benchmark]\n public SomeStruct B() =&gt; Program.ReadUsingMarshalUnsafe&lt;SomeStruct&gt;(m_data, 0, m_data.Length);\n}\n\nclass Program\n{\n static void Main(string[] args) {\n var summary = BenchmarkRunner.Run&lt;Race&gt;();\n\n Console.ReadKey();\n }\n\n public static T ReadUsingMarshalUnsafe&lt;T&gt;(byte[] data, int startIndex, int length) {\n byte[] fixedData = new byte[length];\n unsafe {\n fixed (byte* pSource = data, pTarget = fixedData) {\n int index = 0;\n for (int i = startIndex; i &lt; data.Length; i++) {\n pTarget[index] = pSource[i];\n index++;\n }\n }\n\n fixed (byte* p = &amp;fixedData[0]) {\n return (T)Marshal.PtrToStructure(new IntPtr(p), typeof(T));\n }\n }\n }\n}\n</code></pre>\n\n<p><br>\n<strong>BenchmarkDotNet Results:</strong></p>\n\n<p><a href=\"https://i.stack.imgur.com/RDfTU.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/RDfTU.png\" alt=\"Benchmark results.\"></a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-23T09:18:48.107", "Id": "421787", "Score": "0", "body": "MemoryMarshal is not exists in old framework:\\" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-22T23:00:44.733", "Id": "217913", "ParentId": "217908", "Score": "6" } }, { "body": "<p>first of all, thanks for your great example.</p>\n\n<p>I update my little program based of your answer to benchmark it.</p>\n\n<p>The project should be .NETFramework 4.0 client, but for the benchmark i change it to be .NETFramework 4.0.</p>\n\n<pre><code> [StructLayout(LayoutKind.Sequential, Pack = 4)]\npublic class SomeStructure\n{\n [MarshalAs(UnmanagedType.ByValArray, SizeConst = 2)]\n public char[] szF1;\n public char cF2;\n [MarshalAs(UnmanagedType.ByValArray, SizeConst = 8)]\n public char[] szF3;\n [MarshalAs(UnmanagedType.ByValArray, SizeConst = 7)]\n public char[] szF4;\n [MarshalAs(UnmanagedType.ByValArray, SizeConst = 7)]\n public char[] szF5;\n [MarshalAs(UnmanagedType.ByValArray, SizeConst = 7)]\n public char[] szF6;\n [MarshalAs(UnmanagedType.ByValArray, SizeConst = 9)]\n public char[] szF7;\n [MarshalAs(UnmanagedType.ByValArray, SizeConst = 9)]\n public char[] szF8;\n [MarshalAs(UnmanagedType.ByValArray, SizeConst = 9)]\n public char[] szF9;\n [MarshalAs(UnmanagedType.ByValArray, SizeConst = 9)]\n public char[] szF10;\n [MarshalAs(UnmanagedType.ByValArray, SizeConst = 1)]\n public char[] cF11;\n public char cF12;\n [MarshalAs(UnmanagedType.ByValArray, SizeConst = 2)]\n public char[] cF13;\n [MarshalAs(UnmanagedType.ByValArray, SizeConst = 7)]\n public char[] szF14;\n [MarshalAs(UnmanagedType.ByValArray, SizeConst = 9)]\n public char[] szF15;\n [MarshalAs(UnmanagedType.ByValArray, SizeConst = 7)]\n public char[] szF16;\n [MarshalAs(UnmanagedType.ByValArray, SizeConst = 9)]\n public char[] szF17;\n}\n\npublic class Race\n{\n //[Benchmark(Baseline = true)]\n //public SomeStruct A() =&gt; MemoryMarshal.Read&lt;SomeStruct&gt;(_data);\n [Benchmark(Baseline = true)]\n public object A() =&gt; Program.ConvertBytesToStructure(new SomeStructure(), _data, Marshal.SizeOf(typeof(SomeStructure)), 0, _data.Length);\n\n [Benchmark]\n public SomeStructure B() =&gt; Program.ConvertBytesToStructureV2&lt;SomeStructure&gt;(_data, 0, _data.Length);\n\n private readonly byte[] _data = new byte[] {\n 49, 50, 49, 49, 50, 51, 52, 53, 54, 55, 56,\n 49, 50, 51, 52, 53, 54, 55, 49, 50, 51, 52,\n 53, 54, 55, 49, 50, 51, 52, 53, 54, 55, 49,\n 50, 51, 52, 53, 54, 55, 56, 57, 49, 50, 51,\n 52, 53, 54, 55, 56, 57, 49, 50, 51, 52, 53,\n 54, 55, 56, 57, 49, 50, 51, 52, 53, 54, 55,\n 56, 57, 49, 97, 49, 50, 49, 50, 51, 52, 53,\n 54, 55, 49, 50, 51, 52, 53, 54, 55, 56, 57,\n 49, 50, 51, 52, 53, 54, 55, 49, 50, 51, 52,\n 53, 54, 55, 56, 57\n};\n\n}\n\n public class Program\n{\n\n static void Main(string[] args)\n {\n var summary = BenchmarkRunner.Run&lt;Race&gt;();\n Console.ReadKey();\n }\n\n\n public static object ConvertBytesToStructure(object target, byte[] source, Int32 targetSize, int startIndex, int length)\n {\n if (target == null)\n return null;\n\n IntPtr p_objTarget = Marshal.AllocHGlobal(targetSize);\n try\n {\n Marshal.Copy(source, startIndex, p_objTarget, length);\n Marshal.PtrToStructure(p_objTarget, target);\n }\n catch (Exception e)\n {\n Console.WriteLine(e);\n }\n finally\n {\n Marshal.FreeHGlobal(p_objTarget);\n }\n\n return target;\n }\n\n public static T ConvertBytesToStructureV2&lt;T&gt;(byte[] data, int startIndex, int length)\n {\n byte[] fixedData = new byte[length];\n unsafe\n {\n fixed (byte* pSource = data, pTarget = fixedData)\n {\n int index = 0;\n for (int i = startIndex; i &lt; data.Length; i++)\n {\n pTarget[index] = pSource[i];\n index++;\n }\n }\n\n fixed (byte* p = &amp;fixedData[0])\n {\n return (T)Marshal.PtrToStructure(new IntPtr(p), typeof(T));\n }\n }\n }\n\n}\n</code></pre>\n\n<p>The results:</p>\n\n<p><a href=\"https://i.stack.imgur.com/SkjqN.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/SkjqN.png\" alt=\"enter image description here\"></a></p>\n\n<p>If i understand good - it seems that according to the Benchmark results,the first method is faster than the second method.</p>\n\n<p>But these are not the results I see in my system.</p>\n\n<p>More details:\nIt's multi-threading system, i've a service that listen to another service and register to his event, when the event is raised with unmanaged data (byte[]) i convert that to the my cutom managed object.</p>\n\n<p>So far so good, but when i stress the system by sending thousands of events (~20000) per second, The original method (ConvertBytesToStructure) getting poor performance, and the new method getting excellent performance..</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-23T09:06:21.477", "Id": "217935", "ParentId": "217908", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-22T21:05:20.557", "Id": "217908", "Score": "6", "Tags": [ "c#", "memory-management", "serialization" ], "Title": "Unmanaged byte array to managed structure" }
217908
<p><strong>Context</strong></p> <p>Was inspired from this <a href="https://leetcode.com/discuss/interview-question/system-design/159188/Design-a-snake-and-ladders-games" rel="nofollow noreferrer">LeetCode post</a> to do my own System Design exercise of the common Snake and Ladders problem. As I was writing the code Mario Party kept coming to mind so I added a little fun theme to it.</p> <p><strong>Feedback</strong></p> <p>Did I make the appropriate system design choices in terms of the classes I've implemented the functionality expressed within them? Let me know of any improvements I can make to the implementation of inheritance and polymorphism with my <code>Space</code> Abstract Class. I have Smart Pointers in place for possible future requirements to take this board from a linear data structure to something you would see in an actual Mario Party game. Any other general feedback would be appreciated too.</p> <p><strong>Code</strong></p> <pre><code>#include &lt;cstdlib&gt; #include &lt;cmath&gt; #include &lt;iostream&gt; #include &lt;map&gt; #include &lt;memory&gt; #include &lt;string&gt; #include &lt;vector&gt; // stars ✩ space ○ class Player { private: int m_current_space = 1; public: Player() {} void role_dice() { m_current_space += floor( (rand()%10 + 1) / 3 ); } int const get_current_space() { if(m_current_space &gt; 9) { return 9; } return m_current_space; } void set_current_space(int current_space) { m_current_space = current_space; } }; class Space { protected: int m_id; std::vector&lt;std::shared_ptr&lt;Space&gt;&gt; m_paths; public: Space() {} // requied to use [] operator in map Space(int id) : m_id(id) {} /* POSSIBLE SEG FAUL HERE, BE CARFUL */ void add_path(std::shared_ptr&lt;Space&gt; s) { m_paths.push_back(s); } int get_id() { return m_id; } virtual void event(Player&amp; p) = 0; virtual std::string class_type() = 0; }; class Empty : public Space { public: Empty(int id) : Space(id) {} void event(Player&amp; p) {} std::string class_type() { return "Empty"; } }; class Ladder : public Space { public: Ladder(int id) : Space(id) {} virtual void event(Player&amp; p) { std::cout &lt;&lt; "Waha!" &lt;&lt; '\n'; p.set_current_space(5); } std::string class_type() { return "Ladder"; } }; class Snake : public Space { public: Snake(int id) : Space(id) {} virtual void event(Player&amp; p) { std::cout &lt;&lt; "Mumba Mia!" &lt;&lt; '\n'; p.set_current_space(4); } std::string class_type() { return "Snake"; } }; class Board { private: std::map&lt;int, std::shared_ptr&lt;Space&gt;&gt; m_board; public: void add_space(std::shared_ptr&lt;Space&gt; s) { m_board[s-&gt;get_id()] = s; } void draw_board(int position) { int i = 1; std::string line = "\n"; for(auto const&amp; space : m_board) { if(i%3 == 0) { line = "\n"; } else { line = " "; } if (space.first == position) { std::cout &lt;&lt; "●" + line; } else if(space.second-&gt;class_type() == "Snake" || space.second-&gt;class_type() == "Ladder") { std::cout &lt;&lt; "\x1B[32m○\033[0m" + line; } else { std::cout &lt;&lt; "○" + line; } ++i; } } const std::map&lt;int, std::shared_ptr&lt;Space&gt;&gt; get_board() { return m_board; } friend std::ostream &amp;operator&lt;&lt;(std::ostream&amp; os, const Board&amp; b) { return os; } }; class GameStateManager { private: std::string m_state = "game over"; bool m_playing = false; public: std::string const get_state() { return m_state; } void set_state(std::string state) { m_state = state; } }; int main() { std::cout &lt;&lt; "Welcome to Bowser's 9 board game\n"; std::cout &lt;&lt; "Start? y(yes) n(no)\n"; char wants_to_play; std::cin &gt;&gt; wants_to_play; if (wants_to_play == 'y' || wants_to_play == 'Y') { GameStateManager game_manager; game_manager.set_state("playing"); std::cout &lt;&lt; "Let's a go!\nPress Enter to role.\n"; std::cin.get(); auto space1 = std::make_shared&lt;Empty&gt;(1); auto space2 = std::make_shared&lt;Empty&gt;(2); auto space3 = std::make_shared&lt;Ladder&gt;(3); auto space4 = std::make_shared&lt;Empty&gt;(4); auto space5 = std::make_shared&lt;Empty&gt;(5); auto space6 = std::make_shared&lt;Empty&gt;(6); auto space7 = std::make_shared&lt;Snake&gt;(7); auto space8 = std::make_shared&lt;Empty&gt;(8); auto space9 = std::make_shared&lt;Empty&gt;(9); std::vector&lt;std::shared_ptr&lt;Space&gt;&gt; spaces { space1, space2, space3, space4, space5, space6, space7, space8, space9 }; Board bowsers_bigbad_laddersnake; for(auto space : spaces) { bowsers_bigbad_laddersnake.add_space(space); } Player mario; bowsers_bigbad_laddersnake.draw_board(mario.get_current_space()); int turn = 0; while(game_manager.get_state() == "playing") { std::cin.get(); std::cout &lt;&lt; "-- Turn " &lt;&lt; ++turn &lt;&lt; " --" &lt;&lt; '\n'; mario.role_dice(); auto board = bowsers_bigbad_laddersnake.get_board(); std::shared_ptr&lt;Space&gt; s = board[mario.get_current_space()]; s-&gt;event(mario); bowsers_bigbad_laddersnake.draw_board(mario.get_current_space()); std::cout &lt;&lt; mario.get_current_space() &lt;&lt; '\n'; if (mario.get_current_space() &gt;= 9) { game_manager.set_state("game over"); } } std::cout &lt;&lt; "Thanks a so much for to playing!\nPress any key to continue . . .\n"; std::cin.get(); } else if (wants_to_play == 'n' || wants_to_play == 'N') { std::cout &lt;&lt; "Thanks a so much for to playing!\nPress any key to continue . . .\n"; std::cin.get(); } return 0; } </code></pre>
[]
[ { "body": "<p>When you roll the die (not role), the result is one of:</p>\n\n<pre><code>0 1 2 3 4 5 6 7 8 9 rand() % 10\n1 2 3 4 5 6 7 8 9 10 + 1\n0 0 1 1 1 2 2 2 3 3 / 3\n</code></pre>\n\n<p>Rolling a 0 is not fun. Whenever I roll the die, something should happen.</p>\n\n<hr>\n\n<p>When I read the code from top to bottom, I wondered what the magic number 9 had to do with the player. Further down in the code I learned that the board is restricted to 9 spaces. This number 9 should not appear in the <code>Player</code> class, but only in the <code>Board</code> class. And even the it should not be the literal 9, but <code>spaces.size()</code>.</p>\n\n<hr>\n\n<p>In <code>draw_board</code> it is inconsistent to write the escape code once as <code>\\x1B</code> and once as <code>\\033</code>. As a benefit for the readers who don't know the color table by heart, you should explain what these color codes do:</p>\n\n<pre><code>std::string green = \"\\x1B[32m\";\nstd::string normal = \"\\x1B[0m\";\n\nstd::cout &lt;&lt; green &lt;&lt; \"○\" &lt;&lt; normal &lt;&lt; \"\\n\";\n</code></pre>\n\n<hr>\n\n<p>I don't understand the initial question \"do you want to play\"? — of course I want, otherwise I wouldn't have started the game at all.</p>\n\n<hr>\n\n<p>Why did you choose the really long variable name for the board, why not just <code>Board board</code>? As it is written now, the variable name draws too much attention.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-23T14:43:09.370", "Id": "421845", "Score": "0", "body": ">Rolling a 0 is not fun" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-23T20:46:53.980", "Id": "421918", "Score": "0", "body": "For your `normal` color string why are you using `std::string normal = \"\\x1B[0m\";\n` instead of `\\033[0m\"`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-23T22:27:00.603", "Id": "421926", "Score": "0", "body": "Also fixed the rolling and add all of the other feedback here https://leetcode.com/discuss/interview-question/system-design/159188/Design-a-snake-and-ladders-games. This was a fun exercise!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-23T22:32:22.560", "Id": "421928", "Score": "1", "body": "@greg I'm using `\\x1B` instead of `033` because I don't like octal numbers. They are a thing of the 1970s and I don't want to promote them. I'd even prefer them to be banned from programming languages as far as possible. (Probably I'm not involved enough in embedded or microcontrollers or retro computing to appreciate their value.) It's mainly a personal choice." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-24T07:40:17.557", "Id": "422948", "Score": "0", "body": "Thanks for that clarity, I hadn't realized how dated this format is. I agree, I prefer to support more modern practices like your number syntax." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-24T16:14:51.660", "Id": "423035", "Score": "1", "body": "@greg the main annoyance about octal numbers is that in several programming languages the integer literal `0100` does not mean one hundred but instead sixty-four. This is so surprising that probably every programmer wonders what is wrong with their code. That's unnecessary. If octal literals were written as `0o100` instead, I would not be opposed to them since one does not accidentally type that." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-22T23:52:32.603", "Id": "217916", "ParentId": "217910", "Score": "2" } }, { "body": "<ul>\n<li><p>This has been raised in many of your reviews, but let me repeat: <em>make member functions that don't modify object contents const</em>. This improves readability and advocates correctness. (One example is <code>get_board()</code>, but there are plenty more).</p></li>\n<li><p>Don't pass expensive objects (like <code>std::string</code>) by value unless you have to. A better idea is to pass them by const-ref (e.g., <code>const std::string&amp; state</code>).</p></li>\n<li><p>A member function like <code>class_type()</code> is a <strong>bad idea</strong>. Don't do this, it only breaks abstraction. As it stands, someone queries the objects for their type and does an action (= drawing) accordingly. Instead, make every object know how it should be drawn. For example, drop the <code>class_type()</code> function and replace it with something like <code>std::string draw()</code> that returns whatever is correct. Then your board just implements the logic of \"for every object o, call o.draw()\" and your code is greatly simplified.</p></li>\n<li><p>It seems that <code>GameStateManager</code> is completely useless. You can replace it with a boolean in the main program and simplify your program.</p></li>\n<li><p>Consider using <code>const</code> or <code>constexpr</code> values for all the colors and other strings you are printing.</p></li>\n<li><p>The declaration of <code>space1</code> through <code>space9</code> is questionable. In fact, whenever you feel like writing something like that, you should start questioning yourself and think what the better alternative is. In this case, there's no need to name these variables. You can directly initialize the vector by constructing the objects in-place in a constructor call.</p></li>\n<li><p>Is there a reason the Board object must be copied inside the main program on the line <code>auto board = bowsers_bigbad_laddersnake.get_board();</code>?</p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-23T20:51:18.970", "Id": "421920", "Score": "0", "body": "Love the optimization to have the classes manage how they draw/render themselves on board when board calls its draw method. Is there a proper way to determine the class type of a derived class other than the hard coded names I implemented in `class_type()`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-24T07:08:28.720", "Id": "422945", "Score": "0", "body": "@greg dynamic_cast, but you should try not to find out the types." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-23T07:39:29.820", "Id": "217930", "ParentId": "217910", "Score": "3" } } ]
{ "AcceptedAnswerId": "217930", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-22T21:18:37.633", "Id": "217910", "Score": "3", "Tags": [ "c++", "c++11", "pointers", "interface" ], "Title": "Mario Party Snake and Ladders Board" }
217910
<p>The code below is a "World" class method that initializes a Q-Table for use in the SARSA and Q-Learning algorithms.</p> <p>Without going into too much detail, the world has "Pickups" and "Dropoffs" that can become invalid after they are emptied/filled. Termination is achieved once all pickups are emptied and all dropoffs filled. The state space I designed is essentially (y, x, z, i_0...i_n) where</p> <ul> <li><em>(y, x)</em> are node coordinates</li> <li><em>z</em> is whether the agent is carrying a block</li> <li><em>i</em> is context depended on <em>z</em>. It will represent the number pickups or dropoffs depending on whether the agent is carrying or not. It was built this way to allow for any number or combination of pickups and dropoffs, and to allow the learning algorithms to know a pickup or location is no longer attractive after it's invalid.</li> </ul> <p><strong>Main Concerns:</strong></p> <ol> <li>Whether there is a better way to organize the data then a dictionary of dictionaries of dictionaries. This was chosen because of the very fast lookup time of hashmaps.</li> <li>Whether there is a way to create the state space without having to do any deep copies. Here, I have to do a copy to get the actions dictionary. <code>sub_dict[key] = actions.copy()</code></li> <li>Are there any ways to reduce my state space in order to have fewer total states? The goal is for flexibility with the number of pickup and dropoff points.</li> </ol> <p><strong>Code Overview:</strong></p> <p>I have a Q-Table initialization method which is called from inside my <code>get_q_node_table()</code> method if the table hasn't been initialized.</p> <pre><code>def _initialize_table(self): def add_dict(sub_dict: dict, length: int, actions: dict) -&gt; dict: if length == 0: for key in sub_dict: sub_dict[key] = actions.copy() return sub_dict for key in sub_dict: sub_dict[key] = {True: {}, False: {}} add_dict(sub_dict[key], length-1, actions) self.qtable = {} for node in self.nodes: node_actions = self.nodes[node].get_actions() actions = {} for action in node_actions: # We don't want q-values for the pickup and dropoff actions, as those are always taken. # We only want q values for cardinal directions. if action not in ["Pickup", "Dropoff"]: actions[action] = INITIAL_Q_VALUE dropoff = {True: {}, False: {}} add_dict(dropoff, len(self.dropoffs)-1, actions) pickup = {True: {}, False: {}} add_dict(pickup, len(self.pickups)-1, actions) self.qtable[node] = {True: dropoff, False: pickup} </code></pre> <p>For this code <code>self.nodes</code> is a dictionary of Node classes, where the keys are coordinates.</p> <p><code>self.node[node]</code> provides a Node object.</p> <p><code>get_actions()</code> returns a dictionary of valid actions that can be taken from that node. The keys are string actions, and the values are coordinates to the neighbor node.</p> <p><code>self.qtable</code> is empty <code>{}</code> prior to being built in this method.</p> <p>I don't know if it helps at all, but here is the output once the Q-Table has been fully initialized.</p> <pre><code>{(1, 1): {False: {False: {False: {False: {'Down': 0, 'Right': 0}, True: {'Down': 0, 'Right': 0}}, True: {False: {'Down': 0, 'Right': 0}, True: {'Down': 0, 'Right': 0}}}, True: {False: {False: {'Down': 0, 'Right': 0}, True: {'Down': 0, 'Right': 0}}, True: {False: {'Down': 0, 'Right': 0}, True: {'Down': 0, 'Right': 0}}}}, True: {False: {False: {False: {'Down': 0, 'Right': 0}, True: {'Down': 0, 'Right': 0}}, True: {False: {'Down': 0, 'Right': 0}, True: {'Down': 0, 'Right': 0}}}, True: {False: {False: {'Down': 0, 'Right': 0}, True: {'Down': 0, 'Right': 0}}, True: {False: {'Down': 0, 'Right': 0}, True: {'Down': 0, 'Right': 0}}}}}, (1, 2): {False: {False: {False: {False: {'Down': 0, 'Left': 0, 'Right': 0}, True: {'Down': 0, 'Left': 0, 'Right': 0}}, True: {False: {'Down': 0, 'Left': 0, 'Right': 0}, True: {'Down': 0, 'Left': 0, 'Right': 0}}}, True: {False: {False: {'Down': 0, 'Left': 0, 'Right': 0}, True: {'Down': 0, 'Left': 0, 'Right': 0}}, True: {False: {'Down': 0, 'Left': 0, 'Right': 0}, True: {'Down': 0, 'Left': 0, 'Right': 0}}}}, True: {False: {False: {False: {'Down': 0, 'Left': 0, 'Right': 0}, True: {'Down': 0, 'Left': 0, 'Right': 0}}, True: {False: {'Down': 0, 'Left': 0, 'Right': 0}, True: {'Down': 0, 'Left': 0, 'Right': 0}}}, True: {False: {False: {'Down': 0, 'Left': 0, 'Right': 0}, True: {'Down': 0, 'Left': 0, 'Right': 0}}, True: {False: {'Down': 0, 'Left': 0, 'Right': 0}, True: {'Down': 0, 'Left': 0, 'Right': 0}}}}}, (1, 3): {False: {False: {False: {False: {'Down': 0, 'Left': 0, 'Right': 0}, True: {'Down': 0, 'Left': 0, 'Right': 0}}, True: {False: {'Down': 0, 'Left': 0, 'Right': 0}, True: {'Down': 0, 'Left': 0, 'Right': 0}}}, True: {False: {False: {'Down': 0, 'Left': 0, 'Right': 0}, True: {'Down': 0, 'Left': 0, 'Right': 0}}, True: {False: {'Down': 0, 'Left': 0, 'Right': 0}, True: {'Down': 0, 'Left': 0, 'Right': 0}}}}, True: {False: {False: {False: {'Down': 0, 'Left': 0, 'Right': 0}, True: {'Down': 0, 'Left': 0, 'Right': 0}}, True: {False: {'Down': 0, 'Left': 0, 'Right': 0}, True: {'Down': 0, 'Left': 0, 'Right': 0}}}, True: {False: {False: {'Down': 0, 'Left': 0, 'Right': 0}, True: {'Down': 0, 'Left': 0, 'Right': 0}}, True: {False: {'Down': 0, 'Left': 0, 'Right': 0}, True: {'Down': 0, 'Left': 0, 'Right': 0}}}}}, (1, 4): {False: {False: {False: {False: {'Down': 0, 'Left': 0, 'Right': 0}, True: {'Down': 0, 'Left': 0, 'Right': 0}}, True: {False: {'Down': 0, 'Left': 0, 'Right': 0}, True: {'Down': 0, 'Left': 0, 'Right': 0}}}, True: {False: {False: {'Down': 0, 'Left': 0, 'Right': 0}, True: {'Down': 0, 'Left': 0, 'Right': 0}}, True: {False: {'Down': 0, 'Left': 0, 'Right': 0}, True: {'Down': 0, 'Left': 0, 'Right': 0}}}}, True: {False: {False: {False: {'Down': 0, 'Left': 0, 'Right': 0}, True: {'Down': 0, 'Left': 0, 'Right': 0}}, True: {False: {'Down': 0, 'Left': 0, 'Right': 0}, True: {'Down': 0, 'Left': 0, 'Right': 0}}}, True: {False: {False: {'Down': 0, 'Left': 0, 'Right': 0}, True: {'Down': 0, 'Left': 0, 'Right': 0}}, True: {False: {'Down': 0, 'Left': 0, 'Right': 0}, True: {'Down': 0, 'Left': 0, 'Right': 0}}}}}, (1, 5): {False: {False: {False: {False: {'Down': 0, 'Left': 0}, True: {'Down': 0, 'Left': 0}}, True: {False: {'Down': 0, 'Left': 0}, True: {'Down': 0, 'Left': 0}}}, True: {False: {False: {'Down': 0, 'Left': 0}, True: {'Down': 0, 'Left': 0}}, True: {False: {'Down': 0, 'Left': 0}, True: {'Down': 0, 'Left': 0}}}}, True: {False: {False: {False: {'Down': 0, 'Left': 0}, True: {'Down': 0, 'Left': 0}}, True: {False: {'Down': 0, 'Left': 0}, True: {'Down': 0, 'Left': 0}}}, True: {False: {False: {'Down': 0, 'Left': 0}, True: {'Down': 0, 'Left': 0}}, True: {False: {'Down': 0, 'Left': 0}, True: {'Down': 0, 'Left': 0}}}}}, (2, 1): {False: {False: {False: {False: {'Down': 0, 'Right': 0, 'Up': 0}, True: {'Down': 0, 'Right': 0, 'Up': 0}}, True: {False: {'Down': 0, 'Right': 0, 'Up': 0}, True: {'Down': 0, 'Right': 0, 'Up': 0}}}, True: {False: {False: {'Down': 0, 'Right': 0, 'Up': 0}, True: {'Down': 0, 'Right': 0, 'Up': 0}}, True: {False: {'Down': 0, 'Right': 0, 'Up': 0}, True: {'Down': 0, 'Right': 0, 'Up': 0}}}}, True: {False: {False: {False: {'Down': 0, 'Right': 0, 'Up': 0}, True: {'Down': 0, 'Right': 0, 'Up': 0}}, True: {False: {'Down': 0, 'Right': 0, 'Up': 0}, True: {'Down': 0, 'Right': 0, 'Up': 0}}}, True: {False: {False: {'Down': 0, 'Right': 0, 'Up': 0}, True: {'Down': 0, 'Right': 0, 'Up': 0}}, True: {False: {'Down': 0, 'Right': 0, 'Up': 0}, True: {'Down': 0, 'Right': 0, 'Up': 0}}}}}, (2, 2): {False: {False: {False: {False: {'Down': 0, 'Left': 0, 'Right': 0, 'Up': 0}, True: {'Down': 0, 'Left': 0, 'Right': 0, 'Up': 0}}, True: {False: {'Down': 0, 'Left': 0, 'Right': 0, 'Up': 0}, True: {'Down': 0, 'Left': 0, 'Right': 0, 'Up': 0}}}, True: {False: {False: {'Down': 0, 'Left': 0, 'Right': 0, 'Up': 0}, True: {'Down': 0, 'Left': 0, 'Right': 0, 'Up': 0}}, True: {False: {'Down': 0, 'Left': 0, 'Right': 0, 'Up': 0}, True: {'Down': 0, 'Left': 0, 'Right': 0, 'Up': 0}}}}, True: {False: {False: {False: {'Down': 0, 'Left': 0, 'Right': 0, 'Up': 0}, True: {'Down': 0, 'Left': 0, 'Right': 0, 'Up': 0}}, True: {False: {'Down': 0, 'Left': 0, 'Right': 0, 'Up': 0}, True: {'Down': 0, 'Left': 0, 'Right': 0, 'Up': 0}}}, True: {False: {False: {'Down': 0, 'Left': 0, 'Right': 0, 'Up': 0}, True: {'Down': 0, 'Left': 0, 'Right': 0, 'Up': 0}}, True: {False: {'Down': 0, 'Left': 0, 'Right': 0, 'Up': 0}, True: {'Down': 0, 'Left': 0, 'Right': 0, 'Up': 0}}}}}, (2, 3): {False: {False: {False: {False: {'Down': 0, 'Left': 0, 'Right': 0, 'Up': 0}, True: {'Down': 0, 'Left': 0, 'Right': 0, 'Up': 0}}, True: {False: {'Down': 0, 'Left': 0, 'Right': 0, 'Up': 0}, True: {'Down': 0, 'Left': 0, 'Right': 0, 'Up': 0}}}, True: {False: {False: {'Down': 0, 'Left': 0, 'Right': 0, 'Up': 0}, True: {'Down': 0, 'Left': 0, 'Right': 0, 'Up': 0}}, True: {False: {'Down': 0, 'Left': 0, 'Right': 0, 'Up': 0}, True: {'Down': 0, 'Left': 0, 'Right': 0, 'Up': 0}}}}, True: {False: {False: {False: {'Down': 0, 'Left': 0, 'Right': 0, 'Up': 0}, True: {'Down': 0, 'Left': 0, 'Right': 0, 'Up': 0}}, True: {False: {'Down': 0, 'Left': 0, 'Right': 0, 'Up': 0}, True: {'Down': 0, 'Left': 0, 'Right': 0, 'Up': 0}}}, True: {False: {False: {'Down': 0, 'Left': 0, 'Right': 0, 'Up': 0}, True: {'Down': 0, 'Left': 0, 'Right': 0, 'Up': 0}}, True: {False: {'Down': 0, 'Left': 0, 'Right': 0, 'Up': 0}, True: {'Down': 0, 'Left': 0, 'Right': 0, 'Up': 0}}}}}, (2, 4): {False: {False: {False: {False: {'Down': 0, 'Left': 0, 'Right': 0, 'Up': 0}, True: {'Down': 0, 'Left': 0, 'Right': 0, 'Up': 0}}, True: {False: {'Down': 0, 'Left': 0, 'Right': 0, 'Up': 0}, True: {'Down': 0, 'Left': 0, 'Right': 0, 'Up': 0}}}, True: {False: {False: {'Down': 0, 'Left': 0, 'Right': 0, 'Up': 0}, True: {'Down': 0, 'Left': 0, 'Right': 0, 'Up': 0}}, True: {False: {'Down': 0, 'Left': 0, 'Right': 0, 'Up': 0}, True: {'Down': 0, 'Left': 0, 'Right': 0, 'Up': 0}}}}, True: {False: {False: {False: {'Down': 0, 'Left': 0, 'Right': 0, 'Up': 0}, True: {'Down': 0, 'Left': 0, 'Right': 0, 'Up': 0}}, True: {False: {'Down': 0, 'Left': 0, 'Right': 0, 'Up': 0}, True: {'Down': 0, 'Left': 0, 'Right': 0, 'Up': 0}}}, True: {False: {False: {'Down': 0, 'Left': 0, 'Right': 0, 'Up': 0}, True: {'Down': 0, 'Left': 0, 'Right': 0, 'Up': 0}}, True: {False: {'Down': 0, 'Left': 0, 'Right': 0, 'Up': 0}, True: {'Down': 0, 'Left': 0, 'Right': 0, 'Up': 0}}}}}, (2, 5): {False: {False: {False: {False: {'Down': 0, 'Left': 0, 'Up': 0}, True: {'Down': 0, 'Left': 0, 'Up': 0}}, True: {False: {'Down': 0, 'Left': 0, 'Up': 0}, True: {'Down': 0, 'Left': 0, 'Up': 0}}}, True: {False: {False: {'Down': 0, 'Left': 0, 'Up': 0}, True: {'Down': 0, 'Left': 0, 'Up': 0}}, True: {False: {'Down': 0, 'Left': 0, 'Up': 0}, True: {'Down': 0, 'Left': 0, 'Up': 0}}}}, True: {False: {False: {False: {'Down': 0, 'Left': 0, 'Up': 0}, True: {'Down': 0, 'Left': 0, 'Up': 0}}, True: {False: {'Down': 0, 'Left': 0, 'Up': 0}, True: {'Down': 0, 'Left': 0, 'Up': 0}}}, True: {False: {False: {'Down': 0, 'Left': 0, 'Up': 0}, True: {'Down': 0, 'Left': 0, 'Up': 0}}, True: {False: {'Down': 0, 'Left': 0, 'Up': 0}, True: {'Down': 0, 'Left': 0, 'Up': 0}}}}}, (3, 1): {False: {False: {False: {False: {'Down': 0, 'Right': 0, 'Up': 0}, True: {'Down': 0, 'Right': 0, 'Up': 0}}, True: {False: {'Down': 0, 'Right': 0, 'Up': 0}, True: {'Down': 0, 'Right': 0, 'Up': 0}}}, True: {False: {False: {'Down': 0, 'Right': 0, 'Up': 0}, True: {'Down': 0, 'Right': 0, 'Up': 0}}, True: {False: {'Down': 0, 'Right': 0, 'Up': 0}, True: {'Down': 0, 'Right': 0, 'Up': 0}}}}, True: {False: {False: {False: {'Down': 0, 'Right': 0, 'Up': 0}, True: {'Down': 0, 'Right': 0, 'Up': 0}}, True: {False: {'Down': 0, 'Right': 0, 'Up': 0}, True: {'Down': 0, 'Right': 0, 'Up': 0}}}, True: {False: {False: {'Down': 0, 'Right': 0, 'Up': 0}, True: {'Down': 0, 'Right': 0, 'Up': 0}}, True: {False: {'Down': 0, 'Right': 0, 'Up': 0}, True: {'Down': 0, 'Right': 0, 'Up': 0}}}}}, (3, 2): {False: {False: {False: {False: {'Down': 0, 'Left': 0, 'Right': 0, 'Up': 0}, True: {'Down': 0, 'Left': 0, 'Right': 0, 'Up': 0}}, True: {False: {'Down': 0, 'Left': 0, 'Right': 0, 'Up': 0}, True: {'Down': 0, 'Left': 0, 'Right': 0, 'Up': 0}}}, True: {False: {False: {'Down': 0, 'Left': 0, 'Right': 0, 'Up': 0}, True: {'Down': 0, 'Left': 0, 'Right': 0, 'Up': 0}}, True: {False: {'Down': 0, 'Left': 0, 'Right': 0, 'Up': 0}, True: {'Down': 0, 'Left': 0, 'Right': 0, 'Up': 0}}}}, True: {False: {False: {False: {'Down': 0, 'Left': 0, 'Right': 0, 'Up': 0}, True: {'Down': 0, 'Left': 0, 'Right': 0, 'Up': 0}}, True: {False: {'Down': 0, 'Left': 0, 'Right': 0, 'Up': 0}, True: {'Down': 0, 'Left': 0, 'Right': 0, 'Up': 0}}}, True: {False: {False: {'Down': 0, 'Left': 0, 'Right': 0, 'Up': 0}, True: {'Down': 0, 'Left': 0, 'Right': 0, 'Up': 0}}, True: {False: {'Down': 0, 'Left': 0, 'Right': 0, 'Up': 0}, True: {'Down': 0, 'Left': 0, 'Right': 0, 'Up': 0}}}}}, (3, 3): {False: {False: {False: {False: {'Down': 0, 'Left': 0, 'Right': 0, 'Up': 0}, True: {'Down': 0, 'Left': 0, 'Right': 0, 'Up': 0}}, True: {False: {'Down': 0, 'Left': 0, 'Right': 0, 'Up': 0}, True: {'Down': 0, 'Left': 0, 'Right': 0, 'Up': 0}}}, True: {False: {False: {'Down': 0, 'Left': 0, 'Right': 0, 'Up': 0}, True: {'Down': 0, 'Left': 0, 'Right': 0, 'Up': 0}}, True: {False: {'Down': 0, 'Left': 0, 'Right': 0, 'Up': 0}, True: {'Down': 0, 'Left': 0, 'Right': 0, 'Up': 0}}}}, True: {False: {False: {False: {'Down': 0, 'Left': 0, 'Right': 0, 'Up': 0}, True: {'Down': 0, 'Left': 0, 'Right': 0, 'Up': 0}}, True: {False: {'Down': 0, 'Left': 0, 'Right': 0, 'Up': 0}, True: {'Down': 0, 'Left': 0, 'Right': 0, 'Up': 0}}}, True: {False: {False: {'Down': 0, 'Left': 0, 'Right': 0, 'Up': 0}, True: {'Down': 0, 'Left': 0, 'Right': 0, 'Up': 0}}, True: {False: {'Down': 0, 'Left': 0, 'Right': 0, 'Up': 0}, True: {'Down': 0, 'Left': 0, 'Right': 0, 'Up': 0}}}}}, (3, 4): {False: {False: {False: {False: {'Down': 0, 'Left': 0, 'Right': 0, 'Up': 0}, True: {'Down': 0, 'Left': 0, 'Right': 0, 'Up': 0}}, True: {False: {'Down': 0, 'Left': 0, 'Right': 0, 'Up': 0}, True: {'Down': 0, 'Left': 0, 'Right': 0, 'Up': 0}}}, True: {False: {False: {'Down': 0, 'Left': 0, 'Right': 0, 'Up': 0}, True: {'Down': 0, 'Left': 0, 'Right': 0, 'Up': 0}}, True: {False: {'Down': 0, 'Left': 0, 'Right': 0, 'Up': 0}, True: {'Down': 0, 'Left': 0, 'Right': 0, 'Up': 0}}}}, True: {False: {False: {False: {'Down': 0, 'Left': 0, 'Right': 0, 'Up': 0}, True: {'Down': 0, 'Left': 0, 'Right': 0, 'Up': 0}}, True: {False: {'Down': 0, 'Left': 0, 'Right': 0, 'Up': 0}, True: {'Down': 0, 'Left': 0, 'Right': 0, 'Up': 0}}}, True: {False: {False: {'Down': 0, 'Left': 0, 'Right': 0, 'Up': 0}, True: {'Down': 0, 'Left': 0, 'Right': 0, 'Up': 0}}, True: {False: {'Down': 0, 'Left': 0, 'Right': 0, 'Up': 0}, True: {'Down': 0, 'Left': 0, 'Right': 0, 'Up': 0}}}}}, (3, 5): {False: {False: {False: {False: {'Down': 0, 'Left': 0, 'Up': 0}, True: {'Down': 0, 'Left': 0, 'Up': 0}}, True: {False: {'Down': 0, 'Left': 0, 'Up': 0}, True: {'Down': 0, 'Left': 0, 'Up': 0}}}, True: {False: {False: {'Down': 0, 'Left': 0, 'Up': 0}, True: {'Down': 0, 'Left': 0, 'Up': 0}}, True: {False: {'Down': 0, 'Left': 0, 'Up': 0}, True: {'Down': 0, 'Left': 0, 'Up': 0}}}}, True: {False: {False: {False: {'Down': 0, 'Left': 0, 'Up': 0}, True: {'Down': 0, 'Left': 0, 'Up': 0}}, True: {False: {'Down': 0, 'Left': 0, 'Up': 0}, True: {'Down': 0, 'Left': 0, 'Up': 0}}}, True: {False: {False: {'Down': 0, 'Left': 0, 'Up': 0}, True: {'Down': 0, 'Left': 0, 'Up': 0}}, True: {False: {'Down': 0, 'Left': 0, 'Up': 0}, True: {'Down': 0, 'Left': 0, 'Up': 0}}}}}, (4, 1): {False: {False: {False: {False: {'Down': 0, 'Right': 0, 'Up': 0}, True: {'Down': 0, 'Right': 0, 'Up': 0}}, True: {False: {'Down': 0, 'Right': 0, 'Up': 0}, True: {'Down': 0, 'Right': 0, 'Up': 0}}}, True: {False: {False: {'Down': 0, 'Right': 0, 'Up': 0}, True: {'Down': 0, 'Right': 0, 'Up': 0}}, True: {False: {'Down': 0, 'Right': 0, 'Up': 0}, True: {'Down': 0, 'Right': 0, 'Up': 0}}}}, True: {False: {False: {False: {'Down': 0, 'Right': 0, 'Up': 0}, True: {'Down': 0, 'Right': 0, 'Up': 0}}, True: {False: {'Down': 0, 'Right': 0, 'Up': 0}, True: {'Down': 0, 'Right': 0, 'Up': 0}}}, True: {False: {False: {'Down': 0, 'Right': 0, 'Up': 0}, True: {'Down': 0, 'Right': 0, 'Up': 0}}, True: {False: {'Down': 0, 'Right': 0, 'Up': 0}, True: {'Down': 0, 'Right': 0, 'Up': 0}}}}}, (4, 2): {False: {False: {False: {False: {'Down': 0, 'Left': 0, 'Right': 0, 'Up': 0}, True: {'Down': 0, 'Left': 0, 'Right': 0, 'Up': 0}}, True: {False: {'Down': 0, 'Left': 0, 'Right': 0, 'Up': 0}, True: {'Down': 0, 'Left': 0, 'Right': 0, 'Up': 0}}}, True: {False: {False: {'Down': 0, 'Left': 0, 'Right': 0, 'Up': 0}, True: {'Down': 0, 'Left': 0, 'Right': 0, 'Up': 0}}, True: {False: {'Down': 0, 'Left': 0, 'Right': 0, 'Up': 0}, True: {'Down': 0, 'Left': 0, 'Right': 0, 'Up': 0}}}}, True: {False: {False: {False: {'Down': 0, 'Left': 0, 'Right': 0, 'Up': 0}, True: {'Down': 0, 'Left': 0, 'Right': 0, 'Up': 0}}, True: {False: {'Down': 0, 'Left': 0, 'Right': 0, 'Up': 0}, True: {'Down': 0, 'Left': 0, 'Right': 0, 'Up': 0}}}, True: {False: {False: {'Down': 0, 'Left': 0, 'Right': 0, 'Up': 0}, True: {'Down': 0, 'Left': 0, 'Right': 0, 'Up': 0}}, True: {False: {'Down': 0, 'Left': 0, 'Right': 0, 'Up': 0}, True: {'Down': 0, 'Left': 0, 'Right': 0, 'Up': 0}}}}}, (4, 3): {False: {False: {False: {False: {'Down': 0, 'Left': 0, 'Right': 0, 'Up': 0}, True: {'Down': 0, 'Left': 0, 'Right': 0, 'Up': 0}}, True: {False: {'Down': 0, 'Left': 0, 'Right': 0, 'Up': 0}, True: {'Down': 0, 'Left': 0, 'Right': 0, 'Up': 0}}}, True: {False: {False: {'Down': 0, 'Left': 0, 'Right': 0, 'Up': 0}, True: {'Down': 0, 'Left': 0, 'Right': 0, 'Up': 0}}, True: {False: {'Down': 0, 'Left': 0, 'Right': 0, 'Up': 0}, True: {'Down': 0, 'Left': 0, 'Right': 0, 'Up': 0}}}}, True: {False: {False: {False: {'Down': 0, 'Left': 0, 'Right': 0, 'Up': 0}, True: {'Down': 0, 'Left': 0, 'Right': 0, 'Up': 0}}, True: {False: {'Down': 0, 'Left': 0, 'Right': 0, 'Up': 0}, True: {'Down': 0, 'Left': 0, 'Right': 0, 'Up': 0}}}, True: {False: {False: {'Down': 0, 'Left': 0, 'Right': 0, 'Up': 0}, True: {'Down': 0, 'Left': 0, 'Right': 0, 'Up': 0}}, True: {False: {'Down': 0, 'Left': 0, 'Right': 0, 'Up': 0}, True: {'Down': 0, 'Left': 0, 'Right': 0, 'Up': 0}}}}}, (4, 4): {False: {False: {False: {False: {'Down': 0, 'Left': 0, 'Right': 0, 'Up': 0}, True: {'Down': 0, 'Left': 0, 'Right': 0, 'Up': 0}}, True: {False: {'Down': 0, 'Left': 0, 'Right': 0, 'Up': 0}, True: {'Down': 0, 'Left': 0, 'Right': 0, 'Up': 0}}}, True: {False: {False: {'Down': 0, 'Left': 0, 'Right': 0, 'Up': 0}, True: {'Down': 0, 'Left': 0, 'Right': 0, 'Up': 0}}, True: {False: {'Down': 0, 'Left': 0, 'Right': 0, 'Up': 0}, True: {'Down': 0, 'Left': 0, 'Right': 0, 'Up': 0}}}}, True: {False: {False: {False: {'Down': 0, 'Left': 0, 'Right': 0, 'Up': 0}, True: {'Down': 0, 'Left': 0, 'Right': 0, 'Up': 0}}, True: {False: {'Down': 0, 'Left': 0, 'Right': 0, 'Up': 0}, True: {'Down': 0, 'Left': 0, 'Right': 0, 'Up': 0}}}, True: {False: {False: {'Down': 0, 'Left': 0, 'Right': 0, 'Up': 0}, True: {'Down': 0, 'Left': 0, 'Right': 0, 'Up': 0}}, True: {False: {'Down': 0, 'Left': 0, 'Right': 0, 'Up': 0}, True: {'Down': 0, 'Left': 0, 'Right': 0, 'Up': 0}}}}}, (4, 5): {False: {False: {False: {False: {'Down': 0, 'Left': 0, 'Up': 0}, True: {'Down': 0, 'Left': 0, 'Up': 0}}, True: {False: {'Down': 0, 'Left': 0, 'Up': 0}, True: {'Down': 0, 'Left': 0, 'Up': 0}}}, True: {False: {False: {'Down': 0, 'Left': 0, 'Up': 0}, True: {'Down': 0, 'Left': 0, 'Up': 0}}, True: {False: {'Down': 0, 'Left': 0, 'Up': 0}, True: {'Down': 0, 'Left': 0, 'Up': 0}}}}, True: {False: {False: {False: {'Down': 0, 'Left': 0, 'Up': 0}, True: {'Down': 0, 'Left': 0, 'Up': 0}}, True: {False: {'Down': 0, 'Left': 0, 'Up': 0}, True: {'Down': 0, 'Left': 0, 'Up': 0}}}, True: {False: {False: {'Down': 0, 'Left': 0, 'Up': 0}, True: {'Down': 0, 'Left': 0, 'Up': 0}}, True: {False: {'Down': 0, 'Left': 0, 'Up': 0}, True: {'Down': 0, 'Left': 0, 'Up': 0}}}}}, (5, 1): {False: {False: {False: {False: {'Right': 0, 'Up': 0}, True: {'Right': 0, 'Up': 0}}, True: {False: {'Right': 0, 'Up': 0}, True: {'Right': 0, 'Up': 0}}}, True: {False: {False: {'Right': 0, 'Up': 0}, True: {'Right': 0, 'Up': 0}}, True: {False: {'Right': 0, 'Up': 0}, True: {'Right': 0, 'Up': 0}}}}, True: {False: {False: {False: {'Right': 0, 'Up': 0}, True: {'Right': 0, 'Up': 0}}, True: {False: {'Right': 0, 'Up': 0}, True: {'Right': 0, 'Up': 0}}}, True: {False: {False: {'Right': 0, 'Up': 0}, True: {'Right': 0, 'Up': 0}}, True: {False: {'Right': 0, 'Up': 0}, True: {'Right': 0, 'Up': 0}}}}}, (5, 2): {False: {False: {False: {False: {'Left': 0, 'Right': 0, 'Up': 0}, True: {'Left': 0, 'Right': 0, 'Up': 0}}, True: {False: {'Left': 0, 'Right': 0, 'Up': 0}, True: {'Left': 0, 'Right': 0, 'Up': 0}}}, True: {False: {False: {'Left': 0, 'Right': 0, 'Up': 0}, True: {'Left': 0, 'Right': 0, 'Up': 0}}, True: {False: {'Left': 0, 'Right': 0, 'Up': 0}, True: {'Left': 0, 'Right': 0, 'Up': 0}}}}, True: {False: {False: {False: {'Left': 0, 'Right': 0, 'Up': 0}, True: {'Left': 0, 'Right': 0, 'Up': 0}}, True: {False: {'Left': 0, 'Right': 0, 'Up': 0}, True: {'Left': 0, 'Right': 0, 'Up': 0}}}, True: {False: {False: {'Left': 0, 'Right': 0, 'Up': 0}, True: {'Left': 0, 'Right': 0, 'Up': 0}}, True: {False: {'Left': 0, 'Right': 0, 'Up': 0}, True: {'Left': 0, 'Right': 0, 'Up': 0}}}}}, (5, 3): {False: {False: {False: {False: {'Left': 0, 'Right': 0, 'Up': 0}, True: {'Left': 0, 'Right': 0, 'Up': 0}}, True: {False: {'Left': 0, 'Right': 0, 'Up': 0}, True: {'Left': 0, 'Right': 0, 'Up': 0}}}, True: {False: {False: {'Left': 0, 'Right': 0, 'Up': 0}, True: {'Left': 0, 'Right': 0, 'Up': 0}}, True: {False: {'Left': 0, 'Right': 0, 'Up': 0}, True: {'Left': 0, 'Right': 0, 'Up': 0}}}}, True: {False: {False: {False: {'Left': 0, 'Right': 0, 'Up': 0}, True: {'Left': 0, 'Right': 0, 'Up': 0}}, True: {False: {'Left': 0, 'Right': 0, 'Up': 0}, True: {'Left': 0, 'Right': 0, 'Up': 0}}}, True: {False: {False: {'Left': 0, 'Right': 0, 'Up': 0}, True: {'Left': 0, 'Right': 0, 'Up': 0}}, True: {False: {'Left': 0, 'Right': 0, 'Up': 0}, True: {'Left': 0, 'Right': 0, 'Up': 0}}}}}, (5, 4): {False: {False: {False: {False: {'Left': 0, 'Right': 0, 'Up': 0}, True: {'Left': 0, 'Right': 0, 'Up': 0}}, True: {False: {'Left': 0, 'Right': 0, 'Up': 0}, True: {'Left': 0, 'Right': 0, 'Up': 0}}}, True: {False: {False: {'Left': 0, 'Right': 0, 'Up': 0}, True: {'Left': 0, 'Right': 0, 'Up': 0}}, True: {False: {'Left': 0, 'Right': 0, 'Up': 0}, True: {'Left': 0, 'Right': 0, 'Up': 0}}}}, True: {False: {False: {False: {'Left': 0, 'Right': 0, 'Up': 0}, True: {'Left': 0, 'Right': 0, 'Up': 0}}, True: {False: {'Left': 0, 'Right': 0, 'Up': 0}, True: {'Left': 0, 'Right': 0, 'Up': 0}}}, True: {False: {False: {'Left': 0, 'Right': 0, 'Up': 0}, True: {'Left': 0, 'Right': 0, 'Up': 0}}, True: {False: {'Left': 0, 'Right': 0, 'Up': 0}, True: {'Left': 0, 'Right': 0, 'Up': 0}}}}}, (5, 5): {False: {False: {False: {False: {'Left': 0, 'Up': 0}, True: {'Left': 0, 'Up': 0}}, True: {False: {'Left': 0, 'Up': 0}, True: {'Left': 0, 'Up': 0}}}, True: {False: {False: {'Left': 0, 'Up': 0}, True: {'Left': 0, 'Up': 0}}, True: {False: {'Left': 0, 'Up': 0}, True: {'Left': 0, 'Up': 0}}}}, True: {False: {False: {False: {'Left': 0, 'Up': 0}, True: {'Left': 0, 'Up': 0}}, True: {False: {'Left': 0, 'Up': 0}, True: {'Left': 0, 'Up': 0}}}, True: {False: {False: {'Left': 0, 'Up': 0}, True: {'Left': 0, 'Up': 0}}, True: {False: {'Left': 0, 'Up': 0}, True: {'Left': 0, 'Up': 0}}}}}} </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-25T22:39:25.877", "Id": "423258", "Score": "0", "body": "Did I write a bad question? I can add whatever is needed if I did." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-22T21:58:25.370", "Id": "217912", "Score": "2", "Tags": [ "python", "ai", "memory-optimization" ], "Title": "Initializing Reinforcement Learning Q-Table State Space-Python" }
217912
<p>I'm trying to come up with a unit testing framework for Haskell that is</p> <ul> <li>small and self-contained</li> <li>produces TAP-compatible output</li> <li>exits abnormally on failure (instead of relying on the TAP consumer to validate all the output).</li> <li>has a simple API with easy to understand compile-time errors. (That's the motivation for committing to concrete types in the interface).</li> </ul> <p>With that in mind, this is what I came up with:</p> <p>I'm mainly looking for things that</p> <ul> <li>are not idiomatic Haskell</li> <li>would hamper usability in very small to small projects in The Real World.</li> </ul> <hr> <pre><code>module TestTrivial ( tests ) where import System.Exit (exitSuccess, exitFailure) testsImpl :: [(Bool, String)] -&gt; Int -&gt; Bool -&gt; IO () testsImpl [] nextTest status = putStrLn ("1.." ++ show (nextTest - 1)) &lt;&gt; doExit where doExit = if status then exitSuccess else exitFailure testsImpl ((cond, msg):xs) nextTest success = putStrLn msg' &lt;&gt; rest where ok = if cond then "ok" else "not ok" num = show nextTest f [] = unwords [ok, num] f m = unwords [ok, num, "-", msg] msg' = f msg rest = testsImpl xs (nextTest + 1) (success &amp;&amp; cond) tests :: [(Bool, String)] -&gt; IO () tests xs = testsImpl xs 1 True </code></pre> <p>And here's an example test suite using this library.</p> <pre><code>module TestAdd where import TestTrivial main = tests [ (1 + 4 == 5, "1 + 4 == 5") , (5 + 6 /= 7, "5 + 6 /= 7") ] </code></pre> <p>And what it produces. ... Despite the <code>-</code> sign separating the test number from the message and how strange that looks here, the output is formatted correctly.</p> <pre><code>ok 1 - 1 + 4 == 5 ok 2 - 5 + 6 /= 7 1..2 </code></pre>
[]
[ { "body": "<p>Replace explicit recursion with library combinators. Unduplicate and inline as much as possible.</p>\n\n<pre><code>testImpl :: Int -&gt; (Bool, String) -&gt; String \ntestImpl i (cond, msg) = unwords $\n [ if cond then \"ok\" else \"not ok\"\n , show i\n ] ++ case msg of [] -&gt; []; m -&gt; [\"-\", m]\n\ntests :: [(Bool, String)] -&gt; IO ()\ntests xs = do\n putStrLn $ unlines $ zipWith testImpl [1..] xs\n putStrLn $ \"1..\" ++ show (length xs)\n if all fst xs then exitSuccess else exitFailure\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-23T12:46:26.447", "Id": "217956", "ParentId": "217914", "Score": "2" } } ]
{ "AcceptedAnswerId": "217956", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-22T23:43:10.043", "Id": "217914", "Score": "2", "Tags": [ "haskell", "unit-testing" ], "Title": "Minimal Haskell Unit Testing Framework" }
217914
<p>I am working on an easy LinkedList basic operation problem on <a href="https://leetcode.com/problems/remove-linked-list-elements/" rel="nofollow noreferrer">Remove Linked List Elements - LeetCode</a></p> <blockquote> <ol start="203"> <li>Remove Linked List Elements</li> </ol> <p>Remove all elements from a linked list of integers that have value <strong>val</strong>.</p> <p><strong>Example:</strong></p> <pre><code>Input: 1-&gt;2-&gt;6-&gt;3-&gt;4-&gt;5-&gt;6, val = 6 Output: 1-&gt;2-&gt;3-&gt;4-&gt;5 </code></pre> </blockquote> <p>My solution:</p> <blockquote> <p>The 3 nodes: prev_node(prev), current_node(cur), next_node(nxt)</p> <p>change <code>prev.next</code> from current_node to next_node</p> <p>prev</p> <p>cur = prev.next </p> <p>nxt = prev.next.next </p> </blockquote> <pre class="lang-py prettyprint-override"><code># Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def removeElements(self, head: ListNode, val: int) -&gt; ListNode: #relation: prev.next = nxt to replace cur prev = head if prev == None: return head if prev.next == None: #cur == None: if prev.next.val == 6: prev.next = None return head while prev.next != None: #cur !=None if prev.next.val == 6: #if cur.val == 6 nxt = prev.next.next prev.next = nxt prev = prev.next #advance to traverse return head </code></pre> <p>The solution:</p> <pre><code>class Solution: def removeElements(self, head: ListNode, val: int) -&gt; ListNode: #relation: prev.next = nxt to replace cur dummy = prev = ListNode(0) prev.next = head while prev != None and prev.next != None: #cur !=None if prev.next.val == val: #if cur.val == val nxt = prev.next.next prev.next = nxt else: prev = prev.next #advance to traverse return dummy.next </code></pre> <p>However, it reported <code>Time Limit Exceeded</code>Error.</p> <p>I assume that problem is not performance but mistakes in my implementation which I don't find.</p> <p>What's the problem?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-23T00:56:00.127", "Id": "421726", "Score": "3", "body": "I believe that your solution is actually incorrect, not just slow." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-23T01:02:46.233", "Id": "421727", "Score": "0", "body": "thank you.I find the problem. I am surprised than you are so responsible to read almost every post. @200_success. Thank you." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-22T23:43:44.620", "Id": "217915", "Score": "1", "Tags": [ "python", "programming-challenge", "linked-list", "time-limit-exceeded" ], "Title": "TLE error: Remove element from LinkedList" }
217915
<p><strong>Full code is here:</strong> <a href="https://github.com/LionelBergen/LeagueReddit" rel="nofollow noreferrer">https://github.com/LionelBergen/LeagueReddit</a></p> <p>I'm creating a wrapper for the LeagueAPI in Node.js.</p> <p>This includes methods to call various endpoints and classes to map the outputs &amp; inputs.</p> <p>'Champion' class is Integer mapped to a name. (output from endpoints)</p> <p><strong>Champion.js</strong></p> <pre><code>const Champion = { 266 : 'AATROX', 103 : 'AHRI', 84 : 'AKALI', 12 : 'ALISTAR' } module.exports = Champion; </code></pre> <p>'LeagueAccountInfo' contains data returned from an endpoint method.</p> <p><strong>LeagueAccountInfo.js</strong></p> <pre><code>class LeagueAccountInfo { constructor(id, accountId, puuid, name, profileIconId, summonerLevel) { this.id = id; this.accountId = accountId; this.puuid = puuid; this.name = name; this.profileIconId = profileIconId; this.summonerLevel = summonerLevel; } static from(json) { return Object.assign(new LeagueAccountInfo(), json); } } module.exports = LeagueAccountInfo; </code></pre> <p>Here is the main class:</p> <p><strong>LeagueAPI.js</strong></p> <pre><code>require('./classes'); const https = require('https'); // Riot specifies this as a sample regexp to validate names // any visible Unicode letter characters, digits (0-9), spaces, underscores, and periods. const NAME_REGEXP = new RegExp('^[0-9\\p{L} _\\.]+$'); const GET_SUMMONER_BY_NAME_URL = 'https://%region%.api.riotgames.com/lol/summoner/v4/summoners/by-name/%name%?api_key=%apikey%'; const GET_CHAMPION_MASTERY_URL = 'https://%region%.api.riotgames.com/lol/champion-mastery/v4/champion-masteries/by-summoner/%name%?api_key=%apikey%'; const GET_CHAMPION_ROTATION_URL = 'https://%region%.api.riotgames.com/lol/platform/v3/champion-rotations?api_key=%apikey%'; const GET_QUEUES_WITH_RANKS_URL = 'https://%region%.api.riotgames.com/lol/league/v4/positional-rank-queues?api_key=%apikey%'; const GET_STATUS_URL = 'https://%region%.api.riotgames.com/lol/status/v3/shard-data?api_key=%apikey%'; const GET_ACTIVE_GAME_URL = 'https://%region%.api.riotgames.com/lol/spectator/v4/active-games/by-summoner/%name%?api_key=%apikey%'; const GET_MATCHLIST_URL = 'https://%region%.api.riotgames.com/lol/match/v4/matchlists/by-account/%accountid%?api_key=%apikey%' const GET_MATCH_URL = 'https://%region%.api.riotgames.com/lol/match/v4/matches/%matchid%?api_key=%apikey%'; class LeagueAPI { constructor(apiKey, region) { this.apiKey = apiKey; this.region = region; } changeRegion(region) { this.region = region; } getStatus(callback) { makeAnHTTPSCall(getURLStatus(this.apiKey, this.region), callback); } getMatch(matchId, callback) { makeAnHTTPSCall(getMatchURL(matchId, this.apiKey, this.region), callback); } getPositionalRankQueues(callback) { makeAnHTTPSCall(getURLQueuesWithRanks(this.apiKey, this.region), callback); } getSummonerByName(summonerName, callback) { makeAnHTTPSCall(getURLSummonerByName(summonerName, this.apiKey, this.region), function(data) { callback(LeagueAccountInfo.from(data)); }); } getActiveGames(accountObj, callback) { let summonerId = getSummonerIdFromParam(accountObj); makeAnHTTPSCall(getURLActiveGames(summonerId, this.apiKey, this.region), callback); } getMatchList(accountObj, callback) { let accountId = getAccountIdFromParam(accountObj); makeAnHTTPSCall(getURLMatchList(accountId, this.apiKey, this.region), callback); } getChampionMastery(accountObj, callback) { let summonerId = getSummonerIdFromParam(accountObj); makeAnHTTPSCall(getURLChampionMastery(summonerId, this.apiKey, this.region), function(data) { let championMasterObjects = []; for (var i=0; i &lt; data.length; i++) { championMasterObjects.push(ChampionMastery.from(data[i])); } callback(championMasterObjects); }); } getFreeChampionRotation(callback) { makeAnHTTPSCall(getURLChampRotation(this.apiKey, this.region), function(data) { callback(ChampionRotation.from(data)); }); } } function getSummonerIdFromParam(param) { summonerId = ''; if (param instanceof LeagueAccountInfo) { summonerId = param.id; } else if (param instanceof String) { summonerId = param; } else { throw 'invalid argument, requires summonerId or LeagueAccountInfo object'; } return summonerId; } function getAccountIdFromParam(param) { accountId = ''; if (param instanceof LeagueAccountInfo) { accountId = param.accountId; } else if (param instanceof String) { accountId = param; } else { throw 'invalid argument, requires accountId or LeagueAccountInfo object'; } return accountId; } function getMatchURL(matchId, apiKey, region) { return getURLWithRegionAndAPI(GET_MATCH_URL, apiKey, region).replace('%matchid%', matchId); } function getURLMatchList(summonerId, apiKey, region) { return getURLWithRegionAndAPI(GET_MATCHLIST_URL, apiKey, region).replace('%accountid%', summonerId); } function getURLActiveGames(summonerId, apiKey, region) { return getURLWithRegionAndAPI(GET_ACTIVE_GAME_URL, apiKey, region).replace('%name%', summonerId); } function getURLStatus(apiKey, region) { return getURLWithRegionAndAPI(GET_STATUS_URL, apiKey, region); } function getURLQueuesWithRanks(apiKey, region) { return getURLWithRegionAndAPI(GET_QUEUES_WITH_RANKS_URL, apiKey, region); } function getURLChampionMastery(summonerName, apiKey, region) { return getURLWithRegionAndAPI(GET_CHAMPION_MASTERY_URL, apiKey, region).replace('%name%', summonerName); } function getURLSummonerByName(summonerName, apiKey, region) { return getURLWithRegionAndAPI(GET_SUMMONER_BY_NAME_URL, apiKey, region).replace('%name%', summonerName); } function getURLChampRotation(apiKey, region) { return getURLWithRegionAndAPI(GET_CHAMPION_ROTATION_URL, apiKey, region); } // All endpoint URL's contain APIKey and Region function getURLWithRegionAndAPI(url, apiKey, region) { return url.replace('%apikey%', apiKey).replace('%region%', region); } function hasError(jsonData) { return jsonData.status ? true : false; } function makeAnHTTPSCall(URL, callback) { https.get(URL, (resp) =&gt; { let data = ''; // A chunk of data has been recieved. resp.on('data', (chunk) =&gt; { data += chunk; }); // The whole response has been received. resp.on('end', () =&gt; { let parsedData = JSON.parse(data); if (hasError(parsedData)) { console.log('failed: '); console.log(parsedData); } else { callback(parsedData); } }); // TODO: Errors are important, save to a database or Log file }).on("error", (err) =&gt; { console.log("Error: " + err.message); }); } module.exports = LeagueAPI; </code></pre> <p>I've created a folder with all the of mapping classes in one folder, with an index.js inside of it so I could import it via <code>require('./classes')</code>:</p> <pre><code>LeagueAccountInfo = require('./LeagueAccountInfo.js'); ChampionMastery = require('./ChampionMastery.js'); LeagueChampions = require('./Champion.js'); Region = require('./Region.js'); ChampionRotation = require('./ChampionRotation.js'); module.exports = {LeagueAccountInfo, LeagueChampions, ChampionMastery, ChampionRotation, Region} </code></pre> <p><strong>Note: Code is currently in a working state, but not finished. I plan to add the other endpoint methods &amp; classes after review.</strong></p>
[]
[ { "body": "<p>I've taken a look at other Node Code Reviews and done some research;</p>\n\n<p>Use Promises instead of Callbacks. This should be an easy change, just implement a Promise in the <code>makeAnHTTPSCall</code>mathod and remove all callbacks. </p>\n\n<p>This makes error handling easier and makes the code much easier to follow:</p>\n\n<pre><code>// Example usage after implementing Promises\nLeagueAPI.getSummonerByName().then(function(data) {\n return LeagueAPI.getMatchList(data);\n})\n.then(console.log)\n.catch(console.log);\n\n// Example method with Promise (makeAnHTTPSCall should also use Promise instead of callback)\ngetChampionMasteryByChampion(accountObj, championObj)\n{\n let summonerId = getSummonerIdFromParam(accountObj);\n let championId = getChampionIdFromParam(championObj);\n\n return new Promise(function(resolve, reject) {\n makeAnHTTPSCall(getURLChampionMasteryByChampion(summonerId, championId, this.apiKey, this.region))\n .then(function(data) {\n resolve(ChampionMastery.from(data));\n })\n .catch(reject);\n });\n}\n</code></pre>\n\n<p><code>Champion</code> was supposed to be used somewhat like an Enum. Currently for example <code>Champion.AATROX</code> would give an error, since '266' is the key, but <code>Champion.266</code> is invalid JS and doesn't really make sense anyway. Instead I've used Objects as the values:</p>\n\n<pre><code>const Champion =\n{\n AATROX: {value: 266, label: 'Aatrox' },\n AHRI: {value: 103, label: 'Ahri' },\n AKALI: {value: 84, label: 'Akali' },\n ALISTAR: {value: 12, label: 'Alistar' },\n findById(id)\n {\n return Object.values(this).find(champ =&gt; {return champ.value === id})\n }\n}\n</code></pre>\n\n<p>Now <code>Champion.AATROX</code> can be used as well as <code>Champion.findById(266)</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-29T18:10:37.543", "Id": "423778", "Score": "0", "body": "I'm marking this as an accepted answer, but am more than willing to mark a different/better answer if someone posts one" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-27T18:05:50.913", "Id": "219270", "ParentId": "217923", "Score": "3" } } ]
{ "AcceptedAnswerId": "219270", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-23T04:39:43.290", "Id": "217923", "Score": "1", "Tags": [ "javascript", "node.js", "wrapper" ], "Title": "Wrapper for LeagueAPI in Node.js" }
217923
<p>I wrote an authentication app for Django and my worry is primarily about the security of my app.</p> <p>My Django authentication app uses <code>exchangelib</code> to authenticate users against an Exchange server (configurable) so that they can use their Exchange (email) password rather than maintaining another username/password for this site. The project is located at <a href="https://github.com/gregschmit/django-auth-exchange/tree/6659fbcb3622b14d4ceaf53c6c19358fc1c35477" rel="nofollow noreferrer">https://github.com/gregschmit/django-auth-exchange</a>, but here is the relevant auth backend (<code>backends.py</code>):</p> <pre><code>from django.contrib.auth import get_user_model import exchangelib as el from .settings import get_setting try: from django_auth_exchange_organizations.models import DomainOrganization except (ModuleNotFoundError, NameError): DomainOrganization = False user_model = get_user_model() username_field = user_model.USERNAME_FIELD or 'username' class ExchangeAuthBackend: """ This authentication backend uses `exchangelib` to authenticate against the Exchange or Office365 server. By default, the `authenticate` method creates `User` objects for usernames that don't already exist in the database. Subclasses can disable this behavior by setting the `create_unknown_user` attribute to `False`. """ # Create a User object if not already in the database? create_unknown_user = get_setting('AUTH_EXCHANGE_CREATE_UNKNOWN_USER') def authenticate(self, request, username, password): """ Check for the format of the username (dom\\user vs user@dom), then authenticate, and if successful, get or create the user object and return it. """ username = username.lower() allowed_formats = get_setting('AUTH_EXCHANGE_ALLOWED_FORMATS') if '\\' in username: # assume dom\user if 'netbios' not in allowed_formats: return None netbios, user = username.rsplit('\\', 1) try: dom = get_setting('AUTH_EXCHANGE_NETBIOS_TO_DOMAIN_MAP')[netbios] except KeyError: dom = netbios smtp = '{0}@{1}'.format(user, dom) c_username = username elif '@' in username: # assume user@dom if 'email' not in allowed_formats: return None user, dom = username.rsplit('@', 1) smtp = username c_username = username else: # assume username only if 'username' not in allowed_formats: return None dom = get_setting('AUTH_EXCHANGE_DEFAULT_DOMAIN') user = username smtp = "{0}@{1}".format(user, dom) if not '.' in dom: c_username = "{0}\\{1}".format(dom, user) else: c_username = "{0}@{1}".format(user, dom) # check if domain is allowed domains = get_setting('AUTH_EXCHANGE_DOMAIN_SERVERS') if dom not in domains: return None # authenticate against Exchange server domain_server = domains.get(dom, 'autodiscover') or 'autodiscover' cred = el.Credentials(username=c_username, password=password) if domain_server == 'autodiscover': acc_opts = { 'primary_smtp_address': smtp, 'credentials': cred, 'autodiscover': True, 'access_type': el.DELEGATE } try: acc = el.Account(**acc_opts) except (el.errors.UnauthorizedError, el.errors.AutoDiscoverFailed): return None else: cfg_opts = { 'credentials': cred, 'server': domain_server, } try: cfg = el.Configuration(**cfg_opts) except (el.errors.UnauthorizedError, el.errors.AutoDiscoverFailed): return None acc_opts = { 'config': cfg, 'primary_smtp_address': smtp, 'credentials': cred, 'autodiscover': False, 'access_type': el.DELEGATE } try: acc = el.Account(**acc_opts) except (el.errors.UnauthorizedError, el.errors.AutoDiscoverFailed): return None if not acc: return None # auth successful, get or create local user try: u = user_model.objects.get(**{username_field: c_username}) except user_model.DoesNotExist: if self.create_unknown_user: u = user_model.objects.create(**{username_field: c_username}) if DomainOrganization: DomainOrganization.associate_new_user(u, dom) else: return None # enforce domain user properties, if they exist, and save user_properties = get_setting('AUTH_EXCHANGE_DOMAIN_USER_PROPERTIES').get(dom, {}) if user_properties: for k,v in user_properties.items(): setattr(u, k, v) if '.' in dom: setattr(u, u.get_email_field_name(), c_username) u.save() return u def get_user(self, user_id): try: return user_model.objects.get(pk=user_id) except user_model.DoesNotExist: return None </code></pre> <p>I've assumed that <code>exchangelib</code> authenticates in a secure fashion, but I don't know if that's true. This library is used for retrieving email so I figured that it wouldn't do anything crazy like send passwords out in cleartext, but I really don't know. Here are the relevant few lines:</p> <pre><code>try: acc = el.Account(**acc_opts) except (el.errors.UnauthorizedError, el.errors.AutoDiscoverFailed): return None </code></pre> <p>I would also appreciate any other feedback on the rest of the code.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-23T07:47:59.913", "Id": "421760", "Score": "0", "body": "Welcome to Code Review! I hope you'll get some great reviews!" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-23T06:13:18.737", "Id": "217925", "Score": "2", "Tags": [ "python", "security", "authentication", "django" ], "Title": "Django authentication against Exchange server" }
217925
<p>I have a table <code>leave_muster</code> inside which I have to update all the records of the previous month on every start of the new month. </p> <p><strong>My Code</strong></p> <pre><code>public function sync() { $pre_month = (int)date('m') - 1; $data = $this-&gt;Leave_muster_model-&gt;get_by_month($pre_month); $updated_data = []; foreach ($data as $key =&gt; $value) { // Fetch each employee details to perform some check // Then update the array and $updated_data[$key] = [ 'emp_id' =&gt; $value-&gt;emp_id, 'accumulated_leaves' =&gt; 0.0, 'total_accumulated_leaves' =&gt; 0.0, 'leave_taken' =&gt; 0.0, 'salary_deducted_days' =&gt; 0.0, 'leave_balance' =&gt; 0.0, 'month' =&gt; date('m'), 'year' =&gt; date('Y'), 'created_date' =&gt; date('Y-m-d') ]; } } } </code></pre> <p>In the above code, I have to fetch the employee details before updating the leaves to perform some checks, So I have two ways </p> <ol> <li>Fetch the employee details inside the loop before any update to perform checks. </li> <li>Fetch all the employee details outside the loop into an array then get the employee by employee id the perform checks</li> </ol> <p>I want to know which would be a better approach as I know that in any given point of time in the future there won't be any millions of employees in the table.</p> <p><strong>Lang: PHP <br/> Framework: Codeigniter</strong></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-23T08:48:37.093", "Id": "421779", "Score": "1", "body": "You are \"yatta-yatta\"ing with `perform some checks`. This very relevant information for us to know. If the checks can be articulated within SQL, then it would be possible (best practice) to perform the whole process with a single, non-iterated query. Additionally, this is a cronjob, right. Are you executing INSERT or UPDATE queries with the qualifying data? Is `$key` relevant in your code, I am guessing not." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-23T08:52:13.983", "Id": "421780", "Score": "0", "body": "@mickmackusa I cannot directly perform that checks with SQL queries, there are some calculations involved." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-23T08:52:59.797", "Id": "421781", "Score": "0", "body": "Are you able to explain that bit to us (as an edit to your question)? SQL can do calculations." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-13T21:44:16.093", "Id": "465172", "Score": "0", "body": "I am sure you've solved this already, but in case you have not. Not sure how many records you need to modify, but typically, I would've done a single query to retrieve all the data once off, and then loop through the data and do the checks that need to be done. When that is done, I will do the same loop you've done to set the new values, but not do the query inside the loop. I would rather use `update_batch()` once outside of the loop. See here: https://codeigniter.com/userguide3/database/query_builder.html" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-23T07:18:22.657", "Id": "217929", "Score": "1", "Tags": [ "php", "mysql", "codeigniter" ], "Title": "performing SQL SELECT query inside the loop" }
217929
<p>I recently decided that putting strategically placed <code>print</code> statements scattered about my python programs to debug was getting to be a little messy.</p> <p>I had thought to try out other debugging plugins I found online, but thought I would give writing my own <strong><em>simple</em></strong> breakpoint plugin a shot.</p> <p>I know of python's <code>pdb</code> module, but my goal was to minimize the amount that I had to type to debug my programs.</p> <p>Only a few keybinds are mapped:</p> <p>Normal mode:</p> <ul> <li><code>&lt;leader&gt;b</code> — Toggle breakpoint for the current line</li> <li><code>&lt;leader&gt;B</code> — Run debugger in a new tmux split</li> </ul> <p>Visual Mode:</p> <ul> <li><code>&lt;leader&gt;b</code> — Toggle breakpoint for the selected lines</li> </ul> <p>This has only been tested on Linux. The only requirement is <code>tmux</code></p> <pre class="lang-none prettyprint-override"><code>" Define breakpoint highlight color and mark in number column hi Breakpoint ctermfg=1 ctermbg=NONE sign define Breakpoint text=● texthl=Breakpoint " Map of lines that have breakpoints let b:breakpoints = {} function ToggleBreakpoint(lnum) let is_breakpoint = get(b:breakpoints, a:lnum, 0) if is_breakpoint " Remove the line number in breakpoints and unplace the mark call remove(b:breakpoints, a:lnum) exe ":sign unplace" else " Add the line number in breakpoints and place the mark let b:breakpoints[a:lnum] = 1 exe ":sign place 2 line=" . a:lnum . " name=Breakpoint file=" . expand("%:p") endif endfunction function BreakpointIndentation(lnum) " Get the line's current indentation level and first character let indent_count = indent(a:lnum) let curline = getline(a:lnum) let firstChar = curline[0] " Build the indentation to use for the breakpoint if firstChar == "\t" " Handle user defined `tabstop` variable return repeat(firstChar, indent_count / &amp;tabstop) else if firstChar == " " return repeat(firstChar, indent_count) else return "" endif endfunction function RunPDB() let lnum = 1 let num_lines = line("$") " The lines to write to the temporary file " Start out by importing pdb let lines = ["import pdb"] " Iterate over each line in the current buffer while lnum &lt;= num_lines let is_breakpoint = get(b:breakpoints, lnum, 0) " If the line is a breakpoint, add `pdb.set_trace` before that line if is_breakpoint let indentation = BreakpointIndentation(lnum) let breakpoint_line = "pdb.set_trace()" if indentation != "" let breakpoint_line = indentation . breakpoint_line endif call add(lines, breakpoint_line) endif call add(lines, getline(lnum)) let lnum += 1 endwhile " Create a new temporary file with the contents of `lines` let tmpfile = tempname() call writefile(lines, tmpfile) " Make a new vertical tmux split and run the temporary file with python silent exe "!tmux split-pane -v" silent exe "!tmux send-keys 'python " . tmpfile . "' Enter" endfunction nnoremap &lt;leader&gt;b :call ToggleBreakpoint(line("."))&lt;CR&gt; vnoremap &lt;leader&gt;b :call ToggleBreakpoint(line("."))&lt;CR&gt; nnoremap &lt;leader&gt;B :call RunPDB()&lt;CR&gt; </code></pre> <p>This is my first attempt to write anything particularly useful in vimscript.</p> <p>Are there any sections that can be improved upon? </p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-23T08:18:56.830", "Id": "217932", "Score": "4", "Tags": [ "python", "meta-programming", "vimscript" ], "Title": "Python breakpoints in Vim (Vimscript)" }
217932
<p>I currently have two (core) classes :</p> <pre><code>public abstract class BO&lt;TConfig&gt; where TConfig : BOConfigBase { protected TConfig Config { get; set; } internal List&lt;BC&gt; _BCs { get; set; } public abstract void Init(); public void Process() =&gt; _BCs.ForEach(bc =&gt; bc.Process()); } public class BOOne : BO&lt;BOConfigOne&gt; { public BOOne(BOConfigOne config) { Config = config; } public override void Init() { _BCs = new List&lt;BC&gt;() { BCA.Init(Config), BCB.Init(Config), BCC.Init(Config), BCOneA.Init(Config) }; } } </code></pre> <p>Then the code for my BCs</p> <pre><code>public abstract class BC { protected BOConfigBase Config { get; set; } public abstract void Process(); } public class BCA : BC { private BCA() { } public static BCA Init(BOConfigBase config) { BCA ret = new BCA { Config = config }; return ret; } public override void Process() { Config.Counter += 1; } } </code></pre> <p>To call this, I will do this :</p> <pre><code> static void Main() { { var boConfigOne = new BOConfigOne() { A = "one", B = "one", C = "one", One = "one" }; var testBO = new BOOne(boConfigOne); testBO.Init(); testBO.Process(); Console.WriteLine( $"A = {boConfigOne.A}, B = {boConfigOne.B}, C = {boConfigOne.C}, One = {boConfigOne.One}, Counter = {boConfigOne.Counter}"); } { var boConfigTwo = new BOConfigTwo() { A = "two", B = "two", C = "two", Two = "two" }; var testBOTwo = new BOTwo(boConfigTwo); testBOTwo.Init(); testBOTwo.Process(); Console.WriteLine( $"A = {boConfigTwo.A}, B = {boConfigTwo.B}, C = {boConfigTwo.C}, Two = {boConfigTwo.Two}, Counter = {boConfigTwo.Counter}"); } Console.ReadKey(); } </code></pre> <p>BO stands for Business Orchestration, and BC for Business Component. A BC would perform a single function, and a BO would contain several of these re-usable BCs.</p> <p>I would like to change the BO to be able to Init all the BCs generically, something like <code>Init =&gt; BCs.Foreach(bc =&gt; bc.Init(Config));</code>. The problem is that my BC's Init's are static, hence I can't put it in an interface, and call it on the interface, nor can I put it in the base abstract method, and override it.</p> <p>Does anyone have a better solution for me?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-23T08:23:39.667", "Id": "421767", "Score": "0", "body": "We can help you (better) and review the code when you show us your real implementation. This looks very much like pseudocode or hypothetical one." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-23T08:26:26.137", "Id": "421769", "Score": "0", "body": "@t3chb0t. This is the current working set of code I have as a POC. If I can get this to work, I will then implement it completely. I'll add the basic call of the methods to show the test implementation of it as well." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-23T08:27:32.980", "Id": "421770", "Score": "1", "body": "This is a very good idea. Could you tell us at least what BCA, BO etc stand for so we have some more context?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-23T08:28:58.017", "Id": "421771", "Score": "0", "body": "@t3chb0t, my apologies. So used to use the terms in my environment, I forgot to add. BC stands for Business Component, BO stands for Business Orchestration. So, a BO would contain several (reusable in other BO) BC's, that would perform a single function, like updating the DB, writing a file, etc." } ]
[ { "body": "<p>To be honest it's hard to follow with such abstract class names and POC. The root of what you are describing is you have a factory method to create one of your classes. Lucky for you it seems all the factory methods have the same method signature. We can make this a bit easier.</p>\n\n<p>Need to store the factory methods in a private field to be used by the Init method. Also adding a \"helper\" method to make storing the factories easier. </p>\n\n<pre><code>public abstract class BO&lt;TConfig&gt; where TConfig : BOConfigBase\n{\n protected TConfig Config { get; set; }\n internal List&lt;BC&gt; _BCs { get; set; }\n private Func&lt;BOConfigBase, BC&gt;[] _factories = new Func&lt;BOConfigBase, BC&gt;[0];\n\n protected void SetFactories(params Func&lt;BOConfigBase, BC&gt;[] factories)\n {\n _factories = factories;\n }\n\n public void Init()\n {\n _BCs = _factories.Select(b =&gt; b(Config)).ToList();\n }\n\n public void Process() =&gt; _BCs.ForEach(bc =&gt; bc.Process());\n}\n</code></pre>\n\n<p>Now BOOne class can call it like </p>\n\n<pre><code>public class BOOne : BO&lt;BOConfigOne&gt;\n{\n public BOOne(BOConfigOne config)\n {\n Config = config;\n SetFactories(BCA.Init, BCB.Init, BCC.Init, BCOneA.Init);\n }\n}\n</code></pre>\n\n<p>I'm assuming each BO class would take different BC classes if not then you could constructer inject all the factories. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-23T14:00:28.630", "Id": "217961", "ParentId": "217933", "Score": "1" } } ]
{ "AcceptedAnswerId": "217961", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-23T08:22:31.637", "Id": "217933", "Score": "0", "Tags": [ "c#", "generics", "inheritance", "static" ], "Title": "Generically call static methods" }
217933
<p>I'm trying to make a login system for my website which I'll be releasing in public later on. I have inserted some main samples of my code in here and I would like some useful advise or suggestions. Also if I'm doing anything unsafe or anything which may cause problems in future please let me know. Thanks</p> <h3>login.inc.php:</h3> <pre><code>&lt;?php error_reporting(0); $error_message = "Website ran into an error"; session_start(); if (isset($_SESSION['user_id'])) { exit(); } $parameters = json_decode(file_get_contents('php://input'), true); if (isset($parameters["inserted_id"]) &amp;&amp; isset($parameters["inserted_password"])) { // FOR TEST USE I'M USING xampp server, localhost $connection = mysqli_connect("localhost", "root", "", "users") or die($error_message); $inserted_id = $parameters['inserted_id']; $inserted_password = $parameters['inserted_password']; $statement = mysqli_stmt_init($connection) or die($error_message); if (mysqli_stmt_prepare($statement, "SELECT id, account_name, password FROM user WHERE account_name=? OR email=?;")) { mysqli_stmt_bind_param($statement, "ss", $inserted_id, $inserted_id); mysqli_stmt_execute($statement) or die($error_message); if (($row = mysqli_fetch_assoc(mysqli_stmt_get_result($statement))) == null) { echo("No records found with inserted inputs"); mysqli_stmt_close($statement); mysqli_close($connection); exit(); } else { if (password_verify($inserted_password, $row['password'])) { $_SESSION['user_id'] = $row['id']; $_SESSION['account_name'] = $row['account_name']; echo("pass"); } else { echo("Wrong password"); } mysqli_stmt_close($statement); mysqli_close($connection); exit(); } } mysqli_close($connection); exit(); } ?&gt; </code></pre> <h3>login.js:</h3> <pre><code>var request_sent = false; document.querySelector("button").onclick = function () { if (!request_sent) { var inserted_id = document.getElementById("inserted_id").value; var inserted_password = document.getElementById("inserted_password").value; if (inserted_id == "" || inserted_password == "") { alert("Both fields need to be filed out"); } else { request_sent = true; http_request("login.inc.php", JSON.stringify({"inserted_id":inserted_id, "inserted_password":inserted_password})); } } } function http_request(url, params) { $.ajax({ type: "POST", url: url, data: params, success: function(data) { if (data == "pass") { window.open("../website", "_self", "", false); } else { alert(data); } request_sent = false; } }); } </code></pre> <h3>login.html:</h3> <pre><code>&lt;html&gt; &lt;head&gt; &lt;title&gt;&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;input id="inserted_id" type="text" placeholder="Account Name/e-mail"/&gt; &lt;input id="inserted_password" type="password" placeholder="Password"/&gt; &lt;button&gt;SUBMIT&lt;/button&gt; &lt;script src="login.js"&gt;&lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-23T10:22:45.207", "Id": "421793", "Score": "0", "body": "Regarding the topmost line: https://phpdelusions.net/top#zero_error_reporting" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-23T10:25:41.893", "Id": "421794", "Score": "0", "body": "Regarding mysqli_connect: https://phpdelusions.net/mysqli/mysqli_connect" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-23T10:27:03.640", "Id": "421795", "Score": "0", "body": "Regarding the main code block, it can be made much simpler: https://phpdelusions.net/mysqli/password_hash" } ]
[ { "body": "<ul>\n<li><p><code>isset()</code> accepts multiple parameters, you can simplify:</p>\n\n<pre><code>if (isset($parameters[\"inserted_id\"]) &amp;&amp; isset($parameters[\"inserted_password\"])) {\n</code></pre>\n\n<p>To</p>\n\n<pre><code>if (isset($parameters[\"inserted_id\"], $parameters[\"inserted_password\"])) {\n</code></pre></li>\n<li><p>When ever I read anyone's code or database schema and I see any mention of <code>id</code>, I immediately assume that I am dealing with a positive integer. If the value is anything other than a positive integer, I never use <code>id</code> in the field/column/variable name.</p></li>\n<li><p>I never use mysqli's <code>init()</code> call because it is optional. I'll recommend objected-oriented mysqli syntax because it is less verbose.</p></li>\n<li><p>I don't think I'd json encode/decode your form data -- it seems like unnecessary extra data handling. See here: <a href=\"https://stackoverflow.com/q/5004233/2943403\">jQuery Ajax POST example with PHP</a></p></li>\n<li><p><code>echo</code> doesn't need those parentheses. </p></li>\n<li><p>I am confident that @YourCommonSense will post a comprehensive answer containing the 3 pieces of commented advice and more, so I'll leave those recommendations to him.</p></li>\n<li><p>You don't need to write out all those <code>close()</code> calls, just <code>echo</code> your message and let the script end naturally. If you're going to kill the script at <code>if (isset($_SESSION['user_id'])) {</code> be sure to sure to echo something for consistency. </p></li>\n<li><p>I find javascript <code>alert()</code> boxes to be terribly annoying and a bit trashy to be honest. Give your site some \"class\" and fashion an attractive presentation for any response messages that you plan to offer.</p></li>\n<li><p>Your .html has form fields, but no form -- that doesn't feel valid to me. I'll recommend adding the form tags and names attributes. Some discussions: <a href=\"https://stackoverflow.com/q/33370025/2943403\">https://stackoverflow.com/q/33370025/2943403</a></p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-24T08:36:12.810", "Id": "422957", "Score": "0", "body": "No, sorry, I wasn't going to answer, got no time for complete answers atm" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-26T05:15:39.940", "Id": "423287", "Score": "0", "body": "@mickmackusa What about any security or any sort of \"error\" problems which may raise?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-26T12:23:41.180", "Id": "423352", "Score": "0", "body": "@Aman For extreme cases, I recommend that you never store any personally identifying data in the session array as a consideration regarding the topic of \"Session Hijacking\". https://stackoverflow.com/a/42869960/2943403 Between my advice, KIKO's comprehensive answer, and YourCommonSense's comments -- I think we have you pretty well covered." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-23T12:29:49.650", "Id": "217953", "ParentId": "217938", "Score": "5" } }, { "body": "<p>I'll take a more holistic approach than mickmackusa, he already talked about a lot of details.</p>\n\n<p>I don't see any problem with the fact that you use an AJAX call to verify user credentials, and login. There's no real difference, security wise, when I compare this with a normal form submission. Any hacker will simply bypass your Javascript and call <code>login.inc.php</code> directly.</p>\n\n<p>Your PHP code seems to cover the basics well. There are prepared statements, you use hashed passwords and <code>password_verify()</code>, and you don't show system errors to the user (do read the comment by Your Common Sense; 'regarding the topmost line'). But to me the code still looks a bit unorganized.</p>\n\n<p>For instance, you open and close the database connection. I'm sure you'll have other PHP pages where this is needed. It doesn't make sense to have the connection details in every PHP page. I would include another PHP file with functions to open and close the database, so I can simply say: <code>openDatabase();</code>. Then, if I have to change the password of the database, I can change it in one location.</p>\n\n<p>There's also no harm in using functions for other things in your code. It makes it much easier to read:</p>\n\n<pre><code>if (hasLoginDetails($parameters)) {\n list($username, $password) = getLoginDetails($parameters);\n $database = openDatabase();\n if ($user = getUserInfoByName($database, $username)) {\n if (password_verify($password, $user['password'])) {\n setSessionUser($user);\n echo(\"pass\");\n } else {\n echo(\"Wrong password\");\n }\n }\n else {\n echo(\"No records found with inserted inputs\");\n }\n closeDatabase($database);\n}\n</code></pre>\n\n<p>I'm not saying this is the right way to do it, but it is <em>better</em>. Note that I have left out all your <code>exit()</code>. They were used wrongly, because they would have, theoretically, prevented the database to close. Of course, it will close automatically when the script exits, but did you know that?</p>\n\n<p>My point is that structuring your code is very important. It helps you spot problems, and makes it easier to change the code later on.</p>\n\n<p>There's also some, but not much, confusion when it comes to names. An <code>inserted_id</code> seems to have the same content as <code>account_name</code>. That's not obvious. Why not give these more similar names?</p>\n\n<p>Now that I have slightly shortened the code I notice you give two different messages back to the user: <em>\"Wrong password\"</em> and <em>\"No records found with inserted inputs\"</em>. That means that I can start guessing user names first, and when I get it right, I will get feedback telling me so. That's half my job, of breaking in, done. In other words: These two messages should always be the same. <strong>Don't give a hacker any information.</strong></p>\n\n<p>As to the security. There are <em>no other</em> protection mechanisms against hacking in your system. It would happily accept a simple brute force attack. Once I have a valid user name I can try my long list of passwords as fast as your server will process them. Even a simple <code>sleep(4)</code>, when the wrong credentials were supplied, will slow this down enormously. I normally give users five changes to enter their credentials and then block them for a longer time (15 minutes?). The user needs to be told this, of course, otherwise real users might find themselves locked out because they simply tried to often. Something like: <em>\"You have 3 attempts left before your account will be blocked.\"</em>. You should not block an account too long, otherwise someone can block users intentionally. Be careful with this. Another strategy is to make failed logins, by the same person, slower and slower, the more they try it. Anything that will make a brute force attack impossible, but not hinder normal users.</p>\n\n<p>Your system is also lacking the usual 'I forgot my password' mechanism. Because users <em>will</em> forget their password. By not having this mechanism, users will have to correspond with you to get it, which can be very slow, and possibly less secure.</p>\n\n<p>Adding features, like the ones I mentioned above, will further increase the complexity of your code, hence the importance of good structuring to keep it readable.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-24T08:19:28.077", "Id": "422953", "Score": "1", "body": "Thank you. Only one little nitpick more: `error_reporting(0)` actually *suppresses* errors, not preventing them from displaying. You can check the link I posted in the comment under the question, it explains the difference pretty straightforward." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-24T08:22:47.470", "Id": "422954", "Score": "1", "body": "Yeah, I didn't pay attention to that. I shall refer to your comment in my answer." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-26T05:37:09.450", "Id": "423289", "Score": "0", "body": "Thank You. The content in your answer seems useful and I'll try and implement it." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-24T07:35:39.720", "Id": "218999", "ParentId": "217938", "Score": "4" } }, { "body": "<p>I don't use <code>$_SESSION</code> super global array and don't know much about it, so please correct me if I'm wrong, <strong>isn't this code vulnerable to session fixation attacks</strong> ?</p>\n\n<p>AFAIK the magic behind <code>$_SESSION</code> is a session id cookie, I think it's default name is <code>PHPSESSID</code>, and in your code when the user logs in you don't change this cookie! I did little test before I write this, and yep, PHP doesn't change this cookie :(</p>\n\n<p>you need to change this</p>\n\n<pre><code>if (password_verify($inserted_password, $row['password'])) {\n //......\n}\n</code></pre>\n\n<p>into something like this</p>\n\n<pre><code>if (password_verify($inserted_password, $row['password'])) {\n session_regenerate_id(true);\n //......\n}\n</code></pre>\n\n<p>The idea is you must <strong>change</strong> the identification cookies when your clients login, no matter you use <code>$_SERSSION</code> or other way.</p>\n\n<p>This is quoted from <a href=\"https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies\" rel=\"nofollow noreferrer\">MDN</a></p>\n\n<blockquote>\n <p>Session fixation should primarily be mitigated by regenerating session\n cookie values when the user authenticates (even if a cookie already\n exists) and by tieing any CSRF token to the user.</p>\n</blockquote>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-26T12:20:09.427", "Id": "423349", "Score": "1", "body": "The OP's script is not accepting session identifiers via url, so this is not a concern and does not need to be mitigated. https://www.webdigi.co.uk/blog/2009/php-session-fixation-attacks/" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-26T13:41:01.963", "Id": "423378", "Score": "0", "body": "@mickmackusa thank you for the information, yes the most common and easiest to implement technique for fixing the session token on the victims computer is throw URLs, or form fields, which is not happening in the OP's code, however there are still other ways to fix the sessionID on the computer, (e.g: an XSS payload or simply by setting on the victims computer (while he is logged out) and change the cookie by hand). IMHO, I think not changing the session ID after log-ins is a bad practice in general." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-24T12:52:31.420", "Id": "219014", "ParentId": "217938", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-23T09:56:55.067", "Id": "217938", "Score": "3", "Tags": [ "javascript", "php", "security", "session" ], "Title": "httprequest to php login system" }
217938
<p>The task is to compute all the permutations for a given vector of integers (but of course the specific integer type is not relevant for the solution)</p> <p>The strategy is based on recursion + iterations </p> <p>At each recursion, the state consists of </p> <ul> <li><p>the root sequence <code>a</code> which is the set of elements already placed </p></li> <li><p>the remaining elements set <code>b</code> which is the set of elements still to be placed </p></li> </ul> <p>Inside the recursion, a loop places the <code>N(i)</code> (with <code>i</code> recursion index and) remaining elements producing the same amount of new root sequences and a new recursion is started so that <code>N(i+1)=N(i)-1</code> hence meaning the overall complexity is <code>O(N!)</code> as expected </p> <p>The recursion ends when there are no more elements to place hence <code>b.empty()</code> is true </p> <p>Each recursion set ends with a valid sequence hence they are all merged together in a final list of sequences </p> <p>Here is my CPP solution </p> <pre class="lang-cpp prettyprint-override"><code>#include &lt;iostream&gt; #include &lt;vector&gt; using namespace std; vector&lt;int&gt; remove_item (const vector&lt;int&gt;&amp; a, const unsigned int id) { vector&lt;int&gt; res; for(unsigned int i=0; i&lt;a.size(); ++i) if(i!=id) res.push_back(a[i]); return res; } vector&lt;int&gt; add_item(const vector&lt;int&gt;&amp; a, const int b) { vector&lt;int&gt; res=a; res.push_back(b); return res; } vector&lt; vector&lt;int&gt; &gt; merge(const vector&lt; vector&lt;int&gt; &gt;&amp; a, const vector&lt; vector&lt;int&gt; &gt;&amp; b) { vector&lt; vector&lt;int&gt; &gt; res=a; for(const auto&amp; e : b) res.push_back(e); return res; } vector&lt; vector&lt;int&gt; &gt; permutations(const vector&lt;int&gt;&amp; b, const vector&lt;int&gt;&amp; a={}) { if(b.empty()) return { a }; vector&lt; vector&lt;int&gt; &gt; res; for(unsigned int i=0; i&lt;b.size(); ++i) res=merge(res, permutations(remove_item(b,i), add_item(a, b[i]))); return res; } int main() { // your code goes here auto res = permutations({1,2,3,4,5}); cout &lt;&lt; "Sol Num = " &lt;&lt; res.size() &lt;&lt; endl; for(const auto&amp; a : res) { for(const auto&amp; b : a) cout &lt;&lt; to_string(b) &lt;&lt; " "; cout &lt;&lt; endl; } return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-24T12:05:10.383", "Id": "422979", "Score": "0", "body": "Not only the time complexity, but also the memory complexity is \\$O(n!)\\$ – because that's the size of your output. For \\$n\\$ greater than tiny this may be a serious disadvantage..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-24T12:12:50.387", "Id": "422980", "Score": "0", "body": "The number of permutations is N! which means eventually you need to store all of them so you need O(N!) memory, unless you are allowed to print them as soon as you discover them" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-24T12:59:23.487", "Id": "422989", "Score": "0", "body": "That's it: _unless_. You never said they must be delivered all at once. So it's a valid supposition you can find them one by one and utilize (for example: print) iteratively..." } ]
[ { "body": "<p>A cleaner solution is to trust the standard library and try to re-use the generic components already available there. Your problem is solved by <a href=\"https://en.cppreference.com/w/cpp/algorithm/next_permutation\" rel=\"nofollow noreferrer\">std::next_permutation</a>, so you can proceed along the lines of:</p>\n\n<pre><code>#include &lt;iostream&gt;\n#include &lt;vector&gt;\n#include &lt;algorithm&gt;\n\nint main()\n{\n std::vector&lt;int&gt; v = { 1, 2, 3, 4, 5 };\n\n do\n {\n for (auto e : v)\n std::cout &lt;&lt; e &lt;&lt; \" \";\n std::cout &lt;&lt; \"\\n\";\n } \n while (std::next_permutation(v.begin(), v.end()));\n}\n</code></pre>\n\n<hr>\n\n<p>For pedagogical purposes, if you wanted to keep your current structure, you could also use standard functions there. In particular, <code>remove_item</code> and <code>merge</code> could be rewritten to:</p>\n\n<pre><code>std::vector&lt;int&gt; remove_item(const std::vector&lt;int&gt;&amp; a, int id)\n{\n assert(id &gt;= 0 &amp;&amp; id &lt; a.size());\n\n std::vector&lt;int&gt; res(a.begin(), a.begin() + id);\n res.insert(res.end(), a.begin() + id + 1, a.end());\n return res;\n}\n\nstd::vector&lt;std::vector&lt;int&gt; &gt; merge(const std::vector&lt;std::vector&lt;int&gt; &gt;&amp; a, const std::vector&lt;std::vector&lt;int&gt; &gt;&amp; b)\n{\n std::vector&lt;std::vector&lt;int&gt; &gt; res(a);\n std::copy(b.begin(), b.end(), std::back_inserter(res));\n return res;\n}\n</code></pre>\n\n<p>Whatever you do, as general comments:</p>\n\n<ul>\n<li><p><a href=\"//stackoverflow.com/q/1452721\">Avoid writing <code>using namespace std;</code>.</a></p></li>\n<li><p><a href=\"//stackoverflow.com/q/213907\">Don't write <code>std::endl</code> when <code>\\n</code> will do.</a></p></li>\n<li><p>You don't need <code>std::to_string</code>, just print <code>b</code>.</p></li>\n<li><p>You are more likely to make mistakes when you put multiple statements on the same line. So instead of writing <code>for(...) if(...) v.push_back(x);</code> just write</p>\n\n<pre><code>for(...)\n{\n if(...)\n {\n v.push_back(x);\n }\n}\n</code></pre>\n\n<p>This also improves readability.</p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-23T13:57:34.703", "Id": "421836", "Score": "2", "body": "Sure, but using the standard library makes it trivial \nMy goal was to develop a working algo" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-23T13:58:36.133", "Id": "421837", "Score": "0", "body": "@NicolaBernini Indeed, I hope that nobody is discouraged from reviewing your code beyond my answer." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-23T15:02:48.277", "Id": "421851", "Score": "1", "body": "@NicolaBernini Trust Juho, you will be able to write better algorithms if you learn the standard library." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-23T15:15:21.510", "Id": "421861", "Score": "0", "body": "@WooWapDaBug I already know it (at least at some extent, there is always room for improvement) but I hope it is clear it was not the point of the exercise" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-23T17:09:14.690", "Id": "421883", "Score": "0", "body": "@NicolaBernini It wasn't, but now the relevant tag is added so it is." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-23T10:39:32.017", "Id": "217941", "ParentId": "217939", "Score": "6" } }, { "body": "<p>I understand the need to reinvent the wheel but in this case you reinvented an other kind of wheel: functional-style combinatorics aren't very well suited to C++ and the high-performance / low-memory usage it is well known for. I mean, that's a bike wheel for a car.</p>\n\n<p>Now if you want to reinvent the C++ wheel, the best thing would be to re-implement <code>std::next_permutation</code>: an algorithm that does its work incrementally, in place, and with iterators (meaning that you can compute the permutations of strings, arrays, double-linked lists and everything that exposes bidirectional iterators).</p>\n\n<p>Interestingly, there's an example of implementation on <a href=\"https://en.cppreference.com/w/cpp/algorithm/next_permutation\" rel=\"nofollow noreferrer\">cppreference.com</a>:</p>\n\n<pre><code>template&lt;class BidirIt&gt;\nbool next_permutation(BidirIt first, BidirIt last)\n{\n if (first == last) return false;\n BidirIt i = last;\n if (first == --i) return false;\n\n while (true) {\n BidirIt i1, i2;\n\n i1 = i;\n if (*--i &lt; *i1) {\n i2 = last;\n while (!(*i &lt; *--i2))\n ;\n std::iter_swap(i, i2);\n std::reverse(i1, last);\n return true;\n }\n if (i == first) {\n std::reverse(first, last);\n return false;\n }\n }\n}\n</code></pre>\n\n<p>This implementation is a good example of \"C++-sprinkled\" C code. It's rather elegant but difficult to understand. If you reverse-engineer it though, you'll see it's quite simple:</p>\n\n<ul>\n<li><p>first, beginning from the end, find the first adjacent items in increasing order. Let's call the lesser item's position the permutation point. If there are none, that was the last permutation: reverse and return false;</p></li>\n<li><p>then, also beginning from the end, find the first item whose value is superior to that of the permutation point. Swap those two, reverse the range <code>(permutation_point, last)</code> and return true.</p></li>\n</ul>\n\n<p>Now we're ready to reinvent a C++ wheel the C++ way:</p>\n\n<pre><code>#include &lt;algorithm&gt;\n#include &lt;iterator&gt;\n\ntemplate &lt;typename Iterator&gt;\nbool permute(Iterator first, Iterator last) {\n // check if there are at least two elements\n if (first == last || std::next(first) == last) return false;\n\n // first step: first adjacent elements in increasing order, starting from the end\n const auto r_first = std::reverse_iterator(last);\n const auto r_last = std::reverse_iterator(first);\n auto position = std::adjacent_find(r_first, r_last, [](auto lhs, auto rhs) {\n return lhs &gt; rhs;\n });\n // check if it was the last permutation\n if (position == r_last) {\n std::reverse(first, last);\n return false;\n }\n ++position; // advance position to the lesser item\n\n // second step: swap the permutation point and the first greater value from the end\n std::iter_swap(position, std::find_if(r_first, position, [position](auto value) {\n return value &gt; *position;\n }));\n std::reverse(r_first, position);\n return true;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-24T09:25:00.320", "Id": "422960", "Score": "0", "body": "I understand your point and thanks for sharing it, but I have to do bias disclosure now: I (strongly) favour functional style over imperative (which does not mean I’m a purist, otherwise I would not have used loops, I’m just trying to take the best of both worlds) \nCertainly it can have a performance cost (depends how smart the compiler is) but I think it is not necessary for me to list the joys functional programming" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-24T09:44:42.297", "Id": "422963", "Score": "0", "body": "@NicolaBernini: well, you can always put `next_permutation` into a functional shell (like you do with `insert`, `push_back`, etc. in your helper functions). I also like functional programming a lot, and have tried a few times to adopt functional idioms in C++ but there's always a point where you understand C++ won't ever be Haskell. But yeah, sure!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-24T10:07:51.387", "Id": "422965", "Score": "0", "body": "This is the strategy I adopt typically for my hybrid functional style, but not in this case as I was trying to reimplement next_permutation but in production code that’s what I tend to do. \nC++ does not need be Haskell, but some C++ programmer would certainly take benefit from some exposure to Haskell :)" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-24T09:13:57.007", "Id": "219005", "ParentId": "217939", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-23T10:17:47.173", "Id": "217939", "Score": "7", "Tags": [ "c++", "reinventing-the-wheel", "combinatorics" ], "Title": "Compute all the permutations for a given vector of integers" }
217939
<p><strong>The task</strong> is taken from leetcode</p> <blockquote> <p>Given an array A of non-negative integers, return an array consisting of all the even elements of A, followed by all the odd elements of A.</p> <p>You may return any answer array that satisfies this condition. </p> <p>Example 1:</p> <p>Input: [3,1,2,4]</p> <p>Output: [2,4,3,1]</p> <p>The outputs [4,2,3,1], [2,4,1,3], and [4,2,1,3] would also be accepted. </p> <p>Note:</p> <p>1 &lt;= A.length &lt;= 5000</p> <p>0 &lt;= A[i] &lt;= 5000</p> </blockquote> <p><strong>My functional solution 1</strong></p> <pre><code>const sortArrayByParity = A =&gt; A.reduce((acc, x) =&gt; { if (x % 2 === 0) { acc.unshift(x); } else { acc.push(x); } return acc; }, []); </code></pre> <p><strong>My functional solution 2</strong></p> <pre><code>const sortArrayByParity = A =&gt; A.reduce((acc, x) =&gt; x % 2 === 0 ? [x, ...acc] : [...acc, x]); </code></pre> <p><strong>My imperative solution</strong></p> <pre><code>function sortArrayByParity2(A) { const odd = []; const even = []; for (const a of A) { if (a % 2 === 0) { even.push(a); } else { odd.push(a); } } return [...even, ...odd]; }; </code></pre>
[]
[ { "body": "<h2>Bug</h2>\n\n<p>Your second functional solution does not run. You forgot to add the second argument to <code>A.reduce</code>. I will assume you wanted an array as the last argument.</p>\n\n<h2>Why functional sucks</h2>\n\n<p>This example clearly illustrates the problem with some functional solutions that involve data manipulation. The requirement of no side effects forces the solution to copy the whole dataset even when you manipulate only a single item. This is particularly noticeable in your second functional solution. See performance results below.</p>\n\n<h2>Code and Style</h2>\n\n<p>Some minor points...</p>\n\n<ul>\n<li><code>function () {};</code> the trailing semicolon is not needed.</li>\n<li><p>Swap the conditions. </p>\n\n<p>You have <code>if(a % 2 === 0) { /*even*/ } else { /*odd*/ }</code> ...</p>\n\n<p>can be <code>if(a % 2) { /*odd*/ } else { /*even*/ }</code></p></li>\n<li><p>Compact code. Try to avoid sprawling code. It may not matter for small segments of code, but source code can very long and reading code there spans pages is not as easy as having it all in one view.</p></li>\n<li><p>Before a newline it is either <code>}</code> or <code>;</code>. There are two exceptions. The <code>}</code> that closes an object literal should have a closing <code>;</code> eg <code>const a = {};</code>. And multi line statements and expressions.</p></li>\n</ul>\n\n<h2>Know the language.</h2>\n\n<p>You do a lot of code examples, many of them are rather trivial. Of late many of your posts contain bugs or incomplete code (may be a sign of boredom? or a lack of challenge (engagement)) . I do not believe in the classical closed book assessment examination, it does not reflect the real world. However a good memory of the field makes you a more productive coder.</p>\n\n<p>There are many subtle tricks in JavaScript that can catch you out if unaware. Testing your knowledge improves your understanding of the language making you a better coder.</p>\n\n<p>This is a example <a href=\"http://davidshariff.com/js-quiz/\" rel=\"nofollow noreferrer\">JavaScript Web Development Quiz</a> picked at random from a web search <code>\"javascript quiz\"</code> </p>\n\n<p>It is good practice to do one of these every now and then.</p>\n\n<p><sub><sup>I did not get 100% </sup></sub></p>\n\n<h2>Example A</h2>\n\n<p>Compacting the function. </p>\n\n<pre><code>function sortByParity(arr) {\n const odd = [], even = [];\n for (const val of arr) {\n if (val % 2) { odd.push(val) }\n else { even.push(val) }\n }\n return [...even, ...odd];\n}\n</code></pre>\n\n<h2>Performance</h2>\n\n<p>The second functional example was so slow I had to push the other best time down to the timer resolution cutoff 0.2ms or it would have taken forever to complete the test.</p>\n\n<p>The functions as tested</p>\n\n<pre><code>function sortByParity_I1(A) {\n const odd = [], even = [];\n for (const a of A) {\n if (a % 2 === 0) { even.push(a) }\n else { odd.push(a) }\n }\n return [...even, ...odd];\n}\nconst sortByParity_F2 = A =&gt; A.reduce((acc, x) =&gt; x % 2 === 0 ? [x, ...acc] : [...acc, x], []);\nconst sortByParity_F1 = A =&gt; A.reduce((acc, x) =&gt; {\n if (x % 2 === 0) { acc.unshift(x) }\n else { acc.push(x) }\n return acc;\n }, []);\n</code></pre>\n\n<h3>Benchmarks</h3>\n\n<p>Mean time per call to the function in 1/1,000,000 second. OPS is operations per second. % is relative performance of best.</p>\n\n<p>For array of 1000 random integers</p>\n\n<pre><code>sortByParity_I1: 20.709µs OPS 48,287 100%\nsortByParity_F1: 133.933µs OPS 7,466 15%\nsortByParity_F2: 3,514.830µs OPS 284 1%\n</code></pre>\n\n<p>For array of 100 random integers</p>\n\n<pre><code>sortByParity_I1: 2.049µs OPS 488,148 100%\nsortByParity_F1: 10.005µs OPS 99,947 20%\nsortByParity_F2: 46.679µs OPS 21,422 4%\n</code></pre>\n\n<p><strong>Note</strong> that the results for the functional solution do not have a linear relationship with the size of the array.</p>\n\n<h2>Improving performance</h2>\n\n<p>I will drop the slow functional and add an improved imperative function that pre allocates the result array. This avoids the overhead of allocation when you grow the arrays. As there is one array the overhead of joining the two arrays is avoided as well. This almost doubles the performance.</p>\n\n<pre><code>function sortByParity_I2(A) {\n const res = new Array(A.length);\n var top = res.length - 1, bot = 0;\n for (const a of A) { res[a % 2 ? top-- : bot ++] = a }\n return res;\n}\n\n10000 items\nsortByParity_I2: 119.851µs OPS 8,343 100%\nsortByParity_I1: 223.468µs OPS 4,474 54%\nsortByParity_F1: 5,092.816µs OPS 196 2%\n\n1000 items\nsortByParity_I2: 13.094µs OPS 76,372 100%\nsortByParity_I1: 23.731µs OPS 42,138 55%\nsortByParity_F1: 123.381µs OPS 8,104 11%\n\n100 items\nsortByParity_I2: 0.900µs OPS 1,110,691 100%\nsortByParity_I1: 2.245µs OPS 445,398 40%\nsortByParity_F1: 9.520µs OPS 105,039 9%\n</code></pre>\n\n<p><sub><sup>Test on Win10 Chrome 73 CPU i7 1.5Ghz </sup></sub></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-24T15:40:26.997", "Id": "423023", "Score": "0", "body": "Yeah, the last weeks I picked only easy task. My thinking was: I have to master them first before tackling the more difficult ones (if I can't solve easy ones, why should I solve the hard ones). Lately I have been frustrated with private things and it seems it has affected the way I write and test my code....\n\nThanks, for the link. I only got 65%. *frustration peaks*. lol.\n\nHow come you've been so good at JS resp. programming in general?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-24T16:24:54.187", "Id": "423040", "Score": "0", "body": "@thadeuszlay I am just average, the only thing I have was starting young and now experience, 40 years coding under my belt very soon." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-24T19:07:30.323", "Id": "423075", "Score": "0", "body": "`I do not believe in the classical closed book assessment examination, it does not reflex the real world` According to you, what does reflect real world tasks?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-24T19:43:35.077", "Id": "423081", "Score": "0", "body": "@thadeuszlay Oh that should be `reflect`.. In the real world you have full access to all references, can ask work mates for advice and/or help, outsource advice / help, or even go home and sleep on a particularly difficult problem. No good employer would have you work under closed book exam conditions." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-24T19:58:45.720", "Id": "423083", "Score": "0", "body": "Isn't it better this way. If you can solve under `closed book exam conditions` you can also solve it in the `real world`?" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-24T13:14:44.883", "Id": "219016", "ParentId": "217944", "Score": "1" } } ]
{ "AcceptedAnswerId": "219016", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-23T10:58:16.823", "Id": "217944", "Score": "1", "Tags": [ "javascript", "algorithm", "programming-challenge", "functional-programming", "ecmascript-6" ], "Title": "Sort Array By Parity" }
217944
<p>I would like to create a function which returns a map containing differences between two unordered maps. Here is the code:</p> <pre><code>std::map&lt;std::string, int&gt; getDiff(const std::unordered_map&lt;std::string, int&gt;&amp; unordered_mapA, const std::unordered_map&lt;std::string, int&gt;&amp; unordered_mapB) { std::map&lt;std::string, int&gt; mapA(unordered_mapA.begin(), unordered_mapA.end()); std::map&lt;std::string, int&gt; mapB(unordered_mapB.begin(), unordered_mapB.end());; std::map&lt;std::string, int&gt; diffMap; std::set_difference(mapA.begin(), mapA.end(), mapB.begin(), mapB.end(), std::inserter(diffMap, diffMap.end())); return diffMap; } </code></pre> <p>Edit:</p> <p>A result should contain elements which are present in mapA but are not present in mapB.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-23T11:57:33.243", "Id": "421805", "Score": "0", "body": "I'd be surprised if it worked: `std::set_difference` and the like require the inputs to be sorted, which unordered maps obviously aren't. Besides, \"differences\" is a bit vague but if you want every element from both lists that isn't in the other list, then `std::set_symmetric_difference` would be what you're looking for" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-23T12:10:36.367", "Id": "421809", "Score": "0", "body": "I apply std::set_differences on containers which are sorted (mapA, mapB). You're right about std::set_symmetric_difference but my goal was other, please Edit, I have also edited title." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-23T12:14:40.493", "Id": "421811", "Score": "0", "body": "right, sorry, my mistake" } ]
[ { "body": "<p>At first sight, this looks good - you let a standard library algorithm and two standard library class constructors do the heavy lifting. But this approach ships with a drawback, especially the linear (given that the input is sorted) copy construction of the two local <code>std::map</code>s can be quite a bottleneck, e.g. when the keys are long enough to not fit into the SSO buffer. Together with <code>std::set_difference</code>, you have a time complexity of approximately <code>O(N1 + N2)</code> (neglecting constant factors) plus that of the insertion into the resulting map (which is inevitable).</p>\n\n<p>You could consider a simpler, more manual approach. Recall that element lookup by a key is constant time in a hash map, so doing that inside a loop over all elements doesn't add much overhead to the function:</p>\n\n<pre><code>std::map&lt;std::string, int&gt; getDiff(const std::unordered_map&lt;std::string, int&gt;&amp; src,\n const std::unordered_map&lt;std::string, int&gt;&amp; exclude)\n{\n std::map&lt;std::string, int&gt; diff;\n\n for (const auto&amp; node : src) {\n const auto lookup = exclude.find(node.first);\n\n if (lookup == src.cend() || node.second != lookup-&gt;second)\n diff.insert(node);\n }\n\n return diff;\n}\n</code></pre>\n\n<p>First note that I have renamed the function arguments here. Whether <code>src</code> and <code>exclude</code> is the clearest choice might be debatable, but it should be better than <code>unordered_mapA</code> and <code>unordered_mapB</code>, which duplicates info already present in the type of these arguments. This has an improved time complexity of <code>O(N1)</code> (again, without constant factors or counting <code>std::map::insert</code>).</p>\n\n<p>This can be taken one step further to make it more reusable, as there aren't any specific requirements on key and value types that should be nailed down (besides the ability to check whether objects of the value type compare equal).</p>\n\n<pre><code>template &lt;class Key, class Value&gt;\nstd::map&lt;Key, Value&gt; getDiff(const std::unordered_map&lt;Key, Value&gt;&amp; src,\n const std::unordered_map&lt;Key, Value&gt;&amp; exclude)\n{\n // Exactly as above...\n}\n</code></pre>\n\n<p>You can use type deduction for saving some keyboard strokes upon the invocation:</p>\n\n<pre><code>std::unordered_map&lt;std::string, int&gt; a{/* ... */};\nstd::unordered_map&lt;std::string, int&gt; b{/* ... */};\n\nconst auto diff = getDiff(a, b));\n</code></pre>\n\n<p>And one last, idiomatic level of indirection could then be to not commit to a specifiy return type, but instead pass an output iterator that accepts a <code>std::pair&lt;Key, Value&gt;</code>:</p>\n\n<pre><code>template &lt;class Key, class Value, class OutputIt&gt;\nOutputIt getDiff(const std::unordered_map&lt;Key, Value&gt;&amp; src,\n const std::unordered_map&lt;Key, Value&gt;&amp; exclude, OutputIt dest)\n{\n // As above... \n\n if (...)\n dest = node; // instead of diff.insert(node);\n\n return dest;\n}\n</code></pre>\n\n<p>Here, it is convention to return the output iterator at the end of the function. You can instantiate and invoke the above template as follows.</p>\n\n<pre><code>std::map&lt;std::string, int&gt; diff;\ngetDiff(a, b, std::inserter(diff, diff.end()));\n</code></pre>\n\n<p>Or, if you later decied that you need cache locality for the result of the operation:</p>\n\n<pre><code>std::vector&lt;std::pair&lt;std::string, int&gt;&gt; seqDiff;\ngetDiff(a, b, std::inserter(seqDiff, seqDiff.end()));\n</code></pre>\n\n<p>Note that you still want more abstraction, you could also hide the <code>src</code> argument behind input iterators, as the loop over this container isn't specific to the hash map type.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-23T21:31:20.663", "Id": "217989", "ParentId": "217945", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-23T10:58:42.347", "Id": "217945", "Score": "1", "Tags": [ "c++", "c++11" ], "Title": "Get a map containing elements which are present in unordered map A but are not present in unordered map B" }
217945
<p>I have a tsv file containing the mapping for two kinds of identifiers.</p> <pre><code>accession accession.version taxid gi V00184 V00184.1 44689 7184 V00185 V00185.1 44689 7186 V00187 V00187.1 44689 7190 X07806 X07806.1 7227 8179 </code></pre> <p>Basically, I want to be able to get the <code>taxid</code> from an <code>accession</code> number. I though I could put this in a database with a PRIMARY KEY on the <code>accession</code> field.</p> <p>This is what I did and It works but I have around 1.5billion lines and it takes a lot of time to do.</p> <pre><code>import sqlite3 import time start = time.time() connection = sqlite3.connect("test.sqlite") cursor = connection.cursor() cursor.execute(""" CREATE TABLE IF NOT EXISTS map ( accession TEXT PRIMARY KEY, accession_version TEXT, taxid TEXT, gi TEXT )""") def read_large_file(f): """Generator for the file""" for l in f: yield l.strip().split() with open("test_file.map", "r") as f: next(f) # ignore header cursor.executemany("INSERT INTO map VALUES (?, ?, ?, ?)", read_large_file(f)) cursor.close() connection.commit() connection.close() print(time.time() - start) </code></pre> <p>Do you have any tricks or ideas I could use to speed up the insert ? (I will do very basic SELECT on the data using the <code>accession</code> primary key)</p>
[]
[ { "body": "<p>First, some comments on your code:</p>\n\n<ul>\n<li><p>An <code>sqlite3</code> connection <a href=\"https://docs.python.org/3/library/sqlite3.html#using-the-connection-as-a-context-manager\" rel=\"nofollow noreferrer\">can be used as a context manager</a>. This ensures that the statement is committed if it succeeds and rolled back in case of an exception. Unfortunately it does not also close the connection afterwards</p>\n\n<pre><code>with sqlite3.connect(\"test.sqlite\") as connection, open(\"test_file.map\") as f:\n connection.execute(\"\"\"\n CREATE TABLE IF NOT EXISTS map (\n accession TEXT PRIMARY KEY,\n accession_version TEXT,\n taxid TEXT, gi TEXT\n )\"\"\")\n\n next(f) # ignore header\n connection.executemany(\"INSERT INTO map VALUES (?, ?, ?, ?)\", read_large_file(f))\nconnection.close()\n</code></pre></li>\n<li><p>You should separate your functions from the code calling it. The general layout for Python code is to first define your classes, then your functions and finally have a main block that is protected by a <a href=\"http://stackoverflow.com/questions/419163/what-does-if-name-main-do\"><code>if __name__ == \"__main__\":</code> guard</a> to allow importing from the script without executing all the code.</p></li>\n<li><code>open</code> automatically opens a file in read-mode, if not specified otherwise.</li>\n</ul>\n\n<hr>\n\n<p>That being said, if you have a billion lines, basically any approach is probably going to be slow. Here is an alternate approach using <a href=\"https://docs.dask.org/en/latest/\" rel=\"nofollow noreferrer\"><code>dask</code></a>. It may or may not be faster, you will have to test it. The usage is very similar to <code>pandas</code>, except that the computations are only performed once committed to with the call to <code>compute()</code>.</p>\n\n<p>First, to install <code>dask</code>:</p>\n\n<pre><code>pip install dask[dataframe] --upgrade\n</code></pre>\n\n<p>Then for the actual usecase you mention, finding a specific <code>gi</code> in the table:</p>\n\n<pre><code>from dask import dataframe\n\ndf = dataframe.read_csv(\"test_file.map\", sep=\"\\t\")\ndf[df.gi == 7184].compute()\n# accession accession.version taxid gi\n# 0 V00184 V00184.1 44689 7184\n</code></pre>\n\n<p>In the call to <code>dataframe.read_csv</code> you can set it to <a href=\"http://docs.dask.org/en/latest/dataframe-api.html#dask.dataframe.read_csv\" rel=\"nofollow noreferrer\">read the file in blocks</a> if needed, e.g. in 25MB chunks:</p>\n\n<pre><code>df = dataframe.read_csv(\"test_file.map\", sep=\"\\t\", blocksize=25e6)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-24T15:13:22.783", "Id": "423017", "Score": "1", "body": "Thank you !\nI've tried dask and it wasn't faster for this particular case but It seems like I could use it somewhere else.\n\nSomething I noticed is the PRIMARY KEY statement, removing it seemed to speed up the insertion. However SQLite3 does not provide an `ALTER TABLE ADD CONSTRAINT` functionality. I'm trying with Postgresql to see if adding the constraint afterwards leads to any significant improvements" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-23T14:11:09.650", "Id": "217962", "ParentId": "217951", "Score": "3" } } ]
{ "AcceptedAnswerId": "217962", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-23T12:10:24.230", "Id": "217951", "Score": "4", "Tags": [ "python", "sqlite" ], "Title": "Insert into SQLite3 database" }
217951
<p>I'm currently writing an API to work with Bioinformatic SAM records. Here's an example of one:</p> <p><code>SBL_XSBF463_ID:3230017:BCR1:GCATAA:BCR2:CATATA/1:vpe 97 hs07 38253395 3 30M = 38330420 77055 TTGTTCCACTGCCAAAGAGTTTCTTATAAT EEEEEEEEEEEEAEEEEEEEEEEEEEEEEE PG:Z:novoalign AS:i:0 UQ:i:0 NM:i:0 MD:Z:30 ZS:Z:R NH:i:2 HI:i:1 IH:i:1</code></p> <p>Each piece of information separated by a tab is it's own field and corresponds to some type of data.</p> <p>Now, it's important to note that these files get BIG (10's of GB) and so splitting each one as soon as it's instantiated in some kind of POJO would be inefficient. </p> <p>Hence, I've decided to create an object with a lazy loading mechanism. Only the original string is stored until one of the fields is requested by some calling code. This should minimise the amount of work done when the object is created, as well as minimise the amount of memory taken by the objects. </p> <p>Here's my attempt: </p> <pre><code>/** Class for storing and working with sam formatted DNA sequence. * * Upon construction, only the String record is stored. * All querying of fields is done on demand, to save time. * */ public class SamRecord implements Record { private final String read; private String id = null; private int flag = -1; private String referenceName = null; private int pos = -1; private int mappingQuality = -1; private String cigar = null; private String mateReferenceName = null; private int matePosition = -1; private int templateLength = -1; private String sequence = null; private String quality = null; private String variableTerms = null; private final static String REPEAT_TERM = "ZS:Z:R"; private final static String MATCH_TERM = "ZS:Z:NM"; private final static String QUALITY_CHECK_TERM = "ZS:Z:QC"; /** Simple constructor for the sam record * @param read full read */ public SamRecord(String read) { this.read = read; } public String getRead() { return read; } /** * {@inheritDoc} */ @Override public String getId() { if(id == null){ id = XsamReadQueries.findID(read); } return id; } /** * {@inheritDoc} */ @Override public int getFlag() throws NumberFormatException { if(flag == -1) { flag = Integer.parseInt(XsamReadQueries.findElement(read, 1)); } return flag; } /** * {@inheritDoc} */ @Override public String getReferenceName() { if(referenceName == null){ referenceName = XsamReadQueries.findReferneceName(read); } return referenceName; } /** * {@inheritDoc} */ @Override public int getPos() throws NumberFormatException{ if(pos == -1){ pos = Integer.parseInt(XsamReadQueries.findElement(read, 3)); } return pos; } /** * {@inheritDoc} */ @Override public int getMappingQuality() throws NumberFormatException { if(mappingQuality == -1){ mappingQuality = Integer.parseInt(XsamReadQueries.findElement(read, 4)); } return mappingQuality; } /** * {@inheritDoc} */ @Override public String getCigar() { if(cigar == null){ cigar = XsamReadQueries.findCigar(read); } return cigar; } /** * {@inheritDoc} */ @Override public String getMateReferenceName() { if(mateReferenceName == null){ mateReferenceName = XsamReadQueries.findElement(read, 6); } return mateReferenceName; } /** * {@inheritDoc} */ @Override public int getMatePosition() throws NumberFormatException { if(matePosition == -1){ matePosition = Integer.parseInt(XsamReadQueries.findElement(read, 7)); } return matePosition; } /** * {@inheritDoc} */ @Override public int getTemplateLength() throws NumberFormatException { if(templateLength == -1){ templateLength = Integer.parseInt(XsamReadQueries.findElement(read, 8)); } return templateLength; } /** * {@inheritDoc} */ @Override public String getSequence() { if(sequence == null){ sequence = XsamReadQueries.findBaseSequence(read); } return sequence; } /** * {@inheritDoc} */ @Override public String getQuality() { if(quality == null){ quality = XsamReadQueries.findElement(read, 10); } return quality; } /** * {@inheritDoc} */ @Override public boolean isRepeat() { return read.contains(REPEAT_TERM); } /** * {@inheritDoc} */ @Override public boolean isMapped() { return !read.contains(MATCH_TERM); } /** * {@inheritDoc} */ @Override public String getVariableTerms() { if(variableTerms == null){ variableTerms = XsamReadQueries.findVariableRegionSequence(read); } return variableTerms; } /** * {@inheritDoc} */ @Override public boolean isQualityFailed() { return read.contains(QUALITY_CHECK_TERM); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; SamRecord samRecord = (SamRecord) o; return Objects.equals(read, samRecord.read); } @Override public int hashCode() { return Objects.hash(read); } @Override public String toString() { return read; } } </code></pre> <p>The fields are returned by static methods in a helper class which retrieve them by looking at where the tab characters are. i.e. <code>flag = Integer.parseInt(XsamReadQueries.findElement(read, 1));</code></p> <p>Below is the <code>XsamReadQuery</code> class</p> <pre><code>/** * Non-instantiable utility class for working with Xsam reads */ public final class XsamReadQueries { // Suppress instantiation private XsamReadQueries() { throw new AssertionError(); } /** finds the position of the tab directly before the start of the variable region * @param read whole sam or Xsam read to search * @return position of the tab in the String */ public static int findVariableRegionStart(String read){ int found = 0; for(int i = 0; i &lt; read.length(); i++){ if(read.charAt(i) == '\t'){ found++; if(found &gt;= 11 &amp;&amp; i+1 &lt; read.length() &amp;&amp; (read.charAt(i+1) != 'x' &amp;&amp; read.charAt(i+1) != '\t')){ //guard against double-tabs return i + 1; } } } return -1; } /** Attempts to find the library name from SBL reads * where SBL reads have the id SBL_LibraryName_ID:XXXXX * if LibraryName end's with a lower case letter, the letter will be removed. * if SBL_LibID is not valid, return the full ID. * @param ID or String to search. * @return Library name with lower case endings removed */ public static String findLibraryName(String ID){ if(!ID.startsWith("SBL")) return ""; try { int firstPos = XsamReadQueries.findPosAfter(ID, "_"); int i = firstPos; while (ID.charAt(i) != '_' &amp;&amp; ID.charAt(i) != '\t') { i++; } String library = ID.substring(firstPos, i); char lastChar = library.charAt(library.length()-1); if(lastChar &gt;= 97 &amp;&amp; lastChar &lt;= 122){ library = library.substring(0, library.length()-1); } return library; }catch (Exception e){ int i = 0; while(ID.charAt(i) != '\t'){ i++; if(i == ID.length()){ break; } } return ID.substring(0, i); } } /** Returns the ID from the sample * @param sample Xsam read * @return ID */ public static String findID(String sample){ return findElement(sample, 0); } /** Returns the phred score from the sample * @param sample Xsam read * @return phred string */ public static String findPhred(String sample){ return findElement(sample, 10); } /** * Returns the cigar from the xsam read * * @param sample read * @return cigar string */ public static String findCigar(String sample) { return findElement(sample, 5); } /** * Returns the bases from the xsam read * * @param sample read * @return base string */ public static String findBaseSequence(String sample) { return findElement(sample, 9); } /** * finds the n'th element in the tab delimited sample * i.e findElement(0) returns one from "one\ttwo" * 0 indexed. * * @param sample String to search * @param element element to find * @return found element or "" if not found */ public static String findElement(String sample, int element) { boolean tabsFound = false; int i = 0; int firstTab = 0; int secondTab = 0; int tabsToSkip = element - 1 &gt;= 0 ? element - 1 : 0; int skippedTabs = 0; if (element == 0) { while (sample.charAt(i) != '\t') { i++; } return sample.substring(0, i); } else { while (!tabsFound) { if (sample.charAt(i) != '\t') { i++; } else { if (skippedTabs == tabsToSkip) { if (firstTab == 0) { firstTab = i; } else { secondTab = i; tabsFound = true; } } else { skippedTabs++; } i++; } } } return sample.substring(firstTab + 1, secondTab); } /** finds the variable region past the quality * @param sample sam or Xsam record string * @return variable sequence or empty string */ public static String findVariableRegionSequence(String sample){ int start = findVariableRegionStart(sample); if(start == -1) return ""; return sample.substring(findVariableRegionStart(sample)); } /** finds the xL field * @param sample String to search * @return position if found, '\0' (null) value if not. */ public static int findxLField(String sample) { int chartStart = findPosAfter(sample, "\txL:i:"); if (chartStart == -1) { return -1; //return -1 if not found. } int i = chartStart; while (sample.charAt(i) != '\t') { i++; } return Integer.parseInt(sample.substring(chartStart, i)); } /** finds the xR field * @param sample String to search * @return position if found, '\0' (null) value if not. */ public static int findxRField(String sample) { int chartStart = findPosAfter(sample, "\txR:i:"); if (chartStart == -1) { return '\0'; //return NULL if not found. } int i = chartStart; while (sample.charAt(i) != '\t') { i++; } return Integer.parseInt(sample.substring(chartStart, i)); } /** finds the xLSeq field * @param sample String to search * @return String if found, empty string if not. */ public static Optional&lt;String&gt; findxLSeqField(String sample) { int charStart = findPosAfter(sample, "\txLseq:i:"); if (charStart == -1) { return Optional.empty(); //return NULL if not found. } int i = charStart; while (sample.charAt(i) != '\t') { i++; } return Optional.of(sample.substring(charStart, i)); } /** finds the reference name field * @param sample String to search * @return String if found, empty string if not. */ public static String findReferneceName(String sample) { //should always appear between the second and third tabs boolean tabsFound = false; int i = 0; int secondTab = 0; int thirdTab = 0; boolean skippedFirstTab = false; while (!tabsFound) { if (sample.charAt(i) != '\t') { i++; } else { if (skippedFirstTab) { if (secondTab == 0) { secondTab = i; } else { thirdTab = i; tabsFound = true; } } skippedFirstTab = true; i++; } } if(sample.substring(secondTab + 1, thirdTab).contains("/")){ String[] split = sample.substring(secondTab + 1, thirdTab).split("/"); return split[split.length-1]; } return sample.substring(secondTab + 1, thirdTab); } /** * Finds the needle in the haystack, and returns the position of the single next digit. * * @param haystack The string to search * @param needle String field to search on. * @return position of the end of the needle */ private static int findPosAfter(String haystack, String needle) { int hLen = haystack.length(); int nLen = needle.length(); int maxSearch = hLen - nLen; outer: for (int i = 0; i &lt; maxSearch; i++) { for (int j = 0; j &lt; nLen; j++) { if (haystack.charAt(i + j) != needle.charAt(j)) { continue outer; } } // If it reaches here, match has been found: return i + nLen; } return -1; // Not found } } </code></pre> <p>My question is, are there are any drawbacks to this approach? Or any alternative way that might be more effective?</p> <p>Thanks in advance,</p> <p>Sam</p> <p>Edit: </p> <p>Instantiating code:</p> <pre><code>public interface RecordFactory&lt;T extends Record&gt; { T createRecord(String recordString); } </code></pre> <p>Implementing it like:</p> <pre><code>private RecordFactory&lt;SamRecord&gt; samRecordFactory = SamRecord::new </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-23T13:47:45.670", "Id": "421833", "Score": "0", "body": "Is this class, or could this class, be used in a multithreaded scenario?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-23T13:48:57.270", "Id": "421834", "Score": "0", "body": "It will be, yes. However, it's unlikely to be shared between threads. It's more likely that collections of these records will be handed off to separate workers." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-23T14:41:14.477", "Id": "421843", "Score": "0", "body": "0. Do you have an actual, tested performance issue, or are you guessing at a potential problem? 1. What are you trying to minimize, execution time or memory footprint?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-23T15:09:23.987", "Id": "421856", "Score": "0", "body": "Also, are you able/willing to share the code that instantiates `SamRecord`s?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-24T12:21:52.433", "Id": "422984", "Score": "0", "body": "Hi @EricStein. Sure thing, but it's just a short factory method using generics (since `SamRecord` extends from `Record` - and I also have a few other types that extend `Record` too.) I know from past experience that this is a performance issue, since these files have 100's of millions of records. When I split the file, and hand the records to workers, I need to do as little as possible with the record themselves. The software using this API most likely wont need *every* detail of the record at one time" } ]
[ { "body": "<h2>Performance</h2>\n<p>There is one thing that I believe could increase the performance of your application.</p>\n<p>You often call <code>findElement</code>, which goes through the SAM record every time.</p>\n<p>By loading a record, you are pretty certain that you will at least access it once.</p>\n<p>At some point, maybe when creating the class, or when accessing the first property for the first time, you should &quot;index&quot; your SAM record.</p>\n<p>Go through the whole file once and keep an array of where the tabs are. This way, if your code ends up calling :</p>\n<pre><code>XsamReadQueries.findElement(read, 1)\nXsamReadQueries.findElement(read, 2)\nXsamReadQueries.findElement(read, 3)\n</code></pre>\n<p>The calls to the second and third method would be much faster than they are now.</p>\n<p>To do this, you could add a method to <code>XsamReadQueries</code> names something like <code>IndexTabs</code>, that would return an array of ints.</p>\n<p>If you want more insight as to how to do this, you can write a comment and I'll add more information, but I'm pretty sure this would help you.</p>\n<h2>Code style</h2>\n<p>There are one of two things that are bothering me in your code with regards to clarity and future maintenance.</p>\n<p>You have methods named <code>findPhred</code>, which call <code>findElement</code> , but in your <code>SamRecord</code> sometimes you call <code>findElement</code> and something a specific <code>find*</code>, which is basically the same code. You should decide on one way to do things, either have specific methods for each field in the <code>XsamReadQueries</code> or keep only the <code>findElement</code> method.</p>\n<p>Finally, you could consider using an <code>enum</code> for the <code>element</code> parameter of the <code>findElement</code> method.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-23T16:00:32.593", "Id": "421876", "Score": "1", "body": "Hi @IEatBagels, thanks for the answer. Indexing is a really good idea, I'll definitely look to implement that. I agree with the find* notation - It's partially as I'm halfway through coding the API and wanted some feedback before committing to one way or the other. The enum's a good idea too, it'll definitely make it more readable!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-23T14:13:27.273", "Id": "217963", "ParentId": "217955", "Score": "5" } } ]
{ "AcceptedAnswerId": "217963", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-23T12:45:50.580", "Id": "217955", "Score": "4", "Tags": [ "java", "bioinformatics", "lazy" ], "Title": "Lazy Loading a Bioinformatic SAM record" }
217955
<p>I have been following along the book 'The C Programming Language' 2nd edition by Kernighan and Ritchie. The below code is an exercise from the book. What I am confused about in this code is the Character array 'line'. It is a local variable so I don't understand how the value is changing when it is used as an argument in the 'get_line' function. </p> <pre><code>/******************************* * Author: * * Date: 4/22/2019 * * Purpose: Book exercise * *******************************/ #include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #define MAX_LINE 1000 int get_line(char line[], int maxline); void copy(char to[], char from[]); /*Print longest input line*/ int main() { int len; //Current line length int max; //Maximum length seen so far char line[MAX_LINE]; //Current input line char longest[MAX_LINE]; //Longest line saved here max = 0; //While input length is greater than 0 while((len = get_line(line, MAX_LINE)) &gt; 0) { //If current string is longer than max if (len &gt; max) { max = len; //Assign new max value copy(longest, line); //Replace longest string value with current string } } if (max &gt; 0) { printf("%s", longest); } return 0; } int get_line(char s[], int lim) { int c, i; /*i = 0; i less than limit - 1 *and* input is not EOF *and* input is not enter key */ for (i=0; i&lt;lim - 1 &amp;&amp; (c=getchar())!=EOF &amp;&amp; c!='\n'; i++) { s[i] = c; // input array position i is = input } //Once enter key is hit if (c == '\n') { s[i] = c; //Add enter key '\n' onto array i++; //Incr i so that last char can be '\0' later } s[i] = '\0'; //The last spot on char array is '\0' return i; } void copy(char to[], char from[]) { int i; i = 0; //Assign from[i] to to[i] until null terminator while((to[i] = from[i]) != '\0') { i++; } } </code></pre> <p>For example if I had a variable in the main routine</p> <pre><code>int add_num(int num1); main() { int x = 5; add_num(x); printf("%d", x); } int add_num(int num1) { num1 += 5; return num1; } </code></pre> <p>x would still remain equal to 5 unless I did:</p> <pre><code>x = add_num(x); </code></pre> <p>then x would equal 10.</p> <p>So how does the line character array change when the function that it's used in returns 'i'? Where I is the length of the string entered.</p> <p>Sorry if this was a little long, but I wanted to explain myself clearly.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-23T15:05:22.097", "Id": "421854", "Score": "2", "body": "This question is off-topic for 2 reasons, the first is it isn't asking for a code review it is asking a \"How To Question\". The second reason is that you aren't the author of most of the code. Please see \"How to I ask a good question?\" and \"What types of questions should I avoid asking\" at https://codereview.stackexchange.com/help." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-23T15:15:32.367", "Id": "421862", "Score": "1", "body": "Unfortunately this question doesn't reflect what the site is about. We review code that you have written for improvements. It's not on topic to ask for explanations of code that has been written by someone other than you. For more information, see the [help/on-topic]. Thanks." } ]
[ { "body": "<p>From the end of the chapter 1.8:</p>\n\n<blockquote>\n <p>\"When the name of an array is used as an argument, the value passed to\n the function is the location or address of the beginning of the array\n - there is no copying of array elements. By subscripting this value, the function can access and alter any element of the array\".</p>\n</blockquote>\n\n<p>So, when you pass array as an argument to a function, you don't create a local copy of array. Instead, you create a pointer (Chapter 5) and work with it as with an array. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-23T13:54:52.667", "Id": "421835", "Score": "0", "body": "Thanks for the explanation, I guess I probably should have read a little further in the book before I asked." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-23T15:07:34.063", "Id": "421855", "Score": "2", "body": "Your answer is a good one, but the question is off-topic." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-23T13:47:27.033", "Id": "217960", "ParentId": "217959", "Score": "-1" } } ]
{ "AcceptedAnswerId": "217960", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-23T13:31:00.457", "Id": "217959", "Score": "0", "Tags": [ "c" ], "Title": "Beginning C character array explanation" }
217959
<p>Minimum viable test program:</p> <pre><code>class Program { private static List&lt;Param&gt; paramList; private class Param { public string xmlName; public double scalingFactor; public double Value { get; set; } public Param( string xmlName, double scalingFactor) { this.xmlName = xmlName; this.scalingFactor = scalingFactor; } } private static void UpdateParams(XDocument xDoc) { IEnumerable&lt;Param&gt; filteredParamList; foreach (XElement xElement in xDoc.Root.Elements()) { filteredParamList = paramList.Where(param =&gt; param.xmlName == xElement.Name.LocalName); if (filteredParamList != null &amp;&amp; filteredParamList.Any()) { filteredParamList.Single().Value = double.Parse(xElement.Value) * filteredParamList.Single().scalingFactor; } } } static void Main(string[] args) { paramList = new List&lt;Param&gt; { new Param("paramA",1), new Param("paramB",.5), new Param("paramC",.01) }; /* For testing, this XDocument is hard coded here. */ UpdateParams(XDocument.Parse("&lt;root&gt;&lt;paramA&gt;121&lt;/paramA&gt;&lt;paramB&gt;100&lt;/paramB&gt;&lt;paramC&gt;197&lt;/paramC&gt;&lt;/root&gt;")); foreach(Param param in paramList) { Console.WriteLine("Name: {0} Value: {1}", param.xmlName, param.Value); } Console.Read(); } } </code></pre> <p>Let's focus on UpdateParams. So I have an XDoc that has a root and values. Looks like this:</p> <pre><code>&lt;root&gt; &lt;paramA&gt;121&lt;/paramA&gt; &lt;paramB&gt;100&lt;/paramB&gt; &lt;paramC&gt;105&lt;/paramC&gt; ... &lt;/root&gt; </code></pre> <p>I have a <code>List</code> of my <code>param</code> objects with an <code>xmlName</code> field which matches my XML key's. The <code>xmlName</code> of each <code>Param</code> object in my list will be unique; I'm manually creating every <code>Param</code> class in the main class's constructor (or in this test program, the main function). For context, the param objects will eventually have UI/WPF bindings from <code>Value</code> to textboxes or other UI elements as needed. For each key in the XML, i want to find the matching param object from my list, and fill in the <code>Value</code> field. If there's something weird in my <code>XDocument</code> that doesn't match my object list, I want to ignore it (and not throw an exception). </p> <p>Is there a simpler/better way to write the parsing? Seems a little verbose, and i don't like that I have that extra <code>IEnumerable filteredParamList</code> just to work around null checking.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-23T15:12:07.910", "Id": "421857", "Score": "1", "body": "Using `.Single()` is usually very dangours. Is it guaranteed that there will be only single match? I'd be great if you could post the rest of the code too. There are some undefined variables." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-23T15:27:30.003", "Id": "421870", "Score": "0", "body": "Yep, I can guarantee that `xmlName` will be unique through the entire paramList. If `.Any()` returns true, `.Single()` will pass." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-23T15:41:28.450", "Id": "421872", "Score": "0", "body": "As @t3chb0t indicated it would be better if you could post more of the code to provide context." } ]
[ { "body": "<p>I'm going to revew only this part as I think the rest of it is just for demonstration purposes.</p>\n\n<blockquote>\n<pre><code>private static void UpdateParams(XDocument xDoc)\n{\n IEnumerable&lt;Param&gt; filteredParamList;\n foreach (XElement xElement in xDoc.Root.Elements())\n {\n filteredParamList = paramList.Where(param =&gt; param.xmlName == xElement.Name.LocalName);\n if (filteredParamList != null &amp;&amp; filteredParamList.Any())\n {\n filteredParamList.Single().Value = double.Parse(xElement.Value) * filteredParamList.Single().scalingFactor;\n }\n }\n}\n</code></pre>\n</blockquote>\n\n<ul>\n<li><p>Try to avoid writing methods like this one, where one of the parameters is some <code>static</code> field. This makes it very difficult to test because of the external dependency. If possible you should pass the parameter as anoter argument. I had a hard time understanding your code.</p></li>\n<li><p>Try to also avoid modifying methods parameters like you do here with the <code>paramList</code>. It's usually much better to return a new result. Such methods are called <a href=\"https://www.sitepoint.com/functional-programming-pure-functions/\" rel=\"nofollow noreferrer\">pure methods</a> and are much easier to test and to maintain. Modifying global objects can make debugging very painful.</p></li>\n<li><p>Use the <em>smallest</em> possible type for parameters (or the most general/abstract). This means, your method doesn't need the <code>XDocument</code>, it can do its job just fine with an <code>IEnumerable&lt;XElement&gt;</code>.</p></li>\n<li><p>Choose more meaningful method names. <code>UpdateParams</code> is too general and doesn't say anything about what is going to be updated.</p></li>\n<li><p>You neither need the <code>foreach</code>, nor <code>Where</code>, nor <code>Any</code>, nor <code>Single</code>, nor the <code>null</code> check. All this can be replaced by a much nicer <code>join</code>.</p></li>\n</ul>\n\n<hr>\n\n<p>This is how it could look like after refactoring:</p>\n\n<pre><code>private static IEnumerable&lt;Param&gt; ScaleParameterValues\n(\n IEnumerable&lt;XElement&gt; elements, \n IEnumerable&lt;Param&gt; parameters\n)\n{\n return\n from xe in elements\n join p in parameters on xe.Name.LocalName equals p.xmlName\n select new Param(p.xmlName, p.scalingFactor) \n { \n Value = p.scalingFactor * double.Parse(xe.Value) \n };\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-24T14:08:14.637", "Id": "423001", "Score": "0", "body": "That makes perfect sense! I'm obviously new to C# and Linq, it didn't click to me that linq gives me practically everything from sql (including joins)." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-24T13:43:27.927", "Id": "219020", "ParentId": "217968", "Score": "3" } } ]
{ "AcceptedAnswerId": "219020", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-23T15:03:00.203", "Id": "217968", "Score": "2", "Tags": [ "c#", "linq", "xml" ], "Title": "Parse through an XDocument efficiently and match values to matching object" }
217968
<p>I decided to implement the round robin algorithm in Python. My code takes a list of teams as input and prints the schedule. </p> <p>This is my first try to write something by my own after taking some online courses, so I am absolutely sure that this code must be significantly improved. </p> <p>Here it is:</p> <pre><code>import random def simulate_draw(teams): if len(teams) % 2 == 0: simulate_even_draw(teams) else: simulate_odd_draw(teams) def simulate_even_draw(teams): dic = {} for i in range(len(teams)): dic[i] = teams[i] games = [] arr1 = [i+1 for i in range(int(len(teams)/2))] arr2 = [i+1 for i in range(int(len(teams)/2), len(teams))][::-1] for i in range(len(teams)-1): arr1.insert(1, arr2[0]) arr2.append(arr1[-1]) arr2.remove(arr2[0]) arr1.remove(arr1[-1]) zipped = list(zip(arr1, arr2)) games.append(zipped) zipped = [] for game in games: for gm in list(game): r = random.sample(gm, len(gm)) print(dic[r[0]-1] + ' plays ' + dic[r[1]-1]) def simulate_odd_draw(teams): dic = {} for i in range(len(teams)): dic[i] = teams[i] dic[i+1] = '' games = [] arr1 = [i+1 for i in range(int((len(teams)+1)/2))] arr2 = [i+1 for i in range(int((len(teams)+1)/2), len(teams)+1)][::-1] for i in range(len(teams)): arr1.insert(1, arr2[0]) arr2.append(arr1[-1]) arr2.remove(arr2[0]) arr1.remove(arr1[-1]) zipped = list(zip(arr1, arr2)) games.append(zipped) zipped = [] for game in games: for gm in list(game): r = random.sample(gm, len(gm)) if len(teams)+1 not in r: print(dic[r[0]-1] + ' plays ' + dic[r[1]-1]) </code></pre> <p>I think that big blocks of code that largely repeat themselves inside 2 functions may be united in one function, but not sure how to implement it. </p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-23T15:18:13.863", "Id": "421864", "Score": "0", "body": "I think your code is missing an entry point (`if __name__ == \"__main__\":`) because it shouldn't run in it's current format. Can you fix? Verify by copying then pasting into a new file and running that." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-23T16:40:38.507", "Id": "421879", "Score": "0", "body": "@C.Harley This seems to be a lib, as such, I don't see the necessity for an entry point. You can call `simulate_draw` with a list of names of your liking if you want to test it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-24T05:41:32.283", "Id": "422937", "Score": "0", "body": "@Mathias Ettinger - aren't we here to help improve fellow developers? Without any tests or data nor a clear entry point even if it was library, this wouldn't fly within my team." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-24T06:02:23.067", "Id": "422940", "Score": "0", "body": "@C.Harley Well then write an answer pointing to the lack of tests, no need to require an entry point for the question when it's not required." } ]
[ { "body": "<p><strong>Making the code testable and tested</strong></p>\n\n<p>The first step to improve your code is to try to make it testable. By doing so, you usually have to deal with <a href=\"https://en.wikipedia.org/wiki/Separation_of_concerns\" rel=\"noreferrer\">Separation of Concerns</a>: in your case, you have to split the logic doing the output from the logic computing games. The easiest way to do so it to rewrite slightly the <code>simulate_XXX</code> functions to return values instead of writing them.</p>\n\n<p>Once it it done, you can easily write tests for the function computing the games (in order to make this easier to implement, I've extracted out the randomising part as well).</p>\n\n<p>At this stage, we have something like:</p>\n\n<pre><code>import random\n\ndef simulate_draw(teams):\n \"\"\"Return the list of games.\"\"\"\n if len(teams) % 2 == 0:\n return simulate_even_draw(teams)\n else:\n return simulate_odd_draw(teams)\n\ndef simulate_even_draw(teams):\n \"\"\"Return the list of games.\"\"\"\n matches = []\n dic = {}\n for i in range(len(teams)):\n dic[i] = teams[i]\n\n games = []\n arr1 = [i+1 for i in range(int(len(teams)/2))]\n arr2 = [i+1 for i in range(int(len(teams)/2), len(teams))][::-1]\n\n for i in range(len(teams)-1):\n arr1.insert(1, arr2[0])\n arr2.append(arr1[-1])\n arr2.remove(arr2[0])\n arr1.remove(arr1[-1])\n zipped = list(zip(arr1, arr2))\n games.append(zipped)\n zipped = [] \n\n for game in games:\n for gm in list(game):\n r = gm # remove randomness for now - random.sample(gm, len(gm))\n a, b = dic[r[0]-1], dic[r[1]-1]\n matches.append((a, b))\n # print(a + ' plays ' + b)\n return matches\n\ndef simulate_odd_draw(teams):\n \"\"\"Return the list of games.\"\"\"\n matches = []\n dic = {}\n for i in range(len(teams)):\n dic[i] = teams[i]\n dic[i+1] = ''\n games = []\n arr1 = [i+1 for i in range(int((len(teams)+1)/2))]\n arr2 = [i+1 for i in range(int((len(teams)+1)/2), len(teams)+1)][::-1]\n for i in range(len(teams)):\n arr1.insert(1, arr2[0])\n arr2.append(arr1[-1])\n arr2.remove(arr2[0])\n arr1.remove(arr1[-1])\n zipped = list(zip(arr1, arr2))\n games.append(zipped)\n zipped = [] \n for game in games:\n for gm in list(game):\n r = gm # remove randomness for now - random.sample(gm, len(gm))\n if len(teams)+1 not in r:\n a, b = dic[r[0]-1], dic[r[1]-1]\n matches.append((a, b))\n # print(a + ' plays ' + b)\n return matches\n\n\ndef displays_simulated_draws(teams):\n \"\"\"Print the list of games.\"\"\"\n for gm in simulate_draw(teams):\n a, b = random.sample(gm, len(gm))\n print(a + ' plays ' + b)\n\n\ndef test_simulate_draw():\n \"\"\"Small tests for simulate_draw.\"\"\"\n # TODO: Use a proper testing framework\n TESTS = [\n ([], []),\n (['A'], []),\n (['A', 'B', 'C', 'D'], [('A', 'C'), ('D', 'B'), ('A', 'B'), ('C', 'D'), ('A', 'D'), ('B', 'C')]),\n (['A', 'B', 'C', 'D', 'E'], [('A', 'E'), ('B', 'C'), ('A', 'D'), ('E', 'C'), ('A', 'C'), ('D', 'B'), ('A', 'B'), ('D', 'E'), ('B', 'E'), ('C', 'D')]),\n ]\n for teams, expected_out in TESTS:\n # print(teams)\n ret = simulate_draw(teams)\n assert ret == expected_out\n\nif __name__ == '__main__':\n test_simulate_draw()\n displays_simulated_draws(['A', 'B', 'C', 'D'])\n</code></pre>\n\n<p>Now we can start improving the code in a safer way.</p>\n\n<p><strong>Remove what's not required</strong></p>\n\n<p><code>dic[i+1] = ''</code> is not required, we can remove it.</p>\n\n<p>Also, resetting <code>zipped</code> to the empty string is not required, we can remove it. Maybe we could get rid of <code>zipped</code> altogether.</p>\n\n<p>Finally, we call <code>for gm in list(game)</code> when <code>game</code> is already a list. We can remove the call to <code>list</code>.</p>\n\n<p><strong>Loop like a native</strong></p>\n\n<p>I highly recommend <a href=\"https://nedbatchelder.com/text/iter.html\" rel=\"noreferrer\">Ned Batchelder's talk \"Loop like a native\"</a> about iterators. One of the most simple take away is that whenever you're doing range(len(iterable)), you can probably do things in a better way: more concise, clearer and more efficient.</p>\n\n<p>In your case, we could have:</p>\n\n<pre><code>for i in range(len(teams)):\n dic[i] = teams[i]\n</code></pre>\n\n<p>replaced by</p>\n\n<pre><code>for i, team in enumerate(teams):\n dic[i] = team\n</code></pre>\n\n<p>And we could do:</p>\n\n<pre><code>for _ in teams:\n</code></pre>\n\n<p>instead of </p>\n\n<pre><code>for i in range(len(teams))\n</code></pre>\n\n<p>(Unfortunately, this can hardly be adapted to the \"even\" situation)</p>\n\n<p>Note: \"_\" is a usual variable names for values one does not plan to use.</p>\n\n<p><strong>Dict comprehension</strong></p>\n\n<p>The dictionnary initiation you perform via <code>dict[index] = value</code> in a loop could be done using the <a href=\"https://www.datacamp.com/community/tutorials/python-dictionary-comprehension\" rel=\"noreferrer\">Dictionnary Comprehension</a> syntactic sugar.</p>\n\n<p>Instead of:</p>\n\n<pre><code>dic = {}\nfor i, team in enumerate(teams):\n dic[i] = team\n</code></pre>\n\n<p>we you can write:</p>\n\n<pre><code>dic = {i: team for i, team in enumerate(teams)}\n</code></pre>\n\n<p>Now it is much more obvious, it also corresponds to:</p>\n\n<pre><code>dic = dict(enumerate(teams))\n</code></pre>\n\n<p>Finally, we can ask ourselves how we use this dictionnary: the answer is \"to get the team at a given index\". Do we really need a dictionnay for this ? I do not think so. We can get rid of the <code>dic</code> variable and use <code>teams</code> directly.</p>\n\n<p>At this stage, we have:</p>\n\n<pre><code>import random\n\ndef simulate_draw(teams):\n \"\"\"Return the list of games.\"\"\"\n if len(teams) % 2 == 0:\n return simulate_even_draw(teams)\n else:\n return simulate_odd_draw(teams)\n\ndef simulate_even_draw(teams):\n \"\"\"Return the list of games.\"\"\"\n matches = []\n games = []\n half_len = int(len(teams)/2)\n arr1 = [i+1 for i in range(half_len)]\n arr2 = [i+1 for i in range(half_len, len(teams))][::-1]\n for i in range(len(teams)-1):\n arr1.insert(1, arr2[0])\n arr2.append(arr1[-1])\n arr2.remove(arr2[0])\n arr1.remove(arr1[-1])\n games.append(list(zip(arr1, arr2)))\n for game in games:\n for gm in game:\n r = gm # remove randomness for now - random.sample(gm, len(gm))\n a, b = teams[r[0]-1], teams[r[1]-1]\n matches.append((a, b))\n # print(a + ' plays ' + b)\n return matches\n\ndef simulate_odd_draw(teams):\n \"\"\"Return the list of games.\"\"\"\n matches = []\n games = []\n half_len = int((len(teams)+1)/2)\n arr1 = [i+1 for i in range(half_len)]\n arr2 = [i+1 for i in range(half_len, len(teams)+1)][::-1]\n for i in range(len(teams)):\n arr1.insert(1, arr2[0])\n arr2.append(arr1[-1])\n arr2.remove(arr2[0])\n arr1.remove(arr1[-1])\n games.append(list(zip(arr1, arr2)))\n for game in games:\n for gm in game:\n r = gm # remove randomness for now - random.sample(gm, len(gm))\n if len(teams)+1 not in r:\n a, b = teams[r[0]-1], teams[r[1]-1]\n matches.append((a, b))\n # print(a + ' plays ' + b)\n return matches\n\n\ndef displays_simulated_draws(teams):\n \"\"\"Print the list of games.\"\"\"\n for gm in simulate_draw(teams):\n a, b = random.sample(gm, len(gm))\n print(a + ' plays ' + b)\n\n\ndef test_simulate_draw():\n \"\"\"Small tests for simulate_draw.\"\"\"\n # TODO: Use a proper testing framework\n TESTS = [\n ([], []),\n (['A'], []),\n (['A', 'B', 'C', 'D'], [('A', 'C'), ('D', 'B'), ('A', 'B'), ('C', 'D'), ('A', 'D'), ('B', 'C')]),\n (['A', 'B', 'C', 'D', 'E'], [('A', 'E'), ('B', 'C'), ('A', 'D'), ('E', 'C'), ('A', 'C'), ('D', 'B'), ('A', 'B'), ('D', 'E'), ('B', 'E'), ('C', 'D')]),\n ]\n for teams, expected_out in TESTS:\n # print(teams)\n ret = simulate_draw(teams)\n assert ret == expected_out\n\nif __name__ == '__main__':\n test_simulate_draw()\n displays_simulated_draws(['A', 'B', 'C', 'D'])\n</code></pre>\n\n<p><strong>The right tool for the task</strong></p>\n\n<p>The part:</p>\n\n<pre><code> arr2.remove(arr2[0])\n arr1.remove(arr1[-1])\n</code></pre>\n\n<p>could/should probably be written with pop:</p>\n\n<pre><code> arr2.pop(0)\n arr1.pop()\n</code></pre>\n\n<p>And now, these line can be merged with <code>arrXX.append(arrYYY[ZZ])</code>:</p>\n\n<pre><code>for i in range(len(teams)-1):\n arr1.insert(1, arr2.pop(0))\n arr2.append(arr1.pop())\n games.append(list(zip(arr1, arr2)))\n</code></pre>\n\n<p><strong>Removing useless steps</strong></p>\n\n<p>A loop is used to fill an array. Another one is used to iterate over the array. We could try to use a single loop to do everything (disclaimer: this is not always a good idea as far as readability goes).</p>\n\n<p>This removes the need for a few calls to <code>list</code>.</p>\n\n<p>At this stage, we have:</p>\n\n<pre><code>def simulate_even_draw(teams):\n \"\"\"Return the list of games.\"\"\"\n matches = []\n half_len = int(len(teams)/2)\n arr1 = [i+1 for i in range(half_len)]\n arr2 = [i+1 for i in range(half_len, len(teams))][::-1]\n for i in range(len(teams)-1):\n arr1.insert(1, arr2.pop(0))\n arr2.append(arr1.pop())\n for gm in zip(arr1, arr2):\n matches.append((teams[gm[0]-1], teams[gm[1]-1]))\n return matches\n\ndef simulate_odd_draw(teams):\n \"\"\"Return the list of games.\"\"\"\n matches = []\n half_len = int((len(teams)+1)/2)\n arr1 = [i+1 for i in range(half_len)]\n arr2 = [i+1 for i in range(half_len, len(teams)+1)][::-1]\n for i in range(len(teams)):\n arr1.insert(1, arr2.pop(0))\n arr2.append(arr1.pop())\n for gm in zip(arr1, arr2):\n if len(teams)+1 not in gm:\n matches.append((teams[gm[0]-1], teams[gm[1]-1]))\n return matches\n</code></pre>\n\n<p><strong>Better indices</strong></p>\n\n<p>You generate a list of indices using <code>i+1</code> and then use <code>val - 1</code> when you use them. You can make your life easier twice.</p>\n\n<p><strong>Iterable unpacking</strong></p>\n\n<p>Instead of using indices to get elements from an iterable with a know number of elements, you can use iterable unpacking.</p>\n\n<p>You'd get</p>\n\n<pre><code>def simulate_even_draw(teams):\n \"\"\"Return the list of games.\"\"\"\n half_len = int(len(teams)/2)\n arr1 = [i for i in range(half_len)]\n arr2 = [i for i in range(half_len, len(teams))][::-1]\n matches = []\n for i in range(len(teams)-1):\n arr1.insert(1, arr2.pop(0))\n arr2.append(arr1.pop())\n for a, b in zip(arr1, arr2):\n matches.append((teams[a], teams[b]))\n return matches\n\ndef simulate_odd_draw(teams):\n \"\"\"Return the list of games.\"\"\"\n half_len = int((len(teams)+1)/2)\n arr1 = [i for i in range(half_len)]\n arr2 = [i for i in range(half_len, len(teams)+1)][::-1]\n matches = []\n for i in range(len(teams)):\n arr1.insert(1, arr2.pop(0))\n arr2.append(arr1.pop())\n for a, b in zip(arr1, arr2):\n if len(teams) not in (a, b):\n matches.append((teams[a], teams[b]))\n return matches\n</code></pre>\n\n<p><strong>True divisions</strong></p>\n\n<p>Instead of using \"/\" and convert the float result to int, you can use \"//\" which is an integer division.</p>\n\n<p><strong>Other way to compute indices</strong></p>\n\n<p>We could write something like:</p>\n\n<pre><code>indices = list(range(len(teams)))\nhalf_len = len(indices)//2\narr1 = indices[:half_len]\narr2 = indices[:half_len-1:-1]\n</code></pre>\n\n<p>and</p>\n\n<pre><code>indices = list(range(len(teams)+1))\nhalf_len = len(indices)//2\narr1 = indices[:half_len]\narr2 = indices[:half_len-1:-1]\n</code></pre>\n\n<p>Altough, if we don't care about order, we could use the more direct:</p>\n\n<pre><code>arr1 = indices[:half_len]\narr2 = indices[half_len:]\n</code></pre>\n\n<p><strong>Remove the duplicated logic</strong></p>\n\n<p><a href=\"https://en.wikipedia.org/wiki/Don%27t_repeat_yourself\" rel=\"noreferrer\">Don't repeat yourself</a> is a principle of software development that you could easily apply here. Indeed, we have 2 functions that look very similar.</p>\n\n<p>This is trickier than expected and I have to go. I may continue another day.</p>\n\n<p><strong>Batteries included</strong></p>\n\n<p>The Python standard library contains many useful things. Among them, we have the very interesting module <code>itertools</code> which itself contains <a href=\"https://docs.python.org/2/library/itertools.html#itertools.combinations\" rel=\"noreferrer\">combinations</a> which is what you want.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-23T17:03:50.493", "Id": "217972", "ParentId": "217969", "Score": "9" } } ]
{ "AcceptedAnswerId": "217972", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-23T15:13:33.873", "Id": "217969", "Score": "7", "Tags": [ "python", "simulation" ], "Title": "Simulate round-robin tournament draw" }
217969
<p>I need to be able to access a number of different payment methods in a common list. They can be different methods - credit card, cheque, direct debit etc. The only common attributes are the payment method id and PaymentMethodEnum. I would then be casting the payment method to it's appropriate type to get the extended properties. Is this code arrangement the best way to achieve that?</p> <p>Update: I've added the enums. The usage for this is an MVC Website, and these payment details are effectively read only. The website shows different options based on the current payment method, and the other available methods that belong to a customer.</p> <pre><code>public class PaymentDetailBase { public PaymentDetailBase(string id, PaymentMethodEnum paymentMethod) { this.Id = id; this.PaymentMethod = paymentMethod; } public string Id { get; } public PaymentMethodEnum PaymentMethod { get; } } public class CardDetail : PaymentDetailBase { public CardDetail(string id, PaymentMethodEnum paymentMethod, string last4, DateTime expiry, PaymentCardTypeEnum cardType) : base(id, paymentMethod) { this.Last4 = last4; this.Expiry = expiry; this.CardType = cardType; } public string Last4 { get; } public DateTime Expiry { get; } public PaymentCardTypeEnum CardType { get; } } public class DirectDebitDetail : PaymentDetailBase { public DirectDebitDetail(string id, PaymentMethodEnum paymentMethod, string accountName, string routingNumber, string bankAccount, DirectDebitAccountTypeEnum accountType) : base(id, paymentMethod) { this.AccountName = accountName; this.RoutingNumber = routingNumber; this.BankAccount = bankAccount; this.AccountType = accountType; } public string AccountName { get; } public string RoutingNumber { get; } public string BankAccount { get; } public DirectDebitAccountTypeEnum AccountType { get; } } [Flags] public enum PaymentMethodEnum { [Description("NONE")] None = 0, [Description("Credit Card")] CreditCard = 1 &lt;&lt; 0, [Description("Direct Debit")] DirectDebit = 1 &lt;&lt; 1, [Description("Check")] Cheque = 1 &lt;&lt; 2, [Description("Invoice")] Invoice = 1 &lt;&lt; 3, [Description("Money Order")] MoneyOrder = 1 &lt;&lt; 4, [Description("Paper Invoice")] PaperInvoice = 1 &lt;&lt; 5 } public enum PaymentCardTypeEnum { [Description("Unknown")] Unknown, [Description("AMEX")] Amex, [Description("MASTERCARD")] MasterCard, [Description("DISCOVER")] Discover, [Description("VISA")] Visa } public enum BillingFrequencyEnum { [Description("Unknown")] Unknown, [Description("Annual")] Annual, [Description("Semi-annual")] SemiAnnual, [Description("Quarterly")] Quarterly, [Description("Bi-monthy")] BiMonthly, [Description("Ten months")] TenMonths, [Description("Monthly")] Monthly } public enum DirectDebitAccountTypeEnum { [Description("Unknown")] Unknown, [Description("Checking Account")] Checking, [Description("Savings Account")] Savings } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-23T17:23:56.833", "Id": "421885", "Score": "2", "body": "Please include your different enums" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-23T19:38:35.257", "Id": "421905", "Score": "1", "body": "Have you tested it and does it work?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-24T09:27:45.690", "Id": "422961", "Score": "1", "body": "I've added the enums" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-24T09:35:48.940", "Id": "422962", "Score": "0", "body": "@pacmaninbw no, it's a work in progress..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-24T11:52:49.073", "Id": "422977", "Score": "2", "body": "In such a case it's off-topic here as we require working code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-24T15:07:11.867", "Id": "423016", "Score": "0", "body": "@t3chb0t Why is it off-topic? It's not clear from the OPs response if it is in fact 'not working'. The \"no\" can be a response to just the \"Have you tested it\". The second clause, \"it's a work in progress\", also doesn't make it 'not working'. As all code that comes to Code Review is a WIP as the asker wants to improve it." } ]
[ { "body": "<p>I'm not in love with having an enum to know what base type to cast to. If you want to stick to it then I'll give you a couple of pointers then later I'll give you a couple more options to think about</p>\n\n<p>Make the base abstract and make the enum abstract</p>\n\n<pre><code>public abstract class PaymentDetailBase\n{\n protected PaymentDetailBase(string id)\n {\n this.Id = id;\n }\n\n public string Id { get; }\n\n public abstract PaymentMethodEnum PaymentMethod { get; }\n}\n</code></pre>\n\n<p>if you are going to cast based on the Enum then you don't want it being sent in the constructor. What if I sent in the wrong enum for the type</p>\n\n<p>Now classes the inherit from the base will be forced to fill in the type</p>\n\n<pre><code>public class CardDetail : PaymentDetailBase\n{\n public CardDetail(string id, string last4, DateTime expiry, PaymentCardTypeEnum cardType) : base(id)\n {\n this.Last4 = last4;\n this.Expiry = expiry;\n this.CardType = cardType;\n }\n\n public string Last4 { get; }\n\n public DateTime Expiry { get; }\n\n public PaymentCardTypeEnum CardType { get; }\n\n public override PaymentMethodEnum PaymentMethod =&gt; PaymentMethodEnum.CreditCard;\n}\n</code></pre>\n\n<p>I've worked with applications like this and I don't really care for the Enum. It violates the open/close principle. If I want another payment type I need to change the enum and some switch code that does hardcoded cast (yuck). And what are you saving? A switch statement instead of getting the base class and doing the AS statement and checking for null? </p>\n\n<p>Really when you run into this situation you need to think about your design. What in the outside needs to know about those extended properties. If everything then why cast to the base object in the first place just pass in the right class or you can try to make use of generics with constraints. </p>\n\n<p>Another option is if not a lot needs to know about the specific class then have the class do the operation you want done. For Example you need to just copy over those properties to an entity. Then aleave the base class abstract and make an abstract method like </p>\n\n<pre><code>public void UpdateEntity(PaymentEntity entity);\n</code></pre>\n\n<p>now each class need to implement the update entity and it knows about it's own properties. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-24T09:48:28.597", "Id": "422964", "Score": "0", "body": "Thank you. The rationale for using the base type and not an abstract was that there are several types of payment methods but only two are supported for now. By 'supported' I mean contain extended information. I though this would allow the unsupported types to just be instantiated as the PaymentDetailBase type directly. Perhaps this is a flawed idea. I like the override enum, which seems much better.\n\nI'm not entirely clear on what you mean about enum and switch vs cast, if the enum was dropped, wouldn't I then need to AS the object to all possible types just to determine the payment type?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-24T13:39:56.783", "Id": "422997", "Score": "0", "body": "Guess I should have been more clear. I don't care for the enum or using the AS. Without knowing what your classes need to do it's hard to say what the correct design is. But typically I do go with the option at the end. You can always inject dependency in the class to do the common stuff between all of the payment types and then there is no enum or casting and each class takes care of themselves allowing it to be extended without changing any code." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-23T21:05:36.617", "Id": "217988", "ParentId": "217973", "Score": "3" } } ]
{ "AcceptedAnswerId": "217988", "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-23T17:08:48.750", "Id": "217973", "Score": "0", "Tags": [ "c#", "casting" ], "Title": "Different payment details in a common list, to be casted" }
217973
<p>I'm trying to optimize a function in a process which is going to be run millions of times. The function is supposed to partition the vertices of a graph, which will be used to make a quotient graph. Theoretically, the process is:</p> <ol> <li>Input a graph, G</li> <li>For each vertex, v in G, we choose a random edge of v (the same edge can be chosen for two different vertices)</li> <li>We have a subgraph S, where we only use the edges chosen in (2)</li> <li>We partition our vertices by which connected component they are in</li> </ol> <p>Initially, I simply created S in NetworkX, but found that the process of creating a proper graph was unnecessarily slow. So next, I tried to recreate the bare-bones of the process where I locally created an adjacency dictionary and used that with the NetworkX documentation for finding connected components. Finally, I found it fastest to simply have a dictionary of which connected component each vertex is in, yet still it seems a bit redundant, as for each edge chosen, I need to update the dictionary for the entire connected component.</p> <p>My fastest version:</p> <pre class="lang-py prettyprint-override"><code>def sp3(G): nodes = list(G.nodes) P = [] dic = {} for v in nodes: dic[v] = frozenset([v]) for v in nodes: nb = random.choice(list(G.neighbors(v))) U = frozenset.union(dic[v],dic[nb]) for a in U: dic[a] = U for v in nodes: P.append(dic[v]) P = list(set(P)) return P </code></pre> <p>Slower version:</p> <pre><code>def sp1(G): nodes = list(G.nodes) dic = {v:set() for v in nodes} for v in nodes: nb = random.choice(list(G.neighbors(v))) dic[v].add(nb) dic[nb].add(v) P = list(CCbfs(dic)) return P def CCbfs(dic): seen = set() for v in dic.keys(): if v not in seen: c = frozenset(bfs(dic, v)) yield c seen.update(c) def bfs(dic,n): d = dic seen = set() nextlevel = {n} while nextlevel: thislevel = nextlevel nextlevel = set() for v in thislevel: if v not in seen: yield v seen.add(v) nextlevel.update(d[v]) </code></pre> <p>I've been using cProfile and got the following on a 2690 vertex, nearly maximal planar graph (in reality I'm working with ~600 vertex subgraphs of this graph, but for convenience I just ran it on the whole thing):</p> <pre class="lang-none prettyprint-override"><code> ncalls tottime percall cumtime percall filename:lineno(function) 1 0.000 0.000 99.996 99.996 {built-in method builtins.exec} 1 0.000 0.000 99.996 99.996 &lt;string&gt;:1(&lt;module&gt;) 1 1.083 1.083 99.996 99.996 Imp2.py:1201(SPit) 2500 12.531 0.005 52.974 0.021 Imp2.py:1108(sp1) 2500 22.591 0.009 45.939 0.018 Imp2.py:1085(sp3) 13450000 9.168 0.000 29.084 0.000 random.py:256(choice) 13450000 12.218 0.000 18.138 0.000 random.py:224(_randbelow) 768750 2.602 0.000 13.118 0.000 Imp2.py:149(CCbfs) 7491250 7.274 0.000 9.910 0.000 Imp2.py:156(bfs) 13450000 6.418 0.000 9.225 0.000 graph.py:1209(neighbors) 2500 6.728 0.003 6.728 0.003 Imp2.py:1110(&lt;dictcomp&gt;) 20988370 4.325 0.000 4.325 0.000 {method 'getrandbits' of '_random.Random' objects} 6725000 3.312 0.000 3.312 0.000 {method 'union' of 'frozenset' objects} 13455000 2.810 0.000 2.810 0.000 {built-in method builtins.iter} 20175000 2.541 0.000 2.541 0.000 {method 'add' of 'set' objects} 7491250 2.329 0.000 2.329 0.000 {method 'update' of 'set' objects} 13455000 1.780 0.000 1.780 0.000 {built-in method builtins.len} 13450000 1.595 0.000 1.595 0.000 {method 'bit_length' of 'int' objects} 6725000 0.640 0.000 0.640 0.000 {method 'append' of 'list' objects} 5000 0.029 0.000 0.041 0.000 graph.py:646(nodes) 5000 0.012 0.000 0.012 0.000 reportviews.py:167(__init__) 5000 0.006 0.000 0.009 0.000 reportviews.py:174(__iter__) 5000 0.003 0.000 0.006 0.000 reportviews.py:171(__len__) 2500 0.001 0.000 0.001 0.000 {method 'keys' of 'dict' objects} 1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects} </code></pre> <p>It seems like I spend so much time just going through the for loops in sp3... is there some way to fix this? (Also, I've been told to check if there's a faster implementation than <code>random.choice</code> when I'm using really small lists usually of size 6, give or take, so any insight on that is welcome.)</p> <p>Edit: here's something to test the code, in reality I'm using an adjacency matrix created from some text files but it's really messy and this should mostly capture the properties</p> <pre><code>import networkx as nx import random def SPit(m=25,n): G = nx.grid_2d_graph(m,m) i=0 while i&lt;n: x1 = sp1(G) x3 = sp3(G) i+=1 def sp3(G): nodes = list(G.nodes) P = [] dic = {} for v in nodes: dic[v] = frozenset([v]) for v in nodes: nb = random.choice(list(G.neighbors(v))) U = frozenset.union(dic[v],dic[nb]) for a in U: dic[a] = U for v in nodes: P.append(dic[v]) P = list(set(P)) return P def sp1(G): nodes = list(G.nodes) dic = {v:set() for v in nodes} for v in nodes: nb = random.choice(list(G.neighbors(v))) dic[v].add(nb) dic[nb].add(v) P = list(CCbfs(dic)) return P def CCbfs(dic): seen = set() for v in dic.keys(): if v not in seen: c = frozenset(bfs(dic, v)) yield c seen.update(c) def bfs(dic,n): d = dic seen = set() nextlevel = {n} while nextlevel: thislevel = nextlevel nextlevel = set() for v in thislevel: if v not in seen: yield v seen.add(v) nextlevel.update(d[v]) <span class="math-container">```</span> </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-23T17:37:21.153", "Id": "421891", "Score": "1", "body": "Can you give us testing code and/or a dataset to test `sp3`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-23T19:46:52.513", "Id": "421906", "Score": "1", "body": "This code still isn't runable to someone other than you. You will probably get better results if you include a block of code that tests what you want tested and can be copied and pasted and run without having to figure out all the imports and stuff." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-23T19:50:22.913", "Id": "421908", "Score": "0", "body": "updated, my bad" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-23T22:04:51.563", "Id": "421924", "Score": "0", "body": "No problem, Thanks for fixing it so quickly." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-23T22:18:27.790", "Id": "421925", "Score": "2", "body": "Take a look at the classic [Union-Find](https://algs4.cs.princeton.edu/15uf/) algorithm." } ]
[ { "body": "<p>I'm just going to review <code>sp3</code>.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> P = []\n &lt;snip 8 lines&gt;\n for v in nodes:\n P.append(dic[v])\n</code></pre>\n</blockquote>\n\n<p>It's generally preferable to declare your variables as near as possible to the first use. That way someone reading the code has to keep less information in their memory.</p>\n\n<p><code>P</code> is not an informative name. I would usually guess that it's short for <code>Point</code>, but that doesn't seem to fit.</p>\n\n<blockquote>\n<pre><code> for v in nodes:\n P.append(dic[v])\n P = list(set(P))\n return P\n</code></pre>\n</blockquote>\n\n<p>This could be shortened to</p>\n\n<pre><code> return list(set(dic.values()))\n</code></pre>\n\n<p>But it's not obvious why it's important to return a <code>list</code> rather than a <code>set</code>.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> dic = {}\n for v in nodes:\n dic[v] = frozenset([v])\n for v in nodes:\n nb = random.choice(list(G.neighbors(v)))\n U = frozenset.union(dic[v],dic[nb])\n for a in U:\n dic[a] = U\n</code></pre>\n</blockquote>\n\n<p>Again, <code>dic</code> is not a very informative name. I can see it's a dictionary from the declaration, but what does it <em>mean</em>? Perhaps <code>components</code> would be a better name?</p>\n\n<p>Again, I don't understand the point of conversion to <code>list</code>. <code>random.choice</code> is documented as accepting any sequence. If you've profiled and discovered that it's faster when passed a list, that's the kind of valuable information which should be captured in a comment.</p>\n\n<p>This algorithm is not very efficient. Wikipedia's article <a href=\"https://en.wikipedia.org/wiki/Disjoint-set_data_structure\" rel=\"nofollow noreferrer\">Disjoint-set data structure</a> contains pseudocode for a more efficient approach. Basically you replace the mapping to a set with a mapping to another vertex and build a tree. There are various optimisations which are simple to implement and harder to analyse but give an essentially linear time algorithm.</p>\n\n<p>NB if you can arrange for the vertices to be numbers from 0 to n-1 then you can replace the <code>dict</code> with a list, which should be slightly faster.</p>\n\n<hr>\n\n<blockquote>\n <p>Also, I've been told to check if there's a faster implementation than random.choice when I'm using really small lists usually of size 6, give or take, so any insight on that is welcome.</p>\n</blockquote>\n\n<p>I was expecting the answer to be no, but looking at the <a href=\"https://github.com/python/cpython/blob/master/Lib/random.py\" rel=\"nofollow noreferrer\">implementation of <code>random.choice</code></a> (and, in particular, <code>_randbelow_with_getrandbits</code>) I think that you probably can do better. Certainly it's worth profiling against an implementation rather more like <a href=\"http://hg.openjdk.java.net/jdk8/jdk8/jdk/file/tip/src/share/classes/java/util/Random.java#l386\" rel=\"nofollow noreferrer\">Java's nextInt(int)</a>.</p>\n\n<p>Basically, if you want a random number from <code>0</code> inclusive to <code>n</code> exclusive, Python finds the smallest power of two which is at least <code>n</code>, takes that many random bits, and tries again if the result is <code>n</code> or greater. When <code>n</code> is one more than a power of two it takes two tries on average. Java, on the other hand, always takes 31 random bits and calculates <span class=\"math-container\">\\$2^{31} \\bmod n\\$</span> to figure out the threshold at which to discard. So for <code>n=5</code> it does one expensive operation (<code>%</code>) but has an extremely low probability of needing to try again.</p>\n\n<p>Which approach is fastest probably depends on your CPU. Given that you know the statistics of your list sizes you could also consider taking the Java approach but pre-calculating a lookup table to do the <code>%</code> operations just once at start-up.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-24T15:57:15.357", "Id": "423032", "Score": "0", "body": "type(G.neighbors) is 'dict_keyiterator', which is why I make it a list. but otherwise your smaller comments definitely helped. currently I'm struggling to implement Union Find faster, I think it's because I need to keep track of the names of my nodes and I'm handling that wrong. once I've finally mustered up my best efforts on doing UF and the randomness, if I'm still having trouble, is it recommended I simply make an edit or a new post?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-24T16:14:59.860", "Id": "423036", "Score": "1", "body": "Don't edit the question to update the code. Making a new post is [one of your options](https://codereview.meta.stackexchange.com/a/1765/1402)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-25T16:25:46.133", "Id": "423214", "Score": "0", "body": "The reason python does random choice that way is that unlike Java's implementation, it is unbiased. For small numbers it doesn't matter much, but if for example you wanted to choose a random number between 1 and 1.5*2^30, java's approach would do a very bad job of evenly distributing the results." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-25T18:43:49.193", "Id": "423226", "Score": "0", "body": "@OscarSmith, no. Java's approach is also unbiased; it uses a different technique to Python to achieve that, which is arguably better for weak PRNGs because it uses all of the bits output by the PRNG. At a guess the reason for Python's approach is because it doesn't require special-casing for big integers." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-25T20:13:21.843", "Id": "423238", "Score": "0", "body": "I guess I don't understand what you mean by calculates `2^{31} mod n` to figure out the threshold at which to discard. Can you clarify what that means?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-25T21:37:23.537", "Id": "423252", "Score": "0", "body": "@OscarSmith, \\$2^{31} \\equiv 2 \\pmod 6\\$, so to pick a random number from 0 to 5 you take a random 31-bit integer; if it's greater than or equal to \\$2^{31} - 2\\$ then you discard it and loop; otherwise you return the number modulo 6." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-26T01:23:20.653", "Id": "423280", "Score": "0", "body": "Ok, that makes sense. Thanks" } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-24T08:46:47.903", "Id": "219004", "ParentId": "217975", "Score": "3" } } ]
{ "AcceptedAnswerId": "219004", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-23T17:29:03.190", "Id": "217975", "Score": "5", "Tags": [ "python", "performance", "graph" ], "Title": "Optimizing graph partitioning by connected components of generated subgraph" }
217975
<p>I am not a JS/TS Guru, so i wanted to ask if one could write this better.</p> <p>I needed a very primitive Full-Text-Search of some properties of an Object. What do you think?</p> <pre><code>export const search = &lt;T, K extends keyof T&gt;(term: string, objects: T[], keys: K[]): T[] =&gt; { const foundObjects = objects.filter(x =&gt; { for (const key of keys) { if (x.hasOwnProperty(key) === false) { continue; } const val = x[key]; if (typeof val === 'string' &amp;&amp; val.toLowerCase().includes(term)) { return true; } else { continue; } } return false; }); return foundObjects; }; </code></pre>
[]
[ { "body": "<p>You have a lot of code that is not needed.</p>\n\n<ul>\n<li><p>The two <code>continue</code> are not needed.</p></li>\n<li><p>Rather than assign the variable <code>foundObjects</code> the filtered result just return the result directly.</p></li>\n<li>The variable <code>val</code> that holds the property can be side stepped.</li>\n<li>Then the <code>hasOwnProperty</code> can be combined with the if statement</li>\n<li>Rather than use the for loop you can also use <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some\" rel=\"nofollow noreferrer\"><code>Array.some</code></a> to find if any item matches the search</li>\n</ul>\n\n<p>Thus you get</p>\n\n<pre><code>export const search = &lt;T, K extends keyof T&gt;(term: string, objects: T[], keys: K[]): T[] =&gt; {\n return objects.filter(x =&gt; \n keys.some(key =&gt; \n x.hasOwnProperty(key) &amp;&amp; \n typeof x[key] === 'string' &amp;&amp; \n x[key].toLowerCase().includes(term)\n )\n );\n};\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-23T21:44:54.643", "Id": "421922", "Score": "0", "body": "Thx. I learned something new. One small issue with your solution. (I had the same thats why this `val` variable is there). `x[key].toLowerCase()` throws a `Property 'toLowerCase' does not exist on type 'T[K]'` error. I know its a TS issue, but thats the only small \"issue\". Thx again." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-23T20:10:58.150", "Id": "217984", "ParentId": "217976", "Score": "2" } } ]
{ "AcceptedAnswerId": "217984", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-23T18:12:15.147", "Id": "217976", "Score": "2", "Tags": [ "search", "typescript" ], "Title": "Primitive full-text search on some properties of an object" }
217976
<p>I have two cases here:</p> <ol> <li>the person who ordered a ticket clicks on "Permission" and the <code>OrderConsentUpdate View</code> updates the database.</li> <li>is the attendee him- or herself gives consent for one specific ticket. In that case, <code>AttendeeConsentUpdate</code> is called.</li> </ol> <p>You can see both classes are very similar, but not still differ in essential variables. Is there a way to write that better?</p> <pre><code>class AttendeeConsentUpdate(View): @cached_property def attendee(self): return get_object_or_404( Attendee, ticket_reference=self.kwargs['ticket_reference'], ticket_code=self.kwargs['ticket_code'], ) def post(self, request, *args, **kwargs): # Check if consent already exists which defines if consent entry will be # updated or if a new one will be created. consent = contact_by_email(self.attendee) # Check if consent already exists if consent: # If updated email already exists, selected object will be changed obj_email_exists = self.attendee.event.organizer.contacts.filter( email=self.attendee.email).first() if obj_email_exists: consent = obj_email_exists update_consent( consent=True, instance=consent, first_name=self.attendee.first_name, last_name=self.attendee.last_name, email=self.attendee.email, event=self.attendee.event, ) # If consent is given and does not exist yet as entry else: new_consent = Contact( consent=True, email=self.attendee.email, first_name=self.attendee.first_name, last_name=self.attendee.last_name, organizer=self.attendee.event.organizer, ) new_consent.save() new_consent.events.add(self.attendee.event) # Segment: Track assignment event distinct_id = segment_get_distinct_id(request) if distinct_id: analytics.track(distinct_id, 'Attendee consent via checklist', properties={ 'consentEmail': self.attendee.email, }) messages.success(request, _( "You will receive marketing updates. " "Unsubscribe by clicking the unsubscribe link in our emails." )) return redirect(self.attendee) class OrderConsentUpdate(View): @cached_property def order(self): return get_object_or_404( Order, order_reference=self.kwargs['order_reference'], access_key=self.kwargs['access_key'], ) def post(self, request, *args, **kwargs): # Check if consent already exists which defines if consent entry will be # updated or if a new one will be created. consent = contact_by_email(self.order) # Check if consent already exists if consent: # If updated email already exists, selected object will be changed obj_email_exists = self.order.event.organizer.contacts.filter( email=self.order.email).first() if obj_email_exists: consent = obj_email_exists update_consent( consent=True, instance=consent, first_name=self.order.billing.customer_first_name, last_name=self.order.billing.customer_last_name, email=self.order.email, event=self.order.event, ) # If consent is given and does not exist yet as entry else: new_consent = Contact( consent=True, email=self.order.email, first_name=self.order.billing.customer_first_name, last_name=self.order.billing.customer_last_name, organizer=self.order.event.organizer, ) new_consent.save() new_consent.events.add(self.order.event) # Segment: Track assignment event distinct_id = segment_get_distinct_id(request) if distinct_id: analytics.track(distinct_id, 'Order consent via checklist', properties={ 'consentEmail': self.order.email, }) messages.success(request, _( "You will receive marketing updates. " "Unsubscribe by clicking the unsubscribe link in our emails." )) return redirect(self.order) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-23T21:56:53.867", "Id": "421923", "Score": "0", "body": "Thank you for the feedback Sam." } ]
[ { "body": "<p>How about something like this:</p>\n\n<pre><code>class ConsentUpdate(View):\n def update_consent_if_exists(self):\n self.consent = contact_by_email(self.consent_test_obj)\n\n if self.consent:\n self.change_consent_object()\n else:\n self.add_new_consent()\n\n def add_new_consent(self):\n new_consent = Contact(\n consent=True,\n email=self.email,\n first_name=self.first_name,\n last_name=self.last_name,\n organizer=self.organizer,\n )\n new_consent.save()\n new_consent.events.add(self.event)\n self.track_assignment_event()\n\n def change_consent_object(self):\n obj_email_exists = self.organizer.contacts.filter(\n email=self.email).first()\n if obj_email_exists:\n self.consent = obj_email_exists\n update_consent(\n consent=True,\n instance=self.consent,\n first_name=self.first_name,\n last_name=self.last_name,\n email=self.email,\n event=self.event,\n )\n\n def track_assignment_event(self):\n distinct_id = segment_get_distinct_id(request)\n if distinct_id:\n analytics.track(distinct_id, self.consent_message, properties={\n 'consentEmail': self.email,\n })\n messages.success(request, _(\n \"You will receive marketing updates. \"\n \"Unsubscribe by clicking the unsubscribe link in our emails.\"\n ))\n\n\nclass AttendeeConsentUpdate(ConsentUpdate):\n\n @cached_property\n def attendee(self):\n my_attendee = get_object_or_404(\n Attendee,\n ticket_reference=self.kwargs['ticket_reference'],\n ticket_code=self.kwargs['ticket_code'],\n )\n\n self.email = my_attendee.email\n self.first_name = my_attendee.first_name\n self.last_name = my_attendee.last_name\n self.event = my_attendee.event\n self.organizer = my_attendee.event.organizer\n self.consent_message = 'Attendee consent via checklist'\n self.consent_test_obj = my_attendee\n return my_attendee\n\n def post(self, request, *args, **kwargs):\n self.update_consent_if_exists()\n return redirect(self.attendee)\n\n\nclass OrderConsentUpdate(ConsentUpdate):\n\n @cached_property\n def order(self):\n my_order = get_object_or_404(\n Order,\n order_reference=self.kwargs['order_reference'],\n access_key=self.kwargs['access_key'],\n )\n\n self.email = my_order.email\n self.first_name = my_order.billing.customer_first_name\n self.last_name = my_order.billing.customer_last_name\n self.event = my_order.event\n self.organizer = my_order.event.organizer\n self.consent_message = 'Attendee consent via checklist'\n self.consent_test_obj = my_order\n return my_order\n\n def post(self, request, *args, **kwargs):\n self.update_consent_if_exists()\n return redirect(self.order)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-23T20:35:49.747", "Id": "421914", "Score": "4", "body": "Welcome to Code Review! A code review should focus on the code in question and elaborate on possible weaknesses and ways to improve. At the moment your answer is merely an alternative solution to the task. See also [\"How to write a good answer?\"](https://codereview.stackexchange.com/help/how-to-answer) in the Help Center." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-23T20:16:57.667", "Id": "217985", "ParentId": "217978", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-23T18:35:20.443", "Id": "217978", "Score": "3", "Tags": [ "python", "django" ], "Title": "Two cases for indicating consent for a ticket" }
217978