body
stringlengths 25
86.7k
| comments
list | answers
list | meta_data
dict | question_id
stringlengths 1
6
|
|---|---|---|---|---|
<p>I was successful in solving a challenge in codility, but my solution failed performance tests. How can I improve my solution?</p>
<blockquote>
<p><strong>Challenge:</strong></p>
<p>Integers K, M and a non-empty array A consisting of N integers, not
bigger than M, are given.</p>
<p>The leader of the array is a value that occurs in more than half of
the elements of the array, and the segment of the array is a sequence
of consecutive elements of the array.</p>
<p>You can modify A by choosing exactly one segment of length K and
increasing by 1 every element within that segment.</p>
<p>The goal is to find all of the numbers that may become a leader after
performing exactly one array modification as described above.</p>
<p>Write a function:</p>
<pre><code>def solution(K, M, A)
</code></pre>
<p>that, given integers K and M and an array A consisting of N integers,
returns an array of all numbers that can become a leader, after
increasing by 1 every element of exactly one segment of A of length K.
The returned array should be sorted in ascending order, and if there
is no number that can become a leader, you should return an empty
array. Moreover, if there are multiple ways of choosing a segment to
turn some number into a leader, then this particular number should
appear in an output array only once.</p>
<p>For example, given integers K = 3, M = 5 and the following array A:</p>
<pre><code>A[0] = 2
A[1] = 1
A[2] = 3
A[3] = 1
A[4] = 2
A[5] = 2
A[6] = 3
</code></pre>
<p>the function should return [2, 3]. If we choose segment A[1], A[2],
A[3] then we get the following array A:</p>
<pre><code>A[0] = 2
A[1] = 2
A[2] = 4
A[3] = 2
A[4] = 2
A[5] = 2
A[6] = 3
</code></pre>
<p>and 2 is the leader of this array. If we choose A[3], A[4], A[5] then
A will appear as follows:</p>
<pre><code>A[0] = 2
A[1] = 1
A[2] = 3
A[3] = 2
A[4] = 3
A[5] = 3
A[6] = 3
</code></pre>
<p>and 3 will be the leader.</p>
<p>And, for example, given integers K = 4, M = 2 and the following array:</p>
<pre><code>A[0] = 1
A[1] = 2
A[2] = 2
A[3] = 1
A[4] = 2
</code></pre>
<p>the function should return [2, 3], because choosing a segment A[0],
A[1], A[2], A[3] and A[1], A[2], A[3], A[4] turns 2 and 3 into the
leaders, respectively.</p>
<p>Write an efficient algorithm for the following assumptions:</p>
<ul>
<li>N and M are integers within the range [1..100,000];</li>
<li>K is an integer within the range [1..N];</li>
<li>Each element of array A is an integer within the range [1..M].</li>
</ul>
</blockquote>
<p><strong>My Solution</strong></p>
<pre><code>def modify(segment):
return [e+1 for e in segment]
def dominant(A):
d = dict()
lenOfHalfA = int(len(A)/2)
domList = []
for i in A:
if not i in d:
d[i] = 1
else:
d[i] = d[i]+1
for key, value in d.items():
if value > lenOfHalfA:
domList.append(key)
return domList
def solution(K, M, A):
# write your code in Python 3.6
dominantList = []
x = 0
while x <= len(A) - K:
modifiedA = A[:]
modifiedA[x:K+x] = modify(A[x:K+x])
dominantList += dominant(modifiedA)
x += 1
return list(set(dominantList))
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-04T14:12:46.043",
"Id": "448114",
"Score": "0",
"body": "This question might benefit from an example and it's output. That would make the workings a bit clearer than just text."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-04T18:21:43.000",
"Id": "448149",
"Score": "0",
"body": "@Gloweye I have added some examples now."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-04T22:13:45.133",
"Id": "448171",
"Score": "0",
"body": "yes, looks a lot easier to understand the purpose. I've suggested a few edits that show it more like python lists. So essentially, the \"leader\" is the most common number, and the output is the most common number in either the current array ( increasing a slice of length zero) or any array with a certain slice incremented."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-01T13:16:44.747",
"Id": "470306",
"Score": "0",
"body": "Are you using `list(set(dominantList))` to sort your list?"
}
] |
[
{
"body": "<pre class=\"lang-py prettyprint-override\"><code>def modify(segment):\n return [e+1 for e in segment]\n</code></pre>\n\n<p>This function is used only in one place, and is only one line. That often means it's better to just inline it:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>modifiedA[x:K+x] = modify(A[x:K+x])\n# Becomes:\nmodifiedA[x:K+x] = [e+1 for e in A[x:K+x]]\n</code></pre>\n\n<p>Use meaningful variable names. No matter what your challenge says, K, M and A are not meaningful variable names. It also seems like you're not doing anything with that M, so why do we even pass it to the function?</p>\n\n<p>In your <code>dominant()</code> function, you look like you want to use <a href=\"https://docs.python.org/3.7/library/collections.html#counter-objects\" rel=\"nofollow noreferrer\"><code>collections.Counter</code></a>. For practice with a language it can be good to check how to set it up yourself, but sometimes we have a good solution ready-made and available, and much better tested than any individual developer could ever do.</p>\n\n<p>With Counter, you can make it work like this:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>from collections import Counter\n\ndef dominant(string):\n count = Counter(string)\n return [key for key, value in count.items() if value == count.most_common(1)[0][1]]\n</code></pre>\n\n<p>Yeah, it's as simple as that. You could split it out over multiple lines, for clarity:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>from collections import Counter\n\ndef dominant(string):\n count = Counter(string)\n dom_list = []\n max_occurred = count.most_common(1)[0][1]\n for key, value in count.items():\n if value >= max_occurred:\n dom_list.append(key)\n return dom_list\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-04T14:37:13.103",
"Id": "448118",
"Score": "3",
"body": "_That often means it's better to just inline it_ - In this case I agree, but in general I don't. Functions are cheap, and inlining for performance is about the last thing you should try. The modularity, testability and legibility that functions offer is important, and well worth the tiny performance hit. The only reason I agree here is that the purpose of the function isn't well-defined."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-04T14:46:28.930",
"Id": "448120",
"Score": "1",
"body": "There's loads of cases where functions are appropriate, but it can also be premature optimization and/or a lot of scrolling to see what a line does. In my opinion, primary reason for functions is to avoid repetition, and secondary is to aid readability and make it easier to see what a block of code does. If there's no repetition to avoid and no readability gained with a function, then IMO it shouldn't exist."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-01T13:01:02.960",
"Id": "470303",
"Score": "0",
"body": "Would inline here even give a speed increase? I was under the impression that lambda functions appear identical to normal (local) functions in the bytecode."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-02T09:48:14.643",
"Id": "470392",
"Score": "0",
"body": "It should, but that's not important. The reason I suggested it is to make the code easier to read."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-04T14:25:02.190",
"Id": "230166",
"ParentId": "230163",
"Score": "1"
}
},
{
"body": "<p>You can speed some things up by using more list and dict comprehensions, and by reducing your function calls. Some examples follow.</p>\n\n<p><code>d = dict()</code> vs <code>d = {}</code>: 131 ns vs 30 ns.</p>\n\n<p><code>len_of_half_a = int(len(a)/2)</code> vs <code>len_of_half_a = len(a)//2</code>: 201 ns vs 99 ns.</p>\n\n<p>I used Python 3.8.1 for both tests.</p>\n\n<p>Granted that this isn't much, but several of these tiny improvements could help you reach the target. You should see similar if not better performance increases by using list and dict comprehensions, e.g. for <code>domList</code>, <code>d</code>, and <code>dominantList</code>. And replacing your <code>while x <= len(A) - K:</code> with a range-based iterator should bump you up a little more.</p>\n\n<p>And a final small note is that you should try to follow standards with your naming and ensure clear and obvious names. <code>A</code> is not a good name for a variable, nor is <code>d</code>, and python tends to use <code>snake_case</code> over <code>camelCase</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-01T13:16:08.720",
"Id": "239742",
"ParentId": "230163",
"Score": "1"
}
},
{
"body": "<h3>Algorithm in O(N^2)</h3>\n\n<p>The current solution will be slow for large N, because it has a complexity of O(N^2) (It checks every element in the array for every possible position of the k adjusted elements => O(N * (N-K)) => O(N^2)).</p>\n\n<h3>There is an O(N) solution.</h3>\n\n<p>Consider that as the K-element segment \"slides\" along the array, there are only two elements whose value changes: the one entering and the one leaving the segment.</p>\n\n<p>Something like:</p>\n\n<pre><code>def solution(K, M, A):\n threshold = len(A)//2\n counts = Counter(A)\n\n # increment count for each element in the initial window\n for head in A[:K]:\n counts[head] -= 1\n counts[head+1] += 1\n\n # initial leaders\n leaders = set(k for k,v in counts.items() if v > threshold)\n\n # slide window along the array adjusting the counts for \n # elements that leave (tail) or enter (head) the window.\n # An element entering gets incremented, so \n # count[element] -= 1 and count[element+1] += 1.\n # It is the reverse for element leaving.\n for tail, head in zip(A, A[K:]):\n counts[tail] += 1\n counts[tail + 1] -= 1\n\n counts[head] -= 1\n counts[head + 1] += 1\n\n if counts[tail] > threshold:\n leaders.add(tail)\n\n if counts[head + 1] > threshold:\n leaders.add(head + 1)\n\n return leaders\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-01T19:29:29.980",
"Id": "239760",
"ParentId": "230163",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-04T13:58:36.910",
"Id": "230163",
"Score": "3",
"Tags": [
"python",
"algorithm",
"python-3.x",
"array"
],
"Title": "Given an array, find all its elements that can become a leader"
}
|
230163
|
<p>Implemented the quick sort algorithm in python, It was just for learning it, now I want to port it to C.</p>
<p>Thoughts on the quality of my python implementation?</p>
<pre class="lang-py prettyprint-override"><code>from random import randint, shuffle
def swap(array, a, b):
array[a], array[b] = array[b], array[a]
def quick_sort(array, start=0, end=None):
if end is None:
end = len(array) - 1
if end - start >= 1:
pivot = array[end]
a = start
b = end - 1
while not a > b:
if not array[a] > pivot:
a += 1
continue
else:
if array[b] < pivot:
swap(array, a, b)
a += 1
b -= 1
swap(array, a, end)
quick_sort(array, start, a - 1)
quick_sort(array, a + 1, end)
arr = [randint(0, 30) for _ in range(20)]
print(arr)
quick_sort(arr)
print(arr)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-04T15:23:36.873",
"Id": "448123",
"Score": "0",
"body": "It works, so far, I didn't found any error."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-04T15:26:56.413",
"Id": "448124",
"Score": "0",
"body": "OK, just checking."
}
] |
[
{
"body": "<h1>Magic Numbers</h1>\n\n<pre><code>arr = [randint(0, 30) for _ in range(20)]\n</code></pre>\n\n<p>What are <code>0</code>, <code>30</code>, and <code>20</code> supposed to represent? I would assign these to variables to make it more clear</p>\n\n<h1>Type Hints</h1>\n\n<p>This</p>\n\n<pre><code>def swap(array, a, b):\n</code></pre>\n\n<p>can be this</p>\n\n<pre><code>def swap(array: list, a: int, b: int) -> None:\n</code></pre>\n\n<p>These allow you to show what types of parameters are accepted, and what types are returned from the functions.</p>\n\n<h1>Main Guard</h1>\n\n<p>This</p>\n\n<pre><code>arr = [randint(0, 30) for _ in range(20)]\nprint(arr)\nquick_sort(arr)\nprint(arr)\n</code></pre>\n\n<p>should be put in a main guard, like so</p>\n\n<pre><code>if __name__ == '__main__':\n arr = [randint(0, 30) for _ in range(20)]\n print(arr)\n quick_sort(arr)\n print(arr)\n</code></pre>\n\n<p>This prevents this code from running if you decide to import this module from another module/program.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-04T18:33:03.867",
"Id": "230178",
"ParentId": "230167",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "230178",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-04T15:07:05.880",
"Id": "230167",
"Score": "3",
"Tags": [
"python",
"python-3.x",
"sorting",
"quick-sort"
],
"Title": "Quick Sort implementation in python"
}
|
230167
|
<p>Experimenting with operator overloading for the first time. Based on my reading, it appears to be a bit of a minefield.</p>
<p>Have I fallen into any traps?</p>
<pre><code>namespace Units
{
class Degree; // Forward declare Degree so it can be passed by reference into Radian.
/// \class Radian
/// Encapsulates a double, and used to represent a radian.
class Radian
{
public:
/// Constructor.
/// \param radian The angle (radians).
Radian(double radian) : angle_(radian) {}
/// Constructor.
/// \param degree The angle (degrees).
Radian(const Degree& degree);
/// Function Call Operator.
/// \return <double> The angle value (radians).
operator double() const { return angle_; }
private:
double angle_;
};
/// \class Degree
/// Encapsulates a degree, and used to represent a degree.
class Degree
{
public:
/// Constructor.
/// \param degree The angle value (degrees).
Degree(double degree) : angle_(degree) {}
/// Constructor.
/// \param radian The angle (radians).
Degree(const Radian& radian);
/// Function Call Operator.
/// \return <double> The angle (degrees).
operator double() const { return angle_; }
private:
double angle_;
};
/// Constructor.
/// Constructor defined outside of class declaration, to allow Degree class to be defined before it.
/// \param degree The angle (degrees).
Radian::Radian(const Degree& degree)
: angle_(degree * SoC::Maths::Trigonometry::DegToRad)
{}
/// Constructor.
/// Constructor defined outside of class declaration, to allow Radian class to be defined before it.
/// \param radian The angle (radians).
Degree::Degree(const Radian& radian)
: angle_(radian * SoC::Maths::Trigonometry::RadToDeg)
{}
} // namespace Units
#endif // UNITS_H
</code></pre>
<hr>
<p>EDIT</p>
<p>and initialised in the way:</p>
<pre><code>const Units::Degree latitude = 48.8566;
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-04T18:03:37.077",
"Id": "448144",
"Score": "2",
"body": "For a more all-encompassing version of the same general idea, you might want to take a look at [Boost Units](https://www.boost.org/doc/libs/1_71_0/doc/html/boost_units.html) sometime."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-05T13:26:16.887",
"Id": "448244",
"Score": "1",
"body": "The std::chrono library can inspire you."
}
] |
[
{
"body": "<h1>Design</h1>\n\n<p>While it might seem that the current design is working fine, I think there are two distinct issues lurking beneath the surface.</p>\n\n<h3>Issue #1: <code>operator double</code></h3>\n\n<p>From what I can tell, the intention behind these unit classes seems to be the prevention of unit mismatches. Providing an access function to the contained value is not a bad idea, but using the <strong>implicit</strong> conversion operator for doing so is probably not the wisest choice here.</p>\n\n<p>Consider the following snippet:</p>\n\n<pre><code>auto angle = Degrees{ 180.0 };\nauto sine = std::sin(angle);\n</code></pre>\n\n<p>It compiles easy enough, but will then fail silently at runtime. It likely won't even crash the application, but quietly produce values different to those expected.</p>\n\n<p>Of course, this is a contrived case (\"<code>std::sin</code> is not really in the scope of this library (yet)!\"), but nonetheless it shows a problem: As it is, there is hardly any prevention of accidental unit mismatches.</p>\n\n<p>Adding the keyword <code>explicit</code> to <code>operator double()</code> might help with some of these cases (though not with <code>std::sin</code>), but not all of them.</p>\n\n<blockquote>\n <p>If this were the only issue, it would be easy to fix with a getter function with a descriptive name (e.g. <code>getDegrees</code>).</p>\n</blockquote>\n\n<h3>Issue #2: Extensibility</h3>\n\n<p>Let's say that in the future, you (as the library developer) want to add another representation for angles (e.g. gons/gradians). Sounds simple, right?</p>\n\n<p>And at that point, it is. Adding one more class according to the given scheme, four more converting constructors, and it is done.</p>\n\n<blockquote>\n <p>Someone familiar with the SOLID principles might already spot a code smell in the last sentence: <strong>four more converting constructors</strong>, two of which have to be added to the existing and otherwise rather independent classes <code>Degrees</code> and <code>Radians</code>, thus violating the Open-Closed part of SOLID.</p>\n</blockquote>\n\n<p>After that comes another user A of the library and wants to add his own custom angle representation <code>RepA</code>. And then comes user B with <code>RepB</code>.</p>\n\n<p>And suddenly, we're having twenty converting constructors just for those five classes. And each additional representation is going to add a lot more: For <span class=\"math-container\">\\$N\\$</span> representations, we need <span class=\"math-container\">\\$N \\cdot (N - 1)\\$</span> converting constructors to cover all combinations.</p>\n\n<blockquote>\n <p>And that is assuming independent developers add converting constructors for each others implementation. Otherwise, <code>operator double</code> will again lurk in the shadows, allowing for code to compile that really should not.</p>\n\n<pre><code>class Gradians {\npublic:\n Gradians(double);\n Gradians(const Degrees&);\n Gradians(const Radians&);\n operator double() const;\n // ...\n};\n\nclass Turns {\npublic:\n Turns(double);\n Turns(const Degrees&);\n Turns(const Radians&);\n operator double() const;\n // ...\n};\n</code></pre>\n \n <p>Now stuff like <code>auto a = Gons(300.0); auto b = Turns(a);</code> will actually compile, but produce wrong results (<code>b == 300.0</code> instead of <code>b == 0.75</code>).</p>\n</blockquote>\n\n<p>How can we solve this conundrum?</p>\n\n<p>A first step would be to separate the value from its representation(s) by choosing one internal representation which can be converted on demand:</p>\n\n<pre><code>class Angle {\npublic:\n static Angle fromDegrees(double degrees);\n static Angle fromRadians(double radians);\n\n double radians() const;\n double degrees() const;\nprivate:\n Angle(double radians) : radians_{ radians } {}\n\n double radians_;\n};\n\nAngle Angle::fromDegrees(double degrees) {\n auto radians = degrees * SoC::Maths::Trigonometry::DegToRad;\n return Angle{ radians };\n}\n\nAngle Angle::fromRadians(double radians) {\n return Angle{ radians };\n}\n\ndouble Angle::degrees() const {\n return radians_ * SoC::Maths::Trigonometry::RadToDeg;\n}\n\ndouble Angle::radians() const {\n return radians_;\n}\n</code></pre>\n\n<p>As you can see, I chose radians for my internal representation (mostly because that's what the trigonometric functions of the standard libary expect). For adding a new representation, we now only need to add one factory function (<code>fromXyz(...)</code>) and one getter function (<code>xyz()</code>).</p>\n\n<blockquote>\n <p>While this is a lot cleaner (and takes care of some issues), SOLID devotees will not fail to notice that the violation of the Open-Closed principle hasn't been fixed yet, just moved.</p>\n \n <p>To address this, we could introduce a hierarchy of derived classes, but that seems like overkill for this problem.</p>\n \n <p>Another easy solution would be to use templates:</p>\n\n<pre><code>struct Degrees {\n static double toRadians(double degrees) {\n return degrees * SoC::Maths::Trigonometry::DegToRad;\n }\n static double fromRadians(double radians) {\n return radians * SoC::Maths::Trigonometry::RadToDeg;\n }\n};\n\nstruct Radians {\n static double toRadians(double radians) { return radians; }\n static double fromRadians(double radians) { return radians; }\n};\n\nclass Angle {\npublic:\n template<typename Representation>\n static Angle from(double value) {\n return Angle{ Representation::toRadian(value) };\n }\n\n template<typename Representation>\n double as() const {\n return Repreentation::fromRadians(radians_);\n }\n\nprivate:\n Angle(double radians) : radians_{ radians } {}\n\n double radians_;\n};\n\n // Usage\n auto angle = Angle::from<Degrees>(180.0);\n auto sine = std::sin(angle.as<Radians>());\n</code></pre>\n</blockquote>\n\n<p>Of course, this is far from done, yet:</p>\n\n<ul>\n<li>Operators for addition, subtraction (angles), multiplication and/or division (scalars) could be overloaded for this <code>Angle</code> class</li>\n<li>For demonstration purposes I didn't mark the member functions above <code>noexcept</code> or <code>constexpr</code>. This should likely be amended.</li>\n<li>Helper functions like <code>sin</code>, <code>cos</code>, <code>tan</code> and similar could be provided for this <code>Angle</code> class.</li>\n<li>For the template version: The templates could be restricted to only accept types with correct signatures for <code>fromRadians</code> and <code>toRadians</code>.</li>\n</ul>\n\n<h1>Implementation</h1>\n\n<p>Aside from the design considerations mentioned above, I can add these points for the general implementation:</p>\n\n<ul>\n<li>Consider marking converting constructors and conversion operators as <code>explicit</code>.</li>\n<li>Very likely <code>sizeof(Degree) == sizeof(double)</code>, so there probable won't be a benefit for taking a <code>const Degree&</code> parameter over just <code>Degree</code>.</li>\n<li>I'd suggest checking the precision of the constants ' DegToRad<code>and</code>RadToDeg`, especially if calculated on your own. If the precision on these constants is poor, there might be small numeric errors that accumulate over multiple conversions to and fro.</li>\n<li>A comment reads <code>/// Function Call Operator</code>: Actually, no, this is a conversion operator. A function call operator would look like this: <code>double operator()() const</code>.</li>\n<li>Generally, the comments don't tell me much about anything. Unless there is a hard requirement for them (in which case they should be improved) I'd suggest removing them. In their current form, they are at best visual clutter, and confusing at worst.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-05T12:09:01.030",
"Id": "448223",
"Score": "0",
"body": "I really appreciate the time you took to review my code! Thank you.\n\nI did consider using an Angle class, however dismissed it. Currently, I am passing round doubles to represent my angles, however this has lead to much confusion as to whether a function is operating with degrees or radians. My intention with these classes was to remove that ambiguity, and I'm not sure an \"Angle\" class would do that.\n\nI acknowledge the issues with using an implicit conversion. Is there any other way to allow assignments as per my edit? Or am I wrong to want to be able to do this?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-05T13:59:38.307",
"Id": "448259",
"Score": "1",
"body": "@pingu The intention behind the Angle class is that you should not need to care about the angle's representation until you explicitly request one. A function taking an Angle parameter doesn't care whether the Angle was initialized from degrees, radians, gons or something else. And if it actually needs the value in a specific representation, it can request it, and it will be converted automatically. (Hint: This might be much easier to use if some of the arithmetic operators are overloaded: 2*alpha is double the angle, regardless of the representation)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-05T14:28:10.887",
"Id": "448263",
"Score": "1",
"body": "@pingu: A bit more worked out: [godbolt link](https://godbolt.org/z/XEOtXY). Take a look at `myFunc` at the bottom: It doesn't care which representation was used to create its inputs, just does some calculations on the angle and passes it on. Only `sin` actually cares about the representation, and then it actually requests it as needed. If you only pass `Angle`s around, you mostly won't even need to care about the actual internal representation, so in my eyes, this is definitely an improvement"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-29T21:50:19.317",
"Id": "451556",
"Score": "0",
"body": "I'd suggest that one could also implement [user-defined literals](https://en.cppreference.com/w/cpp/language/user_literal) as suggested in [this answer](https://codereview.stackexchange.com/questions/220619/arkanoid-console-game/221410#221410)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-30T00:47:21.290",
"Id": "451567",
"Score": "0",
"body": "@pingu You say, \"I am passing round doubles to represent my angles, however this has lead to much confusion as to whether a function is operating with degrees or radians.\" Is there a reason you don't have a convention like the standard library that all functions dealing with angles take radians? Seems like that would solve the issue. Internally a function could do whatever it wants, but externally all angles should be the same representation, usually."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-31T06:29:40.700",
"Id": "451736",
"Score": "0",
"body": "@Edward: UDF would surely be nice, but would have to be done per representation (e.g. `2.0_rad`, `180_deg`, `200_gons`, `2.0_turns`). I was focusing more on the `Angle` design instead, since it was much more in need of improvement."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-31T06:31:42.847",
"Id": "451737",
"Score": "0",
"body": "@user1118321: \"Internally a function could do whatever it wants, but externally all angles should be the same representation, usually.\" That is basically what `Angle` helps you to do in an easy-to-use manner. Explicitly deciding on a uniform representation might not always be feasible (e.g. reliance on third party functions)."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-05T02:49:06.300",
"Id": "230201",
"ParentId": "230174",
"Score": "9"
}
},
{
"body": "<p>The two conversion constructors are not declared in the class, nor are they declared <code>inline</code>. If this code is in a header that is included by multiple source files, you'll have an ODR violation, which typically results in a linker error for multiple definitions of a symbol.</p>\n\n<p>Those two constructors should be declared with the <code>inline</code> keyword.</p>\n\n<pre><code>inline Radian::Radian(const Degree& degree)\n// ...\n\ninline Degree::Degree(const Radian& radian)\n// ...\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-05T12:10:16.520",
"Id": "448224",
"Score": "0",
"body": "many thanks, I will make these changes, and I have learned something."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-05T05:14:53.470",
"Id": "230205",
"ParentId": "230174",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "230201",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-04T17:03:39.137",
"Id": "230174",
"Score": "4",
"Tags": [
"c++",
"unit-conversion",
"overloading"
],
"Title": "Two classes to avoid confusion when handling degrees and radians"
}
|
230174
|
<p>First of all, here is an overview of my application. I want to create a multiple-choice app, on android, using data stored on a remote MySQL database. The DB has 100 questions that will appear in random order. </p>
<p>My php script returns a JSON array with the following results</p>
<pre><code>[
{
"id": 1,
"Question": " blahblahblahblahblah?"
},
{
"id": 2,
"Question": "blehblehblehblehblehblehblehblehbleh?"
},
]
</code></pre>
<p>Since the Question table on my database has integers and strings I thought that it would be a better approach to copy the information of the JSON Objects to different instances of a Class Question. I want the JSONArray to be created once in order to avoid multiple requests to the server.That's why I wrote the following code:</p>
<pre><code>public class Question {
int question_id;
String question_txt ;
JSONArray json ;
public int setQuestion_id(int i) {
try {this.question_id = this.json.getJSONObject(i).getInt("id");}
catch (JSONException e) {e.printStackTrace();}
return question_id;
}
public String setQuestion_txt(int i) {
try {this.question_txt=this.json.getJSONObject(i).getString("Question");}
catch (JSONException e) {e.printStackTrace();}
return question_txt;
}
public JSONArray setJson()throws JSONException, IOException {
java.net.HttpURLConnection connection = null;
URL url = new URL("url_to_my.php");
connection = (java.net.HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("Content-length", "0");
connection.setUseCaches(false);
connection.setConnectTimeout(0);
connection.setReadTimeout(0);
connection.connect();
int status = connection.getResponseCode();
JSONArray json = null;
switch (status) {
case 200:
case 201:
BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line + "\n");
}
this.json = new JSONArray(sb.toString());
br.close();
}
return this.json;
}
}
</code></pre>
<p>What I tried doing is creating an ArrayList questionnaire and add to it different instances of the Class Question with different values. </p>
<pre><code>ArrayList<Question> questionnaire = new ArrayList<Question>();
Question q = new Question();
for(int i=0; i< q.setJson().length() ;i++){
Question newQuestion = new Question();
newQuestion.json = q.json;
newQuestion.setQuestion_id(i);
newQuestion.setQuestion_txt(i);
questionnaire.add(newQuestion);}
</code></pre>
<p>Everything seems to work fine, at least for now. Later on, I want the JSON result to return more information like the possible answers and which is the correct one.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-05T14:36:58.443",
"Id": "448264",
"Score": "0",
"body": "I have rolled back your last edit. Please don't change or add to the code in your question after you have received answers. See [What should I do when someone answers my question?](https://codereview.stackexchange.com/help/someone-answers) Thank you."
}
] |
[
{
"body": "<p>Good effort to get your code working so far. But your code is highly unusual.</p>\n\n<p>You've got the class <code>Question</code> which has an <code>id</code> and <code>question_txt</code>, but each <code>Question</code> also has a reference to a JSONArray of all the questions. Worse than that, for each <code>Question</code>, when you create a new Question and set its reference to all questions, it will come from the API each time.</p>\n\n<p>You've recognised that the behaviour of getting <code>Question</code>s from the API might belong in the <code>Question</code> class (or related class), instead of forcing <code>main</code> (or whatever consumer) to know the details of the API. But it's surely not the responsibility of a single <code>Question</code> instance to fetch all the <code>Question</code>s.</p>\n\n<p>You want the class <code>Question</code> to hold it's data first (and later, some behaviour), so here's a typical data class. </p>\n\n<pre class=\"lang-java prettyprint-override\"><code>public class Question {\n\n private int id;\n private String text;\n\n public Question (int i, String s) {\n this.id = i;\n this.text = s;\n }\n\n public int getId() {\n return id;\n }\n\n public String getText() {\n return text; \n }\n\n}\n</code></pre>\n\n<p>You'll see this type of class referred to as Java Bean or POJO. In this case, because we've used <code>private</code> and only provided <code>get</code> methods, this is a read-only object after its been created.</p>\n\n<p>Then add some behaviour to the <em>class</em> (meaning we're going to use the <code>static</code> keyword) for retrieving the questions:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>public static List<Question> fetchQuestions () throws JSONException, IOException {\n\n HttpURLConnection connection = (HttpURLConnection) new URL(\"url_to_my.php\").openConnection();\n connection.setRequestMethod(\"GET\");\n connection.setRequestProperty(\"Content-length\", \"0\");\n connection.setUseCaches(false);\n connection.setConnectTimeout(0);\n connection.setReadTimeout(0);\n connection.connect();\n int status = connection.getResponseCode();\n if (!(status == 200 || status == 201)) {\n throw new IOException(\"Bad status code: \" + status);\n }\n\n BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));\n StringBuilder sb = new StringBuilder();\n String line;\n while ((line = br.readLine()) != null) {\n sb.append(line + \"\\n\");\n }\n br.close();\n String response = sb.toString();\n\n List<Question> questions = new ArrayList<Question>();\n for (Object arrayItem: new JSONArray(response)) {\n JSONObject questionAsJSON = (JSONObject) arrayItem; // throws on unexpected response format\n questions.add(new Question(questionAsJSON.getInt(\"id\"), \n questionAsJSON.getString(\"Question\")));\n }\n\n return questions;\n\n}\n</code></pre>\n\n<p>And then when we want to grab the questions from the API, it's just a case of invoking the static method:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>List<Question> questionnaire = Question.fetchQuestions();\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-05T14:18:56.653",
"Id": "448261",
"Score": "0",
"body": "Hi Jeremy, it seems like you can't iterate with for each loop a JSONArray. Therefore I made some modifications to your code (Check my Edit). Other than that, your code is what I wanted to do from the beginning, but I couldn't figure how."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-05T22:40:41.593",
"Id": "448310",
"Score": "0",
"body": "`JSONArray` is `Iterable` for me. Could be a version difference? I'm using `<dependency>groupId>org.json</groupId><artifactId>json</artifactId><version>20190722</version></dependency>`"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-05T00:58:35.043",
"Id": "230200",
"ParentId": "230175",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "230200",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-04T17:48:42.933",
"Id": "230175",
"Score": "2",
"Tags": [
"java",
"android",
"json"
],
"Title": "Populate an ArrayList of different instances of a class"
}
|
230175
|
<p><a href="https://leetcode.com/problems/critical-connections-in-a-network/" rel="nofollow noreferrer">https://leetcode.com/problems/critical-connections-in-a-network/</a></p>
<p>Please review for memory and runtime performance.</p>
<blockquote>
<p>There are n servers numbered from 0 to n-1 connected by undirected
server-to-server connections forming a network where connections[i] =
[a, b] represents a connection between servers a and b. Any server can
reach any other server directly or indirectly through the network.</p>
<p>A critical connection is a connection that, if removed, will make some
server unable to reach some other server.</p>
<p>Return all critical connections in the network in any order.
<a href="https://i.stack.imgur.com/b2hSa.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/b2hSa.png" alt="enter image description here"></a></p>
<p>Input: n = 4, connections = [[0,1],[1,2],[2,0],[1,3]] Output: [[1,3]]
Explanation: [[3,1]] is also accepted. </p>
<p>Constraints:</p>
<p>1 <= n <= 10^5 n-1 <= connections.length <= 10^5 connections[i][0] !=
connections<a href="https://i.stack.imgur.com/b2hSa.png" rel="nofollow noreferrer">i</a> There are no repeated connections.</p>
</blockquote>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace GraphsQuestions
{
/// <summary>
/// https://leetcode.com/problems/critical-connections-in-a-network/
/// </summary>
[TestClass]
public class CriticalConnectionsInANetwork
{
[TestMethod]
public void TestMethod1()
{
//[[0,1],[1,2],[2,0],[1,3]]
List<IList<int>> input = new List<IList<int>>();
input.Add(new List<int> { 0, 1 });
input.Add(new List<int> { 1, 2 });
input.Add(new List<int> { 2, 0 });
input.Add(new List<int> { 1, 3 });
CriticalConnectionsClass ccClass = new CriticalConnectionsClass();
var res = ccClass.CriticalConnections(4, input);
List<IList<int>> expcted = new List<IList<int>>();
expcted.Add(new List<int> { 1,3 });
for (int i = 0; i < res.Count; i++)
{
CollectionAssert.AreEqual(expcted[i].ToList(), res[i].ToList());
}
}
}
public class CriticalConnectionsClass
{
//_time when discovered the vertex
private int _time = 0;
public IList<IList<int>> CriticalConnections(int n, IList<IList<int>> connections)
{
int[] low = new int[n];
List<IList<int>> result = new List<IList<int>>();
//we init the visited array to -1 for all vertices
int[] visited = Enumerable.Repeat(-1, n).ToArray();
Dictionary<int, List<int>> dict = new Dictionary<int, List<int>>();
//the graph is connected two ways
foreach (var list in connections)
{
if (!dict.ContainsKey(list[0]))
{
dict.Add(list[0], new List<int>());
}
dict[list[0]].Add(list[1]);
if (!dict.ContainsKey(list[1]))
{
dict.Add(list[1], new List<int>());
}
dict[list[1]].Add(list[0]);
}
for (int i = 0; i < n; i++)
{
if (visited[i] == -1)
{
DFS(i, low, visited, dict, result, i);
}
}
return result;
}
private void DFS(int u, int[] low, int[] visited, Dictionary<int, List<int>> dict, List<IList<int>> result, int pre)
{
visited[u] = low[u] = ++_time; // discovered u;
for (int j = 0; j < dict[u].Count; j++) //iterate all of the nodes connected to u
{
int v = dict[u][j];
if (v == pre)
{
//if parent vertex ignore
continue;
}
if (visited[v] == -1) // if not visited
{
DFS(v, low, visited, dict, result, u);
low[u] = Math.Min(low[u], low[v]);
if (low[v] > visited[u])
{
//u-v is critical there is no path for v to reach back to u or previous vertices of u
result.Add(new List<int> { u, v });
}
}
else // if v is already visited put the minimum into low for vertex u
{
low[u] = Math.Min(low[u], visited[v]);
}
}
}
}
}
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-04T18:23:27.970",
"Id": "230177",
"Score": "1",
"Tags": [
"c#",
"programming-challenge",
"graph",
"depth-first-search"
],
"Title": "LeetCode: critical connections in a network C# (Tarjan's algorithm)"
}
|
230177
|
<p><a href="https://github.com/WebClub-NITK/Hacktoberfest-2k19/pull/148#event-2684596020" rel="nofollow noreferrer">I wrote a quick-select filter in C on Wednesday.</a> (The code is below.)</p>
<p>It is a filter in the UNIX tradition:</p>
<ul>
<li><p>It reads from standard input <code>k</code>, the rank of the integer to select, <code>n</code>, the number of elements, and then <code>n</code> integers.</p></li>
<li><p>It outputs the <code>k</code>th highest integer.</p></li>
</ul>
<p><sub>(A perhaps better design would take <code>k</code> as an argument—but a bigger gripe of mine is having to give <code>n</code>! Bonus points if an answer can show me how to avoid reading <code>n</code> from stdin or as an argument. I would read until EOF, but then I would have to deal with a growing array, I think.)</sub></p>
<p>For the unfamiliar, <a href="https://brilliant.org/wiki/median-finding-algorithm/" rel="nofollow noreferrer">quickselect</a> can find the <code>k</code>th highest integer in <code>O(n)</code> time. The naïve selection algorithm sorts in place and then accesses element <code>k</code>, for <code>O(n lg n)</code> runtime. Quickselect does not sort large lists and achieves linear performance.</p>
<h3>kth_largest.c</h3>
<pre><code>/*d. ben knoble 2019.10.02*/
/*
* PROGRAM
*
* k_largest
*
* Finds the kth largest element of an array in O(n) time.
*
* Reads from standard input
*
* - k: which element to find
* - n: number of elements
* - n elements
*
* Outputs kth largest element to standard out.
*
* IMPLEMENTATION
*
* see kth_largest function
*/
#include <assert.h>
#include <err.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
int compare_longs(const void *a, const void *b) {
long x = *(long *)a;
long y = *(long *)b;
if (x < y)
return -1;
else if (x > y)
return 1;
return 0;
}
void sort(long *a, size_t n) {
qsort(a, n, sizeof(long), compare_longs);
}
size_t med_index(size_t i) {
return (size_t)(floor(i/2));
}
void swap(long *a, long *b) {
long t = *a;
*a = *b;
*b = t;
}
size_t partition(long pivot, long *array, size_t n_elts) {
// find the pivot
size_t pos = -1;
for (size_t i = 0; i < n_elts; ++i) {
if (array[i] == pivot) {
pos = i;
break;
}
}
assert(pos >= 0);
swap(&array[pos], &array[n_elts-1]);
// now pivot is at the end of the array
size_t i = 0;
for (size_t j = 0; j < n_elts; ++j) {
if (array[j] < pivot) {
swap(&array[j], &array[i]);
++i;
}
}
swap(&array[i], &array[n_elts-1]);
return i;
}
long kth_largest(size_t k, long *array, size_t n_elts) {
size_t n_sublists = n_elts/5;
long *medians = malloc(n_sublists * sizeof(long));
if (medians == NULL) { err(1, NULL); }
// sort sublists of 5 elements
for (size_t i = 0; i < n_sublists; ++i) {
size_t start = i*5;
size_t left = n_elts - start < 5 ? n_elts - start : 5;
sort(&array[start], left);
if (left == 5)
medians[i] = array[start + 3];
else
medians[i] = array[start + med_index(left)];
}
// determine pivot (possibly recursively)
long pivot;
if (n_sublists < 5)
pivot = medians[med_index(n_sublists)];
else
pivot = kth_largest(med_index(n_sublists), medians, n_sublists);
// partition
size_t rank = partition(pivot, array, n_elts);
if (k < rank)
return kth_largest(k, array, rank-1);
else if (k > rank)
return kth_largest(rank - k, &array[rank+1], n_elts-(rank+1));
// else k == rank
return pivot;
}
int main(int argc, char **argv) {
size_t k;
size_t n_elts;
scanf("%zd", &k);
scanf("%zd", &n_elts);
long *array = malloc(n_elts * sizeof(long));
if (array == NULL) { err(1, NULL); }
for (size_t i = 0; i < n_elts; ++i)
scanf("%ld", &array[i]);
printf("%ld\n", kth_largest(k, array, n_elts));
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-04T18:35:03.910",
"Id": "448151",
"Score": "0",
"body": "Aside: I've just realized I didn't actually free any of the memory I used "
}
] |
[
{
"body": "<p><strong>Major stuff</strong></p>\n\n<p><strong>Consider <code>const</code></strong></p>\n\n<p>Design: <code>kth_largest()</code> has a side effect of re-arranging <code>array</code>. this is surprising and not part of \"Finds the kth largest element of an array in O(n) time.\" I'd expect code to do the job without the side effect</p>\n\n<pre><code>// long kth_largest(size_t k, long *array, size_t n_elts) {\nlong kth_largest(size_t k, const long *array, size_t n_elts) {\n</code></pre>\n\n<p><strong>Small size error</strong></p>\n\n<p>Code may call <code>err(1, NULL);</code> when <code>n_elts < 5</code> as <code>malloc(0)</code> can return <code>NULL</code>. I'd expect code to work for sizes 1 to 4 also.</p>\n\n<p><strong>Doubtful O() claim</strong></p>\n\n<p>\"Finds the kth largest element of an array in O(n) time.\" Perhaps when <code>n</code> >>> <code>k</code>, but not in general. I'd expect <code>O(n*k)</code>. So perhaps</p>\n\n<pre><code>Finds the kth largest element of an array in O(n) time when k <<< n\notherwise O(n*k)\n</code></pre>\n\n<p><strong>No error check</strong></p>\n\n<p>Do not trust user input follows the rules nor allocations always succeed.</p>\n\n<pre><code>long *array = malloc(n_elts * sizeof(long));\nif (array == NULL) {\n Handle_Error();\n}\n\n\nfor (size_t i = 0; i < n_elts; ++i) {\n // scanf(\"%ld\", &array[i]);\n if (scanf(\"%ld\", &array[i]) != 1) {\n Handle_Error();\n }\n}\n</code></pre>\n\n<hr>\n\n<p><strong>Minor stuff</strong></p>\n\n<p><strong>object vs type</strong></p>\n\n<p>Rather than size to the type, size ot the object. Easier to code right, review and maintain.</p>\n\n<pre><code>// qsort(a, n, sizeof(long), compare_longs);\nqsort(a, n, sizeof *a, compare_longs);\n\n// long *medians = malloc(n_sublists * sizeof(long));\nlong *medians = malloc(sizeof *medians * n_sublists);\n</code></pre>\n\n<p><strong>No need for floating point math</strong></p>\n\n<p><code>i/2</code> will already have \"floor\" the quotient before the <code>floor()</code>. Absolutely no need for <code>floor()</code> and with its potential loss if precision for large <code>i</code>.</p>\n\n<pre><code>// return (size_t)(floor(i/2));\nreturn i/2;\n</code></pre>\n\n<p><strong><code>size_t</code> is an unsigned type</strong><br>\n<strong>Enable all warnings</strong></p>\n\n<p><code>pos >= 0</code> is always true below. A well enabled compilers would have warned.</p>\n\n<pre><code>size_t pos = -1;\n...\nassert(pos >= 0);\n</code></pre>\n\n<p><strong>Match specifier and type</strong></p>\n\n<p><code>\"%zd\"</code> does not match a <code>size_t</code>. <code>\"%zu\"</code> does. Also implies useful warnings were not enabled. Save time - enable warnings. See also <a href=\"https://stackoverflow.com/q/32916575/2410359\">How to use “zd” specifier with <code>printf()</code>?</a>/</p>\n\n<pre><code>// scanf(\"%zd\", &k);\n// scanf(\"%zd\", &n_elts);\nscanf(\"%zu\", &k);\nscanf(\"%zu\", &n_elts);\n</code></pre>\n\n<hr>\n\n<p><strong>Read until <code>EOF</code></strong></p>\n\n<p>\"I would read until EOF, but then I would have to deal with a growing array, I think.\" --> Yes, good idea. Confident this is up to D. Ben Knoble abilities, so will not post code.</p>\n\n<p>Design idea: pass the <code>k</code> as an <code>argv[]</code> and the array via <code>stdin</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-08T02:02:42.547",
"Id": "448602",
"Score": "0",
"body": "Great feedback. Going to take this into consideration soon (I hope). One follow-up: my copy of the CLRS algorithm textbook gives a proof of this as being `O(n)` (section 9.3: Selection in worst-case linear time)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-08T00:34:51.460",
"Id": "230348",
"ParentId": "230179",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-04T18:33:05.907",
"Id": "230179",
"Score": "2",
"Tags": [
"c",
"programming-challenge"
],
"Title": "Median-of-medians/quickselect filter in C"
}
|
230179
|
<p>A few days ago I saw a nice <a href="https://youtu.be/8lhxIOAfDss" rel="nofollow noreferrer">video on YouTube</a> with prof Thorsten Altenkirch about recursion and the <em>Tower of Hanoi</em> puzzle. Today I tried to reproduce the code from the video and came to this:</p>
<pre><code>A = "A"
B = "B"
C = "C"
def move_one(src, dst):
print("Move piece from {} to {}.".format(src,dst))
def move_multiple(n, src, dst, helper):
if n == 1:
move_one(src, dst)
else:
move_multiple(n-1, src, helper, dst)
move_one(src, dst)
move_multiple(n-1, helper, dst, src)
def main():
move_multiple(4, A, B, C)
if __name__ == "__main__":
main()
</code></pre>
<p>This works fine (although I missed the nice <code>if n == 0</code> then <code>pass</code>) but it still is a little disappointing that we do not have a robot to actually move discs and instead use a <code>print</code> statement to indicate the action. </p>
<p>As a compromise I thought it would be cool to change the <code>print</code> statements to some kind of ASCII animation. I started with a <code>print_world</code> function and <code>print_disc</code>, <code>erase_disc</code> functions that uses ANSI escape codes to create and change the <em>ASCII Hanoi tower world</em> (Works on Linux, mileage on Windows may vary).</p>
<p>After a few hours (with trial an error) my code changed to this:</p>
<pre><code>from time import sleep
import sys
A = "A"
B = "B"
C = "C"
N = 6
UP = "\u001b[A"
DOWN = "\u001b[B"
RIGHT = "\u001b[C"
LEFT = "\u001b[D"
LEAD = " "
SPC = " "
# initial state
state = {
A : list(range(N,0,-1)),
B : [],
C : [],
}
def change_state(src,dst):
global state
state[dst].append(state[src].pop())
def print_world():
"""Print empty Hanoi world, the poles and labels"""
print("\n\n")
print((LEAD + SPC.join([SPC * N + "|" + SPC * N] * 3) + "\n") * N)
print(LEAD + SPC * N + (SPC * (2 * N + 1)).join([A,B,C]))
def print_disc(n, up, right):
"""Print disc of certain size at certain screen coordinates"""
tkn = str(n)
print ( UP * up
+ RIGHT * right
+ SPC * (N-n) + tkn * n + RIGHT + tkn * n + SPC * (N-n)
+ LEFT * (2 * N + 1)
+ LEFT * right
+ DOWN * up,
end = "")
def erase_disc(up, right):
"""Erase disc at certain screen coordinates"""
print ( UP * up
+ RIGHT * right
+ SPC * N + RIGHT + SPC * N
+ LEFT * (2 * N + 1)
+ LEFT * right
+ DOWN * up,
end = "")
def find_screen_pos(pole, height):
up = 3 + height
height = len(LEAD) + (2 * N + 2) * {A:0, B:1, C:2}[pole]
return up, height
def print_state():
global state
for pole, discs in state.items():
for height, disc in enumerate(discs):
up, right = find_screen_pos(pole, height)
print_disc(disc, up, right)
sys.stdout.flush()
def find_screen_path(pole_1, height_1, pole_2, height_2):
cur_up, cur_right = find_screen_pos(pole_1, height_1)
end_up, end_right = find_screen_pos(pole_2, height_2)
direction = 0
if end_right > cur_right : direction = 1
if end_right < cur_right : direction = -1
path = [(cur_up, cur_right)]
while cur_up < N + 4:
cur_up += 1
path.append((cur_up, cur_right))
while cur_right != end_right:
cur_right += direction
path.append((cur_up, cur_right))
while cur_up != end_up:
cur_up -= 1
path.append((cur_up, cur_right))
return path
def animate_move(src, dst):
height_src = len(state[src])-1
height_dst = len(state[dst])
n = state[src][-1]
path = find_screen_path(src, height_src, dst, height_dst)
for old, new in zip(path[:-1], path[1:]):
erase_disc(*old)
print_disc(n, *new)
sys.stdout.flush()
sleep(0.01)
def move_one(src, dst):
animate_move(src, dst)
change_state(src, dst)
sleep(0.2)
def move_multiple(n, src, dst, helper):
if n == 1:
move_one(src, dst)
else:
move_multiple(n-1, src, helper, dst)
move_one(src, dst)
move_multiple(n-1, helper, dst, src)
def main():
print_world()
print_state()
sleep(2.0)
while(True):
move_multiple(N,A,B,C)
sleep(2.0)
move_multiple(N,B,C,A)
sleep(2.0)
move_multiple(N,C,A,B)
sleep(2.0)
if __name__ == "__main__":
main()
</code></pre>
<p>This relatively short piece of code (126 lines) works and at this moment I understand it, but do you, and will I in six month time? What should I change to the code to make it more readable and understandable (I know I've sinned against PEP8 sometimes).</p>
|
[] |
[
{
"body": "<h2>docstrings and comments</h2>\n\n<p>There are lots of formulas in the drawing code, like:</p>\n\n<pre><code>+ SPC * (N-n) + tkn * n + RIGHT + tkn * n + SPC * (N-n)\n</code></pre>\n\n<p>How did you arrive at those. How would they change if you wanted to do some other kind of animation? I would add a ASCII art drawing of a puzzle being solved, annotated with the dimensions and formulas.</p>\n\n<h2>Hidden interfaces</h2>\n\n<p>Hidden interfaces are bad. <code>move_multiple()</code> takes a parameter <code>n</code> that is the number of disks to move. This implies that you can select what size problem to solve by changing <code>n</code>. However, the drawing/animation functions are coded to use a global variable <code>N</code> for the number of discs. And <code>N</code> is hard coded to 6 disks.</p>\n\n<h2>separate concerns</h2>\n\n<p>The function <code>move_one()</code> does three things: 1) starts the animation for a move, 2) helps solve the problem (updating the state), and 3) adds a delay between steps in the animation. That can make it harder to maintain or reuse the code. For example, a year from now, you want to change the delay. Will you remember the delay is in the tower solving code and not somewhere in the animation code? Or you want to modify the code to drive an HTML canvas routine. Will you remember that each animation step is started from <code>move_one()</code>?</p>\n\n<p>It would be better if the problem solving code just solved the problem and the animation code just did the animation. Modify the problem solving code to return a list of moves, or, better yet, turn it into a generator that yields the steps as needed:</p>\n\n<pre><code>INTER_STEP_PAUSE = 0.2\nINTER_PUZZLE_PAUSE = 2.0\n\n# labels for the towers. TODO: internationalize\nTOWER1 = 'A'\nTOWER2 = 'B'\nTOWER3 = 'C'\n\ndef hanoi(n, src, dst, helper):\n \"\"\"A generator to solve an n-disk Tower of Hanoi problem.\n\n It yields the steps for moving a stack of n discs from the source tower\n to the target tower. `helper` is the other tower.\n\n Yields (from, to) tuples, which means move the top disc from `from` to `to`.\n\n Can be used like:\n\n for src, dst in hanoi(3, 'Alpha', 'Bravo', 'Charlie'):\n print(f\"Move disk from {src} to {dst}\")\n \"\"\"\n\n if n == 1:\n yield (source, target)\n\n else:\n hanoi(n-1, source, helper, target)\n hanoi( 1, source, target, helper)\n hanoi(n-1, helper, target, source)\n</code></pre>\n\n<p>Then <code>main()</code> can be something like:</p>\n\n<pre><code>def main():\n n = int(sys.argv[1])\n\n print_world(n)\n print_state(n)\n sleep(2.0)\n\n tower1, tower2, tower3 = LABEL1, LABEL2, LABEL3\n\n while True:\n for source,target in hanoi(n, tower1, tower2, tower3):\n animate(source, target)\n sleep(INTER_STEP_PAUSE)\n\n # rotate the tower and solve it again\n tower1, tower2, tower3 = tower2, tower3, tower1\n sleep(INTER_PUZZLE_PAUSE)\n</code></pre>\n\n<p>Implementing the display and animation code is left as an exercise for the reader.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-05T03:22:39.470",
"Id": "230203",
"ParentId": "230180",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-04T19:15:01.660",
"Id": "230180",
"Score": "1",
"Tags": [
"python",
"recursion",
"console",
"animation",
"ascii-art"
],
"Title": "Tower of Hanoi, ASCII animation with ANSI escape codes"
}
|
230180
|
<p>I'm working on a personal project to get better with C#, and as part of that I have a zip file with 20 or so images saved inside. I want to load those images out of the zip file and display them in my WPF app. I have it working, but I don't know if what I have is the best way to go about this. The goal is to load the images to be used as fast as possible, so I tried using threads, which work, but again I'm not sure if this is the proper way to utilize them for this, or if threads are even the best way to achieve the quickest time for the task.</p>
<p>I would appreciate any feedback anyone could give to help me improve this code and write better code in the future.</p>
<p>In the code below, I have the two functions I use to open and get the images. the variable ChapterLocation is a string that stores the file location of the .zip file, and Pages is a List. Page is a custom struct that just holds a BitmapImage and a String that gives that image a name that I can display.</p>
<pre><code>private void BitmapLoad(ZipArchiveEntry z)
{
using (var stream = z.Open())
{
using (var mstream = new MemoryStream())
{
stream.CopyTo(mstream);
mstream.Position = 0;
var bitmap = new BitmapImage();
bitmap.BeginInit();
bitmap.CacheOption = BitmapCacheOption.OnLoad;
bitmap.StreamSource = mstream;
bitmap.EndInit();
bitmap.Freeze();
Pages.Add(new Page(bitmap, z.Name));
}
}
}
private void LoadChapterOptimized()
{
var zipFile = ZipFile.OpenRead(ChapterLocation);
foreach (ZipArchiveEntry z in zipFile.Entries)
{
Thread t = new Thread(() => BitmapLoad(z));
t.Start();
t.Join();
Debug.WriteLine(z.Name);
}
Pages.Sort();
zipFile.Dispose();
}
</code></pre>
|
[] |
[
{
"body": "<blockquote>\n<pre><code> var zipFile = ZipFile.OpenRead(ChapterLocation);\n ...\n zipFile.Dispose();\n</code></pre>\n</blockquote>\n\n<p>One word: <code>using</code>.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> using (var stream = z.Open())\n {\n using (var mstream = new MemoryStream())\n {\n stream.CopyTo(mstream);\n mstream.Position = 0;\n\n var bitmap = new BitmapImage();\n bitmap.BeginInit();\n bitmap.CacheOption = BitmapCacheOption.OnLoad;\n bitmap.StreamSource = mstream;\n\n bitmap.EndInit();\n bitmap.Freeze();\n</code></pre>\n</blockquote>\n\n<p>This needs a comment explaining why <code>mstream</code> is necessary and you can't just use <code>stream</code>.</p>\n\n<p>I suspect that really <code>mstream</code> is either unnecessary or insufficient. If it's necessary then it's probably because of threading issues due to multiple <code>ZipArchiveEntry</code> streams all reading from one backing stream, and in that case doing the read with <code>stream.CopyTo</code> might be reducing the probability of the problem surfacing rather than actually fixing it.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> foreach (ZipArchiveEntry z in zipFile.Entries)\n {\n Thread t = new Thread(() => BitmapLoad(z));\n t.Start();\n t.Join();\n Debug.WriteLine(z.Name);\n }\n</code></pre>\n</blockquote>\n\n<p>Ah, it's not really multi-threaded after all. If you want to do old-school multithreading then you need to spin off all of the threads before calling <code>Join()</code>.</p>\n\n<p>I say \"<em>old-school</em>\" because a more modern approach would be to use Parallel Linq. Bearing in mind my previous comment about streams, the approach would probably be to map the entries to <code>(string Name, MemoryStream ms)</code>s in one thread and then map those tuples to <code>Page</code>s in parallel threads. I <em>think</em> that this can be written as</p>\n\n<pre><code>Pages = zipFile.Entries.\n Select(z => Read(z)).\n AsParallel().\n Select(tuple => LoadPage(tuple)).\n OrderBy(page => page).\n ToList();\n</code></pre>\n\n<p>but I haven't really used Parallel Linq myself, and I don't guarantee that this does the <code>Read</code> calls all in the same thread.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-05T07:42:09.163",
"Id": "230209",
"ParentId": "230184",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-04T20:06:38.750",
"Id": "230184",
"Score": "7",
"Tags": [
"c#",
"image",
"wpf",
"compression"
],
"Title": "Loading BitmapImages out of a Zip file"
}
|
230184
|
<p>I have this script to format var_export's result string. The information in the output is good, but I need know if the code performance is good or if it can be improved.</p>
<p><a href="https://wtools.io/php-sandbox/biDk" rel="nofollow noreferrer">https://wtools.io/php-sandbox/biDk</a></p>
<pre><code><?php
#Variable:
$Test = [];
$Test['Check1'] = null;
$Test['Check2'] = [];
$Test['Check2']['int'] = 20;
$Test['Check2']['float'] = 20.35;
$Test['Check2']['string'] = 'Hello World';
$Test['Check2']['bolean'] = true;
$Test['Check2']['array'] = [];
$Test['Check2']['array']['data'] = 'Array Text';
class Example {
function foo_function() {
return "Hello World! Object";
}
}
$var_object = new Example;
$Test['Check2']['array']['object'] = $var_object;
$Test['Check2']['array']['object2'] = $var_object->foo_function();
#Script Type:
function myGetType($var) {
if (is_null($var) OR $var == 'null' OR $var == 'NULL') {
return "(NULL)";
}
if (is_array($var)) {
return "array";
}
if (in_array($var, array("true", "false"), true)) {
return "boolean";
}
if ((int) $var == $var && is_numeric($var)) {
return "integer" . '(' . strlen($var) . ')';
}
if ((float) $var == $var && is_numeric($var)) {
return "float" . '(' . strlen($var) . ')';
}
if (is_object($var)) {
return "object";
}
if (is_resource($var)) {
return "resource";
}
if (is_string($var)) {
return "string" . '(' . strlen($var) . ')';
}
return "unknown";
}
#Script Analisis:
function VarExportFormat($Var) {
$textvar = '';
$textvar = var_export($Var, true);
$textvar = preg_replace("/^([ ]*)(.*)/m", '$1$1$2', $textvar);
$textvarArr = preg_split("/\r\n|\n|\r/", $textvar);
# Analisis del tipo.
foreach ($textvarArr as $key => $value) {
preg_match('~=>\\s(.*?),~', $value, $newvalue);
if (!empty($newvalue)) {
$newvalue[1] = str_replace("'", "", $newvalue[1]);
$typeval = myGetType($newvalue[1]);
$value = str_replace("=> ", "=> " . $typeval . ': ', $value);
$textvarArr[$key] = $value;
}
}
$textvarArr = preg_replace(["/\s*array\s\($/", "/\)(,)?$/", "/\s=>\s$/"], [NULL, ']$1', ' => array ['], $textvarArr);
$textvar = join(PHP_EOL, array_filter(["array ["] + $textvarArr));
if (substr($textvar, -1) == '[') {
$textvar = str_replace("[", "[]", $textvar);
}
$textvar = str_replace("__set_state", "__set_state(object)", $textvar);
$textvar = highlight_string("<?php \n#output of Variable:\n" . $textvar . ";\n?>", true);
return $textvar;
}
echo VarExportFormat($Test);
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-05T13:21:21.197",
"Id": "448239",
"Score": "1",
"body": "`(string)$string == $string` can be a replacement aswell for `is_string()`, same trick you did with int and floats.."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-05T13:23:26.160",
"Id": "448241",
"Score": "1",
"body": "`(object)$var == $var` and `(array)$var == $var` can also works aswell to replace is_object and is_array but performance is more depending on the object or array size and or PHP version, this trick does not scale that that well as the int, string types.. Might be interesting to test with?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-05T13:35:48.640",
"Id": "448248",
"Score": "1",
"body": "Using [token_get_all()](https://www.php.net/manual/en/function.token-get-all.php) -> *\"token_get_all() parses the given source string into PHP language tokens using the Zend engine's lexical scanner. \"* seams to be making much more sense.. As you are making a parser/lexer color based syntax highlighter as `var_export()` returns parseable PHP..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-05T13:46:51.760",
"Id": "448254",
"Score": "1",
"body": "@Raymond please do not abuse comments and break SE page design. If you want to provide a review, then post an answer. Comments should be used to request clarifications. Please remove all of your comments after posting your answer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-05T13:55:22.180",
"Id": "448257",
"Score": "1",
"body": "*\" Please remove all of your comments after posting your answer.\"* @mickmackusa not going to place a answer/review as mine comments are heavy based on PHP version... Also comments are meant to possibly provide extra information where [possible](https://meta.stackexchange.com/questions/19756/how-do-comments-work).. -> *\"Comments exist so that users can talk about questions and answers without posting new answers that do not make an attempt to answer the question asked. Comments are often used to ask for clarification on, **suggest corrections to**, and provide meta-information about posts. \"*"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-05T15:43:08.113",
"Id": "448280",
"Score": "0",
"body": "I need to clarify that the main variable result of var_export is a string and therefore I cannot use is_string (), is_float, is_integer, because is_string will always be valid, I must evaluate if the string can be converted to the other types to validate them so use (int) (float) etc, and then I make the comparison == (without type)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-23T04:09:56.137",
"Id": "450665",
"Score": "0",
"body": "Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*."
}
] |
[
{
"body": "<p>Your script is like a <code>var_export()</code>-<code>var_dump()</code> hybrid with flare (I've not come across <code>highlight_string()</code> before -- pretty cool).</p>\n\n<ol>\n<li><p>I ran some more tests with a few samples that I had laying around and noticed that your code is having some difficulties accessing the written \"resource\" branch. I tested with <code>fopen($filename, 'r')</code>; the <code>var_export()</code> evaluation of a resource is <code>NULL</code> and <code>var_dump()</code> returns <code>resource(5) of type (stream)</code>. Because your script is founded on <code>var_export()</code>, it will fail to dignify the <code>resource</code> type data, I think you [sh/c]ould remove that from your battery of checks.</p></li>\n<li><p>Miscellaneous gotchas include:</p>\n\n<pre><code>['a => key' => 'something']\n</code></pre>\n\n<p>and</p>\n\n<pre><code>['multiline' => 'line1\nline2']\n</code></pre>\n\n<p>These will break your regex-based parsing -- of course, the former is going to be a much less common occurrence versus the latter.</p></li>\n<li><p>You can safely remove some useless declarations:</p>\n\n<ul>\n<li><code>$Test = [];</code> and <code>$textvar = '';</code></li>\n</ul></li>\n<li><p>As a general rule, I prefer to never use <code>OR</code> or <code>AND</code> in my conditional statements as a matter of consistency and as a means to avoid fringe precedence issues.</p></li>\n<li><p><code>preg_replace(\"/^([ ]*)(.*)/m\", '$1$1$2', $textvar);</code> This pattern/function is over-performing. It doesn't make any sense to pick up the second capture group, just to put it back down unaltered. In fact, there is no need for capture groups or character classes for this task. I will also recommend that you use a consistent pattern delimiter for all patterns in your script. A tilde is a good/popular choice because it shouldn't interfere with any of your patterns and will help to prevent any accidental typos and escaping problems elsewhere. To double the leading whitespace on each line, just use this (there's no use doubling zero whitespaces, so match one-or-more with <code>+</code>):</p>\n\n<pre><code>preg_replace('~^ +~m', '$0$0', $textvar);\n</code></pre></li>\n<li><p><code>$textvarArr = preg_split(\"/\\r\\n|\\n|\\r/\", $textvar)</code> is more succinctly written as:</p>\n\n<pre><code>$textvarArr = preg_split(\"~\\R~\", $textvar)\n</code></pre></li>\n<li><p>Whenever I see <code>preg_match()</code> called inside of a loop so that replacement actions can be performed, this is a classic indicator that <code>preg_replace_callback()</code> should be called.</p>\n\n<pre><code>$textvarArr = preg_split(\"~\\R~\", $textvar);\nforeach ($textvarArr as $key => $value) {\n preg_match('~=>\\\\s(.*?),~', $value, $newvalue);\n if (!empty($newvalue)) {\n $newvalue[1] = str_replace(\"'\", \"\", $newvalue[1]);\n $typeval = myGetType($newvalue[1]);\n $value = str_replace(\"=> \", \"=> \" . $typeval . ': ', $value);\n $textvarArr[$key] = $value;\n }\n}\n</code></pre>\n\n<p>can become:</p>\n\n<pre><code>$textvar = preg_replace_callback(\n \"~ => \\K\\V+(?=,)~\", \n function ($m) {\n return myGetType(str_replace(\"'\", \"\", $m[0])) . \": {$m[0]}\";\n },\n $textvar\n);\n// then proceed with something like...\n$textvarArr = preg_replace([\"/\\s*array\\s\\($/\", \"/\\)(,)?$/\", \"/\\s=>\\s$/\"], [NULL, ']$1', ' => array ['], preg_split(\"~\\R~\", $textvar));\n</code></pre></li>\n<li><p>I've got to say that this looks a little dangerous...</p>\n\n<pre><code>if (substr($textvar, -1) == '[') {\n $textvar = str_replace(\"[\", \"[]\", $textvar);\n}\n</code></pre>\n\n<p>I mean, you are checking the final character, then doing a full text scan and replace operation. This deserves a bit of double-checking. Don't you only mean to close the final square brace? Maybe...</p>\n\n<pre><code>if (substr($textvar, -1) == '[') {\n $textvar .= \"]\";\n}\n</code></pre></li>\n</ol>\n\n<p>I didn't get a chance to properly review (but it could probably use a little polish/simplifying):</p>\n\n<pre><code>$textvarArr = preg_replace([\"/\\s*array\\s\\($/\", \"/\\)(,)?$/\", \"/\\s=>\\s$/\"], [NULL, ']$1', ' => array ['], preg_split(\"~\\R~\", $textvar));\n$textvar = join(PHP_EOL, array_filter([\"array [\"] + $textvarArr));\n</code></pre>\n\n<p>I ran our outputs on a diffchecker program to be sure that my script returns the exact same output as yours.</p>\n\n<p>Overall, an interesting exercise, good job.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-05T13:35:56.683",
"Id": "448249",
"Score": "1",
"body": "I have no idea the ramifications of rebuilding this script on that function. I have only ever seen that function used on this site (never anywhere else in the SE network). I am happy for you to demonstrate."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-05T13:41:15.677",
"Id": "448252",
"Score": "1",
"body": "I don't see `resource` on that list either."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-05T15:43:17.863",
"Id": "448281",
"Score": "0",
"body": "I need to clarify that the main variable result of var_export is a string and therefore I cannot use is_string (), is_float, is_integer, because is_string will always be valid, I must evaluate if the string can be converted to the other types to validate them so use (int) (float) etc, and then I make the comparison == (without type)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-05T15:44:04.420",
"Id": "448282",
"Score": "0",
"body": "the link you provided not have your personalized code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-05T15:57:15.897",
"Id": "448285",
"Score": "0",
"body": "1. It is correct, I will do more testing and verify if I can give you the scope for resources.\n2. In the case what would you recommend to do?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-05T16:48:38.397",
"Id": "448289",
"Score": "0",
"body": "3. They are declarations for tests, since I imagined that they would ask me for a functional example, I can declare an array with a simpler declaration, but some new users would not fully understand it.\n4. Replace them in the myGetType conditionals."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-05T16:49:48.253",
"Id": "448290",
"Score": "0",
"body": "5. I think duplicate blanks are to keep an indented to 4 spaces.\n6. Thank you I will take it into account and try it.\n7. Thank you I will take it into account and try it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-05T16:50:17.533",
"Id": "448291",
"Score": "0",
"body": "8. It happens that if the past value is a null variable, it does not close the square bracked. and that's why I have to do a verification and close it manually, I didn't find another solution."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-05T16:58:49.617",
"Id": "448293",
"Score": "0",
"body": "in your comment 7. `$textvarArr = preg_replace([\"/\\s*array\\s\\($/\", \"/\\)(,)?$/\", \"/\\s=>\\s$/\"], [NULL, ']$1', ' => array ['], preg_split(\"~\\R~\", $textvar));` trown error: preg_split() expects parameter 2 to be string, array given"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-05T22:19:13.327",
"Id": "448308",
"Score": "0",
"body": "Notice in my snippet at #7, I am using the string `$textvar` in `preg_replace_callback()`, its output, and the `preg_split()` call -- the data stays as a string until it is split into an array on the last line. You may have a typo with `Arr`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-06T16:09:24.690",
"Id": "448389",
"Score": "0",
"body": "you can add more about my question of every section you comment..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-22T14:37:46.937",
"Id": "450588",
"Score": "1",
"body": "i have make other post result of it... if you can help me with this: https://stackoverflow.com/questions/58458584/something-wrong-with-regular-expressions?noredirect=1#comment103319154_58458584"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-22T14:42:51.837",
"Id": "450589",
"Score": "1",
"body": "Gotta sleep. Maybe tomorrow."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-22T14:43:30.913",
"Id": "450590",
"Score": "0",
"body": "no problem i wait for you :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-22T23:58:32.630",
"Id": "450643",
"Score": "0",
"body": "i have meet finish the script, but i dont know if is the best way to get the output of data, can you check my Link sandbox."
}
],
"meta_data": {
"CommentCount": "15",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-05T00:11:25.890",
"Id": "230198",
"ParentId": "230185",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "230198",
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-04T20:16:41.647",
"Id": "230185",
"Score": "5",
"Tags": [
"performance",
"php",
"parsing",
"formatting"
],
"Title": "Parsing and formatting var_export() string"
}
|
230185
|
<p>I have a number of async calls that get chained conditionally based on the previous data dependency. I.e. perform call A -> if the result is defined/not an error execute a side effect, if not perform another call. </p>
<p>I originally started with nested subscribes but I was told that is not a good practice. Next I moved to rxjs operations (which I believe are function compositions in this context) and used tap, as we have side-effects. This still looks pretty ugly, wondering if there are any suggestions to improve on this (One thing that I am aware of is I can abstract the general pattern into a </p>
<pre><code>if(undefined) callback else side-effect
</code></pre>
<p>function. Appreciate any other feedback</p>
<pre><code>this.userService.expandUser().pipe(
tap((user: User) => { //flatMap equivilant of Scala
if(user == undefined){
this.userService.setUndefined();
this.bandService.expandBand().pipe(
tap((band: Band) => {
if(band == undefined){
this.bandService.setUndefined()
this.shadowService.checkShadowsStatus().pipe(
tap(result => {
if(!result){
this.shadowService.createShadowUser().pipe(
tap(result => {
this.shadowService.shadowSet = true;
})
)
}else{
this.shadowService.shadowSet = true;
}
})
)
}else{
this.bandService.setBand(band)
}
})
)
}else{
this.userService.setUser(user)
}
})
)
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-04T20:42:51.553",
"Id": "230188",
"Score": "1",
"Tags": [
"typescript",
"angular-2+"
],
"Title": "Angular 6+ Conditionally Chained HTTP Calls"
}
|
230188
|
<p>I'm writting this poker hand evaluator and it's really coming along. But, as you can see I repeat myself many times and I would love to know what's your thought process when you're repeating yourself? Other than this, it's not finished. I still need to account for high cards etc. But you get the jist of it. I'm really working hard on this one and I hope it shows.</p>
<p>Please be blunt! Take it out on me today. :)</p>
<p>The program is split into two files:</p>
<p>analyzer.py and goodhands.py in that order.</p>
<p>This is the main program for running the analyzer: analyzer.py</p>
<pre><code>"""Poker hand probalities"""
hands = 0
while True:
from goodhands import *
import random
from time import sleep
from collections import Counter
def deck():
"""Makes a list of 52 shuffled cards """
suits = "♣♦♥♠"
letts = "JQKA"
specials = [char + suit for suit in suits for char in letts]
numbers = [str(num) + suit for suit in suits for num in range(2, 11)]
deck = numbers + specials
shuffled = random.sample(deck, len(deck))
return shuffled
win_deck_check = deck()[:]
deck = deck()
def players():
"""Make a dictionary of players to store the values of cards"""
players = {"p" + str(num):None for num in range(1, 10)}
return players
players = players()
def dealer(deck):
"""Assign one card per player for two turns for a total of two cards"""
CARD_COUNT = 0
deck.pop(CARD_COUNT) # Discard the first card of the deck.
deal = True
table = {}
while deal:
for i in players:
players[i] = deck[CARD_COUNT] # Assign the first card.
CARD_COUNT += 1
if CARD_COUNT == len(players):
for i in players:
players[i] = players[i] + deck[CARD_COUNT] # Assign the second card.
CARD_COUNT += 1
del deck[:18] # Delete player cards from deck.
for i in range(3):
table['flop'] = deck[1] + deck[2] + deck[3]
del deck[:4]# Delete flop from deck.
table['turn'] = deck[0]
table['river'] = deck[2]
del deck[:3] # Delete turn and river from deck.
break
return players, table
plays = dealer(deck)
# Player hand outcome.
pone = max(good_hands(plays, 0)) if good_hands(plays, 0) else None
ptwo = max(good_hands(plays, 1)) if good_hands(plays, 1) else None
pthree = max(good_hands(plays, 2)) if good_hands(plays, 2) else None
pfour = max(good_hands(plays, 3)) if good_hands(plays, 3) else None
pfive = max(good_hands(plays, 4)) if good_hands(plays, 4) else None
psix = max(good_hands(plays, 5)) if good_hands(plays, 5) else None
pseven = max(good_hands(plays, 6)) if good_hands(plays, 6) else None
peight = max(good_hands(plays, 7)) if good_hands(plays, 7) else None
pnine = max(good_hands(plays, 8)) if good_hands(plays, 8) else None
outcome = [pone, ptwo, pthree, pfour, pfive, psix, pseven, peight, pnine]
hands += 1
if hands == 1:
break
print(outcome)
print(plays)
</code></pre>
<p>This is the analyzer itself: goodhands.py</p>
<pre><code>from collections import Counter
def good_hands(plays, player):
good_hands = [] # This list will hold all the winning values.
table = plays[1] # This is the flop, turn and river.
player_cards = list(plays[0].values()) # List of player_cards
table_list = "".join(list(table.values())) # list of table values.
all_cards = [i + table_list for i in player_cards] # Player cards with table values.
occurrences = list(Counter(all_cards[player]).items()) # Counter is used to make a dict with all the occurences. i.e. "k":2 is two K's.
count = 0
letters = "JQKA"
suits = "♣♦♥♠"
# Card Counters
atofive = 0
twosix = 0
threeseven = 0
foureight = 0
fivenine = 0
six_ten = 0
seventoj = 0
eighttoq = 0
ninetok = 0
tentoa = 0
royal_flush = 0
# This will replace "1" and "0" with a "10"
for i in occurrences:
if "1" in i[0]:
occurrences.remove(i)
for i in occurrences:
if "0" in i[0]:
occurrences.remove(i)
occurrences.append(("10",i[1]))
for i in occurrences:
if i[0].isdigit() == True: # i[0] is the Suit or the number of a card
card_value = int(i[0])
# A - 5 LOW STRAIGHT
if i[0]:
if i[0] == "A":
atofive +=1
if i[0].isdigit():
for n in range(2, 6):
if int(i[0]) == n:
atofive += 1
if atofive == 5 and 21 not in good_hands:
good_hands.append(21)
# 2 - 6 LOW STRAIGHT
if i[0].isdigit() == True:
for n in range(2, 7):
if int(i[0]) == n:
twosix += 1
if twosix == 5 and 21.1 not in good_hands:
good_hands.append(21.1)
# 3 - 7 LOW STRAIGHT
if i[0].isdigit() == True:
for n in range(3, 8):
if int(i[0]) == n:
threeseven += 1
if threeseven == 5 and 21.2 not in good_hands:
good_hands.append(21.2)
# 4 - 8 LOW STRAIGHT
if i[0].isdigit() == True:
for n in range(4, 9):
if int(i[0]) == n:
foureight += 1
if foureight == 5 and 21.3 not in good_hands:
good_hands.append(21.3)
# 5 - 9 LOW STRAIGHT
if i[0].isdigit() == True:
for n in range(5, 10):
if int(i[0]) == n:
fivenine += 1
if fivenine == 5 and 21.4 not in good_hands:
good_hands.append(21.4)
# 6 - 10 LOW STRAIGHT
if i[0].isdigit() == True:
for n in range(6, 11):
if int(i[0]) == n:
six_ten += 1
if six_ten == 5and 21.5 not in good_hands:
good_hands.append(21.5)
# 7 - J MID STRAIGHT
if i[0]:
if i[0] == "J":
seventoj +=1
if i[0].isdigit():
for n in range(7, 11):
if int(i[0]) == n:
seventoj += 1
if seventoj == 5 and 21.6 not in good_hands:
good_hands.append(21.6)
# 8 - Q MID STRAIGHT
if i[0]:
if i[0] == "J":
eighttoq +=1
if i[0] == "Q":
eighttoq +=1
if i[0].isdigit():
for n in range(8, 11):
if int(i[0]) == n:
eighttoq += 1
if eighttoq == 5 and 21.7 not in good_hands:
good_hands.append(21.7)
# 9 - k HIGH STRAIGHT
if i[0]:
if i[0] == "J":
ninetok +=1
if i[0] == "Q":
ninetok +=1
if i[0] == "K":
ninetok +=1
if i[0].isdigit():
for n in range(9, 11):
if int(i[0]) == n:
ninetok += 1
if ninetok == 5 and 21.8 not in good_hands:
good_hands.append(21.8)
# 10 - A HIGHEST STRAIGHT
if i[0]:
if i[0] == "10":
tentoa += 1
if i[0] == "J":
tentoa +=1
if i[0] == "Q":
tentoa +=1
if i[0] == "K":
tentoa +=1
if i[0] == "A":
tentoa += 1
if tentoa == 5 and 21.9 not in good_hands:
good_hands.append(21.9)
if i[0].isdigit() == True and i[1] == 2: # i[1] are the instances
count += 1
if card_value <= 6:
good_hands.append(0) # Low Pair
if card_value > 6 and card_value <= 9:
good_hands.append(1) # Mid Pair
if card_value == 10:
good_hands.append(2) # Mid-High Pair
# Two Pair
if i[0].isdigit() == True and count == 2:
good_hands.append(9)
# Letters Pairs
if i[0] in letters:
if i[1] == 2:
if i[0] == "J":
good_hands.append(3) # Mid-High
if i[0] == "Q":
good_hands.append(4) # High Pair
if i[0] == "K":
good_hands.append(5) # High Pair
if i[0] == "A":
good_hands.append(10) # Highest Pair
# Letter Trips
if i[1] == 3:
if i[0] == "J":
good_hands.append(11.90)
if i[0] == "Q":
good_hands.append(11.91)
if i[0] == "K":
good_hands.append(11.92)
if i[0] == "A":
good_hands.append(11.93)
# Letter Quads
if i[1] == 4:
if i[0] == "J":
good_hands.append(25.90)
if i[0] == "Q":
good_hands.append(25.91)
if i[0] == "K":
good_hands.append(25.92)
if i[0] == "A":
good_hands.append(25.93)
# Letter QUADS VALUE OF **** 20 *****
# Num Trips
if i[0].isdigit() == True and i[1] >= 3:
if [0] == "2":
good_hands.append(11.1)
if [0] == "3":
good_hands.append(11.2)
if [0] == "4":
good_hands.append(11.3)
if [0] == "5":
good_hands.append(11.4)
if [0] == "6":
good_hands.append(11.5)
if [0] == "7":
good_hands.append(11.6)
if [0] == "8":
good_hands.append(11.7)
if [0] == "9":
good_hands.append(11.8)
# Number Quads
if i[1] == 4:
if [0] == "2":
good_hands.append(25.1)
if [0] == "3":
good_hands.append(25.2)
if [0] == "4":
good_hands.append(25.3)
if [0] == "5":
good_hands.append(25.4)
if [0] == "6":
good_hands.append(25.5)
if [0] == "7":
good_hands.append(25.6)
if [0] == "8":
good_hands.append(25.7)
if [0] == "9":
good_hands.append(25.8)
# Full House
pairs = [0,1,2,3,4,5,10]
trips = [11.1, 11.2, 11.3, 11.4,
11.5, 11.6, 11.7, 11.8,
11.9, 11.91, 11.92, 11.93, 11.93]
for p in pairs:
if p in good_hands:
for t in trips:
if t in good_hands and 26 not in good_hands:
good_hands.append(26)
# Flush
if i[0].isdigit() == False and i[1] == 5:
good_hands.append(23)
# Straight Flushes
# Royal Flush
p1_cards = all_cards[0]
royal_count = 0
for suit in suits:
if "10" + suit in p1_cards:
royal_count += 1
if "J" + suit in p1_cards:
royal_count += 1
if "Q" + suit in p1_cards:
royal_count += 1
if "K" + suit in p1_cards:
royal_count += 1
if "A" + suit in p1_cards:
royal_count += 1
if royal_count == 5:
print("ROYAL FLUSH!!!!")
good_hands.append(100)
return good_hands
</code></pre>
<p>I'm more than thankful for the advice because I really need it. I've been coding 'seriously' for about two months after one year off.</p>
|
[] |
[
{
"body": "<p><strong>Note:</strong> general observation before starting to say anything about code written here, my humble not important in any way opinion here is, this might be too far advanced than your current level of coding skills given by the way you write your code I suggest that you write simpler codes first, get used to what's wrong and what's right and then scale your programs as you go through your learning journey. The amount of mistakes here is insane. Even if this code does the job you created for, this might be the machine understands the instructions you presented, however a code is meant to be interpreted by machines and read by human beings and it's ultra-hard to make sense of your code.</p>\n\n<p>A better example: <a href=\"https://codereview.stackexchange.com/questions/144551/find-and-display-best-poker-hand\">Find and display best Poker hand</a> I suggest you check this if your code is meant to assess a poker hand, might give you some idea on other approaches to write a similar code.</p>\n\n<p>As I remember mentioning earlier in your previous card game <a href=\"https://codereview.stackexchange.com/questions/229822/my-second-game-war-card-game-v-1\">My second game: War Card game V.1</a> to refer to PEP0008 when writing your code <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">https://www.python.org/dev/peps/pep-0008/</a></p>\n\n<ul>\n<li><p><strong>An infinite loop full of imports and function definitions:</strong> analyzer.py and goodhands.py (both contain the same approach)</p>\n\n<pre><code>while True:\n from goodhands import *\n import random \n</code></pre>\n\n<p>Let me explain the main structure of your program: you keep defining your functions each time you go through the loop and keep importing things as well.\nThis is a terribly inefficient and poor structure. A loop is meant to automate repetitive tasks. In some cases functions are defined inside loops and since this is not one of them, your functions should be defined outside the loop plus import statements according to PEP0008 should be always at the top of your script.</p></li>\n<li><strong>Possible bug:</strong> When I run the one you call analyze.py I get this result <code>[21.5, 0, 2, None, 23, 5, None, None, 5]</code> and sometimes a list full of numbers which is inconsistent and very ambiguous to anyone trying to make sense of the code. And this is due to the fact that in your goodhands.py, there are 10 p1 through p10 that have a value or a None value(What is this exactly?)</li>\n<li><strong>Docstrings and type hints:</strong> I will not repeat myself defining what those are(refer to your earlier post where I explained what those are) your function <code>good_hands()</code> is A) Ultra long (250 lines for 1 function) that's a mess, you should break it into several functions doing specific tasks in probably 75% less than this and B)Type hints and docstrings are absent and it's hard for anyone trying understand your code to make conclusions about what this function does and what the parameters <code>plays</code> and <code>player</code> are. They could be strings, lists, dicts ...</li>\n<li><p><strong>DRY code</strong>: Which stands for DON'T REPEAT YOURSELF! opposite to <strong>WET</strong> 'write everything twice' There are loops that automate repeating tasks, if you find yourself repeating a code even twice ... think again.</p>\n\n<p>Terrible repetitions in <code>good_hands()</code>:</p>\n\n<p><code>for i in occurrences:</code> repeated 3 times</p>\n\n<p><code>if i[0].isdigit() == True:</code> repeated 13 times!</p></li>\n<li><p><strong>How to Never Ever do this? It's done in the following way:</strong></p>\n\n<pre><code>if i[0].isdigit():\n # do 1\n # do 2\n # do 3\n # ...\n # do 13\n</code></pre>\n\n<p>The if <code>i[0].isdigit():</code> shows up once and contains 13 things to execute instead of the 13 repetitions.</p></li>\n<li><p><strong>Comparison to True:</strong> I also remember mentioning this as well in your previous game, whenever you have a condition, you shouldn't be\ncomparing to True and false <code>if condition == True:</code> is the same as <code>if condition:</code> \nand if <code>condition == False:</code> is the same as <code>if not condition:</code></p></li>\n<li><p><strong>Naming:</strong> you should Never Ever repeat an identifier name ... also in <code>good_hands()</code> there is a list called <code>good_hands</code> what is\nhappening here is first good_hands was a function and inside its\nbody, it became a list ... this is terribly wrong, maybe it did not\nproduce side effects and maybe it did, I don't know however this is a\nno no never situation. Same goes for <code>deck = numbers + specials</code> in \n<code>deck()</code> function, <code>players = {\"p\" + str(num): None for num in range(1, 10)}</code> in <code>players()</code> function.</p></li>\n<li><p><strong>A dictionary that becomes a list:</strong> <code>occurrences = list(Counter(all_cards[player]).items())</code> Is there any explanation here to why are you listing the <code>Counter()</code> dict?</p></li>\n<li><p><strong>Magic numbers:</strong> and the list of magic numbers in your code can never be exhausted ... Examples:</p>\n\n<ul>\n<li>lines 17 to 27 in <code>good_hands()</code> what are these variables that have values of 0 (all of them)</li>\n<li>line 34 <code>if \"0\" in i[0]:</code> what is '0'?</li>\n<li>line 45 <code>for n in range(2, 6):</code> what is n? why <code>range(2, 6)</code> why not <code>range(2, 9)</code>?</li>\n<li>line 48 <code>if atofive == 5 and 21 not in good_hands:</code> what is 5? what is 21?</li>\n<li>line 52 <code>for n in range(2, 7):</code> what is 2? why 7?</li>\n<li>And as I said the list is endless, so I won't go through them all but you must've got the point</li>\n</ul></li>\n<li><p><strong>Nested structures:</strong> line 237 through 250</p>\n\n<pre><code>for suit in suits:\n if \"10\" + suit in p1_cards:\n royal_count += 1\n if \"J\" + suit in p1_cards:\n royal_count += 1\n if \"Q\" + suit in p1_cards:\n royal_count += 1\n if \"K\" + suit in p1_cards:\n royal_count += 1\n if \"A\" + suit in p1_cards:\n royal_count += 1\n if royal_count == 5:\n print(\"ROYAL FLUSH!!!!\")\n good_hands.append(100)\n</code></pre>\n\n<p>This is seriously terrible: 6 nested ifs? and what for? the conditions do not depend on each other and can be:</p>\n\n<pre><code>for suit in suits:\n if \"10\" + suit in p1_cards:\n royal_count += 1\n if \"J\" + suit in p1_cards:\n royal_count += 1\n if \"Q\" + suit in p1_cards:\n royal_count += 1\n if \"K\" + suit in p1_cards:\n royal_count += 1\n if \"A\" + suit in p1_cards:\n royal_count += 1\n if royal_count == 5:\n print(\"ROYAL FLUSH!!!!\")\n good_hands.append(100)\n</code></pre></li>\n<li><p><strong>False shuffle:</strong> I also mentioned this as well in your previous game, <code>shuffled = random.sample(deck, len(deck))</code> does not shuffle, it creates card duplicates and I remember the <code>set()</code> example I used earlier produced 43 cards instead of 52. To properly shuffle, use <code>random.shuffle(list_name)</code> and after shuffling return the list unless there is no point to shuffle in the first place(which is the case here) because the card selection is already random so there is no point in shuffling the list and as I can see you copied the <code>deck()</code> function I presented in the early review without understanding how it works, never copy a code unless you fully understand it(and copying code is not the best way to become a good programmer).</p></li>\n<li><p><strong>main guard:</strong> was also mentioned earlier(please revise the previous feedbacks) </p>\n\n<pre><code>print(outcome)\nprint(plays)\n</code></pre>\n\n<p>should be inside <code>if __name__ == '__main__':</code> at the end of your script after the elimination of the while loop that continuously defines and imports things in the following structure:</p>\n\n<pre><code>import thing_one\nimport thing_two\n\n\ndef func1:\n\ndef func2:\n\ndef func3:\n\n# ...\n\nif __name__ == '__main__':\n # do things\n</code></pre></li>\n<li><p><strong>Useless code:</strong></p>\n\n<pre><code> hands += 1\n if hands == 1:\n break\n</code></pre>\n\n<p>should be just <code>break</code> (given that the while loop is not already useless)</p></li>\n<li><p><strong>Code structure suggestions:</strong> Finally a better way to do this(which is an assignment left to you) if you insist on working on something with that level of difficulty, I suggest making the following functions:\nA) a deck builder B) A poker hand scoring function C)A hand assessor/analyzer/comparison function and you might break these functions down to smaller functions and you go from there.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-05T03:39:28.347",
"Id": "448180",
"Score": "1",
"body": "They don't call you the bullseye for nothing. Thank you for your constructive criticism. I will re-read the comments on my other codes and really analyze what's wrong with my pov. Your last statement really hit the nail or the bullseye. I literally jumped the gun and started coding like a maniac without dividing my code neatly. And, Bro do you even if? Should be on my forehead for the time being. Thanks again."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-05T03:52:08.860",
"Id": "448181",
"Score": "1",
"body": "Haha, thanks man i'm not that good, you'll sooner or later get used to how to think more like a computer and for the 'starting to code like a maniac' part, I suggest before you start writing the code to decide on the structure of your program and might change that along the way and avoid repetition and make it as short as possible."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-05T05:50:16.767",
"Id": "448189",
"Score": "2",
"body": "I'll add to the mention of PEP-8: there are two utilities you can install to help with your coding style: `flake8` and `pylint`. Both can be installed with `pip install flake8` (or `pylint`). Both install command line utilities you can run like `flake8 myfile.py` which will report style and potential code-bug issues with your code. For code to be reviewed, it would be a good idea to clean the code up with one or both of those tools prior to posting -- it eliminates a whole class of complaints from reviewers."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-05T05:54:27.867",
"Id": "448190",
"Score": "0",
"body": "hahaha 'it eliminates a whole class of complaints' I agree."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-06T01:47:06.620",
"Id": "448319",
"Score": "0",
"body": "Thanks for your input Austin. 100% will look into it for the next round."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-06T19:04:47.073",
"Id": "448443",
"Score": "0",
"body": "@Python Novice You can use the _beginner_ tag if you want reviewers to know your level in programming. Beginners tend to get different reviews. Though this user has taken your level into account in this very fine answer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-08T12:08:48.320",
"Id": "448664",
"Score": "1",
"body": "Good points. I'd just like to mentioned two things regarding the \"An infinite loop full of imports and function definitions\" bit though: afaik, re-importing an already imported module is a no-op. It doesn't actually re-import the module, so there shouldn't be any overhead costs (although, as you said, they should still be at the top regardless for correctness). I also wouldn't say that there's never a reason to define a function in a loop. If the function closes over the loop vars, it may be neater than passing them in. Especially since PEP8 discourages \"named lambdas\", it may be necessary."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-08T12:45:03.653",
"Id": "448673",
"Score": "1",
"body": "What @Carcigenicate said. Claiming that _function definitions should Never be inside a loop Ever_ is not true in general. Sometimes closures are needed."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-08T17:48:15.250",
"Id": "448708",
"Score": "0",
"body": "Okay, I'll rephrase"
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-05T02:52:32.120",
"Id": "230202",
"ParentId": "230189",
"Score": "9"
}
},
{
"body": "<p>Whenever you see large amounts of duplication, you should think about what's different about each piece, and what's the same. Once you see what's different, you can try to \"automate\" the duplicated bits.</p>\n\n<p>For example, look at this code:</p>\n\n<pre><code>pone = max(good_hands(plays, 0)) if good_hands(plays, 0) else None\nptwo = max(good_hands(plays, 1)) if good_hands(plays, 1) else None\npthree = max(good_hands(plays, 2)) if good_hands(plays, 2) else None\npfour = max(good_hands(plays, 3)) if good_hands(plays, 3) else None\npfive = max(good_hands(plays, 4)) if good_hands(plays, 4) else None\npsix = max(good_hands(plays, 5)) if good_hands(plays, 5) else None\npseven = max(good_hands(plays, 6)) if good_hands(plays, 6) else None\npeight = max(good_hands(plays, 7)) if good_hands(plays, 7) else None\npnine = max(good_hands(plays, 8)) if good_hands(plays, 8) else None\n</code></pre>\n\n<p>Every line is nearly identical. The only differences are the second argument passed to <code>good_hands</code>, and the name of the variable that you're creating. You're also calling <code>good_hands</code> twice as often as needed, and that looks like a very expensive function.</p>\n\n<p>This block can be easily automated though. To generate numbers, you can use <code>range</code>, and once you have a range of numbers, you can just loop over them:</p>\n\n<pre><code>outcome = []\n\nfor n in range(9):\n # Save the result instead of doing large amounts of work twice per n\n result = good_hands(plays, n)\n\n play = max(result) if result else None\n\n outcome.append(play)\n</code></pre>\n\n<p>Note how there is next to no duplication in this code. It can be improved further though. Whenever you want to turn one sequence into another sequence, you should consider using <code>map</code> (or, in Python specifically, a list comprehension).</p>\n\n<p>That whole original chunk you had can be expressed in two, quite terse lines:</p>\n\n<pre><code>raw_results = [good_hands(plays, n) for n in range(9)] # Calls good_hands on each n\n\noutcome = [max(result) if result else None for result in raw_results] # Then finds the max of each (or None if it's falsey)\n</code></pre>\n\n<p>While this is arguably better, I'm not super happy with it. This really could be one simple line (and avoid the extra overhead) if you didn't need to call <code>max</code>, or you were using Python 3.8. Because you need to call <code>max</code> on a potentially invalid result returned by <code>good_hands</code>, you really need an intermediate variable to avoid calling <code>good_hands</code> twice. I achieved that here by splitting the operation over two list comprehensions. In Python 3.8 though, I'd be able to make use of an <a href=\"https://www.python.org/dev/peps/pep-0572/\" rel=\"nofollow noreferrer\">assignment expression</a> and create a variable inside the comprehension:</p>\n\n<pre><code>outcome = [max(r) if (r := good_hands(plays, n)) else None) for result in raw_results]\n</code></pre>\n\n<p>Although this doesn't really read well. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-29T17:52:26.393",
"Id": "477136",
"Score": "0",
"body": "Automate isn't the right verb, rather \"factor out\" the commonality."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-05T23:26:51.910",
"Id": "230243",
"ParentId": "230189",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-04T21:50:15.507",
"Id": "230189",
"Score": "8",
"Tags": [
"python",
"beginner",
"python-3.x",
"playing-cards"
],
"Title": "My third game - Poker hand strength analyzer"
}
|
230189
|
<p>I just finished this command-line implementation of the Mastermind board game that allows two players to play against each other. I'm fairly new to Ruby, but I think I did a decent job with this. However, I'm sure there are some things I could've done better, so please let me know if there are.</p>
<pre><code>class Codebreaker
attr_accessor :colors
def initialize
@colors = []
end
end
</code></pre>
<pre><code>require 'io/console'
class Codemaker
attr_accessor :code_colors
def make_code
puts "\nCodemaker, select 4 colors! Please enter them separated by spaces, with no commas. To prevent cheating, your input will be hidden. Try to not make any typos :)"
input = STDIN.noecho(&:gets).chomp
@code_colors = input.split(" ")
puts "Excellent!"
end
end
</code></pre>
<pre><code>class Game
require_relative "codebreaker.rb"
require_relative "codemaker.rb"
def initialize
@code_breaker = Codebreaker.new
@code_maker = Codemaker.new
@turn = 1
start_game
end
def start_game
puts "Welcome to Mastermind!
\nRules:
\nThe codemaker creates a code consisting of four colors chosen from the provided list.
It is the goal of the codebreaker to crack the code in 12 turns, entering the same exact colors in the same order. To attempt to crack the code, simply
keep guessing.
\nYou may choose from the following colors: red, blue, green, yellow, orange, purple, white, and black."
@code_maker.make_code
turn
end
def turn
while @turn < 12
code_breaker_input
compare
@turn += 1
if @turn == 12
puts "Unfortunately, you didn't guess the codemaker's code in the allotted 12 turns. Better luck next time!"
exit
end
end
end
def code_breaker_input
puts "\nCodebreaker, please make your selection! Enter colors in lowercase, separated by spaces, with no commas."
@code_breaker.colors = gets.chomp
end
def compare
b_colors = @code_breaker.colors.downcase.split(" ")
m_colors = @code_maker.code_colors
correct_indexes = []
correct_colors = []
b_colors.zip(m_colors).map { |a, b|
if a == b
correct_indexes << "X"
else correct_indexes << "O" end
}
b_colors.each { |color|
m_colors.any? { |c_color|
correct_colors << color if c_color == color
}
}
puts correct_indexes.join(" ")
puts "Colors guessed correctly: #{correct_colors.join(", ")}"
#checks win condition
if correct_indexes.all? { |index| index == "X" }
puts "The codemaker cracked the code!"
exit
end
end
end
game = Game.new
<span class="math-container">```</span>
</code></pre>
|
[] |
[
{
"body": "<p>Simple things you can improve:</p>\n\n<ul>\n<li><code>12</code> is a magic number in your code, you can move it to a constant.</li>\n<li>I think <code>TURNS.times do |turn| ...</code> is better than the while loop because you don't have to keep track of the counter.</li>\n<li>When you're passing a simple space (<code>\" \"</code>) to the method <code>split</code> you can just call <code>split</code> instead, without passing any argument.</li>\n<li>When the block has multiple lines it is a good practice to use <code>do</code> and <code>end</code> instead of brackets.</li>\n<li>I think you can use the <code>select</code> method and assign the result directly to the <code>correct_colors</code> variable.</li>\n<li>I think it would be better to call <code>Game.new.start_game</code> instead of <code>Game.new</code>, for me, it isn't intuitive that the game will begin just by instantiating the <code>Game</code> class.</li>\n<li>You can make some methods private because you are not calling them on the instance.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-21T00:43:45.263",
"Id": "232721",
"ParentId": "230195",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "232721",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-04T22:28:05.667",
"Id": "230195",
"Score": "2",
"Tags": [
"beginner",
"ruby"
],
"Title": "Command-line implementation of Mastermind"
}
|
230195
|
<p>I am trying to solve <a href="https://leetcode.com/problems/word-break-ii/" rel="nofollow noreferrer">this LeetCode question</a>:</p>
<blockquote>
<p>Given a non-empty string s and a dictionary wordDict containing a list
of non-empty words, add spaces in s to construct a sentence where each
word is a valid dictionary word. Return all such possible sentences.</p>
<p>Note:</p>
<p>The same word in the dictionary may be reused multiple times in the
segmentation. You may assume the dictionary does not contain duplicate
words.</p>
</blockquote>
<p>I have a solution that works correctly but exceeds python's memory limit on large inputs.</p>
<p>Note that the <code>Solution</code> class is required by LeetCode's interface.</p>
<pre><code>from collections import defaultdict
class Solution:
def wordBreak(self, s, wordDict):
cache = defaultdict(list)
word_dict = set(wordDict)
def partition(s):
if s in cache:
return cache[s]
res = []
if s in word_dict:
res.append(s)
for i in range(1, len(s)):
words = partition(s[i:])
k = s[:i]
if k in word_dict:
for word in words:
res.append(k +" "+word)
cache[s] = res
return res
return partition(s)
</code></pre>
<p>How do I optimize it in terms of space complexity?</p>
<p>Please refrain from commenting that the function doesn't have to be a method bound to the class instance. It cannot be changed as it is the template used to run the solution.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-05T03:05:47.240",
"Id": "448179",
"Score": "0",
"body": "I'm afraid, this is not a working solution, when run, it produces an error 'NameError: name 'List' is not defined' either you fix the errors and present a properly running code or move it to StackOverflow. I'm voting to close this question."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-05T05:41:36.447",
"Id": "448187",
"Score": "1",
"body": "@bullseye This might have been a copy paste error since the only error is missing the import statement. I edited the question, but anyone let me know if this change deviates from the authors intent (in my opinion it doesn't) and the edit will be rolled back accordingly."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-05T05:49:12.250",
"Id": "448188",
"Score": "0",
"body": "Still it doesn't work due to the class Solution thing. And I think it's not allowed(my best guess, I don't know) to edit the code if it's not working, however let's wait and see."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-05T07:37:33.103",
"Id": "448196",
"Score": "2",
"body": "@bullseye: It is allowed (and in fact, expected) to update the question with working code. What you must not do is to modify the code *after answers have been posted.*"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-05T08:04:43.680",
"Id": "448198",
"Score": "0",
"body": "@MartinR And when to flag the question as not-working?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-05T09:46:15.923",
"Id": "448213",
"Score": "0",
"body": "@bullseye it works now. And what do you mean \"Still it doesn't work due to the class Solution thing\"? To use it, you need to instantiate `Solution`, then call the relevant method."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-05T10:26:46.883",
"Id": "448217",
"Score": "1",
"body": "@bullseye: My comment was only addressed to your remark that *“it's not allowed ... to edit the code if it's not working”* which is wrong. Of course you are free to flag the question if you think that it is not working. – In this case however the code *is* (allegedly) working in the context of LeetCode, so that would (in my opinion) count as “working to the best knowledge of the author.”"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-05T10:28:07.640",
"Id": "448218",
"Score": "3",
"body": "@nz_21: I understand what you mean. However, as a *convenience* to the possible reviewers, you could add the necessary imports and a (minimal) main program to make the code runnable on its own."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-05T15:00:43.903",
"Id": "448268",
"Score": "0",
"body": "@bullseye: I don't think that a missing import makes the question off-topic (in particular if OP states that it works as a LeetCode submission). Related on Meta: https://codereview.meta.stackexchange.com/q/2535/35991: “Code works when it does that which was intended in full and nothing more, ...” and https://codereview.meta.stackexchange.com/a/1923/35991: “I don't believe that it is reasonable to require a question to include the entire codebase.”"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-05T15:18:41.063",
"Id": "448273",
"Score": "0",
"body": "@Martin R I understand that this code might be doing what it was intended to do. What is annoying here is the fact that to test this code, one has to remove this stupid class Solution template and run it in the IDE. I think this Leetcode website has a terrible design flaw plus it's very far from reality since when you're handling a real programming task you won't be given templates to fill, my opinion here is it blocks creativity and I think it shouldn't be accepted as review material on code review (and this is totally my opinion, not a fact)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-05T15:23:56.817",
"Id": "448275",
"Score": "1",
"body": "@bullseye: I get your point (and you are free to [review the challenge requirements](https://codereview.meta.stackexchange.com/q/9345/35991)), but I don't agree that it makes the question itself off-topic (my opinion :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-05T15:31:43.337",
"Id": "448276",
"Score": "0",
"body": "And I get your point as well however since most people presenting such challenges are here for reviewing their coding abilities and not their challenge solving abilities again my opinion here is this should be considered as an off-topic specially such challenges force bad unrealistic code patterns."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-05T15:51:45.540",
"Id": "448284",
"Score": "0",
"body": "@bullseye \"one has to remove this stupid class Solution template and run it in the IDE\" Uh... `s = Solution(); s.wordBreak(...)` -- are you seriously telling me that typing out a few extra characters requires you to bring out a full-fledged IDE to run the code?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-05T16:07:15.003",
"Id": "448286",
"Score": "0",
"body": "@nz_21: This might interest you: [Determine all ways a string can be split into valid words, given a dictionary of all words](https://codereview.stackexchange.com/q/197558/35991)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-05T16:10:32.370",
"Id": "448287",
"Score": "0",
"body": "@nz_21 are there other ways that i don't know of for running a code?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-05T17:59:30.847",
"Id": "448297",
"Score": "0",
"body": "@bullseye yeah, google virtual environment. When you run it as is, presumably you're going to be running it against your system-wide python interpreter. A virtual env allows you to run the code against a specific python version."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "16",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-05T00:03:10.083",
"Id": "230197",
"Score": "2",
"Tags": [
"python",
"algorithm",
"programming-challenge",
"strings",
"memory-optimization"
],
"Title": "Split a string into valid words"
}
|
230197
|
<h2>Simulate a tic-tac-toe game</h2>
<p><strong>Requirements</strong> <br /></p>
<ul>
<li>A player is picked at random as a first player. <br /></li>
<li>The two players plays tic tac toe game. <br /></li>
<li>The game ends when the board is full or either one of the player wins. <br /></li>
<li>Return the board status and result after end of the game. <br /></li>
</ul>
<blockquote>
<p>Player Class</p>
</blockquote>
<pre><code>class Player:
def __init__(self, name, symbol):
self.name = name
self.symbol = symbol
def pick_available_grid(self, available_position):
random_index = random.choice(available_position.keys())
return random_index
</code></pre>
<blockquote>
<p>Board Class</p>
</blockquote>
<pre><code>class Board:
def __init__(self):
self.grid = [None]*9
self.available_position = {1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0, 9: 0}
def update_board(self, index, symbol):
self.grid[index-1] = symbol
del self.available_position[index]
def check_if_board_full(self):
len(self.available_position) == 0
def check_for_win_condition(self,symbol):
if (self.grid[0]==symbol and self.grid[1]==symbol and self.grid[2]==symbol):
return True
if (self.grid[3]==symbol and self.grid[4]==symbol and self.grid[5]==symbol):
return True
if (self.grid[6]==symbol and self.grid[7]==symbol and self.grid[8]==symbol):
return True
#vertical grid check
if (self.grid[0]==symbol and self.grid[3]==symbol and self.grid[6]==symbol):
return True
if (self.grid[1]==symbol and self.grid[4]==symbol and self.grid[7]==symbol):
return True
if (self.grid[2]==symbol and self.grid[5]==symbol and self.grid[8]==symbol):
return True
#diagonal grid check
if (self.grid[0]==symbol and self.grid[4]==symbol and self.grid[8]==symbol):
return True
if (self.grid[2]==symbol and self.grid[4]==symbol and self.grid[6]==symbol):
return True
</code></pre>
<blockquote>
<p>Game Class</p>
</blockquote>
<pre><code>class Game:
global SYMBOL
SYMBOL = ['X', 'O']
def __init__(self):
self.board = Board()
self.players = []
self.result = None
def set_players(self):
player1 = Player('akanksha', SYMBOL[0])
player2 = Player('akanksha', SYMBOL[1])
self.players.append(player1)
self.players.append(player2)
def set_current_player(self, current_player=None):
current_player = self.players[1] if current_player == self.players[0] else self.players[0]
return current_player
def set_result(self):
if self.board.check_for_win_condition(self.players[0].symbol):
self.result = self.players[0]
elif self.board.check_for_win_condition(self.players[1].symbol):
self.result = self.players[1]
elif self.board.check_if_board_full():
self.result = 'Draw'
return self.result
def play_game(self):
current_player = self.set_current_player()
while(not self.set_result()):
available_position = self.board.available_position
grid_position = current_player.pick_available_grid(available_position)
self.board.update_board(grid_position, current_player.symbol)
current_player = self.set_current_player(current_player)
def end_game(self):
print(self.board.grid)
if self.result == 'Draw':
print('This game is a draw')
else:
print('player', self.result.name, "with symbol", self.result.symbol, "wins")
def start_game(self):
self.set_players()
self.play_game()
self.set_result()
self.end_game()
</code></pre>
<blockquote>
<p>Main Program</p>
</blockquote>
<pre><code>class MainProgram:
def main():
print("Welcome to TicTacToe Game")
game = Game()
game.start_game()
main()
</code></pre>
<p>I am new to <code>oops</code>, how can I improve this?</p>
<p>Questions:</p>
<ul>
<li>Should I create a separate class for <code>symbol</code>?</li>
<li>Should <code>check_for_win_condition</code> be included in <code>Game</code> instead of <code>Board</code> class?</li>
<li>Should <code>self.available_position</code> be used or it should be method which computes available cells from <code>grid</code></li>
</ul>
|
[] |
[
{
"body": "<p>Honestly, for the symbol, I'd just go with using uppercase characters (X and O) since the pieces don't really have any special functionality at this stage, and it's good to keep some simplicity with earlier projects.</p>\n\n<p>I'd put the win condition checking into the game class. If you want to reuse the board class in the future, it's a good idea for you to avoid having any implementation-specific code (i.e. functionality that's specific to Tic-Tac-Toe) in the class - when you're dealing with Object Orientied Programming, you have to consider SOLID principles.</p>\n\n<p>In terms of <code>self.available_positions</code>, I'd forego it entirely. You already have a structure which keeps track of the board, so adding a second structure to keep track of available positions is largely redundant - because one is just the inverse of the other (i.e. <code>self.available_positions</code> are the null elements in <code>self.grid</code>), and duplication is wasting memory and can lead to error (it's also good practice to have a single source of truth).</p>\n\n<p>In terms of code, it's a good start, but I have a few suggested modifications for the Board class:</p>\n\n<pre><code>class Board:\n def __init__(self):\n self.grid = {1: '', 2: '', 3: '', 4: '', 5: '', 6: '', 7: '', 8: '', 9: }\n # Board starts with 9 available positions, and we'll decrement it by one.\n # I've changed to this from the self.available_position dictionary because you were\n # essentially maintaining two structures to maintain the progress of the game, \n # and having a single integer that we decrement is easier.\n self.remaining_turns = 9\n\n def update_board(self, index, symbol):\n self.grid[index-1] = symbol\n # Decrease the number of available turns after placing a piece.\n self.remaining_turns -= 1\n # Probably worth checking for 0 remaining turns after performing this decrement. \n\n def check_for_win_condition(self,symbol):\n # This if statement will be entered if any of the functions return true\n\n if check_diagonal(symbol) or check_horizontal(symbol) or check_vertical(symbol):\n return True\n\n def check_horizontal(self, symbol):\n # 0,3,6 refer to the starting elements in your vertical grid check, the additions\n # refer to the offsets to get to the other elements in the line\n for element in [0, 3, 6]:\n if self.grid[element]==self.grid[element+1]==self.grid[element+2]==symbol:\n return True\n\n def check_vertical(self, symbol):\n # 0,1,2 refer to the starting elements in your vertical grid check, the additions\n # refer to the offsets to get to the other elements in the line\n for element in [0, 1, 2]:\n if self.grid[element]==self.grid[element+3]==self.grid[element+6]==symbol:\n return True\n\n def check_diagonal(self, symbol):\n # You can chain equality checks\n if (self.grid[0]==self.grid[4]==self.grid[8]==symbol) or (self.grid[2]==self.grid[4]==self.grid[6]==symbol):\n return True\n</code></pre>\n\n<p>It's just something I typed up quickly, and I haven't had the opportunity to test it yet. My biggest issue was with the <code>check_for_win_condition</code> function - you were repeating a lot of the same checks (just altering the element reference for the grid).</p>\n\n<p>In terms of language choice; Python is great - it's versatile, and it's intuitive - however, go with Python 3. Python 2 is end of life in 2020 - which means it will no longer have support from the Python developers/maintainers, but Python 3 is in active development, and it has a number of improvements and new features.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-07T07:07:14.363",
"Id": "448473",
"Score": "0",
"body": "Thanks for answering this. I need a clarification on one point: \n`self.grid = {1: '', 2: '', 3: '', 4: '', 5: '', 6: '', 7: '', 8: '', 9: }` \n\nHow are players going to find the available_position. Is it by looping through grid and picking up the keys which have empty string as value and then picking a random one among them. \nIf it so then is it not better to have a available_position, it is a trade-off between time and space."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-07T11:29:25.667",
"Id": "448504",
"Score": "0",
"body": "Basically, when the user says where they want to place their piece, you can run a small function to check whether the element at that index is an empty string (i.e. if `self.grid == '':` you can place the piece). If the element at the specified index isn’t an empty string, someone has already placed a piece there, so you should prompt the player to pick another place."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-15T19:35:33.140",
"Id": "493180",
"Score": "0",
"body": "Instead of initializing grid as `dict` won't `list` be a better data structure?"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-06T23:23:24.433",
"Id": "230280",
"ParentId": "230212",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-05T08:27:30.163",
"Id": "230212",
"Score": "2",
"Tags": [
"python",
"game",
"python-2.x",
"tic-tac-toe"
],
"Title": "Simulate Tic-Tac-Toe game in Python"
}
|
230212
|
<p>Here is a new version of a segmented and wheel factorized Sieve of Eratosthenes. It currently uses mod 30 wheel factorization to eliminate multiples of 2, 3, and 5 in the sieve data structure to gain speed. It wraps the wheel with segmentation in order to reduce its memory footprint so it can scale up to N in the billions and beyond. (yeah, I know, Buzz Lightyear)</p>
<p>This is a follow on to an <a href="https://codereview.stackexchange.com/q/229813/210384">earlier version</a>. Thanks to <a href="https://codereview.stackexchange.com/users/207952/gz0">@GZ0</a> for comments including warning me about how soon Python 2.7 will go unsupported, and a huge thanks to <a href="https://codereview.stackexchange.com/users/192268/quantumchris">@QuantumChris</a> for the thorough code review, especially for encouraging me to use OOP for modularity.</p>
<p>I decided to use a class for everything related to the mod 30 wheel. I hope that makes the design more clear, since the wheel and segmentation code is now separate.</p>
<p>The performance degraded by ~1.5%. I think that is fine, since:</p>
<ul>
<li>perhaps more people will read it. More eyeballs on any code is a Good Thing in my opinion.</li>
<li>cProfile output is more helpful because the code is more granular. Woo-hoo! It now shows that cull_one_multiple is the hot spot followed by segmentedSieve.</li>
<li>it will allow replacing the multiple culling code easily, such as a mod 210 wheel (to also eliminate multiples of 7), with only tiny changes outside of the wheel class. This may make up for the degradation if done carefully.</li>
</ul>
<p>Please let me know what you think.</p>
<pre><code>#!/usr/bin/python3 -Wall
"""program to find all primes <= n, using a segmented wheel sieve"""
from sys import argv
from math import log
from time import time
# non standard packages
from bitarray import bitarray
# tuning parameters
CUTOFF = 1e4 # small for debug
SIEVE_SIZE = 2 ** 20 # in bytes, tiny (i.e. 1) for debug
CLOCK_SPEED = 1.6 # in GHz, on my i5-6285U laptop
def progress(current, total):
"""Display a progress bar on the terminal."""
size = 60
x = size * current // total
print(f'\rSieving: [{"#" * x}{"." * (size - x)}] {current}/{total}', end="")
def seg_wheel_stats(n):
"""Returns only the stats from the segmented sieve."""
return(segmentedSieve(n, statsOnly=True))
def print_sieve_size(sieve):
print("sieve size:", end=' ')
ss = len(memoryview(sieve))
print(ss//1024, "KB") if ss > 1024 else print(ss, "bytes")
def prime_gen_wrapper(n):
"""
Decide whether to use the segmented sieve or a simpler version.
Stops recursion.
"""
return smallSieve(n + 1) if n < CUTOFF else segmentedSieve(n)
# NB: rwh_primes1 (a.k.a. smallSieve) returns primes < N.
# We need sieving primes <= sqrt(limit), hence the +1
def smallSieve(n):
"""Returns a list of primes less than n."""
# a copy of Robert William Hanks' odds only rwh_primes1
# used to get sieving primes for smaller ranges
# from https://stackoverflow.com/a/2068548/11943198
sieve = [True] * (n // 2)
for i in range(3, int(n ** 0.5) + 1, 2):
if sieve[i // 2]:
sieve[i * i // 2::i] = [False] * ((n - i * i - 1) // (2 * i) + 1)
return [2] + [2 * i + 1 for i in range(1, n // 2) if sieve[i]]
class PrimeMultiple:
"""Contains information about sieving primes and their multiples"""
__slots__ = ['prime', 'multiple', 'wheel_index']
def __init__(self, prime):
self.prime = prime
def update(self, multiple, wheel_index):
self.multiple = multiple
self.wheel_index = wheel_index
def update_new_mult(self, multiple, wheel_index, wheel):
self.update(multiple, wheel_index)
wheel.inc_mults_in_use()
class m30_wheel:
"""Contains all methods and data unique to a mod 30 (2, 3, 5) wheel"""
# mod 30 wheel factorization based on a non-segmented version found here
# https://programmingpraxis.com/2012/01/06/pritchards-wheel-sieve/
# in a comment by Willy Good
def __init__(self, sqrt):
# mod 30 wheel constant arrays
self.skipped_primes = [2, 3, 5] # the wheel skips multiples of these
self.wheel_primes = [7, 11, 13, 17, 19, 23, 29, 31]
self.wheel_primes_m30 = [7, 11, 13, 17, 19, 23, 29, 1]
self.gaps = [4,2,4,2,4,6,2,6, 4,2,4,2,4,6,2,6] # 2 loops for overflow
self.wheel_indices = [0,0,0,0,1,1,2,2,2,2, 3,3,4,4,4,4,5,5,5,5, 5,5,6,6,7,7,7,7,7,7]
self.round2wheel = [7,7,0,0,0,0,0,0,1,1, 1,1,2,2,3,3,3,3,4,4, 5,5,5,5,6,6,6,6,6,6]
# get sieving primes recursively,
# skipping over those eliminated by the wheel
self.mults = [PrimeMultiple(p) for p in prime_gen_wrapper(sqrt)[len(self.skipped_primes):]]
self.mults_in_use = 0
def inc_mults_in_use(self):
self.mults_in_use += 1
def get_skipped_primes(self):
"""Returns tiny primes which this wheel ignores otherwise"""
return self.skipped_primes
def num2ix(self, n):
"""Return the wheel index for n."""
n = n - 7 # adjust for wheel starting at 7 vs. 0
return (n//30 << 3) + self.wheel_indices[n % 30]
def ix2num(self, i):
"""Return the number corresponding wheel index i."""
return 30 * (i >> 3) + self.wheel_primes[i & 7]
def cull_one_multiple(self, sieve, lo_ix, high, pm):
"""Cull one prime multiple from this segment"""
p = pm.prime
wx = pm.wheel_index
mult = pm.multiple - 7 # compensate for wheel starting at 7 vs. 0
p8 = p << 3
for j in range(8):
cull_start = ((mult // 30 << 3)
+ self.wheel_indices[mult % 30] - lo_ix)
sieve[cull_start::p8] = False
mult += p * self.gaps[wx]
wx += 1
# calculate the next multiple of p and its wheel index
# f = next factor of a multiple of p past this segment
f = (high + p - 1)//p
f_m30 = f % 30
# round up to next wheel index to eliminate multiples of 2,3,5
wx = self.round2wheel[f_m30]
# normal multiple of p past this segment
mult = p * (f - f_m30 + self.wheel_primes_m30[wx])
pm.update(mult, wx) # save multiple and wheel index
def cull_segment(self, sieve, lo_ix, high):
"""Cull all prime multiples from this segment"""
# generate new multiples of sieving primes and wheel indices
# needed in this segment
for pm in self.mults[self.mults_in_use:]:
p = pm.prime
psq = p * p
if psq > high:
break
pm.update_new_mult(psq, self.num2ix(p) & 7, self)
# sieve the current segment
for pm in self.mults[:self.mults_in_use]:
# iterate over all prime multiples relevant to this segment
if pm.multiple <= high:
self.cull_one_multiple(sieve, lo_ix, high, pm)
def segmentedSieve(limit, statsOnly=False):
"""
Sieves potential prime numbers up to and including limit.
statsOnly (default False) controls the return.
when False, returns a list of primes found.
when True, returns a count of the primes found.
"""
# segmentation originally based on Kim Walisch's
# simple C++ example of segmantation found here:
# https://github.com/kimwalisch/primesieve/wiki/Segmented-sieve-of-Eratosthenes
assert(limit > 6)
sqrt = int(limit ** 0.5)
wheel = m30_wheel(sqrt)
lim_ix = wheel.num2ix(limit)
sieve_bits = SIEVE_SIZE * 8
while (sieve_bits >> 1) >= max(lim_ix, 1):
sieve_bits >>= 1 # adjust the sieve size downward for small N
sieve = bitarray(sieve_bits)
num_segments = (lim_ix + sieve_bits - 1) // sieve_bits # round up
show_progress = False
if statsOnly: # outer loop?
print_sieve_size(sieve)
if limit > 1e8:
show_progress = True
outPrimes = wheel.get_skipped_primes() # these may be needed for output
count = len(outPrimes)
# loop over all the segments
for lo_ix in range(0, lim_ix + 1, sieve_bits):
high = wheel.ix2num(lo_ix + sieve_bits) - 1
sieve.setall(True)
if show_progress:
progress(lo_ix // sieve_bits, num_segments)
wheel.cull_segment(sieve, lo_ix, high)
# handle any extras in the last segment
top = lim_ix - lo_ix + 1 if high > limit else sieve_bits
# collect results from this segment
if statsOnly:
count += sieve[:top].count() # a lightweight way to get a result
else:
for i in range(top): # XXX not so lightweight
if sieve[i]:
x = i + lo_ix
# ix2num(x) inlined below, performance is sensitive here
p = 30 * (x >> 3) + wheel.wheel_primes[x & 7]
outPrimes.append(p)
if show_progress:
progress(num_segments, num_segments)
print()
return count if statsOnly else outPrimes
if __name__ == '__main__':
a = '1e8' if len(argv) < 2 else argv[1]
n = int(float(a))
start = time()
count = segmentedSieve(n, statsOnly=True)
elapsed = time() - start
BigOculls = n * log(log(n, 2), 2)
cycles = CLOCK_SPEED * 1e9 * elapsed
cyclesPerCull = cycles/BigOculls
print(f"pi({a}) = {count}")
print(f"{elapsed:.3} seconds, {cyclesPerCull:.2} cycles/N log log N)")
if count < 500:
print(segmentedSieve(n))
</code></pre>
<p><strong>Performance Data:</strong></p>
<pre><code>$ ./v51_segwheel.py 1e6
sieve size: 64 KB
pi(1e6) = 78498
0.00406 seconds, 1.5 cycles/N log log N)
$ ./v51_segwheel.py 1e7
sieve size: 512 KB
pi(1e7) = 664579
0.0323 seconds, 1.1 cycles/N log log N)
$ ./v51_segwheel.py 1e8
sieve size: 1024 KB
pi(1e8) = 5761455
0.288 seconds, 0.97 cycles/N log log N)
$ ./v51_segwheel.py 1e9
sieve size: 1024 KB
Sieving: [############################################################] 32/32
pi(1e9) = 50847534
2.79 seconds, 0.91 cycles/N log log N)
</code></pre>
<p>The cycles per N log log N shrink as the sieve size grows, probably due to a higher ratio of optimized sieving code to initialization and everything else. The sieve size is capped at 1MB; that produces the fastest results for N in the billions perhaps due to how it almost fits in the L2 0.5MB CPU cache. For the smaller sieve sizes, there should only be one segment. The progress bar starts appearing - possible ADD issues here :-( .</p>
<p>N = 1e9 (one billion) is the performance sweet spot at present. Beyond that, you can see the cycles per N log log N starting to creep up:</p>
<pre><code>$ ./v51_segwheel.py 1e10
sieve size: 1024 KB
Sieving: [############################################################] 318/318
pi(1e10) = 455052511
35.3 seconds, 1.1 cycles/N log log N)
</code></pre>
<p>I've run the earlier version up to 1e12 (1 trillion). But that's no fun for someone with mild ADD. It takes a good part of a day. The progress bar starts to be very useful. I had to keep my eye on the laptop to prevent it from hibernating as much as possible. Once when it did hibernate and I woke it up, my WSL Ubuntu bash terminal froze, but I was able to hit various keys to salvage the run.</p>
<p>The hot spots:</p>
<pre><code>$ python3 -m cProfile -s 'tottime' ./v51_segwheel.py 1e9 | head -15
...
ncalls tottime percall cumtime percall filename:lineno(function)
77125 1.664 0.000 1.736 0.000 v51_segwheel.py:112(cull_one_multiple)
2/1 1.188 0.594 3.049 3.049 v51_segwheel.py:153(segmentedSieve)
33 0.083 0.003 1.837 0.056 v51_segwheel.py:136(cull_segment)
80560 0.075 0.000 0.075 0.000 v51_segwheel.py:64(update)
32 0.012 0.000 0.012 0.000 {method 'count' of 'bitarray._bitarray' objects}
3435 0.009 0.000 0.015 0.000 v51_segwheel.py:68(update_new_mult)
</code></pre>
<p><strong>WHAT I'M LOOKING FOR</strong></p>
<ul>
<li>Performance enhancements.
<ul>
<li>I'm using a bitarray as the sieve. If you know of something that performs better as a sieve, please answer.</li>
<li>Help here:</li>
</ul></li>
</ul>
<pre><code> # collect results from this segment
if statsOnly:
count += sieve[:top].count() # a lightweight way to get a result
else:
for i in range(top): # XXX not so lightweight
if sieve[i]:
x = i + lo_ix
# ix2num(x) inlined below, performance is sensitive here
p = 30 * (x >> 3) + wheel.wheel_primes[x & 7]
outPrimes.append(p)
</code></pre>
<p>The <code>statsOnly</code> leg is great because bitarray is doing the work in optimized C no doubt. I think the <code>else</code> leg could be shrunk. It would be fantastic to change the <code>else</code> into a generator, i.e. <code>yield</code> the primes. I tried that, but then had problems getting it to return the count when the recursion unwound to the top level. It seemed to be stuck in generator mode and didn't want to be bi-modal.</p>
<ul>
<li><p>algorithmic advice. I chose a mod 30 wheel vs. mod 210 because the former has 8 teeth allowing shifts and & ops to replace divide and mod. But I see that there are only a couple of places where the bit hacks are used in the critical paths, so eliminating multiples of 7 from the data structure/culling code may be a win.</p></li>
<li><p>Ways to shrink, clarify, or further modularize the code.</p></li>
<li>Help with the class stuff. This is my first voluntary OOP effort. I did dabble in JUnit back when I worked for {bigCo}. That gave me a bad taste for objects, but in retrospect, the badness was probably due to the JVM. Not a problem in Python.</li>
</ul>
<p><strong>EDIT</strong></p>
<ul>
<li>Updated the code with a new version which adds the PrimeMultiple class in place of three separate arrays. No noticeable change in performance.</li>
<li>Added the performance info and "what I want" sections.</li>
<li>Minor wording tweaks to the original post</li>
</ul>
|
[] |
[
{
"body": "<p>Prepare for a random grab-bag of solicited and unsolicited advice.</p>\n\n<h2>Shebang</h2>\n\n<p>It's typically preferred to use</p>\n\n<pre><code>#!/usr/bin/env python3\n</code></pre>\n\n<p>so that a non-system, e.g. a virtualenv-based, Python binary can kick in automatically when needed. The script can be opinionated about which version of Python it's running, but shouldn't be when it comes to which interpreter binary should be used.</p>\n\n<h2>Clock speed</h2>\n\n<p>Firstly: as you'll no doubt already know, it's not meaningful to hard-code the clock speed. You could do a trivial parse of <code>/proc/cpuinfo</code> which would tie you to Linux, or you could import a third-party library which is able to do this in a platform-agnostic manner.</p>\n\n<p>Even then: once you have the processor frequency, that's only loosely correlated with actual execution speed. Python is a multi-architecture interpreter. Different CPUs have very different capabilities in terms of branch lookahead, etc. which make it so that an advanced 1GHz CPU will beat the pants off of a cheap, consumer-grade 2GHz CPU ten times out of ten.</p>\n\n<p>Another big factor is the entire idea of how much gets done in one instruction cycle based on the instruction set - x86_64 (CISC) versus Arm (RISC) being a huge gap.</p>\n\n<p>That's also not accounting for the fact that you're running a multi-process operating system and time-sharing the CPU, so the number of actual cycles consumed will be less than expected given the amount of real-time duration measured.</p>\n\n<p>All of that said: don't worry about the frequency; instead just print the output of <code>import platform; platform.processor()</code>. The cycle estimate is unfortunately baloney.</p>\n\n<h2>Formatting standards</h2>\n\n<p>PEP8 linters will tell you that:</p>\n\n<ul>\n<li><code>segmentedSieve</code> should be <code>segmented_sieve</code> (and so on for <code>statsOnly</code>, etc.)</li>\n<li>there should only be one blank line before <code># get sieving primes recursively,</code></li>\n<li><code>m30_wheel</code> should be <code>M30Wheel</code> due to being a class</li>\n<li>etc.</li>\n</ul>\n\n<h2>Reduce <code>print</code> calls</h2>\n\n<pre><code>print(\"sieve size:\", end=' ')\nss = len(memoryview(sieve))\nprint(ss//1024, \"KB\") if ss > 1024 else print(ss, \"bytes\")\n</code></pre>\n\n<p>can be</p>\n\n<pre><code>ss = len(memoryview(sieve))\nsize = f'{ss//1024} KiB' if ss > 1024 else f'{ss} bytes'\nprint(f'sieve size: {size}')\n</code></pre>\n\n<p>Also note that <code>KB</code> is not a unit. <code>kB</code> is 1000 bytes, and <code>KiB</code> is 1024 bytes.</p>\n\n<h2>Don't exponentiate needlessly</h2>\n\n<p>I don't trust Python to convert <code>n ** 0.5</code> to a more efficient <code>sqrt</code> automatically. Just call <code>sqrt</code>.</p>\n\n<h2>Use Numpy</h2>\n\n<p>Operations like this:</p>\n\n<pre><code> sieve[i * i // 2::i] = [False] * ((n - i * i - 1) // (2 * i) + 1)\n</code></pre>\n\n<p>where array segments are copied over - can be made much more efficient through the use of Numpy. Numpy is built exactly for this kind of thing - fast array operations for numerical work.</p>\n\n<h2>Type hints</h2>\n\n<p>You're concerned about performance, and that's fine - type hints do not incur a performance hit. So something like this:</p>\n\n<pre><code>def update_new_mult(self, multiple, wheel_index, wheel):\n</code></pre>\n\n<p>can be made more self-documenting by adding some PEP484, possibly:</p>\n\n<pre><code>def update_new_mult(self, multiple: int, wheel_index: int, wheel: M30Wheel) -> None:\n</code></pre>\n\n<h2>Immutability</h2>\n\n<p>Something like</p>\n\n<pre><code> self.gaps = [4,2,4,2,4,6,2,6, 4,2,4,2,4,6,2,6] # 2 loops for overflow\n</code></pre>\n\n<p>is written once and read many times, so use a tuple, not a list. Past that: since it's only calculated during initialization, you really shouldn't be hard-coding these values. Calculate them in a simple loop based on your <code>wheel_primes</code>. This will improve maintainability if ever you change your modulus.</p>\n\n<h2>In-place subtraction</h2>\n\n<pre><code>n = n - 7 # adjust for wheel starting at 7 vs. 0\n</code></pre>\n\n<p>should be</p>\n\n<pre><code>n -= 7 # adjust for wheel starting at 7 vs. 0\n</code></pre>\n\n<h2>Combined division and modulation</h2>\n\n<pre><code> return (n//30 << 3) + self.wheel_indices[n % 30]\n</code></pre>\n\n<p>should use <code>divmod(n, 30)</code> to get both the quotient and remainder at the same time.</p>\n\n<h2>Magic numbers</h2>\n\n<p>30 should be stored in a constant, for the same reasons that you should be calculating <code>gaps</code> - what if it changes? And for third parties, or you in three years, it isn't immediately evident what <code>30</code> means.</p>\n\n<p>The same goes for basically every number in these lines:</p>\n\n<pre><code> n = n - 7 # adjust for wheel starting at 7 vs. 0\n return (n//30 << 3) + self.wheel_indices[n % 30]\n\n return 30 * (i >> 3) + self.wheel_primes[i & 7]\n</code></pre>\n\n<p>I don't know where 7 comes from, but I suspect that it should be calculated from <code>(1 << 3) - 1</code> based on its usage as a mask.</p>\n\n<h2>Name collisions</h2>\n\n<p>Don't call a variable <code>sqrt</code>. It's common enough that there's a bare import of that symbol from <code>math</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-08T04:23:05.663",
"Id": "448613",
"Score": "0",
"body": "@bullseye Seems I trampled your edit - sorry - feel free to suggest it again and I'll accept it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-08T05:01:37.783",
"Id": "448617",
"Score": "0",
"body": "Time tests with `divmod(n, d)` have shown that separate expressions actually perform better, probably due to the return tuple creation & unpacking that is needed to use the result. (I was shocked.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-08T05:10:01.157",
"Id": "448620",
"Score": "1",
"body": "Expanding a little on \"just call `sqrt`\", Python 3.8 will have `math.isqrt`. Look for it, starting October 14th, 2019 (fingers crossed)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-08T06:27:06.107",
"Id": "448622",
"Score": "0",
"body": "@Reinderien done"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-08T09:53:40.253",
"Id": "448644",
"Score": "0",
"body": "Thanks for the review. I will incorporate most of your suggestions. divmod and type hints: cool! I didn't know you could do that. cycles: I don't feel I need a lecture about how CPUs perform having serviced mainframes for a while, but I see you have an EE background, The cycles/<big_O_effort> is a trick I learned from Jon Bentley that serves me well as a scorecard. I'm more concerned about the N log log N denominator being incomplete. I don't think it covers creating/maintaining sieving primes and the associated stuff. But it's probably good enough to let me move ahead."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-08T10:15:31.460",
"Id": "448649",
"Score": "0",
"body": "@Reinderian Something like dhrystones/Dmips would be more accurate for the numerator than clock speed, but harder to obtain. I don't think I want more external dependencies. >>> platform.processor()\n'x86_64' - not useful. Sticking to hard coded clock speed for now."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-08T12:34:38.987",
"Id": "448670",
"Score": "0",
"body": "@AJNeufeld re: divmod() I also had a bad experience with namedtuples due to tons of new() calls when searching for a C struct replacement. class `__slots__` works great as a struct. I appreciate you saving me time. re: isqrt/3.8 - on my calendar"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-08T12:39:21.323",
"Id": "448671",
"Score": "0",
"body": "@Reinderien sorry about mis-spelling your handle above. It's too late to edit it now."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-09T00:36:52.563",
"Id": "448754",
"Score": "0",
"body": "@Reinderien actually using math.sqrt(n) vs. n ** 0.5 degrades performance of the isolated small_sieve code at 1e8 by about 4.1%"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-09T00:53:17.937",
"Id": "448755",
"Score": "0",
"body": "Interesting. Have a read through https://stackoverflow.com/questions/327002/which-is-faster-in-python-x-5-or-math-sqrtx . Both the intuitive and the generally tested conclusion are that `sqrt` is the way to go - I wonder why your case is different."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-09T00:56:02.103",
"Id": "448756",
"Score": "1",
"body": "The likely case is that it's \"not just `sqrt`\" accounting for the 4.1% difference, and that there's something else in play as well - maybe module lookup."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-09T02:44:05.987",
"Id": "448787",
"Score": "0",
"body": "4.1% is huge - downright unbelievable considering it is called exactly once during the search for primes up to 100 million. I’d highly suggest reprofiling. And definitely don’t rely on only one timing trial of each; take the best of (say) 100 trials of each."
}
],
"meta_data": {
"CommentCount": "12",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-08T04:13:41.463",
"Id": "230353",
"ParentId": "230220",
"Score": "4"
}
},
{
"body": "<h2><code>smallSieve</code></h2>\n\n<p>PEP 8 recommends using <code>snake_case</code> for function names, so the function should be named <code>small_sieve</code>.</p>\n\n<p>You've imported <code>bitarray</code>, but do not use it in this function. In addition to reducing the memory requirement of the function, it could really clean up the code (and perhaps speed it up). The key is the slice assignment,</p>\n\n<pre><code> sieve[i * i // 2::i] = False\n</code></pre>\n\n<p>which will assign a single scalar value to every element in the slice. This means you don't have to calculate how many <code>False</code> values to assign into the slice, nor allocate an entire list of <code>False</code> values, just to set each entry of the slice to <code>False</code>.</p>\n\n<p>Finally, the return statement repeatedly indexes into the <code>sieve</code> list, <code>sieve[i]</code>, which is inefficient. It is better to iterate over the sieve list directly, fetching the sieve's primality flags from the iterator. Since you need the indices as well, <code>for i, flag in enumerate(sieve)</code> is the preferred list comprehension construct:</p>\n\n<pre><code>def small_sieve(n):\n sieve = bitarray.bitarray(n // 2)\n\n sieve.setall(True)\n sieve[0] = False # 1 is not prime\n\n for i in range(3, int(n ** 0.5) + 1, 2):\n if sieve[i // 2]:\n sieve[i * i // 2::i] = False\n\n return [2] + [2 * i + 1 for i, flag in enumerate(sieve) if flag]\n</code></pre>\n\n<h2><code>m30_wheel.__init__</code></h2>\n\n<p>The <code>m30_wheel</code> is only constructed once, so its performance is not critical. Instead of hand-coded constants, have you considered computing the constants? It would make building the mod 210 wheel much easier!</p>\n\n<p>As an example:</p>\n\n<pre><code>self.wheel_primes_m30 = [ wheel_prime % 30 for wheel_prime in self.wheel_primes ]\n</code></pre>\n\n<p>Also, instead of spelling out the gaps twice, after computing the gaps, use list multiplication:</p>\n\n<pre><code>temp = self.wheel_primes + [self.wheel_primes[0] + 30]\nself.gaps = [ b - a for a, b in zip(temp[:-1], temp[1:]) ] * 2\n</code></pre>\n\n<p>There are various hard-coded numbers in the wheel that could be made into member values ... 30, 7, 8 ... but hard-coded integers will be faster than member access. So, despite computing the initialization data instead of using hard-coded numbers, I'd be inclined to leave the numbers as numbers in the various member functions which are called multiple times.</p>\n\n<h2>Use computed assignments</h2>\n\n<p>Python cannot optimize a statement like:</p>\n\n<pre><code>n = n - 7\n</code></pre>\n\n<p>into:</p>\n\n<pre><code>n -= 7\n</code></pre>\n\n<p>due to its interpreted nature, where the meaning of the various operations depends on <code>type(n)</code>, which can be different every time the statement is executed. So in the former case, the Python interpreter will search its dictionary for the variable <code>n</code>, subtract 7, and then search its dictionary for the variable <code>n</code> to store the value into. In the latter case, the variable <code>n</code> is only searched for once; the value is retrieved, modified, and stored without needing to consult the variable dictionary a second time.</p>\n\n<h2>Unused variables</h2>\n\n<p>In the loop:</p>\n\n<pre><code>for j in range(8):\n</code></pre>\n\n<p>the variable <code>j</code> is never used. By convention, the <code>_</code> variable should be used when it is needed for syntactical purposes only:</p>\n\n<pre><code>for _ in range(8):\n</code></pre>\n\n<h2>XXX not so lightweight</h2>\n\n<p>As noted, this code is not lightweight:</p>\n\n<pre><code> for i in range(top):\n if sieve[i]:\n x = i + li_ix\n ...\n</code></pre>\n\n<p>due to the repeated indexing into the <code>sieve</code> list. The lighter weight approach is to use iteration over the contents of the list directly:</p>\n\n<pre><code> for i, flag in enumerate(sieve[:top]):\n if flag:\n x = i + li_ix\n ...\n</code></pre>\n\n<p>Even better, since <code>i</code> is only used to compute <code>x</code>, which is a constant offset from <code>i</code>, we can start the enumeration at the value <code>li_ix</code>, and avoid the addition:</p>\n\n<pre><code> for x, flag in enumerate(sieve[:top], li_ix):\n if flag:\n ...\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-08T14:00:57.983",
"Id": "448689",
"Score": "0",
"body": "I'm on it! I was thinking using bitarray in small_sieve since I already use it in the big sieve. fwiw I just cut and pasted the code from the referenced SO post, but I've already changed it to use math.sqrt() per @Reinderien and made note that it's slightly modified for anyone who cares. enumerate(): D'oh, should have known, the reviewer of my last version already suggested that elsewhere. computing wheel constants at init: yep, @ Reinderien already nudged me in that direction. I hope I can figure out a way to do it just once for all the recursive calls."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-08T14:09:28.603",
"Id": "448690",
"Score": "0",
"body": "avoiding constant addition of li_ix: most excellent"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-09T01:03:51.773",
"Id": "448759",
"Score": "0",
"body": "your bitarray verion of small_sieve rocks! It's twice as fast @ 1e8 when isolated"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-09T02:29:30.410",
"Id": "448784",
"Score": "0",
"body": "Thank-you. I was happy to see you were using `bitarray` but then horrified that you weren’t using the scalar-to-slice assignment... and then confused when I saw you were using it in `sieve[cull_start::p8] = False`. I’m happy you like the improvements; it is why I’m here in Code Review. Enjoy!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-09T02:36:37.333",
"Id": "448786",
"Score": "0",
"body": "yeah it's just because I dropped in existing code for small_sieve then pretty much ignored it (except for PEP8) and worked on the big sieve"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-09T12:18:40.073",
"Id": "448845",
"Score": "0",
"body": "thanks for validating my choice of bitarray as the sieve data structure. it's so darned simple. I recall some Smart Person saying that one should think hard about the data structure design, then the code just falls into place."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-08T04:54:00.647",
"Id": "230356",
"ParentId": "230220",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "230356",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-05T13:34:10.997",
"Id": "230220",
"Score": "11",
"Tags": [
"python",
"performance",
"python-3.x",
"primes",
"sieve-of-eratosthenes"
],
"Title": "Segmented wheel Sieve of Eratosthenes in Python"
}
|
230220
|
<p>This is just a simple monitor for shopify products for an array of sites. It involves parsing the /products.json of the site, checking if each product ID is already stored as a key in redis and if it isn't it needs to notify a group of discord members (haven't implemented yet). Really appreciate any feedback given!</p>
<pre><code>const axios = require('axios'),
fs = require('fs'),
redis = require('redis');
const client = redis.createClient();
let trackingF = fs.readFileSync("../tracking.json");
let proxiesF = fs.readFileSync("../proxies.json");
let keywords = JSON.parse(trackingF).keywords.map(x => {
return x.toLowerCase();
});
let sites = JSON.parse(trackingF).sites.map(x => {
return x.toLowerCase();
});
let proxies = JSON.parse(proxiesF).proxies;
const getProducts = (url) => {
return new Promise((resolve, reject) => {
axios.get(`${url}/products.json`, rProxy()).then(response => {
resolve(response.data.products);
}).catch(err => {reject(err)});
});
}
const cache = (product) => {
client.get(product.id, (err, reply) => {
if (err) console.log(err);
if (!reply) {
client.set(product.id, JSON.stringify(product));
console.log("NEW PRODUCT: " + product.id);
return;
}
});
}
const rProxy = () => {
return proxies[Math.floor(Math.random() * Math.floor(proxies.length))];
}
const checkStock = () => {
console.log("[MONITOR] CHECKING");
for (let i = 0; i < sites.length; i++) {
getProducts(sites[i]).then(products => {
products.forEach(product => {
cache(product)
});
}).catch(err => console.log(err));
}
}
setInterval(() => checkStock(), 5000);
</code></pre>
|
[] |
[
{
"body": "<pre><code>const axios = require('axios'),\n fs = require('fs'),\n redis = require('redis');\n</code></pre>\n\n<p>Personally, I discourage the use of a single <code>var</code>/<code>let</code>/<code>const</code> for declaring a variable. Firstly, they're not portable. Let's say you want to move <code>fs</code> somewhere else. Instead of copy-pasting the entire line, you end up copying that line <em>and tacking on</em> <code>var</code>/<code>let</code>/<code>const</code> anyways.</p>\n\n<p>Next, say you already had <code>redis</code>. if you wanted to add <code>axios</code>, the Git changelog will look like:</p>\n\n<pre><code>- const redis = require('redis');\n+ const axios = require('axios'),\n+ redis = require('redis');\n</code></pre>\n\n<p>or this:</p>\n\n<pre><code>- const redis = require('redis');\n+ const redis = require('redis'),\n+ axios = require('axios');\n</code></pre>\n\n<p>Instead of just this:</p>\n\n<pre><code>+ const axios = require('axios');\n const redis = require('redis');\n</code></pre>\n\n<p>or this:</p>\n\n<pre><code> const redis = require('redis');\n+ const axios = require('axios');\n</code></pre>\n\n<p>You never touched redis, yet it's highlighted in the commit. This is because you had to add the <code>,</code>. This ends up being unnecessary noise in the commit, and annoying in code reviews and pull requests.</p>\n\n<hr>\n\n<p>Next up, I recommend a <code>const</code>-first policy. The priority should be <code>const</code> first, then <code>let</code> if the variable has to mutate (e.g. loop counters). Then <code>var</code> if you absolutely have to have a function-scoped variable defined in some nested block for whatever reason.</p>\n\n<p>This block-scoped variables reduce cognitive overhead, avoiding having to remember that what variables exist in the upper scopes, and to avoid accidentally clobbering a variable elsewhere. Small change in process, but has big benefits down the line.</p>\n\n<hr>\n\n<p>Node.js has native support for <code>async</code>/<code>await</code>. So you no longer have to deal with the clunky syntax of promises.</p>\n\n<p>Additionally, if you have functions that use the Node-style callback API (an async function that takes a callback whose first argument is an error and the second being the result), Node has <a href=\"https://nodejs.org/api/util.html#util_util_promisify_original\" rel=\"nofollow noreferrer\"><code>utils.promisify()</code></a> which returns a promise-based version of it.</p>\n\n<hr>\n\n<pre><code>for (let i = 0; i < sites.length; i++) {\n getProducts(sites[i]).then(products => {\n products.forEach(product => {\n cache(product)\n });\n }).catch(err => console.log(err));\n}\n</code></pre>\n\n<p>You can replace this with an <code>array.map()</code> and <code>Promise.all()</code>. Put the promises returned by <code>getProducts()</code> in an array, pass that array to <code>Promise.all()</code> which returns a promise, await that promise to listen for the completion.</p>\n\n<hr>\n\n<pre><code>setInterval(() => checkStock(), 5000);\n</code></pre>\n\n<p>I'd wait for <code>checkStock()</code> to complete first before launching the next run. You wouldn't want to hammer the site every 5 seconds. They might not respond in time, and your requests may accumulate. You might be rate-limited or worse, blocked, before you know it.</p>\n\n<hr>\n\n<p>Here's how I'd write it:</p>\n\n<pre><code>const axios = require('axios')\nconst fs = require('fs')\nconst redis = require('redis')\n\nconst trackingF = fs.readFileSync(\"../tracking.json\")\nconst proxiesF = fs.readFileSync(\"../proxies.json\")\n\nconst client = redis.createClient()\nconst clientGetAsync = utils.promisify(client.get)\n\nconst toLower = x => x.toLowerCase()\n\nconst keywords = JSON.parse(trackingF).keywords.map(toLower)\nconst sites = JSON.parse(trackingF).sites.map(toLower)\nconst proxies = JSON.parse(proxiesF).proxies;\n\nconst rProxy = () => proxies[Math.floor(Math.random() * Math.floor(proxies.length))]\n\nconst getProducts = async url => {\n const response = await axios.get(`${url}/products.json`, rProxy())\n return response.data.products\n}\n\nconst cache = async product => {\n try {\n const reply = await clientGetAsync(product.id)\n if (reply) return\n client.set(product.id, JSON.stringify(product))\n console.log(\"NEW PRODUCT: \" + product.id)\n } catch (e) {\n console.error(e)\n }\n}\n\nconst checkStock = async delay => {\n console.log(\"[MONITOR] CHECKING\")\n\n const promises = sites.map(async site => {\n try {\n const products = await getProducts(site)\n await Promise.all(products.map(cache))\n } catch (e) {\n console.error(e)\n }\n })\n\n await Promise.all(promises)\n\n setTimeout(() => checkStock(delay), delay)\n}\n\ncheckStock(5000).catch(e => console.error(e))\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-07T17:11:09.023",
"Id": "448560",
"Score": "0",
"body": "Really appreciate the advice, definitely time for me to go back over concurrency! Thank you."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-05T18:08:56.370",
"Id": "230232",
"ParentId": "230222",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-05T14:26:48.560",
"Id": "230222",
"Score": "2",
"Tags": [
"javascript"
],
"Title": "Shopify monitor that utilizes redis for caching each product"
}
|
230222
|
<p>I was solving one competitive coding question having integer bounds <code>2^100</code>. Fortunately, it was a dp question and I didn't need an array of that size. Practically we cannot create an array of size more than <code>Integer.MAX_VALUE</code>.</p>
<blockquote>
<p>But I was thinking of creating a multidimensional array and treat it as a one-dimensional array.</p>
</blockquote>
<p>what I need was a very large array with <code>O(1)</code> retrieval time. So Internally it will be a multidimensional array but I will treat it as a one-dimensional array.</p>
<h3>So the size of the resultant array will be n*n.</h3>
<blockquote>
<p>if n is Integer.MAX_VALUE then the resultant augmented array will be of Integer.MAX * Integer.MAX</p>
</blockquote>
<p>Here what I did to implement this idea.</p>
<h2>BigArray class</h2>
<pre><code>public class BigArray
{
private int[][] arr;
private int row=0;
private int col = 0;
private int size;
public BigArray(int size)
{
arr = new int[size][size];
this.size = size;
}
}
</code></pre>
<h2>add method</h2>
<pre><code>public void add(int data)
{
if(row > size-1)
{
col++;
row=0;
this.arr[col][row] = data;
row++;
}
else
{
this.arr[col][row] = data;
row++;
}
}
</code></pre>
<h2>get method</h2>
<pre><code>public int get(int pos)
{ //get value in O(1)
if((int) Math.sqrt(pos) > size)
return -1;
int col1 = pos/(size);
int row1 = pos%(size);
return arr[col1][row1];
}
</code></pre>
<p>But If I pass <code>Integer.MAX_VALUE</code> in <code>BigArray</code> it throws <code>Exception in thread "main" java.lang.OutOfMemoryError: Requested array size exceeds VM limit</code>
maximum size I've tried is 20,000 so resultant size will be 20,000 x 20,000 = 400,000,000.</p>
<h3>But if add one more dimension to this array I'll get more space.</h3>
<p>if BigArray has <code>arr[][][]</code> resultant size will be n x n x n;
if BigArray has <code>arr[][][][]</code> resultant size will be n x n x n x n; and so on.</p>
<h3>I know I had to implement necessary methods as I add a new dimension to the base array.</h3>
<p>But I would like a review on this type of storage class. I don't know</p>
<blockquote>
<p>what's the maximum dimensions java array can have?</p>
</blockquote>
<p>Also, do tell me</p>
<ul>
<li>if can use this approach to create arrays size more than the traditional array size</li>
<li>Future scope such as generic BigArray of character will create string greater size</li>
<li>other opinions/suggestions on this approach</li>
</ul>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-05T16:14:07.257",
"Id": "448288",
"Score": "0",
"body": "How big of an array are you actually aiming for? Multidimensional with Integer.MAX_VALUE each dimension would be huge"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-05T16:54:47.207",
"Id": "448292",
"Score": "0",
"body": "Yes Im trying create array of size larger than Integer.MAX"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-06T00:13:53.513",
"Id": "448315",
"Score": "1",
"body": "Is it not an option to just use streams for the challenge? It doesn't seem practical to try and have that much stored at once."
}
] |
[
{
"body": "<p>The biggest problem I can see with this approach, is that a user can't <code>add</code> or <code>get</code> any index higher than <code>Integer.MAXVALUE</code>. You might need to parse <code>Strings</code> or use a <code>BigInteger</code> type instead of <code>int</code> for those methods.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-05T18:09:53.097",
"Id": "230233",
"ParentId": "230223",
"Score": "6"
}
},
{
"body": "<p>Have you increased the size of your VM? If not, you will not get past <code>java.lang.OutOfMemoryError: Requested array size exceeds VM limit</code> without doing something creative like storing the array in a file.</p>\n\n<p>Do you need 4-byte integers, or would 2-byte shorts be sufficient?</p>\n\n<p>This is allocating all the memory in one chunk:</p>\n\n<pre><code>arr = new int[size][size];\n</code></pre>\n\n<p>Perhaps you should use:</p>\n\n<pre><code>arr = new int[size][];\narr[0] = new int[size];\n</code></pre>\n\n<p>to allocate one chunk to hold the columns, one chunk to hold the first column, and then as data is being added, allocate new columns on demand:</p>\n\n<pre><code>public void add(int data) {\n if (row >= size) {\n arr[++col] = new int[size];\n row = 0;\n }\n\n arr[col][row] = data;\n row++;\n}\n</code></pre>\n\n<p>Using a variable size, or even <code>Integer.MAX_VALUE</code> to partition data into rows, columns, and higher dimensions is inefficient. I’d use a hard-coded power of 2, to allow efficient module arithmetic. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-05T19:30:22.073",
"Id": "230237",
"ParentId": "230223",
"Score": "3"
}
},
{
"body": "<p>In addition to the answer <a href=\"https://codereview.stackexchange.com/users/33306/tinstaafl\">@tinstaafl</a> <a href=\"https://codereview.stackexchange.com/a/230233/15863\">provided</a>, I think that your class doesn't behave like arrays are implemented: namely, it is allocated in different places in the program's memory space. You can't, for instance, call <code>System.arraycopy()</code> to make a copy out of it.</p>\n\n<p>I think that you implement here a specific <code>Map</code>, with keys as integers (or longs, as mentioned), and values as integers.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-05T20:06:50.887",
"Id": "230238",
"ParentId": "230223",
"Score": "3"
}
},
{
"body": "<p>An int is 32 bits? Then your 400,000,000 array requires ...</p>\n\n<p>... 1,600,000,000 bytes == 1,600,000 KB == 1,600 MB == 1.6 GB</p>\n\n<p>Have you configured your JVM to have that much RAM? You need some overhead for the application, so I'd probably configure 1.76 GB or so.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-06T03:33:02.323",
"Id": "448321",
"Score": "0",
"body": "Any Idea how to configure? is it by means configurations or java code ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-06T18:39:13.490",
"Id": "448436",
"Score": "2",
"body": "First hit on google. It's a standard command-line feature for all JVMs (e.g. \"-Xms\"). But if you're using an IDE, your IDE will have a setting for this. If you're using an unusual JVM, it will have a custom setting for this. You need to read your JVM docs."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-06T01:14:04.837",
"Id": "230245",
"ParentId": "230223",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "230245",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-05T14:36:44.527",
"Id": "230223",
"Score": "3",
"Tags": [
"java",
"array"
],
"Title": "Java creating augmented array of size 400,000,000"
}
|
230223
|
<p>I'm writing my first game and would love some advice on how to get away from all this hardcoding I'm using...
Each Character has "abilities" (all individual functions) but I can't seem to figure out how to streamline this. Example:</p>
<pre><code>def lightning_bolt(self):
if self.is_stunned:
print("Stunned...ability unsuccessful.")
elif self.is_confused:
confused_test = roll_d_x(2)
if confused_test == 1:
print("Confused...ability unsuccessful.")
else:
defender.mobility = (defender.mobility / 2)
success = self.success_check()
defender.mobility = (defender.mobility * 2)
if success:
volatile_roll = roll_d_x(10)
if volatile_roll == 1:
self.volatile_magic()
else:
defender.lose_health(((self.energy * 0.5) + 10))
self.lose_energy(25)
stun_test = roll_d_x(4)
if stun_test == 1:
defender.is_stunned = True
else:
print("Ability failed.")
</code></pre>
<p>Note: all abilities must pass this "stunned and confused test" and a "volatile test". I will be defining a function for those. *I wanted to make "class Ability:", but I want each character to have their own individual abilities. Is there a way to nest classes or something? Any ideas to streamline aspects like "cost" and "damage dealt", etc.?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-05T15:39:50.673",
"Id": "448278",
"Score": "2",
"body": "This is incomplete code and is considered as an off-topic here, you should provide the full code and a clear description of what this could is intended to do and samples of input and output. I'm voting to close this question."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-05T17:21:57.927",
"Id": "448294",
"Score": "3",
"body": "Please do provide additional code for context. There are quite a few possible directions for improvement here."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-05T20:38:56.710",
"Id": "448304",
"Score": "1",
"body": "Thank you for commenting. I will scratch this question and reask with much more code. I didn't want to spam. New here."
}
] |
[
{
"body": "<p>I have asked that you provide more code, and I hope that you do.</p>\n\n<p>Until then, I suggest you have a look at the <a href=\"https://python-3-patterns-idioms-test.readthedocs.io/en/latest/Visitor.html\" rel=\"nofollow noreferrer\"><em>Visitor Pattern</em></a> and its implementation using <em>multiple dispatch</em>.</p>\n\n<p>You have a lightning attack. You are applying certain effects, including some effects that are common to all attacks. </p>\n\n<p>You have not yet reached the point where some defenders will be immune to lightning, or take reduced damage, or immune to stun, but you will.</p>\n\n<p>It makes more sense to <a href=\"https://www.martinfowler.com/bliki/TellDontAsk.html\" rel=\"nofollow noreferrer\"><em>Tell, don't Ask</em></a> in thise situation. You tell the defender that they were attacked by lightning, and let the defender handle things. </p>\n\n<p>The default behavior would be substantially what you have shown. But you could then create a defender subclass that was immune to lightning, or suffered reduced damage, and the logic would be located <em>with that particular defender,</em> which improves your code organization and maintainability.</p>\n\n<p>Beyond that, since your defender seems to be a class already (based on the code you have shown), it should be easy to encode the \"standard attack checks\" into the base class in a single method. You can then raise an exception or return a sentinel value to indicate that the attack is blocked due to stun or confusion, or just print out the results (not recommended).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-05T17:30:31.417",
"Id": "230230",
"ParentId": "230224",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-05T14:52:00.740",
"Id": "230224",
"Score": "4",
"Tags": [
"python",
"dice",
"role-playing-game",
"battle-simulation"
],
"Title": "Function to determine the effect of a lightning bolt on a game character using \"abilities\""
}
|
230224
|
<p>I have a function that takes an object ("token") and three additional parameters of different types ("obj1", "obj2", "obj3"). The object "token" has an 'IsSatisfied' method that may take none, 1, 2, or 3 paremeters of types matching "obj1", "obj2", "obj3". Versions of "token" that have 1 or more parameters are generic. Right now, I have an inelegant solution of pattern matching the "token" against every permutation of 0, 1, 2, or 3 parameters, as shown in the code sample below. </p>
<p>Is there a more elegant way to write this? It works as is, but I might go to 4 parameters ("obj1", "obj2", "obj3", "obj4") in which case the list of permutations gets really long. Perhaps a solution that uses 'params' for an indefinite number of parameters. I would also be happy to drop the generic parameters on the Tokenizer class.</p>
<pre><code>public class Tokenizer <T1, T2, T3>
{
public void Test(IBoolToken token, T1 obj1, T2 obj2, T3 obj3)
{
if (token is IBooleanTokenable tokenable0P) tokenable0P.IsSatisfied();
else if (token is IBooleanTokenable<T1> tokenable1P1) tokenable1P1.IsSatisfied(obj1);
else if (token is IBooleanTokenable<T2> tokenable1P2) tokenable1P2.IsSatisfied(obj2);
else if (token is IBooleanTokenable<T3> tokenable1P3) tokenable1P3.IsSatisfied(obj3);
else if (token is IBooleanTokenable<T1, T2> tokenable2P1) tokenable2P1.IsSatisfied(obj1, obj2);
else if (token is IBooleanTokenable<T1, T3> tokenable2P2) tokenable2P2.IsSatisfied(obj1, obj3);
else if (token is IBooleanTokenable<T2, T3> tokenable2P3) tokenable2P3.IsSatisfied(obj2, obj3);
else if (token is IBooleanTokenable<T2, T1> tokenable2P4) tokenable2P4.IsSatisfied(obj2, obj1);
else if (token is IBooleanTokenable<T3, T1> tokenable2P5) tokenable2P5.IsSatisfied(obj3, obj1);
else if (token is IBooleanTokenable<T3, T2> tokenable2P6) tokenable2P6.IsSatisfied(obj3, obj2);
else if (token is IBooleanTokenable<T1, T2, T3> tokenable3P1) tokenable3P1.IsSatisfied(obj1, obj2, obj3);
else if (token is IBooleanTokenable<T1, T3, T2> tokenable3P2) tokenable3P2.IsSatisfied(obj1, obj3, obj2);
else if (token is IBooleanTokenable<T2, T1, T3> tokenable3P3) tokenable3P3.IsSatisfied(obj2, obj1, obj3);
else if (token is IBooleanTokenable<T2, T3, T1> tokenable3P4) tokenable3P4.IsSatisfied(obj2, obj3, obj1);
else if (token is IBooleanTokenable<T3, T1, T2> tokenable3P5) tokenable3P5.IsSatisfied(obj3, obj1, obj2);
else if (token is IBooleanTokenable<T3, T2, T1> tokenable3P6) tokenable3P6.IsSatisfied(obj3, obj2, obj1);
}
}
<span class="math-container">```</span>
</code></pre>
|
[] |
[
{
"body": "<p>If this is a comment theme throughout your code I would say to make an IArgument interface that would manage your object parameters. But if this is the only time you are dealing with these obj parameters, I would say pass the arguments of IsSatisfied in as generic objects and let IsSatisfied worry about ordering the arguments by type:</p>\n\n<pre><code> void IsSatisfied(params object[] objects)\n { \n // T1 obj1 = <find T1 in objects>;\n // T2 obj2 = <find T2 in objects>;\n // T3 obj3 = <find T3 in objects>;\n // continue with previous implementation of IsSatisfied\n }\n</code></pre>\n\n<p>You would need to deal with the case when more than one of the objs is the same type.</p>\n\n<p>Overall I don't like how the Test() method smells. You're passing in obj1, obj2, obj3, and possibly even obj4, every time, but you may only use obj2. What are obj1 and obj3 in this case?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-05T19:24:16.760",
"Id": "448302",
"Score": "0",
"body": "Thanks for your comments. The sample code in my question is actually just an abstraction of my actual code to isolate the issue I am facing. You can assume that my code is not as smelly as it appears. For my purposes, keeping this logic outside of the IsSatisfied methods is better."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-05T16:44:00.910",
"Id": "230228",
"ParentId": "230226",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-05T15:28:03.103",
"Id": "230226",
"Score": "3",
"Tags": [
"c#",
"generics"
],
"Title": "Check all permutations of generic type parameters"
}
|
230226
|
<p><a href="https://leetcode.com/problems/burst-balloons/" rel="noreferrer">https://leetcode.com/problems/burst-balloons/</a></p>
<blockquote>
<p>Given <code>n</code> balloons, indexed from <code>0</code> to <code>n-1</code>, each balloon is painted with
a number on it represented by array <code>nums</code>. You are asked to burst all
the balloons. If you burst balloon <code>i</code>, the number of coins you will get is calculated as:
<span class="math-container">$$ nums[left] * nums[i] * nums[right] $$</span>Here, <code>left</code> and <code>right</code> are adjacent indices of <code>i</code>. After the burst, <code>left</code> and <code>right</code> then becomes adjacent.</p>
<p>Find the maximum coins you can collect by bursting the balloons
wisely.</p>
<p>Note:</p>
<p>You may imagine <span class="math-container">$$ nums[-1] = nums[n] = 1 $$</span>They are not real therefore
you can not burst them. 0 ≤ <code>n</code> ≤ 500, 0 ≤ <code>nums[i]</code> ≤ 100</p>
<pre><code>Example:
Input: [3,1,5,8]
Output: 167
Explanation: nums = [3,1,5,8] --> [3,5,8] --> [3,8] --> [8] --> []
coins = 3*1*5 + 3*5*8 + 1*3*8 + 1*8*1 = 167
</code></pre>
</blockquote>
<pre><code>using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace RecurssionQuestions
{
/// <summary>
/// https://leetcode.com/problems/burst-balloons/
/// </summary>
[TestClass]
public class BurstBalloonsTest
{
[TestMethod]
public void TestExample()
{
int[] nums = {3, 1, 5, 8};
BurstBalloonsClass burst = new BurstBalloonsClass();
Assert.AreEqual(167, burst.MaxCoins(nums));
}
}
public class BurstBalloonsClass
{
public int MaxCoins(int[] nums)
{
int[] numbers = new int[nums.Length +2]; // we add 2 because of the question
// nums[-1] = nums[n] = 1
int n = 1;
foreach (var x in nums)
{
if (x > 0) // we care only about positive values for profit
{
numbers[n++] = x;
}
}
numbers[0] = numbers[n++] = 1;
int[][] memo = new int[n][];
for (var index = 0; index < memo.Length; index++)
{
memo[index]= new int[n];
}
// we allocate NxN matrix for memoization
return Burst(memo, numbers, 0, n - 1);
}
private int Burst(int[][] memo, int[] numbers, int left, int right)
{
if (left + 1 == right)
{
return 0;
}
if (memo[left][right] > 0)
{
return memo[left][right];
}
int ans = 0;
// we try all the options between left and right
// we compare the answers of all of the options and the maxmial one
// if poped all of the ballons from left to u and from i to right we have only an option to pop
// numbers[left] * numbers[i] * numbers[right]
for (int i = left + 1; i < right; ++i)
{
ans = Math.Max(ans, numbers[left] * numbers[i] * numbers[right]
+ Burst(memo, numbers, left, i)
+ Burst(memo, numbers, i, right));
}
memo[left][right] = ans;
return ans;
}
}
}
</code></pre>
|
[] |
[
{
"body": "<p>Some things come to mind when I read your code. </p>\n\n<p>There is a nice feature on arrays in C# called <code>CopyTo()</code>. It gives you the possibility to copy an array without using a loop. Like so:</p>\n\n<pre><code>int[] newNums = new int[n];\nnums.CopyTo(newNums, 1); \nnewNums[0] = newNums[n-1] = 1; //This line I really like. \n</code></pre>\n\n<p>There is also something called a multidimensional Array which basically does the same thing as <code>int[][]</code>. This gives you the possibility to do this:</p>\n\n<pre><code>int[,] memo = new int[n,n];\n</code></pre>\n\n<p>Use them together and you can remove all your loops from <code>int maxcoins</code>. </p>\n\n<p>Regarding your actual work method Burst I would say that you make things rather confusing. When debugging, the first thing that happens is that you cache a number series which is not allowed until 3 balloons are popped. It adds [0]<em>[1]</em>[5] to the cache. A more reasonable approach would have been [0]<em>[1]</em>[2] then [0]<em>[1]</em>[3] up to [0]<em>[1]</em>[5]. After that switch to [0]<em>[2]</em>[3] etc. When you reach [0]<em>[4]</em>[5] you start over at [1]<em>[2]</em>[3].</p>\n\n<p>To do that you would have to create nested loops in your <code>Burst</code> method:</p>\n\n<pre><code> for (int i = left+1; i < right; ++i)\n {\n for(int j = i+1; j<= right; ++j)\n ans = Math.Max(ans, numbers[left] * numbers[i] * numbers[j]\n + Burst(memo, numbers, left, i)\n + Burst(memo, numbers, i, j));\n }\n</code></pre>\n\n<p>However, there is an even more simple approach to this problem and that is to actually pop the balloons in the array. This can be done easiest with a list instead of an array. But both are possible. So what you would do is to create a new set of balloons after each pop. So here caching is out of the question because you never really know what range you processed before. And to be honest I guess it would most likely slow down the process and make the code harder to read. I use the same variable names as you but in reality I would name <code>nums</code> and <code>numbers</code> as <code>balloons</code> and <code>newNumbers</code> would be named <code>remainingBalloons</code>. I did however change the variable <code>i</code> to <code>baloonToPop</code> to make it easier to understand what it represents. I left the adding of the ones in the code because it simplifies the Burst method. </p>\n\n<pre><code> public void MaxCoins(List<int> nums)\n {\n nums.Insert(0, 1); //Add the ones to the array\n nums.Add(1);\n int result = Burst(nums);\n }\n\n private int Burst(List<int> numbers)\n {\n int result = 0;\n for (int baloonToPop = 1; baloonToPop < numbers.Count-1; baloonToPop++)\n {\n List<int> newNumbers = new List<int>();\n newNumbers.AddRange(numbers);\n newNumbers.RemoveAt(baloonToPop);\n int sumFromBaloonPop = numbers[baloonToPop - 1] * numbers[baloonToPop] * numbers[baloonToPop + 1];\n result = Math.Max(result, Burst(newNumbers) + sumFromBaloonPop);\n }\n return result;\n }\n</code></pre>\n\n<p>To do it with an array (in case there is a library restriction) you would have to create a new <code>Array</code> and then copy <code>Subranges</code> from the initial one instead of creating a copy of the <code>List</code> using <code>AddRange + RemoveAt</code> as above: </p>\n\n<pre><code>int[] newNumbers = new int[numbers.Length-1];\nArray.ConstrainedCopy(numbers, 0, newNumbers, 0, baloonToPop);\nArray.ConstrainedCopy(numbers, baloonToPop + 1, newNumbers, baloonToPop, numbers.Length - (baloonToPop + 1));\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-11T19:46:58.973",
"Id": "449290",
"Score": "1",
"body": "Thorough review, have some rep from me :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-12T06:47:28.930",
"Id": "449344",
"Score": "1",
"body": "@dfhwze I didn't understand why you put a bounty on my question, but thanks you and thank you guys for the reviews"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-11T10:24:10.727",
"Id": "230533",
"ParentId": "230227",
"Score": "4"
}
},
{
"body": "<p>The comment here</p>\n\n<pre><code>int[] numbers = new int[nums.Length +2]; // we add 2 because of the question\n</code></pre>\n\n<p>is not really useful, it requires to read the entire question to figure out why 2 is added to the number of balloons. I would suggest something like</p>\n\n<pre><code>// Allocate array for all balloons, plus the two \"imaginary\" balloons \n// at positions -1 and n.\n</code></pre>\n\n<p>which closely matches the note from the problem description:</p>\n\n<blockquote>\n <p>You may imagine nums[-1] = nums[n] = 1. They are not real therefore you can not burst them.</p>\n</blockquote>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-11T17:30:28.883",
"Id": "230559",
"ParentId": "230227",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "230533",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-05T15:47:10.043",
"Id": "230227",
"Score": "7",
"Tags": [
"c#",
"programming-challenge",
"dynamic-programming"
],
"Title": "LeetCode: Burst Balloons C#"
}
|
230227
|
<p>I'm checking if an byte array contains a another Byte Array with this Code:</p>
<pre><code>private int IndexOf(int index, byte[] AllBytes, byte[] searchByteArray)
{
for (int i = index; i <= AllBytes.Length - 1 - searchByteArray.Length - 1; i++)
{
for (int j = 0; j <= searchByteArray.Length - 1; j++)
{
if (AllBytes[i + j] == searchByteArray[j])
{
if (j + 1 == searchByteArray.Length)
return i;
}
else
break;
}
}
return -1;
}
</code></pre>
<p>That works perfect and I get the index of the first byte back.</p>
<p>But the problem is I want to check very large Data.</p>
<p>My "big" Array contains around 900000000 Bytes and my searchArray about 10-20 Bytes. In that way my function is very very slow. Is there a way to make a better performance?</p>
<p>I need the Index of every found match so I do it into a loop: </p>
<pre><code>for (int i = (IndexOf(0, allData, suchBytes) - 1); i < allData.Length; i++)
{
Debug.WriteLine(i);
tmpIndex = IndexOf(i, allData, suchBytes);
if (tmpIndex > -1)
{
Byte1_Index.Add(tmpIndex + suchBytes.Length);
Debug.WriteLine("Counter: " + Byte_Index_Counter);
i = tmpIndex;
Byte_Index_Counter++;
}
}
</code></pre>
<p>And it takes a way too much time... </p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-05T19:07:08.463",
"Id": "448299",
"Score": "3",
"body": "Maybe [Boyer Moore (string) search algorithm](https://en.wikipedia.org/wiki/Boyer%E2%80%93Moore_string-search_algorithm) can help out here as it could be able to get it working on Byte Array in C#"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-06T14:03:11.820",
"Id": "448367",
"Score": "0",
"body": "Where does `Byte_Index_Counter` come from? The 2nd snippet doesn't look like it's self-contained.. how do the two snippets relate? Please [edit] your post to clarify."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-06T14:56:22.093",
"Id": "448381",
"Score": "0",
"body": "`Byte_Index_Counter` is just for debuggig. Sorry."
}
] |
[
{
"body": "<p>The biggest improvement would be to keep track of potential matches while you are finding if the current match is valid. As Raymond mentioned, in his comment, you could look at KMP or Boyer Moore algorithms but you trade performance for complexity. </p>\n\n<p>Searching though 900000000 Byte will just take some time. There is no magic answer for that but I did a couple of test one with just searching while keeping track of potential matches and one using producer/consumer pattern so I could use the TPL and not block the main threads. Neither one of these was actually faster than the other - in the end it was a wash and both ran anywhere between 7.5 seconds to 8 seconds to run on my machine. The async version was a little better as it didn't just \"hang\" the system while it ran but I don't know if you can use Task in your solution. I did try to bench your code on my machine but it had index out of bound issues. I fixed them with what I thought would be correct but never got a bench mark because I got tired of waiting for the result. </p>\n\n<p>Here is a example of searching that keeps track of potential matches. There is more optimization that could happen. Like not checking rest of source if no matches found and it is past the length of the search. Also could do a pattern match but I'm just checking the first character. </p>\n\n<p><strong>Word of warning I did not do extensive testing on this</strong></p>\n\n<pre><code>public class ByteSearch\n{\n public static IEnumerable<int> Search(byte[] source, byte[] searchByteArray)\n {\n if (source == null)\n {\n throw new ArgumentNullException(nameof(source));\n }\n if (searchByteArray == null)\n {\n throw new ArgumentNullException(nameof(searchByteArray));\n }\n\n var searchLength = searchByteArray.Length;\n var sourceLength = source.Length;\n if (searchLength > sourceLength || searchLength == 0)\n {\n yield break;\n }\n\n var matches = new List<ByteSearchStore>(searchLength);\n for (var i = 0; i < sourceLength - 1; i++)\n {\n var currentByte = source[i];\n\n // found a potential match\n if (currentByte == searchByteArray[0])\n {\n if (searchByteArray.Length == 1)\n {\n yield return i;\n }\n else\n {\n matches.Add(new ByteSearchStore\n {\n StartingIndex = i,\n Index = -1\n });\n }\n }\n\n // check matches\n var count = matches.Count;\n var m = 0;\n while (m < count)\n {\n var potentalMatch = matches[m];\n if (searchByteArray[potentalMatch.Index + 1] == currentByte)\n {\n potentalMatch.Index++;\n if (potentalMatch.Index == searchLength - 1)\n {\n yield return potentalMatch.StartingIndex;\n count = 0;\n matches = new List<ByteSearchStore>(searchLength);\n }\n else\n {\n m++;\n }\n }\n else\n {\n matches.RemoveAt(m);\n count--;\n }\n }\n }\n }\n\n private class ByteSearchStore\n {\n public int Index { get; set; }\n public int StartingIndex { get; set; }\n }\n}\n</code></pre>\n\n<p>The program builds up a list of matches each time it hits the first character of the search string then ejects them once they stop matching the search string. We only check the top match to see if it's the search string because it would be the longest and if it matches we wipe the list as we don't want matches inside our current match. </p>\n\n<p>Example how I ran the program</p>\n\n<pre><code>var random = new Random();\nvar source = Enumerable.Range(0, 900000000).Select(_ => (byte)random.Next(byte.MinValue, byte.MaxValue)).ToArray();\nvar search = Enumerable.Range(0, 9000).Select(_ => (byte)random.Next(byte.MinValue, byte.MaxValue)).ToArray();\nvar test = ByteSearch.Search(source, search).ToArray();\n</code></pre>\n\n<p>If you want the TPL Producer/Consumer one I can post that but again it will be <strong>As Is</strong></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-08T16:00:08.863",
"Id": "230376",
"ParentId": "230231",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-05T17:43:18.543",
"Id": "230231",
"Score": "1",
"Tags": [
"c#",
"performance",
"array"
],
"Title": "Way to check if a byte array contains another byte Array"
}
|
230231
|
<p>I'm working on a small piece of my personal website. I'd like a timeline logging all of my relevant achievements in my career in Computer Science, in general. I'd like to implement a feature that would allow the user to focus on a specific section of the timeline.</p>
<p>I have implemented a fairly sparse version of what I would like. I populate an ordered list via JavaScript, with each list element containing a single child element containing a year. When the user clicks a year that is not the last year in the timeline, it will delete all but the selected year and the proceeding year, then position the selected year on the left end of the timeline and the proceeding year on the right end of the timeline.</p>
<p>I intend to populate the area in between with month that will exhibit the same focus function described above, in order to view each event between the months. </p>
<p>My concern is that I don't <em>think</em> this is the most efficient way of implementing what I want, hence my presence on SO. The implementation of this feature is, in my opinion, quite messy. However, due to the absence of great degrees of experience in the field of front-end development, my opinion may very well be wrong. </p>
<p>Naturally, I've added the code to this question. I really don't know whether or not this is the best implementation; any advice would be much appreciated. </p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>let focussed = false;
document.addEventListener("DOMContentLoaded", () => {
generateTimeline();
});
function generateTimeline() {
let timeline = document.getElementsByClassName("timeline")[0];
timeline.appendChild(createYearElement("2019"));
timeline.appendChild(createYearElement("2018"));
timeline.appendChild(createYearElement("2017"));
timeline.appendChild(createYearElement("2016"));
for (let i = 0; i < timeline.children.length; i++) {
const child = timeline.children[i];
let text = child.children[0];
if (text.innerHTML === "2016") continue;
text.addEventListener("click", () => {
let year = text.innerHTML;
let lastYear = null;
if (focussed) return;
if (year === "2017") {
lastYear = "2016";
}
if (year === "2018") {
lastYear = "2017";
}
if (year === "2019") {
lastYear = "2018";
}
if (year !== "2019") removeYearElement("2019");
if (year !== "2018" && lastYear !== "2018") removeYearElement("2018");
if (year !== "2017" && lastYear !== "2017") removeYearElement("2017");
if (lastYear !== "2016") removeYearElement("2016");
let lastYearElement = document.getElementById(`${lastYear}YearElement`);
lastYearElement.style.marginLeft = "400px";
focussed = !focussed;
createBackButton();
});
}
}
function createYearElement(year) {
let element = document.createElement("li");
element.setAttribute("class", "year");
element.setAttribute("id", `${year}YearElement`);
let text = document.createElement("div");
text.innerHTML = year;
element.appendChild(text);
return element;
}
function createBackButton() {
let button = document.createElement("button");
button.innerHTML = "Back";
button.setAttribute("id", "backButton");
button.addEventListener("click", () => {
let timeline = document.getElementsByClassName("timeline")[0];
let childrenArray = Array.slice(timeline.children);
for (let i = 0; i < childrenArray.length; i++) {
const child = childrenArray[i];
child.remove();
}
generateTimeline();
focussed = !focussed;
button.remove();
});
document.getElementsByClassName("timeline_box")[0].appendChild(button);
}
function removeYearElement(year) {
let timeline = document.getElementsByClassName("timeline")[0];
for (let i = 0; i < timeline.children.length; i++) {
const child = timeline.children[i];
if (child.children[0].innerHTML === year) child.remove();
}
}</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>.timeline_box {
width: 80%;
height: 50%;
background: lightslategrey;
margin: auto;
margin-top: 10%;
display: grid;
justify-content: center;
align-content: center;
position: relative;
}
.timeline_wrapper {
width: 500px; }
.timeline_line {
z-index: 1;
width: inherit;
height: 20px;
margin-top: 5px;
background: linear-gradient(to bottom, rgba(255, 255, 255, 0) 0%, rgba(255, 255, 255, 0) 45%, #fd2600 51%, rgba(255, 255, 255, 0) 57%, rgba(255, 255, 255, 0) 100%); }
.timeline {
z-index: 2;
list-style: none;
width: inherit; }
.timeline > li {
float: left;
margin-left: 100px;
background: greenyellow;
padding: 5px;
border-radius: 5px; }
.timeline > li:nth-child(1) {
margin-left: 0; }
button {
width: 100px;
height: 30px;
color: black;
margin: auto; }
html,
body,
element,
* {
margin: 0;
padding: 0;
border: 0; }</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code> <body>
<div class="timeline_box">
<div class="timeline_wrapper">
<ol class="timeline">
</ol>
<div class="timeline_line"></div>
</div>
</div>
</body></code></pre>
</div>
</div>
</p>
|
[] |
[
{
"body": "<blockquote>\n <p>I really don't know whether or not this is the best implementation; any advice would be much appreciated</p>\n</blockquote>\n\n<p>In my opinion, the 'best' way is relative, subjective, arbitrary. There's a lot of moving parts to the DOM and many avenues that get you to the same destination. So there, <em>for the majority of scenarios</em>, is no 'righter' way. I do, circumstantially, think there are more efficient ways to do things, but I stress circumstantially. Your performance hits are few and far between in personal websites like you are building though so in my opinion I would say don't make that a focal point for concern. </p>\n\n<p>For brevity, I think it's a valid concern and shows that you have a great mentality thinking about the 'grand scheme' of things, but you should never say things like </p>\n\n<blockquote>\n <p>due to the absence of great degrees of experience in the field of front-end development, my opinion may very well be wrong</p>\n</blockquote>\n\n<p>That pre-dispositions you for failure. Just because you don't have a degree, which is debatably relevant in today's scope anyways, does not automatically dismiss your creative freedom or mean you automatically know less. Anyone on a team can have a good idea and even PMs mess up :) we're all just people. Although I get what you are saying, try not to make it a habit, for many reasons.</p>\n\n<p>Anyways, I'm going to offer a solution and I'm aware it may not be what you are looking for, but it's there if you fancy it, it's there if you don't. I'll certainly explain my thought process however, but right, wrong or indifferent, it's a way to do it, I'm not implicitly arguing it's <em>the</em> way to do it either. </p>\n\n<p>Located at the bottom for review, just keep in mind I'm not a graphic designer :p \nThe solution is also not responsive because I don't know what your plans are so I didn't want to force it, but of course it can/should be. The CSS isn't important anyways, it's just for the demo, you're going to change it to fit your needs.</p>\n\n<p>However, my solution, as it stands now, is a pure CSS solution. My high-level reasons for that are</p>\n\n<ul>\n<li>Maintainability </li>\n<li>Accessibility</li>\n<li>Readability</li>\n<li>Semantics</li>\n</ul>\n\n<p>There really are no efficiency concerns with this ask. Overall though, in my opinion, keeping a timeline like this CSS-focused will make it easier to maintain as your requirements change or get more complex. As you can see, there isn't that much HTML involved, we let CSS handle it independently, like it should, so that way we can move the HTML around anywhere without causing conflicts, and we can even use the same stylesheet for other projects. Overall, it feels moduralized, your HTML is maintainable now, same for CSS but now you don't have scripts dependent on, or creating, elements or altering/creating selectors like ids other files are dependent on. I'm not saying what you are doing is wrong, I'm just saying don't make it hard on yourself maintainability wise by having attributes and elements set in different ways in different places, if it can be avoided. </p>\n\n<p>I don't want to drag this on or bore you, so I think readability is understood.</p>\n\n<p>I'm sure other people have suggestions about your javascript, as do I, but I just wanted to talk about semantics and accessibility. </p>\n\n<h3>semantics</h3>\n\n<p>Semantics are very important for many reasons, like SEO and accessibility. There's lots of resources out there already for you to review so I won't double-tap; but for me, the biggest take away is that it's layered. Semantics isn't just about using the right tag for it's intended purpose, it's also about UIX and how are those tags semantically being used by the end user. Meaning, would you rather, as a user, want to manually click 'load more' at the end of a picture feed, or would you prefer the 'infinite scrolling' method. Both work, both apply, but one of them just feels right as a user. You know what you want, you're obviously at the end for a reason. </p>\n\n<p>So I would just ask, re the UIX topic, how will your users <strong><em>know</em></strong> they need to click on a year for more details? How do they even know they can? Timelines are tough because usually they are static content and what you want to do is very cool and different, so you need to give them a reason to invest their time in your portfolio and use those cool things. You have to effectively sell yourself very quickly and I would just ask maybe reconsider the explicit interaction you are suggesting, or at least how I interpreted it. Think about how often you really digest a persons portfolio, I'm guessing not much but I think that's normal; just consider there potentially are a lot of people out there with \"not much attitude\" too.</p>\n\n<p>My way may not be the best answer to that, but I think people at least can gather that with every year there are months next to it. Curiosity is left up to them after that in my case, but again, I'm not a designer I actually hire some for my personal stuff so I leave no room for doubt in my own mind. </p>\n\n<p>Lastly on this topic, what you have in HTML isn't wrong, it's what the spec would call <code>conformed</code>, but it could use improvement. Think about the structure, a timeline is a list of events that happen in a specific order(ol) and can also happen in any order (ul). All checks out, your syntax meets that requirement. </p>\n\n<p>But by your definition, \"a timeline separated by years that contains a list of months\" implicitly identifies a sectioning flow of content; a la an address book. Each section has a header, usually the first letter of last name, then lists those contacts that qualify. Again, this helps screen readers, but more importantly SEO. What you are trying to do is fit a header into an li, so how do you suppose google will index that? Probably as just another li. </p>\n\n<p>What I like to do when I think about content model is simply go to MDN or the spec and review what the <code>permitted content</code> is to make sure I'm giving myself the best chance at SEO. Over time this will come to you like it's second nature because there are only so many pre-defined tags.</p>\n\n<p>If you look at the <a href=\"https://developer.mozilla.org/en-US/docs/Web/HTML/Element/li\" rel=\"nofollow noreferrer\">permitted content</a> of an li, it states \"flow content\", which actually includes h1,h2,h3 etc. So again, while it's valid HTML, it's not reflecting intention. </p>\n\n<p>Now, if you read the <a href=\"https://html.spec.whatwg.org/multipage/grouping-content.html#the-li-element\" rel=\"nofollow noreferrer\">spec</a> at the very end of that section, it states:</p>\n\n<blockquote>\n <p>While it is conforming to include heading elements (e.g. h1) inside li elements, it likely does not convey the semantics that the author intended. A heading starts a new section, so a heading in a list implicitly splits the list into spanning multiple sections.</p>\n</blockquote>\n\n<p>How oddly specific to this situation :P</p>\n\n<p>Now the question comes, how do you add a section title to a ul/ol, there's no tag or attribute for it? Well, turns out there are many ways, using a <code>dl</code>, an <code>h3</code> before the list tag and more 'list-like' tags, but the example I used in the snippet below comes straight from the source and satisfies intention and helps SEO and screen readers and makes it easier to style! Win-win-win-wins!! If you go back to the <a href=\"https://html.spec.whatwg.org/multipage/grouping-content.html#the-li-element\" rel=\"nofollow noreferrer\">spec</a>, in the examples for li, the second example they provide demonstrates that edge case, what I consider an edge case any ways.</p>\n\n<p>Really, when it comes to knowing what tag is used where and when and how just comes down to practice. I have spent many a nights in a endless loop of reading all the details for some scenarios but as mentioned, over time it is just a thought a way. I walked through all this just to show how I approach some of these same issues. Those resources are a great start but you'll find what works best for you.</p>\n\n<h3>accessibility</h3>\n\n<p>Accessibility and semantics kind of go hand-in-hand. Whatever is semantically sound is <em>almost</em> accessibility-ready. Unfortunately, a lot of devs don't consider doing it because they aren't impacted by an inaccessible web or don't do it for their job. It's one of things that \"you think will never happen to you\" until something bad happens or you have a family member. I think a personal site is a great time to start learning if you haven't already because you have the luxury of taking your time to learn it right, understand how it works and be a resume builder. Mostly because you do not want to give anyone a reason to disqualify you from a job if their recruiter happens to be disabled and visits your site. Additionally, trust me, even if they aren't some will inspect the page to see whats under the hood, so if anything, it could very well set you apart from other candidates.</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>:root {\n --color-tl-chevron-fg-hover: rgba(255,255,255,1);\n --color-tl-chevron-fg: rgba(255,255,255,0.6);\n --color-tl-chevron: cornflowerblue;\n --color-tl-bg: snow;\n --color-tl-fg: rgba(0,0,0,1);\n}\n\nhtml {\n font-family: \"Trebuchet MS\", Geneva, sans-serif;\n font-size: 16px;\n background-color:#022b3a;\n}\n\n.timeline-container {\n display: flex; \n position: relative;\n flex-flow: row nowrap; \n margin: 0 auto; padding: 0;\n width: 96%;\n \n background-color: var(--color-tl-bg);\n box-shadow: 7px 0px 30px 0px rgba(0,0,0,0.3);\n}\n.timeline-container:after {\n content: '';\n position: absolute;\n width: 0; height: 0;\n right:0;\n margin-right: -1em;\n \n border: solid var(--color-tl-bg) 1.6em;\n border-left-width: 1em;\n border-right-width: 0;\n border-top-color: transparent;\n border-bottom-color: transparent;\n \n overflow: hidden;\n}\n\nfigure {\n display: flex;\n margin: 0; padding: 0;\n \n transition: flex 0.15s ease-in-out;\n z-index: 1;\n}\nfigure:hover:not(:last-child) ~ figure:last-child {\n flex: unset; \n}\nfigure:hover:not(:nth-last-child(-n+2)) ~ figure:last-child figcaption {\n color: var(--color-tl-chevron-fg);\n font-weight: normal;\n}\nfigure:hover:not(:last-child) ~ figure:last-child ul {\n display: none;\n} \n\nfigure figcaption {\n position: relative;\n padding: 1rem;\n \n background-color: var(--color-tl-chevron);\n color: var(--color-tl-chevron-fg);\n}\nfigure figcaption:before,\nfigure figcaption:after {\n content: '';\n position: absolute;\n width: 0; height: 0;\n right:0;\n top:0;\n \n border: solid var(--color-tl-chevron) 1.59rem;\n border-left-width: 1em;\n border-right-width: 0;\n \n overflow: hidden;\n}\nfigure figcaption:after {\n margin-right: -1em;\n \n border-color: var(--color-tl-chevron);\n border-top-color: transparent;\n border-bottom-color: transparent;\n}\nfigure figcaption:before {\n margin-right: 3.5em;\n \n border-right-width: 1em;\n border-left-color: transparent;\n}\nfigure:hover,\nfigure:not(:hover):last-child {\n flex: 2;\n cursor: default;\n}\n\nfigure:hover figcaption,\nfigure:hover + figure figcaption,\nfigure:not(:hover):last-child figcaption {\n color: var(--color-tl-chevron-fg-hover);\n font-weight: bold;\n}\nfigure:hover ul,\nfigure:not(:hover):last-child ul {\n display: flex;\n}\n\n\nul {\n display: none; \n flex: 1;\n margin: 0; padding: 0;\n}\n\nul li {\n display: flex;\n flex: 1;\n justify-content: center;\n align-items:center;\n \n font-size: 0.85em;\n list-style: none;\n}\n\na,\na:link,\na:visited,\na:focus,\na:active,\na:hover {\n color: var(--color-tl-fg);\n \n text-decoration: none;\n cursor: pointer;\n}\n\na:hover {\n font-weight: bold;\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><div class=\"timeline-container\">\n <figure>\n <figcaption>2015</figcaption>\n <ul>\n <li><a href=\"\">Jan</a></li>\n <li><a href=\"\">Feb</a></li>\n <li><a href=\"\">March</a></li>\n <li><a href=\"\">April</a></li>\n </ul>\n </figure>\n <figure>\n <figcaption>2016</figcaption>\n <ul>\n <li><a href=\"\">May</a></li>\n <li><a href=\"\">Jun</a></li>\n <li><a href=\"\">July</a></li>\n <li><a href=\"\">Aug</a></li>\n </ul>\n </figure>\n <figure>\n <figcaption>2017</figcaption>\n <ul id=\"2017-Portfolio\">\n <li><a href=\"\">Oct</a></li>\n <li><a href=\"\">Nov</a></li>\n <li><a href=\"\">Dec</a></li>\n <li><a href=\"\">Jan</a></li>\n </ul>\n </figure>\n <figure>\n <figcaption>2018</figcaption>\n <ul>\n <li><a href=\"\">Jan</a></li>\n <li><a href=\"\">Feb</a></li>\n <li><a href=\"\">March</a></li>\n <li><a href=\"\">April</a></li>\n </ul>\n </figure>\n <figure>\n <figcaption>2019</figcaption>\n <ul>\n <li><a href=\"\">Jan</a></li>\n <li><a href=\"\">Feb</a></li>\n <li><a href=\"\">March</a></li>\n <li><a href=\"\">April</a></li>\n </ul>\n </figure>\n</div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-02T13:30:12.630",
"Id": "455882",
"Score": "2",
"body": "You have presented an alternative solution, but haven't reviewed the code. Please [edit] to show what aspects of the question code prompted you to write this version, and in what ways it's an improvement over the original. It may be worth (re-)reading [answer]."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-29T23:32:14.140",
"Id": "233179",
"ParentId": "230239",
"Score": "2"
}
},
{
"body": "<h1>Implementation Review</h1>\n<p>Ten years ago there were typically users that would commonly use IE and code like this that creates elements, adds event handlers to those elements and then removes those elements <a href=\"https://stackoverflow.com/q/2631265/1575353\">had the possibility to leak memory</a>. While that may not be an issue anymore it is something to consider. A simpler approach would use <a href=\"https://davidwalsh.name/event-delegate\" rel=\"nofollow noreferrer\">event delegation</a> to observe clicks on a parent element and distribute event handling to other functions.</p>\n<p>Instead of removing and re-adding elements, a simpler approach would be to apply a class name to the selected item and hide adjacent siblings via CSS. This helps <a href=\"https://developers.google.com/speed/docs/insights/browser-reflow\" rel=\"nofollow noreferrer\">limit browser reflow</a>. On a page with few elements that might not be an important consideration but it would on a large page/application.</p>\n<h1>Bug</h1>\n<p>When the back button is clicked, this line is called</p>\n<blockquote>\n<pre><code>let childrenArray = Array.slice(timeline.children);\n</code></pre>\n</blockquote>\n<p>That leads to an error:</p>\n<blockquote>\n<p>Error: Array.slice is not a function.</p>\n</blockquote>\n<p>Perhaps the intention was to call the <code>slice</code> method from <code>Array.prototype</code> on that array/nodelist:</p>\n<pre><code>let childrenArray = Array.prototype.slice.call(timeline.children);\n</code></pre>\n<h1>Code Review</h1>\n<h2>Variable declarations</h2>\n<p>Good job using <code>const</code> in some places. There are however places where <code>const</code> could be used instead of <code>let</code> - e.g. for <code>timeline</code>, since it never gets re-assigned. It is advised to default to using <code>const</code> and then switch to <code>let</code> when re-assignment is deemed necessary. This helps avoid <a href=\"https://softwareengineering.stackexchange.com/a/278653/244085\">accidental re-assignment and other bugs</a>.</p>\n<h2>DRY code</h2>\n<p>The following lines are quite repetitive:</p>\n<blockquote>\n<pre><code> timeline.appendChild(createYearElement("2019"));\n timeline.appendChild(createYearElement("2018"));\n timeline.appendChild(createYearElement("2017"));\n timeline.appendChild(createYearElement("2016"));\n</code></pre>\n</blockquote>\n<p>They go against the <a href=\"https://deviq.com/don-t-repeat-yourself/\" rel=\"nofollow noreferrer\"><em><strong>D</strong>on’t <strong>R</strong>epeat <strong>Y</strong>ourself</em> principle</a>. A loop could simplify this:</p>\n<pre><code>for (let year = 2019; year > 2015; year--) {\n timeline.appendChild(createYearElement(year));\n}\n</code></pre>\n<p>This also makes changes to the year limit simpler.</p>\n<h2>Extra lambda/anonymous function/closure</h2>\n<p>There is an extra function here:</p>\n<blockquote>\n<pre><code>document.addEventListener("DOMContentLoaded", () => {\n generateTimeline();\n});\n</code></pre>\n</blockquote>\n<p>That could be simplified to just a reference to the function:</p>\n<pre><code>document.addEventListener("DOMContentLoaded", generateTimeline);\n</code></pre>\n<h2>Simplified code</h2>\n<p>Putting the suggestions above to work the code can be simplified dramatically.</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"false\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>document.addEventListener(\"DOMContentLoaded\", generateTimeline);\nconst selectedItems = document.getElementsByClassName('selected');\nconst timelineBox = document.getElementsByClassName('timeline_box')[0];\nfunction generateTimeline() {\n const timeline = document.getElementsByClassName(\"timeline\")[0];\n for (let year = 2019; year > 2015; year--) {\n timeline.appendChild(createYearElement(year));\n }\n createBackButton();\n timeline.addEventListener('click', event => {\n if (selectedItems.length) { //do this instead of tracking focussed\n return;\n }\n if (event.target.tagName.toLowerCase() !== 'div') {\n return;\n }\n if (event.target.innerText === '2016') {\n return;\n }\n const selectedItem = event.target.parentNode;\n timelineBox.classList.add('focussed');\n selectedItem.classList.add('selected');\n });\n\n}\n\nfunction createYearElement(year) {\n const element = document.createElement(\"li\");\n element.setAttribute(\"class\", \"year\");\n element.setAttribute(\"id\", `${year}YearElement`);\n const text = document.createElement(\"div\");\n text.innerHTML = year;\n element.appendChild(text);\n return element;\n}\n\nfunction createBackButton() {\n const button = document.createElement(\"button\");\n button.innerHTML = \"Back\";\n button.setAttribute(\"id\", \"backButton\");\n\n button.addEventListener(\"click\", () => {\n timelineBox.classList.remove('focussed');\n selectedItems[0].classList.remove('selected');\n });\n\n timelineBox.appendChild(button);\n}</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>.timeline_box {\n width: 80%;\n height: 50%;\n background: lightslategrey;\n margin: auto;\n margin-top: 10%;\n display: grid;\n justify-content: center;\n align-content: center;\n position: relative;\n}\n\n.timeline_wrapper {\n width: 500px;\n}\n\n.timeline_line {\n z-index: 1;\n width: inherit;\n height: 20px;\n margin-top: 5px;\n background: linear-gradient(to bottom, rgba(255, 255, 255, 0) 0%, rgba(255, 255, 255, 0) 45%, #fd2600 51%, rgba(255, 255, 255, 0) 57%, rgba(255, 255, 255, 0) 100%);\n}\n\n.timeline {\n z-index: 2;\n list-style: none;\n width: inherit;\n}\n\n.timeline>li {\n float: left;\n margin-left: 100px;\n background: greenyellow;\n padding: 5px;\n border-radius: 5px;\n}\n\n.timeline>li:nth-child(1) {\n margin-left: 0;\n}\n.timeline_box.focussed .timeline > li {\n display: none;\n}\n.timeline_box.focussed .timeline > li.selected {\n display: block;\n margin-left: 0;\n}\n.timeline_box.focussed .timeline > li.selected + li {\n display: block;\n margin-left: 400px;\n}\n#backButton {\n display: none;\n}\n.timeline_box.focussed > #backButton {\n display: block;\n}\n\nbutton {\n width: 100px;\n height: 30px;\n color: black;\n margin: auto;\n}\n\nhtml,\nbody,\nelement,\n* {\n margin: 0;\n padding: 0;\n border: 0;\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><body>\n <div class=\"timeline_box\">\n <div class=\"timeline_wrapper\">\n <ol class=\"timeline\">\n </ol>\n <div class=\"timeline_line\"></div>\n </div>\n </div>\n</body></code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-27T05:27:58.933",
"Id": "251193",
"ParentId": "230239",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-05T20:46:41.070",
"Id": "230239",
"Score": "9",
"Tags": [
"javascript",
"html",
"css",
"ecmascript-6",
"event-handling"
],
"Title": "User-focused timeline logging"
}
|
230239
|
<p>I'm currently learning C by working on my first project.
It's a calculator with a parser that transforms input into an operator tree. These trees consist of nodes of different types: Operators (inner nodes), constants and variables. My first attempt was to create a single <strong>struct node</strong> and just put everything a Node <em>might have</em> in it -- which wastes a lot of memory because not all of the fields are used, depending on the actual type a Node has.</p>
<p>My solution:
I implemented three different structs for the three different Node types.</p>
<pre><code>typedef enum
{
NTYPE_OPERATOR,
NTYPE_CONSTANT,
NTYPE_VARIABLE
} NodeType;
typedef NodeType* Node;
struct VariableNode_
{
NodeType type;
char var_name[];
};
struct ConstantNode_
{
NodeType type;
double const_value;
};
struct OperatorNode_
{
NodeType type;
Operator *op;
size_t num_children;
Node children[];
};
</code></pre>
<p>They all have a type as their first field -- a header to let me know which type a Node actually has. A Node is always a pointer to the heap, so I typedef'ed it to hide its pointer type. A node may be created and used by the following "constructors" and accessors:</p>
<pre class="lang-c prettyprint-override"><code>Node malloc_variable_node(char *var_name)
{
VariableNode res = malloc(sizeof(struct VariableNode_) + (strlen(var_name) + 1) * sizeof(char));
if (res == NULL) return NULL;
res->type = NTYPE_VARIABLE;
strcpy(res->var_name, var_name);
return (Node)res;
}
Node malloc_constant_node(ConstantType value)
{
ConstantNode res = malloc(sizeof(struct ConstantNode_));
if (res == NULL) return NULL;
res->type = NTYPE_CONSTANT;
res->const_value = value;
return (Node)res;
}
Node malloc_operator_node(Operator *op, size_t num_children)
{
if (num_children > MAX_ARITY)
{
// Max. arity exceeded
return NULL;
}
OperatorNode res = malloc(sizeof(struct OperatorNode_) + num_children * sizeof(Node));
if (res == NULL) return NULL;
for (size_t i = 0; i < num_children; i++)
{
res->children[i] = NULL;
}
res->type = NTYPE_OPERATOR;
res->op = op;
res->num_children = num_children;
return (Node)res;
}
void free_tree(Node tree)
{
if (tree == NULL) return;
if (get_type(tree) == NTYPE_OPERATOR)
{
for (size_t i = 0; i < get_num_children(tree); i++)
{
free_tree(get_child(tree, i));
}
}
free(tree);
}
NodeType get_type(Node node)
{
return *node;
}
Operator *get_op(Node node)
{
return ((OperatorNode)node)->op;
}
size_t get_num_children(Node node)
{
return ((OperatorNode)node)->num_children;
}
Node get_child(Node node, size_t index)
{
return ((OperatorNode)node)->children[index];
}
Node *get_child_addr(Node node, size_t index)
{
return &((OperatorNode)node)->children[index];
}
void set_child(Node node, size_t index, Node child)
{
((OperatorNode)node)->children[index] = child;
}
char *get_var_name(Node node)
{
return ((VariableNode)node)->var_name;
}
double get_const_value(Node node)
{
return ((ConstantNode)node)->const_value;
}
</code></pre>
<p>Is this common practice? Would there be a better way to do it? Would it have been okay to just waste the space and use a single struct as I did before? This would almost always safe me a level of indirection when dealing with trees and transforming them because all Nodes would have the same size and could be recycled.
If you want to look at the full file(s): <a href="https://github.com/PhilippHochmann/Calculator/blob/master/src/parsing/node.h" rel="nofollow noreferrer">node.h hosted at GitHub</a></p>
<p>Thanks in advance :)</p>
<p>Edit: Changed ConstantType to double because the type was not defined in the excerpt I posted</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-06T13:59:54.727",
"Id": "448365",
"Score": "0",
"body": "You have provided a link to the source code, however, it would be better if the entire node.h file and node.c file were here for review. It might also be better if you provided enough code from other files to show how this code was used. At least one type, `ConstantType` lacks a definition in the code that is here."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-06T14:02:02.187",
"Id": "448366",
"Score": "0",
"body": "Do you have any unit testing set up, or is the only way to test it to run the calculator? It would be better for you if you could test the parser separately from the calculator."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-06T14:20:12.823",
"Id": "448369",
"Score": "0",
"body": "I have a separate parser test, which is located at https://github.com/PhilippHochmann/Calculator/blob/master/tests/parser_test.c and is run when invoking make.sh with the flag -d"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-06T14:20:22.600",
"Id": "448371",
"Score": "0",
"body": "Just a suggestion, but if you're running on Linux you might want to look into using CMake, on almost all systems (Windows, Linux, OSX) Make is supported. The value of Make over the make.sh file you have is that only source files and header files that have changed will be recompiled. Many development environments build the make file for you as you add files."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-06T14:23:43.227",
"Id": "448372",
"Score": "0",
"body": "Polymorphism is an implementation-agnostic term - you don't have C++ polymorphism, but you do still have polymorphism. It's not really 'faux'."
}
] |
[
{
"body": "<blockquote>\n <p>Is this common practice?</p>\n</blockquote>\n\n<p>Enum-based type tracking in C? Yes.</p>\n\n<blockquote>\n <p>Would there be a better way to do it?</p>\n</blockquote>\n\n<p>Depends on a few things, including your definition of <em>better</em>. I think this is fine, but if your type-conditional code ends up being extremely long, then you can move to a more C++-style approach, where instead of tracking a type enum, you track function pointers; then your <code>if (get_type())</code> code disappears and you can blindly call the function pointer. It's a little more complicated, and can have performance implications.</p>\n\n<blockquote>\n <p>Would it have been okay to just waste the space and use a single struct as I did before?</p>\n</blockquote>\n\n<p>Again - it depends. How many of these structures are you instantiating? Seven, or seven billion?</p>\n\n<p>Wasting the space can actually be more performant - you can simplify your allocation logic.</p>\n\n<p>There's yet another option where you don't waste space at all - C allows you to do a dirty trick called <code>union</code> punning. Basically, write multiple versions of the structure whose memory overlaps, and choose the right one based on context. </p>\n\n<p>Until performance becomes a very specific and dominant issue, just stick with what you have, which is simple and legible, and resist the urge to prematurely optimize.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-06T14:40:16.073",
"Id": "230268",
"ParentId": "230240",
"Score": "2"
}
},
{
"body": "<p>Remarks for beginners:</p>\n\n<ul>\n<li>Never hide a pointer behind a typedef! Never! It makes the code confusing and very hard to read and maintain.</li>\n<li>You can't unfortunately use a generic <code>Node</code> pointer like in your code, because this isn't well-defined by the language. There are ways around it, but they are a bit controversial (see advanced reply below).</li>\n<li>Generally, when doing any kind of polymorphism, you might want to have an \"abstract base class\". In this case it would have been <code>NodeType</code>, but it should be a struct of its own and each inherited class should contain an instance of the base class as first member. Not a pointer to it. </li>\n<li>Avoid calling functions in the controlling statement of a <code>for</code> loop like you do in <code>for (size_t i = 0; i < get_num_children(tree); i++)</code>. This will often produce needlessly slow code. Instead call the function once before the loop, then store the result in a variable.</li>\n</ul>\n\n<hr>\n\n<p>Remarks for veterans (beginners ignore):</p>\n\n<p>One advanced trick which is supposedly fully supported by the standard (but might have diverse quality of implementation on different compilers) is the \"union common initial sequence\" trick.</p>\n\n<p>There's a rule stating that if you expose a union containing all those structs to the same translation unit as where those structs are used, type punning between the structs is well-defined. In your case something like this:</p>\n\n<pre><code>union type_punning\n{\n struct VariableNode_ a;\n struct ConstantNode_ b;\n struct OperatorNode_ c;\n};\n</code></pre>\n\n<p>This union just needs to sit there; you don't need to use it, or even show it to the caller. This tells the compiler that since these struct share a common initial sequence, the <code>NodeType</code> member, we can type pun between them and it is well-defined, as long as we only access shared members of that initial sequence.</p>\n\n<p>Meaning that suddenly we can do this:</p>\n\n<pre><code>void func (struct VariableNode_* vn)\n{\n if(vn->type == NTYPE_CONSTANT)\n {\n struct ConstantNode_* cn = (struct ConstantNode_*)vn;\n cn->const_value = something; // well-defined!\n }\n}\n</code></pre>\n\n<p>There's also exceptions to the strict aliasing rule allowing this use. </p>\n\n<p>Source: C17 6.5.2.3</p>\n\n<blockquote>\n <p>One special guarantee is made in order to simplify the use of unions: if a union contains\n several structures that share a common initial sequence (see below), and if the union\n object currently contains one of these structures, it is permitted to inspect the common\n initial part of any of them anywhere that a declaration of the completed type of the union\n is visible. Two structures share a <em>common initial sequence</em> if corresponding members\n have compatible types (and, for bit-fields, the same widths) for a sequence of one or more\n initial members.</p>\n</blockquote>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-08T14:11:11.130",
"Id": "448691",
"Score": "0",
"body": "On bullet 4 in the beginner section are you say that when it is compiled -O3 the compiler won't put that value into a register or temporary variable and reuse it? Not that this would be specified by the standard."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-08T14:19:21.227",
"Id": "448692",
"Score": "0",
"body": "@pacmaninbw The compiler can't do that if the function has external linkage. Some standard lib functions like `strlen` might be inline optimized, but custom functions most likely not."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-08T14:22:55.287",
"Id": "448693",
"Score": "0",
"body": "So if the function is declared `static` and local to the file it should do the optimization? (clarifying for users)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-08T14:26:39.337",
"Id": "448696",
"Score": "2",
"body": "@pacmaninbw It depends on what the function does too, of course. It might not be feasible to inline it because it's too big. Generally the compiler is better suited than the programmer to determine what to inline (why `inline` is regarded as a mostly obsolete keyword). At any rate, there is never any harm with calling the function before the loop - it will make the loop slightly easier to read if nothing else."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-08T14:28:27.060",
"Id": "448697",
"Score": "0",
"body": "You're correct of course, there is never a problem calling the function before the loop."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-08T21:34:08.057",
"Id": "448737",
"Score": "0",
"body": "I've read in the Linux Kernel Code guidlines to never typedef a pointer-type, but I think when there can't be a case that code wants to directly dereference it, it's not a problem. No code would ever do something with a Node other than passing it to a getter function (which dereferences it). It's nothing else than a handle, like FILE."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-08T21:39:25.893",
"Id": "448738",
"Score": "0",
"body": "So, the way I do it is undefined or implementation-defined? Because it works well. Of course, I'm gonna try to implement it by a union to be compliant to the standard."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-08T21:44:51.137",
"Id": "448739",
"Score": "0",
"body": "Also, what type should I pass to a function? In your example, you arbitrarily chose VariableNode_, but it could have also been the other two."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-09T06:32:16.487",
"Id": "448790",
"Score": "1",
"body": "@PhilippHochmann It leads to muddy use. Before you know it, people will start using `Node*` which is actually a pointer to pointer, to avoid passing the variable by value. Or write bugs because they don't realize it is a pointer, like `Node n = (Node){0}; ... return n;`. So there is absolutely no point in hiding the pointer syntax to the user. If they can or can't acccess the pointed-at contents is irrelevant."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-09T06:42:14.690",
"Id": "448791",
"Score": "1",
"body": "@PhilippHochmann To cast a pointer to struct into a pointer of the type of its first element is well-defined. However, your various struct types are not compatible with each other. What I'm trying to say is that you should have a struct which acts as base class, containing the enum. Then have every other struct type declare an instance of that struct acting as base class, as its first member. This would allow you to write an API where functions take the base class pointer as parameter, but may invoke inherited class functionality. Also known as polymorphism in OO design."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-09T10:53:02.620",
"Id": "448826",
"Score": "0",
"body": "Alright, I've changed it to suit your description (I think) and pushed it. Thank you :)"
}
],
"meta_data": {
"CommentCount": "11",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-08T14:01:21.813",
"Id": "230374",
"ParentId": "230240",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "230268",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-05T22:30:29.570",
"Id": "230240",
"Score": "3",
"Tags": [
"beginner",
"object-oriented",
"c",
"parsing",
"polymorphism"
],
"Title": "Implementation of tree with different node types and faux-polymorphism in C"
}
|
230240
|
<p>Inspired by this <a href="https://shintakezou.blogspot.com/2019/10/enumeration-enum-in-perl6.html" rel="nofollow noreferrer">blogpost</a> I decided to try and make it possible to have ranges of <code>enum</code> members that dwim, aka. that contain the actual members and not a stringified form. </p>
<p>This is the result. I'm looking for comments and wether I overlook a pitfall. Also, maybe <code>EnumMember</code> subset can be expressed in a more performant way?</p>
<pre><code>use Test;
subset EnumMember of Any where .HOW.^name eq "Perl6::Metamodel::EnumHOW";
multi sub infix:<..>( EnumMember $a, EnumMember $b )
{
die "Can only do ranges for members of the same enum" unless $a.WHAT === $b.WHAT;
$a.WHAT.^enum_value_list.grep({ $_ === $a fff $_ === $b })
}
enum Foo ( XA => 17, XB => 19, XC => 2, XD => 17, XE => 1, XF => 99 );
enum Goo < YA YB >;
is-deeply( ( XC..XE ).Array, [XC, XD, XE] );
dies-ok({ XA..YB });
</code></pre>
|
[] |
[
{
"body": "<p>Probably, you could do something similar by <code>...</code> and <code>succ</code>.</p>\n\n<pre class=\"lang-perl prettyprint-override\"><code>enum Foo ( XA => 17, XB => 19, XC => 2, XD => 17, XE => 1, XF => 99 );\nenum Goo < YA YB >;\nXC, *.succ ... XE andthen .say\n</code></pre>\n\n<p>Thus your example could be rewritten</p>\n\n<pre class=\"lang-perl prettyprint-override\"><code>use Test;\n\nsubset EnumMember of Enumeration; \n\nmulti sub infix:<..>( EnumMember:D ::T $a, T:D $b ) {\n $a, *.succ ... $b \n}\n\nmulti sub infix:<..>( EnumMember $a, $b ) {\n die 'Can only do ranges for members of the same enum' \n}\n\nenum Foo ( XA => 17, XB => 19, XC => 2, XD => 17, XE => 1, XF => 99 );\nenum Goo < YA YB >;\n\nis-deeply( ( XC..XE ).Array, [XC, XD, XE] ); \ndies-ok({ XA..YB }); \n</code></pre>\n\n<p>But you get <code>Seq</code>, not <code>Range</code>. So I prefer redefine the sequence operator <code>...</code> and make a new role instead of a subtype.</p>\n\n<pre class=\"lang-perl prettyprint-override\"><code>use Test;\n\nrole EnumMember {}; \n\nmulti sub infix:<...>( EnumMember:D ::T $a, T:D $b ) {\n $a, *.succ ... $b \n}\n\nmulti sub infix:<...>( EnumMember $a, $b ) {\n fail 'Can only do sequence for members of the same enum' \n}\n\nmulti sub infix:<…>( EnumMember $a, $b ) {\n $a ... $b\n}\n\nenum Foo does EnumMember ( XA => 17, XB => 19, XC => 2, XD => 17, XE => 1, XF => 99 );\nenum Goo does EnumMember < YA YB >;\n\nis (XC … XE), (XC, XD, XE); \ndies-ok { XA … YB }; \n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-06T08:02:28.730",
"Id": "230250",
"ParentId": "230241",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-05T22:55:04.130",
"Id": "230241",
"Score": "2",
"Tags": [
"enum",
"raku"
],
"Title": "Ranges of enum members that dwim"
}
|
230241
|
<p>Below is my code for the Fantasy Game Inventory problem from <a href="https://automatetheboringstuff.com/chapter5/" rel="noreferrer">Chapter 5 of Automate the Boring Stuff with Python</a>. Is there anything I can do to make it cleaner or more efficient?</p>
<p>The code starts out with a dictionary "inv" that contains the player's current inventory as well as a list "dragon_loot" that contains the items from the dead dragon. The goal of the code is to combine the list with the dictionary while increasing the quantity of duplicate items.</p>
<p>As a note, I am using the starting list from the previous question simply because it seems impossible to kill a dragon without possessing a weapon :)</p>
<blockquote>
<p>You are creating a fantasy video game. The data structure to model the player’s inventory will be a dictionary where the keys are string values describing the item in the inventory and the value is an integer value detailing how many of that item the player has. For example, the dictionary value {'rope': 1, 'torch': 6, 'gold coin': 42, 'dagger': 1, 'arrow': 12} means the player has 1 rope, 6 torches, 42 gold coins, and so on.</p>
<p><strong>List to Dictionary Function for Fantasy Game Inventory</strong></p>
<p>Imagine that a vanquished dragon’s loot is represented as a list of strings like this:</p>
<p>dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']</p>
<p>Write a function named addToInventory(inventory, addedItems), where the inventory parameter is a dictionary representing the player’s inventory (like in the previous project) and the addedItems parameter is a list like dragonLoot. The addToInventory() function should return a dictionary that represents the updated inventory. Note that the addedItems list can contain multiples of the same item. Your code could look something like this:</p>
</blockquote>
<pre><code>def addToInventory(inventory, addedItems):
# your code goes here
inv = {'gold coin': 42, 'rope': 1}
dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']
inv = addToInventory(inv, dragonLoot)
displayInventory(inv)
</code></pre>
<blockquote>
<p>The output of the following code is:</p>
</blockquote>
<pre class="lang-none prettyprint-override"><code>Inventory:
1 rope
6 torch
45 gold coin
2 dagger
12 arrow
1 ruby
Total number of items: 67
</code></pre>
<blockquote>
<p>Thank you in advance. I have learned a lot from the comments I received for my previous questions!</p>
</blockquote>
<pre><code>from collections import Counter
# players current inventory before killing dragon
inv = {'rope': 1, 'torch': 6, 'gold coin': 42, 'dagger': 1, 'arrow': 12}
# items from the slain dragon
dragon_loot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']
# this function prints the players inventory in a list and reports the total items
def display_inventory(inventory):
print("Inventory:")
item_total = 0
for k, v in inventory.items():
print(str(v) + " " + str(k))
item_total = item_total + int(v)
print("\nTotal number of items: " + str(item_total))
# this function adds the dragon's stuff to the players inventory
def add_to_inventory(inventory, added_items):
added_items_dict ={i:added_items.count(i) for i in added_items}
inv = Counter(inventory) + Counter(added_items_dict)
return inv
inv = add_to_inventory(inv, dragon_loot)
display_inventory(inv)
</code></pre>
|
[] |
[
{
"body": "<h1>Style</h1>\n\n<p>I suggest you check PEP0008 <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">https://www.python.org/dev/peps/pep-0008/</a> the official Python style guide for writing a more Pythonic code and Flake8 <a href=\"http://flake8.pycqa.org/en/latest/\" rel=\"nofollow noreferrer\">http://flake8.pycqa.org/en/latest/</a> for style enforcement. The following goes accordingly:</p>\n\n<ul>\n<li><p><strong>Blank lines:</strong> Surround top-level function and class definitions with two blank lines. Method definitions inside a class are surrounded by a single blank line.\nExtra blank lines may be used (sparingly) to separate groups of related functions. Blank lines may be omitted between a bunch of related one-liners (e.g. a set of dummy implementations).</p>\n\n<p>No blank lines between the function and what's above:</p>\n\n<pre><code># this function prints the players inventory in a list and reports the total items\ndef display_inventory(inventory):\n</code></pre>\n\n<p>and same goes to the other function.</p></li>\n<li><p><strong>f-strings:</strong> Since you're using Python 3.x I can tell from the print statements F-strings provide a way to embed expressions inside string literals, using a minimal syntax. It should be noted that an f-string is really an expression evaluated at run time, not a constant value. You could use f-strings for readability enhancement in the following way:</p>\n\n<p><strong>This line:</strong></p>\n\n<pre><code>print(\"\\nTotal number of items: \" + str(item_total))\n</code></pre>\n\n<p><strong>is written:</strong></p>\n\n<pre><code>print(f'\\nTotal number of items: {item_total!s}')\n</code></pre>\n\n<p><strong>as well as:</strong></p>\n\n<pre><code>print(str(v) + \" \" + str(k))\n</code></pre>\n\n<p><strong>is written:</strong></p>\n\n<pre><code>print(f'{v!s} {k!s}')\n</code></pre></li>\n<li><p><strong>Docstrings:</strong> Python documentation strings (or docstrings) provide a convenient way of associating documentation with Python modules, functions, classes, and methods. ... A docstring is simply a multi-line string, that is not assigned to anything. It is specified in source code that is used to document a specific segment of code. You should include docstrings to your functions indicating what they do and what they return.</p>\n\n<p><strong>Example:</strong></p>\n\n<pre><code>def add_to_inventory(inventory: dict, added_items: list):\n \"\"\"Update and return inventory.\"\"\"\n</code></pre>\n\n<p>And note the type hints to indicate the types of these parameters.</p></li>\n<li><strong>Indentation:</strong> your function <code>add_to_inventory</code> body is over indented (8 spaces instead of 4) and 4 spaces is the common convention in Python.</li>\n</ul>\n\n<h1>Code</h1>\n\n<ul>\n<li><p><strong>A function returns:</strong> functions are meant to return, not to print.</p>\n\n<pre><code>def display_inventory(inventory):\n print(\"Inventory:\")\n item_total = 0\n for k, v in inventory.items():\n print(str(v) + \" \" + str(k))\n item_total = item_total + int(v)\n print(\"\\nTotal number of items: \" + str(item_total))\n</code></pre>\n\n<p>And since there is no particular sophisticated printing pattern required, the display function can be replaced by <code>print()</code> statement(s).</p></li>\n<li><p><strong>Augmented assignment:</strong> Python supports augmented assignment using <code>+=</code></p>\n\n<p><code>item_total = item_total + int(v)</code> is written: <code>item_total += int(v)</code></p></li>\n<li><p><strong><code>main</code> guard:</strong> Use <code>if __name__ == '__main__':</code> at the end of your script and call your functions from there. to allow the module to be imported by other modules without running the whole script.</p></li>\n</ul>\n\n<p><strong>And the code can be a one-liner:</strong></p>\n\n<pre><code>from collections import Counter\n\n\ndef update_inventory(inventory: dict, new_items: list):\n \"\"\"Update and return inventory.\"\"\"\n return Counter(inventory) + Counter(new_items)\n\n\nif __name__ == '__main__':\n inventory = {'rope': 1, 'torch': 6, 'gold coin': 42, 'dagger': 1, 'arrow': 12}\n dragon_loot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']\n new_inventory = update_inventory(inventory, dragon_loot)\n for item, number in new_inventory.items():\n print(f'{number} {item}')\n print(f'\\nTotal number of items: {sum(new_inventory.values())}')\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-06T08:28:54.357",
"Id": "448327",
"Score": "2",
"body": "`f\"{str(var)}\"` can also be written ass f\"{var!s}\", which is shorter."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-06T14:20:19.817",
"Id": "448370",
"Score": "0",
"body": "Agreed; that needs to change. Implicit stringifying is half of the advantage of using f-strings in the first place."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-06T16:36:02.230",
"Id": "448391",
"Score": "1",
"body": "Okay, i'll change it"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-06T07:45:23.930",
"Id": "230249",
"ParentId": "230248",
"Score": "3"
}
},
{
"body": "<p>The best case would be if your inventory is always a <code>collections.Counter</code>. Then you could just use the <a href=\"https://docs.python.org/3/library/collections.html#collections.Counter.update\" rel=\"nofollow noreferrer\"><code>update</code></a> method, which takes either a dictionary-like object, or an iterable (like the constructor). This way you don't need to do <code>added_items.count(i)</code> all the time, which takes away almost all of the benefits of using <code>Counter</code> in the first place.</p>\n\n<pre><code>from collections import Counter\n\ndef print_inventory(inventory):\n \"\"\"prints the players inventory\n and reports the total number of items.\"\"\"\n print(\"Inventory:\")\n item_total = 0\n for k, v in inventory.items():\n print(f\"{v} {k}\")\n item_total += v\n print(f\"\\nTotal number of items: {item_total}\")\n\n\ndef add_to_inventory(inventory, added_items):\n \"\"\"Add all items from `added_items` to `inventory`.\n\n `inventory` is assumed to be a `collection.Counter` instance.\n \"\"\"\n inventory.update(added_items)\n\nif __name__ == \"__main__\":\n # players current inventory before killing dragon\n inv = Counter({'rope': 1, 'torch': 6, 'gold coin': 42,\n 'dagger': 1, 'arrow': 12})\n # items from the slain dragon\n dragon_loot = ['gold coin', 'dagger', 'gold coin',\n 'gold coin', 'ruby']\n add_to_inventory(inv, dragon_loot)\n # inv.update(dragon_loot) # could also just inline it...\n print_inventory(inv)\n</code></pre>\n\n<p>Of course, this strays a bit away from the specifications, but since this is mostly about learning how to program (or automate stuff), I think this is acceptable.</p>\n\n<p>Note that I also added proper <a href=\"https://www.python.org/dev/peps/pep-0257/\" rel=\"nofollow noreferrer\">docstrings</a>, added a <a href=\"http://stackoverflow.com/questions/419163/what-does-if-name-main-do\"><code>if __name__ == \"__main__\"</code> guard</a>, used consistent indentation (of 4 spaces) and <code>lower_case</code> as required by <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP8, Python's official style-guide</a>, used <a href=\"https://realpython.com/python-f-strings/\" rel=\"nofollow noreferrer\">f-strings</a> where applicable and used in-place addition for the total.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-06T10:09:06.347",
"Id": "230255",
"ParentId": "230248",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "230249",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-06T05:41:51.857",
"Id": "230248",
"Score": "5",
"Tags": [
"python",
"beginner",
"python-3.x",
"hash-map"
],
"Title": "Fantasy Game Inventory - Automate the Boring Stuff with Python"
}
|
230248
|
<p>I am beginner in OOP. And i want you to analyze my piece of code and give me some recommendations.</p>
<p>My task was :</p>
<p>RPG game give a chance to choose race of Hero : Argonian, Breton, altmer, nord. In addition to choosing a race, the user has the opportunity to choose these characteristics : sex, color skin,weight,tattoo, hair color (if it exists in the race). Write a program for display all the characteristics of the created hero.</p>
<p>I would like to hear your opinion about my code.</p>
<pre><code>import random
class Descriptor(object):
'''base dicriptor'''
def __init__(self,possibledata:list):
#list in which must be our set value
self.possible_list=possibledata
self.standarterror = ValueError(f"Your value must be in : {self.possible_list}")
def __get__(self, instance, owner):
#return value of instance
pass
def __set__(self, instance, value):
#check if value is correct
#if True -> set
pass
class Descriptor_weight():
def __get__(self, instance, owner):
return instance._Hero__weight
def __set__(self, instance, value):
if 0<value<501 :
instance._Hero__weight=value
else :
raise ValueError(f"Your value must be in : 0 .. 500")
class Descriptor_sex(Descriptor):
def __get__(self, instance, owner):
return instance._Hero__sex
def __set__(self, instance, value):
if value in self.possible_list:
instance._Hero__sex=value
else :
raise self.standarterror
class Descriptor_color_skin(Descriptor):
def __get__(self, instance, owner):
return instance._Hero__color_skin
def __set__(self, instance, value):
if value in self.possible_list:
instance._Hero__color_skin=value
else :
raise self.standarterror
class Descriptor_tatoo(Descriptor):
def __get__(self, instance, owner):
return instance._Hero__tatoo
def __set__(self, instance, value):
if value in self.possible_list:
instance._Hero__tatoo=value
else :
raise self.standarterror
class Descriptor_color_hair(Descriptor):
def __get__(self, instance, owner):
return instance._Hero__color_hair
def __set__(self, instance, value):
if value in self.possible_list:
instance._Hero__color_hair=value
else :
raise self.standarterror
class Hero():
#dict of possible parametres of all type of heroes
data = {
'sex' : ['male', 'female'],
'color_skin' : ['yellow', 'black', 'brown', 'green', 'blue', 'orange'],
'tatoo' : ['sun', 'water', 'cloud', 'snake', 'monkey', 'car', 'cat'],
'color_hair' : ['black', 'brown', 'green', 'red', 'blue', 'silver'],
}
@staticmethod
def randomchoice(parametr_name):
'''to choose random 3 parameters
return --> list of 3 possible parameters
it will be used in the inherited classes'''
random_params = []
random_3_numbers = random.sample([0, 1, 2, 3, 4, 5], 3)
for index in random_3_numbers:
random_params.append(Hero.data[parametr_name][index])
return random_params
def __init__(self,sex=None,color_skin=None,weight=None,tatoo=None,color_hear=None):
self.__sex=sex
self.__color_skin=color_skin
self.__weight=weight
self.__tatoo=tatoo
self.__color_hear=color_hear
self.__race=self.__class__.__name__
# SETTERS GETTERS
def getWeight(self):
return self.weight
def setWeight(self,value):
self.weight=value
def getSex(self):
return self.sex
def setSex(self,value):
self.sex=value
def getSkin(self):
return self.color_skin
def setSkin(self,value):
self.color_skin=value
def getTatoo(self):
return self.tatoo
def setTatoo(self,value):
self.tatoo=value
def getHair(self):
return self.color_hear
def setHair(self,value):
self.color_hear=value
def getRace(self):
return self.__race
def setRace(self,value):
self.__race=value
def __str__(self):
'''Instance presentation'''
return(f"___ Your Hero ___ \n"
f"Race --> {self.getRace()}\n"
f"Sex --> {self.getSex()}\n"
f"Skin --> {self.getSkin()}\n"
f"Weight --> {self.getWeight()}\n"
f"Tatoo --> {self.getTatoo()}\n"
f"Hair --> {self.getHair() if not None else 'Nothing'}\n"
f".....................")
#using for descriptors
weight=Descriptor_weight()
sex=Descriptor_sex(data['sex'])
color_skin=Descriptor_color_skin(data['color_skin'])
tatoo=Descriptor_tatoo(data['tatoo'])
color_hair=Descriptor_color_hair(data['color_hair'])
class Agronianin(Hero):
#personal class data possible attributes
data = {
'sex' : Hero.data['sex'],
'color_skin' : Hero.randomchoice('color_skin'),
'tatoo' : Hero.randomchoice('tatoo'),
'color_hair' : Hero.randomchoice('color_hair'),
}
class Bretinec(Hero):
data = {
'sex': Hero.data['sex'],
'color_skin': Hero.randomchoice('color_skin'),
'tatoo': Hero.randomchoice('tatoo'),
'color_hair': Hero.randomchoice('color_hair'),
}
class Altmer(Hero):
data = {
'sex': Hero.data['sex'],
'color_skin': Hero.randomchoice('color_skin'),
'tatoo': Hero.randomchoice('tatoo'),
'color_hair': Hero.randomchoice('color_hair'),
}
class Nord(Hero):#!
pass
class Danmer(Hero):#!
pass
class Game():#!
'''Our game interface'''
#our possible types
types = [Agronianin, Bretinec, Altmer]#!
def __init__(self):
self.__Hero=None
def main(self):
'''Start game func'''
#Meet player
self.Hi()
input()
#Playing
while True :
self.dataprocessing(self.menu())
print(self.get_playerHero())
input()
def get_playerHero(self):
return self.__Hero
'''def createHeroObject(self):
return self.Hero_class(self,self.Hero_sex,self.Hero_skin,self.Hero_weight,self.Hero_tatoo,self.Here_hair)
'''
def Hi(self):
print("Dear, player ! \n"
"Today you have a nice chance to create your own player !!\n"
"Press ENTER and i will show you the MENU")
def menu(self):
print("Menu :\n"
"0 - Exit()\n"
"1 - create the Hero\n")
while True:
try :
_=input("What do you want ?")
if _ not in ("0","1"):
raise ValueError("Please, choose correct answer :)")
break
except ValueError as e :
print(e.args[0])
continue
return _
def dataprocessing(self,data):
'''Handler menu input'''
if data == "0":
print("Have a nice day !")
import sys
sys.exit(1)
elif data == "1":
self.createCharacteristicsHero()
else:
raise ValueError
def createCrh(self,attrname,setObjectFunc):
'''Creates characteristics of our Hero
it is a template for every simple sch in our Hero'''
while True:
try:
for i in range(len(self.get_playerHero().data[attrname])):
print(f"{i+1} - {self.get_playerHero().data[attrname][i]}")
_= input("Your decision")
if _ in [str(i + 1) for i in range(len(self.get_playerHero().data[attrname]))]:
setObjectFunc(self.get_playerHero().data[attrname][int(_) - 1])
break
else:
raise ValueError("Please,choose correct variant :)")
continue
except ValueError as e:
print (e.args[0])
continue
def createTypeHero(self):
'''Race of hero to create hero based on Class name'''
while True:
try:
for i in range(len(self.types)):
print(f"{i+1} - {self.types[i].__name__}")
_ = input("Your decision")
if _ in [str(i + 1) for i in range(len(self.types))]:
return self.types[int(_)-1]
else:
raise ValueError("Please,choose correct variant :)")
except ValueError as e:
print (e.args[0])
continue
def handler_hair(self):
while True:
try:
_=input("1 - With hair\n"
"0 - Wihout hair\n")
if _ in ("0","1"):
if _ == '1':
return self.createCrh('color_hair',self.get_playerHero().setHair)
else:
raise ValueError("Please,choose correct variant :)")
except ValueError as e:
print (e.args[0])
continue
def handlerWeight(self):
while True:
try:
print('Weight must be in 1..500')
value=input()
self.get_playerHero().setWeight(int(value))
break
except ValueError:
print('Write correct data')
continue
def createCharacteristicsHero(self):
print('Okay ... Start ...')
print ('To begin with type of your Hero')
self.__Hero=self.createTypeHero()()
print ('Now , choose sex of your hero :')
self.createCrh('sex',self.get_playerHero().setSex)
print ('Now, choose color skin of your hero :')
self.createCrh('color_skin',self.get_playerHero().setSkin)
print ('Okay, How much killograms your hero will be weight ?')
self.handlerWeight()
print ('Your hero will be beautiful for you with hear or not ?')
self.handler_hair()
print ('And the last chr of you hero - tatoo ')
self.createCrh('tatoo',self.get_playerHero().setTatoo)
print('Great choice !!')
game=Game()
game.main()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-06T12:21:02.097",
"Id": "448359",
"Score": "2",
"body": "@dfhwze , now title is better ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-06T12:21:36.433",
"Id": "448360",
"Score": "3",
"body": "It is now, after my edit. It should state what the code is about. The specific question about improvement should be in the question, not the title."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-06T12:22:56.917",
"Id": "448361",
"Score": "2",
"body": "@dfhwze , thank you ."
}
] |
[
{
"body": "<h2>Formatting</h2>\n\n<p>A PEP8 formatter, linter or IDE will tell you (among other things) that</p>\n\n<ul>\n<li>You need blank lines between your class definitions</li>\n<li>You need spaces between your operators in statements like this: <code>0<value<501</code></li>\n<li>Class names like <code>Descriptor_sex</code> should be <code>DescriptorSex</code></li>\n<li>Variable names like <code>standarterror</code> should be <code>standard_error</code>; <code>_Hero__weight</code> should be <code>_hero_weight</code>.</li>\n</ul>\n\n<h2>Typos</h2>\n\n<p>standart = standard, tatoo = tattoo, parametr = parameter, dicriptor = descriptor, parametres = parameters.</p>\n\n<h2>Variable names</h2>\n\n<p><code>_</code> is reserved by convention for a variable you don't use - but you <em>do</em> use it here:</p>\n\n<pre><code>_=input(\"What do you want ?\")\n</code></pre>\n\n<p>so give it a meaningful name.</p>\n\n<p>Don't call your dict of all possible values <code>data</code>. Call it perhaps <code>possible_params</code>.</p>\n\n<p>Don't use double-underscores for something like this: <code>self.__weight</code> - just use one underscore. Double underscores are used in <a href=\"https://docs.python.org/3/tutorial/classes.html#private-variables\" rel=\"nofollow noreferrer\">name mangling</a>, and your application doesn't justify the use of that mechanism.</p>\n\n<h2>Abstract base class</h2>\n\n<p><code>Descriptor</code> defines a <code>__get__</code> and a <code>__set__</code>, but they're no-ops, and overridden in all child classes. That means you probably intend for <code>Descriptor</code> to be abstract, in which case those base methods should <code>raise NotImplementedError</code>.</p>\n\n<h2>Intervals</h2>\n\n<pre><code>if 0<value<501\n</code></pre>\n\n<p>does not match your description. If you want to include 0 and 500, you're better off writing</p>\n\n<pre><code>if 0 <= value <= 500\n</code></pre>\n\n<h2>Validation</h2>\n\n<p>You hold onto a <code>possible_list</code> of allowed values for your various descriptors. This list is better off as a set, whose membership tests execute more quickly. You don't need to keep duplicates or order.</p>\n\n<p>Also: you go through all of the trouble of making this descriptor class system, with an included <code>possible_data</code>, but then don't actually use it in the base class. You should factor out the membership tests from your children to the base class so that it only needs to be written once.</p>\n\n<p>By example, the base class could include something like</p>\n\n<pre><code>def __set__(self, instance, value):\n if value not in self.possible_values:\n raise self.standard_error\n instance._value = value\n</code></pre>\n\n<p>There's not really an advantage to having different names for your <code>value</code>, so you can just track it as a member in the base class. Then most <code>__set__</code> methods don't even need to be reimplemented in the children.</p>\n\n<p>This:</p>\n\n<pre><code>if _ in [str(i + 1) for i in range(len(self.types))]:\n</code></pre>\n\n<p>is doing things somewhat backwards. Instead of stringifying the expected values, you should integer-parse the user input; something like</p>\n\n<pre><code>decision = int(input('Your decision'))\n</code></pre>\n\n<p>keeping in mind that you'll need to catch a <code>ValueError</code> if you want to deal with input validity there.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-06T14:52:50.927",
"Id": "448379",
"Score": "0",
"body": "thank you for your explanation, but i have some questions. 1. I read,that if i want to hide realization i must use __ . Is it really incorrect encapsulation ? As you say , i mustn't use it at all ? 2. Can you give me small example about your second paragraph in Validation (also you go through ..) ."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-06T14:54:29.483",
"Id": "448380",
"Score": "0",
"body": "Python has no enforced idea of \"private\". Single-underscore methods are used by convention to hide the implementation (realization, as you put it). Double-underscore methods are reserved for built-ins."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-06T15:00:31.527",
"Id": "448382",
"Score": "0",
"body": "I've added an example - let me know if it needs further expansion."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-06T15:20:51.890",
"Id": "448384",
"Score": "0",
"body": "okay , but each children has own parameter _value ( weight...) , which also must be changed in each __set__ method . How can i solve this problem ? I can create class attribute in each child class : _value = ''__weight'' . But it will only work , if i will use \"eval\" func and change ''__weight'' to __weight . I hope you understand my think ."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-07T07:34:28.590",
"Id": "448477",
"Score": "3",
"body": "\"Double underscores are reserved for Python built-ins.\" <- That's not really correct. They are reserved for attributes that should not be visible to subclasses (see [9.6. Private Variables](https://docs.python.org/3/tutorial/classes.html#private-variables)). You probably mixed that up with special methods that have two leading **and** two trailing underscores which are reserved for Pythons data model (see [3.3. Special method names](https://docs.python.org/3/reference/datamodel.html#special-method-names))."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-07T17:23:41.150",
"Id": "448561",
"Score": "2",
"body": "@MSeifert right you are; edited."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-06T14:09:56.180",
"Id": "230264",
"ParentId": "230251",
"Score": "8"
}
},
{
"body": "<p>Your <code>randomchoice</code> method could be a lot easier. It also has a confusing name, since <code>random.choice</code> returns only a single value, but your method returns three. For this there is the function <code>random.sample</code>, which you already use, however not in the best way. Instead of sampling the indices and then indexing, sample the underlying list directly (this assumes you always have an indexable object there, but so does your code).</p>\n\n<pre><code>@staticmethod\ndef random_sample(parametr_name):\n '''choose random 3 parameters\n return --> list of 3 possible parameters\n it will be used in the inherited classes'''\n return random.sample(Hero.data[parametr_name], 3)\n</code></pre>\n\n<p>Note that <em>if</em> you need to sample indices, <code>random.sample(range(1, 6))</code> is more efficient (especially for large ranges).</p>\n\n<p>But I think you might as well inline it, the method does not add anything:</p>\n\n<pre><code>from random import sample\n\nclass Altmer(Hero):\n data = {\n 'sex': Hero.data['sex'],\n 'color_skin': sample(Hero.data['color_skin'], 3),\n 'tatoo': sample(Hero.data['tattoo'], 3),\n 'color_hair': sample(Hero.data['color_hair'], 3),\n }\n</code></pre>\n\n<p>Sidenote: my spellchecker tells me it is \"tattoo\", \"parameter\" and \"standard\". You might also want to consider calling it <code>skin_color</code> and <code>hair_color</code>, since that reads more naturally.</p>\n\n<hr>\n\n<p>All of your getters and setters are superfluous. They don't add anything, just use attribute access. If you <em>do</em> need to add a getter or setter later that does more than just returning/setting the attribute, you can still add it later via properties:</p>\n\n<pre><code>class A:\n \"\"\"A class with a simple attribute\"\"\"\n def __init__(self):\n self.x = 3\n\nclass B(A):\n \"\"\"The same class but with getter and setter added for x\"\"\"\n def __init__(self):\n self._x = 3\n\n @property\n def x(self):\n return self._x + 1\n\n @x.setter\n def x(self, v):\n if 0 <= v <= 100:\n self._x = v\n else:\n raise ValueError(\"Only integers 0 <= x <= 100 are valid\")\n</code></pre>\n\n<p>Both classes can be used in exactly the same way, the interface does not change, whether the underlying attribute is a real attribute or a property:</p>\n\n<pre><code>a = A()\nb = B()\n\nprint(a.x, b.x)\n# 3 4\n\na.x = 2\nb.x = 2\nprint(a.x, b.x)\n# 2, 3\n\nb.x = 101\n# ValueError: ...\n</code></pre>\n\n<hr>\n\n<p>I also don't see the reason for all of your <code>Descriptor</code> sub classes, not even for the base class itself. It seems to me you could just have it like this:</p>\n\n<pre><code>class Hero():\n #dict of possible parameters of all type of heroes\n\n data = {\n 'sex' : ['male', 'female'],\n 'color_skin' : ['yellow', 'black', 'brown', 'green', 'blue', 'orange'],\n 'tatoo' : ['sun', 'water', 'cloud', 'snake', 'monkey', 'car', 'cat'],\n 'color_hair' : ['black', 'brown', 'green', 'red', 'blue', 'silver'],\n }\n\n def __init__(self, sex=None, color_skin=None, weight=None, tattoo=None, color_hair=None):\n\n self.sex = sex\n self.color_skin = color_skin\n self.weight = weight\n self.tattoo = tattoo\n self.color_hair = color_hair\n self.race = self.__class__.__name__\n\n def __str__(self):\n '''Instance presentation'''\n return(f\"___ Your Hero ___ \\n\"\n f\"Race --> {self.race}\\n\"\n f\"Sex --> {self.sex}\\n\"\n f\"Skin --> {self.color_skin}\\n\"\n f\"Weight --> {self.weight}\\n\"\n f\"Tattoo --> {self.tattoo}\\n\"\n f\"Hair --> {self.color_hair or 'Nothing'}\\n\"\n f\".....................\")\n</code></pre>\n\n<p>Then you can perform the checking in the character creation part:</p>\n\n<pre><code>TYPES = {cls.__name__: cls for cls in (Argonian, ...)}\n# or\nTYPES = {cls.__name__: cls\n for cls in globals().values()\n if issubclass(cls, Hero)}\n\nclass InclusiveInterval:\n def __init__(self, start, end):\n self.start, self.end = start, end\n\n def __contains__(self, x):\n return self.start <= x <= self.end\n\ndef ask_user(message, choices=None, type_=None):\n while True:\n choice = input(message)\n if type_ is not None:\n try:\n choice = type_(choice)\n except ValueError:\n print(\"Please try again\")\n continue\n if choices is None or choice in choices:\n return choice\n print(\"Please try again\")\n\nclass Game:\n ...\n def create_hero(self):\n\n print('Okay ... Start ...')\n print ('To begin with type of your Hero')\n\n Race = TYPES[ask_user(\"Which race? \", TYPES)]\n data = Race.data\n sex = ask_user('Now , choose sex of your hero: ',\n data[\"sex\"])\n skin_color = ask_user('Now, choose color skin of your hero: ',\n data[\"color_skin\"])\n\n weight = ask_user('Okay, what is the weight of your hero (in kilograms)? ',\n InclusiveInterval(0, 500), type_=int)\n ...\n print('Great choice !!')\n self.__Hero = Race(sex, color_skin, weight, tattoo, color_hair)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-06T15:42:58.777",
"Id": "230270",
"ParentId": "230251",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": "230270",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-06T08:39:43.340",
"Id": "230251",
"Score": "7",
"Tags": [
"python",
"beginner",
"python-3.x",
"object-oriented"
],
"Title": "Displaying characteristics of the Hero in a console game"
}
|
230251
|
<p>I got frustrated with the jargon and created an alternative state management solution. Its up at <a href="https://github.com/smakazmi/react-soliit" rel="nofollow noreferrer">https://github.com/smakazmi/react-soliit</a>. It goes something like this</p>
<pre><code>import React from "react";
export default class StateStore<T> {
private listeners: Array<Function>;
constructor(public state: T) {
this.listeners = new Array<() => void>();
}
private fireOnSetState() {
this.listeners.forEach(l => {
try {
l();
}
catch { }
})
}
protected setState(newState: Partial<T>) {
this.state = { ...this.state, ...newState };
this.fireOnSetState();
}
subscribe(callback: () => void) {
if (this.listeners.indexOf(callback) < 0)
this.listeners.push(callback);
}
unsubscribe(callback: () => void) {
this.listeners = this.listeners.filter(l => l !== callback);
}
}
export const withStores = function (WrappedComponent: any, stores: { [index: string]: StateStore<{}> }) {
return class extends React.Component {
updateState = () => {
this.forceUpdate();
}
componentDidMount() {
Object.keys(stores).forEach(k => {
stores[k].subscribe(this.updateState);
});
}
componentWillUnmount() {
Object.keys(stores).forEach(k => {
stores[k].unsubscribe(this.updateState);
});
}
render() {
return (<WrappedComponent {...this.props} {...stores} />);
}
}
}
</code></pre>
<p>Can be used as follows</p>
<pre><code>const counterStore = new StateStore({ count: 0 });
const Counter = function({ counterStore }) {
const increment = () =>
counterStore.setState({ count: counterStore.state.count + 1 });
const decrement = () =>
counterStore.setState({ count: counterStore.state.count - 1 });
return (
<div>
<button onClick={decrement}>-</button>
<span>{counterStore.state.count}</span>
<button onClick={increment}>+</button>
</div>
);
};
const ConnectedCounter = withStores(Counter, { counterStore });
render(<ConnectedCounter />, document.getElementById("root"));
</code></pre>
<p>The sample is available at <a href="https://stackblitz.com/edit/soliit-simple-counter" rel="nofollow noreferrer">https://stackblitz.com/edit/soliit-simple-counter</a></p>
<p>Seems to work fine, at the same time seems too good to be true. So looking for reasons to why to go for Redux, MobX or even Unstated and not something as simple as this. </p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-07T06:59:48.143",
"Id": "448469",
"Score": "0",
"body": "When you use well maintained/active packages, you get a lot of extra tools. In Redux, you get the option to have powerful middlewares and good technical support. It's totally fine to make your own state management implementation, but if something goes wrong or you need to extend/add complex functionality, you're on your own."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-07T07:08:18.303",
"Id": "448474",
"Score": "0",
"body": "thanks for your comment @andrew. i realize what you're saying though. i was infact looking for technical feedback on the approach that i've used here. for e.g. does it miss any obvious use cases ? any obvious performance issues ?"
}
] |
[
{
"body": "<p>After looking at the implementation, this is not an implementation of global state management. The entire point of things like redux is so you can directly connect components to a global store. In your case, it looks like every instance of <code>StateStore</code> has its own unique data structure, which seems to imply that you are only going to use <code>StateStore</code> once.</p>\n\n<p>You can only import it at the highest level and keep passing it down in order to persist the data. This has very heavy performance implications. Read up on how React decides on whether it should scan an entire component for any changes (rerenders can severely add up) and how the reconciliation algorithms relates to it.</p>\n\n<p>Your implementation is essentially <code>this.state</code> but also handles functions. Technically the same functionality, but it's not a true global state like how the context api or redux works.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-07T17:57:16.523",
"Id": "448565",
"Score": "0",
"body": "What if I only ever create one single instance of the store, connect it to the root app component and then in any child component I can interact directly with the store instance and still get updates when the store is updated. I dont necessarily need to connect each child component to the store instance directly or to pass down the store explicitly."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-07T18:03:03.193",
"Id": "448566",
"Score": "0",
"body": "Current set of functions requires you to pass in the entire store, regardless of where you \"connect\" the component. You should create a scheme that allows you to pick and choose which props you want from your state (aka `mapStateToProps`), or you're going to have the exact same performance issues, possibly worse."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-10T06:26:59.830",
"Id": "448981",
"Score": "0",
"body": "Great advice andew, much appreciated. I've made some changes. I'd appreciate it if you give it a look and let me know what you think. Its still possible to make the entire store(s) accessible to containers but now I use proxies to track which state components depend on. Also, I acknowledge that sometimes its better to expose state selectively, so I added a mechanism for that too.\n\nThe source is at https://github.com/smakazmi/react-redeux\n\nAn example can seen at https://codesandbox.io/s/github/smakazmi/react-redeux/tree/master/examples/todos"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-07T17:42:42.193",
"Id": "230326",
"ParentId": "230253",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-06T09:30:45.583",
"Id": "230253",
"Score": "2",
"Tags": [
"react.js",
"typescript",
"redux",
"state",
"mobx"
],
"Title": "Simpler state manament alternative to Redux, MobX, Context API, etc"
}
|
230253
|
<p>I have coded a speedreading training <code>bash</code> script. My targed was to make some experience with <code>bash</code> in a funny way.</p>
<p>It essentially does the following:</p>
<ol>
<li>Prints to screen a random number consisting of a default number of digits</li>
<li>Erases that number after a default time interval</li>
<li>Waits for the user input
<ul>
<li>if the user enters a string starting with a digit (only in this case, <kbd>Enter</kbd> is required as the end-of-input key)
<ol>
<li>Checks if the answer matches the number that was shown</li>
<li>Updates the number of hits and misses which is always shown on the top right</li>
</ol></li>
<li>if the user hits <kbd>j</kbd>/<kbd>k</kbd> the time interval is reduced/increased</li>
<li>if the user hits <kbd>h</kbd>/<kbd>l</kbd> the number of digits is reduced/increased</li>
<li>if the user hits <kbd>q</kbd> the script exits (*)</li>
<li>if the user hits any other key, does nothing</li>
</ul></li>
<li>Throws the next number (i.e. it goes to step 1 in outer list)</li>
</ol>
<p>(*) This is the only "clean" way to exit the code; in this respect, the line</p>
<pre><code>while [[ "$answer${answer+xxx}" != "xxx" ]]; do # keep going if a non-null answer is provided
</code></pre>
<p>behaves just like <code>while true</code> (and the comment is therefore wrong), as <code>answer</code> is unset before <code>while</code>, and it becomes set only when the <code>[0-9]</code> case is entered, in which case it becomes and remains non-empty.</p>
<p>The script is also on <a href="https://github.com/Aster89/miscellaneous/blob/60e8b88798902d3d43fc428cd59a6cf5d87801f0/blink" rel="nofollow noreferrer">GitHub</a>.</p>
<pre><code>#!/bin/bash
# terminal based speedreading tester
# links that helped me:
# - https://superuser.com/q/835824/597763
# activate extended regex
shopt -s extglob
# fall back on defaults
BLINK_DIGITS=${BLINK_DIGITS:-5}
BLINK_INTERVAL=${BLINK_INTERVAL:-0.5}
BLINK_QUIT=${BLINK_QUIT:-q}
BLINK_INCREMENT_DIGITS=${BLINK_INCREMENT_DIGITS:-l}
BLINK_DECREMENT_DIGITS=${BLINK_DECREMENT_DIGITS:-h}
BLINK_DECREMENT_TIME=${BLINK_DECREMENT_TIME:-j}
BLINK_INCREMENT_TIME=${BLINK_INCREMENT_TIME:-k}
# initialize score
right=0
wrong=0
# define functions
generate_number() {
gen=
while (( ${#gen} < $BLINK_DIGITS )); do
gen=$gen$RANDOM
done
echo ${gen:0:$BLINK_DIGITS}
}
center_vertically() {
print_header
lines=$(tput lines)
for (( i = 0; i < $lines/2; i++ )); do
printf "\n"
done
}
center_horizontally() {
width=$1
cols=$(tput cols)
for (( i = 0; i < ($cols - ${#width})/2; i++ )); do
printf " "
done
}
print_spaces() {
eval "printf ' %.0s' {1..$1}"
}
print_header() {
# prepare left part of first two lines (I can't use here-strings/documents since
# some computation has to be donw with the length of the strings, provided I want to flush
# some text to the right)
selected_time_interval="Time interval: $BLINK_INTERVAL seconds ([$BLINK_DECREMENT_TIME] reduces, [$BLINK_INCREMENT_TIME] increases)"
string_length="String length: $BLINK_DIGITS digits ([$BLINK_DECREMENT_DIGITS] removes digit, [$BLINK_INCREMENT_DIGITS] adds digit)"
# compute scores and align them to the right
trim=$(( ${#right} - ${#wrong} ))
(( trim < 0 )) && score_plus="Score: ✓ $(print_spaces ${trim#-})$right" || score_plus="Score: ✓ $right"
(( trim > 0 )) && score_minus=" ✗ $(print_spaces ${trim#-})$wrong" || score_minus=" ✗ $wrong"
max_length=$(( ${#score_plus} > ${#score_minus} ? ${#score_plus} : ${#score_minus} ))
# fill space in between and print the two lines
cols=$(tput cols)
printf "$selected_time_interval$(print_spaces $(( $cols - ${#selected_time_interval} - $max_length )))$score_plus\n"
printf "$string_length$(print_spaces $(( $cols - ${#string_length} - $max_length )))$score_minus"
echo "[$BLINK_QUIT] quits, all other keys regenerate the number"
}
redraw_screen() {
clear
center_vertically
center_horizontally $number
}
decrement_time() {
BLINK_INTERVAL="${BLINK_INTERVAL::$((${#BLINK_INTERVAL}-1))}$((${BLINK_INTERVAL:$((${#BLINK_INTERVAL}-1))} - 1))"
(( ${BLINK_INTERVAL:$((${#BLINK_INTERVAL}-1))} == 0 )) && BLINK_INTERVAL="${BLINK_INTERVAL}9"
}
increment_time() {
(( ${BLINK_INTERVAL##0.} == 9 )) && return 1
BLINK_INTERVAL=${BLINK_INTERVAL%%[1-9]*}$((${BLINK_INTERVAL##0.*(0)} + 1))
(( ${BLINK_INTERVAL:$((${#BLINK_INTERVAL} - 1))} == 0 )) && BLINK_INTERVAL=${BLINK_INTERVAL/0.0/0.} && BLINK_INTERVAL=${BLINK_INTERVAL%%0}
}
quit() {
# clear screen and exit
clear
exit 0
}
# main loop
while [[ "$answer${answer+xxx}" != "xxx" ]]; do # keep going if a non-null answer is provided
# generate number
number=$(generate_number $BLINK_DIGITS)
# show number for short time
redraw_screen
printf $number
sleep $BLINK_INTERVAL
# erase the number (go back, overwrite with spaces, go back again)
eval "printf '\b%.0s' {1..${#number}}"
eval "printf ' %.0s' {1..${#number}}"
eval "printf '\b%.0s' {1..${#number}}"
read -rn 1 first_char
case $first_char in
$BLINK_QUIT )
quit
;;
$BLINK_DECREMENT_DIGITS )
(( BLINK_DIGITS > 1 )) && (( BLINK_DIGITS-- ))
;;
$BLINK_INCREMENT_DIGITS )
(( BLINK_DIGITS < $cols - 1 )) && (( BLINK_DIGITS++ ))
;;
$BLINK_DECREMENT_TIME )
decrement_time
;;
$BLINK_INCREMENT_TIME )
increment_time
;;
[0-9] )
redraw_screen
# erase $first_char
printf '\b%.0s'
# use $first_char as a default to have it printed again
# the leading space is to allow backspacing on the first digit
# without the all leading space being erased all together
read -i " $first_char" -e answer
if (( $answer == $number )); then
(( right++ ))
else
(( wrong++ ))
fi
;;
esac
done
(( $? == 0 )) && quit || exit
</code></pre>
|
[] |
[
{
"body": "<blockquote>\n<pre><code># fall back on defaults\nBLINK_DIGITS=${BLINK_DIGITS:-5}\nBLINK_INTERVAL=${BLINK_INTERVAL:-0.5}\nBLINK_QUIT=${BLINK_QUIT:-q}\nBLINK_INCREMENT_DIGITS=${BLINK_INCREMENT_DIGITS:-l}\nBLINK_DECREMENT_DIGITS=${BLINK_DECREMENT_DIGITS:-h}\nBLINK_DECREMENT_TIME=${BLINK_DECREMENT_TIME:-j}\nBLINK_INCREMENT_TIME=${BLINK_INCREMENT_TIME:-k}\n</code></pre>\n</blockquote>\n\n<p>This is exactly the right way to do this. Good job.</p>\n\n<hr>\n\n<blockquote>\n<pre><code># activate extended regex\nshopt -s extglob\n</code></pre>\n</blockquote>\n\n<p>Is this even needed?</p>\n\n<hr>\n\n<blockquote>\n<pre><code>generate_number() {\n gen=\n while (( ${#gen} < $BLINK_DIGITS )); do\n gen=$gen$RANDOM\n done\n echo ${gen:0:$BLINK_DIGITS}\n}\n</code></pre>\n</blockquote>\n\n<p>This is biased because the first digit of <code>RANDOM</code> will rarely be zero, and the maximum value of 32767 means you get more 1-3 than 4-9. Keep only the ones digit: it nearly eliminates the bias and avoids the need to truncate at the end.</p>\n\n<pre><code>for (( i=0; i < BLINK_DIGITS; ++i )); do \n gen+=$(( RANDOM % 10 )); \ndone\n</code></pre>\n\n<hr>\n\n<blockquote>\n<pre><code>center_vertically() {\n print_header\n lines=$(tput lines)\n for (( i = 0; i < $lines/2; i++ )); do\n printf \"\\n\"\n done\n}\n</code></pre>\n</blockquote>\n\n<p>You can use the <code>LINES</code> variable here with a <a href=\"https://stackoverflow.com/questions/5349718/how-can-i-repeat-a-character-in-bash\"><code>printf</code> idiom to repeat a character</a> (which only works with constants because <code>{1..n}</code> doesn't allow variables):</p>\n\n<pre><code>printf -vblank \"\\n%.0s\" {1..1000}\necho \"${blank:0:LINES/2}\"\n</code></pre>\n\n<hr>\n\n<blockquote>\n<pre><code>print_spaces() {\n eval \"printf ' %.0s' {1..$1}\"\n}\n</code></pre>\n</blockquote>\n\n<p><code>printf</code> can repeat spaces natively, by supplying a width to <code>%s</code>. This function can be reused by <code>center_horizontally()</code>:</p>\n\n<pre><code>print_spaces() { printf \"%${1}s\" \"\"; }\n\ncenter_horizontally() { print_spaces $(( ( COLUMNS - ${#1} ) / 2 )); }\n</code></pre>\n\n<hr>\n\n<blockquote>\n<pre><code>trim=$(( ${#right} - ${#wrong} ))\n…\nmax_length=$(( ${#score_plus} > ${#score_minus} ? ${#score_plus} : ${#score_minus} ))\n</code></pre>\n</blockquote>\n\n<p>You can assign inside expresssions: </p>\n\n<pre><code>(( trim = ${#right} - ${#wrong} ))\n(( max_length = ${#score_plus} > ${#score_minus} ? ${#score_plus} : ${#score_minus} ))\n</code></pre>\n\n<hr>\n\n<blockquote>\n<pre><code>decrement_time() {\n BLINK_INTERVAL=\"${BLINK_INTERVAL::$((${#BLINK_INTERVAL}-1))}$((${BLINK_INTERVAL:$((${#BLINK_INTERVAL}-1))} - 1))\"\n (( ${BLINK_INTERVAL:$((${#BLINK_INTERVAL}-1))} == 0 )) && BLINK_INTERVAL=\"${BLINK_INTERVAL}9\"\n}\n\nincrement_time() {\n (( ${BLINK_INTERVAL##0.} == 9 )) && return 1\n BLINK_INTERVAL=${BLINK_INTERVAL%%[1-9]*}$((${BLINK_INTERVAL##0.*(0)} + 1))\n (( ${BLINK_INTERVAL:$((${#BLINK_INTERVAL} - 1))} == 0 )) && BLINK_INTERVAL=${BLINK_INTERVAL/0.0/0.} && BLINK_INTERVAL=${BLINK_INTERVAL%%0}\n}\n</code></pre>\n</blockquote>\n\n<p>This is really ugly and it fails if the user provides an integer value for <code>BLINK_INTERVAL</code>. </p>\n\n<p>You could take a value in milliseconds (or tenths of seconds) and manipulate that; it would be pure bash but still kind of ugly. I think the best solution is to use a tool that does floating point calculations. <code>bc</code> is suitable but not installed by default on some distributions. <code>awk</code> is up to the task and universally available. </p>\n\n<p>Put the logic in a single function.</p>\n\n<pre><code>adjust_time() { \n BLINK_INTERVAL=$( awk -vb=$BLINK_INTERVAL -voffset=$1 'BEGIN { print b + offset/10 }' ) \n}\n\nincrement_time() { \n adjust_time 1\n}\n\ndecrement_time() { \n adjust_time -1\n}\n</code></pre>\n\n<hr>\n\n<blockquote>\n<pre><code>printf \"$selected_time_interval$(print_spaces $(( $cols - ${#selected_time_interval} - $max_length )))$score_plus\\n\"\nprintf \"$string_length$(print_spaces $(( $cols - ${#string_length} - $max_length )))$score_minus\"\n</code></pre>\n</blockquote>\n\n<p>Let <code>printf</code> handle the spacing for you. It's a bad habit to put variable data inside the format string; use <code>%s</code> instead:</p>\n\n<pre><code>printf \"%s%$(( COLUMNS - ${#selected_time_interval} - max_length ))s%s\\n\" $selected_time_interval \"\" $score_plus\nprintf \"%s%$(( COLUMNS - ${#string_length} - max_length ))s%s\" $string_length \"\" $score_minus\n</code></pre>\n\n<hr>\n\n<blockquote>\n<pre><code>while [[ \"$answer${answer+xxx}\" != \"xxx\" ]]\n</code></pre>\n</blockquote>\n\n<p>This is hacky. Just test the length of <code>answer</code>:</p>\n\n<pre><code>while (( ${#answer} ))\n</code></pre>\n\n<hr>\n\n<blockquote>\n<pre><code> (( BLINK_DIGITS < $cols - 1 )) && (( BLINK_DIGITS++ ))\n</code></pre>\n</blockquote>\n\n<p>Use <code>COLUMNS</code>, then it remains correct even if the user resizes the terminal during a run.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> if (( $answer == $number )); then\n (( right++ ))\n else\n (( wrong++ ))\n fi\n</code></pre>\n</blockquote>\n\n<p>This can be condensed to one expression. <code>$</code> inside <code>(( … ))</code> are not needed for simple variables that contain a number.</p>\n\n<pre><code>(( answer == number ? right++ : wrong++ ))\n</code></pre>\n\n<hr>\n\n<blockquote>\n<pre><code>(( $? == 0 )) && quit || exit\n</code></pre>\n</blockquote>\n\n<p>Expressions test for zero by default. This could be shortened to:</p>\n\n<pre><code>(( $? )) && exit || quit\n</code></pre>\n\n<p>But all <code>quit</code> does is clear the screen and exit normally. Just attach <code>clear</code> to the loop, and the <code>quit</code> function can go away.</p>\n\n<pre><code>while (( ${#answer} )); do \n …\ndone && clear\nexit\n</code></pre>\n\n<hr>\n\n<p>Finally, tell bash to exit on undefined variables, because you shouldn't have any:</p>\n\n<pre><code>set -u\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-06T18:26:34.140",
"Id": "448423",
"Score": "1",
"body": "Thank you for the thorough review! About `shopt -s extglob`, I tend to put it otherwise, should I make use of extended regexes, I would find myself scratching my head for hours, questioning my memory and the books, before discovering for the `n`th time that I've simply forgot this setting. About `RANDOM` is Benford's law the reason for what you say? Wow for `LINES`, so easy! It looks like reading good `bash` books is never enough. _You can assign inside expresssions_: in principle I know this (`(( BLINK_DIGITS-- ))`), but thank you for pointing out other places where I didn't make use of it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-06T18:40:48.373",
"Id": "448437",
"Score": "1",
"body": "_This is really ugly_: I completely agree with you, and if `awk` is really so universally available, then I will follow also this advise of yours. Yes, I definitely have to use `printf` more properly. _This is hacky_: another place where I didn't make use of what I know already. Like `LINES`, like `COLUMNS`, thank you. Wow, I didn't know `?:` was available! Last suggestion on `set -u` is illuminating!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-06T18:41:58.763",
"Id": "448439",
"Score": "1",
"body": "I will test all your suggestions and accept the answer :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-06T18:44:57.137",
"Id": "448440",
"Score": "2",
"body": "re: RANDOM, it's just that the numbers have an upper limit that is not a power of 10. Like if you generate random numbers 0-19, the number will >9 about half the time, so the digit \"1\" appears way too often. Same idea with a max of 32767: every five-digit number has a biased digit in it. It's not really Benford's because \"2\" is over-represented just as much as \"1\". Normal probability distributions (of which this is one) do not exhibit Benford's law in general, and а random value 0-99999 won't exhibit it at all."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-08T18:12:29.667",
"Id": "448715",
"Score": "0",
"body": "Have you missed the `echo $gen` in `generate_number` just to write one line less, or are you implying a non-`echo` way to return `gen`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-08T19:27:23.680",
"Id": "448720",
"Score": "1",
"body": "I'm only rewriting the loop there. You still need to `echo` the result (or have the caller reference `$gen` itself) and you still need `gen=` to initialize to empty value."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-08T21:19:07.787",
"Id": "448736",
"Score": "0",
"body": "As I use `gen+=`, `gen=` to initialize is not really needed, is it? Concerning `center_vertically`, my understanding is that you `printf` 1000 `\\n`s into `blank` (btw, I couldn't find `-v` in `man printf`...; plus, I my deduction is that the space after `-v` is optional: is this correct?), and then you only `echo` `LINES/2` of them. Why can't I see the effect of those two commands if I run them in the terminal? Besides, did you intentionally avoid using `eval` to stick `$(( LINES/2 ))` into `printf`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-09T12:51:55.597",
"Id": "448850",
"Score": "1",
"body": "`+=` appends; value persists across function calls. You need to say `local gen` to localize it to the function, or init to empty every time with `gen=`. Use `help printf` not man as printf is builtin. Pasting those two lines into terminal empties half my screen; if it doesn't work, make sure `LINES` is defined (should always be, if `TERM` is set) and that you're using the bash-builtin `printf` (no alias/function overriding it). I did intentionally avoid `eval`; using it almost always adds complexity and weird failure modes; best avoided in most cases."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-09T17:59:28.053",
"Id": "448889",
"Score": "0",
"body": "My bad on the two lines which empty half screen! I had forgotten the `\"` in `echo \"${blank:0:LINES/2}\"`, so `bash` was collapsing all the newlines. Any idea why there's no `gen=` in my script and the numbers do not accumulate? (If I run the function separately, I get a `gen` of increasing length, as you suggested in your last comment.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-09T19:19:17.770",
"Id": "448905",
"Score": "1",
"body": "Maybe you're only calling the function once? If nothing is resetting the value, I can't explain why it wouldn't continue to grow."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-10T18:17:33.200",
"Id": "449116",
"Score": "0",
"body": "Ok, if you put only `gen() { x+=\"x\"; echo $x; }` in a file and `source` it, then running `gen` will actually increase the length of `x`, wherease `echo $(gen)` will not. I think it's because the latter command runs `gen` in a subshell, thus preventing the `x` variable from being persistent."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-10T21:03:58.200",
"Id": "449144",
"Score": "0",
"body": "Oh, I had forgotten to underline that the script is made to allow backspacing on all the inserted character. But if you backspace beyond the first character the cursor jumps back to left border of the terminal. This is unwanted, but I don't know how to avoid it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-10T21:51:50.387",
"Id": "449145",
"Score": "2",
"body": "that is a quirk of your terminal emulator; mine doesn't do that. The next step for this kind of application is to use `stty raw` (so keypresses don't echo, for example) and ANSI escape sequences to position the cursor (instead of printing blanks). You can also [read the cursor position with escape sequences](https://stackoverflow.com/questions/2575037/how-to-get-the-cursor-position-in-bash), and use that to decide how it will affect the output"
}
],
"meta_data": {
"CommentCount": "13",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-06T14:11:44.893",
"Id": "230265",
"ParentId": "230256",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "230265",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-06T10:10:41.017",
"Id": "230256",
"Score": "5",
"Tags": [
"bash",
"console",
"shell",
"quiz"
],
"Title": "Bash script for speedreading training"
}
|
230256
|
<p>Now I have this very simple priority queue. <code>add</code> and <code>changePriority</code> both run in <span class="math-container">\$\mathcal{O}(n)\$</span> and <code>extractMinimum</code> in <span class="math-container">\$\Theta(1)\$</span>:</p>
<p><strong><code>net.coderodde.util.pq.PriorityQueue</code></strong>:</p>
<pre><code>package net.coderodde.util.pq;
/**
* This interface defines the API for priority queue data structures.
*
* @author Rodion "rodde" Efremov
* @version 1.6 (Oct 3, 2019)
* @param <E>
* @param <P>
* @since 1.6 (Oct 3, 2019)
*/
public interface PriorityQueue<E, P extends Comparable<? super P>> {
/**
* Attempts to add an element to this queue only if it is not yet present.
*
* @return {@code true} if no duplicates are present and, thus, the element
* is added to this priority queue. {@code false} is returned otherwise.
*/
public boolean add(E element, P priority);
/**
* Changes the priority of the element.
*
* @param element the target element.
* @param priority the new priority for the element.
* @return {@code true} if the priority of the target element changed.
* {@code false} otherwise.
*/
public boolean changePriority(E element, P priority);
/**
* Removes and returns the element with the highest element.
*
* @return the highest priority element.
* @throws {@link java.lang.IllegalStateException} if the queue is empty.
*/
public E extractMinimum();
/**
* Checks wether the parameter element is in this queue.
*
* @return {@code true} if the input parameter is in this queue,
* {@code false} otherwise.
*/
public boolean containsElement(E element);
/**
* The number of elements currently in the queue.
*/
public int size();
/**
* Checks whether this queue is empty.
*
* @return {@code true} only if this queue contains no elements.
*/
public boolean isEmpty();
/**
* Clears this queue removing all the elements from the queue.
*/
public void clear();
}
</code></pre>
<p><strong><code>net.coderodde.util.pq.impl.SimplePriorityQueue</code></strong>:</p>
<pre><code>package net.coderodde.util.pq.impl;
import java.util.ConcurrentModificationException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.NoSuchElementException;
import net.coderodde.util.pq.PriorityQueue;
/**
* This class implements a simple priority queue.The elements are ordered in a
* linked list, the head node of which contains the highest priority element,
* and the tail node contains the lowest priority element.
*
* @author Rodion "rodde" Efremov
* @version 1.6 (Oct 3, 2019)
* @param <E> the element type.
* @param <P> the priority key type.
* @since 1.6 (Oct 3, 2019)
*/
public final class SimplePriorityQueue<E, P extends Comparable<? super P>>
implements PriorityQueue<E, P>, Iterable<E> {
@Override
public Iterator<E> iterator() {
return new SimplePriorityQueueIterator();
}
/**
* This static inner class holds an element along with its priority.
*
* @param <E> the element type.
* @param <P> the priority key type.
*/
private static final class Node<E, P> {
E element;
P priority;
Node<E, P> next;
Node<E, P> prev;
Node(E element, P priority) {
this.element = element;
this.priority = priority;
}
E getElement() {
return element;
}
P getPriority() {
return priority;
}
void setPriority(P priority) {
this.priority = priority;
}
Node<E, P> getNextNode() {
return next;
}
Node<E, P> getPreviousNode() {
return prev;
}
void setNextNode(Node<E, P> next) {
this.next = next;
}
void setPreviousNode(Node<E, P> prev) {
this.prev = prev;
}
}
/**
* Maps each element to the linked list node holding it.
*/
private final Map<E, Node<E, P>> map = new HashMap<>();
private Node<E, P> headNode = null;
private Node<E, P> tailNode = null;
private int size = 0;
private int modCount = 0;
/**
* {@inheritDoc}
*/
@Override
public boolean containsElement(E element) {
return map.containsKey(element);
}
/**
* {@inheritDoc}
*/
@Override
public boolean add(E element, P priority) {
if (map.containsKey(element)) {
// Do not add the duplicates:
return false;
}
Node<E, P> newNode = new Node<>(element, priority);
if (headNode == null) {
headNode = newNode;
tailNode = newNode;
size = 1;
modCount++;
map.put(element, newNode);
return true;
}
insertNode(newNode);
map.put(element, newNode);
size++;
modCount++;
return true;
}
/**
* {@inheritDoc}
*/
@Override
public boolean changePriority(E element, P priority) {
if (!map.containsKey(element)) {
return false;
}
Node<E, P> node = map.get(element);
node.setPriority(priority);
unlinkNode(node);
insertNode(node);
return true;
}
/**
* {@inheritDoc}
*/
@Override
public E extractMinimum() {
if (size == 0) {
throw new NoSuchElementException("Extracting from an empty queue.");
}
Node<E, P> topPriorityNode = headNode;
headNode = headNode.getNextNode();
if (headNode == null) {
tailNode = null;
size = 0;
} else {
headNode.setPreviousNode(null);
size--;
}
map.remove(topPriorityNode.getElement());
modCount++;
return topPriorityNode.getElement();
}
/**
* {@inheritDoc}
*/
@Override
public int size() {
return size;
}
/**
* {@inheritDoc}
*/
@Override
public boolean isEmpty() {
return size == 0;
}
/**
* {@inheritDoc}
*/
@Override
public void clear() {
size = 0;
modCount++;
map.clear();
}
/**
* Inserts the given node to its correct location.
*/
private void insertNode(Node<E, P> node) {
Node<E, P> currentNode = headNode;
// Comparator operator <= instead of < guarantees stability:
while (currentNode != null
&& currentNode.priority.compareTo(node.getPriority()) <= 0) {
currentNode = currentNode.getNextNode();
}
if (currentNode == null) {
tailNode.setNextNode(node);
node.setPreviousNode(tailNode);
tailNode = node;
} else if (currentNode.getPreviousNode() == null) {
// The priority of the new element is smaller than the minimum
// priority throughout the queue:
headNode.setPreviousNode(node);
node.setNextNode(headNode);
headNode = node;
} else {
node.setNextNode(currentNode);
node.setPreviousNode(currentNode.getPreviousNode());
currentNode.setPreviousNode(node);
node.getPreviousNode().setNextNode(node);
}
}
/**
* Unlinks the parameter node from the linked list.
*/
private void unlinkNode(Node<E, P> node) {
if (node.getPreviousNode() != null) {
node.getPreviousNode().setNextNode(node.getNextNode());
} else {
headNode = node.getNextNode();
}
if (node.getNextNode() != null) {
node.getNextNode().setPreviousNode(node.getPreviousNode());
} else {
tailNode = node.getPreviousNode();
}
}
/**
* This inner class implements an iterator over the priority queue.
*/
private final class SimplePriorityQueueIterator implements Iterator<E> {
private Node<E, P> node = headNode;
private final int expectedModCount = SimplePriorityQueue.this.modCount;
@Override
public boolean hasNext() {
checkComodification();
return node != null;
}
@Override
public E next() {
checkComodification();
if (!hasNext()) {
throw new NoSuchElementException();
}
E returnValue = node.getElement();
node = node.getNextNode();
return returnValue;
}
private void checkComodification() {
if (expectedModCount != SimplePriorityQueue.this.modCount) {
throw new ConcurrentModificationException(
"Expected modification count: " + expectedModCount + ", " +
"actual modification count: " +
SimplePriorityQueue.this.modCount);
}
}
}
}
</code></pre>
<p><strong><code>net.coderodde.util.pq.impl.SimplePriorityQueueTest</code></strong>:</p>
<pre><code>package net.coderodde.util.pq.impl;
import java.util.Iterator;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.*;
public class SimplePriorityQueueTest {
private SimplePriorityQueue<Integer, Integer> queue;
@Before
public void setUp() {
queue = new SimplePriorityQueue<>();
}
@Test
public void testIterator() {
queue.add(1, 1);
queue.add(4, 4);
queue.add(3, 3);
queue.add(2, 2);
Iterator<Integer> iter = queue.iterator();
assertTrue(iter.hasNext());
assertEquals((Integer) 1, iter.next());
assertTrue(iter.hasNext());
assertEquals((Integer) 2, iter.next());
assertTrue(iter.hasNext());
assertEquals((Integer) 3, iter.next());
assertTrue(iter.hasNext());
assertEquals((Integer) 4, iter.next());
// Arrived to the end of the queue:
assertFalse(iter.hasNext());
}
@Test
public void testContainsElement() {
assertFalse(queue.containsElement(100));
assertFalse(queue.containsElement(90));
assertFalse(queue.containsElement(80));
queue.add(100, 100);
queue.add(80, 80);
queue.add(90, 90);
assertTrue(queue.containsElement(100));
assertTrue(queue.containsElement(90));
assertTrue(queue.containsElement(80));
assertFalse(queue.containsElement(70));
assertFalse(queue.containsElement(60));
}
@Test
public void testAdd() {
assertFalse(queue.containsElement(3));
queue.add(3, 3);
assertTrue(queue.containsElement(3));
assertFalse(queue.containsElement(2));
queue.add(2, 2);
assertTrue(queue.containsElement(2));
assertFalse(queue.containsElement(4));
queue.add(4, 4);
assertTrue(queue.containsElement(4));
}
@Test
public void testChangePriority() {
for (int i = 0; i < 10; i++) {
queue.add(i, i);
}
queue.changePriority(5, -1);
assertEquals((Integer) 5, queue.extractMinimum());
assertEquals((Integer) 0, queue.extractMinimum());
queue.changePriority(1, 100);
assertEquals((Integer) 2, queue.extractMinimum());
assertEquals((Integer) 3, queue.extractMinimum());
assertEquals((Integer) 4, queue.extractMinimum());
assertEquals((Integer) 6, queue.extractMinimum());
assertEquals((Integer) 7, queue.extractMinimum());
assertEquals((Integer) 8, queue.extractMinimum());
assertEquals((Integer) 9, queue.extractMinimum());
assertEquals((Integer) 1, queue.extractMinimum());
}
@Test
public void testExtractMinimum() {
queue.add(5, 5);
queue.add(3, 3);
queue.add(4, 4);
queue.add(7, 7);
queue.add(6, 6);
for (int i = 3; i <= 7; i++) {
assertEquals((Integer) i, queue.extractMinimum());
}
// Is the queue stable?
queue.add(2, 1);
queue.add(3, 1);
queue.add(1, 1);
assertEquals((Integer) 2, queue.extractMinimum());
assertEquals((Integer) 3, queue.extractMinimum());
assertEquals((Integer) 1, queue.extractMinimum());
}
@Test
public void testSize() {
for (int i = 0; i < 10; i++) {
assertEquals(i, queue.size());
queue.add(i, i);
assertEquals(i + 1, queue.size());
}
}
@Test
public void testIsEmpty() {
assertTrue(queue.isEmpty());
queue.add(2, 2);
assertFalse(queue.isEmpty());
queue.add(1, 1);
assertFalse(queue.isEmpty());
}
@Test
public void testClear() {
queue.clear(); // No-op.
assertTrue(queue.isEmpty());
for (int i = 0; i < 5; i++) {
queue.add(i, i);
assertFalse(queue.isEmpty());
}
queue.clear();
assertTrue(queue.isEmpty());
}
}
</code></pre>
<p><strong>Critique request</strong></p>
<p>I would like to hear comments on test coverage, coding style, maintainability and readability, to name a few. Thank you in advance.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-06T11:18:24.850",
"Id": "448349",
"Score": "0",
"body": "In terms of performance, IFAIK priority queue can be implemented in O(log(n)) for `add`, `remove`, and `getMin` (or `getMax`, depends on your queue) operations."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-06T11:28:09.433",
"Id": "448351",
"Score": "0",
"body": "@RonKlein I know: binary heap, d-ary heap, Fibonacci heap, binomial heap, Dial's heap, pairing heap. I have implemented all of those in one language or another."
}
] |
[
{
"body": "<h3>Small issue</h3>\n\n<pre><code> if (!map.containsKey(element)) {\n return false;\n }\n\n Node<E, P> node = map.get(element);\n</code></pre>\n\n<p>You can simply write <code>Node<E, P> node = map.get(element);</code> and check if <code>node</code> is null. This increases performance and atomicity.</p>\n\n<h3>Design issue</h3>\n\n<p>I think you could improve readability if you split the implementation to a Doubly-Linked-List (\"DLL\") inside the priority queue.</p>\n\n<p>This way, you could have the following code encapsulated in your DLL</p>\n\n<pre><code> // Comparator operator <= instead of < guarantees stability:\n while (currentNode != null \n && currentNode.priority.compareTo(node.getPriority()) <= 0) {\n currentNode = currentNode.getNextNode();\n }\n</code></pre>\n\n<p>You could gain a better separation of concerns. Tests could also improve this way.</p>\n\n<h3>Small implementation issue</h3>\n\n<p>As for your implementation of the DLL, perhaps you could consider using a sentinel rather than check for <code>null</code> for the head/tail operations.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-06T11:40:26.243",
"Id": "230261",
"ParentId": "230257",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "230261",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-06T10:26:19.443",
"Id": "230257",
"Score": "2",
"Tags": [
"java",
"linked-list",
"unit-testing",
"iterator",
"priority-queue"
],
"Title": "A simple priority queue in Java via linked list sorted by priority keys"
}
|
230257
|
<p>I am currently working on a <a href="https://www.navcen.uscg.gov/?pageName=AISMessages" rel="nofollow noreferrer">AIS message</a> decoder written in pure Python. It's just a little project to teach me some things about binary data, decoding, etc. Because I am only programming for about a year or so I am not quite sure, if my approaches is reasonable. The full source code be found here: <a href="https://github.com/M0r13n/pyais" rel="nofollow noreferrer">https://github.com/M0r13n/pyais</a></p>
<p>Without going too deep into the details, my question is: What is a reasonably fast way to decode binary content in pure Python?</p>
<p>Let's say I have a bit sequence with a length of 168 bits and this bit sequence contains encoded data. The data may not be a multiple of 2 and therefore won't fit into typical data structures such as bytes. </p>
<p>I tried three approaches:</p>
<p>1: Store the bin sequence as a normal string and convert each substring into an int individually:</p>
<pre><code>bit_str = '000001000101011110010111000110100110000000100000000000000001010111001111101011010110110000010101101000100010000010011001100101001111111111110110000010001000100010001110'
d = {
'type': int(bit_vector[0:6], 2),
'repeat': int(bit_vector[6:8], 2),
'mmsi': int(bit_vector[8:38], 2),
'ais_version': int(bit_vector[38:40], 2),
'imo': int(bit_vector[40:70], 2),
'callsign': ascii6(bit_vector[70:112]), # custom method of mine, ignore for now
# ...
}
</code></pre>
<p>2: Using bitstring's BitArray and slicing:</p>
<pre><code>b = BitArray(bin=bit_vector)
# access each piece of data like so
type_ = b[0:6].int
</code></pre>
<p>3: Using the bitarray module:</p>
<p>-> The Bitarray module does not have a nice way to convert individual parts into ints, so I dropped it.</p>
<p>Approach 1 (my current one) decodes #8000 messages in 1.132967184 seconds
and the second one takes nearly 3 seconds. </p>
<p>Overall I am fairly happy with my first idea, but I feel like, I could be missing something.
My main concern is readability, but the code should not be overly slow. In C I would have used structs, is the ctypes module worth a consideration? </p>
<p><strong>EDIT</strong>:
It was suggested, that I include all relevant parts of my code here. So here we go:</p>
<p>The overall flow can be summarized like this. First part is the name of the method and the second part in brackets it the new data type, after the method was called:</p>
<p><strong>Socket data(bytes) -> decode("utf-8")(string) -> decode_ascii6()(string) -> decode_msg_1()(dict)</strong></p>
<p><strong>Reading the data</strong>. </p>
<p>Data is coming from a TCP socket:</p>
<pre class="lang-py prettyprint-override"><code>def ais_stream(url="ais.exploratorium.edu", port=80):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((url, port))
while True:
# there may be multiple messages
for msg in s.recv(4096).decode("utf-8").splitlines():
yield msg
</code></pre>
<p><strong>Decoding</strong></p>
<p>Each message is then decoded and it's checksum is computed. Because AIS is using 6bit ASCII and not 8bit like normal, we need convert the payload. The checksum is just a logical XOR of all characters. Also there are different message types and each type requires it's own decoding. I simply created a list of the first 25 types and stored the corresponding function in it. Because functions are objects in python, that should not be a problem. And this is a very clean way to express my intention. The to_int and signed methods are just wrappers around Pythons normal int method, that check of empty strings, etc.</p>
<pre class="lang-py prettyprint-override"><code>def decode_ascii6(data):
"""
Decode AIS_ASCII_6 encoded data and convert it into binary.
:param data: ASI_ASCII_6 encoded data
:return: a binary string of 0's and 1's, e.g. 011100 011111 100001
"""
binary_string = ''
for c in data:
c = ord(c) - 48
if c > 40:
c -= 8
binary_string += f'{c:06b}'
return binary_string
def checksum(msg):
"""
Compute the checksum of a given message
:param msg: message
:return: hex
"""
c_sum = 0
for c in msg[1::]:
if c == '*':
break
c_sum ^= ord(c)
return c_sum
def decode(msg):
m_typ, n_sentences, sentence_num, seq_id, channel, data, chcksum = msg.split(',')
# convert normal ASCII into AIS_ASCII_6
decoded_data = decode_ascii6(data)
msg_type = int(decoded_data[0:6], 2)
if checksum(msg) != int("0x" + chcksum[2::], 16):
print(f"\x1b[31mInvalid Checksum dropping packet!\x1b[0m")
return None
if n_sentences != '1' or sentence_num != '1':
print(f"\x1b[31mSentencing is not supported yet!\x1b[0m")
return None
if 0 < msg_type < 25:
# DECODE_MSG is a list of functions
return DECODE_MSG[msg_type](decoded_data)
return None
</code></pre>
<p><strong>Actual AIS Message Decoding</strong></p>
<p>As I said, each message types is different and so needs to be treated individually. I decided to decode each message and return a dictionary containing all relevant information. Because 90% of the data is numeric, I also convert every chunk of data into an integer. Some information needs additional context. For example the NAVIGATION_STATUS, where each number has a special meaning. Therefore I initialize a Dictionary when the script is called, which serves as a lookup table. The lookup time is O(1) and the code gets very readable. See the decoding of message type 1 as an example:</p>
<pre class="lang-py prettyprint-override"><code>def decode_msg_1(bit_vector):
"""
AIS Vessel position report using SOTDMA (Self-Organizing Time Division Multiple Access)
Src: https://gpsd.gitlab.io/gpsd/AIVDM.html#_types_1_2_and_3_position_report_class_a
"""
status = to_int(bit_vector[38:42], 2)
maneuver = to_int(bit_vector[143:145], 2)
return {
'type': to_int(bit_vector[0:6], 2),
'repeat': to_int(bit_vector[6:8], 2),
'mmsi': to_int(bit_vector[8:38], 2),
'status': (status, NAVIGATION_STATUS[status]),
# ...
'lon': signed(bit_vector[61:89]) / 600000.0,
'lat': signed(bit_vector[89:116]) / 600000.0,
'course': to_int(bit_vector[116:128], 2) * 0.1,
# ...
'maneuver': (maneuver, MANEUVER_INDICATOR[maneuver]),
}
</code></pre>
<p>I would love to get some feedback and tips from you! :-)</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-06T11:27:24.193",
"Id": "448350",
"Score": "1",
"body": "Did you also have a look at the [`struct` module](https://docs.python.org/3/library/struct.html) in the standard library?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-06T11:31:40.840",
"Id": "448352",
"Score": "0",
"body": "Yes, but it does not seem to offer the possibility to extract data of arbitrary Width, e.g. 6 bits or 17 bits."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-06T11:32:43.337",
"Id": "448353",
"Score": "0",
"body": "True, but that also seems to be true of both your methods, at least of the method one."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-06T11:33:47.950",
"Id": "448354",
"Score": "0",
"body": "Or rather, there can be only one variable-length field, the last (with `b[123:]`)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-06T11:35:53.323",
"Id": "448355",
"Score": "0",
"body": "In method one I am simply slicing the string and cast it to an int. See int('111101'[0:3],2) = 3"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-06T11:39:52.907",
"Id": "448356",
"Score": "0",
"body": "Yes, and your slices are fixed, i.e. independent of the bit string."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-06T11:46:50.937",
"Id": "448357",
"Score": "0",
"body": "I may have expressed myself misleadingly. \n\nI have a sequence of bits and want to slice it into n arbitrary sized sub-sequences and then convert each subsequence into an integer. And this process I want to perform somewhat efficient. I the first case I am converting binary data into a string and then slicing that string into substrings and then converting each substring into an integer. Basically I search a pythonic equivalent of Structs in C to decode a stream of binary data."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-06T13:34:26.973",
"Id": "448363",
"Score": "0",
"body": "Keeping in mind that `bit_str` is not particularly a binary format - it's an ASCII format of `0` or `1` characters in a string - what is your _actual input format_? Is it up for you to decide? Where will the data be coming from at the very start of your program?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-06T13:50:17.457",
"Id": "448364",
"Score": "0",
"body": "Data is coming from a TCP socket and red in chunks of 4096 bytes."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-06T14:16:12.180",
"Id": "448368",
"Score": "0",
"body": "OK. Then it's important that you show enough code to review including the full \"chain of custody\" - the socket code and all code that touches the data after."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-06T15:32:53.023",
"Id": "448387",
"Score": "0",
"body": "I have everything in one file here: https://github.com/M0r13n/pyais/blob/master/pyais.py I hope it is okay to link to Github."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-06T16:43:03.287",
"Id": "448398",
"Score": "3",
"body": "Please include all relevant code here."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-07T07:53:55.553",
"Id": "448479",
"Score": "0",
"body": "I have included the most important parts of code, that touch the data."
}
] |
[
{
"body": "<h2>Avoid stringly-typed data</h2>\n\n<p>Given this sequence of operations:</p>\n\n<pre><code>Socket data(bytes) -> decode(\"utf-8\")(string) -> decode_ascii6()(string) -> decode_msg_1()(dict)\n</code></pre>\n\n<p>and based on the <a href=\"https://en.wikipedia.org/wiki/Automatic_identification_system#Message_format\" rel=\"nofollow noreferrer\">specification for AIS</a>, UTF-8 is not an appropriate decode format. ASCII should be used instead - it's a fixed-width character format, and from what I read, none of the characters in the format deviate from that.</p>\n\n<p>I discourage your approach in #1. Binary data are binary data; having any concern for performance rules out a string-based representation.</p>\n\n<h2>Generators and message boundaries</h2>\n\n<p>You should probably have a more nuanced approach to buffering. You should only <code>yield</code> after ensuring that your buffer ends on the boundary of a message, delimited by an ASCII newline byte. Another 'gotcha' is that <code>recv</code> only returns <em>up to</em> the number of bytes you specify, so you'll need to have logic to measure the returned result and deal with this.</p>\n\n<p>The sanest way to represent this is two different generator functions. The first asks for 4096 bytes, yields chunks of one line at a time, and maintains a local buffer between loop iterations of incomplete lines.</p>\n\n<p>The second generator function iterates over the result of the first generator function and does the actual unpacking into structured message objects.</p>\n\n<h2>Modularize your file</h2>\n\n<p>There's enough going on here - you have a bunch of documentation, a bunch of functions, etc. - that it's worth breaking out your file into multiple files in a module. It's still executable from the outside via <code>python -m</code>. I've made a <a href=\"https://github.com/M0r13n/pyais/pull/1\" rel=\"nofollow noreferrer\">pull request</a> doing only this.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-14T08:07:41.137",
"Id": "449569",
"Score": "0",
"body": "Thank you for you comments and improvements. I am already thinking and trying around to avoid stringly-typed data. I hope that I can get it to work soon. I don't think that there are two generators needed, because the AIS spec does not allow for a message to be longer than 4096 bytes. At least I did not find any exception. The modularization is definitely nice and will help other to gain a quicker overview!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-14T13:27:04.820",
"Id": "449620",
"Score": "1",
"body": "The problem is not that a message may be longer than 4096 bytes - the problem is that one message may be _split_ across the buffer boundary if many messages are received at once. You're using TCP, so there is no guarantee of predictable packet size."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-14T19:18:43.830",
"Id": "449674",
"Score": "0",
"body": "I see. Now that we are working with raw bytes, values can be extracted by bitwise operations like so: raw_bytes[0] & 0x3f to get the first 6 bits. That should be pretty fast, doesnt it?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-14T19:20:24.017",
"Id": "449675",
"Score": "0",
"body": "I think so :) That being said, I think your concern for performance is a little unbalanced. I ran the code against your default server and the rate of message reception is very low. You should be optimizing for correctness and simplicity first."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-14T20:28:45.580",
"Id": "449702",
"Score": "1",
"body": "Thats definitly right, but my primary concern is to learn something about working with binary data. Otherwise I would use a c++-based library such as libais. Thanks for your great support!"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-13T16:34:06.793",
"Id": "230652",
"ParentId": "230258",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "230652",
"CommentCount": "13",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-06T11:19:48.593",
"Id": "230258",
"Score": "4",
"Tags": [
"python",
"performance",
"comparative-review",
"bitwise"
],
"Title": "Decoding of binary data (AIS) from socket"
}
|
230258
|
<p>I have a piece of working code that takes some strings from Consul configuration exports, sanitizes them a little and converts them into valid json and/or hocon structures. </p>
<p>While I am iterating over a vector of <code>Nodes</code> in the <code>process</code> function, I couldn't come up with a better solution than having to <code>clone</code> them. After inspecting some related APIs and looking for possible solutions, I understand (hopefully correctly) that it's a baked-in feature of Rust that you cannot move the ownership of the 'iteratee' to the result of the iteration.</p>
<p>Probably, I have to re-write everything in order to optimize the performance, but I need to research more to understand what would be the most idiomatic way to write this in Rust.</p>
<p>In the <code>process</code> I'm cloning the <code>Vec</code>'s of <code>Node</code>'s. I want to collect them as <code>Node</code>'s, and not as <code>&Node</code>'s, and this doesn't play well with the ownership transfer.</p>
<p>I apologize for my shallow Rust knowledge in advance.</p>
<pre><code>pub struct ConsulKV {
pub Key: String,
pub Value: Option<String>
}
pub struct RawKV {
pub key: String,
pub value: String
}
struct Location {
ns: Vec<String>,
}
impl Location {
fn path(&self) -> String {
self.ns.join("/")
}
fn name(&self) -> String {
self.ns.last().get_or_insert(&String::from(".")).clone()
}
fn base(&self) -> Location {
match self.ns.first() {
None => Location { ns: vec![] },
Some(head) => Location {
ns: vec![head.clone()],
},
}
}
fn drop_base_mut(&mut self) -> &Location {
self.ns.remove(0);
self
}
}
impl PartialEq for Location {
fn eq(&self, other: &Location) -> bool {
self.ns == other.ns
}
}
pub enum Node {
KeyValue {
path: Location,
name: String,
value: String,
},
Directory {
path: Location,
nodes: Vec<Node>,
},
}
impl Node {
pub fn new(r1: Vec<RawKV>) -> ResulT<Vec<Node>> {
let raws = Node::preprocess(r1)?;
Ok(Node::process(raws))
}
fn preprocess(raw_kvs: Vec<RawKV>) -> ResulT<Vec<Node>> {
let nodes = raw_kvs.into_iter().map(|rkv| {
let path: Vec<String> = rkv.key.split("/").map(|s| s.to_string()).collect();
let name = path.last().ok_or("Can't construct a node")?;
let loc = Location { ns: path.clone() };
if !rkv.key.ends_with("/") && !rkv.value.is_empty() {
let n = Node::KeyValue {
path: loc,
name: name.clone(),
value: rkv.value.clone(),
};
Ok(n)
} else {
let dir = Node::Directory {
path: loc,
nodes: vec![],
};
Ok(dir)
}
});
nodes.collect()
}
fn process(mut nodes: Vec<Node>) -> Vec<Node> {
let grouped = nodes.iter_mut().group_by(|n| n.path().base());
grouped
.into_iter()
.map(|(key, group)| {
let (leafs, dirs): (Vec<&Node>, Vec<&Node>) = group
.into_iter()
.map(|n| n.drop_base_mut())
.partition(|n| n.path().ns.is_empty());
let lfs: Vec<&Node> = leafs
.into_iter()
.filter(|n| match n {
Node::Directory { nodes, .. } => !nodes.is_empty(),
_ => true,
})
.collect();
let mut n1: Vec<Node> = lfs.into_iter().map(move |x| x.clone()).collect();
let nodes = if dirs.is_empty() {
n1
} else {
let dir2: Vec<Node> = dirs.into_iter().map(move |x| x.clone()).collect();
let mut s = Node::process(dir2);
n1.append(&mut s);
n1
};
Node::Directory {
path: key,
nodes: nodes,
}
})
.collect::<Vec<Node>>()
}
fn drop_base_mut(&mut self) -> &Node {
match self {
Node::KeyValue { path, .. } => {
path.drop_base_mut();
self
}
Node::Directory { path, .. } => {
path.drop_base_mut();
self
}
}
}
fn path(&self) -> &Location {
match self {
Node::KeyValue { path, .. } => path,
Node::Directory { path, .. } => path,
}
}
}
</code></pre>
|
[] |
[
{
"body": "<p>You're doing multiple clone operations because of the types you've used. Due to the fact that consul's KV store is a <strong>tree</strong>, it does not really make that much sense to represent it as a set of nested <code>Vec</code>s. As I'm sure you found out, you're running into serious issues trying to figure out whether keys are inserted, what keys are inserted, and how to modify them without getting the borrow checker in a twist.</p>\n\n<p>I'd like to share with you a <a href=\"https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=be066aca1540aab0fa333e7563b75e03\" rel=\"nofollow noreferrer\"><strong>simpler implementation</strong></a>, one that sidesteps all the problems you've had entirely. Since we're dealing with a KV tree, we can and should take advantage of a <code>HashMap</code> for this - its type is absolutely ideal for what we are about to do. We're going to define two enum types, one for the keys, one for the value:</p>\n\n<pre><code>#[derive(Eq, PartialEq, Hash, Debug)]\npub enum Key {\n Leaf(String),\n Branch(String)\n}\n\n#[derive(Eq, PartialEq, Debug)]\npub enum Node {\n Leaf {\n key: String,\n value: String\n },\n Branch {\n key: String,\n children: HashMap<Key, Node>\n }\n}\n</code></pre>\n\n<p>We're going to then proceed through a little game of indirection to avoid some of the reference issues we might encounter...</p>\n\n<pre><code>impl Node {\n fn insert_key(children: &mut HashMap<Key, Node>, key: String, value: String) {\n match children.entry(Key::Leaf(key.clone())) {\n Entry::Occupied(mut state) => {\n state.insert(Node::Leaf {\n key: key,\n value: value\n });\n },\n Entry::Vacant(state) => {\n\n state.insert(Node::Leaf {\n key: key,\n value: value\n });\n }\n }\n }\n fn branch(children: &mut HashMap<Key, Node>, key: String, remainder: Vec<String>, value: String) {\n match children.entry(Key::Branch(key.clone())) {\n Entry::Occupied(mut state) => {\n // We already have a branch of that name, we just\n // forward the call and move on\n state.get_mut().add_value(remainder, value)\n },\n Entry::Vacant(state) => {\n // We need to create the node\n let mut node = Node::Branch {\n key: key,\n children: HashMap::new()\n };\n let status = node.add_value(remainder, value);\n state.insert(node);\n status\n }\n };\n }\n pub fn get(&self, test: &Key) -> Option<&Node> {\n match self {\n Node::Branch {\n key: _key,\n ref children\n } => children.get(test),\n _ => None\n }\n }\n pub fn add_value(&mut self, mut path: Vec<String>, value: String) {\n (match self {\n Node::Leaf {\n key: _key,\n value: _value\n } => None,\n Node::Branch {\n key: _key,\n ref mut children\n } => Some(children)\n }).map(|contents| {\n match path.len() {\n 0 => panic!(\"Path cannot be empty\"),\n 1 => Node::insert_key(contents, path.pop().unwrap(), value),\n _ => Node::branch(contents, path.pop().unwrap(), path, value)\n }\n });\n }\n}\n</code></pre>\n\n<p>And finally, we create a method to construct our tree:</p>\n\n<pre><code>pub fn into_tree(collection: Vec<RawKV>) -> Node {\n // Create the root namespace\n println!(\"Creating nodes\");\n let mut root_node = Node::Branch {\n key: \"/\".to_string(),\n children: HashMap::new()\n };\n\n for node in collection {\n let mut path_elements:Vec<String> = node.key.split(\"/\").map(|r| r.to_string()).collect();\n path_elements.reverse();\n root_node.add_value(path_elements, node.value);\n }\n\n root_node\n}\n</code></pre>\n\n<p>This is more efficient than your method in multiple respects:</p>\n\n<ul>\n<li>Less allocations (I am not copying nodes unless I absolutely <em>have</em> to)</li>\n<li>Less re-processing (no use of <code>group_by</code>, no <code>partition</code>, nothing but recursive tree access)</li>\n<li>Clearer code</li>\n</ul>\n\n<p>Let me know what you think :-)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-07T20:00:02.523",
"Id": "448591",
"Score": "0",
"body": "I'm really impressed with your approach and the quickness you reacted to my question. Well done and huge thanks. I'm currently trying to integrate your approach with some additions, like dropping the empty children directories. Once done, I will `cargo bench` it against my implementation. I'm super curious about the results. Once again, great approach and neat code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-07T22:35:32.123",
"Id": "448597",
"Score": "0",
"body": "I've had a play with my own solution on benchmarks; deeply-nested trees are `O(N)` worst-case, as expected (2000 keys, 256 nesting levels - this is impossible on consul BTW). Also as expected, the flatter the tree, the faster the tree-building is; 2000 keys take 3ms if deeply nested, <1ms if sparsely nested. Not bad for a first draft"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-09T09:25:47.957",
"Id": "448817",
"Score": "0",
"body": "I have written a wrapper struct in order to serialise recursively and print the tree to json: [the link to the code](https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=7755378ca773a8b3f1207b5281e65669). It was a bit easier than to write a serialiser for the Node itself. Now working on reverse functionality (making Consul config from json), and the hocon version."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-06T19:18:59.947",
"Id": "230275",
"ParentId": "230267",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "230275",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-06T14:36:22.327",
"Id": "230267",
"Score": "4",
"Tags": [
"performance",
"beginner",
"rust",
"configuration"
],
"Title": "Sanitize and build data structure from Consul configuration"
}
|
230267
|
<p>This is a programming challenge.</p>
<p>I have been given the following input:</p>
<blockquote>
<ol>
<li><span class="math-container">\$n\$</span> where n is size of sequence</li>
<li><span class="math-container">\$k\$</span> is an integer</li>
<li>a sequence <span class="math-container">\$A_0, A_1, A_2, \ldots A_{n-1}\$</span></li>
</ol>
</blockquote>
<p>I need to perform for each index from 0 to (k-1) inclusive</p>
<blockquote>
<pre><code>find a,b
where a = A[i % n] and b = A[n - (i % n) - 1]
then set A[i % n] = a XOR b
</code></pre>
</blockquote>
<p>and output the final sequence, separated by spaces</p>
<p>The inputs are within the ranges: </p>
<blockquote>
<p><span class="math-container">\$n \leq 10^4\$</span><br>
<span class="math-container">\$k \leq 10^{12}\$</span><br>
<span class="math-container">\$A_i \leq 10^7\$</span></p>
</blockquote>
<p>I have applied the following naive approach</p>
<pre><code>n,k=map(int,input().split())
arr=list(map(int,input().split())) #read input sequence and store it as list type
for i in range(k): #iterate over 0 to (k-1)
t=i%n #module of i wrt n
arr[t]=arr[t]^arr[n-(t)-1] #xor between two list elements and then set result to the ith list element
for i in arr:
print(i,end=" ") #print the final sequence
</code></pre>
<p>This code runs in 2 seconds when <span class="math-container">\$K \leq 10^6\$</span>, but it shows Time Limit exceeded for large test cases.<br>
I am looking for an alternate suggestion for the problem</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-06T18:12:06.923",
"Id": "448416",
"Score": "0",
"body": "From which site comes this problem? Are you interested in alternative implementations or a review of the code provided? Please take a look at the [help/on-topic] before answering the latter and modify your question accordingly."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-06T18:13:17.980",
"Id": "448417",
"Score": "0",
"body": "Link to problem : https://www.codechef.com/OCT19B/problems/MARM"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-06T18:14:12.543",
"Id": "448418",
"Score": "0",
"body": "I am looking for an alternative approach as i know my naive approach wouldn't work for large values of K"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-06T18:17:20.497",
"Id": "448419",
"Score": "2",
"body": "@Mast _Not looking for the review of my code_ is against the very purpose of this site: Code Review :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-06T18:28:16.043",
"Id": "448425",
"Score": "3",
"body": "For a next question, I give you this link (https://codereview.stackexchange.com/help/on-topic). I hope we can avoid ping-ponging your next question between sites :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-06T21:57:56.097",
"Id": "448449",
"Score": "0",
"body": "Why are you modulating `A[i % n]`? The modulus has no effect because `A` is of length `n`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-07T04:43:00.357",
"Id": "448465",
"Score": "0",
"body": "@Reinderien The modulo is required because the problem has the index `i` going from `0` to `k-1`, where `k` can be 100 million times larger than `n`. The OP’s solution works because it has the modulo operation. It just Time-Limit-Exceeded because it is inefficient."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-07T16:33:30.830",
"Id": "448548",
"Score": "0",
"body": "Please note that editing the question after an answer is available might invalidate that answer. This is why your edits are being rolled back. You are free to post a self-answer or a follow-up question with updated code instead."
}
] |
[
{
"body": "<p>Now that that pesky \"<em>Not looking for the review of my code</em>\" is gone...</p>\n\n<h2>Step 1: White space</h2>\n\n<p>Follow the <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"noreferrer\">PEP 8</a> guidelines, specifically (but not limited to) put a space around operators and after commas:</p>\n\n<pre><code>n, k = map(int, input().split()) \narr = list(map(int, input().split())) # read input sequence and store it as list type\nfor i in range(k): # iterate over 0 to (k-1)\n t = i % n # module of i wrt n\n arr[t] = arr[t] ^ arr[n - (t) - 1] # xor between two list elements and then set result to the ith list element \nfor i in arr:\n print(i, end=\" \") # print the final sequence\n</code></pre>\n\n<p>Much easier to read.</p>\n\n<h2>Step 2: Avoid multiple lookups</h2>\n\n<p>Python is an interpreted language, and the meaning of a line of code -- or even a fragment of code -- can change by the time the interpreter returns to execute the code as second time. This means the interpreter cannot truly compile the code; unless something is a well defined short-circuiting operation, every operation must be executed.</p>\n\n<p>Consider:</p>\n\n<pre><code>arr[t] = arr[t] ^ arr[n - (t) - 1]\n</code></pre>\n\n<p>The interpreter must compute the address of <code>arr[t]</code> twice; once to fetch the value, and a second time to store the new value, because some side-effect which occurs during the execution of <code>arr[n - (t) - 1]</code> may change the meaning of <code>arr[t]</code>. In your case, <code>arr</code> is a <code>list</code>, and <code>n</code> and <code>t</code> are simple integers, but with user-defined types, anything can happen. As such, the Python interpreter can never make the following optimization:</p>\n\n<pre><code>arr[t] ^= arr[n - (t) - 1]\n</code></pre>\n\n<p>It is a tiny speed-up, but considering the code may execute <span class=\"math-container\">\\$10^{12}\\$</span> times, it can add up.</p>\n\n<h2>Step 3: Avoid calculations</h2>\n\n<p>Speaking of avoiding work: because we know the length of the array is fixed, <code>arr[n - 1]</code> is the same as <code>arr[-1]</code>. So we can further speed up the line of code as follows:</p>\n\n<pre><code>arr[t] ^= arr[-1 - t]\n</code></pre>\n\n<p>Instead of two subtractions, we now have only one. Yes, Python has to index from the back of the array, which internally is going to involve a subtraction, <strong>BUT</strong> that will be an optimized, C-coded subtraction operation on <code>ssize_t</code> values, instead of subtraction on variable byte length integers, which must be allocated and deallocated from the heap.</p>\n\n<h2>Step 4: Printing space-separated lists</h2>\n\n<p>The following is slow:</p>\n\n<pre><code>for i in arr:\n print(i, end=\" \")\n</code></pre>\n\n<p>This is faster:</p>\n\n<pre><code>print(*arr)\n</code></pre>\n\n<p>And for long lists, this may be fastest:</p>\n\n<pre><code>print(\" \".join(map(str, arr)))\n</code></pre>\n\n<p>For a detail discussion, including timing charts, see <a href=\"https://codereview.stackexchange.com/questions/226970/printing-a-list-as-a-b-c-using-python/226976#226976\">my answer</a> and <a href=\"https://codereview.stackexchange.com/a/226974/100620\">this answer</a> on another question.</p>\n\n<h2>Step 5: The Algorithm</h2>\n\n<p>Consider the list <code>[A, B, C, D, E]</code>.</p>\n\n<p>After applying a single pass of the operation on it (ie, <code>k = n</code>), you'll get:</p>\n\n<pre><code>[A^E, B^D, C^C, D^(B^D), E^(A^E)]\n</code></pre>\n\n<p>which simplifies to:</p>\n\n<pre><code>[A^E, B^D, 0, B, A]\n</code></pre>\n\n<p>If we apply a second pass (ie, <code>k = 2*n</code>), you'll get:</p>\n\n<pre><code>[(A^E)^A, (B^D)^B, 0^0, B^((B^D)^B), A^((A^E)^A)]\n</code></pre>\n\n<p>which simplifies to:</p>\n\n<pre><code>[E, D, 0, B^D, A^E]\n</code></pre>\n\n<p>A third pass, (ie, <code>k = 3*n</code>) gives:</p>\n\n<pre><code>[E^(A^E), D^(B^D), 0^0, (B^D)^(D^(B^D)), (A^E)^(E^(A^E))]\n</code></pre>\n\n<p>or:</p>\n\n<pre><code>[A, B, 0, D, E]\n</code></pre>\n\n<p>Now <code>k</code> does not need to be an exact multiple of <code>n</code>, so you'll have to figure out what to do in the general cases, but you should be able to use the above observation to eliminate a lot of unnecessary calculations.</p>\n\n<p>Implementation left to student.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-06T23:23:52.557",
"Id": "448451",
"Score": "0",
"body": "One of the potential offenders is also the mod operation. It might (or might not) be faster to use an increment with an if after that."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-07T14:16:19.233",
"Id": "448523",
"Score": "0",
"body": "i have updated my implementation using the above algorithm getting right answer on most of the self-made cases but looks like one of case is not working properly. so Wrong Answer error"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-07T14:27:31.237",
"Id": "448531",
"Score": "0",
"body": "I have rolled back your most recent edit. You may not edit your question to incorporate suggestions made in answers. See [what should I do when someone answers my question](https://codereview.stackexchange.com/help/someone-answers) in the help center."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-07T14:49:10.833",
"Id": "448537",
"Score": "0",
"body": "sorry for the edit in question. I have posted my updated approach as a self -answer"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-06T19:49:30.563",
"Id": "230277",
"ParentId": "230272",
"Score": "6"
}
},
{
"body": "<p>Any solution which does something <span class=\"math-container\">\\$k\\$</span> times will be hopelessly slow. We have to make use of the structure of the problem here. Suppose <span class=\"math-container\">\\$i<\\lfloor n/2\\rfloor\\$</span> and write <span class=\"math-container\">\\$ a = A_i \\$</span> and <span class=\"math-container\">\\$b= A_{n-i}\\$</span>. Then each time through the list we execute <span class=\"math-container\">\\$ a \\leftarrow a\\wedge b \\$</span> and then <span class=\"math-container\">\\$b\\leftarrow a\\wedge b\\$</span>. Lets record the values of <span class=\"math-container\">\\$a \\$</span> and <span class=\"math-container\">\\$b\\$</span> on each iteration of the loop, starting with values <span class=\"math-container\">\\$x\\$</span> and <span class=\"math-container\">\\$ y\\$</span> for <span class=\"math-container\">\\$a\\$</span> and <span class=\"math-container\">\\$ b\\$</span>, respectively:</p>\n\n<ol>\n<li>First <span class=\"math-container\">\\$a \\leftarrow x\\wedge y\\$</span>, then <span class=\"math-container\">\\$b \\leftarrow (x\\wedge y)\\wedge y = x\\$</span></li>\n<li>First <span class=\"math-container\">\\$a \\leftarrow (x\\wedge y) \\wedge x = y\\$</span>, then <span class=\"math-container\">\\$b\\leftarrow y\\wedge x\\$</span></li>\n<li>First <span class=\"math-container\">\\$a \\leftarrow y \\wedge (y\\wedge x) = x\\$</span>, then <span class=\"math-container\">\\$b\\leftarrow x \\wedge (y\\wedge x) = y\\$</span></li>\n</ol>\n\n<p>Notice that the effect of three such iterations is to do nothing at all. Therefore we can subtract any multiple of <span class=\"math-container\">\\$ 3n\\$</span> from <span class=\"math-container\">\\$k\\$</span> and not change the result. If you reduce <span class=\"math-container\">\\$k\\$</span> mod <span class=\"math-container\">\\$3 n\\$</span> before executing your original code, you should be good. (Actually we have to be a little careful to handle the case of odd <span class=\"math-container\">\\$n\\$</span>, because the middle element has to be handled specially. I leave this as an exercise).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-07T14:19:51.600",
"Id": "448527",
"Score": "0",
"body": "updated my implementation as per the algorithm suggested but still getting wrong answer on submission. It works perfectly on my self made test cases though"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-07T02:46:05.313",
"Id": "230284",
"ParentId": "230272",
"Score": "4"
}
},
{
"body": "<p>**</p>\n\n<blockquote>\n <p>Re:Updated implementation approach for the problem</p>\n</blockquote>\n\n<p>**</p>\n\n<p>After combining algorithm suggested my </p>\n\n<blockquote>\n <p>@AJNeufeld and @vujazzman</p>\n</blockquote>\n\n<p>Sequence remains same if loop is run upto any multiple of <code>(N*3)</code> </p>\n\n<p>so we can save the overhead of running for all values of <code>k</code> </p>\n\n<p>Rather find the closest multiple of <code>(n*3) to K</code> and then <code>run loop for remaining value from the found multiple to k</code></p>\n\n<p>Note:- Odd number <code>n</code> case to be handled separately in advance by <code>set A[n//2] = 0</code></p>\n\n<p>so i have came up with the following implementation:</p>\n\n<pre><code>for _ in range(int(input())):\n n,k=map(int,input().split())\n arr=list(map(int,input().split()))\n if n % 2 and k > n//2 : #odd n case\n arr[ n//2 ] = 0\n rem= k % ( 3*n )\n closest_multiple_3n = ( k-rem )\n for i in range( closest_multiple_3n,k ):\n t=i % n\n arr[t] ^= arr[-1-t]\n print(*arr)\n</code></pre>\n\n<p>i have created some self made test cases like :-</p>\n\n<pre><code>t=1\nn=11 k=9999999998\nA[] = 20 7 27 36 49 50 67 72 81 92 99\n\noutput:- 20 7 27 36 49 0 67 72 81 92 119\n\nnote :- closest_multiple_3n = 9999999966\n rem = 32\n (20^92=119)\n</code></pre>\n\n<p>It works perfectly now</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-07T16:36:25.033",
"Id": "448549",
"Score": "2",
"body": "Code review is not intended to be used for collaborative coding to get things working (faster). While this post provides a (hopefully) improved code base, it's not a code review. I am converting it to a wiki answer (instead of deleting it). Please consider analyzing the actual performance of the code, and seeing if there is a different approach you can take. If it were me, I would benchmark your original code, then this code, and then possibly ask a new question if this revised code is faster, but not fast enough."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-07T16:49:09.777",
"Id": "448558",
"Score": "0",
"body": "okay i have updated my answer and the code in it works well !!"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-07T14:48:27.123",
"Id": "230314",
"ParentId": "230272",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "230277",
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-06T17:33:04.787",
"Id": "230272",
"Score": "2",
"Tags": [
"python",
"programming-challenge",
"time-limit-exceeded"
],
"Title": "Perform a predetermined set of operations on a large sequence"
}
|
230272
|
<p>I'm learning Rust.</p>
<p>I find it sometimes confusing when compared to other programming languages, especially when dealing with strings and slices.</p>
<p>Her's an implementation of the 99 beer song that I've written, but the code feels clunky and I think it's bad.</p>
<p>How would you have written it, if it was a production code of a real-world software? Any way to improve performance, readability and a more reasonable way to deal with strings in Rust?</p>
<pre><code>const BOTTLE: &str = "bottle";
const S: &str = "s";
const OF_BEER: &str = "of beer";
const N_UP: &str = "N";
const N_DOWN: &str = "n";
const O_MORE: &str = "o more";
const ON_THE_WALL: &str = "on the wall";
const SPACE: &str = " ";
const COMMA: &str = ",";
const PERIOD: &str = ".";
const NL: &str = "\n";
const TAKE: &str = "Take";
const IT: &str = "it";
const ONE: &str = "one";
const DOWN_AND_PASS: &str = "down and pass it around";
const GO_STORE: &str = "Go to the store and buy some more";
const NINE_NINE: &str = "99";
pub fn verse(n: i32) -> String {
let mut phrase: String;
let bottles = &format!("{}{}", BOTTLE, S)[..];
let bottles_of_beer = &format!(
"{}{}{}",if n == 1 { BOTTLE } else { bottles }, SPACE, OF_BEER
);
let n_str = &format!("{}", n)[..];
if n < 1 {
phrase = format!("{}{}{}{}", N_UP, O_MORE, SPACE, bottles_of_beer);
} else {
phrase = format!("{}{}{}", n_str, SPACE, bottles_of_beer);
}
phrase = phrase + SPACE + ON_THE_WALL + COMMA + SPACE;
if n < 1 {
phrase = phrase + N_DOWN + O_MORE;
} else {
phrase = phrase + n_str;
}
phrase = phrase + SPACE + bottles_of_beer + PERIOD + NL;
if n < 1 {
phrase = phrase + GO_STORE;
} else {
phrase = phrase + TAKE + SPACE + if n == 1 { IT } else { ONE } + SPACE + DOWN_AND_PASS
}
phrase = phrase + COMMA + SPACE;
if n < 1 {
phrase = phrase + NINE_NINE + SPACE + bottles;
} else {
let n = n - 1;
if n < 1 {
phrase = phrase + N_DOWN + O_MORE + SPACE + bottles;
} else {
phrase = phrase + &format!("{}", n)[..] + SPACE + if n == 1 { BOTTLE } else { bottles };
}
}
phrase = phrase + SPACE + OF_BEER + SPACE + ON_THE_WALL + PERIOD + NL;
return phrase;
}
pub fn sing(start: i32, end: i32) -> String {
let mut s = String::new();
let mut x = start;
while x >= end {
if x < start {
s = s + NL;
}
s = s + &verse(x)[..];
x -= 1;
}
return s
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-14T05:40:05.097",
"Id": "449556",
"Score": "1",
"body": "Why so many string constants? Your code is awkward primarily because you use string constants instead of just using strings in your code. Is there a reason you are doing that?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-04T00:58:15.430",
"Id": "452266",
"Score": "0",
"body": "[Your devotion to the elimination of repetition put me in mind of this tale.](https://users.rust-lang.org/t/rust-koans/2408/4) The song is simple; your code is complex."
}
] |
[
{
"body": "<p>Being myself new to rust, take the following with a grain of salt. I would welcome further edits.</p>\n\n<p>I think, generally, that there are two things your code is trying to do.\nOn one hand, it's about string tokens and concatenation.<br>\nOn the other, there's the solving the 99 bottles problem.</p>\n\n<h1>99 Bottles</h1>\n\n<p>For this problem, your approach seems complex and results in rather gauche\ncode. What makes it so, is that it's hard to understand at first glance what\n<code>phrase</code> is at any point.<br>\nAdding comments would be a good thing.<br>\nMyself, I would forego the whole tokenisation part, and solve it in a more\nconcise way.</p>\n\n<p>There are only a handful of sentences in the song, which need slight variations.\nI'd like to use something like Python's raw strings:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>SOLO = r\"{QTY} bottles of beer on the wall, {QTY} bottles of beer.\"\nSOLOT.format(QTY=count)\n</code></pre>\n\n<p>In rust, I managed to get this behaviour by using <code>std::String::replace</code>:</p>\n\n<pre class=\"lang-rust prettyprint-override\"><code>const SOLO: &str = \"{QTY} bottles of beer on the wall, {QTY} bottles of beer.\"\nlet mut solo: String = SOLO.to_string().replace(\"{QTY}\", &count.to_string());\n</code></pre>\n\n<p>Once can likewise replace <code>bottles</code> for its singular form, <code>one</code> for <code>it</code>. </p>\n\n<p>Other details to clarify are:\n1. are negative bottles allowed?\n2. in one place, we're talking of phrase, in another of verse, and returned are\na bunch of sentences. Which nomenclature is correct? A single term ought to be used.\n3. We're only dealing with beer, perhaps <code>bottles_of_beer</code> could become <code>bottles</code>?</p>\n\n<p>We then end up with something like so:</p>\n\n<pre class=\"lang-rust prettyprint-override\"><code>const SOLO: &str = \"{QTY} bottles on the wall. \";\nconst CHORUS: &str = \"Take one down and pass it around, {QTY} bottles of beer on the wall.\\n\";\nconst BOTTLE: &str = \"bottle\"; // for substitution when 1 bottle left.\nconst NONE: &str = \"\\\nNo more bottles of beer on the wall, no more bottles of beer.\\n\\\nGo to the store and buy some more, {QTY} bottles of beer on the wall.\\n\\\n\";\n\npub fn get_song(start: u32, stop: u32) -> String {\n let mut song: String = String::new();\n\n for x in (start..stop+1).rev() {\n if x == 0 {\n let no_beer: String = NONE.to_string().replace(\"{QTY}\", &start.to_string());\n song = song + &no_beer;\n break;\n }\n let mut solo: String = SOLO.to_string().replace(\"{QTY}\", &x.to_string());\n let mut chorus: String = CHORUS.to_string().replace(\"{QTY}\", &x.to_string());\n if x == 1 {\n solo = solo.replace(\"bottles\", BOTTLE);\n chorus = chorus.replace(\"bottles\", BOTTLE);\n chorus = chorus.replace(\"one\", \"it\");\n }\n song = song + &solo + &chorus;\n }\n return song;\n}\n\n\nfn main() {\n println!(\"{}\", get_song(10, 0)); \n}\n</code></pre>\n\n<p><em>note that I am not sure this is a correct way to do such constant\nstrings.</em><br>\nI think <code>let mut song: String = String::new();</code> is the preferred style,\nas <a href=\"https://doc.rust-lang.org/stable/book/ch08-02-strings.html#creating-a-new-string\" rel=\"nofollow noreferrer\">seen in the rust book</a>, over\n<code>let mut phrase: String;</code></p>\n\n<p>The <code>while</code> loop can be replaced by a <code>for</code> loop. This is actually the <a href=\"https://doc.rust-lang.org/1.1.0/book/for-loops.html\" rel=\"nofollow noreferrer\">textbook example</a>:</p>\n\n<pre class=\"lang-rust prettyprint-override\"><code>for x in (stop..start+1).rev() {\n ...\n}\n</code></pre>\n\n<p>There's the <code>+1</code> increment to include the starting value, then the iterator is reversed to go from high to low values.</p>\n\n<h1>String Tokens and Concatenation</h1>\n\n<p>To stay on the string concatenation path, I suggest commenting what each path does.\nThere are several <code>if n < 1</code>, which could be put together. Within that, <code>n</code>\nis redefined and subtracted, leading to an nested <code>if n < 1</code> test.</p>\n\n<p>We can observe that there are two types of operations: building different types of sentences,\nand checking whether we're at the end of the song (<code>n < 1</code>).</p>\n\n<p>Let's agree to not return a <code>phrase</code>, but a <code>paragraph</code>:</p>\n\n<pre class=\"lang-rust prettyprint-override\"><code>let mut paragraph: String = String::new();\n\n// Build qty of bottles on the wall sentence\nif n < 1 {\n ...\n paragraph = format!(...);\n} else { ... }\n\n// Build qty of bottles left on the wall sentence\nif n < 1 {\n paragraph = format!(\"{} {}\", paragraph, ...);\n} else { ... }\n</code></pre>\n\n<p>And so on.</p>\n\n<p>Now I'm thinking, what's actually done here, is not checking a condition, but\nrather <code>match</code>ing a parameter, so <code>if-else</code>s could become:</p>\n\n<pre class=\"lang-rust prettyprint-override\"><code>// Build qty of bottles on the wall sentence\nmatch n {\n 0 => paragraph = format!(\"{}{}{}{}\", N_UP, O_MORE, SPACE, bottles),\n _ => paragraph = format!(\"{}{}{}\", n_str, SPACE, bottles), \n}\n</code></pre>\n\n<p>By using <code>match</code> extensively, we also can remove the nested <code>if-else</code>:</p>\n\n<pre class=\"lang-rust prettyprint-override\"><code> // Build closing \n let phrase = match n {\n 0 => format!(\"{}{}{}\", NINE_NINE, SPACE, bottles),\n 1 => format!(\"{}{}{}{}\", N_DOWN, O_MORE, SPACE, bottles),\n _ => format!(\"{}{}{}\", qty, SPACE, bottles),\n };\n</code></pre>\n\n<p>Finally, we get to such a result:</p>\n\n<pre class=\"lang-rust prettyprint-override\"><code>const BOTTLE: &str = \"bottle\";\nconst BOTTLES: &str = \"bottles\";\nconst OF_BEER: &str = \"of beer\";\nconst UPPERCASE_N: &str = \"N\";\nconst LOWERCASE_N: &str = \"n\";\nconst O_MORE: &str = \"o more\";\nconst ON_THE_WALL: &str = \"on the wall\";\nconst SPACE: &str = \" \";\nconst COMMA: &str = \",\";\nconst PERIOD: &str = \".\";\nconst NL: &str = \"\\n\";\nconst TAKE: &str = \"Take\";\nconst IT: &str = \"it\";\nconst ONE: &str = \"one\";\nconst DOWN_AND_PASS: &str = \"down and pass it around\";\nconst GO_STORE: &str = \"Go to the store and buy some more\";\nconst NINE_NINE: &str = \"99\";\n\npub fn verse(n: u32) -> String {\n let mut paragraph: String = String::new();\n\n // Is `bottle` plural in this paragraph?\n let bottles: String = match n {\n 1 => BOTTLE.to_string(),\n _ => BOTTLES.to_string(),\n };\n\n // Create first half of first verse.\n let phrase: String = match n {\n 0 => UPPERCASE_N.to_owned() + O_MORE + SPACE + &bottles,\n _ => n.to_string() + SPACE + &bottles,\n };\n paragraph = paragraph + &phrase;\n paragraph = paragraph + SPACE + ON_THE_WALL + COMMA + SPACE;\n\n // Create second half of first verse.\n let phrase: String = match n {\n 0 => LOWERCASE_N.to_owned() + O_MORE,\n _ => n.to_string(),\n };\n paragraph = paragraph + &phrase;\n paragraph = paragraph + SPACE + &bottles + PERIOD + NL;\n\n // Create first half of second verse.\n let phrase: String = match n {\n 0 => GO_STORE.to_string(),\n 1 => TAKE.to_owned() + SPACE + IT + SPACE + DOWN_AND_PASS,\n _ => TAKE.to_owned() + SPACE + ONE + SPACE + DOWN_AND_PASS,\n };\n paragraph = paragraph + &phrase;\n // Add punctuation\n paragraph = paragraph + COMMA + SPACE;\n\n // Create second half of second verse.\n let phrase = match n {\n 0 => NINE_NINE.to_owned() + SPACE + &bottles,\n 1 => LOWERCASE_N.to_owned() + O_MORE + SPACE + BOTTLES,\n _ => n.to_string() + SPACE + &bottles,\n };\n paragraph = paragraph + &phrase;\n\n // Finish second verse\n paragraph = paragraph + SPACE + OF_BEER + SPACE + ON_THE_WALL + PERIOD + NL;\n\n return paragraph;\n}\n\nfn main() {\n let start: u32 = 10;\n let stop: u32 = 0;\n let mut song: String = String::new();\n for x in (stop..start+1).rev() {\n song = song + &verse(x);\n }\n println!(\"{}\", song);\n}\n</code></pre>\n\n<p>This is still not too clear code to me, and I'd rather work with the\nfirst variant. </p>\n\n<p>On a final note, there were places were you use <code>n_str</code> or <code>format!(\"{}\", n)</code>, be mindful of this types of errors.\nLikewise, typically <code>start/stop</code> or <code>begin/end</code> are used, but try not to mix them up.<br>\nLastly, I had a lot of trouble distinguishing between <code>O_DOWN</code> <code>N_DOWN</code>, <code>N_UP</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-13T16:24:36.723",
"Id": "449500",
"Score": "0",
"body": "About the tokens to be replaced, there's also the pluralization of words (ie. when quantity is 1 ore more than 1) also when the bottles are 0 the phrase will be very different. (negative are not allowed)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-13T16:26:43.323",
"Id": "449502",
"Score": "0",
"body": "Any alternative about using `format!(\"{}{}{}{}{}{}{}{}{}{}{}{}{}\")....` for a cleaner string concatenation?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-13T16:27:55.353",
"Id": "449503",
"Score": "0",
"body": "`s = s + &s2` should concatenate without using format, doesn't it?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-14T08:17:41.163",
"Id": "449571",
"Score": "0",
"body": "Indeed, thanks for the pointer, I've updated the answer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-15T05:28:40.410",
"Id": "449730",
"Score": "0",
"body": "FYI, rust's format string support named parameters like python's format function. See https://doc.rust-lang.org/std/macro.format.html"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-11T20:07:57.743",
"Id": "230566",
"ParentId": "230274",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-06T18:42:19.703",
"Id": "230274",
"Score": "5",
"Tags": [
"beginner",
"strings",
"rust",
"99-bottles-of-beer"
],
"Title": "99 beers song in Rust"
}
|
230274
|
<p>How can I improve this code? Is it somehow possible to remove <code>fields</code> from HTML and pass all necessary data through <code>FormGroup</code>?</p>
<p><strong>app.components.ts</strong></p>
<pre><code>import { Component } from '@angular/core';
import { FormGroup, FormBuilder, FormControl } from '@angular/forms';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
myForm: FormGroup;
fields = [
{ label: "Drill Bit Type", name: "drillBitType", options: ["Masonry", "SDS", "Universal"], type: "mat-input" },
{ label: "Drill Bit SharpAngel", name: "drillBitSharpAngel", options: ["118", "120", "135"], type: "mat-select" },
{ label: "Drill Bit Sharp Direction", name: "drillBitSharpDirection", options: ["Left", "Right"], type: "mat-select" }];
constructor(private formBuilder: FormBuilder) {
let dictionary: { [key: string]: FormControl; } = {};
this.fields.forEach(element => {
dictionary[element.name] = new FormControl(element.label);
});
this.myForm = new FormGroup(dictionary);
}
Submit() {
this.fields.forEach(element => {
console.log(this.myForm.value[element.name]);
});
}
}
</code></pre>
<p><strong>app.components.html</strong></p>
<pre class="lang-html prettyprint-override"><code><br />
<form [formGroup]="myForm">
<ng-container *ngFor="let field of fields">
<br />
<mat-form-field class="example-full-width" *ngIf="field.type=='mat-input'">
<input matInput formControlName="{{field.name}}">
</mat-form-field>
<mat-form-field *ngIf="field.type=='mat-select'">
<mat-label>{{field.label}}</mat-label>
<mat-select formControlName="{{field.name}}">
<mat-option *ngFor="let option of field.options" [value]="option">
{{option}}
</mat-option>
</mat-select>
</mat-form-field>
</ng-container>
<br />
<button mat-button (click)="Submit()" type="submit">Submit!</button>
</form>
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-06T20:07:14.583",
"Id": "230278",
"Score": "1",
"Tags": [
"javascript",
"html",
"angular-2+"
],
"Title": "Pass all data through FormGroup"
}
|
230278
|
<p>Below is a peak/valley detection algorithm I've designed. The basic premises for this function is that we split our data into chunks, do linear regressions on these chunks, detrend the data based on the line of best fit, points above a certain standard deviation are noted. Chunks are determined with a specified amount of overlap. For example if we set the overlap to be 0.5, chunk one will be indexes 0-100, chunk 2 will be 50-150, and so on.</p>
<p>Because of the ability for overlapping chunks, the same index may be noted in multiple chunks. After this we only look at the indexes that have a counts past the threshold. For example, a threshold of 1 will mean that all indexes gathered are valid. For a count of 2, an index needs to be noted in two separate chunks for it to be valid, etc.</p>
<p>Lastly, we iterate through our data and index, and only carry over the most extreme point from a group of similar consecutive events. For example if there are 3 peaks in a row before a valley is noted. Only the highest peak from this set of 3 will be carried through.</p>
<p>Note: A safe thing to do with this data is to clip the start of the data by window_size, and the end of the data by window_size * 2. This is to ensure the integrity of the data, i.e. that peaks and valleys exist that weren't detected due to lack of context of availability in multiple chunk overlaps.</p>
<p>Now that I've explained how this algorithm works, I am looking to hear some suggestions on optimization. I want this to run faster. Any ideas?</p>
<pre><code>def get_peak_valley(threshold, window_size, overlap, req_angles):
# validate params
window_size = int(round(window_size))
req_angles = int(round(req_angles))
window_step = int(round(window_size * (1 - overlap)))
if window_step == 0:
window_step = 1
if req_angles == 0:
req_angles = 1
# get all points that classify as a peak/valley
ind = 0
peak_inds, valley_inds = [], []
while ind + window_size <= len(close_prices):
flattened = detrend(close_prices[ind:ind + window_size])
std, avg = np.std(flattened), np.mean(flattened)
lower_b = avg - std * threshold
upper_b = avg + std * threshold
for idx, val in enumerate(flattened):
if val < lower_b:
valley_inds.append(idx + ind)
elif val > upper_b:
peak_inds.append(idx + ind)
ind += window_step
# discard points that have counts below the threshold
peak_counts = Counter(peak_inds)
pk_inds = [c for c in peak_counts.keys() if peak_counts[c] >= req_angles]
valley_counts = Counter(valley_inds)
vly_inds = [c for c in valley_counts.keys() if valley_counts[c] >= req_angles]
# initialize iterator to find to best peak/valley for consecutive detections
if len(pk_inds) == 0 or len(vly_inds) == 0:
return pk_inds, vly_inds
if pk_inds[0] < vly_inds[0]:
curr_event = 'peak'
best_price = close_prices[pk_inds[0]]
else:
curr_event = 'valley'
best_price = close_prices[vly_inds[0]]
#iterate through points and only carry forward the index that has the highest or lowest value from the current group
best_ind = 0
new_vly_inds, new_pk_inds = [], []
for x in range(len(close_prices)):
if x in pk_inds and curr_event == 'valley':
new_vly_inds.append(best_ind)
curr_event = 'peak'
best_price = close_prices[x]
best_ind = x
continue
if x in vly_inds and curr_event == 'peak':
new_pk_inds.append(best_ind)
curr_event = 'valley'
best_price = close_prices[x]
best_ind = x
continue
if x in pk_inds and curr_event == 'peak' and close_prices[x] > best_price:
best_price = close_prices[x]
best_ind = x
elif x in vly_inds and curr_event == 'valley' and close_prices[x] < best_price:
best_price = close_prices[x]
best_ind = x
# deal with the final group of events
if curr_event == 'valley':
new_vly_inds.append(best_ind)
if curr_event == 'peak':
new_pk_inds.append(best_ind)
return new_pk_inds, new_vly_inds
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-07T14:18:37.463",
"Id": "448525",
"Score": "2",
"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-10-07T14:39:47.797",
"Id": "448534",
"Score": "0",
"body": "I didn't update my code based on any feedback here."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-07T14:46:38.210",
"Id": "448536",
"Score": "0",
"body": "Why you update the code really doesn't matter. As soon as answers start coming in, you no longer touch the code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-07T14:49:13.127",
"Id": "448538",
"Score": "0",
"body": "Gotcha, didn't realize. Will keep that in mind for the future"
}
] |
[
{
"body": "<p>Putting aside the matter of optimization for now: I have concerns about the numerical approach here. If this is written with a specific application in mind, and you can make certain assumptions about your data, you might be fine; but if this is to be applied generally there are certain cases that are going to give you a lot of trouble.</p>\n\n<p>I suspect that the data being processed are financial in nature, due to your <code>close_prices</code> variable, in which case the following degenerate case is entirely possible.</p>\n\n<p>What if your data are periodic, and the fundamental spectral component is close to the reciprocal of your window size? In the simplest case, imagine a cosine whose peaks align with the borders of your window. Noise at the borders will generate false peak and valley positives. For this and other reasons, having a fixed window size doesn't lend itself well to accurate analysis.</p>\n\n<p>Numerical statistics is a deep and very complex topic. You'll need to do some reading on this, and will likely find that it's more appropriate for you to apply a library with local minima/maxima search than to roll your own. Read for example this SO answer:</p>\n\n<p><a href=\"https://stackoverflow.com/a/22640362/313768\">https://stackoverflow.com/a/22640362/313768</a></p>\n\n<p>and some of the many links it includes.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-07T07:51:40.903",
"Id": "448478",
"Score": "0",
"body": "This is solved by the use of overlap with the windows no?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-07T08:05:37.253",
"Id": "448481",
"Score": "0",
"body": "Also in response to the post you linked, I wanted to design an algo that looks at both sides of a peak. For example with moving average you're only concerned about data in the past. What if we have a situation in which the signal abruptly enters a very noisy period. With moving average the beginning of this period would be incorrectly identified as a peak."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-07T08:08:24.267",
"Id": "448483",
"Score": "0",
"body": "And by letting user set both overlap and required number of angles, I believe this can let some decide if they want a situation like when the signal jumps and plateaus for a while to be considered a peak or not"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-07T04:00:57.060",
"Id": "230287",
"ParentId": "230281",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-07T02:01:42.150",
"Id": "230281",
"Score": "6",
"Tags": [
"python",
"algorithm",
"signal-processing"
],
"Title": "Peak valley detection in python"
}
|
230281
|
<h1>Description</h1>
<blockquote>
<p>What this does is it takes a randomly generated 64x64 stack and checks
for overlap within the 64x64 array. Here is an example:
<a href="https://imgur.com/a/kkPRzhn" rel="nofollow noreferrer">https://imgur.com/a/kkPRzhn</a>. Each color is its own number (0 is
black, 1 is yellow, 2 is red, etc.) If the colors overlap, the
<code>colors</code> array will place a zero for that color in the array. At the
end of the program, there will be only one color with a non-zero. In
this example, yellow (with color code 1) does not get overlapped at
all, so that is the answer. I am trying to see if I can make these two
nested loops into a single one rather than doing horizontal first and
then vertical. I would like to do both horizontal and vertical
simultaneously.</p>
</blockquote>
<h1>Question</h1>
<p>I have two separate nested for loops that work on the same array of data; one nested for loop for working horizontally, and the other for going vertically. There are conditions that will change the <code>i</code> and <code>j</code> values within each loop.</p>
<ul>
<li>I am struggling to find a way to combine this into a single nested for-loop. </li>
</ul>
<h1>Code</h1>
<pre><code>/*
This program loads a pile and finds the color of the topmost piece. */
#include <stdio.h>
#include <stdlib.h>
#define DEBUG 1 // RESET THIS TO 0 BEFORE SUBMITTING YOUR CODE
int main(int argc, char *argv[]) {
int PileInts[1024];
int NumInts, TopColor=0;
int Load_Mem(char *, int *);
// This allows you to access the pixels (individual bytes)
// as byte array accesses (e.g., Pile[25] gives pixel 25):
char *Pile = (char *)PileInts;
if (argc != 2) {
printf("usage: ./P1-1 valuefile\n");
exit(1);
}
NumInts = Load_Mem(argv[1], PileInts);
if (NumInts != 1024) {
printf("valuefiles must contain 1024 entries\n");
exit(1);
}
if (DEBUG){
printf("Pile[0] is Pixel 0: 0x%02x\n", Pile[0]);
printf("Pile[107] is Pixel 107: 0x%02x\n", Pile[107]);
}
/* Your program goes here */
int colors[] = {1, 2, 3, 4, 5, 6, 7};
// NESTED LOOP 1 - HORIZONTAL
for (int i=1; i<63; i++){ //run through 63 rows
for (int j=1; j<63; j++){ //run through 63 columns
int current = Pile[i*64 + j]; //current position in linearized 64x64 array
int right1 = Pile[i*64+j+1]; //1 right of current position
int right2 = Pile[i*64+j+2]; //2 right of current position
//int left = Pile[i*64+j-1]; //left of current position
// CHECK HORIZONTAL OVERLAP
if ((current != right1) && (current != 0) && (right1 != 0) && (current == right2)) { // check immediately right + edge case,
colors[current-1] = 0; // horizontal edge touches vertical
j++;
}
}
}
// NESTED LOOP 2 - VERTICAL
for (int j=1; j<63; j++){ //run through 63 rows
for (int i=1; i<63; i++){ //run through 63 columns
int current = Pile[i*64 + j]; //current position in linearized 64x64 array
//int above = Pile[(i-1)*64+j]; //above current position
int below1 = Pile[(i+1)*64+j]; //1 below current position
int below2 = Pile[(i+2)*64+j]; //2 below current position
// CHECK VERTICAL OVERLAP
if ((current != below1) && (current != 0) && (below1 != 0) && (current == below2)) { // check immediately right + edge case,
colors[current-1] = 0; // horizontal edge touches vertical
i++;
}
}
}
for (int k = 0; k < 7; k++){
if (colors[k] != 0){
TopColor = colors[k];
}
}
printf("The topmost part color is: %d\n", TopColor);
exit(0);
}
/*
Constraints:
1 - each part is composed of horizontal and vertical lines all of the same color
2 - not all parts have the same number of horizontal and vertical lines
3 - all horizontal and vertical lines in a part have the same length, 25-45 pixels.
4 - a parts horizontal line length is not necessarily the same as its verical line length
Helpful Information:
The array PileInts is a 1-D array that represents 64x64 pixels
Index 0 of PileInts represents index (0,0) on a 64x64 pixeled screen which is the top left corner.
Index 65 of PileInts represents index (1,0) on a 64x64 pixeled screen
Index 1023 of PileInts represents index (63,63) on a 64x64 pixeled screen which is the bottom right
*/
/* This routine loads in up to 1024 newline delimited integers from
a named file in the local directory. The values are placed in the
passed integer array. The number of input integers is returned. */
int Load_Mem(char *InputFileName, int IntArray[]) {
int N, Addr, Value, NumVals;
FILE *FP;
FP = fopen(InputFileName, "r");
if (FP == NULL) {
printf("%s could not be opened; check the filename\n", InputFileName);
return 0;
} else {
for (N=0; N < 1024; N++) {
NumVals = fscanf(FP, "%d: %d", &Addr, &Value);
if (NumVals == 2)
IntArray[N] = Value;
else
break;
}
fclose(FP);
return N;
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-07T03:18:40.023",
"Id": "448456",
"Score": "0",
"body": "I'm not sure what you're trying to do here but since the loop bodies don't depend on previous loop iterations they can be placed in the same loop body (although there may be performance issues). Assuming you have enough memory allocated for a 64x64 array, `Pile[i*64+j+2]` will access the start of the next row (or past the end for the last row) when `j` is 63. (Loop 2 will go past the end when `i` is 62 with `i + 2`.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-07T03:45:22.147",
"Id": "448457",
"Score": "1",
"body": "Welcome to CodeReview! As @1201ProgramAlarm states, _I'm not sure what you're trying to do here_. Code snippets divorced from the rest of your code are not reviewable; they don't have sufficient context. What does this program do? Is it brief enough that we can see it in full? What would you like out of a review?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-07T04:03:02.757",
"Id": "448458",
"Score": "1",
"body": "@Reinderien I've updated the code and added information. I hope that clears it up even a little more. Thanks!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-07T04:36:42.030",
"Id": "448462",
"Score": "2",
"body": "Could you update the title to state what your code does functionally instead of what you are technically looking for?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-07T09:54:20.660",
"Id": "448490",
"Score": "1",
"body": "This code is clearly broken - indexing far outside the bounds of `PileInts`. Please fix the bugs (compile with a good set of warnings and run under Valgrind or similar) and bring it back for review once it's ready."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-07T02:04:16.590",
"Id": "230282",
"Score": "2",
"Tags": [
"c",
"array",
"iterator"
],
"Title": "Combining two nested for loops into one"
}
|
230282
|
<p>I've written a function that moves selected items from a list into a new position. I've found that in order to do this, I need to retain the original 'index structure' of the array. The way I've done this is, instead of splicing the array right away, I set the elements to null, then later traverse the list backwards and splice the null elements. I don't know if this is the best way of doing this, but I thought I would post it here to see if anyone else has an idea of how to better accomplish this.</p>
<p><a href="https://jsfiddle.net/g407pjbk/1/" rel="nofollow noreferrer">https://jsfiddle.net/g407pjbk/1/</a></p>
<pre class="lang-js prettyprint-override"><code>function drag_and_drop(list, before_index){
const selected = [];
for(let index in list){
const item = list[index];
if(item.selected){
selected.push(item);
// Set elements to null in order to retain indecies
list[index] = null;
}
}
// Insert selected items
list.splice(before_index, 0, ...selected);
// Backwards traverse and splice remaining null elements
for(let i=list.length-1;i>=0;i--){
if(list[i] == null)
list.splice(i, 1);
}
return list;
}
</code></pre>
|
[] |
[
{
"body": "<p>First some general remarks to coding conventions:</p>\n\n<ul>\n<li>JavaScript uses camelCase identifiers, not snake_case.</li>\n<li>Insert a space between keywords and a following opening bracket (<code>if (...</code>) so that they don't look like functions.</li>\n</ul>\n\n<hr>\n\n<p>I'm not a big fan of the method name. It should be called after what is does, not what it's for. <code>moveSelectedItemsBeforeIndex</code> would be my choice.</p>\n\n<hr>\n\n<p>Never use <code>for ... in</code> on arrays. It iterates over all properties not only integer properties, and it's not guaranteed to do that in order. Use either a regular <code>for</code> loop or <code>.forEach()</code>.</p>\n\n<hr>\n\n<p>Always use <code>===</code> for comparison, unless you specifically want loose equality (<code>null === undefined</code> is false, but <code>null == undefined</code> is true).</p>\n\n<hr>\n\n<p>You can replace the final loop with a simple <code>.filter</code>:</p>\n\n<pre><code>return list.filter(i => i !== null);\n</code></pre>\n\n<hr>\n\n<p>An alternative implementation with a more functional approach could be:</p>\n\n<pre><code>function drag_and_drop(list, before_index){\n let part1 = list.slice(0, before_index);\n let part2 = list.slice(before_index);\n\n let [selected1, unselected1] = groupBySelect(part1);\n let [selected2, unselected2] = groupBySelect(part2);\n\n return [...unselected1, ...selected1, ...selected2, ...unselected2];\n}\n\nfunction groupBySelect(list) {\n return list.reduce(\n (acc, item) => item.selected ? [[...acc[0], item], acc[1]] : [acc[0], [...acc[1], item]], \n [[], []]\n );\n}\n</code></pre>\n\n<p>It first splits at the index and then groups the elements of the two \"halves\" of the list whether they are selected or not and finally reassembles the array in the right order.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-07T10:33:19.610",
"Id": "230301",
"ParentId": "230286",
"Score": "1"
}
},
{
"body": "<p>So you don't need two loops here. You can just use one loop to </p>\n\n<ol>\n<li>First, get the selected items</li>\n<li>Remove the selected items from the actual array. So you can later put them in the index you want.</li>\n</ol>\n\n<p>So to do that, first, you have to retrieve the indices where the selected obj is there. Then spice it. IN the loop</p>\n\n<pre><code>for (let index in list) {\n const item = list[index];\n\n if (item.selected) {\n selected.push(item);\n list.spice(index,1)\n }\n}\n\n</code></pre>\n\n<p>So you don't have to run another loop to remove the null values. You can now simply just put the values using another spice. That saves you a loop.</p>\n\n<p>You shouldn't be using <code>for ... in</code> for the reasons you have got in RoToRa's answer.</p>\n\n<p><strong>My approach:</strong> I prefer using just one filter. In that, you can do the same thing.</p>\n\n<pre><code>function drag_and_drop(list, before_index) {\n const selected = list.filter((obj,i) => obj.selected ? list.splice(i,1) : obj.selected)\n list.splice(before_index - selected.length , 0, ...selected)\n return list\n}\n</code></pre>\n\n<p>So here, first we check if the object is selected and if it is then we'll just splice it off and if we didn't got a selected item then we can just return the selected item in the selected loop.</p>\n\n<p>So now you have inside selected, the values which have <code>item.selected</code> as true and your list don't have them now because you did splice already in the filter, so you can just splice them with another splice. </p>\n\n<p>Now the index is not anymore <code>before_index</code> it's two values more, because we took out two objects. So to balance that, we will do <code>before_index - selected.length</code> because that's the number of indexes we are going to drop.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-07T11:51:09.047",
"Id": "230305",
"ParentId": "230286",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "230305",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-07T03:52:01.383",
"Id": "230286",
"Score": "4",
"Tags": [
"javascript",
"algorithm",
"interface"
],
"Title": "Drag and drop selected array items in Javascript"
}
|
230286
|
<p>I have a scheduled task where I synch all the data from one table (via an API) to another. There are about 10,000 rows that are being updated and the new ones get created. This is what I came up with and for some reason, it is extremely slow.</p>
<pre><code>def sync_data_from_hub():
stats = tasks.sync_clients_from_hub()
return stats
</code></pre>
<p><strong>tasks.py</strong></p>
<pre><code># 1. This method calls an external API to fetch all the rows.
def sync_clients_from_hub():
url = resolve_hub_url('clients')
response = requests.get(url, headers=headers)
if response.status_code != 200:
print('api response error: {}'.format(response))
return
try:
response_payload = response.json()
except ValueError:
return
# response from API
clients_data = response_payload.get('data')
for (key, value) in clients_data.items():
# Check whether there are any actual changes in this row
# by comparing the last updated date
if services.should_update_data_from_hub(value, constants.SyncTypes.CLIENT):
user, action = services.update_or_create_client_from_hub_data(value)
if action == constants.SyncActions.CRT:
result['new'] += 1
if action == constants.SyncActions.UPD:
result['update'] += 1
# soft delete clients which are not present in payload but still available in database.
if clients_data:
discarded_clients = models.Client.objects.exclude(pk__in=list(map(int, clients_data.keys()))).filter(
is_active=True)
for client in discarded_clients:
client.is_active = False
client.save()
result['deleted'] += 1
return result
</code></pre>
<p><strong>service.py</strong></p>
<pre><code># logic to determine whether we should update the row or not
def should_update_data_from_hub(hub_data: dict, sync_type: str) -> bool:
last_updated_date_from_api = hub_data.get('updatedAt', None)
hub_data['id'] = int(hub_data.get('client', ''))
# This line hits DB to fetch the row corresponding to the one in the API
entity = get_client_by_pk(hub_data['id'])
if not entity:
return True
last_updated_date_local = entity.last_updated_date
if not last_updated_date_local:
return True
# The last updated dates have different timezones, so I have to adjust the timezone before comparison.
last_updated_date_tz = last_updated_date.replace(tzinfo=timezone.utc).astimezone(tz=None)
last_updated_date_local_formatted = last_updated_date_tz.strftime('%Y-%m-%d %H:%M:%S')
return last_updated_date_formatted != last_updated_date_from_api
# Actual method to update the data
def update_or_create_client_from_hub_data(client_data: dict):
client_data['id'] = int(client_data.get('client', None))
# Set `is_active` based on the `archived` flag.
if client_data.get('archive', None) == '1':
client_data['is_active'] = False
else:
client_data['is_active'] = True
...
# Set `last_updated_date`
client_data['last_updated_date'] = client_data.get('updatedAt', datetime.datetime.now())
serializer = serializers.ClientCreateSerializer(data=client_data)
if not serializer.is_valid():
print('client sync errors: {}'.format(serializer.errors))
return None, None
# This line hits DB to fetch the row corresponding to the one in the API
client = get_client_by_pk(serializer.validated_data['id'])
if client:
action = constants.SyncActions.UPD
for (key, value) in serializer.validated_data.items():
setattr(client, key, value)
client.save()
else:
action = constants.SyncActions.CRT
client = models.Client.objects.create(**serializer.validated_data)
return client, action
def get_client_by_pk(pk: int) -> Optional[models.Client]:
return models.Client.objects.filter(pk=pk).first()
</code></pre>
<p>How can I optimize it to perform better? Should I load all the rows from DB in memory first rather than fetching them one by one and doing a comparison?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-15T11:43:04.213",
"Id": "449760",
"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)*."
}
] |
[
{
"body": "<h2>Error handling</h2>\n\n<pre><code>if response.status_code != 200:\n print('api response error: {}'.format(response))\n return\n</code></pre>\n\n<p>is better represented as a simple call to <code>response.raise_for_status()</code>.</p>\n\n<p>Also, this:</p>\n\n<pre><code>try:\n response_payload = response.json()\nexcept ValueError:\n return\n</code></pre>\n\n<p>is dangerous. Silently failing should (at the least) be left up to the caller to decide whether an exception should be caught and swallowed, caught and printed, or allowed to fall through.</p>\n\n<h2>Tuple unpacking</h2>\n\n<pre><code>for (key, value) in clients_data.items():\n</code></pre>\n\n<p>can be</p>\n\n<pre><code>for key, value in clients_data.items():\n</code></pre>\n\n<h2>Undeclared variable</h2>\n\n<pre><code> if action == constants.SyncActions.CRT:\n result['new'] += 1\n if action == constants.SyncActions.UPD:\n result['update'] += 1\n</code></pre>\n\n<p>Where does <code>result</code> come from? You don't show this. Is it a <code>defaultdict</code>?</p>\n\n<h2>Incorrect default</h2>\n\n<pre><code>hub_data['id'] = int(hub_data.get('client', ''))\n</code></pre>\n\n<p>will not work in the case that the key is missing. You can't convert <code>''</code> to an <code>int</code>. Perhaps you meant:</p>\n\n<pre><code>hub_data['id'] = int(hub_data.get('client', '0'))\n</code></pre>\n\n<h2>Ellipses</h2>\n\n<p>This is more of a meta-comment, but</p>\n\n<pre><code># Set `is_active` based on the `archived` flag.\nif client_data.get('archive', None) == '1':\n client_data['is_active'] = False\nelse:\n client_data['is_active'] = True\n...\n</code></pre>\n\n<p>should show the ellipses as a comment to avoid breaking syntactical validity, and you should provide rationale as to why this code is elided. Eliding code harms the potential for you to receive a meaningful review.</p>\n\n<h2>Optimization</h2>\n\n<blockquote>\n <p>How can I optimize it to perform better? </p>\n</blockquote>\n\n<p>It's nearly impossible to say. You haven't run a profiler, which you should; you've elided too much code for us to run this thing; you haven't shown any example data; and you haven't given us an API endpoint (or if that's not possible, at least a sample of a payload the endpoint would return).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-13T16:10:07.550",
"Id": "230650",
"ParentId": "230288",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-07T04:59:59.573",
"Id": "230288",
"Score": "4",
"Tags": [
"python",
"performance",
"mysql",
"django",
"scheduled-tasks"
],
"Title": "Periodically synching data from an API to database is extremely slow"
}
|
230288
|
<p>This code is asp.net core middleware written in f# and called from c# for a blazor server-side app. How can this be made more efficient if any in regards to the async code. </p>
<p>F#:</p>
<pre><code>type CheckMaintenanceStatusMiddleWare(next : RequestDelegate) =
let _next = next
member this.InvokeAsync(context : HttpContext) =
let statusCheck = true
if statusCheck
then
Task.Run(fun arg -> context.Response.Redirect("/Maintenance"))
else
_next.Invoke(context)
[<Extension>]
type CheckMaintenanceStatusMiddleWareExtensions() =
[<Extension>]
static member inline UseCheckMaintenanceStatus(builder : IApplicationBuilder) =
builder.UseMiddleware<CheckMaintenanceStatusMiddleWare>()
</code></pre>
<p>C#</p>
<pre><code>public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseCheckMaintenanceStatus();
var connectionString = Configuration.GetConnectionString("DefaultConnection");
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
}
else
{
app.UseExceptionHandler("/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
//app.UseCookiePolicy();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
endpoints.MapBlazorHub();
endpoints.MapFallbackToPage("/_Host");
});
}
</code></pre>
<p>Razor Component:</p>
<pre><code>@page "/Maintenance"
<h3>Maintenance</h3>
@code {
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-07T06:29:50.093",
"Id": "448467",
"Score": "1",
"body": "@CaringDev please explain, thanks."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-07T14:27:19.950",
"Id": "448530",
"Score": "1",
"body": "Hi, you should explain what your code does in your post, otherwise it's hard to tell if it can be improved."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-13T00:44:24.210",
"Id": "449438",
"Score": "0",
"body": "@IEatBagels, do you have experience with Asp.net core 3? Specifically middleware, and async code?"
}
] |
[
{
"body": "<p><a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.threading.tasks.task.run?view=netframework-4.8\" rel=\"nofollow noreferrer\"><code>Task.Run</code></a> schedules the work specified by the lambda to be executed on the thread pool.\nScheduling the work and managing the thread pool is costly in terms of CPU time, allocations and possible thread starvation. <code>Task.Run</code> is useful for CPU-bound tasks but usually a smell in asynchronous code in web applications. Most of the time it hints at misunderstanding of async vs. parallel.\nAs <code>context.Response.Redirect(\"/Maintenance\")</code> is not async by itself, there is no need to block/wait/schedule work. Instead, you can synchronously instruct the response to redirect and return a premade, completed task:</p>\n\n<pre><code>context.Response.Redirect(\"/Maintenance\")\nTask.CompletedTask\n</code></pre>\n\n<p>or return a result directly</p>\n\n<pre><code>Task.FromResult(response)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-07T07:16:57.280",
"Id": "230293",
"ParentId": "230290",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "230293",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-07T06:28:32.223",
"Id": "230290",
"Score": "0",
"Tags": [
"c#",
"asp.net",
"f#",
"asp.net-core"
],
"Title": "Asp.net middleware"
}
|
230290
|
<p>Here is the React Native code to optimize: it's an OTP form. I want it to be as small as possible.</p>
<pre><code>/* eslint-disable react-native/no-inline-styles */
import React, {Component, createRef} from 'react';
import {Input, Button} from 'react-native-ui-kitten';
import {View, StyleSheet, Image, Dimensions, Text} from 'react-native';
import {SvgUri} from 'react-native-svg';
import {styles} from '../components/Inputs';
import {fill} from '../constants/Icons';
class ConfirmScreen extends Component {
input1 = createRef();
input2 = createRef();
input3 = createRef();
input4 = createRef();
state = {
phoneNumber: '',
};
buttonIcon = style => {
return <SvgUri style={{fill: '#fff'}} uri={fill.forward} />;
};
handleTextChange1 = value => {
this.setState({phoneNumber: value});
this.input2.current.focus();
};
handleTextChange2 = value => {
this.setState({phoneNumber: value});
this.input3.current.focus();
};
handleTextChange3 = value => {
this.setState({phoneNumber: value});
this.input4.current.focus();
};
handleTextChange4 = value => {
this.setState({phoneNumber: value});
};
render() {
return (
<>
<View style={styles.container}>
<View style={styles.card}>
<Image
style={{
width: 60,
height: 60,
transform: [{translateX: getWidth(100) / 2.6}],
marginTop: 30,
marginBottom: 10,
}}
source={require('../assets/images/icon.png')}
/>
<View>
<Text style={styles.header1}>Are you new to miles?</Text>
</View>
<View>
<Text style={styles.header2}>
Enter the 6 digit sent to your mobile number.
</Text>
<View style={{marginBottom: 10}}>
<Text style={{color: '#fe4c5a', fontWeight: 'bold'}}>
0754669999
</Text>
</View>
</View>
<View>
<Input
style={styless.input}
onChangeText={this.handleTextChange1}
keyboardType="number-pad"
/>
<Input
style={[styless.input, styless.secondInput]}
ref={this.input2}
onChangeText={this.handleTextChange2}
keyboardType="number-pad"
/>
<Input
style={[styless.input, styless.thirdInput]}
ref={this.input3}
onChangeText={this.handleTextChange3}
keyboardType="number-pad"
/>
<Input
style={[styless.input, styless.fourthInput]}
ref={this.input4}
onChangeText={this.handleTextChange4}
keyboardType="number-pad"
/>
</View>
<View style={{position: 'relative', bottom: 150}}>
<Text
onPress={this.socialScreenOrPassword}
style={styles.socialLink}>
Resend code in:{' '}
<Text style={{color: '#000', fontWeight: 'bold'}}>00:59</Text>
</Text>
<Button
style={styles.buttonContinue}
size="medium"
icon={this.buttonIcon}
/>
</View>
</View>
</View>
</>
);
}
}
ConfirmScreen.navigationOptions = {
header: null,
};
const getWidth = percentage => {
if (Dimensions.get('window').width > Dimensions.get('window').height) {
return (Dimensions.get('window').height * percentage) / 100;
}
return (Dimensions.get('window').width * percentage) / 100;
};
const styless = StyleSheet.create({
input: {
borderColor: '#dddddd',
backgroundColor: '#fff',
width: 80,
textAlign: 'center',
position: 'relative',
},
secondInput: {
bottom: 52,
left: 88,
},
thirdInput: {
bottom: 104,
left: 176,
},
fourthInput: {
bottom: 156,
left: 263.5,
},
});
export default ConfirmScreen
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-07T07:10:00.550",
"Id": "448475",
"Score": "5",
"body": "The current question title, which states your concerns about the code, applies to too many questions on this site to be useful. The site standard is for the title to simply state the task accomplished by the code. Please see [How do I ask a good question?](https://codereview.stackexchange.com/help/how-to-ask) for examples, and revise the title accordingly."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-07T09:26:40.710",
"Id": "448488",
"Score": "1",
"body": "Please see [**How to get the best value out of Code Review: Asking Questions**](https://CodeReview.Meta.StackExchange.com/q/2436) for guidance on writing good question titles."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-07T07:02:55.163",
"Id": "230292",
"Score": "1",
"Tags": [
"form",
"authentication",
"jsx",
"react-native"
],
"Title": "React Native form for entering one-time password"
}
|
230292
|
<p>I am solving this problem: <a href="https://www.hackerrank.com/challenges/fraudulent-activity-notifications/problem?h_l=interview&playlist_slugs%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D=sorting&h_r=next-challenge&h_v=zen" rel="noreferrer">Fraudulent Activity Notifications</a> on HackerRank. I am done with my code and is working, but it is <strong>inefficient</strong> as well for very large inputs. </p>
<blockquote>
<p>I don't know but after all my efforts, I am able to give out good solution to a problem of a MEDIUM LEVEL but this <code>timeout error</code> happens every time for very large inputs. I have tried optimizing my code and still I get timeout errors.
My agendas for this question and upcoming questions are: </p>
<ul>
<li>How to put efficiency for very large inputs. What kind of intellect it requires.</li>
<li>How to reach to that level. What should I prepare for this.</li>
<li>Code optimization</li>
</ul>
</blockquote>
<p><em>I am open to learning, and I am really desperate to learn how to write a more advanced and optimized code to make myself better. I am open to do hard work.</em></p>
<p><strong>My Algorithm:</strong></p>
<blockquote>
<ol>
<li>For this problem we must go from <code>incrementing variable i</code> till <code>len(givenArray)-d</code></li>
<li>Take a variable for the next variable to be compared, my case <code>iterate</code> is the variable</li>
<li>Pass the values to the particular array to the method for counting <code>countFraud()</code></li>
<li>Add it to the count variable</li>
<li>Increment iterate variable</li>
</ol>
</blockquote>
<p><strong>Code:</strong></p>
<pre><code># this is for counting the trailing array
def countFraud(arr, nextNum):
count = 0
median = 0.0
d = len(arr)
#for calculating the median correctly
arr.sort()
if d%2 != 0:
median = arr[int(d/2)]
else:
n = int(d/2)
median = (arr[n] + arr[n-1]) / 2
#now the opeartion for count from the array
if nextNum >= 2*median: count += 1
return count
# Complete the activityNotifications function below.
def activityNotifications(expenditure, d):
count = 0
iterate = d
# it will go upto the len of array - d, so that it will go upto the d length
# leaving the last element everytime for the comparision
for i in range(len(expenditure)-d):
count += countFraud(expenditure[i:iterate], expenditure[iterate])
iterate += 1
return count
</code></pre>
<p>Now previously I was doing two loops, adding the items to the <code>new_array</code> and passing it to the the <code>countFraud()</code>. But now I have optimized it and made it sort of <code>O(N)</code>. </p>
<p>I don't know but this code is not getting submitted for all TCs due to <code>Timeout Error</code>. There is no problem in operation part. It is just with the efficiency of the code. </p>
<p><strong>Timeout Error Input Example:</strong></p>
<pre><code>200000 10000
</code></pre>
<p>Link for input - <a href="https://hr-testcases-us-east-1.s3.amazonaws.com/26114/input01.txt?AWSAccessKeyId=AKIAJ4WZFDFQTZRGO3QA&Expires=1570391890&Signature=qHOz%2FQxsQJy08w7FQmp7sj1zW18%3D&response-content-type=text%2Fplain" rel="noreferrer">Input Data</a></p>
<p><strong>Expected Output:</strong></p>
<pre><code>633
</code></pre>
<p>I have read upon this article: <a href="https://www.hackerrank.com/environment" rel="noreferrer">HackerRank Environment</a> to learn about the timing issue. For <strong>Python/Python 3</strong> it is <strong>10 seconds</strong>. My code is definitely taking more than that for <code>values greater than 10^3 or 4</code>. </p>
<p>My code has successfully passed 3 TCs though.</p>
|
[] |
[
{
"body": "<p>If this wasn't a programming challenge with restricted modules, I would suggest using <a href=\"https://pandas.pydata.org/\" rel=\"nofollow noreferrer\"><code>pandas</code></a>. It has a rolling windowed median implemented, so it is quite straight forward (just have to be careful not to have an off-by-one error with the <code>shift</code>):</p>\n\n<pre><code>import pandas as pd\n\ndef activityNotifications(expenditure, d):\n df = pd.DataFrame(expenditure)\n return (df.shift(-1) > 2 * df.rolling(d).median())[0].sum()\n</code></pre>\n\n<p>For the example input you gave, this runs in about 210 ms ± 3.71 ms on my machine. This is very hard to beat, both in runtime and readability.</p>\n\n<hr>\n\n<p>Unfortunately, Hackerrank does not have <code>pandas</code> available (or even <code>numpy</code> for that matter). So, we need another implementation of a windowed running median. There are multiple ways to implement it, but here is one. You keep track of two collections, one is the window you are looking at and one is a sorted version of it. The former tells you which value drops out when you add a new one, and the latter allows you to easily get the median without having to sort the window each time, if you insert elements at the right place. For this you can use the <code>bisect</code> modules <code>insort</code> (which is <span class=\"math-container\">\\$\\mathcal{O}(n)\\$</span>, instead of <span class=\"math-container\">\\$\\mathcal{O}(n\\log n)\\$</span> for sorting each time).</p>\n\n<p>I used the <code>RunningMedian</code> function from <a href=\"http://code.activestate.com/recipes/578480-running-median-mean-and-mode/\" rel=\"nofollow noreferrer\">here</a>, and modified it a bit to directly count instead of collecting the medians. It is not the most beautiful code to look at, I might clean it up a bit later. </p>\n\n<pre><code>from itertools import islice\nfrom collections import deque\nfrom bisect import insort, bisect_left\n\ndef activityNotifications(seq, M):\n \"\"\"\n Purpose: Find the median for the points in a sliding window (odd number in size) \n as it is moved from left to right by one point at a time.\n Inputs:\n seq -- list containing items for which a running median (in a sliding window) \n is to be calculated\n M -- number of items in window (window size) -- must be an integer > 1\n Otputs:\n medians -- list of medians with size N - M + 1\n Note:\n 1. The median of a finite list of numbers is the \"center\" value when this list\n is sorted in ascending order. \n 2. If M is an even number the two elements in the window that\n are close to the center are averaged to give the median (this\n is not by definition)\n \"\"\" \n seq = iter(seq)\n s = []\n m = M // 2\n\n # Set up list s (to be sorted) and load deque with first window of seq\n s = [item for item in islice(seq, M)] \n d = deque(s)\n\n # Simple lambda function to handle even/odd window sizes \n median = lambda : s[m] if bool(M&1) else (s[m-1]+s[m])*0.5\n\n # Sort it in increasing order and extract the median (\"center\" of the sorted window)\n s.sort()\n\n # Now slide the window by one point to the right for each new position (each pass through \n # the loop). Stop when the item in the right end of the deque contains the last item in seq\n count = 0\n for item in seq:\n count += item > 2 * median()\n old = d.popleft() # pop oldest from left\n d.append(item) # push newest in from right\n del s[bisect_left(s, old)] # locate insertion point and then remove old \n insort(s, item) # insert newest such that new sort is not required \n return count\n</code></pre>\n\n<p>This code takes about 871 ms ± 14.5 ms on my machine for the given testcase. It passes all testcases on Hackerrank as well. It is slower than the <code>pandas</code> one, but that is to be expected. Both functions give the same result.</p>\n\n<hr>\n\n<p>Some additional comments about your code itself:</p>\n\n<ul>\n<li><code>if nextNum >= 2*median: count += 1</code> could just be <code>return nextNum >= 2*median</code>. Summing <code>bool</code>s is perfectly fine, since they are just <code>int</code>s underneath.</li>\n<li><code>if d%2 != 0:</code> can be <code>if d % 2</code>, because non-zero integers are truthy.</li>\n<li>In actual code please follow Python's official style-guide, <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP8</a>. It recommends naming your function <code>activity_notifications</code>.</li>\n<li>You should add a <a href=\"https://www.python.org/dev/peps/pep-0257/\" rel=\"nofollow noreferrer\">docstring</a> to explain what your function does.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-07T14:38:18.410",
"Id": "230312",
"ParentId": "230294",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-07T07:22:38.917",
"Id": "230294",
"Score": "6",
"Tags": [
"python",
"python-3.x",
"sorting",
"time-limit-exceeded",
"functional-programming"
],
"Title": "Timeout Error in Fraudulent Activity Notification HackerRank"
}
|
230294
|
<p>I wrote three Flask views below.</p>
<h3>First view</h3>
<ol>
<li>input stock code</li>
</ol>
<h3>Second view</h3>
<ol start="2">
<li>get the stock details (name, price) of the stock by using 3rd party api</li>
<li>get the balance cash of DB and show to the view after calculating available number of stock by computing stock price and cash balance</li>
<li>and user input positive number of stock that would buy for this price</li>
</ol>
<h3>Third view</h3>
<ol start="5">
<li>after receive the number of stock send the query to reduce the cash balance from first table called users, and then sent another query to update purchasing record to second table called history.</li>
</ol>
<p>I believe there would certainly be better way than this one. As a newbie in programming and python, it was for me very difficult to send and receive information from html form and python by flask. especially this is three step showing but not simple one step so i use flag. But not sure this is a good way.</p>
<p>Another point is using global variable. since I seperate case by using if statement and flag, the variable used in other if statement could only be accessed by using global variable. However, I would do another way since i worry it would affect for the further fuction as sell later.</p>
<pre><code>def dbexe(sqlquery, str):
db = sqlite3.connect("finance.db")
cur = db.cursor()
if str == "regi" or str == "updat":
cur.execute(sqlquery)
db.commit()
elif str == "selec":
rows = cur.execute(sqlquery)
tupdata = rows.fetchone()
return tupdata
db.close()
@app.route("/buy", methods=["GET", "POST"])
@login_required
def buy():
global flag, balance, sharePrice, username, symbol, resultcom, comname
username=session["user_id"]
if request.method == "GET":
flag=1
return render_template("buy.html")
if request.method == "POST" and flag==1:
symbol = request.form.get("symbol")
resultcom = lookup(symbol)
if not resultcom:
return apology("No such Stock exist!")
sharePrice = resultcom["price"]
balance = int(dbexe(f"select cash from users where username='{username}'", "selec")[0])
maxshareNum = balance//sharePrice
flag=2
return render_template("buy.html", htmlflag=1, result=resultcom, maxNum=maxshareNum)
if request.method == "POST" and flag==2:
sharenum = int(request.form.get("shares"))
newbal = balance-(sharePrice*sharenum)
dbexe(f"update users SET cash={newbal} where username='{username}'", "updat")
comname=resultcom["name"]
dbexe(f"INSERT INTO history('usernameid','date','symbol','comname','sharenum','balatthetime') VALUES('{username}',datetime('now'),'{symbol}','{comname}',{sharenum},{newbal})","regi")
return render_template("buy.html", htmlflag=2)
</code></pre>
<h2>HTML</h2>
<pre><code>{% extends "layout.html" %}
{% block title %}
Buy stock
{% endblock %}
{% block main %}
{% if htmlflag==1 %}
<form action="/buy" method="POST" class="needs-validation" novalidate>
<div class="form-group">
<input type="text" autocomplete="off" autofocus class="form-control" name="symbol"
placeholder="{{result["name"]}}" value="{{result["symbol"]}}" disabled>
</div>
{{result["name"]}} 's current pirce is <B>{{result["price"]| usd}}</B><br>
You can purchase {{result["name"]}} up to <b>{{maxNum}}</b> shares.<br>
How many will you buy? <br>
<div class="form-group">
<input type="number" min="1" max="{{maxNum}}" autocomplete="off" autofocus class="form-control" name="shares"
placeholder="# of Share" required>
</div>
<button class="btn btn-primary" type="submit">Buy</button>
</form>
{% elif htmlflag==2 %}
Successfully bought!
{% else%}
<form action="/buy" method="POST" class="needs-validation" novalidate>
<div class="form-group">
<input autocomplete="off" autofocus class="form-control" name="symbol" placeholder="Stock Symbol" type="text"
required>
</div>
<button class="btn btn-primary" type="submit">Search</button>
</form>
{% endif %}
<script>
(function () {
'use strict';
window.addEventListener('load', function () {
// Fetch all the forms we want to apply custom Bootstrap validation styles to
var forms = document.getElementsByClassName('needs-validation');
// Loop over them and prevent submission
var validation = Array.prototype.filter.call(forms, function (form) {
form.addEventListener('submit', function (event) {
if (form.checkValidity() === false) {
event.preventDefault();
event.stopPropagation();
}
form.classList.add('was-validated');
}, false);
});
}, false);
})();
</script>
{% endblock %}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-07T08:24:53.623",
"Id": "448486",
"Score": "8",
"body": "Welcome to Code Review! Instead of stating your concerns about your code, [please describe what your code should accomplish in the title](/help/how-to-ask). That will help to attract reviewers who are interested in the thing you are trying to do. Also *python* and *flask* don't belong there, these are covered in the tags."
}
] |
[
{
"body": "<h1>Unclosed Connection</h1>\n\n<p>Your <code>dbexe</code> method has a bug. If the <code>elif</code> statement is executed, <code>tupdata</code> is returned without closing the connection to the database. A simple fix is to close the connection the line before returning data.</p>\n\n<h1>Operator Spacing</h1>\n\n<p>There should be one space on either side of operators and assignments, like so</p>\n\n<pre><code>flag==1: -> flag == 1:\nusername=session[\"user_id\"] -> username = session[\"user_id\"]\nflag=2 -> flag = 2\n</code></pre>\n\n<h1>Variable Names</h1>\n\n<p>Variable and function names should be in <code>snake_case</code>.</p>\n\n<h1>Type Hints</h1>\n\n<p>Use type hints to display what types of parameters are accepted, and the type of data that is returned by the function</p>\n\n<p>From this</p>\n\n<pre><code>def dbexe(sqlquery, str):\n</code></pre>\n\n<p>to this</p>\n\n<pre><code>def dbexe(sqlquery: str, string: str):\n</code></pre>\n\n<h1>Reserved Names</h1>\n\n<p>It's not recommended to use <code>str</code> as a parameter/variable name, as it's a reserved keyword in python. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-07T19:02:54.960",
"Id": "448583",
"Score": "1",
"body": "_A simple fix is to close the connection the line before returning data._ - Simple, yes; complete or robust, unfortunately not. At the very least, you should recommend that the OP use a `finally` clause."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-07T17:43:43.267",
"Id": "230327",
"ParentId": "230295",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-07T08:08:53.017",
"Id": "230295",
"Score": "6",
"Tags": [
"python",
"beginner",
"python-3.x",
"flask",
"e-commerce"
],
"Title": "Flask application for buying stocks"
}
|
230295
|
<p>I wrote an extension to create a string-representation by an object:</p>
<pre><code>public static string ToString<T>(this T @this, Func<T, string> predicate) where T: class
{
return predicate(@this);
}
</code></pre>
<p>So I can do something like </p>
<pre><code>return handler.GetUserById(id)?.ToString(x => $"{x.LastName}, {x.FirstName}");
</code></pre>
<p>which gives me either null if the user is null or otherwise e.g. "Miller, Peter" </p>
<p>My question: is this a good extension? Makes it sense? Anything I didn't consider?
And what about the null-thing? Should I check the null value in the extension? Imho, the thrown <code>NullReferenceException</code> is okay, if s.o. calls this with a null object.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-07T09:37:57.450",
"Id": "448489",
"Score": "1",
"body": "Sure, looks like fun, however make sure you check for null on @this"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-07T10:03:14.127",
"Id": "448493",
"Score": "0",
"body": "@PPann I saw, in my library i mostly check for null and throw ArgumentNullException if it's null - so I will add this here too :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-07T10:18:35.433",
"Id": "448494",
"Score": "2",
"body": "Just so you know, `Func<T, string>` is not called a predicate."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-07T19:13:01.260",
"Id": "448584",
"Score": "0",
"body": "worth reading about null reference exception vs argument null exception: https://docs.microsoft.com/en-us/dotnet/api/system.nullreferenceexception?view=netframework-4.8"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-08T07:09:52.910",
"Id": "448625",
"Score": "0",
"body": "@dfhwze thanks for the article, I read it but still didn't get the point.. what should I throw? `A NullReferenceException exception is thrown by a method that is passed null. Some methods validate the arguments that are passed to them. If they do and one of the arguments is null, the method throws an System.ArgumentNullException exception.` imo, throwing an `ArgumentNullException` is correct when I validate the argument. isn't it?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-08T07:51:39.337",
"Id": "448626",
"Score": "0",
"body": "I prefer ANE because of better error details. NRE is a PITA when encountered at runtime in production code."
}
] |
[
{
"body": "<p>There are not much to review, so to answer your questions:</p>\n\n<ol>\n<li>It's a good extension if you can see it useful in more than one place.</li>\n<li>It makes sense.</li>\n<li>I can't see anything else to consider - a <code>null</code> check on the <code>predicate</code> maybe?</li>\n<li>If the exception thrown by the predicate when <code>@this</code> is <code>null</code> is good enough for you, don't bother further.</li>\n</ol>\n\n<hr>\n\n<p>I don't see why the restriction <code>where T: class</code> is necessary</p>\n\n<hr>\n\n<p>If you always want to generate a string containing a list of properties (or another predefined format), you could change the signature to:</p>\n\n<pre><code>public static string ToString<T>(this T @this, params Func<T, object>[] getters)\n{\n return string.Join(\", \", getters.Select(g => g(@this)));\n}\n</code></pre>\n\n<p>called as:</p>\n\n<pre><code>handler.GetUserById(id)?.ToString(p => p.LastName, p => p.FirstName)\n</code></pre>\n\n<p>so that you don't have to format the input when calling the extension.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-07T10:02:30.550",
"Id": "448492",
"Score": "1",
"body": "thx! yeah the restriction is unneccessary.. could also call it on a struct."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-07T09:50:34.977",
"Id": "230298",
"ParentId": "230296",
"Score": "9"
}
}
] |
{
"AcceptedAnswerId": "230298",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-07T09:10:19.207",
"Id": "230296",
"Score": "7",
"Tags": [
"c#",
"functional-programming",
"extension-methods"
],
"Title": "String Format object extension"
}
|
230296
|
<p>This is a class representing a city in a mod I am creating for Minecraft. All the constructor parameters are mandatory and they are used to help the class that calculates and builds the Paths, Buildings etc. </p>
<p>The City class has all the fields that are listed in the constructor including a 2D array that is a representation of the city in X and Z axes. There are also 2 methods to serialize and deserialize the data in order to save them using the Minecraft Forge API. </p>
<pre><code>public City(int id, BlockPos startingPos, int citySize, int edgeLenght, int pathExtends, Block groundBlock, Block pathBlock, boolean hasMainStreets, boolean hasPaths) {
this.id = id;
this.startingPos = startingPos;
this.chunkLength = citySize;
this.cityLength = citySize * 16;
this.edgeLength = edgeLenght;
this.mapLength = cityLength + edgeLenght + blockStart;
this.pathExtends = pathExtends;
this.hasMainStreets = hasMainStreets;
this.hasPaths = hasPaths;
this.groundBlock = groundBlock;
this.pathBlock = pathBlock;
this.blockStart = edgeLenght;
}
</code></pre>
<p>Initializing a city object looks like:</p>
<pre><code>BlockPos startingPos = new BlockPos(1000,63,1000);
int citySize = 5; // Will be pseudorandom
int edgeLength = 4;// Will be pseudorandom
int pathExtends = 2;// Will be pseudorandom
City newCity = new City(++id, startingPos, citySize, edgeLength, pathExtends, Blocks.OBSIDIAN, Blocks.DIAMOND_BLOCK, true, true);
</code></pre>
<p>From an organizational point of view I can see the benefits of this approach but is this a good practice? Does it involve any pitfalls I have not thought about or is there a better way to do this?</p>
<p>This is not easy to read and understand and I was wondering if there was any better way to do it. My idea was to create CitySettings object hence making more readable the City object by moving all these fields to another class.</p>
<p>I am thinking of creating a class <code>CitySettings</code> to hold all of <code>City</code>'s fields and an instance of CitySettings that will be stored as a field in the <code>City</code> class. </p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-07T14:22:23.270",
"Id": "448528",
"Score": "6",
"body": "I don't think that we can give you meaningful advice for improving this code by analyzing it in isolation. Please provide more code for context. See [ask]."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-07T18:45:35.653",
"Id": "448579",
"Score": "1",
"body": "Note you have a typo in _edgeLenght_."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-07T19:17:47.977",
"Id": "448585",
"Score": "2",
"body": "I think you're still missing enough of the code that this is hard to review - you mention methods for (de)serializing the data, but don't provide them. Can you also provide a link to some documentation on the API for those of us who are unfamiliar with it?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-07T19:26:16.467",
"Id": "448587",
"Score": "0",
"body": "I am not providing more code because I do not think it is relevant to what I am asking a code review with and the rest of the class consists of getters for the fields of the class."
}
] |
[
{
"body": "<p>If it's readability you're mostly worried about, then you could change the style of your code:</p>\n\n<pre><code>public City(int id, BlockPos startingPos,\n int citySize, int edgeLenght, \n int pathExtends, Block groundBlock,\n Block pathBlock, boolean hasMainStreets,\n boolean hasPaths) {\n this.id = id;\n this.startingPos = startingPos;\n this.chunkLength = citySize;\n this.cityLength = citySize * 16;\n this.edgeLength = edgeLenght;\n this.mapLength = cityLength + edgeLenght + blockStart;\n this.pathExtends = pathExtends;\n this.hasMainStreets = hasMainStreets;\n this.hasPaths = hasPaths;\n this.groundBlock = groundBlock;\n this.pathBlock = pathBlock;\n this.blockStart = edgeLenght;\n\n}\n</code></pre>\n\n<p>Columnising is a useful trick which can make things more readable.</p>\n\n<p>Yes, there is still visibly a lot of parameters clogging up the screen, but it's not so much that you can't put it all in one constructor. It also helps to remember KISS (Keep It Simple, Stupid), don't overcomplicate unless you need to.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-07T12:09:56.493",
"Id": "230307",
"ParentId": "230302",
"Score": "1"
}
},
{
"body": "<p>Regarding your idea of creating a <code>CitySettings</code> class: from introducing such a class, you'd have only moved the problem - now you have a CitySettings constructor with 9 constructors. Not an improvement.</p>\n\n<p>Further possibilities: if a significant number of the fields are optional, create a builder-pattern. (Do not do this, if all parameters are mandatory, as an object should be completely usable after creation.)</p>\n\n<p>If you find a <em>meaningful</em> subset of the parameters (e.g. startingPos, size, edgeLength might be somehing like <code>GeographicalBounds</code>) you can create a class for these and reduce the parameter count.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-07T14:40:46.143",
"Id": "230313",
"ParentId": "230302",
"Score": "1"
}
},
{
"body": "<p>Use the <strong>builder pattern</strong>. The builder object can remain unmentioned, and City (maybe) without public constructor:</p>\n\n<pre><code>City varna = City.create()\n .withStartingPos(0)\n .withCitySize(10_000)\n .build();\n</code></pre>\n\n<p>Where <code>City.create()</code> returns a <code>CityBuilder</code>.\nChecks can be done in the final <code>CityBuilder.build</code> method raising an ' <code>IllegalStateException(\"Missing mapLength and groundBlock\")</code>.</p>\n\n<p>This also allows some fields to be final (immutable).</p>\n\n<p>Such data classes - when stored in a database table - might also profit from a <em>record format version</em>, indicator of which fields were defined, as one might expect some changes in the fields.</p>\n\n<p>If those data have no calculatory use, you were right to store them is a map / CitySettings.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-07T16:07:42.770",
"Id": "230318",
"ParentId": "230302",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "230318",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-07T10:52:01.357",
"Id": "230302",
"Score": "0",
"Tags": [
"java",
"constructor"
],
"Title": "Minecraft city class"
}
|
230302
|
<blockquote>
<p><strong>Problem</strong></p>
<p>Given two matrices: a pattern <code>p</code> and a text <code>t</code>. Write a program that
counts the number of occurrences of <code>p</code> in <code>t</code>.</p>
<p><strong>Input</strong> </p>
<p>the first line contains two numbers
<code>x</code> and
<code>y</code> -- the number of rows and columns in a pattern. Each of the next
<code>x</code> lines contains a string of length
<code>y</code>. The following lines contain a text in the same format. It is guaranteed that the sizes of rows and columns both for the pattern and
for the text are not equal to zero.</p>
<p><strong>Output</strong> </p>
<p>the number of occurrences of the pattern in the text.</p>
</blockquote>
<p>Here is my solution. I would like to get a code review on this:</p>
<pre><code>import java.util.*;
public class Matrix {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String[] patternMatrix = new String[Integer.parseInt(scanner.nextLine().split(" ")[0])];
for (int i = 0; i < patternMatrix.length; i++) {
patternMatrix[i] = scanner.nextLine();
}
String[] textMatrix = new String[Integer.parseInt(scanner.nextLine().split(" ")[0])];
for (int i = 0; i < textMatrix.length; i++) {
textMatrix[i] = scanner.nextLine();
}
long t = System.currentTimeMillis();
System.out.println(findOccurrences(textMatrix, patternMatrix));
System.out.println("Time: " + (System.currentTimeMillis() - t));
}
private static int findOccurrences(String[] textMatrix, String[] patternMatrix) {
int occurrences = 0;
for (int i = 0; i < textMatrix.length; i++) {
// check if you have appropriate remaining rows
if (textMatrix.length - 1 - i < patternMatrix.length - 1) {
break;
}
// check if you can find the first row
List<Integer> indices = occurrences(textMatrix[i], patternMatrix[0]);
if (indices.isEmpty()) {
continue;
}
for (int j = i + 1, a = 1; a <= patternMatrix.length - 1; j++, a++) {
if (textMatrix[j].equals(textMatrix[j - 1]) && patternMatrix[a].equals(patternMatrix[a - 1])) {
continue;
}
Iterator<Integer> iterator = indices.iterator();
while (iterator.hasNext()) {
int index = iterator.next();
if (!textMatrix[j].substring(index, index + patternMatrix[a].length()).equals(patternMatrix[a])) {
iterator.remove();
}
}
if (indices.isEmpty()) {
break;
}
}
occurrences += indices.size();
}
return occurrences;
}
private static int[] prefixFunction(String str) {
/* 1 */
int[] prefixFunc = new int[str.length()];
/* 2 */
for (int i = 1; i < str.length(); i++) {
/* 3 */
int j = prefixFunc[i - 1];
while (j > 0 && str.charAt(i) != str.charAt(j)) {
j = prefixFunc[j - 1];
}
/* 4 */
if (str.charAt(i) == str.charAt(j)) {
j += 1;
}
/* 5 */
prefixFunc[i] = j;
}
/* 6 */
return prefixFunc;
}
private static List<Integer> occurrences(String text, String pattern) {
int[] prefixArray = prefixFunction(pattern);
List<Integer> occurrencesList = new ArrayList<>();
int j = 0;
for (int i = 0; i < text.length(); i++) {
while (j > 0 && text.charAt(i) != pattern.charAt(j)) {
j = prefixArray[j - 1];
}
if (text.charAt(i) == pattern.charAt(j)) {
j++;
}
if (j == pattern.length()) {
occurrencesList.add(i - pattern.length() + 1);
j = prefixArray[j - 1];
}
}
return occurrencesList;
}
}
</code></pre>
<p><strong>Sample Input 1:</strong></p>
<p>1 1</p>
<p>a</p>
<p>2 2</p>
<p>ab</p>
<p>ba</p>
<p><strong>Sample Output 1:</strong></p>
<p>2</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-07T12:01:45.550",
"Id": "448506",
"Score": "2",
"body": "For starters, there's no need to check the bottom 99 rows or last 99 columns if the pattern is 100x100. Next you should document the algorithm with JavaDoc. I'm way too lazy to try to figure out what the \"prefixFunction\" tries to achieve."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-07T12:35:26.000",
"Id": "448513",
"Score": "0",
"body": "It's okay if you don't understand the Prefix Function because that's been given to me, it's part of the KMP algorithm. I have to optimise findOccurrences function. Also, why don't I need to check the last 99 columns or rows if the pattern is 100x100?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-08T08:10:16.853",
"Id": "448630",
"Score": "0",
"body": "I mean that if the pattern does not start at the 100th to last row/column, it won't start after it, because it won't fit."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-08T08:51:17.347",
"Id": "448637",
"Score": "0",
"body": "@TorbenPutkonen yes, you're right. I should change that in my code"
}
] |
[
{
"body": "<h2>Objects</h2>\n\n<p>If there's a place to drink OOP kool-aid, it's Java. Your <code>static main</code> should be much more limited. Consider:</p>\n\n<ul>\n<li>Make <code>findOccurrences</code> an instance, not <code>static</code>, method</li>\n<li>Give <code>Matrix</code> a convenience constructor accepting a <code>Scanner</code>, and another constructor accepting two <code>int</code>s</li>\n<li>Make <code>patternMatrix</code> and <code>textMatrix</code> instance member variables</li>\n<li>Remove all method parameters from <code>findOccurrences</code> and have it use members instead</li>\n</ul>\n\n<p>This pattern helps with testability and re-entrance. The Probably More Correct (tm) thing to do is separate the <code>Matrix</code> class entirely from your entry point class.</p>\n\n<h2>Discarding input</h2>\n\n<blockquote>\n <p>the first line contains two numbers x and y -- the number of rows and columns in a pattern.</p>\n</blockquote>\n\n<p>You're ignoring <code>y</code>. Is that deliberate? You'll definitely want to parse it and hold onto it, and maybe even validate the string lengths.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-09T09:43:28.817",
"Id": "448819",
"Score": "2",
"body": "Thank you. Your suggestions make total sense. I'll change my code to incorporate these changes"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-09T03:01:17.243",
"Id": "230401",
"ParentId": "230304",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-07T10:56:56.207",
"Id": "230304",
"Score": "3",
"Tags": [
"java",
"performance",
"algorithm",
"strings"
],
"Title": "Knuth-Morris-Pratt algorithm in Java Finding substrings in a matrix"
}
|
230304
|
<p>I wrote a program which creates a svg-group that contains several arranged rectangles with passages inbetween to reach all of the rectangles inside of an area selected by the user. Each rectangle should get an Id.</p>
<p>The user can input several things like rectangle-width/height and a number which represents the ID of the first rectangle. The special thing about this ID is that the user should add 0's to the front of the ID like "01" so that all of the rectangles created by the program have the same ID-length. With "1" the program could create 9 rectangles with the same ID-length, with "01" 99, with "001" 999 and so on.</p>
<p>If the user does not input enough 0's in front of the ID the program should output an error. This can only be checked while I am already computing the rectangles.</p>
<blockquote>
<p>My main question now is: Are the solutions a good way to handle the error? (Question A)</p>
<p>Furthermore, when the user inputs a falsy number, did I handle that exception in a good way?
handled? (Question B)</p>
<p>Lastly, before the code is run I want to check if there are too many
rectangles that have to be computed when e.g. the user inputs a
rectangle height of "0.001". Do you think this is the best way to handle that error? (Question C)</p>
</blockquote>
<p>I thought of three options: </p>
<ol>
<li><strong>Throwing an exception if the program notices that there are not enough 0's.</strong>
I think this would be the easiest to implement. My problem with that is that I read that you should only use Exceptions if there is something you could not foresee. This would not be the case here.</li>
<li><strong>Returning error codes out of all of the sub functions.</strong>
This would be absolutely tideous and, in my opinion, make the code extremely hard to read.</li>
<li><strong>Setting a boolean when the function notices the error. Then checking for all of the error-booleans in the highest function and return an error-code once.</strong></li>
</ol>
<p>What is the best way to output these "exceptions"? </p>
<p>My program:
I added all three types of error handlings I came up with because I'm not sure when to use which one.</p>
<pre><code>function createRectangleLayout(oInputs) {
let bNotEnoughZeros = false;
let aExceptions = checkInputs(); //Question B
if (aExceptions.length > 0)
return "Falsy inputs";
if (areTooManyEstimatedRectangles()) //Question C
new TooManyRectanglesException();
let layout = createNewLayout(); //Question A
if (bNotEnoughZeros) //Is set deep inside of createNewLayout()
return "Not enough zeros exception";
return layout;
function checkInputs() {
let aExceptions = [];
if (oInputs.rectWidth <= 0)
aExceptions.push("RectWidth < 0");
if (oInputs.rectHeight <= 0)
aExceptions.push("RectHeight < 0");
return aExceptions;
}
function areTooManyEstimatedRectangles() {
const MAX_NR_OF_RECTS = 5000;
let estimatedRects = estimateRects(); //returns e.g. 100
return estimatedRects > MAX_NR_OF_RECTS;
}
function createLayout() {
let aRows = calculateRows();
let aCols = calculateCols();
return createSVG(aRows, aCols);
}
function calculateRows() {
//similar function also exists for calculateCols()
let iRows = calculateNrOfRows();
let aRows = [];
for (let i = 0; i < iRows; i++) {
if (doesNeedPassage) aRows.push("Passage");
else aRows.push("Rectangle");
}
}
function createSVG(aRows, aCols) {
let svgGroup = createSVGGroup();
let iRect = 0;
let x = 0, y = 0;
aRows.foreach((row, iRow) => {
if (row == "Passage")
y += oInputs.passageWidth;
else
aCols.foreach((col, iCol) => {
if (col == "Passage")
x += oInputs.passageWidth;
else {
addRectToSVGGroup(svgGroup, x, y, iRect);
iRect++;
}
});
x = 0;
y += oInputs.rectHeight;
});
}
function addRectToSVGGroup(svgGroup, x, y, iRect) {
let rect = createId(iRect);
svgGroup.appendChild(rect);
}
function createId(iRect) {
//only here the program notices if there are not enough zeros
if (areNotEnoughZeros()) {
bNotEnoughZeros = true;
return "";
} else
return calculateId(iRect);
}
}
</code></pre>
<p>This is how the function could get called:</p>
<pre><code>function main() {
try {
let oInputs = getInputsFromForm();
let layout = createRectangleLayout(oInputs);
if (layout == INPUT_ERROR)
console.error("Input error");
if (layout == TOO_MANY_RECTS_ERROR)
console.error("Too many rectangles. Would take too long to compute");
} catch (e) {
console.error(e.getMessage());
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-07T12:28:13.467",
"Id": "448512",
"Score": "0",
"body": "This is my first question here, so not quite sure how I should input the code. I left out the unnecessary functions..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-07T14:19:46.077",
"Id": "448526",
"Score": "0",
"body": "Your code contains syntax errors. `aCols.foreach(col, iCol) => {`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-07T14:25:32.410",
"Id": "448529",
"Score": "0",
"body": "Yes my bad. Corrected it"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-07T14:31:00.167",
"Id": "448532",
"Score": "0",
"body": "There are some (only a quick glance so far) logic errors in the code. `\"passage\"` and `\"Passage\"` are not matching strings"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-07T14:33:53.993",
"Id": "448533",
"Score": "0",
"body": "Missing functions `calculateCols`, `calculateNrOfRows`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-07T14:40:33.997",
"Id": "448535",
"Score": "0",
"body": "@Blindman67 Am I supposed to put the entire code here even if the functions are not important to the question?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-07T14:56:10.720",
"Id": "448539",
"Score": "1",
"body": "The title of your question defines what is to be reviewed. There is not enough code to \"create a SVG-Group\". Consider restating the title to better reflect what you want reviewed. BTW question (C) \"How can...\" is not a review question, restate as \"Is my solution...\" or similar and include the code that is your solution."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-07T15:05:02.213",
"Id": "448544",
"Score": "0",
"body": "Ok thanks. I'll try to do that in the future. Is this better?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-08T09:12:15.567",
"Id": "448639",
"Score": "0",
"body": "Usually it's best to include all the relevant functions, even if you consider them non-important. However, since the first answer has arrived now, please stop editing your question."
}
] |
[
{
"body": "<p>In my opinion the error handling is the smallest problem with this code. The main problem is that it's very unstructured and chaotic.</p>\n\n<p>Every single function is reading from (and worse, sometimes writing to) variables outside its scope. It's impossible to know which data a function is actually working with or what has changed after it has run. </p>\n\n<p>A function should only use any data passed to it through it's parameters and never change anything \"outside\". </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-08T08:33:11.973",
"Id": "448633",
"Score": "0",
"body": "Ok makes sense. My problem is always that you would have to pass these arguments through 5 different functions to actually use them and sometimes some functions have 5 arguments in the end. That's why I thought using global variables might be better if you don't have too many of them..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-08T08:40:09.230",
"Id": "448636",
"Score": "0",
"body": "But still, what do you think is the best way of handling these errors?"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-08T08:09:11.587",
"Id": "230361",
"ParentId": "230309",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-07T12:27:03.997",
"Id": "230309",
"Score": "1",
"Tags": [
"javascript",
"error-handling",
"exception"
],
"Title": "Handling errors in an input based program"
}
|
230309
|
<p>I am a C# game developer currently learning C++ and this is my second <em>big-ish</em> project (the first one being a <a href="https://codereview.stackexchange.com/questions/227716/yavi-yet-another-vector-implementation">vector implementation</a>).
This time I opted for implementing a mot-a-mot <code>any</code> implementation based on the specifications of the ISO/IEC N4830 standard draft.</p>
<p>My objective is to familiarize myself with the modern C++ techniques. </p>
<p>The code can be found on Github. <a href="https://github.com/TheSica/any/blob/8ed1e1e4d2e6f4ce5441ec5d96d1dbd9fc88b0b8/any/any.h" rel="nofollow noreferrer">Here is the link.</a></p>
<p>Thank you in advance for taking the time to read my code.</p>
<pre class="lang-cpp prettyprint-override"><code>#pragma once
/*
At any point, an <any> stores one of the following types:
1. Big types
2. Small types
3. Trivial types
In the 1st case, <any> will dynamically allocate memory on the heap for the object
In the 2nd case, <any> will store the object inside any itself
In the 3rd case, <any> will store the object inside any itself and no destructor shall be called for the object. Additionally, the copy and moves will be treated differently
*/
#include <utility>
#include <initializer_list>
#include <type_traits>
class bad_any_cast : public std::bad_cast
{
const char* what() const noexcept override
{
return "bad_any_cast";
}
};
constexpr size_t small_space_size = 8 * sizeof(void*);
template<class T>
using any_is_small = std::bool_constant<std::is_nothrow_move_constructible_v<T>
&& sizeof(T) <= small_space_size
&& alignof(T) <= alignof(void*)>; // Check if alignment shouldnt be % == 0
enum class any_representation
{
Small,
Big,
};
template<class T, class... Args>
void Construct(void* destination, Args&&... args) noexcept
{
new(destination) T(std::forward<Args>(args)...);
}
struct any_big
{
template <class T>
static void Destroy(void* target) noexcept
{
std::destroy_at(static_cast<T*>(target));
_aligned_free(target);
}
template<class T>
static void* Copy(const void* source)
{
return new T(*static_cast<const T*>(source));
}
template<class T>
static void* Type()
{
return (void*)&typeid(T);
}
void (*_destroy)(void*);
void* (*_copy)(const void*);
void* (*_type)();
};
struct any_small
{
template <class T>
static void Destroy(void* target)
{
if constexpr (!std::is_trivially_copyable_v<T>)
{
std::destroy_at(static_cast<T*>(target));
}
}
template<class T>
static void Copy(void* destination, const void* what)
{
if constexpr (std::is_trivially_copyable_v<T>)
{
*static_cast<T*>(destination) = *static_cast<const T*>(what);
}
else
{
Construct<T>(static_cast<T*>(destination), *static_cast<const T*>(what));
}
}
template<class T>
static void Move(void* destination, void* what) noexcept
{
if constexpr (std::is_trivially_copyable_v<T>)
{
*static_cast<T*>(destination) = *static_cast<T*>(what);
}
else
{
Construct<T>(static_cast<T*>(destination), std::move(*static_cast<T*>(what)));
}
}
template<class T>
static void* Type()
{
return (void*) & typeid(T);
}
void (*_destroy)(void*);
void (*_copy)(void*, const void*);
void (*_move)(void*, void*);
void* (*_type)();
};
template<class T>
any_big any_big_obj = { &any_big::Destroy<T>, &any_big::Copy<T>, &any_big::Type<T> };
template<class T>
any_small any_small_obj = { &any_small::Destroy<T>, &any_small::Copy<T>, &any_small::Move<T>, &any_small::Type<T> };
class any
{
public:
constexpr any() noexcept
:_storage{},
_representation{}
{
}
any(const any& other) noexcept
:_storage{},
_representation{}
{
if (!other.has_value())
{
return;
}
switch (other._representation)
{
case any_representation::Big:
_storage.big_storage.handler = other._storage.big_storage.handler;
_storage.big_storage.storage = other._storage.big_storage.handler->_copy(other._storage.big_storage.storage);
_representation = any_representation::Big;
break;
case any_representation::Small:
_storage.small_storage.handler = other._storage.small_storage.handler;
other._storage.small_storage.handler->_copy(&_storage.small_storage.storage, &other._storage.small_storage.storage);
_representation = any_representation::Small;
break;
}
}
any(any&& other) noexcept
:_storage{},
_representation{}
{
if (!other.has_value())
{
return;
}
switch (other._representation)
{
case any_representation::Big:
_storage.big_storage.handler = other._storage.big_storage.handler;
_storage.big_storage.storage = other._storage.big_storage.storage;
_representation = any_representation::Big;
break;
case any_representation::Small:
_storage.small_storage.handler = other._storage.small_storage.handler;
other._storage.small_storage.handler->_move(&_storage.small_storage.storage, &other._storage.small_storage.storage);
_representation = any_representation::Small;
break;
}
}
template<class T, typename VT = std::decay_t<T>, typename = std::enable_if_t<!std::is_same_v<VT, any> // can use conjunction and negation for short circuit but it's too hard too
&& std::is_copy_constructible_v<VT>>> // check if VT is a specialization of in_place_type_t
any(T&& value)
{
emplace<VT>(std::forward<T>(value));
}
template<class T, class... Args, typename VT = std::decay_t<T>, typename = std::enable_if<std::is_copy_constructible_v<VT>
&& std::is_constructible_v<VT, Args...>>>
explicit any(std::in_place_type_t<T>, Args&&... args)
{
emplace<VT>(std::forward<T>(args)...);
}
template<class T, class U, class...Args, typename VT = std::decay_t<T>, typename = std::enable_if_t<std::is_copy_constructible_v<VT> &&
std::is_constructible_v<VT, std::initializer_list<U>&, Args...>>>
explicit any(std::in_place_type_t<T>, std::initializer_list<U> il, Args&&... args)
{
emplace<VT>(il, std::forward<Args>(args)...);
}
~any()
{
reset();
}
any& operator=(const any& rhs)
{
any(rhs).swap(*this);
return *this;
}
any& operator=(any&& rhs) noexcept
{
any(std::move(rhs)).swap(*this);
return *this;
}
template<class T, typename VT = std::decay_t<T>, typename = std::enable_if_t<!std::is_same_v<VT, any>
&& std::is_copy_constructible_v<VT>>>
any& operator=(T&& rhs)
{
any tmp(rhs);
tmp.swap(*this);
return *this;
}
template<class T, typename VT = std::decay_t<T>, class... Args, typename = std::enable_if_t<std::is_copy_constructible_v<VT>
&& std::is_constructible_v<VT, Args...>>>
std::decay_t<T>& emplace(Args&&... args)
{
reset();
return emplace_impl<VT>(any_is_small<T>{}, std::forward<Args>(args)...);
}
template<class T, class U, typename VT = std::decay_t<T>, class... Args, typename = std::enable_if_t<std::is_copy_constructible_v<VT>
&& std::is_constructible_v<VT,std::initializer_list<U>&, Args...>>>
std::decay_t<T>& emplace(std::initializer_list<U> il, Args&&... args)
{
reset();
return emplace_impl<VT>(any_is_small<T>{}, il, std::forward<Args>(args)...);
}
void reset() noexcept
{
if (!has_value())
{
return;
}
switch (_representation)
{
case any_representation::Big:
_storage.big_storage.handler->_destroy(_storage.big_storage.storage);
_storage.big_storage.handler = nullptr;
break;
case any_representation::Small:
_storage.small_storage.handler->_destroy(&_storage.small_storage.storage);
_storage.small_storage.handler = nullptr;
break;
}
}
void swap(any& rhs) noexcept
{
any tmp;
tmp._storage = rhs._storage;
tmp._representation = rhs._representation;
rhs._storage = _storage;
rhs._representation = _representation;
_storage = tmp._storage;
_representation = tmp._representation;
}
bool has_value() const noexcept
{
switch (_representation)
{
case any_representation::Big:
return _storage.big_storage.handler != nullptr;
case any_representation::Small:
return _storage.small_storage.handler != nullptr;
default:
return false;
}
}
const std::type_info& type() const noexcept
{
if (has_value())
{
switch (_representation)
{
case any_representation::Big:
return *static_cast<const std::type_info*>(_storage.big_storage.handler->_type());
case any_representation::Small:
return *static_cast<const std::type_info*>(_storage.small_storage.handler->_type());
}
}
else
{
return typeid(void);
}
}
template<class T>
T* get_val() noexcept
{
return static_cast<T*>(get_val_impl(any_is_small<T>{}));
}
private:
template<class T, class... Args>
std::decay_t<T>& emplace_impl(std::true_type, Args&&... args) // any_is_trivial, any_is_small
{
// small any
_storage.small_storage.handler = &any_small_obj<T>;
Construct<T>(static_cast<void*>(&_storage.small_storage.storage), std::forward<Args>(args)...);
_representation = any_representation::Small;
return reinterpret_cast<T&>(_storage.small_storage.storage);
}
template<class T, class... Args>
std::decay_t<T>& emplace_impl(std::false_type, Args&&... args) // any_is_trivial, any_is_small
{
// big any
_storage.big_storage.handler = &any_big_obj<T>;
_storage.big_storage.storage = _aligned_malloc(sizeof(T), alignof(T));
Construct<T>(_storage.big_storage.storage, std::forward<Args>(args)...);
_representation = any_representation::Big;
return reinterpret_cast<T&>(_storage.big_storage.storage);
}
void* get_val_impl(std::true_type) noexcept
{
return (static_cast<void*>(&_storage.small_storage.storage));
}
void* get_val_impl(std::false_type) noexcept
{
return (_storage.big_storage.storage);
}
struct big_storage_t
{
void* storage;
any_big* handler;
};
struct small_storage_t
{
typedef std::aligned_storage_t<small_space_size, std::alignment_of_v<void*>> internal_storage_t;
internal_storage_t storage;
any_small* handler;
};
struct storage
{
union
{
small_storage_t small_storage;
big_storage_t big_storage;
};
std::type_info* _typeInfo;
};
storage _storage;
any_representation _representation;
};
inline void swap(any& x, any& y) noexcept
{
x.swap(y);
}
template<class T, class... Args>
any make_any(Args&&... args)
{
return any{std::in_place_type<T>, std::forward<Args>(args)...};
}
template<class T, class U, class... Args>
any make_any(std::initializer_list<U> il, Args&&... args)
{
return make_any(il, std::forward<Args>(args));
}
template<class T>
T any_cast(const any& operand)
{
static_assert(std::is_constructible_v<T, const std::remove_cv_t<std::remove_reference_t<T>>&>);
const auto storagePtr = any_cast<std::remove_cv_t<std::remove_reference_t<T>>>(&operand);
if (!storagePtr)
{
throw bad_any_cast({});
}
return static_cast<T>(*storagePtr);
}
template<class T>
T any_cast(any& operand)
{
static_assert(std::is_constructible_v<T, std::remove_cv_t<std::remove_reference_t<T>>&>);
const auto storagePtr = any_cast<std::remove_cv_t<std::remove_reference_t<T>>>(&operand);
if (!storagePtr)
{
throw bad_any_cast({});
}
return static_cast<T>(*storagePtr);
}
template<class T>
T any_cast(any&& operand)
{
static_assert(std::is_constructible_v<T, std::remove_cv_t<std::remove_reference_t<T>>>);
const auto storagePtr = any_cast<std::remove_cv_t<std::remove_reference_t<T>>>(&operand);
if (!storagePtr)
{
throw bad_any_cast({});
}
return static_cast<T>(std::move(*storagePtr));
}
template<class T>
const T* any_cast(const any* operand) noexcept
{
if (operand != nullptr && operand->type() == typeid(T))
{
return /*const_cast*/ operand->get_val<T>();
}
return nullptr;
}
template<class T>
T* any_cast(/*const*/ any* operand) noexcept
{
if (operand != nullptr && operand->type() == typeid(T))
{
return /*const_cast*/ operand->get_val<T>();
}
return nullptr;
}
</code></pre>
<p>Edit: A more up-to-date version of this implenetantion can be found <a href="https://github.com/TheSica/any/blob/master/any/any.h" rel="nofollow noreferrer">here</a></p>
|
[] |
[
{
"body": "<p>You've got some issues with your perfect forwarding and move semantics. You wrote:</p>\n\n<pre><code>template<class T, typename VT = std::decay_t<T>,\n typename = std::enable_if_t<!std::is_same_v<VT, any>\n && std::is_copy_constructible_v<VT>>>\nany& operator=(T&& rhs)\n{\n any tmp(rhs);\n tmp.swap(*this);\n return *this;\n}\n</code></pre>\n\n<p>Here <code>T&& rhs</code> is a forwarding reference, so you ought to forward it:</p>\n\n<pre><code> any tmp(std::forward<T>(rhs));\n</code></pre>\n\n<hr>\n\n<p>And again:</p>\n\n<pre><code>template<class T, typename VT = std::decay_t<T>, class... Args,\n typename = std::enable_if_t<std::is_copy_constructible_v<VT>\n && std::is_constructible_v<VT, Args...>>>\nstd::decay_t<T>& emplace(Args&&... args)\n{\n reset();\n return emplace_impl<VT>(any_is_small<T>{}, std::forward<Args>(args)...);\n}\n</code></pre>\n\n<p>Here you are correctly forwarding <code>Args&&... args</code>; but look closely at your <code>enable_if</code> condition! You're asking whether <code>VT</code> is constructible from <code>Args...</code>. But when you actually pass <code>args...</code> to <code>emplace_impl<VT></code>, you end up trying to construct <code>VT</code> from <code>Args&&...</code>! So you should be testing</p>\n\n<pre><code> class = std::enable_if_t<std::is_copy_constructible_v<VT>\n && std::is_constructible_v<VT, Args&&...>>>\n</code></pre>\n\n<p>instead. (And notice that I personally prefer <code>template<class></code> over <code>template<typename></code> — it means the same thing, it's just less to write and less to read.)</p>\n\n<hr>\n\n<p>Since <code>enum class any_representation</code> is part of your struct layout and thus part of your ABI, you should add an explicit underlying type so that you know how many bytes it'll take up in your struct.</p>\n\n<pre><code>enum class any_representation : unsigned char { Small, Big };\n</code></pre>\n\n<hr>\n\n<pre><code>template<class T, class... Args>\nvoid Construct(void* destination, Args&&... args) noexcept\n{\n new(destination) T(std::forward<Args>(args)...);\n}\n</code></pre>\n\n<p><code>noexcept</code>? Really? What if it throws?\nThis is a good argument to never put <code>noexcept</code> anywhere except on move-constructors (to avoid the vector pessimization) and perhaps <code>swap</code>. Certainly you should be very careful every time you apply it; don't just scatter it willy-nilly like <code>constexpr</code>!</p>\n\n<hr>\n\n<pre><code>template<class T>\nany_big any_big_obj = { &any_big::Destroy<T>, &any_big::Copy<T>, &any_big::Type<T> };\n\ntemplate<class T>\nany_small any_small_obj = { &any_small::Destroy<T>, &any_small::Copy<T>, &any_small::Move<T>, &any_small::Type<T> };\n</code></pre>\n\n<p>Why do you have two different layouts for these structs (<code>any_small</code> has 4 function pointers where <code>any_big</code> has only 3)? The whole point of <code>any</code> is that you're type-erasing everything about the original <code>VT</code> except for its affordances. If \"small\" VTs require different affordances than \"big\" VTs, you're probably doing something incorrect somewhere.</p>\n\n<hr>\n\n<pre><code>std::type_info* _typeInfo;\n</code></pre>\n\n<p>This field is completely unused, I think. Why is it here? (More importantly, how could you improve your workflow to avoid submitting code reviews for dead code?)</p>\n\n<hr>\n\n<pre><code>typedef std::aligned_storage_t<small_space_size, std::alignment_of_v<void*>> internal_storage_t;\ninternal_storage_t storage;\n</code></pre>\n\n<p>I strongly recommend against using <code>std::aligned_storage_t</code> in C++11-and-later; its behavior is <a href=\"https://github.com/WG21-SG14/SG14/search?q=aligned_storage&type=Commits\" rel=\"noreferrer\">not portable</a> from one library to the next. Instead, you can use C++11's built-in support for alignment:</p>\n\n<pre><code>alignas(void*) char storage[small_space_size];\n</code></pre>\n\n<hr>\n\n<pre><code>inline void swap(any& x, any& y) noexcept \n{\n x.swap(y);\n}\n</code></pre>\n\n<p>Prefer to use the Hidden Friend idiom here: make this function findable only via ADL.</p>\n\n<hr>\n\n<pre><code>void swap(any& rhs) noexcept\n{\n any tmp;\n tmp._storage = rhs._storage;\n tmp._representation = rhs._representation;\n\n rhs._storage = _storage;\n rhs._representation = _representation;\n\n _storage = tmp._storage;\n _representation = tmp._representation;\n}\n</code></pre>\n\n<p>First of all, if this code were correct, you should just be using <code>std::swap(_storage, rhs._storage); std::swap(_representation, rhs._representation);</code>, not writing out the three-step dance by hand.</p>\n\n<p>However, this code is utterly wrong. Try it (on libstdc++ or libc++) with</p>\n\n<pre><code>any a1 = std::list<int>{1,2,3};\nany a2 = std::list<int>{4,5,6};\na1.swap(a2);\nstd::list<int> r = any_cast<const std::list<int>&>(a1);\n</code></pre>\n\n<p>You can't just memswap the bytes of two <code>std::list</code>s and expect them to come through unscathed; <code>std::list</code> is not <a href=\"https://www.youtube.com/watch?v=SGdfPextuAU\" rel=\"noreferrer\">trivially relocatable</a>. To move <code>a1</code>'s contents over into <code>a2</code>, and vice versa, you must at some point invoke <code>std::list</code>'s move-constructor. Your code never invokes the move-constructor, so I know it's wrong.</p>\n\n<p><a href=\"https://godbolt.org/z/1A7HjR\" rel=\"noreferrer\">Godbolt</a> seems to show that you've got problems elsewhere in the code, too. I haven't tried to track them down.</p>\n\n<p>This goes to show: you should also write <strong>unit tests</strong> for your code, and test it, before submitting it for review!</p>\n\n<hr>\n\n<pre><code>return make_any(il, std::forward<Args>(args));\n</code></pre>\n\n<p>This line gives an error on Clang, because you forgot the <code>...</code> after <code>(args)</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-08T10:23:59.627",
"Id": "448651",
"Score": "0",
"body": "`is_constructible_v<T, Args...>` is identical to `is_constructible_v<T, Args&&...>` because `is_constructible` is defined in terms of `declval`. Unless you are talking about incomplete types ..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-08T11:41:00.467",
"Id": "448657",
"Score": "0",
"body": "Thank you for the review.\nI'm not sure about the difference between `std::is_constructible_v<VT, Args&&...>>` and `std::is_constructible_v<VT, Args...>>` though.\nI know that `Construct` should not have been marked as noexcept. My cppcore code analysis kept screaming I should mark it as noexcept for some reason and I did but it was the wrong call.\nany_big doesn't have a `move` method because I work with pointers so in my mind I can just swap/assign the pointers that point to the allocated object on the heap."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-08T11:44:17.490",
"Id": "448658",
"Score": "0",
"body": "Interestingly enough, if I do change the `swap` method to work with `std::swap(storage...)` and and `std::swap(representation...)` your example works fine. You were right to say I shouldn't \"three-step dance by hand\". I don't see why I should (move) construct the objects in a `swap` operation though.\n\nI do have unit tests for my code but perhaps these are not enough:\nhttps://github.com/TheSica/any/blob/master/any/TestAny.cpp\n\nI will work on fixing the errors/warnings that I get from different compilers.\n\nThank you again for your review!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-08T14:59:01.827",
"Id": "448698",
"Score": "0",
"body": "@MariusT: Those look like a good start on tests! However, indeed, I don't see any tests of `swap` for non-trivially relocatable types. If you're on GCC/libstdc++, then even `std::string` (for a small string) would have exposed the problem with `swap`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-08T15:04:14.117",
"Id": "448699",
"Score": "0",
"body": "\"`any_big` doesn't have a `move` method because I work with pointers so in my mind I can just swap/assign the pointers\" — Right, what it means to \"move\" an `any_big` is pretty trivial. But you still have code somewhere that describes what you do to a `storage` when you need to \"move\" it, in the `any_big` case. You just chose to write that code inline rather than attach it to `void (*move)(void*, void*)`. If you attach it to `void (*move)(void*, void*)`, then your `big_handler` and `small_handler` get the same layout, so you're one step closer to removing that switch from your move-constructor."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-08T17:08:10.497",
"Id": "448704",
"Score": "0",
"body": "I can confirm that any::swap with `std::swap(_storage, rhs._storage);` and `std::swap(_representation, rhs._representation);` instead of what I had, works with swapping `std:list<int>`, `std::string`, `std::list<TestObject>`. \n(https://github.com/TheSica/any/blob/master/any/TestAny.cpp#L405)\n\nagain, this is only tested on MSVC.\n--\nAlso you have a very good point about getting rid of the switch and unifying everything!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-08T18:11:28.317",
"Id": "448714",
"Score": "0",
"body": "Yes, MSVC's `std::list` is trivially relocatable. But try it with their `std::function` or `std::any`! See [\"What library types are `trivially_relocatable` in practice?\"](https://quuxplusone.github.io/blog/2019/02/20/p1144-what-types-are-relocatable/) (You might have to increase your `small_space_size` from 32 up to `sizeof(std::function<int()>`.) For more info including a walkthrough of the problem case (with `std::function` specifically), please watch the YouTube video linked from my answer above."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-07T20:37:01.043",
"Id": "230337",
"ParentId": "230310",
"Score": "6"
}
},
{
"body": "<ol>\n<li>Regarding your <a href=\"https://en.cppreference.com/w/cpp/language/typeid\" rel=\"nofollow noreferrer\"><code>typeid</code></a>, you have to include the header <a href=\"https://en.cppreference.com/w/cpp/header/typeinfo\" rel=\"nofollow noreferrer\"><code><typeinfo></code></a> before being allowed to use it.</li>\n<li>In your <code>any_big</code> and <code>any_small</code>: Why does the function <code>static void* Type<T>()</code> return a <code>void*</code>? You could return a <code>const std::type_info&</code> instead</li>\n<li><p>Your <code>any_big_obj</code> and <code>any_small_obj</code> are variables defined in the header-file. If you include your <code>any.h</code> in two cpp-files and instantiate the variable templates with the same type, you will get a linker error. Two avoid that, mark the variables as either const or inline (or both, which I suggest)</p>\n\n<pre><code>inline const any_big any_big_obj = ...\n</code></pre></li>\n<li><p>In <code>any_small::Destroy</code>: The <code>if constexpr</code> check should be <code>!std::is_trivially_destructible_v<T></code></p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-11T09:40:33.627",
"Id": "230531",
"ParentId": "230310",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-07T14:06:15.230",
"Id": "230310",
"Score": "11",
"Tags": [
"c++",
"reinventing-the-wheel",
"template",
"stl",
"variant-type"
],
"Title": "YAAI (Yet another any implementation)"
}
|
230310
|
<p>I made a random-walk predator-prey simulation that focuses on individual animals instead of the (maybe) more common array-based approach. I'd like to hear your opinion about this: how could the concept and the code structure be improved, and how good is my implementation?</p>
<blockquote>
<h3>Rules in the model:</h3>
<ul>
<li>There are two species competing on a rectangular grid: rabbits and foxes.</li>
<li>Initially an exact number of them is spawned on random distinct locations.</li>
<li>In each step, each of them moves 1 step to a neighbour grid (no diagonal movements).</li>
<li>If a rabbit and a fox steps on the same spot, the fox eats the rabbit, so the rabbit dies.</li>
<li>Each animal starts with a given amount of energy, and each timestep they lose 1 energy. If an animal runs out of energy, it dies.</li>
<li>in each step, there's a small chance for each point that a newborn rabbit or fox spawns there, with fresh energy. If a (newborn/not)
rabbit and a (newborn/not) fox occupies the same point, the fox eats
the rabbit instantly.</li>
</ul>
</blockquote>
<p>And, of course, there's a lot of possibility to play around: change parameters like energy or spawning probability, initial values, rules of interaction (recharge energy when feeding?) or spawning (spawn only if two of the same species on the same place? after feeding)... even adding a new species is fairly simple.</p>
<p>The code:</p>
<pre><code>#!/opt/anaconda3/bin/python
# -*- coding: utf-8 -*-
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import animation as animation
from scipy import integrate
from progressbar import progressbar as prbar # (use pip/conda install progressbar2, or rewrite line 116.)
from copy import copy
RABBIT = 0
FOX = 1
UP = 0
DOWN = 1
LEFT = 2
RIGHT = 3
STAY = 4
# initial number of rabbits and foxes
nrabbits = 10
nfoxes = 5
# size of the grid
gridxsize = 30
gridysize = 30
# energy of a freshly spawned rabbit/fox
rabben = 20
foxen = 20
# chance of a new fox/rabbit being spawned at a gridpoint on a step
rabbit_newborn_chance = 0.01
fox_newborn_chance = 0.01
# number of steps to simulate
steps = 200
class Animal(object):
"""
Tracks the animal's position, energy, species (rabbit/fox) and state (live/dead).
"""
def __init__(self, x0, y0, init_energy, species):
self.x = x0
self.y = y0
self.energy = init_energy
self.species = species
self.isDead = False
def interact(self, other):
"""
Interact with another animal:
- If they're from the same species, ignore each other.
- Fox eats rabbit.
"""
if self.species == RABBIT and other.species == FOX:
self.die()
elif self.species == FOX and other.species == RABBIT:
other.die()
def die(self):
"R.I.P"
self.isDead = True
def move(self, direction):
"""Move a step on the grid. Each step consumes 1 energy; if no energy left, die.
If hitting the bounds of the grid, "bounde back", step to the opposite direction insetad.
Arguments:
direction {int} -- direction to move: UP: 0, DOWN: 1, LEFT: 2, RIGHT: 3, STAY: 4
"""
self.energy -= 1
if direction == LEFT:
self.x += 1 if self.x > 0 else -1 #"bounce back"
if direction == RIGHT:
self.x -= 1 if self.x < gridxsize-1 else -1
if direction == UP:
self.y += 1 if self.y < gridysize-1 else -1
if direction == DOWN:
self.y -= 1 if self.y > 0 else -1
if direction == STAY:
pass
if self.energy <= 0:
self.die() #R.I.P.
animals = [] # this will contain all animals on the grid
# all possible coordinate pair (following https://stackoverflow.com/a/11144716/5099168)
xcoords = np.arange(gridxsize)
ycoords = np.arange(gridysize)
coords = np.transpose([np.tile(xcoords, len(ycoords)), np.repeat(ycoords, len(xcoords))])
# populate grid randomly, unique coordinates for all animals
randcoords = np.random.permutation(coords)
rabbitcoords = randcoords[:nrabbits]
foxcoords = randcoords[nrabbits:(nrabbits + nfoxes)]
for (x, y) in rabbitcoords:
animals.append(Animal(x0=x, y0=y, init_energy=rabben, species=RABBIT))
for (x, y) in foxcoords:
animals.append(Animal(x0=x, y0=y, init_energy=foxen, species=FOX))
t_rabcoordsx = [] # track the coordinates of the animals in each step in these arrays
t_rabcoordsy = []
t_foxcoordsx = []
t_foxcoordsy = []
rabbitnums, foxnums = [nrabbits], [nfoxes] #track the number of rabbits and foxes too
animfigs = []
for i in prbar(range(steps), max_value = steps, redirect_stdout=True): # NOTE: substitute with for i in range(steps) if progressbar2 is not installed
# step with each animal in a random direction
directions = np.random.randint(0, 5, size=len(animals))
for animal, direction in zip(animals, directions):
animal.move(direction)
# generate newborn rabbits...
rabbit_is_born_here = np.random.rand(len(coords)) <= rabbit_newborn_chance
newrabbits = coords[rabbit_is_born_here]
for (x, y) in newrabbits:
animals.append(Animal(x0=x, y0=y, init_energy=rabben, species=RABBIT))
#... and foxes
fox_is_born_here = np.random.rand(len(coords)) <= fox_newborn_chance
newfoxes = coords[fox_is_born_here]
for (x, y) in newfoxes:
animals.append(Animal(x0=x, y0=y, init_energy=foxen, species=FOX))
# interact if two animals are at the same coordinates
for j, animal1 in enumerate(animals):
for animal2 in animals[j:]:
if (animal1.x == animal2.x and
animal1.y == animal2.y):
animal1.interact(animal2)
# clean up corpses
dead_indexes = []
for j, animal in enumerate(animals):
if animal.isDead:
dead_indexes.append(j)
animals = list(np.delete(animals, dead_indexes))
# count animals and log
foxnum, rabnum = 0,0
for animal in animals:
if animal.species == RABBIT:
rabnum += 1
elif animal.species == FOX:
foxnum += 1
rabbitnums.append(rabnum)
foxnums.append(foxnum)
# print(rabnum, foxnum, len(dead_indexes))
# get and log animal coordinates
rabcsx = []
rabcsy = []
foxcsx = []
foxcsy = []
for animal in animals:
if animal.species == RABBIT:
rabcsx.append(animal.x)
rabcsy.append(animal.y)
# ax.plot(, animal.y, 'bo')
elif animal.species == FOX:
foxcsx.append(animal.x)
foxcsy.append(animal.y)
# ax.plot(animal.x, animal.y, 'ro')
t_rabcoordsx.append(rabcsx)
t_rabcoordsy.append(rabcsy)
t_foxcoordsx.append(foxcsx)
t_foxcoordsy.append(foxcsy)
#Display the movement on an animation
fig, ax = plt.subplots()
fig.suptitle("Hunger Games")
ax.set_xlim(0, gridxsize-1)
ax.set_ylim(0, gridysize-1)
ax.set_xticks(xcoords)
ax.set_yticks(ycoords)
plt.grid(True)
rabpc, = ax.plot(t_rabcoordsx[0], t_rabcoordsy[0], 'bo', label='rabbit')
foxpc, = ax.plot(t_foxcoordsx[0], t_foxcoordsy[0], 'ro', label='fox')
fig.legend()
txt = ax.text(0.1, 0.1,'', ha='center', va='center', alpha=0.8,
transform=ax.transAxes, fontdict={'color':'black', 'backgroundcolor': 'white', 'size': 10})
#initialize the animation:
def anim_init():
rabpc.set_data(t_rabcoordsx[0], t_rabcoordsy[0])
foxpc.set_data(t_foxcoordsx[0], t_foxcoordsy[0])
txt.set_text('rabbits: {}\nfoxes:{}'.format(rabbitnums[0], foxnums[0]))
return rabpc, foxpc, txt
#update the plot to the i-th frame:
def animate(i):
rabpc.set_data(t_rabcoordsx[i], t_rabcoordsy[i])
foxpc.set_data(t_foxcoordsx[i], t_foxcoordsy[i])
txt.set_text('rabbits: {}\nfoxes:{}'.format(rabbitnums[i], foxnums[i]))
return rabpc, foxpc, txt
#construct and display the animation
im_ani = animation.FuncAnimation(fig, animate, init_func=anim_init, frames=steps,
interval=500, repeat=False, save_count=10, blit=True)
plt.show()
#plot population vs time
plt.plot(rabbitnums, 'b-', label="rabbits",)
plt.plot(foxnums, 'r-', label="foxes")
plt.xlabel('t')
plt.ylabel('population')
plt.suptitle("Population VS time")
plt.legend()
plt.show()
#plot rabbuts vs foxes
plt.suptitle("Rabbit vs fox population")
plt.plot(rabbitnums, foxnums)
plt.xlabel('rabbits')
plt.ylabel('foxes')
plt.show()
</code></pre>
<p>Sample output:
<a href="https://i.stack.imgur.com/0RyCy.png" rel="noreferrer"><img src="https://i.stack.imgur.com/0RyCy.png" alt="grid image"></a>
<a href="https://i.stack.imgur.com/lKK43.png" rel="noreferrer"><img src="https://i.stack.imgur.com/lKK43.png" alt="popt"></a>
<a href="https://i.stack.imgur.com/NBtFw.png" rel="noreferrer"><img src="https://i.stack.imgur.com/NBtFw.png" alt="enter image description here"></a></p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-07T16:20:37.510",
"Id": "448547",
"Score": "1",
"body": "It would be interesting if procreation could only happen if two animals of the same species meet, costs energy, and can result in more than one offspring (with different distributions for rabbits and foxes)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-08T06:12:04.990",
"Id": "448621",
"Score": "0",
"body": "You say adding new species is fairly simple, but with the current code structure I'd have my doubts."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-09T09:49:34.907",
"Id": "448821",
"Score": "0",
"body": "@Mast Right, maybe no-brainer would be a better choice of words. It indeed could be made more extendable."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-11T04:10:50.347",
"Id": "507543",
"Score": "0",
"body": "Next add grass to the model, for the sheep. Full ecosystem."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-11T15:28:48.673",
"Id": "507603",
"Score": "0",
"body": "@FMc Should be straightforward. It's just an animal who doesn't move, after all..."
}
] |
[
{
"body": "<h2>Shebang</h2>\n\n<pre><code>#!/opt/anaconda3/bin/python\n</code></pre>\n\n<p>This is suspicious. Usually you should just</p>\n\n<pre><code>#!/usr/bin/env python\n</code></pre>\n\n<p>and make sure that your environment uses the correct Python. Among other things, it'll make it easier for you to switch to system Python if you need it.</p>\n\n<h2>Enums</h2>\n\n<pre><code>RABBIT = 0\nFOX = 1\n</code></pre>\n\n<p>It's good that you're assigning symbols for these values, but you should consider taking it a step further and using <a href=\"https://docs.python.org/3/library/enum.html\" rel=\"noreferrer\">https://docs.python.org/3/library/enum.html</a> .</p>\n\n<h2>Encapsulation</h2>\n\n<p>Rather than these variables</p>\n\n<pre><code># initial number of rabbits and foxes\nnrabbits = 10\nnfoxes = 5\n\n# energy of a freshly spawned rabbit/fox\nrabben = 20\nfoxen = 20\n\n# chance of a new fox/rabbit being spawned at a gridpoint on a step\nrabbit_newborn_chance = 0.01\nfox_newborn_chance = 0.01\n</code></pre>\n\n<p>being tracked individually, consider making a <code>Species</code> class with two instances, each having the above attributes. You can then factor out a lot of common code.</p>\n\n<h2>Type hinting</h2>\n\n<p>PEP484 type hints can help, here; for instance:</p>\n\n<pre><code>def __init__(self, x0: int, y0: int, init_energy: float, species: int):\n</code></pre>\n\n<p>though the type for that <code>species</code> would change if you make it an <code>Enum</code>.</p>\n\n<h2>Variable names</h2>\n\n<pre><code>isDead\n</code></pre>\n\n<p>should be</p>\n\n<pre><code>is_dead\n</code></pre>\n\n<h2>No-op branches</h2>\n\n<p>This can be deleted:</p>\n\n<pre><code> if direction == STAY:\n pass\n</code></pre>\n\n<h2>Global code</h2>\n\n<p>Your <code>Animal</code> class is a good start. You should move the global-scoped code starting with <code>animals = []</code> into functions, as well.</p>\n\n<h2>Scaling</h2>\n\n<pre><code># interact if two animals are at the same coordinates\nfor j, animal1 in enumerate(animals):\n for animal2 in animals[j:]:\n if (animal1.x == animal2.x and\n animal1.y == animal2.y):\n animal1.interact(animal2)\n</code></pre>\n\n<p>This will get slow as you scale up to larger and larger grid sizes. Consider maintaining a nested grid list tracking where all of your animals are. <a href=\"https://wiki.python.org/moin/TimeComplexity\" rel=\"noreferrer\">List lookup is O(1)</a> so this will be fast, and you won't have to compare all animal coordinates, which seems to be O(n^2).</p>\n\n<h2>Data vis</h2>\n\n<p>Your <em>Rabbit vs fox population</em> graph is cool, but it quickly becomes muddied when the system converges. This should be re-represented with another dimension, either density or time. There are many approaches to this - you could decrease the opacity of the line, or you could show a heat map, or you could make the colour of the line parametric on time and use a jet pallette so that it becomes clearer where convergence is.</p>\n\n<p>Another option is to show your <em>population vs time</em> graph with the series smoothed and confidence intervals shown; an example is shown here - <a href=\"https://stackoverflow.com/questions/27164114/show-confidence-limits-and-prediction-limits-in-scatter-plot\">https://stackoverflow.com/questions/27164114/show-confidence-limits-and-prediction-limits-in-scatter-plot</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-07T18:08:20.917",
"Id": "230330",
"ParentId": "230311",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "230330",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-07T14:13:16.617",
"Id": "230311",
"Score": "12",
"Tags": [
"python",
"python-3.x",
"simulation",
"data-visualization",
"matplotlib"
],
"Title": "Predator-prey simulation"
}
|
230311
|
<p>I would like to record a list of the most recent values passed as props to a React component, <em>including</em> the current one. This list will be passed as props to a child component (a time series chart, which will show the last N values). </p>
<p>To do this, I made a custom hook <code>useDataWindow</code>:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="true">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const { useCallback, useRef, useState, useEffect } = React;
function useDataWindow(length) {
return useCallback(
(datum) => {
const [data, setData] = useState([]);
useEffect(
() => {
setData([...data, datum].slice(-length));
},
[datum, length]
);
return data;
},
[length]
);
}
function App({ value }) {
const dataWindow = useDataWindow(3);
const items = dataWindow(value);
return (
<ul>
{items.map((item, i) => <li key={i}>{item}</li>)}
</ul>
);
}
for (let i = 1; i <= 4; ++i) {
ReactDOM.render(<App value={i} />, document.getElementById("root"));
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.10.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.10.2/umd/react-dom.production.min.js"></script>
<div id="root"></div></code></pre>
</div>
</div>
</p>
<p>The <code><App /></code> component is passed the values <code>1, 2, 3, 4</code> and displays the 3 most recent values, so this appears to do what I want, but is this the "right way to do it"? It seems weird to call <code>setData</code> in every render (which I guess is triggering a re-render). </p>
<p>I tried to do it without <code>useState</code>, but this leaves me with the <em>previous</em> values, <em>not including</em> the current one:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="true">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const { useCallback, useRef, useState, useEffect } = React;
function useDataWindow(length) {
return useCallback(
(datum) => {
const data = useRef([]);
useEffect(
() => {
data.current = [...data.current, datum].slice(-length);
},
[datum, length]
);
return data.current;
},
[length]
);
}
function App({ value }) {
const dataWindow = useDataWindow(3);
const items = dataWindow(value);
return (
<ul>
{items.map((item, i) => <li key={i}>{item}</li>)}
</ul>
);
}
for (let i = 1; i <= 4; ++i) {
ReactDOM.render(<App value={i} />, document.getElementById("root"));
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.10.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.10.2/umd/react-dom.production.min.js"></script>
<div id="root"></div></code></pre>
</div>
</div>
</p>
<p>Is the first approach a good idea, and if not:</p>
<ul>
<li>is there a way to fix the second approach to make it include the current value?</li>
<li>is there a more sensible way to do what I want which I have overlooked?</li>
</ul>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-07T15:31:44.977",
"Id": "230315",
"Score": "1",
"Tags": [
"javascript",
"react.js"
],
"Title": "Custom React hook to store a sample window"
}
|
230315
|
<p>In an application that I built recently, I needed to persist several variables, without loosing their state, for duration that the application was in use. After some research, I found <a href="https://stackoverflow.com/questions/38952243/in-excel-vba-how-to-persist-key-variables-over-a-state-loss-without-writing-t/38956839#38956839">this</a> post on StackOverflow that led me in the right direction and from there I encapsulated that logic into a class. </p>
<p>I have tested this with custom classes and it works as intended. Note that the class is Pre-Declared (i.e. <code>Attribute VB_PredeclaredId = True</code>) because I wanted this to function more or less like Access's <code>TempVars</code> object, which does not have to be "Newed-up" to obtain availability to properties/methods.</p>
<p>To use this class you must add references to the <code>Common Language Runtime Execution Engine 2.4 Library</code> and the <code>mscorlib.dll</code> respectively. Below I have provided the code to the add those pro-grammatically, as neither are easy to find in the References listing. </p>
<p>As for feedback, I am looking to make sure that my implementation is not implicitly causing some sort of a memory leak (kind of an important factor, ha). As per the link posted above, the object should only persist for the duration that Excel is open. That being said, If you plan to use this class in one of your projects, you need to call the <code>RemoveAll</code> method during the <code>Workbook_BeforeClose</code> event. You have to remember that the user may close your application, but leave other instances of Excel open, which means that the <code>AppSessionVariables</code> would still be "alive". If the user were to close excel entirely, then Session Variables would be cleared and you needn't worry, but that's only in a perfect world, and we developers know more than anyone that no such world exists. </p>
<p><strong>Class: AppSessionVariables</strong></p>
<pre><code>VERSION 1.0 CLASS
BEGIN
MultiUse = -1 'True
END
Attribute VB_Name = "AppSessionVariables"
Attribute VB_GlobalNameSpace = False
Attribute VB_Creatable = False
Attribute VB_PredeclaredId = True
Attribute VB_Exposed = False
Option Explicit
Private Const APP_SESSION_VARIABLES_NAME As String = "APP_SESSION_VARIABLES"
Public Enum AppSessionVariablesError
Error_AlreadyExists = vbObjectError + 1042
Error_DoesNotExist
End Enum
Private Type TAppSessionVariables
dictSessionVars As Object
End Type
Private this As TAppSessionVariables
Private Sub Class_Initialize()
If this.dictSessionVars Is Nothing Then Set this.dictSessionVars = GetPersistentDictionary()
End Sub
Private Function GetPersistentDictionary() As Object
Dim host As mscoree.CorRuntimeHost
Dim domain As mscorlib.AppDomain
Dim dict As Object
Set host = New mscoree.CorRuntimeHost
host.Start
host.GetDefaultDomain domain
If IsObject(domain.GetData(APP_SESSION_VARIABLES_NAME)) Then
Set dict = domain.GetData(APP_SESSION_VARIABLES_NAME)
Else
Set dict = CreateObject("Scripting.Dictionary")
domain.SetData APP_SESSION_VARIABLES_NAME, dict
End If
Set GetPersistentDictionary = dict
End Function
Public Sub Add(ByVal Name As String, ByVal Value As Variant)
ThrowIfAlreadyExists Name
If IsObject(Value) Then
Set this.dictSessionVars(Name) = Value
Else
this.dictSessionVars(Name) = Value
End If
End Sub
Public Function Exists(ByVal Name As String) As Boolean
Exists = this.dictSessionVars.Exists(Name)
End Function
Public Sub Remove(ByVal Name As String)
On Error Resume Next
this.dictSessionVars.Remove Name
End Sub
Public Sub RemoveAll()
this.dictSessionVars.RemoveAll
End Sub
Public Function Item(ByVal Name As String) As Variant
ThrowIfDoesNotExist Name
If IsObject(this.dictSessionVars(Name)) Then
Set Item = this.dictSessionVars(Name)
Else
Item = this.dictSessionVars(Name)
End If
End Function
Public Function Count() As Long
Count = this.dictSessionVars.Count
End Function
Private Sub ThrowIfAlreadyExists(ByVal Name As String)
If Exists(Name) Then
Err.Raise AppSessionVariablesError.Error_AlreadyExists, TypeName(Me), _
"This Variable already exists."
End If
End Sub
Private Sub ThrowIfDoesNotExist(ByVal Name As String)
If Not Exists(Name) Then
Err.Raise AppSessionVariablesError.Error_DoesNotExist, TypeName(Me), _
"This does not exist."
End If
End Sub
</code></pre>
<p><strong>Adding the References:</strong> </p>
<p>Place the following in a regular module and run<code>CheckAndFixReferences</code></p>
<pre><code>Private Const MSCOREE_GUID As String = "{5477469E-83B1-11D2-8B49-00A0C9B7C9C4}"
Private Const MSCOREE_MAJOR_VERSION As Long = 2
Private Const MSCOREE_MINOR_VERSION As Long = 4
Private Const MSCORLIB_GUID As String = "{BED7F4EA-1A96-11D2-8F08-00A0C9A6186D}"
Private Const MSCORLIB_MAJOR_VERSION As Long = 2
Private Const MSCORLIB_MINOR_VERSION As Long = 4
Private Sub CheckAndFixReferences()
AddIfNotExists MSCOREE_GUID, MSCOREE_MAJOR_VERSION, MSCOREE_MINOR_VERSION
AddIfNotExists MSCORLIB_GUID, MSCORLIB_MAJOR_VERSION, MSCORLIB_MINOR_VERSION
End Sub
Private Sub AddIfNotExists(ByVal Guid As String, MajorVersion As Long, MinorVersion As Long)
Const ErrorAlreadyExists As Long = 32813
On Error GoTo ReferenceAlreadyExists
ThisWorkbook.VBProject.References.AddFromGuid Guid, MajorVersion, MinorVersion
CleanExit:
Exit Sub
ReferenceAlreadyExists:
If Err.Number = ErrorAlreadyExists Then Resume CleanExit
End Sub
</code></pre>
<p><strong>Usage:</strong> </p>
<p>For the purpose of testing, you can create the following simple class: </p>
<pre><code>**Class: TestClass**
Option Explicit
Private Type TTestClass
PropertyOne As Boolean
End Type
Private this As TTestClass
Public Property Let PropertyOne(ByVal value As Boolean)
this.PropertyOne = value
End Property
Public Property Get PropertyOne() As Boolean
PropertyOne = this.PropertyOne
End Property
</code></pre>
<p>And then place and run the following subs in a module: </p>
<pre><code>Private Sub SetVariable()
Dim TestObject As TestClass
Set TestObject = New TestClass
TestObject.PropertyOne = True
If Not AppSessionVariables.Exists("TestObject") Then
AppSessionVariables.Add "TestObject", TestObject
End If
If Not AppSessionVariables.Exists("TestVar") Then
AppSessionVariables.Add "TestVar", "TestVar"
End If
End Sub
Private Sub GetVariable()
Debug.Assert AppSessionVariables.Item("TestObject").PropertyOne
Debug.Print AppSessionVariables.Item("TestVar")
AppSessionVariables.RemoveAll
End Sub
</code></pre>
|
[] |
[
{
"body": "<p>The <code>dictSessionVars</code> is initialized together with the default instance of the class:</p>\n\n<blockquote>\n<pre><code>Private Sub Class_Initialize()\n If this.dictSessionVars Is Nothing Then Set this.dictSessionVars = GetPersistentDictionary()\nEnd Sub\n</code></pre>\n</blockquote>\n\n<p>That's great, because it ensures you always have a valid managed storage.</p>\n\n<blockquote>\n <p>That being said, If you plan to use this class in one of your\n projects, you need to call the <code>RemoveAll</code> method during the\n <code>Workbook_BeforeClose</code> event.</p>\n</blockquote>\n\n<p>Ok. Consider this code:</p>\n\n<pre><code>Dim borked As AppSessionVariables\nSet borked = New AppSessionVariables '<~ initialize handler runs here, before LHS gets the reference\n\nborked.Add \"Leak\", \"Leak\"\nSet borked = Nothing '<~ no terminate handler, any instance state is leaked memory\n\nSet borked = AppSessionVariables '<~ default instance ref.\nborked.Add \"Leak?\", \"Leak?\"\nSet borked = Nothing '<~ instance state is destroyed, but managed AppDomain is still up\n\n'initialize handler runs again here, before .Add is invoked:\nborked.Add \"Leak?\", \"Leak?\" '<~ should fail to add existing key\n</code></pre>\n\n<p>How many <code>CorRuntimeHost</code> instances are running at that point?</p>\n\n<p>I think the class should have a <code>Terminate</code> handler, and the <code>CorRuntimeHost</code> object reference should be persisted at instance level, and cleanly stopped in the terminate handler.</p>\n\n<p><strong>The class should throw errors if it is initialized as a non-default instance</strong>. That way <code>Set foo = New AppSessionVariables</code> would throw an error before <code>foo</code> even gets ahold of the object reference, and a new <code>CorRuntimeHost</code> wouldn't be created in that case; invoking this upon entering any <code>Public</code> member should do:</p>\n\n<pre><code>Private Sub ThrowIfNonDefaultInstance()\n If Not Me Is AppSessionVariables Then\n Err.Raise AppSessionVariablesError.Error_NonDefaultInstance, Typename(Me), \"Use the default instance, not a new one.\"\n End If\nEnd Sub\n</code></pre>\n\n<blockquote>\n <p>I am looking to make sure that my implementation is not implicitly causing some sort of a memory leak</p>\n</blockquote>\n\n<p>The problem is that the memory leak is pretty much a feature here: you <em>want</em> the data to outlive your class instance.</p>\n\n<p>I've personally never encountered a single use case for this behavior in over 20 years of VBA programming. IMO data that outlives the class that creates it, is <em>by definition</em> a memory leak, and thus boils down to being a Bad Idea™.</p>\n\n<p>When VBA code does this:</p>\n\n<pre><code>Set thing = Nothing\n</code></pre>\n\n<p>The VBA dev has every reason on Earth to believe they have effectively destroyed the object and its encapsulated state.</p>\n\n<p>Even worse - when this instruction is encountered:</p>\n\n<pre><code>End\n</code></pre>\n\n<p>VBA devs should <em>expect</em> <strong>all</strong> global state to cleanly reset.</p>\n\n<p>By design, this <code>AppSessionVariables</code> thwarts these fundamental expectations, and this can easily make using this class more error-prone than it needs to be.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-07T16:38:09.583",
"Id": "448550",
"Score": "0",
"body": "Man, excellent points! In the application I built, I was using this class to persist only string variables (Names of sub-procedures) and If the sub was successfully run, I saved it's name to the session. I did this because I wanted know if they had successfully completed certain tasks before allowing them to continue through to other tasks in that session. I added the ability to persist objects for completeness sake, but I didn't really like the Idea of persisting an entire custom object, lol."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-07T16:44:33.053",
"Id": "448557",
"Score": "0",
"body": "Also, you say \"The class should throw errors if it is initialized as a non-default instance\". How can I do that?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-07T17:06:10.387",
"Id": "448559",
"Score": "1",
"body": "@rickmanalexander see edit, added `ThrowIfNonDefaultInstance`, which leverages the `Is` operator to compare the current instance (`Me`) against the default one (`AppSessionVariables`) and raises an error if the two objects aren't the same."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-06T00:41:31.667",
"Id": "520858",
"Score": "0",
"body": "In my 20+ years pro VBA experience with leading companies, i've had occasions where i needed persistent data. Examples: \"WorkbookWasUpdated\", \"IsCustomerWorkbook\", or \"UserPreference\". However, i don't store such data in variables, so no possibility of memory leak. Rather, i store in hidden workbook names. Names are built into Excel -- no external libraries needed. The persistent data rides with the workbook. I see no reason why couldn't work with serialized objects. Saving to a hidden sheet is another method, but i think hidden names is cleaner and uses less resources than a worksheet."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-07T16:12:22.807",
"Id": "230320",
"ParentId": "230316",
"Score": "3"
}
},
{
"body": "<p>My tests indicate that adding an instance of TTestClass to the AppSessionVariables Dictionary does not survive a state loss.</p>\n\n<pre><code>Private Sub SetVariable()\n Rem ...Code\n End\n\nEnd Sub\n</code></pre>\n\n<p>Adding <strong>End</strong> to <code>SetVariable</code> and then calling <code>GetVariable</code> throws this error:</p>\n\n<p><a href=\"https://i.stack.imgur.com/WzUgn.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/WzUgn.png\" alt=\"Immediate Window\"></a></p>\n\n<p>Simple Key/Value pairs do, however, persist. The values persist even after closing and reopening the workbook. Closing the Excel.Application destroys the reference.</p>\n\n<h2>Saving and Restoring the Object's State</h2>\n\n<p>It should be the responsibility of the class to determine how to save and restore its state. This will not only make it easier to implement but will also allow you to store private field values.</p>\n\n<p>All the classes to be saved should Implement a common Interface which defines the methods used to save and restore the settings. Having each object store its setting in its own dictionary and adding the objects dictionary to the AppSessionVariables's persistent dictionary will encapsulate the objects settings making it easier to work with. </p>\n\n<p>To test my design I created an IVBASerializable Interface and two classes that Implement it. The classes are successfully saved and restored as long as the application is not closed.</p>\n\n<h2>Interface: IVBASerializable</h2>\n\n<pre><code>Attribute VB_Name = \"IVBASerializable\"\n\nOption Explicit\n\nPublic Function Save() As Boolean\nEnd Function\n\nPublic Function Restore() As Boolean\nEnd Function\n\nPublic Property Get Guid() As String\nEnd Property\n\nPublic Property Let Guid(ByVal Value As String)\nEnd Property\n\nPublic Property Get ToString() As String\nEnd Property\n\nPublic Property Get ClassName() As String\nEnd Property\n</code></pre>\n\n<h2>Class: SerializableRange</h2>\n\n<pre><code>Attribute VB_Name = \"SerializableRange\"\n\nOption Explicit\nImplements IVBASerializable\n\nPrivate Type Members\n RangeExternalAddress As String\nEnd Type\n\nPrivate this As Members\nPrivate Created As Date\nPublic Guid As String\n\nPrivate Sub Class_Initialize()\n Created = Date\nEnd Sub\n\nPublic Property Get ClassName() As String\n ClassName = TypeName(Me)\nEnd Property\n\nPrivate Property Get IVBASerializable_ClassName() As String\n IVBASerializable_ClassName = ClassName\nEnd Property\n\nPrivate Property Get IVBASerializable_Guid() As String\n IVBASerializable_Guid = Guid\nEnd Property\n\nPrivate Property Let IVBASerializable_Guid(ByVal Value As String)\n Guid = Value\nEnd Property\n\nPrivate Property Get IVBASerializable_ToString() As String\n Dim Values(3) As String\n Values(0) = \"Address: \" & this.RangeExternalAddress\n Values(1) = \"Row Count: \" & Range.Rows.Count\n Values(2) = \"Column Count: \" & Range.Columns.Count\n Values(3) = \"Created: \" & Created\n\n IVBASerializable_ToString = Join(Values, vbNewLine)\nEnd Property\n\nPublic Property Get Range() As Range\n Set Range = Application.Range(this.RangeExternalAddress)\nEnd Property\n\nPublic Property Let Range(ByVal newRange As Range)\n this.RangeExternalAddress = newRange.Address(External:=True)\nEnd Property\n\nPublic Property Get Self() As SerializableRange\n Set Self = Me\nEnd Property\n\n\n\nPrivate Function IVBASerializable_Restore() As Boolean\n IVBASerializable_Restore = Restore\nEnd Function\n\nPrivate Function IVBASerializable_Save() As Boolean\n IVBASerializable_Save = Save\nEnd Function\n\nPublic Function Restore() As Boolean\n If AppSessionVariables.Exists(Guid) Then\n Dim Map As Scripting.Dictionary\n Set Map = AppSessionVariables.Item(Guid)\n Map(\"Created\") = Created\n this.RangeExternalAddress = Map(\"RangeExternalAddress\")\n End If\nEnd Function\n\nPublic Function Save() As Boolean\n If Len(Guid) > 0 Then\n Dim Map As New Scripting.Dictionary\n Map(\"RangeExternalAddress\") = this.RangeExternalAddress\n Map(\"Created\") = Created\n AppSessionVariables.Add Guid, Map\n End If\nEnd Function\n</code></pre>\n\n<h2>Class: SerializableSize</h2>\n\n<pre><code>Attribute VB_Name = \"SerializableSize\"\n\nOption Explicit\nImplements IVBASerializable\n\nPrivate Type Members\n Guid As String\n Shape As Shape\nEnd Type\n\nPrivate this As Members\nPublic Guid As String\nPrivate Created As Date\nPublic Width As Single\nPublic Height As Single\n\nPrivate Sub Class_Initialize()\n Created = Date\nEnd Sub\n\nPublic Property Get ClassName() As String\n ClassName = TypeName(Me)\nEnd Property\n\nPrivate Property Get IVBASerializable_ClassName() As String\n IVBASerializable_ClassName = ClassName\nEnd Property\n\nPrivate Property Get IVBASerializable_Guid() As String\n IVBASerializable_Guid = Guid\nEnd Property\n\nPrivate Property Let IVBASerializable_Guid(ByVal Value As String)\n Guid = Value\nEnd Property\n\nPrivate Property Get IVBASerializable_ToString() As String\n Dim Values(2) As String\n Values(0) = \"Width: \" & Width\n Values(1) = \"Height: \" & Height\n Values(2) = \"Created: \" & Created\n\n IVBASerializable_ToString = Join(Values, vbNewLine)\nEnd Property\n\nPublic Property Get Self() As SerializableSize\n Set Self = Me\nEnd Property\n\nPrivate Function IVBASerializable_Restore() As Boolean\n IVBASerializable_Restore = Restore\nEnd Function\n\nPrivate Function IVBASerializable_Save() As Boolean\n IVBASerializable_Save = Save\nEnd Function\n\nPublic Function Restore() As Boolean\n If AppSessionVariables.Exists(Guid) Then\n Dim Map As Scripting.Dictionary\n Set Map = AppSessionVariables.Item(Guid)\n Width = Map(\"Width\")\n Height = Map(\"Height\")\n End If\nEnd Function\n\nPublic Function Save() As Boolean\n If Len(Guid) > 0 Then\n Dim Map As New Scripting.Dictionary\n Map(\"Created\") = Created\n Map(\"Width\") = Width\n Map(\"Height\") = Height\n AppSessionVariables.Add Guid, Map\n End If\nEnd Function\n</code></pre>\n\n<h2>UnitTest</h2>\n\n<pre><code>Option Explicit\nPublic Enum DefaultSerializables\n Range1\n Range2\n Size1\n Size2\n [_First] = Range1\n [_Last] = Size2\nEnd Enum\n\nPublic Serializables() As IVBASerializable\n\nPublic Sub TestPart1()\n InitSerializables\n SaveSerializables\n Debug.Print \"TestPart1\"\n PrintSerializables\n Erase Serializables\n End\nEnd Sub\n\nPublic Sub TestPart2()\n Debug.Print\n Debug.Print \"TestPart2\"\n RestoreSerializables\n PrintSerializables\nEnd Sub\n\nPrivate Sub InitSerializables()\n ReDim Serializables(0 To DefaultSerializables.[_Last])\n\n With New SerializableRange\n Set Serializables(Range1) = .Self\n .Guid = .ClassName & \";\" & Range1\n .Range = Sheet1.Range(\"A1:C20\")\n End With\n\n With New SerializableRange\n Set Serializables(Range2) = .Self\n .Guid = .ClassName & \";\" & Range2\n .Range = Sheet1.Range(\"AA1:AC20\")\n End With\n\n With New SerializableSize\n Set Serializables(Size1) = .Self\n .Guid = .ClassName & \";\" & Size1\n .Height = Sheet1.Shapes(1).Height\n .Width = Sheet1.Shapes(1).Width\n End With\n\n With New SerializableSize\n Set Serializables(Size2) = .Self\n .Guid = .ClassName & \";\" & Size2\n .Height = Sheet1.Shapes(2).Height\n .Width = Sheet1.Shapes(2).Width\n End With\n\nEnd Sub\n\nSub SaveSerializables()\n Dim n As Long\n For n = DefaultSerializables.[_First] To DefaultSerializables.[_Last]\n Serializables(n).Save\n Next\nEnd Sub\n\nSub RestoreSerializables()\n ReDim Serializables(0 To DefaultSerializables.[_Last])\n\n With New SerializableRange\n Set Serializables(Range1) = .Self\n .Guid = .ClassName & \";\" & Range1\n .Restore\n End With\n\n With New SerializableRange\n Set Serializables(Range2) = .Self\n .Guid = .ClassName & \";\" & Range2\n .Restore\n End With\n\n With New SerializableSize\n Set Serializables(Size1) = .Self\n .Guid = .ClassName & \";\" & Size1\n .Restore\n End With\n\n With New SerializableSize\n Set Serializables(Size2) = .Self\n .Guid = .ClassName & \";\" & Size2\n .Restore\n End With\nEnd Sub\n\nSub PrintSerializables()\n Dim n As Long\n For n = DefaultSerializables.[_First] To DefaultSerializables.[_Last]\n Debug.Print Serializables(n).ToString\n Next\nEnd Sub\n</code></pre>\n\n<h2>Test Results</h2>\n\n<p><a href=\"https://i.stack.imgur.com/UQl7n.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/UQl7n.png\" alt=\"Test Results\"></a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-08T11:21:57.170",
"Id": "448655",
"Score": "0",
"body": "I foolishly did not think of testing with the `End` statement, which forces state loss. This situation could easily occur if an unhandled error was thrown. \"It should be the responsibility of the class to determine how to save and restore its state\", excellent point and I totally agree. I also quite like the idea of using an interface here too."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-09T06:47:48.647",
"Id": "448793",
"Score": "0",
"body": "IIRC, the `End` statement actually removes the class definition, not the instance of the object in memory. I may be wrong, but I believe an instance of a non user defined class like `Scripting.Dictionary` should be persisted. (Edit: see [here](https://stackoverflow.com/q/57560124/6609896))"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-09T10:00:19.007",
"Id": "448823",
"Score": "0",
"body": "@Greedo You are correct. The OP is using a Scripting.Dictionary. Values that are not destroyed by Stop or End do persist. Your comment lead me to test a Range and it also persisted. In case you want to test it out, here is the file [download](https://drive.google.com/open?id=17Fg2iwdQy91Y3UKSQvPzWXwg22ZCEZEN)"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-08T07:02:24.240",
"Id": "230358",
"ParentId": "230316",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "230320",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-07T15:33:37.320",
"Id": "230316",
"Score": "3",
"Tags": [
"vba",
"excel",
"state"
],
"Title": "Persisting Variables Over A State Loss"
}
|
230316
|
<p>Labelling <code>Traversable</code> containers is an ancient and honorable test of skill. My task here is to create a <strong>generic labelling mechanism</strong> for a <code>Bitraversable</code>, such as a tuple, or a graph with vertex and edge labels.</p>
<pre><code>bilabelWith
:: Bitraversable t
=> (l -> indexl -> l') -> (r -> indexr -> r')
-> Stream indexl -> Stream indexr
-> t l r -> t l' r'
bilabelWith f g xs ys =
let labelLeft = fmap (withStateLens fst (\(_, y) x' -> (x', y))) (labelOneWith f)
labelRight = fmap (withStateLens snd (\(x, _) y' -> (x, y'))) (labelOneWith g)
in flip evalState (xs, ys) . bitraverse labelLeft labelRight
labelOneWith :: (a -> index -> b) -> a -> State (Stream index) b
labelOneWith f u = do
(Stream.Cons x xs) <- get
put xs
return (f u x)
withStateLens :: (s -> t) -> (s -> t -> s) -> State t a -> State s a
withStateLens thrust merge u = do
s <- get
let t = thrust s
let (r, t') = runState u t
put (merge s t')
return r
</code></pre>
<p> </p>
<p><strong>Here is how it may be applied:</strong></p>
<pre><code>λ bilabelWith (+) (*) (Stream.fromList [2]) (Stream.fromList [3]) (5, 7)
(7,21)
</code></pre>
<p>A more complicated example requires us to obtain a <code>Bitraversable</code> graph.</p>
<pre><code>circular :: (DynGraph gr, Bitraversable gr) => gr a b -> gr (V2 Double, a) b
circular gr =
let n = fromIntegral (Graph.noNodes gr)
coords =
let alpha = (pi * 2 / n)
in Stream.prefix [ 0.8 * V2 (sin (alpha * i)) (cos (alpha * i)) | i <- [1.. n] ]
$ error "circular: Impossible error: not enough coordinates to label all points."
in bilabelWith (flip (,)) const coords (Stream.repeat ()) gr
</code></pre>
<p> </p>
<p><strong>Does this code make sense?</strong> Is there anything to make more compact or clarify?</p>
|
[] |
[
{
"body": "<p>The <code>fmap</code> in <code>labelLeft</code> should be <code>(.)</code>. <code>Control.Lens.Zoom</code> provides something like <code>withStateLens</code>. Inline definitions that are only used once.</p>\n\n<pre><code>bilabelWith\n :: Bitraversable t\n => (l -> indexl -> l') -> (r -> indexr -> r')\n -> Stream indexl -> Stream indexr\n -> t l r -> t l' r'\nbilabelWith f g xs ys = flip evalState (xs, ys) .\n bitraverse (zoom _1 . pops . f) (zoom _2 . pops . g)\n\npops :: (s -> a) -> State (Stream s) a\npops = flip fmap $ state $ \\(Stream.Cons x xs) -> (x, xs)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-18T11:55:30.780",
"Id": "450125",
"Score": "0",
"body": "Thanks. Looks nice. Can you explain the `pops` part in more detail?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-18T12:58:19.470",
"Id": "450139",
"Score": "0",
"body": "`\\(Stream.Cons x xs) -> (x, xs)` should be `Stream.uncons`. `state` produces simple `State` objects. `pop = state Stream.uncons` is a usual name for taking the front item off a queue. `s` is a usual suffix to add a hook of form `s -> a`, see `gets` or `uses`. `pops f = fmap f pop`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-18T13:05:44.843",
"Id": "450140",
"Score": "0",
"body": "I see. Perhaps in pointy style it would have been more readable."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-18T00:47:53.393",
"Id": "230929",
"ParentId": "230321",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "230929",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-07T16:31:11.773",
"Id": "230321",
"Score": "0",
"Tags": [
"haskell"
],
"Title": "Apply labels from a stream to a Bitraversable"
}
|
230321
|
<p>I have created a clock divider that works as follows:</p>
<ul>
<li>If the division factor is 0, pass the clock through unchanged.</li>
<li>Otherwise, flip the output clock signal after the specified number of input clock cycles has passed.</li>
</ul>
<p>I am relatively new to hardware design, so I would like advice on general best practices that I may have violated, as well as whether there would be any robustness issues. (I know that the output clock will be delayed since it passes through gates, but I don't think this is a problem as long as downstream logic does not attempt to use both clocks simultaneously.)</p>
<pre><code>library IEEE;
use IEEE.STD_LOGIC_1164.ALL;
use IEEE.NUMERIC_STD.ALL;
entity config_clk_div is
Port ( clk : in STD_LOGIC;
divfactor : in STD_LOGIC_VECTOR (15 downto 0);
clkout : out STD_LOGIC);
end config_clk_div;
architecture Behavioral of config_clk_div is
signal clk_counter : UNSIGNED(15 downto 0);
signal current_clk : STD_LOGIC;
begin
process (clk, divfactor) is
begin
if divfactor = x"0000" then
clkout <= clk;
current_clk <= clk;
else
if rising_edge(clk) then
clk_counter <= clk_counter + 1;
if clk_counter >= unsigned(divfactor) then
clk_counter <= to_unsigned(1,16);
current_clk <= not current_clk;
-- Not here as well to avoid lag
clkout <= not current_clk;
else
clkout <= current_clk;
end if;
end if;
end if;
end process;
end Behavioral;
</code></pre>
|
[] |
[
{
"body": "<p>Yes, there are some issues. </p>\n\n<p>With <code>process (clk, divfactor)</code> you're making it difficult for the synthesis software to generate a nice clocked process. So you should separate the clocked process from the clock multiplexer.</p>\n\n<p>A bigger problem is the clock multiplexer. <code>divfactor</code> is — even <em>if</em> it is synchronous — a 16-bit value, for which all bits have to be checked for 0. This introduces quite some logic, which will always be glitchy... and you're putting it directly into your clock output. danger! danger! A glitchy clock results in undefined behavior... it can even lock your FSMs to an unresolvable state.</p>\n\n<p>Instead check the condition in a clocked process and set a single synchronous output based on its value.</p>\n\n<p>This is how I would write something like this:</p>\n\n<pre><code>library ieee;\nuse ieee.std_logic_1164.all;\n\nentity config_clk_div is\n port (\n clk : in std_logic;\n divfactor : in std_logic_vector (15 downto 0); -- Note this is actually not a factor!\n clkout : out std_logic);\nend entity;\n\narchitecture rtl of config_clk_div is\n use ieee.numeric_std.all;\n signal clk_counter : unsigned(15 downto 0) := (others => '0');\n signal div_clk : std_logic := '1';\n\n signal divider_disabled : std_logic := '0';\nbegin\n process (clk)\n begin\n if rising_edge(clk) then\n if divfactor = x\"0000\" then\n divider_disabled <= '1';\n else\n divider_disabled <= '0';\n if clk_counter = 0 then\n clk_counter <= unsigned(divfactor) - 1;\n div_clk <= not div_clk;\n else\n clk_counter <= clk_counter - 1;\n end if;\n end if;\n end if;\n end process;\n\n clkout <= clk when divider_disabled = '1' else div_clk;\nend architecture;\n</code></pre>\n\n<p>Note: counting down on a counter makes the compare (to 0) a bit easier. Although this makes more of a difference when designing ASICs.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-05T14:26:18.727",
"Id": "231891",
"ParentId": "230323",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "231891",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-07T17:13:34.953",
"Id": "230323",
"Score": "5",
"Tags": [
"state-machine",
"vhdl"
],
"Title": "Hardware Clock Divider"
}
|
230323
|
<p>I was fed up with the default alarm clock when doing laundry. The washing machine is in the basement and takes different time depending on the choosen program. The stopwatch has to be configured for every use and can run only one instance (we also have a tumble dryer). The alarm itself is only for fixed times, not for durations, so I figured I write my own app for this.</p>
<p>The app is working in itself, you can create new 'templates' consisting of a name and duration. You can modify or delete them afterwards. You can start a 'reminder' by tapping one template. Once the time is due a notification is send.</p>
<p>Here is my github where the complete project can be seen: <a href="https://github.com/totoMauz/Reminder/tree/a00006cbd5558a98836c0f95f2bdd3b29978b387" rel="nofollow noreferrer">https://github.com/totoMauz/Reminder</a></p>
<p>I'm looking for feedback on the following:</p>
<ul>
<li>My Kotlin usage as it's my first project</li>
<li>Any misuse of Android patterns, as it's my first app</li>
</ul>
<p>I'm unhappy with the use of the companion objects like this:</p>
<pre><code>class MaintainReminderActivity : AppCompatActivity() {
companion object {
const val TOKEN = "MaintainReminder"
val INTENTS: MutableList<Intent> = ArrayList()
}
...
}
</code></pre>
<p>And one usage of the INTENTS and why it's still static:</p>
<pre><code>class AlarmReceiver : BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent?) {
buildNotification(context, intent)
MaintainReminderActivity.INTENTS.remove(intent)
}
}
</code></pre>
<p>I tried to replace it with Intents and startActivity(ForResult) but somehow couldn't make it work from inside the BroadcastReceiver...</p>
<p>Anotherthing that is bugging me is, that the ActionMode is only showing the Icon, despite the title beeing in the XML:</p>
<pre><code><menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="@+id/template_delete"
android:icon="@drawable/delete"
android:title="@string/action_mode_template_delete" />
<item
android:id="@+id/template_edit"
android:icon="@drawable/edit"
android:title="@string/action_mode_template_edit" />
</menu>
</code></pre>
<p>The ActionMode is invoked like this:</p>
<pre><code>class MaintainTemplatesActivity : AppCompatActivity() {
...
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_maintain_templates)
loadTemplates()
viewManager = LinearLayoutManager(this)
viewAdapter = TemplateAdapter(ITEMS)
(viewAdapter as TemplateAdapter).apply {
onItemClick = { reminder: Reminder ->
triggerAlarm(reminder)
}
onLongItemClick = { reminder: Reminder ->
startActionMode(TemplateActionModeCallback(reminder, this@MaintainTemplatesActivity), ActionMode.TYPE_PRIMARY)
true
}
}
recyclerView = findViewById<RecyclerView>(R.id.rvTemplates).apply {
setHasFixedSize(true)
layoutManager = viewManager
adapter = viewAdapter
}
}
....
}
class TemplateActionModeCallback(val reminder: Reminder, private val templateActivity: MaintainTemplatesActivity) : ActionMode.Callback {
override fun onActionItemClicked(mode: ActionMode, item: MenuItem): Boolean {
return when (item.itemId) {
R.id.template_delete -> {
templateActivity.deleteTemplate(reminder)
mode.finish()
true
}
R.id.template_edit -> {
templateActivity.deleteTemplate(reminder)
val intent = Intent(templateActivity.applicationContext, TemplateActivity::class.java)
intent.putExtra(EXTRA_REMINDER, reminder.name)
intent.putExtra(EXTRA_DURATION, reminder.duration)
templateActivity.startActivityForResult(intent, 1)
mode.finish()
true
}
else -> false
}
}
override fun onCreateActionMode(mode: ActionMode, menu: Menu): Boolean {
val inflater = mode.menuInflater
inflater?.inflate(R.menu.template_menu, menu)
return true
}
override fun onPrepareActionMode(mode: ActionMode, menu: Menu): Boolean {
return false
}
override fun onDestroyActionMode(mode: ActionMode) {}
}
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-07T20:15:04.837",
"Id": "230335",
"Score": "1",
"Tags": [
"android",
"kotlin"
],
"Title": "Multiple Stopwatch App"
}
|
230335
|
<p>I have implemented a class to abstract the process of building a shader program in OpenGL (For now it does not deal with uniforms).</p>
<p>I would like some feedback on the coding style, and more specifically the structure. I have implemented a bunch of small and private methods in the class to handle various aspects of compilation - but I am uncertain of when/where to create small functions, and when to just do it all in once place.</p>
<p><strong>Shader.hpp</strong></p>
<pre><code>#pragma once
#include <GL/glew.h>
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
class Shader
{
public:
enum Type : unsigned int
{
Vertex = GL_VERTEX_SHADER,
Fragment = GL_FRAGMENT_SHADER
};
public:
Shader(std::string vertex_shader_path, std::string fragment_shader_path);
~Shader();
void use();
private:
unsigned int program;
unsigned int vertex_shader;
unsigned int fragment_shader;
private:
std::string get_contents(std::string file_path);
unsigned int create_shader(const char* shader_code, Type shader_type);
unsigned int create_program();
bool check_shader_compilation_status(unsigned int shader);
bool check_program_linking_status(unsigned int program);
void print_error(std::vector<char> error_message, std::string info);
};
</code></pre>
<p><strong>Shader.cpp</strong></p>
<pre><code>#include "Shader.hpp"
Shader::Shader(std::string vertex_shader_path, std::string fragment_shader_path)
{
vertex_shader = create_shader(get_contents(vertex_shader_path).c_str(), Type::Vertex);
fragment_shader = create_shader(get_contents(fragment_shader_path).c_str(), Type::Fragment);
program = create_program();
}
Shader::~Shader()
{
glDeleteShader(vertex_shader);
glDeleteShader(fragment_shader);
glDeleteProgram(program);
}
void Shader::use()
{
glUseProgram(program);
}
std::string Shader::get_contents(std::string file_path)
{
std::ifstream file(file_path);
return std::string(std::istreambuf_iterator<char>(file), std::istreambuf_iterator<char>());
}
unsigned int Shader::create_shader(const char* shader_code, Type shader_type)
{
unsigned int shader = glCreateShader(shader_type);
glShaderSource(shader, 1, &shader_code, nullptr);
glCompileShader(shader);
if (!check_shader_compilation_status(shader))
{
glDeleteShader(shader);
return 0;
}
else
{
return shader;
}
}
unsigned int Shader::create_program()
{
unsigned int program = glCreateProgram();
glAttachShader(program, vertex_shader);
glAttachShader(program, fragment_shader);
glLinkProgram(program);
if (!check_program_linking_status(program))
{
glDeleteProgram(program);
return 0;
}
else
{
return program;
}
}
bool Shader::check_shader_compilation_status(unsigned int shader)
{
int is_compiled = 0;
glGetShaderiv(shader, GL_COMPILE_STATUS, &is_compiled);
if (!is_compiled)
{
int max_length = 0;
glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &max_length);
std::vector<char> error_log(max_length);
glGetShaderInfoLog(shader, max_length, &max_length, &error_log[0]);
print_error(error_log, "Shader compalation failed");
return false;
}
else
{
return true;
}
}
bool Shader::check_program_linking_status(unsigned int program)
{
int is_compiled = 0;
glGetProgramiv(program, GL_LINK_STATUS, &is_compiled);
if (!is_compiled)
{
int max_length = 0;
glGetProgramiv(program, GL_INFO_LOG_LENGTH, &max_length);
std::vector<char> error_log(max_length);
glGetShaderInfoLog(program, max_length, &max_length, &error_log[0]);
print_error(error_log, "Program linking failed");
return false;
}
else
{
return true;
}
}
void Shader::print_error(std::vector<char> error_message, std::string info)
{
std::cout << info << ": ";
for (char letter : error_message)
{
std::cout << letter;
}
}
</code></pre>
<p>Im primairly concered with simply bettering my coding skills - so any suggestions are appreciated.</p>
|
[] |
[
{
"body": "<p><code>std::string</code>s can be passed by <code>const&</code> (or as a <code>std::string_view</code>) rather than by value if we don't need to make a copy, e.g.:</p>\n\n<pre><code>Shader(std::string const& vertex_shader_path, std::string const& fragment_shader_path)\n\nstd::string get_contents(std::string const& file_path);\n\nvoid Shader::print_error(std::vector<char> const& error_message, std::string const& info)\n</code></pre>\n\n<p>Incidentally, using a <code>std::string</code> instead of a <code>std::vector<char></code> for the error message would make printing easier.</p>\n\n<hr>\n\n<p>Member functions that don't change member data should be <code>const</code>.</p>\n\n<pre><code>void use() const;\n</code></pre>\n\n<p>Member functions that don't require access to member data should be <code>static</code>.</p>\n\n<pre><code>static std::string get_contents(std::string const& file_path);\n... and all of the others!\n</code></pre>\n\n<hr>\n\n<p>There are quite a few error cases we have to handle:</p>\n\n<ul>\n<li>File opening fails.</li>\n<li>Reading from the file fails.</li>\n<li>Shader compilation fails.</li>\n<li>Program linking fails.</li>\n</ul>\n\n<p>Currently the code continues attempting to create the shader program when an earlier step fails, even though it won't succeed. This adds complexity, since we have to check that everything will \"work\" (in this case fail gracefully) with our invalid state.</p>\n\n<p>While it might be helpful to show the compilation errors for every shader object, we probably don't want to try linking the program - we'll just be generating an OpenGL error, as well as extra noise from the linking failure in our logs.</p>\n\n<p>Similarly, if we fail to read from a file, we should output an appropriate error message, and not try to compile a shader object or link the program.</p>\n\n<hr>\n\n<p>I'd suggest using the specified OpenGL types for interacting with OpenGL. e.g. <code>GLuint</code> for shader object / program ids, <code>GLint</code> for compile status, etc.</p>\n\n<p>This is safer and more portable, and also makes the purpose of each variable more obvious.</p>\n\n<hr>\n\n<p>We don't need to immediately delete shaders that fail to compile (or programs that fail to link). The <code>Shader</code> class destructor will still do that for us (it might even be useful to keep the ID around for debugging). So we can simpify a bit:</p>\n\n<pre><code>unsigned int Shader::create_shader(const char* shader_code, Type shader_type)\n{\n GLuint shader = glCreateShader(shader_type);\n glShaderSource(shader, 1, &shader_code, nullptr);\n glCompileShader(shader);\n\n check_shader_compilation_status(shader);\n\n return shader;\n}\n</code></pre>\n\n<hr>\n\n<p>This looks fine for a simple shader class, but you might run into a few issues in future:</p>\n\n<ul>\n<li><p>A shader object can be composed from multiple shader source strings / files (which is very useful to avoid unnecessary duplication of shader code).</p></li>\n<li><p>There are other types of shader object (tessellation control / evaluation, geometry, compute) that may or may not be present in the shader program.</p></li>\n</ul>\n\n<p>It would be more flexible to load the shader sources from their files outside of the <code>Shader</code> class and pass them in. Or even to add a separate <code>ShaderObject</code> class, and create the Shader from a <code>std::vector<ShaderObject></code>.</p>\n\n<p>But maybe that's more than you need right now.</p>\n\n<hr>\n\n<p>Technically, <a href=\"https://stackoverflow.com/a/48987445/673679\">we should write error messages to <code>stderr</code>, not <code>stdout</code></a>, which means using <code>std::cerr</code> or <code>std::clog</code> instead of <code>std::cout</code>. It doesn't really matter for a graphical program though.</p>\n\n<hr>\n\n<pre><code>if (!is_compiled)\n{\n // ...\n return false;\n}\nelse\n{\n return true;\n}\n</code></pre>\n\n<p>We don't need the <code>else</code> statement here, since we <code>return</code> from the other branch. We can just <code>return true</code> and avoid the brackets and the extra indent. (This is more of an issue when there's more code in the <code>else</code> branch).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-08T09:03:38.980",
"Id": "230363",
"ParentId": "230338",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "230363",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-07T20:56:24.127",
"Id": "230338",
"Score": "5",
"Tags": [
"c++",
"opengl"
],
"Title": "OpenGL shader abstraction class"
}
|
230338
|
<p>This is my first attempt at OOP/classes: a game where you will select a character and use attacks and abilities to defeat the enemy character.
I have a few specific questions:</p>
<p>I was told that having the "while" statement in the Character doesn't make any sense but I don't know where I should put those.
Also, notable right away, is what seems to me like a scissors and tape way of taking turns... I feel like there's a better way but I could not think of it.</p>
<pre><code>import random
class Character:
def __init__(self, health, strength, mobility, energy):
self.health = health
self.strength = strength
self.mobility = mobility
self.energy = energy
turn = False
is_target = True
is_dazed = False
is_stunned = False
is_debilitated = False
is_confused = False
is_terrified = False
while is_debilitated:
mobility = 0
def success_check(self):
defense = roll_d_x(attack_dice)
if defense >= defender.mobility:
success = True
else:
success = False
return success
def skip_turn(self):
print("Skipping turn.")
self.turn = False
player1 = None
player2 = None
defender = None
attack_dice = 100
nec_starting_health = 80
nec_starting_strength = 10
nec_starting_mobility = 10
nec_starting_energy = 20
ghost_starting_health = 10
ghost_starting_strength = 10
ghost_starting_mobility = 30
ghost_starting_terr = 5
skel_starting_health = 30
skel_starting_strength = 30
skel_starting_mobility = 10
skel_starting_terr = 10
mons_starting_health = 50
mons_starting_strength = 20
mons_starting_mobility = 20
mons_starting_terr = 20
</code></pre>
<p>My idea for minions was to give the Necromancer a list and append these minions to it...good idea/bad idea?</p>
<pre><code>class Necromancer(Character):
def __init__(self):
self.health = nec_starting_health
self.strength = nec_starting_strength
self.mobility = nec_starting_mobility
self.energy = nec_starting_energy
self.friendly_minions = list()
def gain_health(self, amount):
self.health += amount
print(f"Health gained: {amount}")
if self.health > nec_starting_health:
self.health = nec_starting_health
def lose_health(self, amount):
self.health -= amount
print(f"Health lost: {amount}")
self.energy += amount
print(f"Life Force gained: {amount}")
if self.health <= 0:
game_over = True
def gain_strength(self, amount):
self.strength += amount
if self.strength > nec_starting_strength:
self.strength = nec_starting_strength
def lose_strength(self, amount):
self.strength -= amount
if self.strength < 0:
self.strength = 0
def gain_mobility(self, amount):
self.mobility += amount
if self.mobility > nec_starting_mobility:
self.mobility = nec_starting_mobility
def lose_mobility(self, amount):
self.mobility -= amount
if self.mobility < 0:
self.mobility = 0
def gain_energy(self, amount):
self.energy += amount
print(f"Life Force gained: {amount}")
if self.energy > (nec_starting_energy + nec_starting_energy):
self.energy = (nec_starting_energy + nec_starting_energy)
def lose_energy(self, amount):
self.energy -= amount
print(f"Life Force lost: {amount}")
if self.energy < 0:
self.energy = 0
def sacrifice_random_minion(self):
if len(self.friendly_minions) == 0:
print("No Minion to sacrifice.")
else:
ran_minion = random.randint(0, (len(self.friendly_minions) - 1))
sacrificed_minion = self.friendly_minions[ran_minion]
print("Minion sacrificed.")
sacrificed_minion.show_attributes()
self.friendly_minions.remove(sacrificed_minion)
def attack(self):
if self.is_dazed:
print("Dazed...attack unsuccessful.")
elif self.is_confused:
confused_test = roll_d_x(2)
if confused_test == 1:
print("Confused...attack unsuccessful.")
else:
success = self.success_check()
if success:
defender.lose_health(self.strength)
self.gain_health(20)
else:
print(f"Attack missed.")
def cull(self):
if self.is_stunned:
print("Stunned...ability unsuccessful.")
elif self.is_confused:
confused_test = roll_d_x(2)
if confused_test == 1:
print("Confused...ability unsuccessful.")
else:
success = self.success_check()
if success:
if len(self.friendly_minions) == 0:
print("Ability failed. No Minion to sacrifice.")
else:
ran_minion = random.randint(0, (len(self.friendly_minions) - 1))
sacrificed_minion = self.friendly_minions[ran_minion]
print("Minion sacrificed.")
sacrificed_minion.show_attributes()
self.gain_health(sacrificed_minion.health)
self.friendly_minions.remove(sacrificed_minion)
else:
print("Ability failed.")
def call_ghost(self):
if self.is_stunned:
print("Stunned...ability unsuccessful.")
elif self.is_confused:
confused_test = roll_d_x(2)
if confused_test == 1:
print("Confused...ability unsuccessful.")
else:
success = self.success_check()
if success:
self.lose_health(5)
self.lose_energy(10)
ghost = Ghost()
self.friendly_minions.append(ghost)
print("Ghost Called.")
else:
print("Ability failed.")
def raise_skeleton(self):
if self.is_stunned:
print("Stunned...ability unsuccessful.")
elif self.is_confused:
confused_test = roll_d_x(2)
if confused_test == 1:
print("Confused...ability unsuccessful.")
else:
success = self.success_check()
if success:
self.lose_health(10)
self.lose_energy(25)
skeleton = Skeleton()
self.friendly_minions.append(skeleton)
print("Skeleton Raised.")
else:
print("Ability failed")
def summon_monster(self):
if self.is_stunned:
print("Stunned...ability unsuccessful.")
elif self.is_confused:
confused_test = roll_d_x(2)
if confused_test == 1:
print("Confused...ability unsuccessful.")
else:
success = self.success_check()
if success:
self.lose_health(20)
self.lose_energy(40)
monster = Monster()
self.friendly_minions.append(monster)
print("Monster Created.")
else:
print("Ability failed.")
def start_turn(self):
self.gain_energy(((100 - self.health) / 2) + 10)
for minion in self.friendly_minions:
minion.attack()
def end_of_turn(self):
self.is_dazed = False
self.is_stunned = False
self.is_debilitated = False
self.is_confused = False
self.is_terrified = False
self.gain_energy((100 - self.health) / 2 + 10)
if (self.health + self.energy) > 100:
self.energy = (100 - self.health)
class Minion:
def __init__(self, health, strength, mobility, chance_terrify):
self.health = health
self.strength = strength
self.mobility = mobility
self.chance_terrify = chance_terrify
is_target = True
def show_attributes(self):
print(f"Minion:\n{self.health} Health\n{self.strength} Strength\n{self.mobility} Mobility")
def attack(self):
flip = roll_d_x(2)
if flip == 1:
print("Minion attack failed.")
else:
defense = roll_d_x(100)
if defense >= defender.mobility:
defender.lose_health(self.strength)
print(f"The minion attack is successful.")
else:
print(f"Attack missed.\n(Defense Roll, {defense}. Defender's Mobility, {defender.mobility})")
class Ghost(Minion):
def __init__(self):
self.health = ghost_starting_health
self.strength = ghost_starting_strength
self.mobility = ghost_starting_mobility
self.chance_terrify = ghost_starting_terr
class Skeleton(Minion):
def __init__(self):
self.health = skel_starting_health
self.strength = skel_starting_strength
self.mobility = skel_starting_mobility
self.chance_terrify = skel_starting_terr
class Monster(Minion):
def __init__(self):
self.health = mons_starting_health
self.strength = mons_starting_strength
self.mobility = mons_starting_mobility
self.chance_terrify = mons_starting_terr
def roll_d_x(max_num):
roll = random.randint(1, max_num)
return roll
</code></pre>
<p>This, again, is a but of scissors and tape. I'm not sure of a better way to do this.</p>
<pre><code>def pick_starting_player():
flip = roll_d_x(2)
if flip is 1:
player1.turn = True
else:
player2.turn = True
if player1.turn:
print("Player 1 goes first.")
else:
print("Player 2 goes first.")
def end_turn_p1():
player1.turn = False
player2.turn = True
def end_turn_p2():
player2.turn = False
player1.turn = True
</code></pre>
<p>This is for testing ... I need to learn how to make a <strong>main</strong> I think...
Eventually, I would like to get this into pygame(?), have clickable buttons for abilities, visual monsters and heroes, etc...</p>
<pre><code>player1 = Necromancer()
player2 = Necromancer()
pick_starting_player()
game_over = False
while not game_over:
while player1.turn is True:
defender = player2
player1.start_turn()
print("***\nPlayer1")
player1.show_skills()
while True:
user_skill = input("Enter the skill you wish to use: ")
if user_skill.lower() == 'attack':
player1.attack()
break
elif user_skill.lower() == 'cull':
player1.cull()
break
elif user_skill.lower() == 'call ghost':
player1.call_ghost()
break
elif user_skill.lower() == 'raise skeleton':
player1.raise_skeleton()
break
elif user_skill.lower() == 'summon monster':
player1.summon_monster()
break
else:
print("Invalid skill")
continue
player1.end_of_turn()
end_turn_p1()
while player2.turn is True:
defender = player1
player2.start_turn()
print("Player2 does nothing on his turn.")
end_turn_p2()
</code></pre>
|
[] |
[
{
"body": "<h1><code>Character.success_check</code></h1>\n\n<p>This method can be reduced to two lines</p>\n\n<pre><code>def success_check(self):\n defense = roll_d_x(attack_dice)\n return defense >= defender.mobility\n</code></pre>\n\n<p>Since <code>defense >= defender.mobility</code> evaluates to a boolean expression, you can simply return the statement.</p>\n\n<h1><code>roll_d_x()</code></h1>\n\n<p>This method can be reduced to one line</p>\n\n<pre><code>def roll_d_x(max_num):\n return random.randint(1, max_num)\n</code></pre>\n\n<h1>Expression vs <code>is True</code> or <code>== True</code></h1>\n\n<p>Instead of checking if an expression is equal to <code>True</code> or <code>False</code>, simply check the expression. It evaluates to a boolean result, and you can go from there:</p>\n\n<pre><code>while player2.turn is True:\n</code></pre>\n\n<p>to</p>\n\n<pre><code>while player2.turn:\n</code></pre>\n\n<p>For numbers, use <code>==</code> instead of <code>is</code>. <code>is</code> will return True if two variables point to the same object, <code>==</code> if the objects referred to by the variables are equal.</p>\n\n<h1>Character Class</h1>\n\n<p>Not really sure what the <code>while</code> loop is doing there. If this were to be run, and the loops expression be <code>True</code>, then it'd be an infinite loop, as there's no way to change the state of <code>is_debilitated</code> with the code that's written.</p>\n\n<h1>Reduce Method Calls</h1>\n\n<p>Instead of calling <code>.lower()</code> every time when you check for matches, simply call it on the <code>input()</code> function itself:</p>\n\n<pre><code>user_skill = input(\"Enter the skill you wish to use: \").lower()\n</code></pre>\n\n<h1>Type Hints</h1>\n\n<p>Use type hints to display what types of parameters are accepted, and what type(s) of value(s) are being returned from the function/method.</p>\n\n<p>From this</p>\n\n<pre><code>gain_health(self, amount):\nsuccess_check(self):\n</code></pre>\n\n<p>to this</p>\n\n<pre><code>gain_health(self, amount: int) -> None:\nsuccess_check(self) -> bool:\n</code></pre>\n\n<h1>Docstrings</h1>\n\n<p>You should include a docstring at the beginning of every method, class and module you write. This will allow you to express what these are supposed to do, and allows other programmers to more easily understand what the purpose and \"function\" of the functions are.</p>\n\n<h1>\"Main\" Method</h1>\n\n<p>There isn't really a main method in python. There is a main guard, however. It's a simple if statement that prevents code from being run if you decide to import this module from other programs. It works like so</p>\n\n<pre><code>if __name__ == '__main__':\n # code here\n</code></pre>\n\n<p>\"name\" will only be \"main\" in the module that the program is run from.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-09T00:05:42.460",
"Id": "448752",
"Score": "0",
"body": "Are type hints used for readability only?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-09T00:34:18.540",
"Id": "448753",
"Score": "0",
"body": "@ClaudeFried Yes, and to let programmers know what types of data to pass, instead of having to validate the data inside the function."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-07T23:48:07.063",
"Id": "230345",
"ParentId": "230343",
"Score": "7"
}
},
{
"body": "<p>Welcome back! I'm going to take a moment to talk about modules and classes before I start reviewing your code.</p>\n\n<h1>Modules and Classes</h1>\n\n<p>Python code is stored in source files with a <code>.py</code> extension. These are <strong>modules</strong>. If you write a \"program\" in python -- something meant to be run from the command line, like <code>python mygame.py</code> -- your program is still a module, although it has some unusual properties (like <code>__name__</code> is set to <code>\"__main__\"</code> instead of the module name).</p>\n\n<h2>Modules</h2>\n\n<p>Regardless, the python execution process starts by parsing all of your code, from the top of the file to the bottom. It produces a parse tree, which converts to an AST (except for possibly 3.8+ where the parser might emit the AST directly), which is then compiled into byte code. The byte code is then either stored in a <code>.pyc</code> file (non-main modules) or just executed directly from memory.</p>\n\n<p>Each module when loaded into memory is made up of nothing but executable statements. The executable statements are all the code that you put \"up against the wall\" on the left margin, and also class definitions and function definitions.</p>\n\n<p>Again: <strong>class definitions are executable code</strong>.</p>\n\n<p>Also: <strong>function definitions are executable code</strong></p>\n\n<h2>Classes</h2>\n\n<p>A class definition is \"executed\" when you reach the point in the code flow that it appears. That means if you have a module like:</p>\n\n<pre><code>A = 1\n\nclass Dog:\n pass\n\nB = 1\n</code></pre>\n\n<p>then the class definition is executed after <code>A = 1</code> and before <code>B = 1</code>. This is also true for function definitions: they are executed where they appear in the code flow.</p>\n\n<p>A class definition consists of some book-keeping code for creating the class and linking it with its parents and metaclass, plus creating a new entry in the module's namespace, <strong>plus</strong> all the code you type inside the class definition.</p>\n\n<p>Most of the time, the \"code you type inside the class definition\" consists of class-level constants, class-level variable initialization, and function (method) definitions, which we already mentioned as being executable code.</p>\n\n<p>If you type code that is \"actual code\" -- that is, call functions, print results, whatever -- it will be executed in the order in which it appears in the class (top to bottom) whenever the class definition is executed. As we have discussed, that means in the order in which the class appears in the file.</p>\n\n<h1>Your code</h1>\n\n<p>Your code looks good. It conforms to a lot of PEP-8, modulo a few nits like the number of blank lines between things. </p>\n\n<p>There is too much code up against the wall. You have skipped over the <code>if __name__ == '__main__':</code> check. Please correct that, even if you do naught but move everything into one big <code>main()</code>.</p>\n\n<h2>Too many names</h2>\n\n<p>One problem you suffer from is too many names. Worse, the names are formatted incorrectly.</p>\n\n<pre><code>nec_starting_health = 80\nnec_starting_strength = 10\nnec_starting_mobility = 10\nnec_starting_energy = 20\n</code></pre>\n\n<p>These are supposed to be constants -- you only use them to set other values. But constants should be in UPPER_SNAKE_CASE.</p>\n\n<p>But rather than change that, I'd suggest you just make these numbers part of the appropriate class. You could have something like:</p>\n\n<pre><code>class Necromancer(...):\n STARTING_ENERGY = 20\n STARTING_HEALTH = 80\n</code></pre>\n\n<p>Instead, I suggest that you just hard-code the numbers into the <code>Necromancer.__init__</code> function, which is the only place they'll be used. Use named parameters for clarity:</p>\n\n<pre><code>class Necromancer(Character):\n \"\"\" ... \"\"\"\n def __init__(self):\n super().__init__(health=80, strength=10, mobility=10, energy=20)\n</code></pre>\n\n<p>This does the same things, with less typing: it conveys that these are magic numbers specific to the initial setup of the Necromancer class, it documents what number is what attribute, and it lets you change them in one place. Admittedly, it doesn't let you change them from outside the module, but I'd call that a feature ;-).</p>\n\n<p>One side effect of this would be creating <code>max_XXX</code> attributes, for attributes where you wanted to be able to gain them back. This seems obvious to me, and you could move these functions into the <code>Character</code> base class if you made the attributes explicit, instead of trying to sneak references to those outside names in your subclass methods.</p>\n\n<h2>Extra code in class <code>Character</code></h2>\n\n<p>As you mentioned yourself, all this code is extra:</p>\n\n<pre><code>turn = False\n\nis_target = True\n\nis_dazed = False\nis_stunned = False\nis_debilitated = False\nis_confused = False\nis_terrified = False\n\nwhile is_debilitated:\n mobility = 0\n</code></pre>\n\n<p>It might be that you planned to indent that under the <code>def __init__()</code> that appears above it. In which case you probably meant something like <code>self.turn = False</code>. Otherwise, you are defining a <em>class variable</em> <code>turn</code> which will be shared by everything that is an instance or subclass-instance of <code>Character</code>. </p>\n\n<p>The <code>is_...</code> attributes clearly should be instance attributes -- move them into your <code>__init__</code> method. The <code>while is_debilitated</code> is not executed, since you defined <code>is_debilitated = False</code> just a few lines higher. But since you don't do anything to change <code>is_debilitated</code> inside your loop, that will be an infinite loop and hang your program if you ever actually run the code. I think you meant <code>if</code> instead of <code>while</code>, and you meant for it to be located someplace else.</p>\n\n<h2>DRY: Missing class <code>Attribute</code></h2>\n\n<p>You have four attributes, and you have written <code>gain</code> and <code>lose</code> methods for all four. Why not just have your attributes be of <code>class Attribute</code> and write <code>gain</code> and <code>lose</code> methods once, for the class:</p>\n\n<pre><code>player1.gain_energy(1) --> player1.energy.gain(1)\n</code></pre>\n\n<h2>DRY: Missing function: <code>use_ability()</code></h2>\n\n<p>Your class Necromancer has a bunch of \"ability\" methods. They all share the same common code:</p>\n\n<pre><code>def call_ghost(self):\n if self.is_stunned:\n print(\"Stunned...ability unsuccessful.\")\n elif self.is_confused:\n confused_test = roll_d_x(2)\n if confused_test == 1:\n print(\"Confused...ability unsuccessful.\")\n else:\n success = self.success_check()\n if success:\n\n ### NOTE: This part is different\n\n else:\n print(\"Ability failed.\")\n</code></pre>\n\n<p>So why not write a function (method) for that:</p>\n\n<pre><code>def use_ability(self, ability):\n \"\"\"Common framework for ability methods.\"\"\"\n # ...\n # as before\n # ...\n if success:\n ability()\n # ...\n # as before ...\n</code></pre>\n\n<p>Then you can code the individual ability methods as <code>_methodname</code> to indicate they're tricky, and drop all the boilerplate code at the beginning and end, just assuming you succeeded.</p>\n\n<h2>Class <code>Minion</code></h2>\n\n<p>This seems like it should be a subclass of <code>Character</code>, but perhaps there should be a common parent class <code>Combatant</code> or something that both <code>Minion</code> and <code>Character</code> can derive from? Or perhaps <code>Minion</code> should be the parent of <code>Character</code>?</p>\n\n<h2>Missing attribute: <code>name</code></h2>\n\n<p>Instead of <code>Minion attack failed</code> print <code>f\"{self.name}'s attack failed\"</code> or perhaps <code>type(self).__name__</code> to get the class name (\"Character's attack failed\", \"Ghost's attack failed\", etc.)</p>\n\n<h2>Bogus attribute: <code>turn</code>.</h2>\n\n<p>The turn is a game concept, not a character concept. Don't store it in the character or minion. Store it at the game level.</p>\n\n<h2>Missing function: player turn</h2>\n\n<p>You have a lot of code inside the game while loop for executing the player1 and player2 turns. Move that into a function.</p>\n\n<p>That's it for this pass. Good luck!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-08T23:59:22.183",
"Id": "448751",
"Score": "0",
"body": "I'm struggling to understand creating class Attribute.\nThank you for everything so far..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-09T03:32:09.027",
"Id": "448788",
"Score": "0",
"body": "An Attribute, as you are using it, has a name, a value, a maxvalue. The minvalue is 0, I assume. It should support `gain()` and `lose()` operations. Then you could say `self.energy = Attribute('energy', 20)` to create one, and say `self.energy.lose(2)` when you want to spend points on something."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-09T12:30:36.927",
"Id": "448847",
"Score": "0",
"body": "As for the `use_ability`, you could also turn this into a decorator."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-10T15:40:24.343",
"Id": "449095",
"Score": "0",
"body": "Procedural question:\nWhen I want to post a revised/expanded code of the same game, does it belong as a new post entirely?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-10T20:32:25.497",
"Id": "449138",
"Score": "0",
"body": "@ClaudeFried You can add an **Update:** to the bottom if you are just incorporating suggested changes. If you extend the game by adding more unreviewed code, I'd say it's time for a new review (but include a link to this one so that people can see the evolution, and nag you about changes you haven't made yet. ;-)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-11T18:19:15.670",
"Id": "449265",
"Score": "0",
"body": "@AustinHastings If the \"turn\" is a game concept and not a character attribute (which I agree with), then how might the turns cycle between you and your opponent? I might just have swamp-brain, but I can't think of a way to \"assign\" a turn to a player at the game-level. It's easy to figure out how to define *what happens* on each players turn and when it ends, but passing it back and forth seems very mysterious at the moment..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-11T19:41:00.243",
"Id": "449289",
"Score": "0",
"body": "@ClaudeFried let the game manager handle the turns. Just give each player a \"do_your_turn()\" method, and call them in order. If you're executing that code, then it's your turn."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-08T00:27:24.620",
"Id": "230347",
"ParentId": "230343",
"Score": "19"
}
},
{
"body": "<p>Re:</p>\n\n<pre><code> while is_debilitated:\n mobility = 0\n</code></pre>\n\n<p>I'm guessing you were hoping that this would set mobility to zero whenever is_debilitated was true? (All that can do is either nothing at all or create an infinite loop.)</p>\n\n<p>I'd suggest something like</p>\n\n<pre><code>def get_mobility(self):\n if self.is_debilitated:\n return 0\n else:\n return self.mobility\n</code></pre>\n\n<p>And any other effects that temporarily modify mobility could go there.\nThen elsewhere you'd put</p>\n\n<pre><code>if defense >= defender.get_mobility():\n</code></pre>\n\n<p>in place of</p>\n\n<pre><code>if defense >= defender.mobility:\n</code></pre>\n\n<p>(Apologies if I got any of the Python grammar wrong - I'm more of a C++ guy...)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-09T07:37:10.923",
"Id": "448798",
"Score": "2",
"body": "Although as far as I'm aware it's often a good idea to use getters and setters, it's also worth noting that we could do this using [`property`](https://docs.python.org/3/library/functions.html?highlight=attribute%20decorator#property) and pretend that `mobility` is just a normal attribute even though everything you do with it is actually calls to custom getters and setters."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-28T12:48:31.313",
"Id": "451344",
"Score": "0",
"body": "I feel this could use a more expanded explanation of why that `while` loop isn't doing anything. It doesn't do anything because it's only run on class instantiation, when is_debilitated is False. A Pythonic solution would be @property over getters."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-08T14:30:48.700",
"Id": "230375",
"ParentId": "230343",
"Score": "3"
}
},
{
"body": "<p>When creating a parent class your attributes can be inherited to a subclass. A conventional way to create characters:</p>\n\n<pre><code>class Char:\n def __init__(self, name, hp, strength, gold):\n self.name = name\n self.hp = hp\n self.strength = strength\n self.gold = gold\n\n\nclass Enemy:\n def __init__(self, name, hp, strength, gold):\n self.name = name\n self.hp = hp\n self.strength = strength\n self.gold = gold\n\n#Create player and enemy\nplayer = Char('John Smith', 100, 100, 100)\ngoblin = Enemy('Goblin', 100, 100, 200)\n</code></pre>\n\n<p>You can also use the <code>super()</code> method to create subclass that automatically inherits the attributes of the parent class without affecting the parent class.</p>\n\n<pre><code>class Goblin(Char):\n def __init__(self):\n super().__init__(name='Goblin', hp=100, strength=100, gold=200)\n</code></pre>\n\n<p>This is using the attributes from the parent class <code>Char</code>. You can also add attributes to this class if you want to include any other variables</p>\n\n<p>@Linny</p>\n\n<p>Yes you can, the extending the attributes would just be included in the class your making however you might not want the rest of the functions from the main class. This is why I usually separate the classes. For instance:</p>\n\n<pre><code>class Char:\n def __init__(self, name, hp, strength, gold):\n self.name = name\n self.hp = hp\n self.strength = strength\n self.gold = gold\n\n def __str__(self): # You may not want to return any values but this will run\n return 'name: {} , hp: {} , strength: {} , gold: {}'.format(self.name, self.hp, self.strength, self.gold)\n\n\nclass Enemy(Char): # You can extend attributes here without changing the parent class\n pass\n\n\nplayer = Char('John Smith', 100, 100, 100)\nenemy_1 = Enemy('Giant', 1000, 1000, 1000)\nprint(player)\nprint(enemy_1)\n</code></pre>\n\n<p>This gives:</p>\n\n<pre><code>name: John Smith , hp: 100 , strength: 100 , gold: 100\nname: Giant , hp: 1000 , strength: 1000 , gold: 1000\n</code></pre>\n\n<p>Your Subclass may not want the Parent class functions so the first method is a good way to achieve full flexibility in your code.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-28T04:32:45.133",
"Id": "451313",
"Score": "0",
"body": "Wouldn't creating a base `Entity` class with the starting values, then extending from that class `Character(Entity)` and `Enemy(Entity)` be better? Then you wouldn't have to write the same class body two times."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-28T08:57:54.127",
"Id": "451325",
"Score": "1",
"body": "Thats a good question . I have amended the answer to include the reason why it is done different ways"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-09T17:26:26.923",
"Id": "230445",
"ParentId": "230343",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-07T23:13:03.623",
"Id": "230343",
"Score": "18",
"Tags": [
"python",
"beginner",
"object-oriented",
"role-playing-game",
"battle-simulation"
],
"Title": "Hero battle game"
}
|
230343
|
<p>How can I test a class that Swizzles? In particular, I want to test the following:</p>
<pre><code>let bundleName = "Bundle.bundle"
var downloadedBundlePath: String? = Bundle.main.path(forResource: bundleName, ofType: nil)
class Localizer: NSObject {
class func swizzleMainBundle() {
MethodSwizzleGivenClassName(cls: Bundle.self, originalSelector: #selector(Bundle.localizedString(forKey:value:table:)), overrideSelector: #selector(Bundle.specialLocalizedStringForKey(_:value:table:)))
}
}
extension Bundle {
@objc func specialLocalizedStringForKey(_ key: String, value: String?, table tableName: String?) -> String {
if self == Bundle.main {
if let path = downloadedBundlePath, let bundle = Bundle(path: path) {
return (bundle.specialLocalizedStringForKey(key, value: value, table: tableName))
}
return (self.specialLocalizedStringForKey(key, value: value, table: tableName))
} else {
return (self.specialLocalizedStringForKey(key, value: value, table: tableName))
}
}
}
func MethodSwizzleGivenClassName(cls: AnyClass, originalSelector: Selector, overrideSelector: Selector) {
if let origMethod: Method = class_getInstanceMethod(cls, originalSelector), let overrideMethod: Method = class_getInstanceMethod(cls, overrideSelector) {
if (class_addMethod(cls, originalSelector, method_getImplementation(overrideMethod), method_getTypeEncoding(overrideMethod))) {
class_replaceMethod(cls, overrideSelector, method_getImplementation(origMethod), method_getTypeEncoding(origMethod));
} else {
method_exchangeImplementations(origMethod, overrideMethod);
}
}
}
</code></pre>
<p>Which changes the localisation bundle for a local bundle that I have created within the user directory (when used correctly).</p>
<p>Do I need to rewrite this class to make it testable? I really have no real idea how to make it easily testable.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-07T23:43:20.463",
"Id": "448599",
"Score": "2",
"body": "We can review code that you have already written. However, if you're asking about how to write a test, then that's asking for code to be written (or advice about how to write such code), which is off-topic for Code Review."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-08T00:06:25.333",
"Id": "448600",
"Score": "1",
"body": "Can you make this question clearer? are you asking if the code is written well enough to be easily testable? if you are asking if the code is written well and within standards that sounds like a code review, but if you are asking us to write test cases for this code, that is as @200_success has noted, off-topic for Code Review."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-08T01:03:01.300",
"Id": "448601",
"Score": "0",
"body": "I can't test this, I believe it to be untestable. Therefore the code review would be to write testable code for the functionality above."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-07T23:39:21.593",
"Id": "230344",
"Score": "1",
"Tags": [
"swift"
],
"Title": "Test a method that Swizzles in Swift"
}
|
230344
|
<p>I am a Javascript/JQuery beginner working on my first ever project. Everything in this program is working as it should and I am happy with its performance. I have pieced it together from a variety of sources and lots of trial and error.</p>
<p>Because this is so new to me I wanted some experienced opinions on the way I have used the various Javascript/JQuery components in my project. The code I have included here has been edited and simplified for clarity but in its entirety it is a working program so I'm not necessarily looking to have it rewritten but more looking for feedback on what I have done to see where I can improve my programming skills.</p>
<p>In particular am I following good programming protocols with my structure and layout of various elements and functions etc.?
Should I change, combine or separate components etc. to simplify coding whilst still allowing me to increase functionality should I want to extend the program further?
Are there better ways through HTML or otherwise to more efficiently achieve the outcomes I have noted in comments?</p>
<pre><code><div class="sandbox">
<video id="videoElement" ><source src="video.mp4" > </video>
<div id="start-page"> <button on="" onclick="playVid();">Start video</button> </div>
<div class="respond"> <p>Click video to respond</p> </div>
<div id="result-page"> <h2 id="result"> </h2> </div>
</div>
<script>
// when page loads hide the respond and result-page divs
$(function(){
$(".respond, #result-page").hide();
});
// play video; hide start-page div; show respond div
var myVid = document.getElementById('videoElement');
function playVid() {
videoElement.play();
$("#start-page").hide(); $(".respond").show();
}
// when ‘respond’ div is clicked the ‘respond’ div is disabled
// “response recorded” message shows & response time compared to settings
$('.respond').on('click', function() {
$('.respond').off('click');
$('.respond').html('<p>response recorded</p>');
var mycurrentTime = myVid.currentTime;
var result;
if (mycurrentTime < 10) {
result = "under 10" ;
} else {
result = "over 10" ;
}
// add ‘result’ text to result-page div
document.getElementById("result").innerHTML = result;
}
);
// at end of video show result-page div
document.getElementById('videoElement').addEventListener('ended',myHandler,false);
function myHandler(e) {
$("#result-page").show();
}
</script>
</code></pre>
|
[] |
[
{
"body": "<p>This script mixes jQuery DOM lookups (e.g. <code>$(\".respond\")</code>) with native DOM lookups (e.g. <code>document.getElementById('videoElement')</code>). It is best to use only one style to avoid confusion (e.g. for anyone reading your code, including your future self). If you are going to load jQuery on the page then you might as well use it. Otherwise if you don't need it then it could reduce the page load time slightly if it is removed. You might find <a href=\"https://ilikekillnerds.com/2015/02/stop-writing-slow-javascript/\" rel=\"nofollow noreferrer\">this article</a> interesting. </p>\n\n<p>Indentation is inconsistent, though maybe that was a mistake during insertion of the code into your post.</p>\n\n<p>The first line in <code>playVid()</code> references <code>videoElement</code> which looks up the element by <code>id</code> attribute implicitly. </p>\n\n<blockquote>\n<pre><code>function playVid() { \n videoElement.play();\n</code></pre>\n</blockquote>\n\n<p>This can also confuse readers of your code. Because <code>myVid</code> points to that same element, that variable could be used instead.</p>\n\n<pre><code>function playVid() { \n myVid.play();\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-21T00:23:39.323",
"Id": "234416",
"ParentId": "230349",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-08T01:55:00.090",
"Id": "230349",
"Score": "5",
"Tags": [
"javascript",
"beginner",
"jquery",
"dom",
"video"
],
"Title": "Video player UI in Javascript/JQuery"
}
|
230349
|
<p><strong>The challenge:</strong></p>
<blockquote>
<p>You managed to send your friend to queue for tickets in your stead, but there is a catch: he will get there only if you tell him how much that is going to take. And everybody can only take one ticket at a time, then they go back in the last position of the queue if they need more (or go home if they are fine).</p>
<p>Each ticket takes one minutes to emit, the queue is well disciplined, Brit-style, and so it moves smoothly, with no waste of time.</p>
<p>You will be given an array/list/vector with all the people queuing and the initial position of your buddy, so for example, knowing that your friend is in the third position (that we will consider equal to the index, 2: he is the guy that wants 3 tickets!) and the initial queue is [2, 5, 3, 4, 6].</p>
<p>The first dude gets his ticket and the queue goes now like this [5, 3, 4, 6, 1], then [3, 4, 6, 1, 4] and so on. In the end, our buddy will be queuing for 12 minutes, true story!</p>
<p>Build a function to compute it, resting assured that only positive integers are going to be there and you will be always given a valid index; but we also want to go to pretty popular events, so be ready for big queues with people getting plenty of tickets.</p>
</blockquote>
<p><strong>My code:</strong></p>
<pre><code>def queue(queuers,pos):
minutes = 0
while 1:
minutes += 1
queuers[0] -= 1
if queuers[0] > 0:
queuers.append(queuers[0])
elif queuers[pos] == 0:
break
queuers.pop(0)
if pos > 0:
pos -= 1
else:
pos = len(queuers)-1
queuers = queuers[:]
return minutes
print(queue([2, 5, 3, 6, 4], 0))
</code></pre>
<p><strong>pythonic code*:</strong> </p>
<blockquote>
<pre><code>def queue(queuers,pos):
return sum(min(queuer, queuers[pos] - (place > pos)) for place, queuer in enumerate(queuers))
print(queue([2, 5, 3, 6, 4], 0))
</code></pre>
</blockquote>
<p><sup>*top voted code for the same kata, I am not the author of this</sup></p>
<p>I obviously am not at that level. How can I get there? I understand (more or less) the pythonic one liners when I see them. I'm just not yet at the point where I think that way from the get go. Any suggestions?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-08T04:09:42.683",
"Id": "448606",
"Score": "5",
"body": "If you want a review for your code, we can provide one, if this is some kind of initiation to a discussion forum then I suggest reddit is a better place. Note that for a code to be reviewed, it has to be a working code and be written by yourself."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-08T04:53:46.580",
"Id": "448616",
"Score": "1",
"body": "The code listed as \"my code\" is my code. It is working. The \"pythonic code\" below it is the top voted code for the same kata. I am asking for guidance on how I might get from where I am as a coder to the skill level demonstrated by the one liner."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-08T05:04:36.313",
"Id": "448618",
"Score": "0",
"body": "I fully understand."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-08T12:59:29.157",
"Id": "448677",
"Score": "2",
"body": "this might be interesting reading material for you: https://codereview.meta.stackexchange.com/questions/9353/requesting-a-comparative-review-of-own-code-with-third-party-code?cb=1"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-09T02:34:00.923",
"Id": "448785",
"Score": "2",
"body": "Given that you both have and understand the cleaner code, and you ask 'how to get there', it seems like you want some broader advice on what books to read, etc. That kind of advice is unfortunately off-topic for CodeReview, so I agree with the other votes-to-close as too broad."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-23T15:19:30.023",
"Id": "450767",
"Score": "0",
"body": "The current question title, which states your concerns about the code, is too general to be useful here. Please [edit] to the site standard, which is for the title to simply state **the task accomplished by the code**. Please see [How to get the best value out of Code Review: Asking Questions](//codereview.meta.stackexchange.com/q/2436) for guidance on writing good question titles."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-02T16:15:10.700",
"Id": "455910",
"Score": "0",
"body": "@jpolache I'd suggest removing the \"top voted one-liner\" and just ask how your code can be better. It's a much better way to learn and honestly, people love to see one-liners in these kinds of competitions but it's not really something you should aspire to do, writing clean code is a better goal :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-03T18:33:38.280",
"Id": "456085",
"Score": "0",
"body": "@IEatBagels Good point"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-08T03:59:03.387",
"Id": "230351",
"Score": "1",
"Tags": [
"python",
"python-3.x",
"programming-challenge",
"queue"
],
"Title": "Codewars Kata - Tickets Queue"
}
|
230351
|
<p>I have written a Lottery contract that picks winner based on the amount they contributed to the pool. I am looking if the code of <code>weightedWinner</code> function can be optimized. And if there is a better way to write the <code>random</code> function.</p>
<pre><code>pragma solidity ^0.5.12;
//import "./SafeMath.sol";
contract WeightedLottery {
//using SafeMath for uint256;
address public owner;
address payable[] private players;
mapping(address => uint256) private amounts;
uint256 totalAmount = 0;
constructor() public {
owner = msg.sender;
}
function random() private view returns (uint) {
return uint(keccak256(abi.encodePacked(blockhash(block.number - 1 - players.length), block.difficulty, now, players)));
}
function weightedWinner() private view returns(address payable) {
require(msg.sender == owner);
require(totalAmount != 0);
require(players.length != 0);
uint256 val = random() % totalAmount;
uint256 temp = 0;
for(uint256 i = 0; i < players.length; i++) {
temp += amounts[players[i]];
if(val < temp) {
return players[i];
}
}
return address(0x0);
}
function getPlayers() public view returns(address payable[] memory) {
return players;
}
function join() payable public {
require(msg.sender != owner);
require(msg.value != 0);
if(amounts[msg.sender] == 0) {
players.push(msg.sender);
}
amounts[msg.sender] += msg.value;
totalAmount += msg.value;
}
function pickWinner() public {
address payable winner = weightedWinner();
require(winner != address(0x0));
winner.transfer(totalAmount);
}
}
</code></pre>
<p><strong>How it works</strong></p>
<p>Players join with an initial amount of tokens. Later s/he can increase the amount. When <code>pickWinner</code> is called, player with the highest amount has the height probability of winning.</p>
<p>Example:</p>
<ol>
<li>player 1 joins with 10 tokens.</li>
<li>player 2 joins with 10 tokens.</li>
<li>player 1 adds 10 tokens.</li>
<li>player 3 joins with 10 tokens.</li>
<li>player 3 adds 10 tokens.</li>
<li><code>pickWinner</code> is called.</li>
</ol>
<p>Now we have player 1 and 3 with 20 tokens and 2 has 10 tokens. So player 1 and 3 has (20/50) probability of winning and player 2 has (10/50) probability.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-08T04:45:05.790",
"Id": "230354",
"Score": "3",
"Tags": [
"random",
"solidity"
],
"Title": "Optimization of weightedWinner() and random() function"
}
|
230354
|
<p>I'm working on a project to downsample some fastqs (files that contain sequences).</p>
<blockquote>
<p>Each line of the <a href="https://en.wikipedia.org/wiki/FASTQ_format" rel="nofollow noreferrer">fastq bioinformatics format</a> comprises 4 lines chunks
(id, dna sequence, "+", quality score).</p>
<p>Downsampling
a fastq is going to select n number of chunks or select x% of chunks.
But I don't handle the downsampling: I just pass parameters to a tool
called <code>seqtk</code> to handle that.</p>
</blockquote>
<p>I'd like some insights on the bash I use to process the options. I especially feel like there's something to have a <code>store_true</code> action for the <code>-t</code> flag.</p>
<pre><code>set -e
usage(){
echo "Downsample fastqs by calling the seqtk tool
Usage example: sh seqtk_downsampling.sh -n {sample_name} -s {seed_for_random: int} -p {percentage_to_downsample_to: [0-100; 0-1]} -t {testing_flag}"
}
while getopts n:s:p::t:h option
do
case "${option}"
in
n) sample_name=${OPTARG};;
s) seed=${OPTARG};;
p) perc_down=${OPTARG};;
t) testing=${OPTARG};;
h) usage
exit
;;
esac
done
# nothing given
if [ -z "$*" ]; then usage; exit 1; fi
# get fqs from sample name, check if they exist
if ! [ -z ${sample_name+x} ]; then
fqs=$(find . -name "${sample_name}*fastq.gz")
if [[ -z ${fqs} ]]; then
current_dir=$(pwd)
echo "Couldn't find the fqs for ${sample_name} in ${current_dir}"
exit 1
fi
else
echo "No sample name given using -n flag"
exit 1
fi
# testing mode
if [[ $testing == "true" ]]; then
percs_down="50 60 70 80 90"
for perc in $percs_down
do
for file in $fqs
do
echo $file $perc $seed
# seqtk sample -s ${seed} ${file} ${perc}
done
done
exit 0
else
echo "Wrong argument given to -t flag"
exit 1
fi
# given percentage and seed
if ! [ -z ${perc_down+x} ] && ! [ -z ${seed+x} ]; then
# format the perc
if [[ ${perc_down} =~ ^[0][,.][0-9]*$ ]]; then
perc=${perc_down/,/.}
elif [[ ${perc_down} -le 100 ]] && [[ ${perc_down} -gt 0 ]]; then
perc=$(awk -v per=$perc_down 'BEGIN {print per/100}')
else
echo "I wantz int between 0 and 100 (or float between 0 and 1)"
exit 1
fi
for file in $fqs
do
echo $file $perc $seed
# seqtk sample -s ${seed} ${file} ${perc}
done
else
echo "Missing required arguments -s {seed} or -p {perc_down}"
exit 1
fi
</code></pre>
|
[] |
[
{
"body": "<p>If you intend to make the script executable, it needs a shebang to select the desired interpreter:</p>\n\n<pre><code>#!/bin/bash\n</code></pre>\n\n<hr>\n\n<p>I like the use of <code>set -e</code>; you might consider adding <code>-u</code> and <code>-o pipefail</code>.</p>\n\n<hr>\n\n<p>We missed the error when an invalid option is specified:</p>\n\n<pre><code>'?') usage >&2; exit 1 ;;\n</code></pre>\n\n<hr>\n\n<p>Error messages should go to stream 2 (the standard error stream). Like this:</p>\n\n<pre><code>if [ -z \"$*\" ]; then usage >&2; exit 1; fi\n</code></pre>\n\n\n\n<pre><code> echo >&2 \"Couldn't find the fqs for ${sample_name} in ${current_dir}\"\n exit 1\n</code></pre>\n\n\n\n<pre><code>echo >&2 \"Missing required arguments -s {seed} or -p {perc_down}\"\nexit 1\n</code></pre>\n\n<hr>\n\n<p>Since we're using Bash, then we can use arrays:</p>\n\n<pre><code>if [[ $testing == \"true\" ]]; then\n percs_down=(50 60 70 80 90)\n\n for perc in \"${percs_down[@]}\"\n</code></pre>\n\n<hr>\n\n<p>We can test that both <code>$perc_down</code> and <code>$seed</code> are set with a single, positive test:</p>\n\n<pre><code>if [ \"${perc_down+x}${seed+x}\" = \"xx\" ]\n</code></pre>\n\n<hr>\n\n<p>If there's only one acceptable value for <code>-t</code> argument, why isn't it a simple flag argument? OTOH, if we will be adding new values, then <code>case</code> is going to be more suitable than <code>if</code> for selecting the desired code path.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-09T08:04:51.253",
"Id": "448800",
"Score": "0",
"body": "Yes I want the `-t` option to be a flag argument but I'm not sure how to do it. Could you explain your single test: `perc_down` and `seed` ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-09T11:19:56.727",
"Id": "448838",
"Score": "1",
"body": "For a flag argument, just remove the `:` after the `t` in the `getopts` argument. The single test just combines the strings (empty or `x`) for each variable, and checks that we got two `x`'s."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-08T16:30:53.177",
"Id": "230377",
"ParentId": "230359",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "230377",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-08T07:57:47.040",
"Id": "230359",
"Score": "5",
"Tags": [
"bash",
"console",
"shell",
"bioinformatics"
],
"Title": "Downsample fastqs"
}
|
230359
|
<p>I developed a function that, from a given sequence of digits, extracts the date and reformat it.<br>
This is the code: </p>
<pre><code>from datetime import datetime as dt
def format_dates(field):
n = len(field)
match = False
i = 0
while match is False:
try:
# Take the last four digits
year = int(field[-4 - i:n - i])
except ValueError:
return ''
# Check if this year is between today's year +/- (15, 100)
if (1919 <= year <= 2019):
# Check if there are other 4 digits before these 4 ones
if (len(field[-8 - i:n - i]) == 8):
try:
f_date = dt.strptime(field[-8 - i:n - i],
'%d%m%Y').strftime('%d/%m/%Y')
match = True
return f_date
except ValueError:
pass
else:
return ''
i += 1
</code></pre>
<p><strong>Explanation:</strong><br>
This function: </p>
<ul>
<li><p>Takes a sequence of digits as input.</p></li>
<li><p>extracts the last four digits from that sequence.</p></li>
<li><p>Checks if the extracted four digits are between 2019 and 1919, if not, it breaks.</p></li>
<li><p>If yes, it checks if there are more 4 digits before the previously extracted ones, if not it breaks. </p></li>
<li><p>If yes, it tries to format the whole 8 digits.</p></li>
<li>If there is a ValueError exception, it passes (ValueError, means there are 8 digits, the last four of them represent a correct year, but the fist four digits are wrong. So it passes to increment i + 1 to add a the next digits in the front and remove the last digit in the processed sequence).</li>
</ul>
<p><strong>Example:</strong> </p>
<p><em>input: '1303201946'</em></p>
<ol>
<li><p>Iteration 1:</p>
<ul>
<li>i = 0, match = False</li>
<li>year = 1946</li>
<li>test 1 (year between 2019 and 1919): passes.</li>
<li>test2 (there are 4 other digits before 1946, which are 0320): passes. </li>
<li>format the whole 8 digits: ValueError exception, so i = i+1 and pass to the next iteration. </li>
</ul></li>
<li>Iteration 2:
<ul>
<li>i = 1, match = False </li>
<li>year = 0194</li>
<li>test 1 (year between 2019 and 1919): fails, so i = i + 1 and pass to the next iteration. </li>
</ul></li>
<li>Iteration 3:
<ul>
<li>i = 2, match = False </li>
<li>year = 2019</li>
<li>test 1: passes </li>
<li>test 2: passes </li>
<li>format the whole 8 digits (13032019): 13/03/2019 (No ValueError exception) passes</li>
<li>match = True, return the formatted date, break from the while loop. </li>
</ul></li>
</ol>
<p>This function works fine, but the way it handles the errors seems ugly. Also I believe it is not optimized (same exceptions are repeated, a lot of returns and the code does not seem elegant).<br>
How to reformat the code and make it more optimized? </p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-08T09:52:58.537",
"Id": "448643",
"Score": "0",
"body": "This gives a `NameError: name 'sub_field' is not defined`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-08T09:55:43.853",
"Id": "448645",
"Score": "0",
"body": "@MaartenFabré, sorry I fixed it, it should be field instead of sub_field"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-08T10:10:00.560",
"Id": "448647",
"Score": "0",
"body": "@MaartenFabré, There was some errors in the code, I fixed them"
}
] |
[
{
"body": "<h1>Exception</h1>\n\n<p>If your algorithm cannot find a date, it is easier to raise an Exception than to return <code>''</code>. Returning sentinel values instead of exceptions can lead to unexpected behaviour if the user of this function does not test for this sentinel value.</p>\n\n<h1>comments</h1>\n\n<p>Comments should explain why you did something, not how. <code># Take the last four digits</code> tells you nothing more than the code itself. I would rather comment at <code>field[-4 - i:n - i]</code> why you did <code>n - i</code> instead of just <code>-i</code>.</p>\n\n<h1>nesting</h1>\n\n<p>Instead of nesting a number of if-clauses, it can be better to test the negative of the condition, and <code>continue</code>, so the rest of the code is less nested.</p>\n\n<h1>match</h1>\n\n<p>Don't test <code>condition is True</code>. Just do <code>condition</code>. In Python a lot of values can act as <code>True</code> or <code>False</code> in tests.</p>\n\n<p>Your <code>match</code> is never used anyway; the moment you set it to <code>True</code>, you also return the result, so a <code>while True:</code> would have sufficed here.</p>\n\n<h1><code>field</code></h1>\n\n<p>This is a very unclear variable name. This method excepts a date in string format, so why not call the argument like that?</p>\n\n<h1>Return type</h1>\n\n<p>Your code does 2 things now. It looks for a date in the string, and converts that date to another format. It would be better to separate those 2 things, and return a <code>datetime.datetime</code> instead, and let the caller of this method worry about formatting that correctly. </p>\n\n<h1><code>while True</code></h1>\n\n<p>You use a <code>while True</code>-loop, with an incrementing counter. A better way to do this would be to either use <code>for i in range(...)</code> or using <code>itertools.count</code>: <code>for i in itertools.count()</code>. In this case you know there will be no more than <code>len(field) - 7</code> iterations, so you might as well use that.</p>\n\n<h1>Revert the algorithm</h1>\n\n<p>You explicitly test whether the substring is 8 characters long, and then if it is in the right format. By changing the <code>while True</code> to the <code>for</code>-loop, you know the substring will be 8 characters long. Then it makes sense to first try to convert it to a <code>datetime</code>, and then check whether the year is correct:</p>\n\n<pre><code>def format_dates2(date_string):\n n = len(date_string)\n for i in range(n - 7):\n sub_string = date_string[-(8 + i) : n - i]\n # not just -i because that fails at i==0\n try:\n date = dt.strptime(sub_string, \"%d%m%Y\")\n except ValueError:\n continue\n if not (1919 <= date.year <= 2019):\n continue\n return date\n raise ValueError(\"Date not in the correct format\")\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-08T10:54:29.047",
"Id": "448652",
"Score": "1",
"body": "Thank you for the clear explanation."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-08T10:36:14.597",
"Id": "230366",
"ParentId": "230365",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": "230366",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-08T09:08:46.050",
"Id": "230365",
"Score": "7",
"Tags": [
"python",
"parsing",
"datetime",
"error-handling"
],
"Title": "Interpret a date from a string of digits"
}
|
230365
|
<p>I need to concatenate the <code>LastName</code> and <code>Initials</code> and all of that authors affiliations. Is there a better way or faster way to do this? I'm very new to working XML in JavaScript.</p>
<p>This is a portion of an XML string that I get back from an API that I parse in JavaScript:</p>
<pre><code> <AuthorList CompleteYN="Y">
<Author ValidYN="Y">
<LastName>Basree</LastName>
<ForeName>Mustafa M</ForeName>
<Initials>MM</Initials>
<AffiliationInfo>
<Affiliation>The Cancer Center...</Affiliation>
</AffiliationInfo>
</Author>
<Author ValidYN="Y">
<LastName>Shinde</LastName>
<ForeName>Neelam</ForeName>
<Initials>N</Initials>
<AffiliationInfo>
<Affiliation>The Comprehensive..</Affiliation>
</AffiliationInfo>
</Author>
<Author ValidYN="Y">
<LastName>Koivisto</LastName>
<ForeName>Christopher</ForeName>
<Initials>C</Initials>
<AffiliationInfo>
<Affiliation>Hollings ...</Affiliation>
</AffiliationInfo>
<AffiliationInfo>
<Affiliation>Department ...</Affiliation>
</AffiliationInfo>
</Author>
<Author ValidYN="Y">
<LastName>Cuitino</LastName>
<ForeName>Maria</ForeName>
<Initials>M</Initials>
<AffiliationInfo>
<Affiliation>Hollings...</Affiliation>
</AffiliationInfo>
<AffiliationInfo>
<Affiliation>Department ..</Affiliation>
</AffiliationInfo>
</Author>
</AuthorList>
</code></pre>
<p>my Code:</p>
<pre><code> let HTMLContent = ""
parser = new DOMParser();
xmlDoc = parser.parseFromString(response.data, "text/xml");
const AuthorsInfo = xmlDoc.querySelectorAll("Author");
AuthorsInfo.forEach(a => {
let affiliations = "";
let AuthorName = "";
for (var i = 0; i < a.children.length; i++) {
let tt = a.children[i].nodeName;
let t = a.children[i].textContent;
if (tt === "AffiliationInfo") {
affiliations += a.children[i].textContent;
affiliations += "<br /><br />";
} else if (tt === "LastName") {
AuthorName = a.children[i].textContent;
} else if (tt === "Initials") {
AuthorName += " " + a.children[i].textContent;
AuthorName += "<br /><br />";
}
}
HTMLContent += AuthorName + " " + affiliations;
});
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-08T13:16:49.757",
"Id": "448681",
"Score": "0",
"body": "Can the node loop be improved"
}
] |
[
{
"body": "<h2>Style</h2>\n<ul>\n<li><p>Inconsistent use of line ending semi colon</p>\n</li>\n<li><p>Undeclared variables <code>parser</code> and <code>xmlDoc</code></p>\n</li>\n<li><p>Unused code. <code>let t = a.children[i].textContent;</code> <code>t</code> is never used the line should not be there</p>\n</li>\n<li><p>Poor naming</p>\n<ul>\n<li>Capitalisation of variable names. Only if objects to be instanciated via new <code>token</code>, if accronim (eg HTML, XML) or if a constant (optional).\nExamples; <code>AuthorsInfo</code> should be <code>authorsInfo</code>, <code>AuthorName</code> as <code>authorName</code>, <code>xmlDoc</code> as <code>XMLDoc</code>.</li>\n<li>Non descripttive names, <code>a</code>, <code>tt</code>, <code>t</code></li>\n<li>Semanticly inacurate names, <code>AuthorsInfo</code> either <code>authorNodes</code> or just <code>authors</code></li>\n</ul>\n</li>\n<li><p>Use <code>for of</code> loops rather than <code>for if</code> loops if you do not need the index counter</p>\n</li>\n<li><p>Use <code>for of</code> loops rather than <code>Array</code> iterators</p>\n</li>\n<li><p>Function scoped variables should be declared as <code>var</code> and hoisted to the top of the function</p>\n</li>\n</ul>\n<h2>Code design</h2>\n<p>As you have several potential errors in the code (undeclared variables) you should ALWAYS use the directive <code>"use strict"</code> in your code to ensure these types of syntax problems are caught early in the development process.</p>\n<p>Always present your code as a function/s. Presenting code as flat global scoped source string is very poor design practice.</p>\n<p>Flat code often ends up performing many tasks that should be separated. Writing functions helps you define task roles under clearly named functions.</p>\n<p>The parsing of the XML to HTML is more than one task. I suggest you have two functions <code>parseAuthors</code> to extract the author details, and <code>authorsToHTML</code> to create the markup.</p>\n<h2>Example rewrite</h2>\n<p>From your code it is unclear as to the nature of the XML. Can authors have no last name, initials, or affiliations. Do authors always have one last name, does the last name always come before the initials. And many more unanswered questions regarding the XML.</p>\n<p>The example assumes that the XML given defines the XML.</p>\n<p>The example breaks the code into many smaller functions and puts them all together inside a IIF (immediately invoked function). In the real world you would put all the code inside a module.</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>\"use strict\";\n// As IFF or better as module (No need for use strict if module)\nconst authors = (() => {\n const AUTHORS = \"Author\"; \n const AFFILIATION = \"AffiliationInfo\";\n const LAST_NAME = \"LastName\";\n const INITIALS = \"Initials\";\n const SEP = \"<br/><br/>\";\n const nodeTxt = (node, name) => (name ? node.querySelector(name) : node).textContent;\n \n function Author(authorNode) {\n const author = {\n lastName: nodeTxt(authorNode, LAST_NAME),\n initials: nodeTxt(authorNode, INITIALS),\n affiliations: []\n }\n for (const affNode of authorNode.querySelectorAll(AFFILIATION)) {\n author.affiliations.push(nodeTxt(affNode));\n }\n return author;\n }\n\n return {\n parse(XMLString) {\n const authors = [];\n const authorNodes = new DOMParser()\n .parseFromString(XMLString, \"text/xml\")\n .querySelectorAll(\"Author\");\n for (const authorNode of authorNodes) { authors.push(Author(authorNode)) }\n return authors;\n },\n toHTML(authors) {\n var markup = \"\";\n for (const author of authors) {\n markup += author.lastName + \" \" + author.initials + SEP;\n markup += \" \" + author.affiliations.join(SEP) + SEP;\n }\n return markup;\n },\n };\n})();\ndocument.body.innerHTML = authors.toHTML(authors.parse(getXML()));\n\n\n\n\n\nfunction getXML() { return `<AuthorList CompleteYN=\"Y\">\n<Author ValidYN=\"Y\">\n <LastName>Basree</LastName>\n <ForeName>Mustafa M</ForeName>\n <Initials>MM</Initials>\n <AffiliationInfo>\n <Affiliation>The Cancer Center...</Affiliation>\n </AffiliationInfo>\n</Author>\n<Author ValidYN=\"Y\">\n <LastName>Shinde</LastName>\n <ForeName>Neelam</ForeName>\n <Initials>N</Initials>\n <AffiliationInfo>\n <Affiliation>The Comprehensive..</Affiliation>\n </AffiliationInfo>\n</Author>\n<Author ValidYN=\"Y\">\n <LastName>Koivisto</LastName>\n <ForeName>Christopher</ForeName>\n <Initials>C</Initials>\n <AffiliationInfo>\n <Affiliation>Hollings ...</Affiliation>\n </AffiliationInfo>\n <AffiliationInfo>\n <Affiliation>Department ...</Affiliation>\n </AffiliationInfo>\n</Author>\n<Author ValidYN=\"Y\">\n <LastName>Cuitino</LastName>\n <ForeName>Maria</ForeName>\n <Initials>M</Initials>\n <AffiliationInfo>\n <Affiliation>Hollings...</Affiliation>\n </AffiliationInfo>\n <AffiliationInfo>\n <Affiliation>Department ..</Affiliation>\n </AffiliationInfo>\n</Author>\n</AuthorList>`\n};</code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-10T13:00:22.270",
"Id": "449041",
"Score": "0",
"body": "Hello, I am a javascript beginner and probably mine is an obvious question: why there is no need to use strict in a module and if there are other cases when not to use strict in javascript code. Thanks in advance."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-10T16:33:11.763",
"Id": "449098",
"Score": "0",
"body": "@dariosicily Modules are automatically strict mode and it can not be turned off. There are no good reasons not to use strict mode. For more information https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-10T18:52:23.393",
"Id": "449119",
"Score": "0",
"body": "Fantastic- Thank you. I will include much of your rewrite"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-09T13:07:08.287",
"Id": "230426",
"ParentId": "230369",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "230426",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-08T12:36:27.240",
"Id": "230369",
"Score": "4",
"Tags": [
"javascript",
"beginner",
"parsing",
"xml"
],
"Title": "Rendering the AuthorName using the DOMParser to read XML"
}
|
230369
|
<p>If you need to kill the same process that you're in (for testing purposes or whatever) this code will do it.</p>
<p>A definitive, quick, unmerciful dead of the current Java program/app.<br>
Not a System.exit(0) or a graceful dead. </p>
<p>A headshot to the running JVM</p>
<pre><code>public class KillMe {
private static final String CMD_WINDOWS = "taskkill /F /PID %d";
private static final String CMD_LINUX = "kill -9 %d";
public static void tryNow() {
Thread t = new Thread( () -> {
try {
now();
} catch (CantKillMeException e) {
//TODO whatever
e.printStackTrace();
}
});
t.setName("killmethread");
t.setDaemon(true);
t.start();
}
public static void now() throws CantKillMeException {
int pid = obtainPid();
String command = getCommand(pid);
executeCommand(command);
}
static int obtainPid() throws CantKillMeException {
try {
java.lang.management.RuntimeMXBean runtime = java.lang.management.ManagementFactory.getRuntimeMXBean();
java.lang.reflect.Field jvm = runtime.getClass().getDeclaredField("jvm");
jvm.setAccessible(true);
sun.management.VMManagement mgmt = (sun.management.VMManagement) jvm.get(runtime);
java.lang.reflect.Method pid_method = mgmt.getClass().getDeclaredMethod("getProcessId");
pid_method.setAccessible(true);
int pid = (Integer) pid_method.invoke(mgmt);
return pid;
} catch (IllegalAccessException | java.lang.reflect.InvocationTargetException | NoSuchMethodException | NoSuchFieldException e) {
throw new CantKillMeException("Cant obtain pid", e);
}
}
// https://stackoverflow.com/questions/9573696/kill-a-process-based-on-pid-in-java
static String getCommand(int pid) {
String command = isWindows() ? CMD_WINDOWS : CMD_LINUX;
return String.format(command,pid);
}
// https://stackoverflow.com/questions/14288185/detecting-windows-or-linux
static boolean isWindows() {
String osname = System.getProperty("os.name").toLowerCase();
return osname.contains("win");
}
static void executeCommand(String command) throws CantKillMeException {
try {
Process process = Runtime.getRuntime().exec(command);
process.waitFor();
} catch (java.io.IOException | InterruptedException e) {
throw new CantKillMeException("Cant execute command " + command, e);
}
}
public static class CantKillMeException extends Exception {
CantKillMeException(String message, Throwable cause) {
super(message, cause);
}
}
}
</code></pre>
<p>Will work on Linux. Windows should work (not tested). There's room for improvement, for sure.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-08T15:26:41.277",
"Id": "448702",
"Score": "1",
"body": "Indentation is a bit off, is it a copy paste issue?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-08T19:27:02.940",
"Id": "448719",
"Score": "0",
"body": "What exactly do you want reviewed?"
}
] |
[
{
"body": "<p>Interesting little plot twist in a Java program.</p>\n\n<p>First up, <code>tryNow()</code> is dead code, it's not used, get rid of it, it makes the rest of the class harder to understand by putting red-herrings in the code.</p>\n\n<p>If it is really used somewhere else in your code (it is <code>public static</code>), then it should be moved out of this class in to a more usefully named location.... and it has other issues too, which I will ignore... except for .... never extend <code>Thread</code> directly, use <code>Runnable</code> ....</p>\n\n<p>Next up, you should ensure you are using Java 9.x or newer, and then use the more <a href=\"https://docs.oracle.com/javase/9/docs/api/java/lang/ProcessHandle.html#current--\" rel=\"noreferrer\">convenient <code>ProcessHandle</code> API for getting your current processID</a></p>\n\n<p>This reduces the code:</p>\n\n<blockquote>\n<pre><code>static int obtainPid() throws CantKillMeException {\n try {\n java.lang.management.RuntimeMXBean runtime = java.lang.management.ManagementFactory.getRuntimeMXBean();\n java.lang.reflect.Field jvm = runtime.getClass().getDeclaredField(\"jvm\");\n jvm.setAccessible(true);\n sun.management.VMManagement mgmt = (sun.management.VMManagement) jvm.get(runtime);\n java.lang.reflect.Method pid_method = mgmt.getClass().getDeclaredMethod(\"getProcessId\");\n pid_method.setAccessible(true);\n int pid = (Integer) pid_method.invoke(mgmt);\n return pid;\n } catch (IllegalAccessException | java.lang.reflect.InvocationTargetException | NoSuchMethodException |\nNoSuchFieldException e) {\n throw new CantKillMeException(\"Cant obtain pid\", e);\n }\n}\n</code></pre>\n</blockquote>\n\n<p>to just:</p>\n\n<pre><code>static int obtainPid() throws CantKillMeException {\n try {\n return ProcessHandle.current().pid();\n } catch (SecurityException e) {\n throw new CantKillMeException(\"Cant obtain pid\", e);\n }\n}\n</code></pre>\n\n<p>Although you don't want to do a <code>System.exit(0)</code> I would still plan it as a backup...</p>\n\n<p>You have </p>\n\n<blockquote>\n<pre><code>static void executeCommand(String command) throws CantKillMeException {\n try {\n Process process = Runtime.getRuntime().exec(command);\n process.waitFor();\n } catch (java.io.IOException | InterruptedException e) {\n throw new CantKillMeException(\"Cant execute command \" + command, e);\n }\n }\n</code></pre>\n</blockquote>\n\n<p>which anticipates exceptions on something that should terminate the process....</p>\n\n<p>I would instead log the exception (actually, catch any Throwable), and exit.... within a finally-block - I would do that in the <code>now()</code> method:</p>\n\n<pre><code>public static void now() throws CantKillMeException {\n try {\n int pid = obtainPid();\n String command = getCommand(pid);\n executeCommand(command);\n } catch (Throwable t) {\n System.out.println(t);\n } finally {\n System.exit(1);\n }\n}\n</code></pre>\n\n<p>You can choose a different (improved) logging mechanism.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-08T18:31:32.423",
"Id": "230381",
"ParentId": "230373",
"Score": "7"
}
},
{
"body": "<p>Adding to rolfl's answer:</p>\n\n<p>there should be a check for a signal handler: make sure there isn't one or, if there's one, that it exits the application.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-09T02:07:22.600",
"Id": "448782",
"Score": "0",
"body": "He kills using SIGKILL which can't be ignored or intercepted by a signal handler. SIGKILL is always deadly."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-09T00:38:10.580",
"Id": "230392",
"ParentId": "230373",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-08T13:45:38.273",
"Id": "230373",
"Score": "11",
"Tags": [
"java",
"multithreading",
"io",
"exception"
],
"Title": "Self-inflicted killing utility"
}
|
230373
|
<p>This is my first C# project. I still am a noob to programming, and while I'm happy I carried out this project, I know that my code needs A LOT of improving and that's why I posted it here.</p>
<p>This code represents a Login system for a bigger application in console, a password manager. This is why the <code>dashboard()</code> function in my code is commented, as I only posted the code for the login system. </p>
<p>Basically, the Main is composed from only one big recursive function, <code>registerOrLogIn()</code>. This function asks for 2 commands, 'Register' or 'Log in'. If the input is different, the function will of course call itself again (that's why it is a recursive one, right?) until the first input will be equal to 'Register' or 'Log in'. If either of them is inputted, the program will create an object from class <code>Credentials</code>. This object has 2 proprieties, username and password, both which are created by user input. Of course, when the user types the password, it will appear on console as asterisks like that ****, using <code>maskPass()</code> function.</p>
<p>Furthermore, after the object <code>user</code> is instantiated, the program will work with 2 cases. If first input was 'Log in', the program, through <code>dbVerifyUsername(user.getUsername)</code>, will search in the database if the inputted user actually exists. Of course, if the input was 'Register', the program will make sure through <code>dbVerifyUsername(user.getUsername)</code> that the username if not already picked. </p>
<p>Using <code>hashPassword(pass)</code> function, program hashes and saltes the password that the user inputs in the database when they register. In <code>verifyHashedPass(oldPass, newPass)</code>, the already saved password's hash and the introduced password are verified in order to match. If they do, great! the user can finally log in. In my code, when the user carries out the registration or the login, the function <code>dashboard(username)</code> is called. Otherwise, the console displays why they could not access their dashboard (e.g. passwords that do not match).</p>
<pre><code>using System;
using System.Data.SqlClient;
using System.Security.Cryptography;
namespace PasswordManagerwithCRUDoperations
{
class Program
{
static void Main(string[] args)
{
registerOrLogIn();
}
static void registerOrLogIn()
{
Console.WriteLine("Write 'Register' if you want to sign up or 'Log in' if you want to sign in");
string input = Console.ReadLine();
if (input != "Register" && input != "Log in")
{
Console.WriteLine("Command does not exist");
registerOrLogIn();
}
else
{
Console.WriteLine("Your command was {0}", input);
Credentials user = new Credentials();
Console.WriteLine("Username: ");
string usern = Console.ReadLine();
Console.WriteLine("Password: ");
string pass = maskPass();
user.setUsername(usern);
user.setPassword(pass);
if (input == "Register")
{
if (dbVerifyUsername(user.getUsername()))
{
hashPassword(user.getPassword());
dbInsertUser(user.getUsername(), hashPassword(user.getPassword()));
Console.WriteLine("You are now registered as {0}", user.getUsername());
//dashboard(user.getUsername());
}
else
{
Console.WriteLine("Username already exists");
registerOrLogIn();
}
}
if (input == "Log in")
{
SqlConnection connection = new SqlConnection(@"Server=Server;Database=passmanagerdb;Trusted_Connection=true");
connection.Open();
SqlCommand command = new SqlCommand("Select password from userstbl where username=@usern", connection);
command.Parameters.AddWithValue("@usern", user.getUsername());
using (SqlDataReader reader = command.ExecuteReader())
{
if (reader.Read())
{
string newPass = Convert.ToString(user.getPassword());
string oldPass = Convert.ToString(reader["password"]);
verifyHashedPass(newPass, oldPass);
if (verifyHashedPass(newPass, oldPass))
{
Console.WriteLine("Grant acces");
//dashboard(user.getUsername());
}
else
{
Console.WriteLine("Acces denied. Passwords do not match");
registerOrLogIn();
}
}
else
{
Console.WriteLine("Acces denied. Username not found in the database");
registerOrLogIn();
}
}
connection.Close();
}
}
}
static string maskPass()
{
string pass = "";
ConsoleKeyInfo key;
do
{
key = Console.ReadKey(true);
if (key.Key != ConsoleKey.Backspace && key.Key != ConsoleKey.Enter)
{
pass += key.KeyChar;
Console.Write("*");
}
else
{
if (key.Key == ConsoleKey.Backspace && pass.Length > 0)
{
pass = pass.Substring(0, (pass.Length - 1));
Console.Write("\b \b");
}
else if (key.Key == ConsoleKey.Enter)
{
break;
}
}
} while (key.Key != ConsoleKey.Enter);
Console.WriteLine();
return pass;
}
static bool dbVerifyUsername(string usern)
{
SqlConnection connection = new SqlConnection(@"Server=Server;Database=passmanagerdb;Trusted_Connection=true");
connection.Open();
SqlCommand command = new SqlCommand("Select id from userstbl where username=@usern", connection);
command.Parameters.AddWithValue("@usern", usern);
using (SqlDataReader reader = command.ExecuteReader())
{
if (reader.Read())
{
connection.Close();
return false;
}
else
{
connection.Close();
return true;
}
}
}
static string hashPassword(string pass)
{
RNGCryptoServiceProvider provider = new RNGCryptoServiceProvider();
byte[] salt = new byte[16];
provider.GetBytes(salt);
Rfc2898DeriveBytes pbkdf2 = new Rfc2898DeriveBytes(pass, salt, 10000);
byte[] hash = pbkdf2.GetBytes(20);
byte[] hashBytes = new byte[36];
Array.Copy(salt, 0, hashBytes, 0, 16);
Array.Copy(hash, 0, hashBytes, 16, 20);
string savedPass = Convert.ToBase64String(hashBytes);
return savedPass;
}
static bool verifyHashedPass(string newPw, string oldPw)
{ //reader["password"] - oldPw
//user.getPassword() -newPw
string theSavedPass;
theSavedPass = Convert.ToString(oldPw);
byte[] hashBytes = Convert.FromBase64String(theSavedPass);
byte[] salt = new byte[16];
Array.Copy(hashBytes, 0, salt, 0, 16);
Rfc2898DeriveBytes pbkdf2 = new Rfc2898DeriveBytes(newPw, salt, 10000);
byte[] hash = pbkdf2.GetBytes(20);
bool ok = true;
for (int i = 0; i < 20; i++)
{
if (hashBytes[i + 16] != hash[i])
{
ok = false;
}
}
return ok;
}
static void dbInsertUser(string usern, string pass)
{
SqlConnection connection = new SqlConnection(@"Server=Server;Database=passmanagerdb;Trusted_Connection=true");
connection.Open();
SqlCommand command = new SqlCommand("Insert into userstbl (username, password) values (@usern, @pass)", connection);
command.Parameters.AddWithValue("@usern", usern);
command.Parameters.AddWithValue("@pass", pass);
command.ExecuteNonQuery();
connection.Close();
}
class Credentials
{
private string username;
private string password;
public void setUsername(string usern)
{
username = usern;
}
public string getUsername()
{
return username;
}
public void setPassword(string pass)
{
password = pass;
}
public string getPassword()
{
return password;
}
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-08T17:57:38.127",
"Id": "448711",
"Score": "1",
"body": "Welcome to Code Review! Please tell us more about what your code is supposed to do and whether it does so satisfactory. Did you test it? Got any specific gripes with it?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-08T18:02:32.503",
"Id": "448712",
"Score": "1",
"body": "I'll update the description"
}
] |
[
{
"body": "<p>A few things I noticed:</p>\n\n<p>In <code>maskPass</code> after each <code>ReadKey</code> you're either concatenating a character with <code>pass</code> or you're assigning <code>pass</code> to a <code>Substring</code> of <code>pass</code>. This is very inefficient. Each concatenation and each call to <code>Substring</code>, creates a new string. It would be much better to use a <code>StringBuilder</code> to store the string until you're ready to return it.</p>\n\n<p>In <code>verifyHashedPass</code> you convert the string <code>oldPw</code> to a string then assign it to a variable, then you only use that variable once. I would suggest using <code>oldPw</code> directly.</p>\n\n<p>Also in the loop where you verify that the 2 hashes are the same, instead of using a <code>bool</code> there, it would make more sense to return false as soon as you find a mismatch and true if the loop finishes.</p>\n\n<p>In the <code>Credentials</code> class, you can simplify it by using automatic get and set:</p>\n\n<pre><code>public string username{ get; set;}\n</code></pre>\n\n<p>This translates to the same thing as you are already doing but making it much more simple.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-13T07:32:23.293",
"Id": "449459",
"Score": "0",
"body": "The `bool` in `verifyHashedPass` is probably there to make the timing as constant as possible. It's debatable whether this is necessary for comparing hashed passwords, but at least there should be a comment in the code, otherwise it might get \"optimized\" away."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-08T18:32:17.780",
"Id": "230382",
"ParentId": "230380",
"Score": "4"
}
},
{
"body": "<p>All in all, you did quite well.\nIf you have the option, I'd recommend letting a system like Active Directory handle user credentials rather than storing and validating themselves. However, as there's a cost involved with that, password hashes are the next best thing.</p>\n\n<p>PBKDF2 is a better choice than what I'm used to people using and you're salting it too, so kudos on that. (Argon2id and SCrypt are also good options. MD5 and SHA1 should not be used for passwords. SHA2 is on its way out. I don't know enough about SHA3 to comment.)</p>\n\n<p>I noticed that you have your connection string hard coded. I'm not sure if that's just for the code example or not, but it would be a good idea to move that outside of your code base (even though it doesn't have a password in it).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-12T19:41:04.290",
"Id": "230615",
"ParentId": "230380",
"Score": "3"
}
},
{
"body": "<p>Disclaimer: my first post here and I'm not C# programmer</p>\n\n<hr>\n\n<blockquote>\n <p>If the input is different, the function will of course call itself again (that's why it is a recursive one, right?)</p>\n</blockquote>\n\n<p>This is dangerous, as user can keep entering wrong inputs, which will increment scoping stack (eventually resulting in StackOverflowException being thrown).<br>\nEven doubly so, your function is the beginning of the program (it's not returning but calling dashboard() to pass on), so all stack layers made by wrong inputs will be kept all the way through</p>\n\n<p>Most basic approach of mitigating this is making it a loop with exiting condition</p>\n\n<pre><code>do\n{\n //Input from console\n}while(/*input isn't the one we need*/)\n</code></pre>\n\n<p>You may even add some protection from spamming and limit amount of tries later simply by working around this loop (unlike function stack, where you need to carry iteration results into next layers)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-21T05:21:49.277",
"Id": "450373",
"Score": "0",
"body": "Generally speaking, a recursive approach to this isn't that bad. Because the recursive call can be a tail call, the additional stack layers can be optimized away, making the recursion effectively act as a loop. Unfortunately the C# Compiler does not support this, which is a shame."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-21T08:28:56.827",
"Id": "450401",
"Score": "0",
"body": "@LukeG It's not tail call because function does not return. It's head recursion because it calls `dashboard` in the end"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-21T08:41:15.087",
"Id": "450404",
"Score": "0",
"body": "There are multiple instances where the recursive call is a tail call. Tail call does not necessarily need a return keyword, if it's the last statement in a function. This is definitely the case for the first recursive call, and the remaining 3 can be rewritten to be in tail call position. What the last called instance of \"registerOrLogIn\" does is irrelevant to the question, if a given recursive call is a tail call."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-12T22:41:19.220",
"Id": "230624",
"ParentId": "230380",
"Score": "4"
}
},
{
"body": "<p><strong>Recusion Abuse</strong></p>\n\n<p>This does not seem to be a naturally recursive problem and using recursion here causes more issues than it is worth: </p>\n\n<ul>\n<li>If the user enters too many invalid inputs, they can blow the stack.</li>\n<li><p>If a user errors out by inputting an incorrect password, they have to re-select their intent to login before they are able to try again.</p></li>\n<li><p>Control flow is not very flexible as the primary tool of control is\nrecursively starting from the beginning.</p></li>\n<li>What if you wanted to lock out the user after entering 5 incorrect passwords? Keeping track of this would be needlessly complex using recursion.</li>\n<li>Decreased readability.</li>\n</ul>\n\n<p><strong>Single Responsibility Principle</strong></p>\n\n<p>Functions should do one thing. They should do it well. They should do it only. The method name \"registerOrLogIn\" immediately signals the method is doing more than one thing because of the \"or\". The method is responsible for registering the user <em>and</em> logging in the user. This should be separated into more modular methods. Also, if there are other ways the user can access your application in the future will you keep adding to this method? It makes sense to start to separate things now.</p>\n\n<p><strong>Resource Management</strong></p>\n\n<p>Explicitly Calling .Close() is not necessary if wrapped in a using statement in C#. Consider wrapping all of your SqlConnection statements in a using statement. Also, your connection string should be a global constant of some sort. Realistically this would probably come from the web.config, but a constant in the program class would work for now. </p>\n\n<p><strong>Conclusion</strong></p>\n\n<p>This is a great start! I like the way you are salting your hashes. Although things could be more modular, it is pretty easy to understand the flow of the code. I have recorded my live code review and will leave the link below. I hope this feedback helps!</p>\n\n<p>Live code review:\n<a href=\"https://www.youtube.com/watch?v=c9ZheaGGRMI\" rel=\"nofollow noreferrer\">https://www.youtube.com/watch?v=c9ZheaGGRMI</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-26T23:17:18.440",
"Id": "451215",
"Score": "1",
"body": "Welcome to Code Review, nice first answer! Really above and beyond with a live code review!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-26T22:53:13.000",
"Id": "231356",
"ParentId": "230380",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "230382",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-08T17:45:21.420",
"Id": "230380",
"Score": "9",
"Tags": [
"c#",
"beginner",
"console",
"ado.net"
],
"Title": "Extremely basic login system in console"
}
|
230380
|
<p>A few weeks ago I decided to have a look at the Rust programming language. After a few standard exercises I chose to try to implement the SHA256 hashing algorithm, because why not.</p>
<p>The algorithm's state is stored in a struct, similar to Python's hashlib. This is the <code>lib.rs</code> file:</p>
<pre class="lang-rust prettyprint-override"><code>use std::convert::TryInto;
pub struct SHA256Hash {
h0: u32,
h1: u32,
h2: u32,
h3: u32,
h4: u32,
h5: u32,
h6: u32,
h7: u32,
finalized: bool,
total_bits: usize,
unprocessed_bytes: Vec<u8>,
input_block_size: usize
}
impl SHA256Hash {
/// Create a new hash instance
pub fn new() -> SHA256Hash {
SHA256Hash {
h0: 0x6a09e667,
h1: 0xbb67ae85,
h2: 0x3c6ef372,
h3: 0xa54ff53a,
h4: 0x510e527f,
h5: 0x9b05688c,
h6: 0x1f83d9ab,
h7: 0x5be0cd19,
finalized: false,
total_bits: 0,
unprocessed_bytes: Vec::new(),
input_block_size: 64
}
}
pub fn block_size(&self) -> usize {
self.input_block_size
}
/// update with a block of 512bit
fn update_block(&mut self, block: &[u8; 64]) {
// Initialize array of round constants:
// (first 32 bits of the fractional parts of the cube roots of the first 64 primes 2..311):
let round_constants: [u32; 64] = [
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
];
let mut w: [u32; 64] = [0; 64];
for j in 0..16 {
// let mut bytes: [u8; 4] = Default::default();
// bytes.copy_from_slice(&block[j*4..(j+1)*4]);
// w[j] = transform_array_of_u8_big_endian_to_u32(&bytes);
w[j] = transform_array_of_u8_big_endian_to_u32(block[j*4..(j+1)*4].try_into().expect(""));
// println!("w[{:2}] {:08X?}", j, w[j]);
}
// Extend the first 16 words into the remaining 48 words w[16..63] of the message schedule array:
for j in 16..64 {
let s0 = w[j-15].rotate_right(7) ^ w[j-15].rotate_right(18) ^ (w[j-15] >> 3);
let s1 = w[j-2].rotate_right(17) ^ w[j-2].rotate_right(19) ^ (w[j-2] >> 10);
w[j] = w[j-16].wrapping_add(s0).wrapping_add(w[j-7]).wrapping_add(s1);
}
let mut a = self.h0;
let mut b = self.h1;
let mut c = self.h2;
let mut d = self.h3;
let mut e = self.h4;
let mut f = self.h5;
let mut g = self.h6;
let mut h = self.h7;
// Compression function main loop:
for j in 0..64 {
let s1 = e.rotate_right(6) ^ e.rotate_right(11) ^ e.rotate_right(25);
let ch = (e & f) ^ (!e & g);
let temp1 = h.wrapping_add(s1).wrapping_add(ch).wrapping_add(round_constants[j]).wrapping_add(w[j]);
let s0 = a.rotate_right(2) ^ a.rotate_right(13) ^ a.rotate_right(22);
let maj = (a & b) ^ (a & c) ^ (b & c);
let temp2 = s0.wrapping_add(maj);
h = g;
g = f;
f = e;
e = d.wrapping_add(temp1);
d = c;
c = b;
b = a;
a = temp1.wrapping_add(temp2);
}
self.h0 = self.h0.wrapping_add(a);
self.h1 = self.h1.wrapping_add(b);
self.h2 = self.h2.wrapping_add(c);
self.h3 = self.h3.wrapping_add(d);
self.h4 = self.h4.wrapping_add(e);
self.h5 = self.h5.wrapping_add(f);
self.h6 = self.h6.wrapping_add(g);
self.h7 = self.h7.wrapping_add(h);
}
/// consume blocks of unprocessed bytes
fn consume(&mut self) {
assert_eq!(self.unprocessed_bytes.len() % 64, 0);
let n_blocks = self.unprocessed_bytes.len() / 64;
for i in 0..n_blocks {
let mut block: [u8; 64] = [0; 64];
// the copy seems to be necessary because of a multiple
// mutable/immutable borowing situation I've set up for myself
block.copy_from_slice(&self.unprocessed_bytes[i*64..(i+1)*64]);
self.update_block(&block);
// it's a pitty that try_into does not work here
}
self.unprocessed_bytes.clear();
}
/// query the hash digest
pub fn digest(&mut self) -> [u32; 8] {
self.finalize();
[self.h0, self.h1, self.h2, self.h3, self.h4, self.h5, self.h6, self.h7]
}
/// query the hex digest, formatted as hexadecimal string
pub fn hex_digest(&mut self) -> String {
let digest = self.digest();
format!(
"{:08X?}{:08X?}{:08X?}{:08X?}{:08X?}{:08X?}{:08X?}{:08X?}",
digest[0], digest[1], digest[2], digest[3],
digest[4], digest[5], digest[6], digest[7]
)
}
/// update the hash state
pub fn update(&mut self, input: &[u8]) -> bool {
if self.finalized || input.len() == 0 {
return false;
}
let input_len_bytes = input.len();
self.total_bits += input_len_bytes * 8;
let remaining_bytes = (input_len_bytes + self.unprocessed_bytes.len()) % 64;
self.unprocessed_bytes.extend(input[..(input_len_bytes-remaining_bytes)].iter().clone());
self.consume();
if remaining_bytes > 0 {
self.unprocessed_bytes.extend(input[input_len_bytes-remaining_bytes..].iter().clone());
}
true
}
fn finalize(&mut self) {
self.unprocessed_bytes.push(0x80);
let n_padding_bits = 512 - (self.total_bits + 8 + 64) % 512;
let n_padding_bytes = n_padding_bits / 8;
self.unprocessed_bytes.extend(vec![0; n_padding_bytes]);
let length: u64 = self.total_bits.try_into().unwrap();
self.unprocessed_bytes.extend(&transform_u64_to_array_of_u8_big_endian(length));
self.consume();
self.finalized = true;
}
}
///////////////////////////////////////////////////////////////////////////////
fn transform_u64_to_array_of_u8_big_endian(x: u64) -> [u8; 8] {
let b1 = ((x >> 56) & 0xff) as u8;
let b2 = ((x >> 48) & 0xff) as u8;
let b3 = ((x >> 40) & 0xff) as u8;
let b4 = ((x >> 32) & 0xff) as u8;
let b5 = ((x >> 24) & 0xff) as u8;
let b6 = ((x >> 16) & 0xff) as u8;
let b7 = ((x >> 8) & 0xff) as u8;
let b8 = (x & 0xff) as u8;
[b1, b2, b3, b4, b5, b6, b7, b8]
}
fn transform_array_of_u8_big_endian_to_u32(arr_of_u8: &[u8; 4]) -> u32 {
let mut x: u32 = 0;
x |= (arr_of_u8[0] as u32) << 24;
x |= (arr_of_u8[1] as u32) << 16;
x |= (arr_of_u8[2] as u32) << 8;
x |= arr_of_u8[3] as u32;
x
}
///////////////////////////////////////////////////////////////////////////////
#[cfg(test)]
mod tests {
use super::SHA256Hash;
/// Run empty test input from FIPS 180-2
#[test]
fn sha256_nist_empty() {
let mut hasher = SHA256Hash::new();
hasher.update(&[]);
let digest = hasher.digest();
assert_eq!(
digest,
[0xe3b0c442, 0x98fc1c14, 0x9afbf4c8, 0x996fb924,
0x27ae41e4, 0x649b934c, 0xa495991b, 0x7852b855]
);
}
/// Run abc test from FIPS 180-2
#[test]
fn sha256_nist_abc() {
let mut hasher = SHA256Hash::new();
hasher.update(b"abc");
let digest = hasher.digest();
assert_eq!(
digest,
[0xba7816bf, 0x8f01cfea, 0x414140de, 0x5dae2223,
0xb00361a3, 0x96177a9c, 0xb410ff61, 0xf20015ad]
)
}
/// Run two-block test from FIPS 180-2
#[test]
fn sha256_nist_two_blocks() {
let mut hasher = SHA256Hash::new();
hasher.update(b"abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq");
let digest = hasher.digest();
assert_eq!(
digest,
[0x248d6a61, 0xd20638b8, 0xe5c02693, 0x0c3e6039,
0xa33ce459, 0x64ff2167, 0xf6ecedd4, 0x19db06c1]
);
}
/// Run large input test (1,000,000 x a) from FIPS 180-2
#[test]
fn sha256_nist_large_input() {
let input_str = std::iter::repeat("a").take(1_000_000).collect::<String>();
let input = input_str.as_bytes();
let mut hasher = SHA256Hash::new();
hasher.update(&input);
let digest = hasher.digest();
assert_eq!(
digest,
[0xcdc76e5c, 0x9914fb92, 0x81a1c7e2, 0x84d73e67,
0xf1809a48, 0xa497200e, 0x046d39cc, 0xc7112cd0]
);
}
}
</code></pre>
<p><code>lib.rs</code> comes with a small suite of unit tests as specified in <a href="https://csrc.nist.gov/CSRC/media/Publications/fips/180/2/archive/2002-08-01/documents/fips180-2withchangenotice.pdf" rel="nofollow noreferrer">FIPS 180-2</a> Appendix B. The test suite can be run using <code>cargo test [--release]</code></p>
<p>Then there is also <code>main.rs</code> which generates an executable to be used a command-line tool:</p>
<pre class="lang-rust prettyprint-override"><code>use std::env;
use std::fs::File;
use std::io::{BufRead, BufReader};
use sha256::SHA256Hash;
fn main() -> std::io::Result<()> {
let mut hasher = SHA256Hash::new();
let args: Vec<String> = env::args().collect();
if args.len() < 2 {
eprintln!("Please provide a filename as command line argument!");
return Ok(());
}
let filename = &args[1];
let file = File::open(filename)?;
let chunk_size: usize = hasher.block_size() * 1024;
let mut reader = BufReader::with_capacity(chunk_size, file);
loop {
let length = {
let buffer = reader.fill_buf()?;
hasher.update(buffer);
buffer.len()
};
if length == 0 {
break;
}
reader.consume(length);
}
println!("{} {}", hasher.hex_digest().to_ascii_lowercase(), filename);
Ok(())
}
</code></pre>
<p>As an example, let's compute the hash of lib.rs ;-)</p>
<pre class="lang-none prettyprint-override"><code>cargo run --release src\lib.rs
86dccf89c7cb4de0837a2c4a3c709ae7845151338a1a21a8321fcbf9e4d8dcf7 src\lib.rs
</code></pre>
<p>Computing the hash for an ISO image of 3.64 GiB takes roughly 39s here on my laptop (35s with 7zip's built-in SHA256).</p>
<p>I'm open to all kinds of feedback, be it style, idiomatic rust, performance, usability, whatever comes to your mind.</p>
<hr>
<p><code>Cargo.toml</code> for completeness:</p>
<pre><code>[package]
name = "hash_sha256"
version = "0.1.0"
authors = ["AlexV"]
edition = "2018"
[lib]
name = "sha256"
path = "src/lib.rs"
</code></pre>
<hr>
<p>I'm aware of a <a href="https://codereview.stackexchange.com/q/221826/92478">similar question</a> here on Code Review, but unfortunately it has no answer. Also from what I can judge, the approaches are reasonably different to exist in their own right.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-08T20:46:48.240",
"Id": "448727",
"Score": "1",
"body": "In preparation for a proper answer, I'm laying out an implementation trait and a `criterion` benchmark so we can profile your code together and find improvements. SHA256 is a good way to challenge your optimization skills, so it'll definitely be a fun challenge :-)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-08T21:04:01.007",
"Id": "448731",
"Score": "0",
"body": "@SébastienRenauld: Take your time. A quick Google search on profiling in Rust earlier in my Rust endeavours left me a little bit disappointed, but the `criterion` crate sounds interesting."
}
] |
[
{
"body": "<p>First off, let's start with a simple assumption: SIMD is off the table. As such, your kernel computation (<code>update_block</code>) is mostly optimized, and instead, I ended up focusing on the rest.</p>\n\n<h1>Some bad news</h1>\n\n<p>After profiling, and as expected, the bulk of the CPU time of your SHA256 implementation is in <code>update_block()</code>. No real surprise there. As a result, we know ahead of time that we can do very little to ease the pains of the 64 rounds of operations without resorting to some devious trickery.</p>\n\n<p>We can, however, make one simple change. We're going to pull in the <code>byteorder</code> crate and use it to convert our <code>u8</code> arrays into <code>u32</code>s. This will both ease our pain and provide a better version of what you already had. Since we're always feeding it 4 bytes (verifiable by code logic), we can safely drop the slice size prefix and benefit from the blanket <code>&[u8]</code> <code>Read</code> implementation.</p>\n\n<p>It also looks neat and inlinable:</p>\n\n<pre><code>fn transform_array_of_u8_big_endian_to_u32(mut arr_of_u8: &[u8]) -> u32 {\n arr_of_u8.read_u32::<BigEndian>().unwrap()\n}\n</code></pre>\n\n<h1>Some good news</h1>\n\n<p>There's a <em>ton</em> of allocations we can remove!</p>\n\n<p>We're going to change the method signature of <code>consume</code> from <code>fn consume(&mut self);</code> to <code>fn consume(&mut self, bytes: &[u8]);</code>. The reason for this is the pretty neat performance gain we can score by doing the following (<a href=\"https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=fb9ec52bdd7ace8ceeb2e8d79c5ef051\" rel=\"nofollow noreferrer\"><strong>playground</strong></a>):</p>\n\n<pre class=\"lang-rust prettyprint-override\"><code>fn consume(&mut self, mut bytes: &[u8]) {\n let input_len_bytes = bytes.len();\n let unprocessed_len = self.unprocessed_bytes.len();\n self.total_bits += input_len_bytes * 8;\n // Do we have bytes in the unprocessed buffer?\n if unprocessed_len > 0 {\n if (unprocessed_len + input_len_bytes) < 64 {\n // Nothing to do, we just append\n // Copy up to 63 bytes to our Vec\n self.unprocessed_bytes.extend_from_slice(bytes);\n return;\n }\n let (additional, new_bytes) = bytes.split_at(64 - unprocessed_len);\n // Reassign\n bytes = new_bytes;\n // Copy up to 64 bytes from what we just took\n self.unprocessed_bytes.extend_from_slice(additional);\n // We can afford a 64-byte clone\n self.update_block(self.unprocessed_bytes.clone().as_slice());\n self.unprocessed_bytes.clear();\n // Call ourselves\n //return self.inner_consume(new_bytes);\n }\n let iter = bytes.chunks_exact(64);\n let remainder_i = iter.clone();\n for block in iter {\n self.update_block(&block)\n }\n let bytes = remainder_i.remainder();\n self.unprocessed_bytes.extend_from_slice(bytes); // max 64bytes allocated\n}\n</code></pre>\n\n<p>This also opens up repeated calls to <code>update()</code>, something which the previous version fell over on (index out of bounds errors). The <code>chunks_exact()</code> iterator takes advantage that the slice is not mutable and quite literally just moves a pointer around. This both frees us from copies of the data and issues regarding ownership.</p>\n\n<p>Honestly, after having a proper look at profiling data, that's as far as you'll go without venturing into funky territory on the update function, namely <code>simd</code> (via <code>packed_simd</code>); as a learning experiment, I'd strongly recommend it. It is currently nightly-only (it was stable until Rust 1.33, then it broke, and it's on the way to being stable again), but it's worth the hassle - we're talking 10-15x speedups. Due to the nature of the repetitive operation in SHA256, it is ideal for a 256bit (u32x8) vector.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-09T11:55:48.337",
"Id": "448841",
"Score": "0",
"body": "Thanks for your feedback! The playground version also has the trait implementation you were talking about in your comment. I assume it's used to provide a clear (public) interface?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-09T12:06:01.277",
"Id": "448843",
"Score": "0",
"body": "@AlexV Correct :-) it's also useful for benchmarking purposes - write a bench iterator requiring `T`, where `T` in this case would be that trait; from there, you can generate as many alternatives as you want provided they all implement the trait."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-10T06:42:33.770",
"Id": "448982",
"Score": "0",
"body": "I did play around with your code a little bit (mainly copied it ;-) ) and timed it on my \"reference ISO\". Much to my suprise, it was about 8-10% slower than the original one (over multiple interleaved test runs with the original). After that, I created a [very simple criterion benchmark](https://gist.github.com/alexvorndran/2868f9efa4e60321289f0cc495798189) using the one million \"a\" string as input, which seems to also support that observation. Any thoughts on that? Maybe depending on the hardware?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-10T09:22:22.383",
"Id": "449011",
"Score": "0",
"body": "@AlexV what platform are you on and how much can you `renice` the process? When I was benchmarking it I gave it realtime priority due to the bulk (90%+) of the time being spent in `update_block()` (and therefore, anything changed will be *extremely* small). I reckon it's worth digging into"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-10T09:44:27.750",
"Id": "449015",
"Score": "0",
"body": "This was on Windows 10 x64 on a 1st gen Core i5. I'm going to try to renice the benchmark (or the Windows equivalent thereof) once I get home and will also test on a Linux machine."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-13T18:32:05.027",
"Id": "449523",
"Score": "0",
"body": "Still looking into this. Anyway, thanks for your feedback! I appreciate it very much."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-13T18:32:59.953",
"Id": "449524",
"Score": "0",
"body": "@AlexV I forgot about this question :-( the reputation kicked me back into it. I'll be home in two hours and will have another proper look either later today or tomorrow."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-09T00:31:28.880",
"Id": "230391",
"ParentId": "230384",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "230391",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-08T19:51:48.803",
"Id": "230384",
"Score": "5",
"Tags": [
"beginner",
"reinventing-the-wheel",
"rust",
"cryptography"
],
"Title": "Educational implementation of SHA256 in Rust"
}
|
230384
|
<p>I'm trying to find the best solutions for operations on the following database:</p>
<pre><code> Employee (EmployeeId, Surname, Salary, DepartmentId)
Department (DepartmentId, DeptName, City, Director)
Project (ProjectId, ProjectName, Budget, Director)
Works (EmpoyeeId, ProjectId)
</code></pre>
<p>My queries:</p>
<p>1 SQL query to find the surname of the employees who are directors of a department.</p>
<pre><code>SELECT Surname
FROM Employee
WHERE Employee.EmployeeId IN (
SELECT Department.Director
FROM Department
);
</code></pre>
<p>2 SQL query to find the employee surname and salary of all employees who work in Haarlem.</p>
<pre><code>SELECT Surname, Salary, City
FROM Employee,Department
WHERE Department.City = ‘Haarlem’;
</code></pre>
<p>3 SQL query to find the names of the projects whose budget is higher than 100 and the surnames of the employees who work on them.</p>
<pre><code>SELECT ProjectName, Budget, Surname
FROM Project, Employee, Works
WHERE Project.Budget > 100
AND Works.EmployeeId = Employee.EmployeeId
AND Works.ProjectId = Project.ProjectId;
</code></pre>
<p>Are there any better ways to get the information needed?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-08T20:47:10.440",
"Id": "448728",
"Score": "0",
"body": "Can anyone be a director of a department that's different to their department from the Employee table? Why don't you use a JOIN for the first query?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-09T02:12:21.370",
"Id": "448783",
"Score": "1",
"body": "What flavour of SQL? They're unfortunately not all the same."
}
] |
[
{
"body": "<ol>\n<li><pre><code>SELECT Surname\nFROM Employee\nJOIN Department ON Department.Director = Employee.EmployeeId;\n</code></pre>\n\n<p>Other than not requiring a subquery, this is generally a better thing to do because you can then easily access the matching <code>Department</code> table if you ever need to select a column from it.</p></li>\n<li><p>Are you sure that this even works? You aren't joining the employee's department to the department ID. This should likely be:</p>\n\n<pre><code>SELECT Surname, Salary, City\nFROM Employee\nJOIN Department ON Department.DepartmentId = Employee.DepartmentId\n AND Department.City = 'Haarlem';\n</code></pre></li>\n<li><pre><code>SELECT ProjectName, Budget, Surname\nFROM Employee\nJOIN Works ON Works.EmployeeId = Employee.EmployeeId\nJOIN Project ON Project.ProjectId = Works.ProjectId\n AND Project.Budget > 100;\n</code></pre>\n\n<p>This should be functionally equivalent but uses cleaner syntax.</p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-09T02:26:27.857",
"Id": "230399",
"ParentId": "230385",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-08T20:30:06.740",
"Id": "230385",
"Score": "3",
"Tags": [
"sql",
"database"
],
"Title": "SQL query on relational schema"
}
|
230385
|
<p>I am building a simple Java command-line application. And I want to know the best practice and make my code clean. Can anybody suggest to me how many different classes I can make and what more method I need to write to make my code clean? How can I write unit testing for the methods? I am new to writing unit tests.</p>
<p>The question is, I need to call an API then take input from a user and according to the user input I need to call another API, then show some data based on minimum or maximum. I am confused that should I write a separate class for API calls or keep them in the same file. Should I divide my API calling methods more or not? Thanks :)</p>
<pre><code>import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.*;
import static java.lang.System.out;
public class BitcoinRateCheckApplicationByCurrency {
public static final String URL = "https://api.coindesk.com/v1/bpi/currentprice.json";
public static JSONObject jsonAPIresponseObject = null;
public static void main(String[] args) throws IOException {
jsonAPIresponseObject = getJSONAPIdataFromURL(URL);
out.println("Input a currency code (USD, EUR, GBP, etc.)");
;
Scanner scanner = new Scanner(System.in);
String currency = scanner.nextLine();
JSONObject bpiObject = (JSONObject) jsonAPIresponseObject.get("bpi");
JSONObject currencyDataObject = (JSONObject) bpiObject.get(currency);
Double currentRate = (Double) currencyDataObject.get("rate_float");
Date dNow = new Date();
SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd");
System.out.println("Current Date: " + ft.format(dNow));
Calendar cal = Calendar.getInstance();
cal.setTime(new Date());
cal.add(Calendar.DATE, -30);
Date dateBefore30Days = cal.getTime();
String currentDate = ft.format(dNow);
String fromDate = ft.format(dateBefore30Days);
String apiDataRangeURL = "https://api.coindesk.com/v1/bpi/historical/close.json?start=" + fromDate + "&end=" + currentDate + "&?currency=" + currency;
JSONObject lastOneMonthDataObject = getJSONAPIdataFromURL(apiDataRangeURL);
JSONObject obj = (JSONObject) lastOneMonthDataObject.get("bpi");
Set<String> keySet = obj.keySet();
ArrayList<Double> priceListForDateRange = new ArrayList<Double>();
for (String x : keySet) {
double price = (Double) obj.get(x);
priceListForDateRange.add(price);
}
out.println("- The current Bitcoin rate, in the requested currency: " + currentRate);
out.println("- The lowest Bitcoin rate in the last 30 days, in the requested currency: " + getMinValue(priceListForDateRange));
out.println("- The highest Bitcoin rate in the last 30 days, in the requested currency: " + getMaxValue(priceListForDateRange));
}
public static JSONObject getJSONAPIdataFromURL(String url) throws IOException {
JSONObject responseJSON = null;
URL urlForGetRequest = new URL(url);
String readLine = null;
HttpURLConnection conection = (HttpURLConnection) urlForGetRequest.openConnection();
conection.setRequestMethod("GET");
int responseCode = conection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
BufferedReader in = new BufferedReader(new InputStreamReader(conection.getInputStream()));
StringBuffer response = new StringBuffer();
while ((readLine = in.readLine()) != null) {
response.append(readLine);
}
in.close();
responseJSON = new JSONObject(response.toString());
} else {
System.out.println("GET NOT WORKED");
}
return responseJSON;
}
public static double getMaxValue(ArrayList<Double> numbers) {
double maxValue = numbers.get(0);
for (int i = 1; i < numbers.size(); i++) {
if (numbers.get(i) > maxValue) {
maxValue = numbers.get(i);
}
}
return maxValue;
}
public static double getMinValue(ArrayList<Double> numbers) {
double minValue = numbers.get(0);
for (int i = 1; i < numbers.size(); i++) {
if (numbers.get(i) < minValue) {
minValue = numbers.get(i);
}
}
return minValue;
}
}
<span class="math-container">```</span>
</code></pre>
|
[] |
[
{
"body": "<p>Before separating the code into classes try separating it into more methods. At the very least separate business/logic code and input/output code. You should be able to use the same, unchanged business code no matter if it's a command line program, has a GUI or is a web application. For example <code>getJSONAPIdataFromURL</code> shouldn't write to <code>System.out</code>, but return an error value or throw an exception (which you should catch and display to user in the input/output part of the code). That business code would then be a prime example to be put into a separate class.</p>\n\n<p>There are many other things that can be done:</p>\n\n<hr>\n\n<blockquote>\n<pre><code>import java.util.*;\n</code></pre>\n</blockquote>\n\n<p>Don't import using wildcards.</p>\n\n<blockquote>\n<pre><code>import static java.lang.System.out;\n</code></pre>\n</blockquote>\n\n<p>If you import something statically, then use it everywhere and not just in a few places. However I wouldn't statically import <code>System.out</code>, since <code>System.out.println(...)</code> is more readable than just <code>out.println(...)</code>.</p>\n\n<hr>\n\n<p>There is no reason for <code>jsonAPIresponseObject</code> to be a (static) field. It's not used anywhere else than in the <code>main</code> method, and even if it weren't, then it should be passed around to other methods as an argument.</p>\n\n<hr>\n\n<p>Consider (optionally) allowing the user to pass the currency as a command line argument.</p>\n\n<hr>\n\n<p><code>.close()</code> the <code>Scanner</code> and the <code>InputStream</code> you get from the <code>HttpConnection</code> after you've used it, for example using <a href=\"https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html\" rel=\"nofollow noreferrer\">\"try with resources\"</a> and <code>.disconnect()</code> the <code>HttpConnection</code>.</p>\n\n<p>Consider using an third party HTTP client library. It maybe a a bit heavy weight for such a small project, but the API is much nicer. (Or Java 9 has a new HTTP client, that is better than the old one).</p>\n\n<hr>\n\n<p>You are neither checking if the <code>JSONObject::get</code> calls are throwing an exception nor checking if you safely can cast its results. Use <code>JSONObject::optJSONObject</code> (and <code>JOSNObject::optDouble</code> for doubles) to get results that don't need casting and check them for null.</p>\n\n<hr>\n\n<p>If you have Java 8, then use the \"new\" <code>LocalDate</code> class to handle dates. It's much simpler than <code>Date</code>/<code>Calendar</code>:</p>\n\n<pre><code> // The formatter should be a static final field;\n DateTimeFormatter ft = DateTimeFormatter.ISO_LOCAL_DATE;\n\n LocalDate dNow = LocalDate.now();\n LocalDate dateBefore30Days = dNow.minusDays(30);\n\n String currentDate = ft.format(dNow);\n String fromDate = ft.format(dateBefore30Days);\n</code></pre>\n\n<hr>\n\n<p>When building an URL make sure that URL parameters are properly escaped, especially since the currency is user input. </p>\n\n<hr>\n\n<p>Use the smallest possible/sensible interface when declaring variables and method signatures. Instead of </p>\n\n<pre><code>ArrayList<Double> priceListForDateRange = new ArrayList<Double>();\n</code></pre>\n\n<p>and </p>\n\n<pre><code>public static double getMaxValue(ArrayList<Double> numbers) { \n</code></pre>\n\n<p>just </p>\n\n<pre><code>List<Double> priceListForDateRange = new ArrayList<>();\n</code></pre>\n\n<p>and </p>\n\n<pre><code>public static double getMaxValue(List<Double> numbers) {\n</code></pre>\n\n<hr>\n\n<p>The min/max methods can be simplified by using Java 8 streams, e.g:</p>\n\n<pre><code>public static double getMaxValue(List<Double> numbers) {\n return numbers.stream().max(Comparator.naturalOrder()).get();\n}\n</code></pre>\n\n<p>or since you only need the min and max values, calculate them directly in the loop reading them from the JSONObject.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-09T21:01:38.453",
"Id": "448923",
"Score": "0",
"body": "Many many thanks. I am really grateful for your suggestions. I tried to incorporate all of your suggestions. Here is my code. Any further suggestions if needed would be appreciated. \n\nhttps://github.com/forhadmethun/BitcoinRateCheckApplicationByCurrencyJavaCommandLine.git"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-10T07:02:03.947",
"Id": "448986",
"Score": "0",
"body": "@forhadmethun Post a new question with the new code."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-09T10:20:01.440",
"Id": "230415",
"ParentId": "230389",
"Score": "4"
}
},
{
"body": "<p>I'm just adding some elements to the explanation by RoToRa, use the method <a href=\"https://docs.oracle.com/javase/8/docs/api/java/time/LocalDate.html#toString--\" rel=\"nofollow noreferrer\">toString</a> of the class <code>LocalDate</code> because it outputs the date in ISO-8601 format uuuu-MM-dd, and this is exactly the format you are using. If you are looking for math operations on streams of <code>Double</code> like\nsearching for min, max, average you can use the class <a href=\"https://docs.oracle.com/javase/8/docs/api/java/util/DoubleSummaryStatistics.html\" rel=\"nofollow noreferrer\">DoubleSummaryStatistics</a> like the example below:</p>\n\n<pre><code>List<Double> priceListForDateRange;// previously initialized in the code from json values\nDoubleSummaryStatistics statistics = priceListForDateRange.stream()\n .mapToDouble(Double::doubleValue)\n .summaryStatistics();\nSystem.out.println(\"- The lowest Bitcoin rate in the last 30 days, in the requested currency: \" + statistics.getMin());\nSystem.out.println(\"- The highest Bitcoin rate in the last 30 days, in the requested currency: \" + statistics.getMax());\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-09T21:01:43.627",
"Id": "448924",
"Score": "0",
"body": "Many many thanks. I am really grateful for your suggestions. I tried to incorporate all of your suggestions. Here is my code. Any further suggestions if needed would be appreciated. \n\nhttps://github.com/forhadmethun/BitcoinRateCheckApplicationByCurrencyJavaCommandLine.git"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-10T10:38:12.370",
"Id": "449022",
"Score": "0",
"body": "@forhadmethun You are welcome, once you have modified your code you can post a new question with the new code."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-09T13:02:34.667",
"Id": "230424",
"ParentId": "230389",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-08T21:54:27.060",
"Id": "230389",
"Score": "7",
"Tags": [
"java",
"json",
"api",
"unit-conversion",
"cryptocurrency"
],
"Title": "Java command-line API client to fetch Bitcoin exchange rates"
}
|
230389
|
<p>This bubble sort code is very slow compared to the original.</p>
<pre><code>import time
import random
def bubble_sort(a):
#setting my variables
yes=0
d=0
#making a switch
while yes==0:
if d>=last_thing-1:
d=0
if a[0+d]>a[1+d]:
#switching the order
a[0+d],a[1+d]=a[1+d],a[0+d]
d+=1
if correct_order(a):
#turning off the switch
yes=1
return(a)
def correct_order(a):
for i in range(len(a)):
if i != a[i]:
return(False)
return(True)
if __name__ == '__main__':
#setting your range
last_thing=1000+1
#making the random list
a= list(range(0,last_thing))
random.shuffle(a)
#easier setting
currentsortingmethod=bubble_sort(a)
#prints your sorted list
print("--------------------------------------------------------------------------------\n",str(currentsortingmethod).strip('[]').replace(" ", "").replace("'",""))
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-08T22:55:25.937",
"Id": "448742",
"Score": "0",
"body": "Hello and welcome to CodeReview. Your post needs some work. Please reformat it so that your code is all included in a code block."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-08T23:01:45.993",
"Id": "448744",
"Score": "0",
"body": "@Renderien, I fixed it however it might not be working properly I'll check"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-08T23:04:30.450",
"Id": "448745",
"Score": "0",
"body": "@RobbieAwesome This is not working code because it's incomplete `last_thing` and `correct_order` are not defined, fix it or this will count as off-topic and most probably will be closed."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-08T23:09:50.057",
"Id": "448747",
"Score": "3",
"body": "Then edit your post and provide a full working code"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-09T01:40:42.207",
"Id": "448773",
"Score": "0",
"body": "@bullseye What in particular about the code does not work?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-09T01:42:37.750",
"Id": "448775",
"Score": "0",
"body": "There are several issues with this question, including: the title should only indicate what the code does; you make mention of comparison to an \"original\" implementation but don't show the original; and you don't describe why you're implementing a bubble sort, which is already known to be a slow algorithm."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-09T01:51:01.647",
"Id": "448780",
"Score": "1",
"body": "@Reinderien It looks like maybe I jumped to early conclusions, it's currently working, I tested it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-05T13:47:33.167",
"Id": "459977",
"Score": "0",
"body": "What *is* `the original` you compared this to? The fun thing of the code presented is calling `correct_order(a)` in `bubble_sort(a)`'s solitary loop."
}
] |
[
{
"body": "<h2><code>last_thing</code></h2>\n<p>You define <code>last_thing</code> and use it to initialise your array, which is fine, however you also use it within your actual <code>bubble_sort</code> function. This seems wrong, it would be better to use the length of the supplied array in order to determine when to stop. This will make your code more portable and able to handle different sized arrays.</p>\n<h2>When to check for <code>correct_order</code></h2>\n<p>You only need to check if the array is sorted at the end of each pass. As it stands, you're checking if the array is sorted for each entry you're processing, even if you haven't done anything with the array. Which feels like you're turning an O(n^2) algorithm into an O(n^3) solution. Another approach you can use is to keep track of whether or not you've actually done a swap on a given pass, if you haven't then you know it's because the list is already sorted.</p>\n<h2>looping</h2>\n<p>This is probably very subjective, but I don't like this:</p>\n<pre><code>if d>=last_thing-1:\n d=0\n</code></pre>\n<p>To me, it makes the start of each pass through the list less obvious than other methods.</p>\n<h2>Generalisability</h2>\n<p>Algorithms are used to solve general problems. There are several instances where you've tied your solution to the exact problem (such as your use of <code>last_thing</code>) you're solving which means it can't solve the general problem. The way you've implemented <code>correct_order</code> is another good example of this. You iterate through the list and make sure that each item in the list has the same value as it's position in the list. This works for your exact problem, but makes your algorithm useless if you wanted to sort <code>[8,2,4,6]</code>. Consider writing unit tests so that you can actually exercise your code with different inputs to make sure they can be handled. This will help you to build code that is not so tightly coupled to the specific problem you're solving.</p>\n<h2>Odds and Bobs</h2>\n<ul>\n<li>You've imported <code>time</code>, but you're not using it. Redundant code adds unnecessary noise, consider removing the unused import.</li>\n<li>Names matter. <code>a</code> and <code>d</code> aren't very descriptive, consider expanding the names to describe what it is they represent.</li>\n<li>If you just need two values (0, 1), consider using a boolean instead (False/True).</li>\n<li>Try to standardise on your spacing, sometimes you have spaces around operators sometimes you don't... it can make the code look messy.</li>\n</ul>\n<p>Taking some of the above into account, a refactored version of your code might look something like this:</p>\n<pre><code>def bubble_sort(array):\n while not correct_order(array):\n for index in range(len(array) - 1):\n if array[0+index] > array[1+index]:\n array[0+index],array[1+index] = array[1+index],array[0+index]\n return(array)\n\ndef correct_order(array): \n for i in range(len(array)-1):\n if array[i] > array[i+1]:\n return(False)\n return(True)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-11T21:39:57.450",
"Id": "260628",
"ParentId": "230390",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-08T22:41:51.773",
"Id": "230390",
"Score": "0",
"Tags": [
"python",
"sorting",
"reinventing-the-wheel"
],
"Title": "Bubble sort optimization"
}
|
230390
|
<p>I have an NLTK parsing function that I am using to parse a ~2GB text file of a TREC dataset. The goal for this dataset is tokenize the entire collection, perform some calculations (such as calculating TF-IDF weights, etc), and then to run some queries against our collection to use cosine similarity and return the best results.</p>
<p>As it stands, my program works but takes well over an hour (typically between 44-61 minutes) to run. The timing is broken down as follows:</p>
<pre class="lang-none prettyprint-override"><code>TOTAL TIME TO COMPLETE: 4487.930628299713
TIME TO GRAB SORTED COSINE SIMS: 35.24157094955444
TIME TO CREATE TFIDF BY DOC: 57.06743311882019
TIME TO CREATE IDF LOOKUP: 0.5097501277923584
TIME TO CREATE INVERTED INDEX: 2.5217013359069824
TIME TO TOKENIZE: 4392.5711488723755
</code></pre>
<p>So obviously, the tokenization is accounting for ~98% of the time. I am looking for a way to speed that up.</p>
<p>The tokenization code is below:</p>
<pre class="lang-python prettyprint-override"><code>def get_input(filepath):
f = open(filepath, 'r')
content = f.read()
return content
def remove_nums(arr):
pattern = '[0-9]'
arr = [re.sub(pattern, '', i) for i in arr]
return arr
def get_words(para):
stop_words = list(stopwords.words('english'))
words = RegexpTokenizer(r'\w+')
lower = [word.lower() for word in words.tokenize(para)]
nopunctuation = [nopunc.translate(str.maketrans('', '', string.punctuation)) for nopunc in lower]
no_integers = remove_nums(nopunctuation)
dirty_tokens = [data for data in no_integers if data not in stop_words]
tokens = [data for data in dirty_tokens if data.strip()]
return tokens
def driver(file):
#t1 is the start of the file
t1 = time.time()
myfile = get_input(file)
p = r'<P ID=\d+>.*?</P>'
paras = RegexpTokenizer(p)
document_frequency = collections.Counter()
collection_frequency = collections.Counter()
all_lists = []
currWordCount = 0
currList = []
currDocList = []
all_doc_lists = []
num_paragraphs = len(paras.tokenize(myfile))
print()
print(" NOW BEGINNING TOKENIZATION ")
print()
for para in paras.tokenize(myfile):
group_para_id = re.match("<P ID=(\d+)>", para)
para_id = group_para_id.group(1)
tokens = get_words(para)
tokens = list(set(tokens))
collection_frequency.update(tokens)
document_frequency.update(set(tokens))
para = para.translate(str.maketrans('', '', string.punctuation))
currPara = para.lower().split()
for token in tokens:
currWordCount = currPara.count(token)
currList = [token, tuple([para_id, currWordCount])]
all_lists.append(currList)
currDocList = [para_id, tuple([token, currWordCount])]
all_doc_lists.append(currDocList)
d = {}
termfreq_by_doc = {}
for key, new_value in all_lists:
values = d.setdefault(key, [])
values.append(new_value)
for key, new_value in all_doc_lists:
values = termfreq_by_doc.setdefault(key, [])
values.append(new_value)
# t2 is after the tokenization
t2 = time.time()
inverted_index = {word:(document_frequency[word], d[word]) for word in d}
# t3 is after creating the index
t3 = time.time()
print("Number of Paragraphs Processed: {}".format(num_paragraphs))
print("Number of Unique Words (Vocabulary Size): {}".format(vocabulary_size(document_frequency)))
print("Number of Total Words (Collection Size): {}".format(sum(collection_frequency.values())))
"""
1. First, create a lookup hash of the IDFs for each term in the dictionary.
2. Then, compute the tfxidf for each term in every document.
3. Then, calculate the lengths of each document.
4. Now you can process a query.
"""
idf_lookup = create_idf_lookup(inverted_index, num_paragraphs)
#t4 is after creating the lookup
t4 = time.time()
tfidf_by_doc = {a:[(c, int(idf_lookup[c]*d)) for c, d in b] for a, b in termfreq_by_doc.items()}
#t5 is after creating the tfidf by doc
t5 = time.time()
lengths = calculateLength(tfidf_by_doc, idf_lookup)
#Now, process the query:
# Read in the query
query_results = process_query(local_file_path)
# Create tfxidf
query_vector = {a:[(c, int(idf_lookup[c]*d)) for c, d in b] for a, b in query_results.items()}
# Grab length
queryLengthDict = calculateLength(query_vector, idf_lookup)
queryLength = next(iter(queryLengthDict.values()))
result = {}
for k, v in tfidf_by_doc.items():
for se in query_vector.values():
result[k] = dot_prod(dict(v), dict(se))
print()
cosine_sims = {k:v / (lengths[k] * queryLength) if lengths[k] != 0 else 0 for k, v in result.items()}
#https://stackoverflow.com/questions/613183/how-do-i-sort-a-dictionary-by-value
sorted_sims = sort_dictionary(cosine_sims)
top_100 = take(100, sorted_sims)
#t6 is grabbing the sorted sims
t6 = time.time()
print()
print("Cosine Sims")
print(top_100)
t7 = time.time()
print()
print()
print("TOTAL TIME TO COMPLETE: {}".format(t7-t1))
print("TIME TO GRAB SORTED COSINE SIMS: {}".format(t6-t5))
print("TIME TO CREATE TFIDF BY DOC: {}".format(t5-t4))
print("TIME TO CREATE IDF LOOKUP: {}".format(t4-t3))
print("TIME TO CREATE INVERTED INDEX: {}".format(t3-t2))
print("TIME TO TOKENIZE: {}".format(t2-t1))
print("PROGRAM COMPLETED")
</code></pre>
<p>I am pretty new to optimization, and am looking for some feedback. I did see <a href="https://stackoverflow.com/questions/41912083/nltk-tokenize-faster-way">this post</a> which condemns a lot of my list comprehensions as "evil", but I can't think of a way around what I am doing.</p>
<p>The code is <em>not</em> well commented, so if for some reason it is not understandable, that is okay. I see other questions on this forum re: speeding up NLTK tokenization without a lot of feedback, so I am hoping for a positive thread about tokenization optimization programming practices.</p>
<p>Here is an example (~a little bit of <em>one</em> document in the overall corpus). There are about ~58,000 scientific articles (I measure 57,982).</p>
<pre class="lang-xml prettyprint-override"><code><P ID=2630932>
Background
Adrenal cortex oncocytic carcinoma (AOC) represents an exceptional pathological entity, since only 22 cases have been documented in the literature so far.
Case presentation
Our case concerns a 54-year-old man with past medical history of right adrenal excision with partial hepatectomy, due to an adrenocortical carcinoma. The patient was admitted in our hospital to undergo surgical resection of a left lung mass newly detected on chest Computed Tomography scan. The histological and immunohistochemical study revealed a metastatic AOC. Although the patient was given mitotane orally in adjuvant basis, he experienced relapse with multiple metastases in the thorax twice in the next year and was treated with consecutive resections. Two and a half years later, a right hip joint metastasis was found and concurrent chemoradiation was given. Finally, approximately five years post disease onset, the patient died due to massive metastatic disease. A thorough review of AOC and particularly all diagnostic difficulties are extensively stated.
Conclusion
Histological classification of adrenocortical oncocytic tumours has been so far a matter of debate. There is no officially established histological scoring system regarding these rare neoplasms and therefore many diagnostic difficulties occur for pathologists.
Background
Hamperl introduced the term "oncocyte" in 1931 referring to a cell with abundant, granular, eosinophilic cytoplasm []. Electron microscopic studies revealed that this granularity was due to mitochondria accumulation in the oncocyte cytoplasm []. Neoplasms composed predominantly or exclusively of this kind of cells are called "oncocytic" []. Such tumours have been described in the overwhelming majority of organs: kidney, thyroid and pituitary gland, salivary, adrenal, parathyroid and lacrimal glands, paraganglia, respiratory tract, paranasal sinuses and pleura, liver, pancreatobiliary system, stomach, colon and rectum, central nervous system, female and male genital tracts, skin and soft tissues [-]. Adrenocortical oncocytic neoplasms (AONs) represent unusual lesions and three histological categories are included: oncocytoma (AO), oncocytic neoplasm of uncertain malignant potential (AONUMP) and oncocytic carcinoma (AOC) []. In our study, we add to the 22 cases found in the literature a new AOC with peculiar clinical presentation [-].
Case presentation
A 54-year-old man was admitted in the Thoracic and Vascular Surgery Department of our hospital with a 2 cm mass at the upper lobe of the left lung detected on Computed Tomography (CT) scan to undergo complete surgical resection. He had a past medical history of adrenocortical carcinoma (AC) treated surgically with right adrenalectomy and partial hepatectomy en block 2 years ago (Figure ). He was a mild 3 pack year smoker and a moderate drinker (1/2 kgr wine/day).
Figure 1 Abdominal MRI showing the hepatic invasion, which was submitted to en block resection with the right adrenal .
Overall physical examination showed neither specific abnormality, nor any signs of endocrinopathy. All laboratory tests including cortisol, 17-ketosteroids and 17-hydrocorticosteroids serum levels and dexamethasone test, full blood count and complete biochemical hepatic plus renal function tests were in normal rates. The patient was subjected to wedge resection. Histological examination revealed a tumour with an oxyphilic cell population, moderate nuclear atypia, diffuse, rosette-like and papillary growth pattern and focal necroses (Figure ). A number of 4 mitotic figures/50 high power fields (HPFs) were documented. The proliferative index Ki-67 (MIB-1, 1:50, DAKO) was in a value range of 1020% and p53 oncoprotein (DO-7, 1:20, DAKO) was weakly expressed in a few cells. Immunohistochemical examination revealed positivity for Vimentin (V9, 1:2000, DAKO), Melan-A (A103, 1:40, DAKO), Calretinin with a fried-egg-like specific staining pattern (Rabbit anti-human polyclonal antibody, 1:150, DAKO) and Synaptophysin (SY38, 1:20, DAKO). Both Cytokeratins CK8,18 (UCD/PR 10.11, 1:80, ZYMED) and AE1/AE3 (MNF116, 1:100, DAKO) showed a dot-like paranuclear expression. Inhibin-a (R1, 1:40, SEROTEC) and CD56 (123C3, 1:50, ZYMED) were *expressed focally (Figures and ). CK7 (OV-TL 12/30, 1:60, DAKO), CK20 (K S 20.8, 1:20, DAKO), EMA (E29, 1:50, DAKO), CEAm (12-140-10, 1:50, NOVOCASTRA), CEAp (Rabbit anti-human polyclonal antibody, 1:4000, DAKO), TTF-1 (8G7G3/1 1:40, ZYMED), Chromogranin (DAK-A3, 1:20, DAKO) and S-100 (Rabbit anti-human polyclonal antibody, 1:1000, DAKO) were negative. Based on the morphological and immunohistochemical features of the neoplasm and the patient's past medical history, other oncocytic tumours were excluded and the diagnosis of a metastatic AOC was supported. Mitotane oral medication was given in adjuvant setting (2 g/d).*
...
</P>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-09T01:09:14.400",
"Id": "448761",
"Score": "0",
"body": "Is the document XML? If so, can you show a closing tag in your example?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-09T01:12:16.140",
"Id": "448765",
"Score": "0",
"body": "It is not `XML`, it is `SGML`. Closing tag is simply `</P>`, and so the `regex` defines an `article` (since the entire corpus is a large body of many scientific articles) as everything within the tag."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-09T01:17:48.897",
"Id": "448767",
"Score": "0",
"body": "Please show more of the code, particularly `get_input`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-09T01:20:53.837",
"Id": "448768",
"Score": "0",
"body": "More code posted. Majority of which takes less than ~2 minutes to complete."
}
] |
[
{
"body": "<h2>Regex compilation</h2>\n\n<p>If performance is a concern, this:</p>\n\n<pre><code>arr = [re.sub(pattern, '', i) for i in arr]\n</code></pre>\n\n<p>is a problem. You're re-compiling your regex on every function call - and every loop iteration! Instead, move the regex to a <code>re.compile()</code>d symbol outside of the function.</p>\n\n<p>The same applies to <code>re.match(\"<P ID=(\\d+)>\", para)</code>. In other words, you should be issuing something like</p>\n\n<pre><code>group_para_re = re.compile(r\"<P ID=(\\d+)>\")\n</code></pre>\n\n<p>outside of the loop, and then</p>\n\n<pre><code>group_para_id = group_para_re.match(para)\n</code></pre>\n\n<p>inside the loop.</p>\n\n<h2>Premature generator materialization</h2>\n\n<p>That same line has another problem - you're forcing the return value to be a list. Looking at your <code>no_integers</code> usage, you just iterate over it again, so there's no value to holding onto the entire result in memory. Instead, keep it as a generator - replace your brackets with parentheses.</p>\n\n<p>The same thing applies to <code>nopunctuation</code>.</p>\n\n<h2>Set membership</h2>\n\n<p><code>stop_words</code> should not be a <code>list</code> - it should be a <code>set</code>. Read about its performance <a href=\"https://wiki.python.org/moin/TimeComplexity\" rel=\"noreferrer\">here</a>. Lookup is average O(1), instead of O(n) for a list.</p>\n\n<h2>Variable names</h2>\n\n<p><code>nopunctuation</code> should be <code>no_punctuation</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-09T01:08:52.027",
"Id": "448760",
"Score": "0",
"body": "I copied segments of the overall code body over, please allow me to edit. For example, `get_words` returns `tokens` and `driver` _is_ parseable, I just copied it funky."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-09T01:11:18.670",
"Id": "448763",
"Score": "0",
"body": "Funkiness fixed! Let me know if this looks like it makes more sense now..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-09T01:13:39.837",
"Id": "448766",
"Score": "0",
"body": "Today is my not day...if you can't tell, I'm frazzled. Thanks for the catch."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-09T01:21:15.647",
"Id": "448769",
"Score": "0",
"body": "`The same applies to re.match(\"<P ID=(\\d+)>\", para).` The goal of that line is to figure out the _current_ document ID being parsed, so I can capture that for metric evaluation later on. How can I compile the regular expression outside of the loop to be used to capture the ID inside of the loop?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-09T01:42:16.980",
"Id": "448774",
"Score": "0",
"body": "Interesting -- when I compile _outside_ the loop, I no longer am able to match the tags at all. `group_para_id` always shows up as `None` type."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-09T01:45:10.243",
"Id": "448777",
"Score": "0",
"body": "`group_para_re.match(para)[1]`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-09T01:46:14.763",
"Id": "448778",
"Score": "0",
"body": "Yes, although that wouldn't fix the `None` issue. If you aren't able to debug this, in theory the correct procedure would be to post the issue on StackOverflow with a minimal reproducible example."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-09T01:47:34.533",
"Id": "448779",
"Score": "0",
"body": "Understood, thanks for all the help. Will continue to try and optimize here..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-09T12:28:54.363",
"Id": "448846",
"Score": "1",
"body": "As an update -- this showed about a 10 minute improvement in time! Which is good. Thanks."
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-09T01:07:10.913",
"Id": "230395",
"ParentId": "230393",
"Score": "5"
}
},
{
"body": "<blockquote>\n <p>Not a code reviewer, your code looks good though. </p>\n</blockquote>\n\n<p>Your regular expression can be slightly optimized for edge cases. For instance,</p>\n\n<pre><code>(?i)<p\\s+id=[0-9]+\\s*>(.+?)</p>\n</code></pre>\n\n<p>or, </p>\n\n<pre><code>(?i)<p\\s+id=[0-9]+\\s*>.+?</p>\n</code></pre>\n\n<p>with <code>i</code> modifier would safely cover some edge cases, if you would have had any. </p>\n\n<h3><a href=\"https://regex101.com/r/09VDOI/1/\" rel=\"nofollow noreferrer\">Demo 1</a></h3>\n\n<ul>\n<li><code>[0-9]</code> might be, not very sure, slightly more efficient than <code>\\d</code> construct. </li>\n<li><code>(.+?)</code> is very very slightly more efficient than <code>(.*?)</code>. </li>\n</ul>\n\n<p>If your text content in the <code>p</code> tag for sure does not have any <code><</code>, then we would safely simplify our expression to:</p>\n\n<pre><code>(?i)<p\\s+id=[0-9]+\\s*>([^<]+)</p> \n</code></pre>\n\n<p>or</p>\n\n<pre><code>(?i)<p\\s+id=[0-9]+\\s*>[^<]+</p> \n</code></pre>\n\n<p>which are much faster than the previous expressions because of <code>[^<]+</code>. </p>\n\n<h3><a href=\"https://regex101.com/r/U37CAQ/1/\" rel=\"nofollow noreferrer\">Demo 2</a></h3>\n\n<hr>\n\n<h3>Demo</h3>\n\n<p>If you wish to simplify/modify/explore the expression, it's been explained on the top right panel of <a href=\"https://regex101.com/r/U37CAQ/1/\" rel=\"nofollow noreferrer\">regex101.com</a>. If you'd like, you can also watch in <a href=\"https://regex101.com/r/U37CAQ/1/debugger\" rel=\"nofollow noreferrer\">this link</a>, how it would match against some sample inputs.</p>\n\n<hr>\n\n<h3>RegEx Circuit</h3>\n\n<p><a href=\"https://jex.im/regulex/#!flags=&re=%5E(a%7Cb)*%3F%24\" rel=\"nofollow noreferrer\">jex.im</a> visualizes regular expressions: </p>\n\n<p><a href=\"https://i.stack.imgur.com/5oZvc.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/5oZvc.png\" alt=\"enter image description here\"></a></p>\n\n<h3>Test</h3>\n\n<pre><code>import re\n\nregex = r'(?i)<p\\s+id=[0-9]+\\s*>([^<]+)<\\/p>'\nstring = '''\n<P \nID=2630932>\nBackground \nAdrenal cortex oncocytic carcinoma (AOC) represents an exceptional pathological entity, since only 22 cases have been documented in the literature so far.\n</P>\n\n<P ID=2630932>\nBackground\nAdrenal cortex oncocytic carcinoma (AOC) represents an exceptional pathological entity, since only 22 cases have been documented in the literature so far.\n</P>\n\n<P ID=2630932 >\nBackground\nAdrenal cortex oncocytic carcinoma (AOC) represents an exceptional pathological entity, since only 22 cases have been documented in the literature so far.\n</P>\n\n'''\n\nprint(re.findall(regex, string, re.DOTALL))\n</code></pre>\n\n<h3>Output</h3>\n\n<blockquote>\n <p>['\\nBackground \\nAdrenal cortex oncocytic carcinoma (AOC) represents\n an exceptional pathological entity, since only 22 cases have been\n documented in the literature so far.\\n', '\\nBackground\\nAdrenal cortex\n oncocytic carcinoma (AOC) represents an exceptional pathological\n entity, since only 22 cases have been documented in the literature so\n far.\\n', '\\nBackground\\nAdrenal cortex oncocytic carcinoma (AOC)\n represents an exceptional pathological entity, since only 22 cases\n have been documented in the literature so far.\\n']</p>\n</blockquote>\n\n<hr>\n\n<blockquote>\n <p>You can also remove the capturing groups if your code doesn't need those.</p>\n</blockquote>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-09T01:46:49.637",
"Id": "230396",
"ParentId": "230393",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "230395",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-09T00:51:42.083",
"Id": "230393",
"Score": "6",
"Tags": [
"python",
"performance",
"python-3.x",
"parsing",
"natural-language-processing"
],
"Title": "Tokenizing SGML text for NLTK analysis"
}
|
230393
|
<p>I write decorators a lot in my work. Sometimes you need to write "decorator that takes arguments", it usually turns out to be something like this:</p>
<pre><code>def decorator(**kwargs):
def _decorator(func):
@wraps(func)
def decorated(*func_args, **func_kwargs):
# do something with kwargs here
return func(*func_args, **func_kwargs)
return decorated
return _decorator
</code></pre>
<p>but in this case you'll always have to use your decorator like so:</p>
<pre><code>@decorator() # if you forget () here you'll get an exception
def myfunc():
pass
</code></pre>
<p>So I come up with this snippet, IMO this is nicer to read/write and understand:</p>
<pre><code>from functools import wraps, partial
def decorator(func=None, **kwargs):
if func:
@wraps(func)
def decorated(*func_args, **func_kwargs):
if kwargs.get("sayhi"):
print("hi")
return func(*func_args, **func_kwargs)
return decorated
else:
return partial(decorator, **kwargs)
@decorator
def hello(name):
print(f"hello {name}")
@decorator(sayhi=True)
def bye(name):
print(f"bye {name}")
hello("rabbit")
# "hello rabbit"
bye("rabbit")
# hi
# bye rabbit
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-09T01:34:10.220",
"Id": "448771",
"Score": "2",
"body": "Code Review requires real code. Do you have a concrete use case that is not a toy example, so that we can give you proper advice?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-09T01:35:32.383",
"Id": "448772",
"Score": "0",
"body": "I agree with @200_success. This is borderline-hypothetical code; have a read through https://codereview.meta.stackexchange.com/questions/1981/the-gray-areas-of-code-review-hypothetical-example-code"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-09T03:42:23.413",
"Id": "448789",
"Score": "0",
"body": "hmmm it isn't really a question i just want to share this with people, where should i post it?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-09T09:38:01.330",
"Id": "448818",
"Score": "0",
"body": "@rabbit.aaron Github."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-09T14:00:01.427",
"Id": "448855",
"Score": "0",
"body": "I disagree, this is working code. though the real logic isn't displayed inside the code, it serves as a template for myself to write decorators. The purpose of the code is clearly stated in my post. I do think this question complies with most of the things mentioned in the guideline here. https://codereview.meta.stackexchange.com/questions/1954/checklist-for-how-to-write-a-good-code-review-question . if the code isn't working i would have posted it on stackoverflow."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-24T14:08:26.400",
"Id": "450938",
"Score": "0",
"body": "Greetings! I voted to close (we can always re-open later) because the code is too obviously not the real code, it is stub code. There is little (not enough) value in reviewing stub code, so we don't do that here."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-25T19:41:11.947",
"Id": "451111",
"Score": "0",
"body": "@rabbit.aaron, where can you plug this into real production code? do you have to change anything in order to use it in \"the wild\"?"
}
] |
[
{
"body": "<p>Nice little snippet! A couple of minor points:</p>\n\n<ul>\n<li><p>It's usually better to put the shorter block first in an <code>if</code> <code>else</code>. This stops the <code>else</code> statement being far from the <code>if</code>, making it clearer how the logic flows. </p></li>\n<li><p>When comparing to <code>None</code>, check <code>if func is None</code> or similar, rather than comparing to <code>True</code>/<code>False</code>.</p></li>\n<li><p>Although this is just a toy example, docstrings should always be used to show what the code does and returns.</p></li>\n<li><p>PEP8 spacing between imports, functions and code.</p></li>\n<li><p>Argument names could be better but without knowing the application it's hard to say what they should be.</p></li>\n</ul>\n\n<pre class=\"lang-py prettyprint-override\"><code>from functools import partial, wraps\n\n\ndef decorator(func=None, **kwargs):\n \"\"\"\n Decorator which optionally takes an argument sayhi (True or False).\n prints 'hi' if True, function is then returned as normal\n \"\"\"\n if func is None:\n return partial(decorator, **kwargs)\n else:\n @wraps(func)\n def decorated(*func_args, **func_kwargs):\n if kwargs.get('sayhi'):\n print('hi')\n return func(*func_args, **func_kwargs)\n return decorated\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-09T09:35:48.953",
"Id": "230413",
"ParentId": "230394",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-09T01:05:00.233",
"Id": "230394",
"Score": "3",
"Tags": [
"python",
"meta-programming"
],
"Title": "clean approach to decorator that takes optional keyword arguments"
}
|
230394
|
<pre><code>#include "fmt/format.h"
#include <cstdint>
#include <cstdio>
#include <event2/event-config.h>
#include <event2/util.h>
#include <evhttp.h>
#include <memory>
#include <type_traits>
auto
main() -> int
{
constexpr char host[] = "127.0.0.1";
std::uint16_t port = 5555;
using event_base_new_type
= std::pointer_traits<decltype(event_base_new())>::element_type;
using event_base_deleter_type = decltype(&event_base_free);
auto event_base
= std::unique_ptr<event_base_new_type, event_base_deleter_type>(
event_base_new(), &event_base_free);
if(!(event_base))
{
fmt::print(stderr, "Failed to init libevent.\n");
return -1;
}
using evhttp_new_type
= std::pointer_traits<decltype(evhttp_new(event_base.get()))>::element_type;
using evhttp_deleter_type = decltype(&evhttp_free);
auto http = std::unique_ptr<evhttp_new_type, evhttp_deleter_type>(evhttp_new(event_base.get()), &evhttp_free);
auto handle = evhttp_bind_socket_with_handle(http.get(), host, port);
if(!handle)
{
fmt::print(stderr, "Failed to init http server.\n");
return -1;
}
auto callback = [](evhttp_request* req, void*) {
auto* OutBuf = evhttp_request_get_output_buffer(req);
if(!OutBuf)
return;
evbuffer_add_printf(OutBuf,
"<html><body><center><h1>Hello World!</h1></center></body></html>");
evhttp_send_reply(req, HTTP_OK, "", OutBuf);
};
evhttp_set_gencb(http.get(), callback, nullptr);
if(event_base_dispatch(event_base.get()) == -1)
{
fmt::print(stderr, "Failed to run messahe loop.\n");
return -1;
}
return 0;
}
</code></pre>
<h2>Compile</h2>
<pre><code>g++ a.cpp -lfmt -levent
</code></pre>
<h2>Run</h2>
<pre class="lang-none prettyprint-override"><code>$ ./a.out
$ ab -c 1000 -k -r -t 10 http://127.0.0.1:5555/
</code></pre>
<p>Open <code>http://127.0.0.1:5555/</code> in browser</p>
<p>What I want to know:</p>
<ul>
<li>Is my <code>unique_ptr</code> necessary? valgrind reports no memory leak even though I don't use <code>unique_ptr</code> nor free manually.</li>
<li>more elegant/correct code.</li>
</ul>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-10T19:35:08.733",
"Id": "449123",
"Score": "0",
"body": "https://lokiastari.com/blog/2016/05/26/c-plus-plus-wrapper-for-socket/index.html"
}
] |
[
{
"body": "<p>Not too much to review as the code uses <code>evhttp</code> to handle HTTP and provide a basic, static reply for each request.</p>\n\n<p>Why is <code>host</code> <code>constexpr</code>, but not the <code>port</code>?</p>\n\n<p>All those <code>using</code> statements, combined with traits and <code>decltype</code> one after the other makes the code very hard to read, almost obscuring the fact that <code>evhttp</code> is being initialized at that point. I would try to rewrite that part in a simpler way.</p>\n\n<p>Why <code>auto main() -> int</code> instead of the simple, classic <code>int main()</code>?</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-10T18:11:59.867",
"Id": "230498",
"ParentId": "230400",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-09T02:59:52.180",
"Id": "230400",
"Score": "4",
"Tags": [
"c++",
"http",
"c++17",
"server"
],
"Title": "Implement HTTP server using libevent"
}
|
230400
|
<p>I am working on a custom game engine and have been fleshing out the various submodules (meshes, physics, shading, etc.)</p>
<p>Here is a sandbox program that exercises the newly finished camera system. After much testing, the camera system will be integrated into the rest of the engine.</p>
<p>This program loads three wireframe worlds and places the camera in them where the user may take control and move freely, viewing from the camera's perspective.</p>
<p>The code relies on other parts of the engine which I am not releasing yet. Therefore this code, while it does compile on my machine, is technically incomplete.</p>
<p><strong>Camera3D.h</strong></p>
<pre class="lang-cpp prettyprint-override"><code>#ifndef Camera3D_H
#define Camera3D_H
#include <Evector.h>
#include <Vmath.h>
#include <SpatialObject.h>
class Camera3D: public gen::SpatialObject {
private:
// A point in 3D space where the camera is currently focused on
gen::Vector look;
// A vector pointing in the "above" direction from the camera's
// perspective
gen::Vector up;
inline void setLook(gen::Vector aim)
{
look = pos + aim;
}
public:
double maxSpeed;
double lookMax;
// Set the camera in a new position.
//
// Input: Vector pointing to the new position
//
void set(gen::Vector newPosition);
// Translate the camera by some amount.
//
// Input: Triplet forming the displacement to translate by
//
void translate(double dx, double dy, double dz);
// Move the camera along the "forward" direction by some amount,
// either positively or negatively.
//
// Input: One-dimensional displacement to move along the "forward"
// direction by
//
void walk(double velocity);
// Set the azimuthal angle.
//
void setAzi(double newAzimuth);
// Set the zenith angle.
//
void setZen(double newZenith);
// Rotate about the Y axis. On the X-Z plane, positive rotations
// are counterclockwise.
//
// Input: The angular displacement to change the azimuth by
//
// @todo This method seems to be slow. Optimize later.
//
void turn(double deltaAngle);
//
//
void aim(double x, double y, double z);
// Rotate about the "side" axis. The "side" axis points "east".
//
void pivot(double deltaAngle);
// Roll the camera by some amount.
//
void roll(double deltaAngle);
// Set the camera to a new elevation.
//
void hang(double newElev);
// Raise the camera in elevation by some amount.
//
void raise(double deltaElev);
inline gen::Vector getPosition() const {return pos;}
inline gen::Vector getLook() const {return look;}
inline gen::Vector getUp() const {return up;}
inline gen::Vector getAim() const
{
return gen::displacement(getPosition(), getLook());
}
Camera3D(const double lookScale):
gen::SpatialObject(),
lookMax(lookScale)
{
//
// Forward = +Z
// Up = +Y
//
look = gen::Vector(0, 0, lookMax);
up = gen::Vector(0, 1, 0);
maxSpeed = 0;
}
};
#endif
</code></pre>
<p><strong>Camera3D.cpp</strong></p>
<pre class="lang-cpp prettyprint-override"><code>#include <Camera3D.h>
#include <Evector.h>
#include <Vmath.h>
#include <Globals.h>
extern const double PI;
// Set the camera in a new position.
//
// Input: Vector pointing to the new position
//
void Camera3D::set(gen::Vector newPosition)
{
// We're not changing the direction the camera is looking,
// just the position. Restore the aim after the move.
gen::Vector oldAim = getAim();
pos = newPosition;
setLook(oldAim);
}
// Translate the camera by some amount.
//
// Input: Triplet forming the displacement to translate by
//
void Camera3D::translate(double dx, double dy, double dz)
{
set(pos + gen::Vector(dx, dy, dz));
}
// Move the camera along the "forward" direction by some amount,
// either positively or negatively.
//
// Input: One-dimensional displacement to move along the "forward"
// direction by
//
void Camera3D::walk(double velocity)
{
// Here, we're just stepping some distance either forward or back.
gen::Vector step = getAim();
gen::resize(step, velocity);
set(pos + step);
}
// Set the azimuthal angle.
//
void Camera3D::setAzi(double newAzimuth)
{
}
// Set the zenith angle.
//
void Camera3D::setZen(double newZenith)
{
}
// Rotate about the Y axis. On the X-Z plane, positive rotations
// are counterclockwise.
//
// Input: The angular displacement to change the azimuth by
//
// @todo This method seems to be slow. Optimize later.
//
void Camera3D::turn(double deltaAngle)
{
// Camera position does not change when turning, only the "forward"
// vector.
gen::Vector newAim = getAim();
gen::rotate(newAim, deltaAngle, 2);
setLook(newAim);
}
//
//
void Camera3D::aim(double x, double y, double z)
{
}
// Rotate about the "side" axis. The "side" axis points "east".
//
void Camera3D::pivot(double deltaAngle)
{
// Get the "side" vector which is perpendicular to the "forward" and "up"
// vectors.
gen::Vector currentAim = getAim();
double currentPhi = getPhi(currentAim);
// If the caller is trying to look further than "down", do nothing.
if((currentPhi + deltaAngle) > PI) {
gen::Vector straightDown(gen::Vector(0, -lookMax, 0));
setLook(straightDown);
}
// If the caller is trying to look past zero radians, do nothing.
else if((currentPhi + deltaAngle) < 0) {
gen::Vector straightUp(gen::Vector(0, lookMax, 0));
setLook(straightUp);
}
else {
gen::Vector axis = gen::cross(up, currentAim);
gen::Vector newAim = currentAim;
gen::rotateArb(newAim, deltaAngle, axis);
setLook(newAim);
}
}
// Roll the camera by some amount.
//
void Camera3D::roll(double deltaAngle)
{
gen::rotateArb(up, deltaAngle, getAim());
}
// Set the camera to a new elevation.
//
void Camera3D::hang(double newElev)
{
gen::Vector newPosition = pos;
newPosition.y = newElev;
set(newPosition);
}
// Raise the camera in elevation by some amount.
//
void Camera3D::raise(double deltaElev)
{
translate(0, deltaElev, 0);
}
</code></pre>
<p><strong>Cam3D.h</strong></p>
<pre class="lang-cpp prettyprint-override"><code>/*
File: Cam3D.h
Date: Sunday, September 29, 2019
*/
#ifndef Cam3D_H
#define Cam3D_H
#include <AllegApp.h>
#include <Camera3D.h>
#include <InputHandler.h>
#include <Mesh3D.h>
#include <allegro5/allegro.h>
class Cam3D: public lat::AllegApp {
private:
meshx::Mesh3D plane1;
meshx::Mesh3D plane2;
meshx::Mesh3D plane3;
Camera3D camera;
InputHandler inputHandler;
ALLEGRO_TRANSFORM transform;
ALLEGRO_TRANSFORM camTrans;
ALLEGRO_EVENT event;
int doUpdate();
int draw();
protected:
virtual int update() override;
public:
void init() override;
Cam3D(int width, int height);
~Cam3D();
};
#endif
</code></pre>
<p><strong>Cam3D.cpp</strong></p>
<pre class="lang-cpp prettyprint-override"><code>/*
File: Cam3D.cpp
Date: Sunday, September 29, 2019
*/
#include <Cam3D.h>
#include <Camera3D.h>
#include <AllegApp.h>
#include <Mesh3D.h>
#include <MeshLoader.h>
#include <HardRenderer.h>
#include <MeshOps.h>
#include <ColorsA5.h>
#include <InputHandler.h>
#include <Globals.h>
#include <allegro5/allegro.h>
#include <allegro5/allegro_image.h>
#include <allegro5/allegro_primitives.h>
#include <allegro5/allegro_color.h>
#include <string>
const double PI = 3.141592654;
const double RADIANS_PER_DEGREE = PI / 180.0;
const double FOV = (90 * RADIANS_PER_DEGREE / 2.0);
// Window aspect ratio
double ASPECT_RATIO;
// Camera zoom factor
const double ZOOM = 1.0;
// Frame rate limit (in quarters of 60fps)
const int FRAME_RATE_LIMIT = 4;
const double TERRAIN_SCALE = 1000000;
const double DEPTH = 5000000;
const double CAMERA_LOOK_DEPTH = 1000000;
// Starting camera elevation percentage
const double INITIAL_ELEV_FACTOR = 0.1;
//
const double SPACE_FABRIC_CONSTANT = 1.0 / 128;
inline double degToRad(double deg) {return PI * deg / 180.0;}
Cam3D::Cam3D(int width, int height):
AllegApp(width, height),
camera(CAMERA_LOOK_DEPTH)
{
}
Cam3D::~Cam3D()
{
}
void Cam3D::init()
{
AllegApp::init();
ASPECT_RATIO = ((double)getWindowHeight()) / getWindowWidth();
// setDisplayFullscreen();
setWindowTitle("Cam3D");
setFrameRateFrac(FRAME_RATE_LIMIT);
flLockFrameRate = true;
flAllowQuitOnEscape = true;
// Monitor the movement keys.
inputHandler.monitorKey(ALLEGRO_KEY_PAD_2);
inputHandler.monitorKey(ALLEGRO_KEY_PAD_8);
inputHandler.monitorKey(ALLEGRO_KEY_PAD_4);
inputHandler.monitorKey(ALLEGRO_KEY_PAD_6);
inputHandler.monitorKey(ALLEGRO_KEY_LEFT);
inputHandler.monitorKey(ALLEGRO_KEY_RIGHT);
inputHandler.monitorKey(ALLEGRO_KEY_DOWN);
inputHandler.monitorKey(ALLEGRO_KEY_UP);
inputHandler.monitorKey(ALLEGRO_KEY_A);
inputHandler.monitorKey(ALLEGRO_KEY_D);
inputHandler.monitorKey(ALLEGRO_KEY_S);
inputHandler.monitorKey(ALLEGRO_KEY_W);
inputHandler.monitorKey(ALLEGRO_KEY_SPACE);
// Load the world.
plane1 = meshx::loadMesh("H:/testscapes/plane/plane.obj");
meshx::scaleMesh(plane1, TERRAIN_SCALE);
plane2 = meshx::loadMesh("H:/testscapes/plane/plane.obj");
meshx::scaleMesh(plane2, TERRAIN_SCALE / 10.0);
plane2.offset.y = 100000;
plane3 = meshx::loadMesh("H:/testscapes/plane/plane.obj");
meshx::scaleMesh(plane3, TERRAIN_SCALE / 100.0);
plane3.offset.y = 200000;
// Set up the camera.
camera.hang(TERRAIN_SCALE * INITIAL_ELEV_FACTOR);
}
int Cam3D::update()
{
int result = doUpdate();
draw();
return result;
}
int Cam3D::doUpdate()
{
double deltaTheta = 0;
double deltaPhi = 0;
int result = 0;
camera.maxSpeed = SPACE_FABRIC_CONSTANT * TERRAIN_SCALE * 0.01;
inputHandler.getKeyboardInput();
// ------------------------[ROTATION]------------------------
// Counterclockwise on the X-Z plane
if(inputHandler.getKeyFlagByCode(ALLEGRO_KEY_PAD_4)) {
deltaTheta = degToRad(+1);
camera.turn(deltaTheta);
}
// Clockwise on the X-Z plane
else if(inputHandler.getKeyFlagByCode(ALLEGRO_KEY_PAD_6)) {
deltaTheta = degToRad(-1);
camera.turn(deltaTheta);
}
// Look down
if(inputHandler.getKeyFlagByCode(ALLEGRO_KEY_PAD_2)) {
deltaPhi = degToRad(-1);
camera.pivot(deltaPhi);
}
// Look up
else if(inputHandler.getKeyFlagByCode(ALLEGRO_KEY_PAD_8)) {
deltaPhi = degToRad(+1);
camera.pivot(deltaPhi);
}
// ------------------------[TRANSLATION]------------------------
// Speed up
if(inputHandler.getKeyFlagByCode(ALLEGRO_KEY_SPACE)) {
camera.maxSpeed = SPACE_FABRIC_CONSTANT * TERRAIN_SCALE * 0.1;
}
// Forward
if(inputHandler.getKeyFlagByCode(ALLEGRO_KEY_W)) {
camera.walk(+camera.maxSpeed);
}
// Backward
else if(inputHandler.getKeyFlagByCode(ALLEGRO_KEY_S)) {
camera.walk(-camera.maxSpeed);
}
// Translate left
if(inputHandler.getKeyFlagByCode(ALLEGRO_KEY_LEFT)) {
camera.translate(-camera.maxSpeed, 0, 0);
}
// Translate right
if(inputHandler.getKeyFlagByCode(ALLEGRO_KEY_RIGHT)) {
camera.translate(+camera.maxSpeed, 0, 0);
}
// Translate down
if(inputHandler.getKeyFlagByCode(ALLEGRO_KEY_DOWN)) {
camera.translate(0, 0, -camera.maxSpeed);
}
// Translate up
if(inputHandler.getKeyFlagByCode(ALLEGRO_KEY_UP)) {
camera.translate(0, 0, +camera.maxSpeed);
}
return result;
}
int Cam3D::draw()
{
// Clear the screen.
al_clear_to_color(BLACK);
// Used to restore the previous transform
ALLEGRO_TRANSFORM old = *al_get_current_projection_transform();
// Start with the identity transform.
al_identity_transform(&transform);
// Set up the perspective projection matrix.
// Left, Top, Near, Right, Bottom, Far
al_perspective_transform(&transform,
(-1.0 / ZOOM), (-ASPECT_RATIO / ZOOM),
(+1.0 / FOV),
(+1.0 / ZOOM), (+ASPECT_RATIO / ZOOM),
DEPTH);
// Flip the X and Y axes.
al_scale_transform_3d(&transform, -1, -1, +1);
al_use_projection_transform(&transform);
// Set up a matrix to transform from world coordinates to camera
// coordinates.
al_build_camera_transform(&camTrans,
camera.getPosition().x,
camera.getPosition().y,
camera.getPosition().z,
camera.getLook().x,
camera.getLook().y,
camera.getLook().z,
camera.getUp().x,
camera.getUp().y,
camera.getUp().z);
al_use_transform(&camTrans);
al_set_render_state(ALLEGRO_DEPTH_TEST, 1);
al_clear_depth_buffer(1);
// Draw the planes.
drawMeshWire3D(plane1, GREEN);
drawMeshWire3D(plane2, CYAN);
drawMeshWire3D(plane3, MAGENTA);
// Reset the projection transforms.
al_identity_transform(&camTrans);
al_use_transform(&camTrans);
al_use_projection_transform(&old);
al_set_render_state(ALLEGRO_DEPTH_TEST, 0);
al_draw_textf(getSystemFont(), ICEBERG, 0, 0, 0, "%f", getFrameRate());
al_draw_textf(getSystemFont(), ICEBERG, 0, 10, 0, "%f",
camera.getPosition().y);
return 0;
}
</code></pre>
<p><strong>main.cpp</strong></p>
<pre class="lang-cpp prettyprint-override"><code>/*
File: main.cpp
Date: Sunday, September 29, 2019
*/
#include <AllegApp.h>
#include <Cam3D.h>
int main(int argc, char** argv)
{
lat::AllegApp* x = new Cam3D(16 * 75, 9 * 75);
x->init();
x->run();
delete x;
x = 0;
return 0;
}
</code></pre>
<p><strong>Globals.h</strong></p>
<pre class="lang-cpp prettyprint-override"><code>#ifndef Globals_H
#define Globals_H
extern const double PI;
#endif
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-11T10:29:46.540",
"Id": "449186",
"Score": "1",
"body": "Welcome to Code Review!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-10T15:37:30.193",
"Id": "453163",
"Score": "1",
"body": "While we appreciate your need to keep some code private, there are classes used here that are not defined. This makes the question off-topic."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-11T18:28:12.767",
"Id": "453295",
"Score": "0",
"body": "@pacmaninbw Thank you for the advice. Yes, there are many classes used here, however, if I included those class definitions, then the code wouldn't be private anymore."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-11T18:32:41.690",
"Id": "453296",
"Score": "1",
"body": "You're correct, it wouldn't be private anymore. The code you have posted has now become public domain. Suggestion because I won't be answering this question, in `Camera3D.cpp` you already include the `Globals` header, you don't need `extern const double PI;` in the code again."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-09T03:01:23.257",
"Id": "230402",
"Score": "3",
"Tags": [
"c++",
"api",
"coordinate-system"
],
"Title": "Driver program using custom 3D game engine"
}
|
230402
|
<p>How could I further optimize my implementation of Conway's Game of Life? And how would you critique my current strategies? I'm taking a C++ optimization class, the deadline has passed and my assignment has already been submitted. We were supposed to compile with these options: <code>g++ me.cpp -std=c++11 -O3 -march=native -o me</code>. </p>
<p>I'm trying to minimize <code>real</code> time after executing it like this: <code>time ./me 0 1000 0</code>. My program's first argument is the random seed, the second is the number of iterations, and the last is 1 or 0 meaning print or don't print. I don't want to print while timing. The random seed and number of iterations could be any value.</p>
<h2>How it works</h2>
<p>I iterate through living cells instead of all spaces on the board. I manually unrolled iterating through all 9 tiles encompassing each living cell. Living neighbors, including the central living cell, become incremented positively. Dead neighbors of a living cell become decremented. </p>
<p>That means after the <code>encode</code> function a value of -3 on a dead tile means there are 3 living neighbors, therefore that tile should become alive. 1 is not possible because living cells are incremented at least once. Positive 2 means no living neighbors, 3 means 1 living neighbor, 4 means 2 living neighbors, 5 means 3 living neighbors, etc. </p>
<p>According to the rules there are 3 circumstances where a cell can be alive, but my <code>living_cipher</code> array includes a 4th living state. That's because within the <code>decode</code> method a code value of 1 means I've already decided the cell is alive and now I should ignore that tile. Because 1 should be ignored, the <code>counter_cipher</code> has a zero at that entry. This method transforms codes ranging from -8 to 10, to either a 1 or a 0 meaning living or dead. Rise and repeat for the desired number of iterations.</p>
<p>I used macros as an optimization because constant variables were slower. I did not try an inline function.</p>
<pre><code>#include <iostream>
using namespace std;
#define HEIGHT ((1 << 10) + 2)
#define WIDTH ((1 << 11) + 2)
#define MAX_Y (HEIGHT - 1)
#define MAX_X (WIDTH - 1)
#define NEXT_ROW (WIDTH - 2)
#define AREA (HEIGHT * WIDTH)
constexpr signed char offset_living_cipher[19] = {
0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0
};
constexpr signed char offset_counter_cipher[19] = {
0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0
};
class Matthew_Conway{
private:
bool print;
signed char * board;
signed char ** cells, ** next_cells;
unsigned long total_cells;
void make_cells(){
unsigned long next_total_cells = 0;
cells = new signed char * [AREA];
next_cells = new signed char * [AREA];
for (unsigned long row = 1; row <= HEIGHT - 2; ++row){
for(unsigned long column = 1; column <= WIDTH - 2; ++column){
unsigned long index = row * WIDTH + column;
signed char cell = rand() % 2 == 0;
board[index] = cell;
cells[next_total_cells] = board + index;
next_total_cells += cell;
}
}
total_cells = next_total_cells;
}
public:
unsigned long iterations;
Matthew_Conway(char ** argv){
unsigned random_seed = (unsigned) atoi(argv[1]);
srand(random_seed);
iterations = (unsigned long) atoi(argv[2]);
print = (bool) atoi(argv[3]);
board = (signed char*) calloc(AREA, sizeof(signed char));
make_cells();
}
void print_board(){
if (!print)
return;
for (unsigned long row = 1; row <= HEIGHT - 2; ++row){
for (unsigned long column = 1; column <= WIDTH - 2; ++column){
signed char value = board[row * WIDTH + column];
cout << (int) value;
}
cout << endl;
}
}
void encode() {
#define INCREMENT *board_address += 2 * (*board_address > 0) - 1;
unsigned long next_total_cells = 0;
for (unsigned long cell_i = 0; cell_i < total_cells; ++cell_i) {
signed char * cell = cells[next_total_cells] = cells[cell_i];
unsigned long index = cell - board;
unsigned long y = index / WIDTH;
unsigned long x = index % WIDTH;
if (x == 0 || x == MAX_X || y == 0 || y == MAX_Y){
continue;
}
++next_total_cells;
signed char * board_address = cell - WIDTH - 1; // Upper Left
INCREMENT;
++board_address; // Upper Middle
INCREMENT;
++board_address; // Upper Right
INCREMENT;
board_address += NEXT_ROW; // Middle Left
INCREMENT;
++board_address; // Center
++*board_address;
++board_address; // Middle Right
INCREMENT;
board_address += NEXT_ROW; // Lower Left
INCREMENT;
++board_address; // Lower Middle
INCREMENT;
++board_address; // Lower Right
INCREMENT;
}
total_cells = next_total_cells;
}
void decode() {
#define LIVING_CIPHER (offset_living_cipher + 8)
#define COUNTER_CIPHER (offset_counter_cipher + 8)
#define DECIPHER { \
code = *board_address; \
*board_address = LIVING_CIPHER[code]; \
next_cells[next_total_cells] = board_address; \
next_total_cells += COUNTER_CIPHER[code]; \
}
signed char code;
unsigned long next_total_cells = 0;
for (unsigned long cell_i = 0; cell_i < total_cells; ++cell_i) {
signed char * cell = cells[cell_i];
signed char * board_address = cell - WIDTH - 1; // Upper Left
DECIPHER;
++board_address; // Upper Middle
DECIPHER;
++board_address; // Upper Right
DECIPHER;
board_address += NEXT_ROW; // Middle Left
DECIPHER;
++board_address; // Center
DECIPHER;
++board_address; // Middle Right
DECIPHER;
board_address += NEXT_ROW; // Lower Left
DECIPHER;
++board_address; // Lower Middle
DECIPHER;
++board_address; // Lower Right
DECIPHER;
}
total_cells = next_total_cells;
swap(cells, next_cells);
}
};
int main(int argc, char ** argv){
if (argc != 4){
cout << "usage game-of-life <seed> <generations> <0:don't print, 1:print>" << endl;
return 1;
}
Matthew_Conway conway(argv);
conway.print_board();
for (unsigned long i = 0; i < conway.iterations; ++i){
conway.encode();
conway.decode();
}
conway.print_board();
return 0;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-09T09:51:41.407",
"Id": "448822",
"Score": "1",
"body": "How well does the following statement fit to this assignment and the review you are interested in? *\"I don't care how terrible the code is. As long as it executes fast and spits out the right answer I'm happy.\"* I have a feeling answering this will help avoiding people giving you reviews you don't want."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-09T10:45:15.760",
"Id": "448825",
"Score": "1",
"body": "@nwp That's true with regard to the assignment. Absolute speed at any cost except correctness of output. But I'm not sure what optimizations are never appropriate even when every bit of performance is desired. And to cloud things further, I'm not sure if there's a gray area when certain methods are reserved for the most extreme applications."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-09T16:44:04.157",
"Id": "448874",
"Score": "1",
"body": "In addition to my answer below, profile the code, this will tell you where the bottle necks are. Keep in mind the first rule of optimization is don't optimize, the the compiler do it for you. The second rule of optimization is generally find a faster algorithm."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-09T16:53:21.387",
"Id": "448880",
"Score": "1",
"body": "Having the compilation flags is nice, but which architecture are you targeting? Where will the program run for the measurements? Unless that information is given, we can at most give you some superficial answers."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-09T19:13:11.503",
"Id": "448903",
"Score": "0",
"body": "@hoffmale Our assignment is graded on a Xeon chip of unknown specification, but I would prefer to optimize my programs for my personal i7-8565U since I can become most familiar it. https://ark.intel.com/content/www/us/en/ark/products/149091/intel-core-i7-8565u-processor-8m-cache-up-to-4-60-ghz.html"
}
] |
[
{
"body": "<p>The code may be over optimized already and adding additional optimizations will only make it harder to read and maintain the code, but that said:</p>\n\n<h2>Missing Optimizations</h2>\n\n<ul>\n<li>When printing prefer <code>'\\n'</code> over <code>std::endl</code> because <code>std::endl</code> calls a system function to flush the output, <code>'\\n'</code> just inserts a new line. </li>\n<li>Put the check to print outside the function <code>print_board()</code> so that the function isn't even called. This saves the time cost of pushing everything onto the stack and altering the flow of execution. </li>\n<li>Use iterators or pointers in <code>print_board()</code> and <code>make_cells()</code> rather than indexing. Compiling with <code>-O3</code> may do this for you, but direct addressing is going to be faster than indexing. </li>\n<li>Depending on the processor and whether the instruction set includes an <code>auto decrement and test</code> instruction performance may be improved by counting down in for loops rather than counting up.</li>\n<li>Check the generated assembly code and know the instruction sets for the processor being used. </li>\n<li>Use the natural word size of the processor rather than specifying a word length. In the code this mean use <code>unsigned</code> rather than <code>unsigned long</code>. On most current processors you will be guaranteed a word size of at least 32 bits and probably a word size of 64 bits. </li>\n<li><p>Make member functions that don't change member values <code>const</code>.</p>\n\n<pre><code>void print_board() const\n{\n ...\n}\n</code></pre></li>\n</ul>\n\n<h2>Magic Numbers</h2>\n\n<p>There are a few numeric constants that should be removed or changed to symbolic constants. Numeric constants are sometimes referred to as <a href=\"https://en.wikipedia.org/wiki/Magic_number_(programming)\" rel=\"noreferrer\">Magic Numbers</a> because it's not clear what the values represent. There is a discussion of this on <a href=\"//stackoverflow.com/q/47882\">stackoverflow</a>.</p>\n\n<p>Examples would be the value <code>4</code> in main in the comparison of <code>argc</code> and the value <code>19</code> in these two declarations:</p>\n\n<pre><code>constexpr signed char offset_living_cipher[19] =\n{\n 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0\n};\n\nconstexpr signed char offset_counter_cipher[19] = \n{\n 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0\n};\n</code></pre>\n\n<p>The number <code>19</code> in the previous two declarations is not necessary since these will be calculated by the compiler.</p>\n\n<pre><code>constexpr signed char offset_living_cipher[] =\n{\n 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0\n};\n\nconstexpr signed char offset_counter_cipher[] = \n{\n 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0\n};\n</code></pre>\n\n<p>It might also be good to comment these declarations since it's not clear what is being done here.</p>\n\n<p>It might be better to <code>include <cstdlib></code> and use the system-defined symbolic constants <a href=\"https://en.cppreference.com/w/cpp/utility/program/EXIT_status\" rel=\"noreferrer\"><code>EXIT_FAILURE</code> and <code>EXIT_SUCCESS</code></a> in the <code>return</code> statements in <code>main</code>.</p>\n\n<h2>Don't Mix Memory Allocation Methodologies</h2>\n\n<p>In the constructor there is a call to the C programming memory allocation function <code>calloc()</code>, but in the function <code>make_cells()</code> there are two calls to <code>new</code>. There are a couple of problems here, the first is that the results of the call to <code>calloc()</code> are not checked. If the array allocated by <code>calloc()</code> isn't allocated (calloc returns NULL or nullptr) the first use of <code>board</code> will cause the program to terminate, however, if <code>new</code> fails it throws an exception. In this case since there are no <code>try {} catch {}</code> blocks the program will also terminate, but if there was a <code>try {} catch {}</code> block the program would still terminate if the <code>calloc()</code> failed. It would be best to be consistent with the memory allocation, and it would probably be better to stick with <code>new</code> rather than <code>calloc()</code>. </p>\n\n<h2>Avoid Using Namespace <code>std</code></h2>\n\n<p>If you are coding professionally you probably should get out of the habit of using the <code>using namespace std;</code> directive. The code will more clearly define where <code>cout</code> and other identifiers are coming from (<code>std::cin</code>, <code>std::cout</code>). As you start using namespaces in your code, it is better to identify where each function comes from because there may be function name collisions from different namespaces. The object <code>cout</code> you may override within your own classes. This <a href=\"//stackoverflow.com/q/1452721\">Stack Overflow question</a> discusses this in more detail.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-11T15:51:40.300",
"Id": "449245",
"Score": "0",
"body": "Using `'\\n'` instead of `std::endl` will probably not change a thing, as `'\\n'` usually flushes the ostream as well. To avoid unnecessary flushing, you must use `'\\n'`, but also specify `std::cout.sync_with_stdio(false)`. For reference, see https://en.cppreference.com/w/cpp/io/manip/endl , Notes, §2"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-09T16:33:57.793",
"Id": "230442",
"ParentId": "230403",
"Score": "5"
}
},
{
"body": "<p>Exploiting sparseness is a nice trick, though not as good as <a href=\"https://en.wikipedia.org/wiki/Hashlife\" rel=\"nofollow noreferrer\">Hashlife</a> (it's in a class of its own). Hashlife aside, there are simple approaches that work well on actual computers, not by being algorithmically clever but by being computer-friendly. Compared to a a completely plain approach, yours is definitely better. But it does not really tap into the potential of a modern CPU.</p>\n\n<p>For example on my PC (using a 4770K, so not very new any more), your benchmark takes around 2.85 seconds, but if I use some really simple no-tricks AVX2 implementation (so not using sparseness or anything else clever) of Game of Life, that takes around 0.38 seconds. That's around 7.5x faster, even though a lot more <em>work</em> is done. But work isn't time, and SIMD is great at crunching through a lot of work in a short time especially if you're working with 8-bit types. </p>\n\n<p>In a benchmark with a much sparser grid, the SIMD approach wouldn't do so well. Even in this benchmark, simulating more steps decreases the speedup, going down to ~3.7x for 100000 steps.</p>\n\n<p><a href=\"https://en.wikipedia.org/wiki/Advanced_Vector_Extensions\" rel=\"nofollow noreferrer\">AVX2</a> is an instruction set extension available in many x86 CPUs today, for example Haswell and newer Intel processors (including i7-8565U, but the Mystery Xeon CPU in the grading server may or may not support AVX2 depending on how old it is), and AMD Excavator and Zen. The instructions are exposed in C++ as intrinsic functions if you use a compiler that supports them. AVX2 includes instructions that apply an operation to 32 bytes at once, for example in the code below I used <a href=\"https://www.officedaytime.com/simd512e/simdimg/binop.php?f=paddb\" rel=\"nofollow noreferrer\"><code>_mm256_add_epi8</code></a> (aka <code>vpaddb</code>) several times, each performing 32 additions at once, to sum up the number of live neighbours for a row of 32 cells simultaneously. </p>\n\n<p>Example code:</p>\n\n<pre><code>void step() {\n#define INDEX(a, b) ((a) + (b) * WIDTH)\n for (size_t y = 0; y < HEIGHT; y++) {\n if (y == 0 || y == MAX_Y) {\n for (size_t x = 0; x < WIDTH; x++) {\n next_board[INDEX(x, y)] = board[INDEX(x, y)];\n }\n }\n else {\n next_board[INDEX(0, y)] = board[INDEX(0, y)];\n next_board[INDEX(MAX_X, y)] = board[INDEX(MAX_X, y)];\n size_t x = 1;\n for (; x < WIDTH - 33; x += 32) {\n __m256i n = _mm256_loadu_si256((__m256i*)&board[INDEX(x - 1, y - 1)]);\n n = _mm256_add_epi8(n, _mm256_loadu_si256((__m256i*)&board[INDEX(x, y - 1)]));\n n = _mm256_add_epi8(n, _mm256_loadu_si256((__m256i*)&board[INDEX(x + 1, y - 1)]));\n n = _mm256_add_epi8(n, _mm256_loadu_si256((__m256i*)&board[INDEX(x - 1, y)]));\n n = _mm256_add_epi8(n, _mm256_loadu_si256((__m256i*)&board[INDEX(x + 1, y)]));\n n = _mm256_add_epi8(n, _mm256_loadu_si256((__m256i*)&board[INDEX(x - 1, y + 1)]));\n n = _mm256_add_epi8(n, _mm256_loadu_si256((__m256i*)&board[INDEX(x, y + 1)]));\n n = _mm256_add_epi8(n, _mm256_loadu_si256((__m256i*)&board[INDEX(x + 1, y + 1)]));\n __m256i is3 = _mm256_cmpeq_epi8(n, _mm256_set1_epi8(3));\n __m256i is2 = _mm256_cmpeq_epi8(n, _mm256_set1_epi8(2));\n __m256i cellItself = _mm256_loadu_si256((__m256i*)&board[INDEX(x, y)]);\n __m256i isNextLive = _mm256_or_si256(is3, _mm256_and_si256(is2, cellItself));\n isNextLive = _mm256_abs_epi8(isNextLive);\n _mm256_storeu_si256((__m256i*)&next_board[INDEX(x, y)], isNextLive);\n }\n for (; x < WIDTH - 1; x++) {\n int n = board[INDEX(x - 1, y - 1)];\n n += board[INDEX(x, y - 1)];\n n += board[INDEX(x + 1, y - 1)];\n n += board[INDEX(x - 1, y)];\n n += board[INDEX(x + 1, y)];\n n += board[INDEX(x - 1, y + 1)];\n n += board[INDEX(x, y + 1)];\n n += board[INDEX(x + 1, y + 1)];\n next_board[INDEX(x, y)] = n == 3 || (n == 2 && board[INDEX(x, y)]);\n }\n }\n }\n\n swap(board, next_board);\n}\n</code></pre>\n\n<p>There are <a href=\"https://lemire.me/blog/2018/07/18/accelerating-conways-game-of-life-with-simd-instructions/\" rel=\"nofollow noreferrer\">more clever uses of AVX2</a>, for example using <code>vpshufb</code> to implement the automaton rule.</p>\n\n<p>An other popular approach is bit-packing the cells, and then using bitwise operations to calculate the next state, relying on the bit-parallel nature of bitwise operations to speed up the computation. <a href=\"https://www.cs.uaf.edu/2012/spring/cs641/lecture/02_14_SIMD.html\" rel=\"nofollow noreferrer\">This page</a> discusses that trick and some related history. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-09T19:28:08.817",
"Id": "448907",
"Score": "0",
"body": "forgive me for being naive, but could you explain `AVX2`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-09T19:32:17.940",
"Id": "448909",
"Score": "0",
"body": "@pacmaninbw in general or just what I used here?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-09T19:34:04.107",
"Id": "448910",
"Score": "1",
"body": "In general and what you used here, add it to the answer."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-09T18:35:21.867",
"Id": "230448",
"ParentId": "230403",
"Score": "4"
}
},
{
"body": "<p>Coding for performance doesn't mean that you should write unmaintainable code. Remember that developer time is valuable, too: any time you spend tracking down avoidable bugs is time you could have spent tweaking program performance. Some particular things that can be improved without impacting performance:</p>\n\n<ul>\n<li>Include the headers for standard identifiers we use (<code>std::swap</code> requires <code><utility></code>; <code>std::atoi</code> and <code>std::calloc</code> require <code><cstdlib></code>).</li>\n<li>Avoid <code>using namespace std;</code></li>\n<li>Prefer properly-typed <code>constexpr</code> values instead of preprocessor macros (I don't believe your claim that this made your code slower - I get the exact same assembly code with that change). These values should be (private) static members, not globals.</li>\n<li>Prefer C++ memory allocation to <code><cstdlib></code> allocation (<code>malloc()</code> and family). That makes the error checking much simpler (exceptions rather than return-value checking).</li>\n<li>Use a <code>std::vector</code> rather than raw <code>new[]</code>; that stops us leaking memory.</li>\n<li>Keep the argument parsing out of the core logic, and make it more robust (e.g. use <code>std::stoul()</code> for converting to <code>unsigned long</code>).</li>\n<li>Initialise members in the constructor's initializer list.</li>\n<li>If you really need short-term macros, then <code>#undef</code> them after use.</li>\n</ul>\n\n<hr>\n\n<p>Once we have maintainable code, we can work on the algorithm. We're very inefficient with storage (making for poor data locality, and thus, thrashing cache unnecessarily). We have two arrays of pointers, each the same dimension as <code>board</code>, but much bigger on platforms where <code>sizeof (unsigned char *)</code> is greater than 1. The pointers all point into <code>board</code>, so we could store indexes instead; better still, store separate <em>x</em> and <em>y</em> coordinates, so we don't have to do divisions.</p>\n\n<p>Given that our task is to minimize <em>real</em> time, we should look to parallelize as much as we can. On multi-core processors, Game of Life naturally parallelizes with each thread writing its own part of the next state, and with all threads sharing read access to the old state. SIMD parallelisation within each thread is possible, too, if your processor has support (e.g. NEON or AVX).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-10T08:23:40.043",
"Id": "230480",
"ParentId": "230403",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "230442",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-09T04:25:27.063",
"Id": "230403",
"Score": "7",
"Tags": [
"c++",
"performance",
"c++11",
"homework",
"game-of-life"
],
"Title": "Optimizing Conway's Game of Life in C++"
}
|
230403
|
<p>I have implemented a hash table. It works well. But if you think something needs to be improved, say it. This code was tested in Python 3.7.4.</p>
<pre><code>class Hashtable:
def __init__(self,size):
self.size = size
self.mainList = [[] for i in range(0,1)for j in range(self.size)]
def index(self,key):
#To get the index number.
asciiValue = 0
for i in key:
asciiValue = asciiValue + ord(i)
index = asciiValue % self.size
return index
def put(self,key,value):
#To add value to the list.
index = self.index(key)
self.mainList[index].append((key,value))
def get(self,key):
#To get value from the list
index = self.index(key)
for i in range(0,len(self.mainList[index])):
if self.mainList[index][i][0] == key:
return self.mainList[index][i][1]
return "This key cannot be found."
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-09T06:44:35.100",
"Id": "448792",
"Score": "1",
"body": "It will help your question if you tell us a little bit more about *why* you wrote this code (for fun, to learn something, for a specific task, ...) and *how* you intend to use your class, i.e. a little usage example."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-09T06:52:31.700",
"Id": "448794",
"Score": "1",
"body": "I'm learning the data structures inside Python. I just wrote this code to learn."
}
] |
[
{
"body": "<h1>\"magic\" method</h1>\n\n<p>If you're learning the data structures in Python, I would read about the <a href=\"https://docs.python.org/3/reference/datamodel.html#emulating-container-types\" rel=\"nofollow noreferrer\">python data model</a> and <a href=\"https://docs.python.org/3/library/collections.abc.html#collections-abstract-base-classes\" rel=\"nofollow noreferrer\">Collections abstract base classes</a> to see what magic methods you can/should implement. A Hashmap is a mapping, so it should implement <code>__getitem__</code>, <code>__iter__</code>, <code>__len__</code>, <code>__contains__</code>, <code>keys</code>, <code>items</code>, <code>values</code>, <code>get</code>, <code>__eq__</code>, and <code>__ne__</code></p>\n\n<h1>return vs exception</h1>\n\n<p>In case your mapping does not find a key, it returns <code>\"This key cannot be found.\"</code>. This means users of your code should check against this sentinel value when retrieving something. What if that is the value they want to store in this mapping? The correct way to handle a missing key, is to raise an Exception. More specifically a <code>KeyError</code></p>\n\n<h1><code>range</code></h1>\n\n<p><code>for i in range(0,1)</code> is equivalent to <code>range(1)</code>, so it only yields 0, which means that in this list comprehension it does nothing.</p>\n\n<pre><code>[[] for j in range(self.size)] \n</code></pre>\n\n<p>Would hav achieved the same. <code>[[]] * self.size</code> would not have worked, since the reference to the same inner list would have been copied.</p>\n\n<h1>variable names</h1>\n\n<p><code>size</code> is not the size of the mapping, but the size of the hash table, so this name might be confusing. Moreover, this should not be a public variable of the, so <code>_hashtable_size</code> would be more appropriate. </p>\n\n<p>According to PEP-8, variable names should be <code>snake_case</code>, so <code>mainList</code> would be <code>_main_list</code></p>\n\n<h1><code>get</code></h1>\n\n<p>For a dict and a mapping, <a href=\"https://docs.python.org/3/library/stdtypes.html#dict.get\" rel=\"nofollow noreferrer\"><code>get</code></a> has another argument <code>default</code>, which gets returned if the key is missing</p>\n\n<h1>iteration</h1>\n\n<p>In python, it is seldomly necessary to iterate over the index , like you do in <code>for i in range(0,len(self.mainList[index])):</code></p>\n\n<pre><code>for dict_key, value in self.mainList[index]:\n if dict_key == key:\n return value\n</code></pre>\n\n<p>achieves the same, but is a lot more clearer and concise</p>\n\n<h1>docstrings</h1>\n\n<p>Python has a convention on how to document a method. It's called <a href=\"https://www.python.org/dev/peps/pep-0257/\" rel=\"nofollow noreferrer\">docstrings</a>. Instead of a <code>#</code>, you use a <code>\"\"\"</code></p>\n\n<pre><code>def put(self, key, value):\n \"\"\"To add value to the list.\"\"\"\n</code></pre>\n\n<hr>\n\n<pre><code>class Hashtable:\n def __init__(self, size):\n \"\"\"explanation what this class does, and what the argument means\"\"\"\n self._hastable_size = size\n self._main_list = [[] for j in range(size)]\n\n def _index(self, key):\n # To get the index number.\n return sum(ord(i) for i in key) % self._hastable_size\n\n def __contains__(self, key):\n index = self._index(key)\n return any(dict_key == key for dict_key in self._main_list[index])\n\n def put(self, key, value):\n \"\"\"To add value to the list.\"\"\"\n if key in self: # calls self.__contains__(key)\n raise ValueError(f\"<{key}> already present\")\n # you can also choose to overwrite the already present value\n index = self._index(key)\n self._main_list[index].append((key, value))\n\n __setitem__ = put\n\n def __getitem__(self, key):\n if key not in self:\n raise KeyError(f\"<{key}> not present\")\n index = self._index\n for dict_key, value in self._main_list[index]:\n if dict_key == key:\n return value\n\n def get(self, key, default=None):\n # To get value from the list\n try:\n return self[key]\n except KeyError:\n return default\n\n def __len__(self):\n return sum(len(sublist) for sublist in self._main_list)\n\n ...\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-09T09:15:27.717",
"Id": "448814",
"Score": "0",
"body": "Thank you for a Maarten Fabré to spent your valuable time to get the review of my code. Let me correct as per your suggestion and get back to you. Today I learned many coding fundamentals and styles from your suggestions. Thanks a lot once again."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-09T09:19:08.773",
"Id": "448816",
"Score": "1",
"body": "don't correct your original question. Try to take this advice, and any other you might find on this site, and if you have a new version, pose a new question"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-09T07:47:49.347",
"Id": "230408",
"ParentId": "230404",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "230408",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-09T06:00:13.403",
"Id": "230404",
"Score": "1",
"Tags": [
"python",
"python-3.x",
"reinventing-the-wheel",
"hash-map"
],
"Title": "HashTable implementation in Python 3"
}
|
230404
|
<p>I just wrote this script to check if the name (that has 2 characters: 1 alphabet and 1 number) in Github is available or not so I can accompany this name.</p>
<p>Here is my script:</p>
<pre><code>#!/bin/bash
for i in {a..z}
do
echo 'running ...'
for j in {0..9}
do
out=$(curl -s -o /dev/null -w "%{http_code}" "https://github.com/$i$j") &
if [[ $out =~ .*4.* ]]
then
echo "$i$j is available"
else
echo "$i$j is not available"
fi
done
echo 'finish batch ...'
wait
done
</code></pre>
<p>Let me explain:</p>
<ul>
<li><p>I use 2 loops to generate all permutation of 2 characters.</p></li>
<li><p>I use <code>curl</code> to check status of the the host. For example:</p></li>
</ul>
<pre><code>curl -s -o /dev/null -w "%{http_code}" "https://github.com/google"
</code></pre>
<p>it will return the status of the host, in case the username exist it will return <code>200</code> else it will return <code>404</code></p>
<ul>
<li>Then I compare the status code with any 4xx error:</li>
</ul>
<pre><code>$out =~ .*4.*
</code></pre>
<ul>
<li><p>If the status is 4xx then the user name is available so I can get it.</p></li>
<li><p>Currently, it is running 10 background jobs at the same time by using <code>curl</code> with <code>&</code>.</p></li>
</ul>
<p>As you can see I have found <code>j3</code> and <code>m6</code>, <code>n5</code>, <code>u6</code>, <code>y4</code>, <code>y6</code>, <code>y9</code> are available.</p>
<p><a href="https://i.stack.imgur.com/vcfm5.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/vcfm5.png" alt="enter image description here"></a></p>
<p>Could you please help me to review this script.</p>
|
[] |
[
{
"body": "<p>The code is nice and short, and it is easy to read.</p>\n\n<p>I'm surprised that it works at all. Sending the <code>out=$(…)</code> command to the background sounds as if the code might continue before curl had the chance to fill the output. Do you get the same results without the <code>&</code>? I'd expect that more names are reported as available then.</p>\n\n<p>As long as the <code>&</code> is in the program, I would verify the results manually.</p>\n\n<p>I also don't see the point of running the requests in parallel. It's only 10 * 26 requests, which are answered anyway within 5 minutes.</p>\n\n<hr>\n\n<p>Update: The <a href=\"https://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_09_03_02\" rel=\"nofollow noreferrer\">Shell Command Language specification</a> says:</p>\n\n<blockquote>\n <p>If a command is terminated by the control operator ( '&' ), the shell shall execute the command asynchronously in a subshell.</p>\n</blockquote>\n\n<p>This means that the variable assignment cannot affect the <code>out</code> variable at all. This in turn means that the output you posted does not correspond to the code you posted. Please check again.</p>\n\n<p>If you can reproduce the behavior, please write down all details that might influence it. I tried to reproduce it, and I got exactly the result I expect after reading the specification: all names are not available.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-09T07:02:27.420",
"Id": "448795",
"Score": "1",
"body": "Sending them in parallel may not be much of an improvement now, but scripts like this tend to get reused for larger batches as well. If the next time there'll be 1000 requests and it doesn't hurt to add parallelisation now, why not? If there were only 10 requests being made, sure, it would be overkill. But now, sure, got to start somewhere."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-09T12:59:17.650",
"Id": "448851",
"Score": "0",
"body": "Scalability is great, but it doesn't look like the `&` is actually doing anything here or the code would break."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-09T06:48:09.447",
"Id": "230406",
"ParentId": "230405",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": "230406",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-09T06:05:23.823",
"Id": "230405",
"Score": "5",
"Tags": [
"bash",
"shell",
"curl"
],
"Title": "Bash script to check available name in Github"
}
|
230405
|
<p>Use case: </p>
<p>I am writing a proactive session updater; The use case is for parallel API calls or sequential API calls intercept the API call and check whether token is valid.</p>
<p>If token is valid continue with call
If token is invalid first update the token then continue with API call. </p>
<p>This is a cakewalk for sequential calls however for parallel calls I want to avoid DDOSing my server for repeated token calls. </p>
<p>Instead I have the following flow: </p>
<p>Suppose a burst of five parallel calls is intercepted by my token updater
The first call (Thread) goes to update the token, all the other four will await till token is updated by the first call. Once the token is updated, other threads continue with normal execution hence skipping the token updation. </p>
<p>Another point here is that requests might appear in bursts 5 API calls at T=1 and 10 API calls at some T=2 so I am also interested in resetting values
(as in executionLatch)</p>
<p>Now the code I have for implementing this is loaded with frameworks and Jargon, instead for simplicity sake I have come up with a below skeleton of exceution: </p>
<pre><code>class SingleUpdater {
private val lock = ReentrantLock()
private val executionLatch = AtomicBoolean(false)
// Say valueToBeUpdated is my session token
private val valueToBeUpdated = AtomicInteger(0)
private val awaitingThreadsCounter = AtomicInteger(0)
fun start() {
for (i in 0 until 100) {
Thread(this::execute).start()
Thread(this::execute).start()
Thread(this::execute).start()
}
Thread.sleep(3000)
for (i in 0 until 1) {
Thread(this::execute).start()
Thread(this::execute).start()
Thread(this::execute).start()
}
}
private fun execute() {
println("Trying to acquire lock ${Thread.currentThread().name}")
try {
awaitingThreadsCounter.set(awaitingThreadsCounter.get() + 1)
println("============================= awaitingThreadsCounter = ${awaitingThreadsCounter.get()} ============================= ")
lock.lock()
println("I am Thread ${Thread.currentThread().name} I have acquired lock")
if (executionLatch.get()) {
continueWithRestOfExecution()
} else {
doUpdate()
continueWithRestOfExecution()
}
} catch (e: Exception) {
e.printStackTrace()
} finally {
println("Released by ${Thread.currentThread().name}")
lock.unlock()
}
}
private fun continueWithRestOfExecution() {
if (awaitingThreadsCounter.get() >= 0) awaitingThreadsCounter.set(awaitingThreadsCounter.get() - 1)
println("I am Thread: ${Thread.currentThread().name} and I am executing continueWithRestOfExecution")
if (awaitingThreadsCounter.get() == 0) {
println(" ============================= BALANCED ============================= ")
executionLatch.set(false)
}
}
private fun doUpdate() {
try {
Thread.sleep(3000)
valueToBeUpdated.set(valueToBeUpdated.get() + 1)
println("=============================== Value is: $valueToBeUpdated ${Thread.currentThread().name} ===============================")
executionLatch.set(true)
} catch (ex: Exception) {
ex.printStackTrace()
}
}
}
</code></pre>
<p>Please help in analysing edge cases here. </p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-09T08:28:11.950",
"Id": "230410",
"Score": "1",
"Tags": [
"multithreading",
"kotlin"
],
"Title": "Thread await and execute different methods based on some event or value"
}
|
230410
|
<p>I made this script to calculate the amount of silence in seconds in an audio file. Is this a good method to do this, and if yes, can it be improved? It takes about 4 seconds for 20 audio files of 100-200 seconds of audio each, which seems pretty long to me.</p>
<p>The audio file is split in windows of <code>win_size</code> seconds. Every window that is below <code>sil_threshold</code> is considered 'silent'. By multiplying the number of silent windows by the window size, the number of silent seconds is obtained.</p>
<pre><code>import numpy as np
from scipy.io import wavfile
def calc_silence(audio, sil_threshold=0.03, win_size=0.25, ret="sec"):
"""Calculates total silence length in this audio file.
Keywords:
audio: location of the audiofile OR a (samplerate, audiodata) tuple
sil_threshold: percentage of the maximum window-averaged amplitude
below which audio is considered silent
win_size: length of window in sec (audio is cut into windows)
ret: the return type; can be one of the following:
- "sec": return the number of silent seconds
- "frac": return the frac of silence (between 0 and 1)
- "amp": return a list of amplitude values (one for each window)
- "issil": return an np-array of 0s and 1s (1=silent) for each window
- "chunk": return a list of (start, end, is_silent) tuples,
with start and end in seconds and is_silent is a boolean
"""
if isinstance(audio, tuple):
samplerate, data = audio
else:
# read the sample rate and data from the wave file
samplerate, data = wavfile.read(audio)
win_frames = int(samplerate * win_size) # number of samples in a window
win_amps = [] # windows in which to measure amplitude
for win_start in np.arange(0, len(data), win_frames):
# Find the end of the window
win_end = min(win_start + win_frames, len(data))
# Add the mean amplitude for this frame to the list of window amplitudes
win_amps.append(np.nanmean(np.abs(data[win_start:win_end])))
# Calculate the minimum threshold for a window to be silent
threshold = sil_threshold * max(win_amps)
# Find the windows that are silent
sils, = np.where(win_amps <= threshold)
# The silence length is the number of silent windows times the window length
sil = len(sils) * win_size
if ret == "sec":
return sil
elif ret == "frac":
return len(sils) / len(win_amps)
elif ret == "amp":
return win_amps
elif ret == "issil":
return (win_amps <= threshold).astype(int)
elif ret == "chunk":
chunks = []
t0, t1 = 0, 0
is_sil = win_amps[0] <= threshold
for wi, amp in enumerate(win_amps):
winsil = amp <= threshold
if winsil == is_sil:
t1 = (wi + 1) * win_size
else:
chunks.append((t0*win_size, t1*win_size, is_sil))
t0 = (wi + 1) * win_size
is_sil = not is_sil
chunks.append((t0*win_size, len(win_amps)*win_size, is_sil))
return chunks
else:
raise ValueError("Unknown return format: {}".format(ret))
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-09T12:06:58.517",
"Id": "448844",
"Score": "0",
"body": "@AlexV Lol. Not the point, but these files are 100-200 seconds each. (Edited my post)."
}
] |
[
{
"body": "<p>Your implementation is simple, which isn't bad, but it suffers from an accuracy issue. What if there is a single above-threshold sample at the middle of your window, preventing it from being detected as silent, and a similar subsequent window with one above-threshold sample in the middle? That constitutes one window's worth of silent samples that have not been detected. Instead, you should adopt a <em>moving aggregate</em> - absolute max, or maybe absolute median. Moving max requires that you maintain a queue and a sorted list. When you get a new sample, do a sorted insert of the absolute value of the sample to the list, a push to the queue, a pop to the queue, and drop the popped value from the list. The item at the end of the list will always be the max, and the item in the middle of the list will always be the median. As soon as the threshold is detected, silence has started and should not be considered to end until the threshold is exceeded. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-16T11:58:24.617",
"Id": "449874",
"Score": "1",
"body": "That's a nice addition, thanks! What you're describing looks like I'd implement it using a Python for-loop, while numpy-methods are implemented in C/C++ which ensures faster calculations. I'm thinking of applying `scipy.signal.medfilt` to the absolute audiodata."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-09T12:48:42.667",
"Id": "230422",
"ParentId": "230412",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "230422",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-09T09:18:21.173",
"Id": "230412",
"Score": "5",
"Tags": [
"python",
"python-3.x",
"signal-processing"
],
"Title": "Calculating silence in a WAV file"
}
|
230412
|
<p>I wrote this code to track small moving objects falling down a chute. The code works buts runs too slowly: using 60 FPS 1920 by 1080 footage the code only runs at about 10 FPS. The problem there is somewhat self-explanatory as I need the program to be able to process footage accurately at real-time speeds and need a very high FPS as the parts move extremely rapidly. Is there anything I can do to improve the run time? I initially tried using a simple neural network but training it proved to be excessively time consuming while this yielded an accurate result in much shorter time.</p>
<p>I'm a mechanical engineer and had to learn this in about a week, so sorry for any obvious mistakes.</p>
<p>Video footage can be seen here: <a href="https://www.youtube.com/watch?v=Zs5YekjqhxA&feature=youtu.be" rel="nofollow noreferrer">https://www.youtube.com/watch?v=Zs5YekjqhxA&feature=youtu.be</a></p>
<pre><code>import cv2
import numpy as np
import time
start_time = time.time()
count=0
ID=[0,1,2,3,4,5,6,7,8,9]
TrackList=[]
def nothing(x):
pass
def isolate(img, vertices):
mask=np.zeros_like(img)
channelcount=img.shape[2]
match=(255, )*channelcount
cv2.fillPoly(mask, vertices, match)
masked=cv2.bitwise_and(img, mask)
return masked
#read video input
cap=cv2.VideoCapture('testGood.mp4')
#background removal initiation either KNN or MOG2, KNN yeilded best results in testing
back=cv2.createBackgroundSubtractorKNN()
#grab initial frames
_,frameCap1=cap.read()
check , frameCap2=cap.read()
#main loop
while cap.isOpened:
#ensure there are frames to read
if check == False:
break
#image preprocessing
#declare region of interest eliminating some background issues
tlX,tlY,blX,blY,brX,brY,trX,trY=400,0,400,800,1480,800,1480,0
region=[(tlX,tlY), (blX, blY),(brX,brY) , (trX, trY) ]
grab=isolate(frameCap1,np.array([region],np.int32))
frame=cv2.pyrDown(grab)
#isolate region of interest
roi1=isolate(frameCap1,np.array([region],np.int32))
roi2=isolate(frameCap2,np.array([region],np.int32))
#drop resolution of working frames
frame1=cv2.pyrDown(roi1)
frame2=cv2.pyrDown(roi2)
#apply background subraction
fgmask1=back.apply(frame1)
fgmask2=back.apply(frame2)
#remove shadow pixels and replace them with black pixels or white pixels(0 or 255)
fgmask1[fgmask1==127]=0
fgmask2[fgmask2==127]=0
#apply a threshhold, not necessary but cleans ups some grey noise
_,thresh1=cv2.threshold(fgmask1,200,255,cv2.THRESH_BINARY)
_,thresh2=cv2.threshold(fgmask2,200,255,cv2.THRESH_BINARY)
#find movement
diff=cv2.absdiff(thresh1,thresh2)
contours, _=cv2.findContours(diff,cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
movement=False
moveBox=[]
for contour in contours:
if cv2.contourArea(contour)<1350 or cv2.contourArea(contour)>3500:
continue
#cv2.rectangle(frame,(x,y), (x+w,y+h),(0,255,0),2)
(x,y,w,h)=cv2.boundingRect(contour)
moveBox.append([x,y,w,h])
movement=True
continue
#cv2.putText(frame, 'Status: ()'.format('Movement'),(x,y),cv2.FONT_HERSHEY_SIMPLEX,1,(0,0,255),3)
#update existing IDs
for tracked in TrackList:
success, box=tracked[2].update(frame)
if success:
x,y,w,h=[int(v) for v in box]
cv2.rectangle(frame, (x,y), (x+w, y+h),(0,0,255),2)
cv2.rectangle(thresh1, (x,y), (x+w, y+h),(255,255,255),2)
tracked[3].append([x,y,w,h])
else:
tracked[3].append(None)
#check for tracking which has stopped or tracking which hasnt moved
delList=[]
p=0
for tracked in TrackList:
if len(tracked[3])==1:
continue
moved=True
n=len(tracked[3])-1
if tracked[3][n]==tracked[3][n-1] and tracked[3][0]!=tracked[3][n]:
if tracked[3][n][1]>tracked[3][0][1]:
count+=1
print('count1: ',count)
ID.append(tracked[0])
cv2.putText(frame, 'Counted',(tracked[3][-2][0],tracked[3][-2][1]),cv2.FONT_HERSHEY_SIMPLEX,1,(0,200,255),3)
delList.append(p)
else:
ID.append(tracked[0])
delList.append(p)
print('discard 1')
cv2.putText(frame, 'discard 1',(tracked[3][-2][0],tracked[3][-2][1]),cv2.FONT_HERSHEY_SIMPLEX,1,(0,200,255),3)
print(tracked)
elif n>5 and tracked[3][n]==tracked[3][n-1] and tracked[3][0]==tracked[3][n]:
ID.append(tracked[0])
delList.append(p)
cv2.putText(frame, 'discard 1',(tracked[3][-2][0],tracked[3][-2][1]),cv2.FONT_HERSHEY_SIMPLEX,1,(0,200,255),3)
print('discard 2')
elif tracked[3][-1]==None:
count+=1
print('count2: ',count)
ID.append(tracked[0])
cv2.putText(frame, 'Counted',(tracked[3][-2][0],tracked[3][-2][1]),cv2.FONT_HERSHEY_SIMPLEX,1,(0,200,255),3)
delList.append(p)
p+=1
cv2.putText(frame, 'Count: '+str(count),(50,50),cv2.FONT_HERSHEY_SIMPLEX,1,(0,200,255),3)
if len(delList)>0:
for a in delList:
TrackList[a]=None
#remove dead IDs
cleaned=False
while cleaned==False:
try:
TrackList.remove(None)
except ValueError:
cleaned=True
#check if movement was being tracked
untracked=[]
if movement==True:
checkContours,_=cv2.findContours(thresh1,cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
for contour in checkContours:
tracked=False
if 3500>cv2.contourArea(contour)>1350:
(x,y,w,h)=cv2.boundingRect(contour)
for box in TrackList:
if box[3][-1][0]<x+w/2<box[3][-1][0]+box[3][-1][2] and box[3][-1][1]<y+h/2<box[3][-1][1]+box[3][-1][3]:
tracked=True
if tracked==False:
#print('false')
(x,y,w,h)=cv2.boundingRect(contour)
cv2.rectangle(frame, (x,y), (x+w, y+h),(255,0,0),2)
cv2.rectangle(frame, (x,y), (x+w, y+h),(255,255,255),2)
untracked.append([x,y,w,h])
#assign tracking
ID.sort()
for unt in untracked:
idtemp=ID.pop(0)
tempFrame=frame
temp=[idtemp, 0, cv2.TrackerCSRT_create(),[unt]]
temp[2].init(tempFrame,(unt[0],unt[1],1.10*unt[2],1.10*unt[3]))
TrackList.append(temp)
#show frames
cv2.imshow('frame 1',frame)
#cv2.imshow('frame 2',thresh1)
#read new frame
frameCap1=frameCap2
check, frameCap2=cap.read()
#wait delay for a key to be pressed before continuing while loop or exiting
key=cv2.waitKey(1) & 0xFF
if key==27:
break
cap.release()
cv2.destroyAllWindows()
print(count)
print("runtime: %s seconds" % (time.time() - start_time))
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-09T10:58:19.090",
"Id": "448827",
"Score": "1",
"body": "Welcome to Code Review! I changed your [title to actually state what your code is supposed to do](/help/how-to-ask) and also added the [tag:beginner] tag, since you said you don't have a lot of experience (this is not meant to offend you, merely as a hint towards reviewers)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-09T11:00:16.873",
"Id": "448829",
"Score": "1",
"body": "Maybe you should also upload the original video file somewhere, because YouTube runs your video through yet another codec, which usually decreases the video quality (especially if fast moving things are involved)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-10T04:37:01.723",
"Id": "448948",
"Score": "1",
"body": "I can't see this as a code review, so it's a comment. An obvious place to start improving the performance of the code is reducing the preprocessing. The input is 124,416,000 three byte pixels second. It's all getting uncompressed from mp4. Then 80% of the IO and decompression is discarded when downsized to 1080x400 before thresholding discards more work. For a machine learning pipeline, all that data massaging can be done offline. For a real-time system it has a direct impact on performance. A monochrome lower resolution camera designed for computer vision, might be the way to go."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-10T14:04:15.853",
"Id": "449048",
"Score": "0",
"body": "@benrudgers It's a good point. You should be able to reconfigure the camera to simply capture in a lower resolution (and probably even in greyscale), which will not require post-processing."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-10T15:02:21.537",
"Id": "449058",
"Score": "0",
"body": "@Reinderien Since the code mentions .mp4, a camera that does not compress the video stream might also be appropriate. It might be possible to reconfigure a consumer oriented camera, but selecting the right camera for the job probably makes more sense if labor costs are ordinary. 0.5 megapixels at 60 fps in monochrome with a c-mount lens of the right focal length is likely less than $1k. Code that never runs is faster than anything a person can write."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-10T15:11:27.113",
"Id": "449068",
"Score": "0",
"body": "Do you need your video to be in such a high quality? If you reduce the image quality, you could process the video much faster"
}
] |
[
{
"body": "<p>First I'll say that it's very impressive for you to have gotten this working and with mostly reasonable methods, given one weeks' experience.</p>\n\n<h2>Range usage</h2>\n\n<pre><code>ID=[0,1,2,3,4,5,6,7,8,9]\n</code></pre>\n\n<p>can be</p>\n\n<pre><code>ID = list(range(10))\n</code></pre>\n\n<h2>No-op function</h2>\n\n<p>Based on what you've shown us, <code>nothing</code> does, well... nothing. It can be deleted.</p>\n\n<h2>Formatting</h2>\n\n<p>There's a code formatting standard called PEP8 that attempts to make Python code more legible, mostly by defining spacing. Software such as PyCharm or the various linters will suggest that</p>\n\n<ul>\n<li>You should have spaces around <code>=</code> in assignments such as <code>mask=np.zeros_like(img)</code></li>\n<li>Variable names like <code>channelcount</code> should be <code>channel_count</code></li>\n<li>There should be a space after <code>#</code> in comment lines</li>\n<li>etc.</li>\n</ul>\n\n<h2>Tuple unpacking</h2>\n\n<pre><code>_,frameCap1=cap.read()\n</code></pre>\n\n<p>This is fine. If you don't want to unpack, and you don't want to use the <code>_</code>, you could also</p>\n\n<pre><code>frameCap1 = cap.read()[1]\n</code></pre>\n\n<p>The same applies to your <code>threshold</code> calls.</p>\n\n<h2>Boolean comparison</h2>\n\n<pre><code>if check == False:\n</code></pre>\n\n<p>should be</p>\n\n<pre><code>if not check:\n</code></pre>\n\n<p>Similarly,</p>\n\n<pre><code>while cleaned==False:\n</code></pre>\n\n<p>should be</p>\n\n<pre><code>while not cleaned:\n</code></pre>\n\n<p>This:</p>\n\n<pre><code>if movement==True:\n</code></pre>\n\n<p>should be</p>\n\n<pre><code>if movement:\n</code></pre>\n\n<h2>No-op continue</h2>\n\n<p>This loop:</p>\n\n<pre><code>for contour in contours:\n if cv2.contourArea(contour)<1350 or cv2.contourArea(contour)>3500:\n continue\n #cv2.rectangle(frame,(x,y), (x+w,y+h),(0,255,0),2)\n (x,y,w,h)=cv2.boundingRect(contour)\n moveBox.append([x,y,w,h])\n movement=True\n continue\n</code></pre>\n\n<p>does not need a <code>continue</code> at the end; you can delete that.</p>\n\n<h2>Except-or-break</h2>\n\n<p>This loop:</p>\n\n<pre><code>#remove dead IDs\ncleaned=False\nwhile cleaned==False:\n try:\n TrackList.remove(None)\n except ValueError:\n cleaned=True\n</code></pre>\n\n<p>shouldn't use a termination flag. Instead:</p>\n\n<pre><code>while True:\n try:\n TrackList.remove(None)\n except ValueError:\n break\n</code></pre>\n\n<h2>Magic numbers</h2>\n\n<p>They abound in this program. Rather than writing literals like <code>3500</code>, you should assign them to named constants for legibility's sake, e.g.</p>\n\n<pre><code>MAX_CONTOUR = 3500\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-10T01:36:05.040",
"Id": "230461",
"ParentId": "230414",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "230461",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-09T09:42:25.383",
"Id": "230414",
"Score": "5",
"Tags": [
"python",
"performance",
"beginner",
"opencv"
],
"Title": "Image tracking code using opencv in python"
}
|
230414
|
<p>So, purely out of desire to learn, I decided to take on a project of making my own very basic programming language from scratch. After which, I made a lexer.</p>
<p>I've tested the lexer (but only a bit) and it seems to work. But, I tend to doubt myself a lot (which might actually be a good thing). So I I'd like people to review my code.</p>
<p>Just remember that I'm doing this in order to learn, so the code is most likely far from flawless, but I tried my best. Also, as I stated inside the code in comments, the error showing part is still work-in-progress so I've used placeholders instead, just ignore those for now. Ignore everything with the <code>show_error</code> function used.</p>
<p>Also I didn't provide source code for the <code>reader</code> class definition or declaration, but the <code>reader</code> class I used is quite basic so I don't think I would need to post it here, it should be possible to review the lexer without seeing the reader anyway.</p>
<p>Also, the language itself is very C-like for now... I gave the language the codename "Phi". But just treat it as if it were a C lexer for now.</p>
<p>So, here is the code of the lexer:</p>
<p>[declaration] lexer.hpp:</p>
<pre class="lang-cpp prettyprint-override"><code>// lexer.hpp
// Contains declaration of the Phi Lexer class
#ifndef PHI_LEXER
#define PHI_LEXER
#include "reader.hpp"
#include <vector>
#include <unordered_set>
class token
{
public:
enum class kinds : char{kw, iden, op, symbol, int_lit, flt_lit, str_lit, null};
// Enum class to represent every possible "kind" of token
token();
token(kinds kind, std::string token_val, std::size_t pos_line, std::size_t pos_col);
std::string value() const;
kinds kind() const;
std::pair<std::size_t, std::size_t> pos() const;
bool isNull() const;
bool operator==(const token& other) const;
bool operator!=(const token& other) const;
private:
kinds knd; // Token kind
std::string val;
std::size_t line, col;
};
class tokenstream
{
public:
token get();
token peek(std::size_t step = 0) const;
std::size_t size() const;
void unget(std::size_t amount = 0);
void push(token tok);
void pop();
void clear();
bool contains(token tok) const;
bool empty() const;
private:
std::vector<token> tokens;
std::size_t index;
};
namespace lexer_dict
{
static const std::unordered_set<std::string> keywords {"If", "Else", "While", "For"};
static const std::unordered_set<char> operators {'+', '-', '*', '/', '%',
'>', '<', '=', '!'};
static const std::unordered_set<std::string> double_operators
{">=", "<=", "!=", "+=", "-=", "*=", "/=", "%="};
static const std::unordered_set<char> symbols {',', ';', ':', '(', ')', '{', '}', '[', ']'};
static const std::unordered_set<char> whitespace {' ', '\n', '\t', '\v', '\r', '\f'};
} // Lexer dictionary to identify type of a character or string
class lexer
{
public:
lexer();
bool tokenize(reader read);
const tokenstream &value() const;
private:
tokenstream val; // The output value
};
#endif
</code></pre>
<p>[definition] lexer.cpp:</p>
<pre class="lang-cpp prettyprint-override"><code>// lexer.cpp
// Contains implementation of the Phi Lexer class
// WARNING: Errors are Work In Progress. Use it at your own risk
#include "lexer.hpp"
#include "errhandler.hpp"
#include <stdexcept>
#include <algorithm>
using kinds = token::kinds;
token::token() : knd{token::kinds::null}, val{},line{}, col{}
{
}
token::token(kinds kind, std::string token_val, std::size_t pos_line, std::size_t pos_col)
: knd{kind}, val{token_val}, line{pos_line}, col{pos_col}
{
}
std::string token::value() const
{
return val;
}
token::kinds token::kind() const
{
return knd;
}
std::pair<std::size_t, std::size_t> token::pos() const
{
return std::make_pair(line, col);
}
bool token::isNull() const
{
return knd == token::kinds::null;
}
bool token::operator==(const token& other) const
{
return knd == other.knd && val == other.val;
}
bool token::operator!=(const token& other) const
{
return !(*this == other);
}
token tokenstream::get()
{
if(tokens.size() > index)
return tokens[index++];
else
throw std::out_of_range("Trying to read past token stream");
}
token tokenstream::peek(std::size_t step /*= 0*/) const
{
if(tokens.size() > index + step)
return tokens[index + step];
else
throw std::out_of_range("Trying to read past token stream");
}
std::size_t tokenstream::size() const
{
return tokens.size() - index;
}
void tokenstream::unget(std::size_t amount /*= 1*/)
{
if(static_cast<long long>(index - amount) >= 0)
index -= amount;
else
throw std::out_of_range("Trying to read before token stream");
}
void tokenstream::push(token tok)
{
tokens.push_back(tok);
}
void tokenstream::pop()
{
tokens.pop_back();
}
void tokenstream::clear()
{
index = 0;
tokens.clear();
}
bool tokenstream::contains(token tok) const
{
return std::find(tokens.begin(), tokens.end(), tok) != tokens.end();
}
bool tokenstream::empty() const
{
return tokens.size() - index <= 0;
}
lexer::lexer() : val{}
{
}
bool lexer::tokenize(reader read)
{
auto is_oper = [](char c) -> bool
{
return lexer_dict::operators.find(c) != lexer_dict::operators.end();
};
auto is_double_oper = [](std::string &s) -> bool
{
return lexer_dict::double_operators.find(s) != lexer_dict::double_operators.end();
};
auto is_sym = [](char c) -> bool
{
return lexer_dict::symbols.find(c) != lexer_dict::symbols.end();
};
auto is_space = [](char c) -> bool
{
return lexer_dict::whitespace.find(c) != lexer_dict::whitespace.end();
};
auto is_kw = [](const std::string &s) -> bool
{
return lexer_dict::keywords.find(s) != lexer_dict::keywords.end();
};
// Lambda to check if character can be in a Numeric Literal
std::size_t i{}, line{1}, col{1}, begin_col{};
// i : index
// line : current line
// col : current column
// begin_col : beginning column of the current token being processed
const std::string& str = read.value();
std::string temp_str;
bool success = true;
while(i < str.length())
{
if(is_space(str[i]))
{
if(str[i] == '\n' || str[i] == '\v')
{
col = 1;
++line;
++i;
}
else
{
++col;
++i;
}
}
else if(is_sym(str[i]))
{
val.push(token{kinds::symbol, str.substr(i, 1), line, col});
++col;
++i;
}
else if (is_oper(str[i]))
{
// If str[i] is the last character (which is invalid syntax but it's for the parser to deal with)
// or if the next character isn't an operator,
// then just insert it normally into the token stream
if(i == str.length() - 1 || !is_oper(str[i+1]))
{
val.push(token{kinds::op, str.substr(i, 1), line, col});
++col;
++i;
}
// If str[i] is not the last character and the next character is also an operator,
// which means it's a double operator (eg: <=, >=, !=),
// ensure it's not an invalid operator combination (eg: not +- or *+)
// and then push it in the token stream
else
{
temp_str = str[i] + str[i + 1];
if(is_double_oper(temp_str))
val.push(token{kinds::op, temp_str, line, col});
else
{
show_error("stuff"); // Not finished yet
success = false;
break;
}
col += 2;
i += 2;
temp_str.clear();
}
}
else if (str[i] == '"')
{
std::size_t next_quote = str.find('"', i + 1);
// Find the next quote from starting from the next position
if(next_quote == std::string::npos)
{
// If no closing quote is found, show an error and set success flag to false
show_error("stuff"); // Not finished yet
success = false;
break;
}
val.push(token(kinds::str_lit, str.substr(i + 1, next_quote - i - 1), line, col));
// Make a substring containing everything inside the quotes, turn it into a token
// And push it into the tokenstream
col += next_quote - i + 1;
i = next_quote + 1;
}
else if(isdigit(str[i]))
{
begin_col = col;
// Store beginning column of token
// Since a numeric literal can't span multiple lines,
// We don't need to store the line
bool allow_sign = false;
bool expect_num = false;
bool dot_found = false;
bool e_found = false;
// allow_sign : Flag to allow a plus or minus sign if 'e' is encountered while lexing a numeric literal
// expect_num : Flag to check if the current char is '.' or 'e' so the next char must be a number
// dot_found : Flag to determine if '.' has been encountered
// e_found : Flag to determine if 'e' has been encountered
while (!(is_space(str[i]) || is_sym(str[i])))
{
if(isdigit(str[i]))
{
allow_sign = false;
expect_num = false;
}
else if(str[i] == '.')
{
if(expect_num || dot_found || e_found)
{
show_error("stuff"); // Not finished yet
success = false;
temp_str.clear();
break;
}
dot_found = true;
expect_num = true;
}
else if(str[i] == 'e')
{
if (expect_num || e_found)
{
show_error("stuff"); // Not finished yet
success = false;
temp_str.clear();
break;
}
allow_sign = true;
expect_num = true;
e_found = true;
}
else if(str[i] == '+' || str[i] == '-')
{
if (expect_num || !allow_sign)
{
show_error("stuff"); // Not finished yet
success = false;
temp_str.clear();
break;
}
allow_sign = false;
expect_num = false;
}
temp_str += str[i];
++col;
++i;
}
val.push(
token((dot_found || e_found) ? kinds::flt_lit : kinds::int_lit,
temp_str, line, begin_col));
temp_str.clear();
}
// Identifiers must start with an alphabet or an underscore '_'
// All keywords start with an alphabet
else if(isalpha(str[i]) || str[i] == '_')
{
begin_col = col;
// Store beginning column of token
// Since a keyword or identifier can't span multiple lines,
// We don't need to store the line
while (!(is_space(str[i]) || is_sym(str[i])))
{
temp_str += str[i];
++col;
++i;
}
if(is_kw(temp_str))
val.push(token(kinds::kw, temp_str, line, begin_col));
else
val.push(token(kinds::iden, temp_str, line, begin_col));
temp_str.clear();
}
// If a token begins with an invalid character, issue an error
else
{
show_error("stuff"); // Not finished yet
success = false;
break;
}
}
return success;
}
const tokenstream &lexer::value() const
{
return val;
}
</code></pre>
<p>I don't mind criticism. In fact, I would love advice on how to improve this. With that said, it'd be very helpful if you take your valuable time to review this.</p>
<p>Test case:
[source] [NOTE: The Program written in the language is completely random and has no purpose]</p>
<blockquote>
<pre><code>Int i = 0;
If(i < 0)
{
i = 2 + 3.1;
testStr = "Test";
print("Test");
}
While(i >= 2)
{
i--;
}
</code></pre>
</blockquote>
<p>Lexer output (using a print lexer function which prints the content stored in the lexer):</p>
<blockquote>
<pre><code>Lexer:
Token: KW, Val: "Int", Pos: (1, 1)
Token: Iden, Val: "i", Pos: (1, 5)
Token: Op, Val: "=", Pos: (1, 7)
Token: IntLit, Val: "0", Pos: (1, 9)
Token: Sym, Val: ";", Pos: (1, 10)
Token: KW, Val: "If", Pos: (3, 1)
Token: Sym, Val: "(", Pos: (3, 3)
Token: Iden, Val: "i", Pos: (3, 4)
Token: Op, Val: "<", Pos: (3, 6)
Token: IntLit, Val: "0", Pos: (3, 8)
Token: Sym, Val: ")", Pos: (3, 9)
Token: Sym, Val: "{", Pos: (4, 1)
Token: Iden, Val: "i", Pos: (5, 5)
Token: Op, Val: "=", Pos: (5, 7)
Token: IntLit, Val: "2", Pos: (5, 9)
Token: Op, Val: "+", Pos: (5, 11)
Token: FltLit, Val: "3.1", Pos: (5, 13)
Token: Sym, Val: ";", Pos: (5, 16)
Token: Iden, Val: "testStr", Pos: (6, 5)
Token: Op, Val: "=", Pos: (6, 13)
Token: StrLit, Val: "Test", Pos: (6, 15)
Token: Sym, Val: ";", Pos: (6, 21)
Token: Iden, Val: "print", Pos: (7, 5)
Token: Sym, Val: "(", Pos: (7, 10)
Token: StrLit, Val: "Test", Pos: (7, 11)
Token: Sym, Val: ")", Pos: (7, 17)
Token: Sym, Val: ";", Pos: (7, 18)
Token: Sym, Val: "}", Pos: (8, 1)
Token: KW, Val: "While", Pos: (10, 1)
Token: Sym, Val: "(", Pos: (10, 6)
Token: Iden, Val: "i", Pos: (10, 7)
Token: Op, Val: ">=", Pos: (10, 9)
Token: IntLit, Val: "2", Pos: (10, 12)
Token: Sym, Val: ")", Pos: (10, 13)
Token: Sym, Val: "{", Pos: (11, 1)
Token: Iden, Val: "i", Pos: (12, 5)
Token: Op, Val: "--", Pos: (12, 6)
Token: Sym, Val: ";", Pos: (12, 8)
Token: Sym, Val: "}", Pos: (13, 1)
</code></pre>
</blockquote>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-09T11:10:48.857",
"Id": "448834",
"Score": "0",
"body": "Welcome to Code Review! Since this is a lexer for your own programming language, it might help to post an example in that language just so that the reviewers can get a feeling what kind of syntax the code has to parse. From a quick look at your code, it seems to be C-like?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-09T11:24:03.957",
"Id": "448839",
"Score": "0",
"body": "@AlexV Yes it is C-like. I thought it would be obvious enough so I didn't specifically mention it"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-11T10:19:50.813",
"Id": "449184",
"Score": "0",
"body": "Can you list the supported language constructs so far?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-11T11:05:04.260",
"Id": "449194",
"Score": "0",
"body": "@L.F. I guess for now I'll stick to simple mathematic operations, simple things like If Statements and While Loops. That's all, for now"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-11T11:13:27.180",
"Id": "449195",
"Score": "0",
"body": "OK. Can you provide some test cases to provide more context regarding how this is supposed to work?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-11T11:23:34.253",
"Id": "449196",
"Score": "0",
"body": "@L.F. I added an example"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-11T11:50:19.493",
"Id": "449200",
"Score": "0",
"body": "@L.F. Also I fixed the lexer output, it seems the old output was from a previous version of the lexer"
}
] |
[
{
"body": "<p>Welcome to Code Review!</p>\n\n<h1>lexer.hpp</h1>\n\n<p>It is common practice to put standard headers before custom headers and sort them in alphabetical order:</p>\n\n<pre><code>#include <unordered_set>\n#include <vector>\n#include \"reader.hpp\"\n</code></pre>\n\n<p>Usually, class names are capitalized.</p>\n\n<p>In general, try to avoid abbreviations. The token kinds are more readable in full name:</p>\n\n<pre><code>enum class kinds {\n keyword,\n identifier,\n operator,\n symbol,\n int_literal,\n float_literal,\n string_literal,\n null,\n};\n</code></pre>\n\n<p>(The last comma is intentional.)</p>\n\n<p>Strings should be passed around by value. Also, storing numbers as string probably isn't a very good idea.</p>\n\n<p>Make a dedicated class for line-column number pairs.</p>\n\n<p><code>std::unordered_set</code> generally performs worse than <code>std::set</code> without a carefully crafted hash function. Use <code>std::set</code>.</p>\n\n<p>Currently, you are maintaining the class variant yourself. Things will become much easier if you use <code>std::variant</code>.</p>\n\n<h1>lexer.cpp</h1>\n\n<p>Instead of defining the default constructor yourself, use in-class member initializers and <code>= default</code> the default constructor. The other constructor should move from <code>token_val</code>, not copy.</p>\n\n<p><code>pos</code> can just return <code>{line, col}</code>. (Also see above for making a dedicated position class.)</p>\n\n<p>The lambdas don't need to explicitly specify <code>-> bool</code>. <code>is_double_oper</code> should accept by <code>const</code> reference.</p>\n\n<p>Consistently put a space after a control keyword like <code>while</code>.</p>\n\n<p>The <code>tokenize</code> function is becoming very very long. It should be cut down into several functions.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-11T11:57:43.287",
"Id": "449203",
"Score": "0",
"body": "Thanks for your advice, I'll try to do all the stuff you suggested. I don't get one thing though, what exactly do you mean by \"class variant\"? I don't see anything related to variants in my code.."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-11T11:59:56.503",
"Id": "449204",
"Score": "0",
"body": "@Arnil Basically, I mean the way you interpret the value (which is represented by a `std::string`) depends on the kind field."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-11T12:01:47.737",
"Id": "449206",
"Score": "0",
"body": "How can I use std::variant for it? I mean, the kinds are not separate types but just what kind of token the string represents"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-11T12:05:02.560",
"Id": "449207",
"Score": "0",
"body": "@Arnil Define a tag type for each token kind. For null, there is no data (`struct Null {};`). For integer literals, for example, you can store them as an `int` rather than a string (`struct Int_literal { int value; };`). Similarly for the rest. (Also, don't accept so fast, give others some time.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-11T12:05:06.053",
"Id": "449208",
"Score": "0",
"body": "Also any advice on how I can shorten the tokenize function? Like, what will I make smaller functions for?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-11T12:06:25.597",
"Id": "449209",
"Score": "0",
"body": "Also why would that [defining tag types for tokens and using variant] be a better idea than doing what I am doing right now?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-11T12:07:52.360",
"Id": "449210",
"Score": "0",
"body": "@Arnil The first thing that comes to mind is to extract the branches of the long `if else if` chain."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-11T12:09:09.180",
"Id": "449211",
"Score": "0",
"body": "@Arnil Because the semantics is clearer, especially when you add more complex features later (think of user defined objects)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-11T12:10:12.727",
"Id": "449212",
"Score": "0",
"body": "Alright I'll keep that in mind, thanks a lot for your advice, I really appreciate it."
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-11T11:51:55.990",
"Id": "230541",
"ParentId": "230416",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "230541",
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-09T10:28:00.917",
"Id": "230416",
"Score": "5",
"Tags": [
"c++",
"lexical-analysis"
],
"Title": "Work-In-Progress Lexer"
}
|
230416
|
<p>My approach was to visit all inversion count pair and count how many subarrays these pair contribute. Visiting every pair requires <span class="math-container">\$\mathcal{O}(n^2)\$</span> time, but I want an optimized version of this, something like <span class="math-container">\$\mathcal{O}(n \log n)\$</span>.</p>
<p>Can I do something with the Fenwick tree?
<a href="https://www.geeksforgeeks.org/counting-inversions/" rel="nofollow noreferrer">Inversion in an array</a>
<a href="https://www.geeksforgeeks.org/binary-indexed-tree-or-fenwick-tree-2/" rel="nofollow noreferrer">Fenwick tree</a></p>
<p>e.g. if <code>arr = [1,3,4,2]</code> , then total inversion count for all subarrays = <code>5</code>.</p>
<pre><code>number = int(input("Input number := "))
main_list = list(map(int,input().split()))
answer = 0
for i in range(number):
for j in range(number):
if i<j and main_list[i]>main_list[j]:
k = (i+1) * (number-j)
answer += k
print(answer)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-09T11:05:22.657",
"Id": "448831",
"Score": "2",
"body": "Welcome to Code Review! Is this a task you have chosen for yourself or is this from a programming course or challenge? If so, please include a link to the original problem description and also include it in an abbreviated from directly in your question."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-09T13:29:26.897",
"Id": "448853",
"Score": "0",
"body": "My college senior gave me the problem."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-09T15:41:54.850",
"Id": "448867",
"Score": "2",
"body": "Since you are only concerned with `i < j` why not put j in `range(i + 1, n)`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-09T16:20:17.763",
"Id": "448872",
"Score": "0",
"body": "yeah, I'll do that, but still, the time complexity is O(n^2)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-09T16:48:59.417",
"Id": "448875",
"Score": "1",
"body": "You need to learn the naming convention.https://www.python.org/dev/peps/pep-0008/"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-09T17:37:00.957",
"Id": "448888",
"Score": "3",
"body": "This question should include a brief description of what _inversion_ and _Fenwick tree_ mean in this context, as well as links for both. More context will get you a more meaningful review."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-09T21:40:11.640",
"Id": "448930",
"Score": "1",
"body": "Your original code works. The edit by @brijeshkalkani changed `n` to `number` in several places, but `k = (i+1) * (n-j)` remained unchanged. It also changed `l` to `main_list`, but didn't change all occurrences, and mistyped one occurrence as `mail_list`. Moreover, it changed spacing (a PEP review comment) and added a prompt to an `input()` that never existed. The edit should never have been approved."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-09T21:40:23.990",
"Id": "448931",
"Score": "0",
"body": "now it should work"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-09T21:43:36.957",
"Id": "448932",
"Score": "0",
"body": "@AJNeufeld I'm sorry about that. Can you suggest me any way to do this stuff efficiently?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-09T21:53:48.030",
"Id": "448933",
"Score": "0",
"body": "No need to apologize. Yes, you approved the edit, but you're new here, so easily forgiven. @brijeshkalkani is to blame for the low-quality edit, but they are also relatively new here and can be forgiven. \"Community\" is to blame for the rubber-stamp approval. I can give you a more efficient, code-golfed, one-line solution `answer = sum(i*j for i, di in enumerate(main_list[:-1], 1) for j, dj in enumerate(main_list[:i-1:-1], 1) if di > dj)` but that doesn't make use of a _Fenwick tree_, which will require more thought."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-09T21:58:42.553",
"Id": "448934",
"Score": "0",
"body": "but the worst-case complexity is still O(n^2) here. In the problem length of array <=10^5. The worst-case complexity of O(nlogn) is expected."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "11",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-09T10:34:22.053",
"Id": "230417",
"Score": "3",
"Tags": [
"python",
"algorithm",
"python-3.x",
"complexity"
],
"Title": "Calculating the total sum of inversion count for all subarrays"
}
|
230417
|
<p>I have implemented a Singly linked list. It works well. But if you think something needs to be improved, say it. This code was tested in Python 3.7.4.</p>
<pre><code>class Node(object):
def __init__(self, data):
self.data = data
self.nextNode = None
class LinkedList(object):
def __init__(self):
self.head = None
self.size = 0
# O(1) !!!
def insertStart(self, data):
self.size = self.size + 1
newNode = Node(data)
if not self.head:
self.head = newNode
else:
newNode.nextNode = self.head
self.head = newNode
def remove(self, data):
if self.head is None:
return
self.size = self.size - 1
currentNode = self.head
previousNode = None
while currentNode.data != data:
previousNode = currentNode
currentNode = currentNode.nextNode
if previousNode is None:
self.head = currentNode.nextNode
else:
previousNode.nextNode = currentNode.nextNode
# O(1)
def size1(self):
return self.size
# O(N)
def insertEnd(self, data):
self.size = self.size + 1
newNode = Node(data)
actualNode = self.head
while actualNode.nextNode is not None:
actualNode = actualNode.nextNode
actualNode.nextNode = newNode
def traverseList(self):
actualNode = self.head
while actualNode is not None:
print(actualNode.data)
actualNode = actualNode.nextNode
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-09T13:24:10.293",
"Id": "448852",
"Score": "5",
"body": "You added the [tag:unit-testing] tag, but I cannot see any unit tests in your code."
}
] |
[
{
"body": "<p>You are missing several important things for this code:</p>\n\n<h2>Type Annotations</h2>\n\n<p>Python 3.7 supports type annotations. Especially for a container class like this, you should fully use them.</p>\n\n<h2>Initializer parameters</h2>\n\n<p>Python containers generally all provide builder methods or class initializer functions that take other containers and use their contents. Consider:</p>\n\n<ul>\n<li><a href=\"https://docs.python.org/3/library/stdtypes.html#dict\" rel=\"nofollow noreferrer\"><code>dict(</code><em>iterable,</em><code>**kwarg)</code></a></li>\n<li><a href=\"https://docs.python.org/3/library/stdtypes.html#list\" rel=\"nofollow noreferrer\"><code>list(</code><em>iterable</em><code>)</code></a></li>\n<li><a href=\"https://docs.python.org/3/library/stdtypes.html#set\" rel=\"nofollow noreferrer\"><code>set(</code><em>iterable</em><code>)</code></a></li>\n<li><a href=\"https://docs.python.org/3/library/stdtypes.html#str\" rel=\"nofollow noreferrer\"><code>str(object=b'', encoding='utf-8', errors='strict')</code></a></li>\n<li><a href=\"https://docs.python.org/3/library/stdtypes.html#tuple\" rel=\"nofollow noreferrer\"><code>tuple(</code><em>iterable</em><code>)</code></a></li>\n</ul>\n\n<p>If you're writing a Python container, you need to conform to expectations. I expect to be able to initialize the container when I create it.</p>\n\n<h2>Protocols & Magic methods</h2>\n\n<p>Python has a well-established set of <em>protocols</em> for implementing containers. You just have to decide what kind of container you're writing.</p>\n\n<p>I would suggest that a singly-linked list is an <a href=\"https://docs.python.org/3/library/stdtypes.html#iterator-types\" rel=\"nofollow noreferrer\"><code>Iterable</code></a>, a <a href=\"https://docs.python.org/3/library/stdtypes.html#sequence-types-list-tuple-range\" rel=\"nofollow noreferrer\"><code>Sequence</code></a>, a <a href=\"https://docs.python.org/3/library/stdtypes.html#mutable-sequence-types\" rel=\"nofollow noreferrer\"><code>MutableSequence</code></a> and possibly a <a href=\"https://docs.python.org/3/library/stdtypes.html#set\" rel=\"nofollow noreferrer\"><code>Set</code></a> type.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-10T00:30:05.670",
"Id": "448937",
"Score": "1",
"body": "The _type annotations_ comment is certainly true, but a more direct reference to documentation is important for the uninitiated, if not an example applied to the code."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-09T15:27:34.977",
"Id": "230439",
"ParentId": "230425",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "230439",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-09T13:04:38.930",
"Id": "230425",
"Score": "4",
"Tags": [
"python",
"python-3.x",
"linked-list"
],
"Title": "Singly linked list implementation in python 3"
}
|
230425
|
<p>I have written the following method which works as expected. But is there a way to write this more elegantly in Java 8? Appreciate any feedback. Thanks. </p>
<pre><code>private String get(Details details, Value value){
Type type = Type.getEvent(details.getType());
if(type != null){
if("SAMPLE".equals(type.typeDesc())){
if(SPIN.equals(details.getSpin())){ // this if looks very similar to last line..
return BACKUP + SAMPLE + value.getId();
}
return DEFAULT_VAL + SAMPLE + value.getId();
}
return value.getRoute();
}
return StringUtils.contains(details.getSpin(), SPIN) ? BACKUP : DEFAULT_VAL;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-09T16:13:22.167",
"Id": "448871",
"Score": "3",
"body": "Could you edit the title to state what the code does?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-10T03:43:38.360",
"Id": "448943",
"Score": "2",
"body": "And then please [edit] the introduction text as well."
}
] |
[
{
"body": "<p>I think it's a personal thing, but I prefer == null checks with early exits, because that way you have all exception paths at the beginning and the normal execution path is less indented.\nFor your string concatenation you could make a ternary if and have one return statement less.</p>\n\n<pre><code>private String get(Details details, Value value){\n Type type = Type.getEvent(details.getType());\n if(type == null) {\n return StringUtils.contains(details.getSpin(), SPIN) ? BACKUP : DEFAULT_VAL;\n }\n\n if(\"SAMPLE\".equals(type.typeDesc())) {\n String prefix = SPIN.equals(details.getSpin()) ? BACKUP : DEFAULT_VAL;\n return prefix + SAMPLE + value.getId();\n }\n return value.getRoute();\n}\n</code></pre>\n\n<p>Now looking at this, you check the spin for equals and contains. Is this intentional? If not you could further reduce the code by pulling the prefix part up like this:</p>\n\n<pre><code>private String get(Details details, Value value){\n String prefix = SPIN.equals(details.getSpin()) ? BACKUP : DEFAULT_VAL;\n\n Type type = Type.getEvent(details.getType());\n if(type == null) {\n return prefix;\n }\n\n if(\"SAMPLE\".equals(type.typeDesc())) {\n\n return prefix + SAMPLE + value.getId();\n }\n return value.getRoute();\n}\n</code></pre>\n\n<p>In general you should use StringBuilder for string concatenation. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-09T13:44:58.023",
"Id": "230431",
"ParentId": "230428",
"Score": "4"
}
},
{
"body": "<p>Giving a similar answer to the one already provided.</p>\n\n<p>I'm a big fan of \"return a value for an edge case\" pattern. If there's a very specific case with its own return value, then it's more readable (to me..) to eliminate the special case in the beginning of the function, and then to focus on the regular flow.</p>\n\n<p>In your case:</p>\n\n<pre><code>private String get(Details details, Value value){\n Type type = Type.getEvent(details.getType());\n // apply the \"early return\" pattern\n if(type == null){\n return StringUtils.contains(details.getSpin(), SPIN) ? BACKUP : DEFAULT_VAL;\n }\n\n // apply the same pattern again\n if(!\"SAMPLE\".equals(type.typeDesc())){\n return value.getRoute();\n }\n\n // finally, the \"regular\" flow\n String prefix = SPIN.equals(details.getSpin()) ? BACKUP : DEFAULT_VAL\n return prefix + SAMPLE + value.getId();\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-09T21:35:04.673",
"Id": "230454",
"ParentId": "230428",
"Score": "3"
}
},
{
"body": "<p>I'm mostly concerned with this line:</p>\n\n<pre><code>if(\"SAMPLE\".equals(type.typeDesc())){\n</code></pre>\n\n<p>Comparison to a type string is a strong clue that there's an anti-pattern in this code. If the types are constrained to certain known values, then at the very least this should be tracked with an enumeration.</p>\n\n<p>More likely, though, is that you should do the traditional OOP thing: instead of writing polymorphism-by-<code>if</code>-statement, write polymorphism-by-class-derivation. In other words, this <code>get</code> method would be implemented in a base class, and then overridden in child classes where appropriate. No type check would take place except for the implicit type check done in the JVM when a base class method is invoked. Even if there is only one parent class and one <code>Sample</code> child class, that would be a better-structured and more maintainable solution than what I suspect is happening in your code right now.</p>\n\n<p>All of that said: it's difficult to know exactly what to do, what's feasible or even preferable without seeing more of your code. If you show more of the <code>Type</code> code I can expand on this. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-10T03:47:01.153",
"Id": "448945",
"Score": "1",
"body": "Without knowing any context of this code, it's brave to say that splitting the code into several classes makes it more maintainable."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-10T00:45:03.050",
"Id": "230460",
"ParentId": "230428",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "230431",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-09T13:31:50.780",
"Id": "230428",
"Score": "3",
"Tags": [
"java"
],
"Title": "How to write this method with similar checks and multiple returns more elegantly?"
}
|
230428
|
<p>I rewrote <code>echo</code> from the manpage to learn Rust, and got the following:</p>
<pre class="lang-rust prettyprint-override"><code>// echo in rust - display a line of text
use std::env;
static HELP: &'static str = "\
echo the STRING(s) to standard output.\n\
-n do not output the trailing newline\n\
-e enable intepretation of backslash escapes\n\
-E disable intepretation of backslash escapes (default)\n\
--help display this help and exit
If -e is in effect, the following sequence are recognized:
\\\\ backslash
\\a alert (BEL)
\\b backspace
\\c produce no futher output
\\e escape
\\f form feed
\\n new line
\\r carriage return
\\t horizontal tab
\\v vertical tab";
fn main() {
let mut args: Vec<String> = env::args().skip(1).collect();
let mut nl: bool = true; // the "-n" flag can be used to indicate no new line
let mut escape: bool = false; // Disable interpreation of backslashes
let mut args_count: usize = 0; // first argument is binary name
for stuff in &args {
if !stuff.starts_with("-") {
break;
}
if stuff == "-n" {
nl = false;
args_count += 1;
}
if stuff == "-e" {
escape = true;
args_count += 1;
}
if stuff == "-E" {
escape = false;
args_count += 1;
}
if stuff == "--help" {
println!("{}", HELP);
return;
}
}
if escape {
for stuff in &mut args[args_count..] {
*stuff = stuff.replace("\\\\", "\\"); // backslashe
*stuff = stuff.replace("\\a", ""); // alert (BEL)
*stuff = stuff.replace("\\b", ""); // backspace
*stuff = stuff.replace("\\c", ""); // produce no further output
*stuff = stuff.replace("\\e", ""); // escape
*stuff = stuff.replace("\\f", ""); // form feed
*stuff = stuff.replace("\\n", ""); // new line
*stuff = stuff.replace("\\r", ""); // carriage return
*stuff = stuff.replace("\\t", ""); // horizontal tab
*stuff = stuff.replace("\\v", ""); // vertical tab
}
}
print!("{}", args[args_count..].join(" "));
if nl {
println!();
}
}
</code></pre>
<p>I then had a look at previously asked questions on this topic, and learnt of <code>skip</code> from <a href="https://codereview.stackexchange.com/questions/203624/rust-echo-command-implementation/203649#203649">here</a>.</p>
<p>I would particularly welcome feedback on string manipulation, notably on the argument parsing (i.e. here, I expect known flags before data to echo), and the <code>if escape</code> block.</p>
<p>Could the argument parsing be converted to a <code>match</code> statement, whilst retaining the <code>arg_count</code> increment and the <code>break</code> condition?</p>
<p>Another thing I'm unsure of is that I'm first collecting <code>args</code> and then checking each element within the vector and eventually joining it, using a bunch of for loops. </p>
<p>Is there a more idiomatic way to do so, such as vector subtraction or...? </p>
<p>Lastly, my manpage for echo mentions support for decoding bytes:</p>
<pre class="lang-none prettyprint-override"><code>\0NNN byte with octal value NNN (1 to 3 digits)
\xHH byte with hexadecimal value HH (1 to 2 digits)
</code></pre>
<p>Would you have pointers on how to do this type of operation?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-09T14:14:36.040",
"Id": "448857",
"Score": "1",
"body": "As described in [Rust Echo Command Implementation](https://codereview.stackexchange.com/a/203712/32521), you really should not collect all of the input as a vector as it's very wasteful."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-09T14:17:41.450",
"Id": "448859",
"Score": "1",
"body": "@Shepmaster That can even make the program crash in case of infinite input."
}
] |
[
{
"body": "<p>Thanks to @Shepmaster's comment referring to one of his previous <a href=\"https://codereview.stackexchange.com/a/203712/32521\">answers</a>, I was able to make the process nicer, by using <code>env::args</code> as an Iterator. </p>\n\n<p>By doing so, it became much easier to switch to using a <code>match</code> statement, and avoids all the string concatenation I mentioned in my question.</p>\n\n<p>I've also managed to add the conversion from hex and octal values to chars by making use of <a href=\"https://doc.rust-lang.org/1.24.0/std/primitive.u8.html#method.from_str_radix\" rel=\"nofollow noreferrer\"><code>std::u8::from_str_radix</code></a> in conjunction with <a href=\"https://doc.rust-lang.org/std/primitive.str.html#method.trim_start_matches\" rel=\"nofollow noreferrer\"><code>std::string::String::trim_start_matches</code></a></p>\n\n<p>I therefore now have the following:</p>\n\n<pre class=\"lang-rust prettyprint-override\"><code>// echo in rust - display a line of text\nuse std::env;\nuse std::u8;\n\nstatic HELP: &'static str = \"\\\necho the STRING(s) to standard output.\\n\\\n-n do not output the trailing newline\\n\\\n-e enable intepretation of backslash escapes\\n\\\n-E disable intepretation of backslash escapes (default)\\n\\\n--help display this help and exit\n\nIf -e is in effect, the following sequence are recognized:\n\n \\\\\\\\ backslash\n \\\\a alert (BEL)\n \\\\b backspace\n \\\\c produce no futher output\n \\\\e escape\n \\\\f form feed\n \\\\n new line\n \\\\r carriage return\n \\\\t horizontal tab\n \\\\v vertical tab\n \\\\0NNN byte with octal value NNN (1 to 3 digits)\n \\\\xHH byte with hexadecimal value HH (1 to 2 digits)\n\";\n\nfn main() {\n let mut nl: bool = true; // the \"-n\" flag can be used to indicate no new line\n let mut escape: bool = false; // Disable interpretation of backslashes\n let mut args_done = false; // Argument parsing done\n let mut first = true; // Correct the printing spacing\n\n for arg in env::args().skip(1) {\n if !args_done {\n match arg.as_ref() {\n \"-n\" => nl = false,\n \"-e\" => escape = true,\n \"-E\" => escape = false,\n \"--help\" => print!(\"{}\", HELP),\n _ => args_done = true,\n }\n }\n\n if args_done {\n let mut datum: String = arg;\n if escape {\n datum = datum.replace(\"\\\\\\\\\", \"\\\\\"); // backslash\n datum = datum.replace(\"\\\\a\", \"\"); // alert (BEL)\n datum = datum.replace(\"\\\\b\", \"\"); // backspace\n datum = datum.replace(\"\\\\c\", \"\"); // produce no further output\n datum = datum.replace(\"\\\\e\", \"\"); // escape\n datum = datum.replace(\"\\\\f\", \"\"); // form feed\n datum = datum.replace(\"\\\\n\", \"\"); // new line\n datum = datum.replace(\"\\\\r\", \"\"); // carriage return\n datum = datum.replace(\"\\\\t\", \"\"); // horizontal tab\n datum = datum.replace(\"\\\\v\", \"\"); // vertical tab\n\n if datum.starts_with(\"\\\\x\") && 3 <= datum.len() && datum.len() <= 4 {\n // Hex values with at most 2 digits\n let value = datum.trim_start_matches(\"\\\\x\");\n let chr = u8::from_str_radix(value, 16).unwrap() as char;\n datum = chr.to_string();\n }\n\n if datum.starts_with(\"\\\\0\") && 3 <= datum.len() && datum.len() <= 5 {\n // Octal values with at most 3 digits\n let value = datum.trim_start_matches(\"\\\\0\");\n\n let chr = u8::from_str_radix(value, 8);\n // The maximum octal value for a byte is 377.\n // Check that this conversion was successful.\n if chr.is_ok() {\n let x = chr.unwrap() as char;\n datum = x.to_string();\n }\n }\n }\n if first {\n print!(\"{}\", datum);\n first = false;\n } else {\n print!(\" {}\", datum);\n }\n }\n }\n if nl {\n println!();\n }\n}\n</code></pre>\n\n<p>This now adds an extra <code>first</code> flag for correct formatting, but it's okay for what is done here.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-09T15:57:31.057",
"Id": "230441",
"ParentId": "230429",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-09T13:35:23.390",
"Id": "230429",
"Score": "7",
"Tags": [
"beginner",
"strings",
"rust",
"escaping"
],
"Title": "Rust echo implementation that supports command line options"
}
|
230429
|
<p>I'm working on generating large volumes of test data for some performance testing. Part of this is going to involve generating a lot of values that represent an "MBI", which is a certain kind of alpha-numeric identifier.</p>
<p>This identifier has the following rules: </p>
<ul>
<li>Is alpha-numeric (uppercase only letters)</li>
<li>Excludes letters that are commonly confused for numbers or other letters (<code>SLOIBZ</code>)</li>
<li>Is 11 digits long</li>
<li>Has specific rules on which values can go in which digit
<ul>
<li>The first digit can be a number 1-9</li>
<li>The second, fifth, eighth, and ninth digits can be any upper case letter besides <code>SLOIBZ</code>; I don't actually validate the upper-case requirement, and I just call <code>mbi.upper()</code> as needed.</li>
<li>The fourth, seventh, tenth, and eleventh digits can be any number 0-9</li>
<li>The remaining digits (third and sixth) can be any of the valid letters or numbers (including 0)</li>
</ul></li>
</ul>
<p>The following function validates that an MBI is valid (you can assume this is correct for your own review)</p>
<p>Assuming that the numbers are "before" the letters, the "first" MBI is then <code>"1A00A00AA00"</code>. My task is to generate a whole bunch of valid and unique MBIs by "incrementing" them. For example, I want to be able to do this:</p>
<pre><code>for _, mbi in zip(range(count_mbis_to_generate), mbi_generator("1A00A00AA99")):
print(mbi)
</code></pre>
<p>This should print <code>count_mbis_to_generate</code> distinct MBIs, starting with <code>"1A00A00AA99"</code> (assuming there are that many distinct MBIs that are greater than or equal to <code>"1A00A00AA99"</code>. If I wanted 10000 of them, then the last one should be <code>"1A00A00GA98"</code>.</p>
<hr>
<p>To accomplish this, I started by writing a function to validate that a given MBI matches the expected format:</p>
<pre><code>import re
def validate_mbi(mbi):
flags = re.IGNORECASE ^ re.VERBOSE
pattern = re.compile(
r"""
[1-9] # No leading zeros
[ac-hjkmnp-rt-z] # No letters that can be confused for numbers or each other
[ac-hjkmnp-rt-z\d] # Letter or number
\d # Any number
[ac-hjkmnp-rt-z]
[ac-hjkmnp-rt-z\d]
\d
[ac-hjkmnp-rt-z]{2} # Then two letters
\d{2} # Then two numbers
""",
flags=flags,
)
return mbi and len(mbi) == 11 and pattern.match(mbi)
</code></pre>
<p>I then created a generator that will start spitting out MBIs:</p>
<pre><code>def mbi_generator(start=None):
if not start:
start = "1A00A00AA00"
while validate_mbi(start):
yield start
start = increment_mbi(start)
</code></pre>
<p>Now I actually had to do some thinking. To do this arithmatic by hand, I came up with the following algorithm:</p>
<ol>
<li>Starting with the final digit (e.g. <code>mbi[10]</code>), attempt to increment it by 1 (following all normal rules)</li>
<li>If that results in a "carrying" operation, then set this digit to the minimum allowed value for this digit, and move on to the next digit</li>
<li>Repeat until I get to the first digit (e.g. <code>mbi[0]</code>). </li>
<li>If the first digit is the largest allowed value as well (<code>9</code>), then we cannot increment this MBI, so just return <code>None</code></li>
</ol>
<p>To accomplish this, I created dictionaries that I'm calling "pseudo-linked lists" (they are nowhere close to a true linked list, but it was the name that popped in my head when I made it). They would look like this:</p>
<ul>
<li>If my current value is <code>'A'</code>, then the next value is <code>'B'</code> and we don't have to carry. </li>
<li>If my current value is <code>'Z'</code>, then that is the largest possible value, so the "next" value is either <code>0</code> or <code>'A'</code>, depending on digit, and we do have to carry.</li>
</ul>
<p>This would end up looking like this kind of dictionary (for the <code>0-9</code> digits):</p>
<pre><code>{'0': ('1', False),
'1': ('2', False),
'2': ('3', False),
'3': ('4', False),
'4': ('5', False),
'5': ('6', False),
'6': ('7', False),
'7': ('8', False),
'8': ('9', False),
'9': ('0', True)}
</code></pre>
<p>The key is the current value, and then the value's first index is the "next" value, and the second index is the "carry" flag. Note that the values are strings, not numbers, because we're always operating on strings and its easier to store it this way than do conversions all over the place.</p>
<p>The function to spit out one of these dictionaries is like so:</p>
<pre><code>def build_pseudo_linked_list(value_list):
end_point = len(value_list) - 1
return {
current_value: (value_list[0] # Get the first value
if i == end_point # If we're at the end of the list
else value_list[i + 1], # Otherwise get the next value
i == end_point) # Whether or not we were at the end of the list
for i, current_value in enumerate(value_list)
}
</code></pre>
<p>From there, I just need to build up the different kinds of dictionaries, and then use them to increment the MBI.</p>
<pre><code>def increment_mbi(mbi):
# Get the list of possible values for each digit
string_list = [char for char in string.ascii_uppercase if char not in "SLOIBZ"] # exclude easily confused letters
digit_list = [str(i) for i in range(0, 10)] # any digit
partial_digit_list = [val for val in digit_list if val != "0"] # Any non-zero digit
combined_list = digit_list + string_list # any value from any list above
# The values a given digit can have as a pseudo-linked list
# current_value : (next_value, should_advance_digit)
first_digit_range = build_pseudo_linked_list(partial_digit_list)
letter_range = build_pseudo_linked_list(string_list)
full_digit_range = build_pseudo_linked_list(digit_list)
combined_range = build_pseudo_linked_list(combined_list)
# Each digit's ranges
ranges = [
first_digit_range,
letter_range,
combined_range,
full_digit_range,
letter_range,
combined_range,
full_digit_range,
letter_range,
letter_range,
full_digit_range,
full_digit_range,
]
index = 10 # Start from the back
mbi = mbi.upper() # If they gave us lower-case values, just roll with it
# Starting from the back, try to increment digits until we don't have to carry
for i in range(index, 0, -1):
next_value, should_advance = ranges[i][mbi[i]]
# If we get to the front and we need to reset, then we can't go any further
if i == 0 and should_advance:
return None
# Otherwise, slide our value in
mbi = mbi[:i] + next_value + mbi[i + 1 :]
# If we need to advance to the next digit then we continue, otherwise return our current state
if not should_advance:
return mbi
</code></pre>
<p>At this point, the logic was pretty straightforward, and mostly just requires building up our dictionaries and lists.</p>
<p>I'm looking for a review on a few things:</p>
<ol>
<li>Does this make sense? I need to add docstrings that explain all of this still, but hopefully the reasoning makes sense</li>
<li>Would making these classes actually help at all? I played around with it, but it didn't really seem to be any clearer than before</li>
<li>Are there any obvious ways to make this faster? This is working well enough to generate test data, which can be a "run it over the weekend on rare occasions" kind of thing, but I'd love for it to be faster.</li>
</ol>
<p>Bonus points if you come up with a really clever <code>itertools</code> implementation; I played with it for a while but it eventually got a little too obtuse for me</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-09T14:17:36.897",
"Id": "448858",
"Score": "1",
"body": "How about \"lookup table\" instead of \"pseudo-linked lists\"?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-10T20:29:01.113",
"Id": "449136",
"Score": "0",
"body": "Sooooo. This has fairly little to do with the review, and doesn't deserve to be an answer, but I wrote a C implementation: https://github.com/reinderien/mbi It's able to send _200 million codes per second_ to `/dev/null`, slower if you need them to go to a file."
}
] |
[
{
"body": "<blockquote>\n<p>Explicit is better than implicit.</p>\n<p>Simple is better than complex.</p>\n<p>Readability counts.</p>\n</blockquote>\n<p>The easiest way to make it faster would be to simply convert it into code:</p>\n<pre><code>def generate_mbis() -> Iterator[str]:\n """ Generate MBIs, starting with 1A00A00AA00.\n\n An MBI is a string with the following rules:\n\n [1-9] # No leading zeros\n [ac-hjkmnp-rt-z] # No letters that can be confused for numbers or each other\n [ac-hjkmnp-rt-z\\d] # Letter or number\n \\d # Any number\n [ac-hjkmnp-rt-z] \n [ac-hjkmnp-rt-z\\d] \n \\d \n [ac-hjkmnp-rt-z]{2} # Then two letters\n \\d{2} # Then two numbers\n """\n LETTERS = "acdefghjkmnpqrtuvwxyz".upper()\n D0_9 = "0123456789"\n\n # Using 2-space indents because so many\n for p0 in range(1, 9):\n for p1 in LETTERS:\n for p2 in LETTERS + D0_9:\n for p3 in D0_9:\n for p4 in LETTERS: \n for p5 in LETTERS + D0_9:\n for p6 in D0_9:\n for p7 in LETTERS:\n for p8 in LETTERS:\n for p9 in D0_9:\n for p10 in D0_9:\n yield p1+p2+p3+p4+p5+p6+p7+p8+p9+p10\n</code></pre>\n<p>You could probably improve speed by caching the partial sums in the inner loops. You <em>might</em> see some gain by using purely numeric indexing, using <code>range</code> instead of <code>for ... in ...</code>. (I don't know this, I just suspect it.)</p>\n<p>Implementing a start-string would be straightforward, but would require an <code>if/else</code> at each level. You might make a helper function for that. (<strong>Edit:</strong> this turns out to be wrong. See below for an example of resuming.)</p>\n<p><strong>Edit:</strong></p>\n<p>It's worth noting that yes, you could use <code>itertools.product</code> to get the same effect:</p>\n<pre><code>for tpl in itertools.product(range(1, 9),\n LETTERS,\n LETTERS + D0_9,\n D0_9, \n LETTERS,\n LETTERS + D0_9,\n D0_9,\n LETTERS,\n LETTERS,\n D0_9,\n D0_9):\n yield ''.join(tpl)\n</code></pre>\n<p>But you won't have any opportunity to tweak the performance. It's worth trying, but I expect you'll be able to use a <code>bytearray</code> or partial sum or something to get better speed than you can from this approach.</p>\n<p><strong>Edit:</strong></p>\n<p>There was some question in the comments about (re)starting from an arbitrary location and how it would affect performance. Here's a simple 3-digit demo program to show how it could be done:</p>\n<pre><code>import string\n\ndef gen_999(start: str = None):\n if start is None:\n start = '000'\n\n # Figure out the starting values\n s0, s1, s2 = ('000' + str(start))[-3:]\n digits = string.digits\n\n d0 = digits[digits.index(s0):]\n d1 = digits[digits.index(s1):]\n d2 = digits[digits.index(s2):]\n\n for p0 in d0:\n for p1 in d1:\n for p2 in d2:\n yield p0 + p1 + p2\n d2 = digits\n d1 = digits\n d0 = digits # Included only for symmetry.\n\ndef main():\n for i, mbi in enumerate(gen_999(949)):\n print(mbi)\n if i == 100:\n break\n else:\n print("ended before break")\n\nif __name__ == '__main__': \n main()\n</code></pre>\n<p>This code prints numbers from 949 to 999, and the performance hit is an extra assignment statement in each level of looping.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-09T15:02:46.787",
"Id": "448861",
"Score": "3",
"body": "These are - by far - the most nested for loops I have ever seen in Python code (well, basically any code) ;-) I'm glad `itertools.product` exists."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-09T15:27:44.743",
"Id": "448864",
"Score": "2",
"body": "I guess you could also take advantage of the fact that there is a repeating pattern: LETTERS, LETTERS + D0_9, D0_9, to reduce the numbers of nested loops"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-09T17:30:22.843",
"Id": "448886",
"Score": "0",
"body": "Your nested-loop implementation fails to initialize the digit ranges to a starting value, as the OP shows."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-09T17:32:50.503",
"Id": "448887",
"Score": "1",
"body": "_Implementing a start-string would be straightforward, but would require an if/else_ - right; and any meaningful analysis of this code's performance - which is important, since that's your primary focus - would require that that feature be present."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-09T19:10:42.047",
"Id": "448902",
"Score": "0",
"body": "@Reinderien That is untrue. The if/else doesn't affect performance, since it would be changing the iterables outside the loop(s). My point mainly is that this is a clean, performant structure that makes obvious what is happening. The original code is not particularly simple, nor clean, nor performant."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-09T21:06:58.203",
"Id": "448926",
"Score": "0",
"body": "_The original code is not particularly simple, nor clean, nor performant._ - That's certainly true, but it's important to show a cleaner or more performant solution that accomplishes the same goals. As to your claim that the iterables are changed only outside of the loop: I don't think that's possible. On the _first_ run of the inner loops you can use a predefined shorter iterable, but on all subsequent runs you'll need the full iterable."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-09T21:08:43.570",
"Id": "448927",
"Score": "0",
"body": "@AustinHastings One way to accomplish that is to preconfigure some iterables using `chain` and then `cycle`, but this has its own performance implications."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-09T22:37:41.793",
"Id": "448935",
"Score": "1",
"body": "I have added an example of restarting in mid-cycle. It's not as expensive as I originally wrote."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-10T11:23:12.777",
"Id": "449025",
"Score": "0",
"body": "@AustinHastings are you sure that this works as intended? I think you need the full range of digits in the inner loop, so you will have to append `d0 = digits[start:] + digits[:start]` so you will loop over the full range, just with a different starting point ?"
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-09T14:50:08.200",
"Id": "230434",
"ParentId": "230430",
"Score": "6"
}
},
{
"body": "<p>This is a fun problem. I've taken the liberty of writing an alternate implementation, which I will describe below. Note that I've not focused too much on performance at all, only on simplicity and good structure.</p>\n\n<h1>Suggested</h1>\n\n<pre><code>from typing import Iterable\n\nN = 11\n\n\nclass MBI:\n letters = tuple('ACDEFGHJKMNPQRTUVWXYZ')\n numbers = tuple(str(i) for i in range(10))\n digits = (\n numbers[1:],\n letters,\n numbers + letters,\n numbers,\n letters,\n numbers + letters,\n numbers,\n letters,\n letters,\n numbers,\n numbers,\n )\n assert len(digits) == N\n sizes = tuple(len(d) for d in digits)\n\n def __init__(self, indices: Iterable[int] = (0,)*N):\n indices = list(indices)\n assert len(indices) == N\n self.indices = indices\n\n def copy(self):\n return MBI(self.indices)\n\n @classmethod\n def parse(cls, as_str: str):\n assert len(as_str) == N\n return MBI((\n digs.index(s)\n for digs, s in zip(cls.digits, as_str)\n ))\n\n @classmethod\n def is_valid(cls, as_str: str) -> bool:\n try:\n cls.parse(as_str)\n return True\n except Exception as e:\n return False\n\n def __str__(self):\n return ''.join(digs[i] for digs, i in zip(self.digits, self.indices))\n\n def add(self, addend=1):\n for pos in range(N-1, -1, -1):\n carry, digit = divmod(self.indices[pos] + addend, self.sizes[pos])\n self.indices[pos] = digit\n if carry:\n if pos == 0:\n raise ValueError()\n addend = carry\n else:\n break\n\n\ndef increasing_same(mbi: MBI, n: int, addend: int = 1) -> Iterable[MBI]:\n for _ in range(n):\n yield mbi\n mbi.add(addend)\n\n\ndef increasing_copy(mbi: MBI, n: int, addend: int = 1) -> Iterable[MBI]:\n for _ in range(n):\n yield mbi\n mbi = mbi.copy()\n mbi.add(addend)\n\n\ndef test():\n assert MBI.is_valid('1A00A00GA98')\n assert not MBI.is_valid('2')\n assert not MBI.is_valid('00000000000')\n assert MBI.parse('1A00A00GA98').indices == [\n 0, 0, 0, 0, 0, 0, 0, 5, 0, 9, 8\n ]\n assert MBI.parse('1A00A00AA00').indices == [0]*N\n assert str(MBI()) == '1A00A00AA00'\n\n\ndef demo():\n for mbi in increasing_same(MBI.parse('4M44M44MN98'), 6):\n print(mbi)\n print()\n\n for mbi in increasing_same(MBI.parse('8ZZ9ZZ9ZZ95'), 10, 2):\n print(mbi)\n print()\n\n\nif __name__ == '__main__':\n test()\n demo()\n</code></pre>\n\n<h1>Rationale</h1>\n\n<p>This is class-based. You asked</p>\n\n<blockquote>\n <p>Would making these classes actually help at all?</p>\n</blockquote>\n\n<p>The answer is, in general, yes. Modelling a class like I've shown allows you to encapsulate parsing, formatting, validation and increment logic all in one tidy package. The class instance is mutable, so you can choose whether to iterate-and-mutate or iterate-and-copy.</p>\n\n<p>As to your validation strategy: You do not need regexes; just attempt to parse and catch a failure. Parsing into a machine-usable sequence of integers can serve both purposes: preparation for processing, as well as validation that the thing is processible at all.</p>\n\n<p>Another sensible modification is generalization of the addend in your incrementing logic. You can add by any number, not just incrementing by one, and the change is easy enough that it's better to make a generic function that can add anything instead of something that can only increment.</p>\n\n<blockquote>\n <p>Does this make sense?</p>\n</blockquote>\n\n<p>It's more complicated than it needs to be, and it isn't really tested. The suggested implementation includes some rudimentary tests that give you more confidence that this thing is doing what it should.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-09T16:37:01.747",
"Id": "230443",
"ParentId": "230430",
"Score": "11"
}
},
{
"body": "<p>As @AustinHastings pointed out, the itertools.product solution below doesn't work right unless you start at the beginning. So here's an alternate solution:</p>\n\n<pre><code>DIGIT = '0123456789'\nLETTER = 'ACDEFGHJKMNPQRTUVWXYZ'\nDIGLET = DIGIT + LETTER\n\ndef mbi_gen(start=None):\n pattern = [DIGIT[1:], # leading non-zero digit\n LETTER,\n DIGLET,\n DIGIT,\n LETTER,\n DIGLET,\n DIGIT,\n LETTER,\n LETTER,\n DIGIT,\n DIGIT\n ]\n if start:\n indices = [pattern[i].index(c) for i,c in enumerate(start)]\n else:\n indices = [0]*len(pattern)\n\n while True:\n yield ''.join(pat[i] for pat,i in zip(pattern, indices))\n\n for i in range(len(indices)-1, -1, -1):\n indices[i] += 1\n if indices[i] < len(pattern[i]):\n break\n\n indices[i] = 0\n</code></pre>\n\n<p><code>mbi_gen()</code> is a generator and can be used like so:</p>\n\n<pre><code>MBI = mbi_gen()\n\nfor n in range(10000):\n print(next(MBI))\n</code></pre>\n\n<p>or to generate a list of 10000 MBIs:</p>\n\n<pre><code>MBIs = list(it.islice(mbi_gen('3C12D34EF56'), 10000)\n</code></pre>\n\n<h3>itertools.product()</h3>\n\n<p>This is a task made for <code>itertools.product()</code>. As the docs say, <code>product(A, B, C)</code> is equivalent to <code>((a,b,c) for a in A for b in B for c in C)</code>. The <code>c</code> cycles the fastest, then 'b' and <code>a</code> is the slowest. Like an odometer. </p>\n\n<pre><code>import itertools as it\n\nDIGIT = '0123456789'\nLETTER = 'ACDEFGHJKMNPQRTUVWXYZ'\nDIGLET = DIGIT + LETTER\n\ndef mbi_gen(start=None):\n pattern = [DIGIT[1:], # leading non-zero digit\n LETTER,\n DIGLET,\n DIGIT,\n LETTER,\n DIGLET,\n DIGIT,\n LETTER,\n LETTER,\n DIGIT,\n DIGIT\n ]\n\n yield from (''.join(seq) for seq in it.product(*pattern))\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-10T16:51:03.013",
"Id": "449101",
"Score": "0",
"body": "I don't know if `DIGLET` is a good name, as it is very close to the name of a [Pokemon](https://bulbapedia.bulbagarden.net/wiki/Diglett_%28Pok%C3%A9mon%29). Perhaps the basic `DIGIT_LETTER` would be better, as `DIGLET` and `DIGIT` can be mistaken when reading quickly, since they look really similar (starts with `D`, has a `G` and ends with `T`)."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-09T22:00:09.920",
"Id": "230457",
"ParentId": "230430",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "230443",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-09T13:44:56.357",
"Id": "230430",
"Score": "11",
"Tags": [
"python",
"python-3.x",
"strings",
"iteration",
"generator"
],
"Title": "Generating sequential alphanumeric values that match a certain pattern"
}
|
230430
|
<p>Fetching database records and displaying as JSON. Asking for revision to ensure if everything's ok, i.e. connections are properly handled and closed in case of error.</p>
<pre><code>public class Department
{
public Department(int id, String name)
{
this.Id = id;
this.Name = name;
}
public int Id { get; set; }
public String Name { get; set; }
}
public List<Department> FindAllDepartment()
{
List<Department> rows = new List<Department>();
using (SqlConnection sqlConnection = new SqlConnection("Data Source=;Initial Catalog=;Persist Security Info=True;User ID=sa;Password=P@ssw0rd;pooling=true"))
{
SqlCommand command = new SqlCommand("SELECT * FROM Employees.dbo.Department", sqlConnection);
try
{
sqlConnection.Open();
using (SqlDataReader sqlDataReader = command.ExecuteReader())
{
while (sqlDataReader.Read())
rows.Add(new Department(sqlDataReader.GetInt32(0), sqlDataReader.GetString(1)));
}
return rows;
}
finally
{
sqlConnection.Close();
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-09T16:10:59.507",
"Id": "448870",
"Score": "0",
"body": "Could you edit the title to state what the code functionally does, rather than technically?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-10T14:08:17.513",
"Id": "449050",
"Score": "0",
"body": "Don't write ADO.NET code, use the likes of [Dapper](https://github.com/StackExchange/Dapper). [\"if you’re writing ADO.Net code by hand, you’re stealing from your employer or client.\"](https://lostechies.com/jimmybogard/2012/07/24/dont-write-your-own-orm/)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-10T14:11:37.610",
"Id": "449051",
"Score": "1",
"body": "I don't want to give my employer or client something that has 300+ outstanding issues, https://github.com/StackExchange/Dapper/issues plain vanilla ADO, just crack it down and learn to code the right way and just repeat."
}
] |
[
{
"body": "<blockquote>\n<pre><code> using (SqlConnection sqlConnection = new SqlConnection(\"Data Source=;Initial Catalog=;Persist Security Info=True;User ID=sa;Password=P@ssw0rd;pooling=true\"))\n {\n ...\n }\n finally\n {\n sqlConnection.Close();\n }\n }\n</code></pre>\n</blockquote>\n\n<p>You're correctly using a <code>using</code> statement for the connection, which will both close and dispose the connection when its scope finishes. So no need to explicit call <code>Close()</code>.</p>\n\n<p>Almost (if not) every database related object implements <code>IDisposable</code> - including <code>SqlCommand</code>, so you should encapsulate that in a <code>using</code> as well.</p>\n\n<p>All in all, your method should look like something like this:</p>\n\n<pre><code>public List<Department> FindAllDepartment()\n{\n using (SqlConnection sqlConnection = new SqlConnection(\"Data Source=;Initial Catalog=;Persist Security Info=True;User ID=sa;Password=P@ssw0rd;pooling=true\"))\n {\n sqlConnection.Open();\n\n using (SqlCommand command = new SqlCommand(\"SELECT * FROM Employees.dbo.Department\", sqlConnection))\n using (SqlDataReader sqlDataReader = command.ExecuteReader())\n {\n List<Department> rows = new List<Department>();\n while (sqlDataReader.Read())\n {\n rows.Add(new Department(sqlDataReader.GetInt32(0), sqlDataReader.GetString(1)));\n }\n\n return rows;\n }\n }\n}\n</code></pre>\n\n<p>where the <code>using</code> statements handle the clean up - even if an exception is thrown.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-09T16:50:18.933",
"Id": "448876",
"Score": "0",
"body": "Thanks, for `using (SqlCommand command`, are we missing braces?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-09T16:51:55.033",
"Id": "448878",
"Score": "1",
"body": "@AppDeveloper: No, we're allowed to \"stack\" `using` statements as shown :-)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-09T16:55:32.840",
"Id": "448881",
"Score": "0",
"body": "cool beans, very articulate. Can you refer me to any of your comprehensive insert, update or delete posts just for the sake of review."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-09T17:17:31.447",
"Id": "448883",
"Score": "0",
"body": "@AppDeveloper: I'm not sure if I understand your question?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-09T17:23:30.280",
"Id": "448884",
"Score": "2",
"body": "Asking for advice on code yet to be written or implemented is off-topic for this site. Even in a sneaky comment."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-09T16:45:35.190",
"Id": "230444",
"ParentId": "230437",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "230444",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-09T15:16:36.977",
"Id": "230437",
"Score": "0",
"Tags": [
"c#",
"sql-server"
],
"Title": "database connection, fetching rows and handling error in csharp"
}
|
230437
|
<p>I have the following situation: I have two <code>std::map<int,float></code> and I want to go through the first map one by one and find the element in the second map with the key closest to the key in the first map. Now, this plain situation is obviously addressed in other question like e.g. <a href="https://stackoverflow.com/questions/28404971/finding-the-closest-or-exact-key-in-a-stdmap">this one</a>, but here is where my situation deviates:
There might be elements in the second map that I do not want to consider because the value is below some criterion and thus even if the element is the closest, it will be discarded and now I have to check two other elements against the key. Below is a bit of dummy code that illustrates the input data and also a bit of code that seems to achieve what I want, but I am not sure if there is maybe a better/cleaner way of doing this. </p>
<pre><code>#include <iostream>
#include <map>
#include <cmath>
void setClosest( std::map<int,float>::iterator & it, std::map<int,float>::iterator &upper, std::map<int,float>::iterator &lower, int key ) {
it = fabs( upper->first - key ) < fabs( lower->first - key ) ? upper : lower;
}
int main(int, char**)
{
std::map<int, float> map1;
std::map<int, float> map2;
map1[5000] = 5.5;
map1[10000] = 5.2;
map1[12000] = 5.7;
map1[15000] = 5.3;
map1[20000] = 5.5;
map1[25000] = 5.9;
map2[10400] = 523.0;
map2[12500] = 99.0;
map2[15200] = 67.0;
map2[15400] = 76.0;
map2[20200] = 511.0;
map2[25800] = 567.0;
std::map<int,float>::iterator it = map1.begin();
std::map<int,float>::iterator lower;
std::map<int,float>::iterator upper;
std::map<int,float>::iterator closest;
for( ; it != map1.end(); ++it ) {
int key = it->first;
float value = it->second;
lower = map2.lower_bound(key);
upper = ( lower == map2.begin() ? lower : lower-- );
setClosest( closest, upper, lower, key);
std::cout << key << ' ' << upper->first << ' ' << lower->first << " -> " << closest->first << std::endl;
while( closest->second < 100 ) {
std::cout << "skipping too low value " << closest->first << ' ' << closest->second << std::endl;
closest == upper ? upper++ : lower--;
setClosest( closest, upper, lower, key);
}
std::cout << key << ' ' << upper->first << ' ' << lower->first << " -> " << closest->first << std::endl;
}
return 0;
}
</code></pre>
<p>Output</p>
<pre><code>5000 10400 10400 -> 10400
5000 10400 10400 -> 10400
10000 10400 10400 -> 10400
10000 10400 10400 -> 10400
12000 12500 10400 -> 12500
skipping too low value 12500 99
12000 15200 10400 -> 10400
15000 15200 12500 -> 15200
skipping too low value 15200 67
skipping too low value 15400 76
skipping too low value 12500 99
15000 20200 10400 -> 10400
20000 20200 15400 -> 20200
20000 20200 15400 -> 20200
25000 25800 20200 -> 25800
25000 25800 20200 -> 25800
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-09T15:40:10.063",
"Id": "448866",
"Score": "2",
"body": "Micro-review: `<cmath>` provides `std::fabs`, etc. (not necessarily also `::fabs`)."
}
] |
[
{
"body": "<p>Consider replacing the while loop with two for loops that increment lower and upper iterators till they have a suitable value - and only afterwards setting closest - it might be doing more operations but it is more cache friendly.</p>\n\n<p>Or simply create a new map2 with only valid values (simply filtrate unwanted). </p>\n\n<p>Though, different situation have different preferred solutions - there is a trade-off which solution is better depending on number of undesirable values in map2 and relative sizes of map1 and map2.</p>\n\n<p>I don't think that you can improve it beyond that, lest you have some extra knowledge you haven't shared. In certain cases, you might want to implement some completely different solutions that are not reliant on map.</p>\n\n<p>About the code itself, there are just a few minor issues:</p>\n\n<ol>\n<li>You don't take care of the case when <code>lower_bound</code> return an <code>end</code>, in this case program will crash or UB. Same problem inside the <code>while</code> scope.</li>\n<li>There is no need to declare the four iterators outside the scope. Just declare them with <code>auto</code> when you instantiate them. Nobody cares to see <code>std::map<int,float>::iterator</code>.</li>\n<li><p>replace setClosest with</p>\n\n<pre><code> template<typename MapItr>\n auto getClosestMapIterator(const MapItr &upper, const MapItr & lower, int key ) -> const MapItr& \n {\n return abs( upper->first - key ) < abs( lower->first - key ) ? upper : lower;\n }\n</code></pre>\n\n<p>and adjust usage <code>auto closest = getClosestMapIterator(upper, lower, key);</code> Also you better use <code>abs</code> instead of <code>fabs</code>, as <code>fabs</code> is for floating point types, so you unnecessarily cast integers to double with <code>fabs</code>.</p></li>\n<li>Inside <code>while</code> the line <code>closest == upper ? upper++ : lower--;</code> is confusing. Simply write if scope. Don't use the expression <code>cond ? ret_on_true : ret_on_false</code> for side-effects, only when you want to get the return value.</li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-12T07:59:20.007",
"Id": "230587",
"ParentId": "230438",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-09T15:23:07.937",
"Id": "230438",
"Score": "3",
"Tags": [
"c++"
],
"Title": "Closest element in std map when discarding values"
}
|
230438
|
<p>I was wondering wether my implementation of the PreferenceService below is thread safe or could cause memory leaks. </p>
<p>Android Studio gives me the warning "Do not place Android context classes in static fields". But since this warning is known to show in some cases where it does not really apply I am not sure if this is actually one of those cases. Replacing <code>this._context = context;</code> with <code>this._context = context.getApplicationContext();</code> removes the warning...</p>
<p>Is there anything else that should stop me from using this in my release build?</p>
<pre><code>package my.package.service;
// Android
import android.content.Context;
import android.content.SharedPreferences;
// Android X
import androidx.annotation.NonNull;
import androidx.preference.PreferenceManager;
// Internal dependencies
import my.package.R;
public class PreferenceService
{
/* SINGLETON */
private static PreferenceService instance;
/* ATTRIBUTES */
private Context _context;
private SharedPreferences _preferences;
/* LIFECYCLE */
/**
* TODO
* @param context
*/
private PreferenceService(@NonNull Context context)
{
this._context = context;
this._preferences = PreferenceManager.getDefaultSharedPreferences(this._context);
}
/**
* TODO
* @return
*/
@NonNull
public static synchronized PreferenceService create(@NonNull Context context)
{
if(PreferenceService.instance == null)
{
PreferenceService.instance = new PreferenceService(context);
}
return PreferenceService.instance;
}
/**
* TODO
* @return
*/
@NonNull
public static PreferenceService use()
{
if(PreferenceService.instance != null)
{
return PreferenceService.instance;
}
else throw new IllegalStateException("PreferenceService must be created before usage.");
}
/* GETTER & SETTER */
/**
* TODO
* @return
*/
public boolean getNightModePreference()
{
return this._preferences.getBoolean(this._context.getString(R.string.preference_key_night_mode), false);
}
/**
* TODO
* @param newNightModePreferenceValue
* @return
*/
public void setNightModePreference(boolean newNightModePreferenceValue)
{
this._preferences.edit().putBoolean(this._context.getString(R.string.preference_key_night_mode), newNightModePreferenceValue).apply();
}
}
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-09T15:38:50.543",
"Id": "230440",
"Score": "2",
"Tags": [
"java",
"android",
"singleton",
"wrapper",
"configuration"
],
"Title": "SharedPreferences singleton wrapper"
}
|
230440
|
<p>I have written below code using GMAIL API reference which creates a basic message, sends it and also lists all the messages from user's mailbox matching a keyword.It works fine. Looking for experts comments to improve it .</p>
<p>Here is the code- </p>
<pre><code># coding: utf-8
# In[26]:
#!/usr/bin/python
# -*- coding: utf-8 -*-
from __future__ import print_function
import pickle
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from email.mime.text import MIMEText
import base64
from apiclient import errors
import pandas as pd
# Defining the scope, although it should be narrowed down, but I used full access for this task
SCOPES = ['https://mail.google.com/']
def get_creds():
"""Shows basic usage of the Gmail API.
Lists the user's Gmail labels.
"""
creds = None
# The file token.pickle stores the user's access and refresh tokens, and is
# created automatically when the authorization flow completes for the first
# time.
if os.path.exists('token.pickle'):
with open('token.pickle', 'rb') as token:
creds = pickle.load(token)
# If there are no (valid) credentials available, let the user log in.
if not creds or not creds.valid:
if creds and creds.expired and creds.refresh_token:
creds.refresh(Request())
else:
flow = InstalledAppFlow.from_client_secrets_file('credentials.json'
, SCOPES)
creds = flow.run_local_server(port=0)
# Save the credentials for the next run
with open('token.pickle', 'wb') as token:
pickle.dump(creds, token)
# Bulding the service
service = build('gmail', 'v1', credentials=creds)
return service
def create_message(
sender,
to,
subject,
message_text,
):
"""
Create a message for an email. Args:
sender: Email address of the sender.
to: Email address of the receiver.
subject: The subject of the email message.
message_text: The text of the email message.
Returns:
An object containing a base64url encoded email object.
"""
message = MIMEText(message_text)
message['to'] = to
message['from'] = sender
message['subject'] = subject
return {'raw': base64.urlsafe_b64encode(message.as_string().encode()).decode()}
def send_message(service, user_id, message):
"""Send an email message.
Args:
service: Authorized Gmail API service instance.
user_id: User's email address. The special value "me"
can be used to indicate the authenticated user.
message: Message to be sent.
Returns:
Sent Message.
"""
try:
message = service.users().messages().send(userId=user_id,
body=message).execute()
# print('Message Id: %s' % message['id'])
return message
except errors.HttpError as error:
# I would rather log all the errors in staging table or in a file, though it depends on error handling method used
print('An error occurred: %s' % error)
def ListMessagesMatchingQuery(service, user_id, query=''):
"""List all Messages of the user's mailbox matching the query.
Args:
service: Authorized Gmail API service instance.
user_id: User's email address. The special value "me"
can be used to indicate the authenticated user.
query: String used to filter messages returned.
Eg.- 'from:user@some_domain.com' for Messages from a particular sender.
Returns:
List of Messages that match the criteria of the query. Note that the
returned list contains Message IDs, you must use get with the
appropriate ID to get the details of a Message.
"""
try:
response = service.users().messages().list(userId=user_id,
q=query).execute()
messages = []
if 'messages' in response:
messages.extend(response['messages'])
while 'nextPageToken' in response:
page_token = response['nextPageToken']
response = service.users().messages().list(userId=user_id,
q=query, pageToken=page_token).execute()
messages.extend(response['messages'])
return messages
except errors.HttpError as error:
# Again ,depends on error handling method, its a print command for this task
print('An error occurred: %s' % error)
def GetMimeMessage(service, user_id, msg_id):
"""Get a Message and use it to create a MIME Message.
Args:
service: Authorized Gmail API service instance.
user_id: User's email address. The special value "me"
can be used to indicate the authenticated user.
msg_id: The ID of the Message required.
Returns:
A MIME Message, consisting of data from Message.
....
....The format can vary there are many as full,
...."full": Returns the full email message data with body
....content parsed in the payload field; the raw field is not used. (default)
"""
try:
f_m = service.users().messages().get(userId=user_id, id=msg_id,
format='full').execute()
# msg_str = base64.urlsafe_b64decode(message['full'].encode('ASCII'))
# mime_msg = email.message_from_string(msg_str)
return f_m
except errors.HttpError as error:
# Again, depends on error handling method
print('An error occurred: %s' % error)
if __name__ == '__main__':
# Calling to connect and authorize GMAIL API
creds = get_creds()
# Call to create a message with parameters, parameters can be read from a file also
the_message = create_message('sender',
'rec',
'final test',
'final test before commenting')
# Call to send the message created above, again parameters can be read from a file
send_message(creds, 'sender', the_message)
matching_message = ListMessagesMatchingQuery(creds,
'sender', query='ams')
df = pd.DataFrame()
for i in matching_message:
full_m = GetMimeMessage(creds, 'sender', i['id'])
dict_new = dict(full_m)
df = df.append(dict_new, ignore_index=True)
# Exporting to CSV, File name can be parametrized
df.to_csv('out0910.csv')
</code></pre>
<p>Based on the review comment
1. Variable RE use
2. Unguarded Code </p>
<p>below is the revised code-</p>
<pre><code># coding: utf-8
# In[26]:
#!/usr/bin/python
# -*- coding: utf-8 -*-
from __future__ import print_function
import pickle
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from email.mime.text import MIMEText
import base64
from apiclient import errors
import pandas as pd
# Defining the scope, although it should be narrowed down, but I used full access for this task
SCOPES = ['https://mail.google.com/']
def get_creds():
"""Shows basic usage of the Gmail API.
Lists the user's Gmail labels.
"""
creds = None
file = 'token.pickle'
# The file token.pickle stores the user's access and refresh tokens, and is
# created automatically when the authorization flow completes for the first
# time.
if os.path.exists(file):
with open(file, 'rb') as token:
creds = pickle.load(token)
# If there are no (valid) credentials available, let the user log in.
if not creds or not creds.valid:
if creds and creds.expired and creds.refresh_token:
creds.refresh(Request())
else:
flow = InstalledAppFlow.from_client_secrets_file('credentials.json'
, SCOPES)
creds = flow.run_local_server(port=0)
# Save the credentials for the next run
with open(file, 'wb') as token:
pickle.dump(creds, token)
# Bulding the service
service = build('gmail', 'v1', credentials=creds)
return service
def create_message(
sender,
to,
subject,
message_text,
):
"""
Create a message for an email. Args:
sender: Email address of the sender.
to: Email address of the receiver.
subject: The subject of the email message.
message_text: The text of the email message.
Returns:
An object containing a base64url encoded email object.
"""
message = MIMEText(message_text)
message['to'] = to
message['from'] = sender
message['subject'] = subject
return {'raw': base64.urlsafe_b64encode(message.as_string().encode()).decode()}
def send_message(service, user_id, message):
"""Send an email message.
Args:
service: Authorized Gmail API service instance.
user_id: User's email address. The special value "me"
can be used to indicate the authenticated user.
message: Message to be sent.
Returns:
Sent Message.
"""
try:
message = service.users().messages().send(userId=user_id,
body=message).execute()
# print('Message Id: %s' % message['id'])
return message
except errors.HttpError as error:
# I would rather log all the errors in staging table or in a file, though it depends on error handling method used
print('An error occurred: %s' % error)
def ListMessagesMatchingQuery(service, user_id, query=''):
"""List all Messages of the user's mailbox matching the query.
Args:
service: Authorized Gmail API service instance.
user_id: User's email address. The special value "me"
can be used to indicate the authenticated user.
query: String used to filter messages returned.
Eg.- 'from:user@some_domain.com' for Messages from a particular sender.
Returns:
List of Messages that match the criteria of the query. Note that the
returned list contains Message IDs, you must use get with the
appropriate ID to get the details of a Message.
"""
try:
response = service.users().messages().list(userId=user_id,
q=query).execute()
messages = []
if 'messages' in response:
messages.extend(response['messages'])
while 'nextPageToken' in response:
page_token = response['nextPageToken']
response = service.users().messages().list(userId=user_id,
q=query, pageToken=page_token).execute()
messages.extend(response['messages'])
return messages
except errors.HttpError as error:
# Again ,depends on error handling method, its a print command for this task
print('An error occurred: %s' % error)
def GetMimeMessage(service, user_id, msg_id):
"""Get a Message and use it to create a MIME Message.
Args:
service: Authorized Gmail API service instance.
user_id: User's email address. The special value "me"
can be used to indicate the authenticated user.
msg_id: The ID of the Message required.
Returns:
A MIME Message, consisting of data from Message.
....
....The format can vary there are many as full,
...."full": Returns the full email message data with body
....content parsed in the payload field; the raw field is not used. (default)
"""
try:
f_m = service.users().messages().get(userId=user_id, id=msg_id,
format='full').execute()
# msg_str = base64.urlsafe_b64decode(message['full'].encode('ASCII'))
# mime_msg = email.message_from_string(msg_str)
return f_m
except errors.HttpError as error:
# Again, depends on error handling method
print('An error occurred: %s' % error)
def GetEmailListWithContent(matching_message,creds, sender):
df = pd.DataFrame()
for i in matching_message:
full_m = GetMimeMessage(creds, 'sender', i['id'])
dict_new = dict(full_m)
df = df.append(dict_new, ignore_index=True)
return df
if __name__ == '__main__':
# Calling to connect and authorize GMAIL API
creds = get_creds()
# Call to create a message with parameters, parameters can be read from a file also
the_message = create_message('sender',
'rec',
'final test',
'final test before commenting')
# Call to send the message created above, again parameters can be read from a file
send_message(creds, 'sender', the_message)
matching_message = ListMessagesMatchingQuery(creds,'sender', query='hello')
content = GetEmailListWithContent(matching_message,creds, 'sender')
# Exporting to CSV, File name can be parametrized
content.to_csv('out0910.csv')
</code></pre>
|
[] |
[
{
"body": "<h2>Variable reuse</h2>\n\n<p>Put</p>\n\n<pre><code>'token.pickle'\n</code></pre>\n\n<p>into a constant variable somewhere.</p>\n\n<h2>Security</h2>\n\n<p>You're using an unencrypted serialized format for credential storage. This is not advisable. There are many (many) ways that this can be done more securely, some of them operating-system-dependent, some of them generic Python packages that you can import - but don't do what you're doing now.</p>\n\n<h2>Legacy libraries</h2>\n\n<p><code>email.mime</code> is a legacy library. Have a read through <a href=\"https://docs.python.org/3.7/library/email.html#module-email\" rel=\"nofollow noreferrer\">https://docs.python.org/3.7/library/email.html#module-email</a> - it will describe the newer methods of email composition and transmission, including <code>email.message</code>.</p>\n\n<h2>Error handling</h2>\n\n<blockquote>\n <p>I would rather log all the errors in staging table or in a file, though it depends on error handling method used</p>\n</blockquote>\n\n<p>Indeed. In that particular case, you should just let the exception fall through (or maybe wrap it in another exception using a <code>from</code> clause). You can catch it in the calling code above, and decide what to do from there. Perhaps investigate the use of the standard <code>logging</code> library, which gives you flexible options around sending log lines to files and/or the console.</p>\n\n<h2>Unguarded code</h2>\n\n<p>As of <code>df = pd.DataFrame()</code> and below, that code is not <code>main</code>-guarded. Tab it in. Also consider putting it in a function to keep it out of global scope. Unlike in C, <code>if</code> blocks do not create inner scope.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-10T00:24:57.933",
"Id": "230459",
"ParentId": "230446",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "230459",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-09T18:17:16.217",
"Id": "230446",
"Score": "5",
"Tags": [
"python",
"python-3.x",
"api",
"pandas",
"email"
],
"Title": "GMAIL API -Create/Send/Search messages for keyword"
}
|
230446
|
<p>I wrote code to plot a rating distribution, which looks like this:</p>
<p><a href="https://i.stack.imgur.com/IJEvP.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/IJEvP.png" alt="enter image description here"></a></p>
<p>The most important function is the <code>stats</code> function:</p>
<pre><code>function stats($songID){
$st=$this->conn->prepare("SELECT
(SELECT COUNT(*) FROM list WHERE SongID=:songID),
(SELECT COUNT(*) FROM list WHERE SongID=:songID AND Rating='10'),
(SELECT COUNT(*) FROM list WHERE SongID=:songID AND Rating='9.5'),
(SELECT COUNT(*) FROM list WHERE SongID=:songID AND Rating='9'),
(SELECT COUNT(*) FROM list WHERE SongID=:songID AND Rating='8.5'),
(SELECT COUNT(*) FROM list WHERE SongID=:songID AND Rating='8'),
(SELECT COUNT(*) FROM list WHERE SongID=:songID AND Rating='7.5'),
(SELECT COUNT(*) FROM list WHERE SongID=:songID AND Rating='7'),
(SELECT COUNT(*) FROM list WHERE SongID=:songID AND Rating='6.5'),
(SELECT COUNT(*) FROM list WHERE SongID=:songID AND Rating='6'),
(SELECT COUNT(*) FROM list WHERE SongID=:songID AND Rating='5.5'),
(SELECT COUNT(*) FROM list WHERE SongID=:songID AND Rating='5'),
(SELECT COUNT(*) FROM list WHERE SongID=:songID AND Rating='4.5'),
(SELECT COUNT(*) FROM list WHERE SongID=:songID AND Rating='4'),
(SELECT COUNT(*) FROM list WHERE SongID=:songID AND Rating='3.5'),
(SELECT COUNT(*) FROM list WHERE SongID=:songID AND Rating='3'),
(SELECT COUNT(*) FROM list WHERE SongID=:songID AND Rating='2.5'),
(SELECT COUNT(*) FROM list WHERE SongID=:songID AND Rating='2'),
(SELECT COUNT(*) FROM list WHERE SongID=:songID AND Rating='1.5'),
(SELECT COUNT(*) FROM list WHERE SongID=:songID AND Rating='1'),
(SELECT COUNT(*) FROM list WHERE SongID=:songID AND Rating='0.5')
FROM list WHERE SongID=:songID");
$st->bindparam(":songID",$songID);
$st->execute();
return $st->fetchall();
}
function bars($rate,$percentage,$ratings){
return <<<HTML
<div class="progress border border-dark w-100 bg-transparent border-0 mt-1">
<span style="width:20px;" class="font-weight-bold text-light">
{$rate}
</span>
<div class="progress-bar border border-dark bg-light" role="progressbar" style="max-width:25%;width:{$percentage}%;" aria-valuenow="{$ratings}" aria-valuemin="0" aria-valuemax="100"></div>
<span class="font-weight-bold text-light ml-1 mr-1">
{$percentage}%({$ratings} votes)
</span>
</div>
HTML;
}
</code></pre>
<p>And then in another file I use these methods:</p>
<pre><code>$stats=$song->stats($_GET['songid']);
foreach($stats as $key){
$total=$key[0];
$rate=10;
for($i=1;$i<21;$i++){
echo $song->bars($rate,round(($key[$i]/$total)*100,2),$key[$i]);
$rate-=0.5;
}
break;
}
</code></pre>
<p>This code works perfectly, but somehow I'm not satisfied with the <code>stats</code> function, the way I solved it. It's just too long, and doesn't look quite good to me.</p>
<p>So the question is: is there a way to make that <code>function</code> a bit shorter, so I wouldn't repeat the same thing 20 times but with different values for the <code>Rating</code> column?</p>
<p>I was thinking that this might actually be the only way to do it, but I thought I'd give it a try here, since there are way smarter programmers here than I am.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-09T18:38:19.380",
"Id": "448895",
"Score": "8",
"body": "Just to make the question clear, please post the schema definition for the `list` table as well."
}
] |
[
{
"body": "<p>It would be better to use GROUP by in your SQL. By this way you will get rid of long SQL query.</p>\n\n<pre><code>SELECT Rating, COUNT(id) FROM list WHERE songID=:songID GROUP BY Rating;\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-09T19:15:18.423",
"Id": "230450",
"ParentId": "230447",
"Score": "6"
}
},
{
"body": "<p>Assuming that you are trying to extract ALL of the rating values from your table, I agree with Unnamed that you should simply GROUP BY and return the <code>Rating</code>, and the <code>COUNT()</code> in the result set.</p>\n\n<p>Two things to add here...</p>\n\n<ol>\n<li><p>Without apply default values, you need to be aware that Unnamed's query will potentially deliver gaps where there is no count for a particular <code>Rating</code> score. To mitigate this, you should <code>array_merge()</code> your own set of defaults (all of the expected Rating scores) and assign them with a zero count or modify your looping process to provide 0 counts for missing Ratings.</p></li>\n<li><p><code>GROUP BY</code> has a cool feature that will provide the grand total for you as well (which seems perfect for your use case and is not included in unnamed's solution)-- <code>ROLL UP</code>: <a href=\"http://www.mysqltutorial.org/mysql-rollup/\" rel=\"nofollow noreferrer\">http://www.mysqltutorial.org/mysql-rollup/</a></p>\n\n<p>This means you can do something like:</p>\n\n<pre><code>function stats($songID){\n $st = $this->conn->prepare(\n \"SELECT COALESCE(Rating, 'Total') Rating, COUNT(1) `Count`\n FROM list\n WHERE songID = ?\n GROUP BY Rating DESC WITH ROLLUP\"\n );\n\n return $st->execute([$songID])->fetchall();\n}\n</code></pre>\n\n<p>Here's a fiddle demo: <a href=\"https://www.db-fiddle.com/f/9WZJwBunnEHjy6MMQGYSbt/4\" rel=\"nofollow noreferrer\">https://www.db-fiddle.com/f/9WZJwBunnEHjy6MMQGYSbt/4</a></p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-10T04:53:08.733",
"Id": "230468",
"ParentId": "230447",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-09T18:27:50.880",
"Id": "230447",
"Score": "4",
"Tags": [
"php",
"mysql",
"statistics",
"pdo",
"data-visualization"
],
"Title": "Query to plot a histogram of song ratings"
}
|
230447
|
<p>I am working on a "comprehensive" library for use in my internal applications and I have created a working method (as far as all of my testing has shown thus far) to ensure that a file/directory path is - or, at least, <em>could</em> be - legitimate and <em>should</em> be accessible to any user of the same application. <strong><em>NOTE:</strong> These are all internal systems not intended for public use or consumption.</em></p>
<p>I've tried to pull together bits of information/code I've found that address certain aspects of the issue into a "single" method, part of which involves converting an individual user's mapped drives to full UNC paths (<code>U:\PublicFolder\SomeFile.txt</code> becomes <code>\\SERVERNAME\Share\PublicFolder\SomeFile.txt</code>). On the other hand, if the drive is a local, physical drive on the user's machine, I <em>don't</em> want to convert that to UNC (<code>\\COMPUTERNAME\C$\SomeFolder\SomeFile.txt</code>), but instead retain the absolute path to the local drive (<code>C:\SomeFolder\SomeFile.txt</code>) to prevent issues with access privileges. This is what I've come up with, but I'm wondering if this code is a bit too ambitious or overly contrived.</p>
<pre class="lang-vb prettyprint-override"><code>Public Enum PathType
File
Directory
End Enum
Public Shared Function GetRealPath(ByVal file As IO.FileInfo) As String
Return GetRealPath(file.FullName, PathType.File)
End Function
Public Shared Function GetRealPath(ByVal folder As IO.DirectoryInfo) As String
Return GetRealPath(folder.FullName, PathType.Directory)
End Function
Public Shared Function GetRealPath(ByVal filePath As String, ByVal pathType As PathType) As String
Dim FullPath As String = String.Empty
If filePath Is Nothing OrElse String.IsNullOrEmpty(filePath) Then
Throw New ArgumentNullException("No path specified")
Else
If filePath.IndexOfAny(IO.Path.GetInvalidPathChars) >= 0 Then
Throw New ArgumentException("The specified path '" & filePath & "' is invalid")
Else
If pathType = PathType.File Then
Try
Dim TempFile As New IO.FileInfo(filePath)
If TempFile.Name.IndexOfAny(Path.GetInvalidFileNameChars) >= 0 Then
Throw New ArgumentException("The specified file name '" & filePath & "' is invalid")
End If
TempFile = Nothing
Catch ex As Exception
Throw New ArgumentException("The specified file name '" & filePath & "' is invalid", ex)
End Try
End If
' The path should not contain any invalid characters. Start trying to populate the FullPath variable.
If IO.Path.IsPathRooted(filePath) Then
FullPath = filePath
Else
Try
FullPath = IO.Path.GetFullPath(filePath)
Catch ex As Exception
Throw New ArgumentException("The specified path '" & filePath & "' is invalid", ex)
End Try
End If
If Not FullPath.StartsWith("\\") Then
Dim PathRoot As String = IO.Path.GetPathRoot(FullPath)
If PathRoot Is Nothing OrElse String.IsNullOrEmpty(PathRoot) Then
FullPath = String.Empty
Throw New ArgumentException("The specified path '" & filePath & "' is invalid")
Else
If Not IO.Directory.GetLogicalDrives.Contains(PathRoot) Then
FullPath = String.Empty
Throw New ArgumentException("The specified path '" & filePath & "' is invalid. Drive '" & PathRoot & "' does not exist.")
Else
Dim CurrentDrive As New System.IO.DriveInfo(PathRoot)
If CurrentDrive.DriveType = DriveType.Network Then
Using HKCU As Microsoft.Win32.RegistryKey = Microsoft.Win32.Registry.CurrentUser.OpenSubKey("Network\" & FullPath(0))
If Not HKCU Is Nothing Then
FullPath = HKCU.GetValue("RemotePath").ToString() & FullPath.Remove(0, 2).ToString()
End If
End Using
ElseIf Not CurrentDrive.DriveType = DriveType.NoRootDirectory AndAlso Not CurrentDrive.DriveType = DriveType.Unknown Then
Dim SubstPath As String = String.Empty
If IsSubstPath(FullPath, SubstPath) Then
FullPath = SubstPath
End If
Else
FullPath = String.Empty
Throw New ArgumentException("The specified path '" & filePath & "' is invalid. Drive '" & CurrentDrive.Name & "' does not exist.")
End If
End If
End If
End If
End If
End If
Return FullPath
End Function
<DllImport("kernel32.dll", SetLastError:=True)>
Private Shared Function QueryDosDevice(ByVal lpDeviceName As String, ByVal lpTargetPath As System.Text.StringBuilder, ByVal ucchMax As Integer) As UInteger
End Function
Private Shared Function IsSubstPath(ByVal pathToTest As String, <Out> ByRef realPath As String) As Boolean
Dim PathInformation As System.Text.StringBuilder = New System.Text.StringBuilder(250)
Dim DriveLetter As String = Nothing
Dim WinApiResult As UInteger = 0
realPath = Nothing
Try
' Get the drive letter of the path
DriveLetter = IO.Path.GetPathRoot(pathToTest).Replace("\", "")
Catch ex As ArgumentException
Return False
End Try
WinApiResult = QueryDosDevice(DriveLetter, PathInformation, 250)
If WinApiResult = 0 Then
' For debugging
Dim LastWinError As Integer = Marshal.GetLastWin32Error()
Return False
End If
' If drive is SUBST'ed, the result will be in the format of "\??\C:\RealPath\".
If PathInformation.ToString().StartsWith("\??\") Then
Dim RealRoot As String = PathInformation.ToString().Remove(0, 4)
RealRoot += If(PathInformation.ToString().EndsWith("\"), "", "\")
realPath = IO.Path.Combine(RealRoot, pathToTest.Replace(IO.Path.GetPathRoot(pathToTest), ""))
Return True
End If
realPath = pathToTest
Return False
End Function
</code></pre>
<hr>
<h2>TESTING DONE</h2>
<p>I've run this through a few different tests, although I'm certain I've not been exhaustive in coming up with ways to make it break. Here are the details I can remember:</p>
<p><strong>On my computer, drive <code>S:</code> is mapped to <code>\\SERVERNAME\Accounts\</code></strong></p>
<p>I've declared the following variables for use during my testing.</p>
<pre class="lang-vb prettyprint-override"><code>Dim TestFile As IO.FileInfo
Dim TestFolder As IO.DirectoryInfo
Dim Path As String
</code></pre>
<hr>
<h3>INDIVIDUAL TESTS/RESULTS</h3>
<hr>
<pre class="lang-vb prettyprint-override"><code>' Existing Directory
TestFolder = New IO.DirectoryInfo("S:\EXE\0984\")
Path = Common.Utility.GetRealPath(TestFolder)
</code></pre>
<p>Correctly returns <code>\\SERVERNAME\Accounts\EXE\0984\</code></p>
<hr>
<pre class="lang-vb prettyprint-override"><code>' Existing File
TestFile = New IO.FileInfo("S:\EXE\0984\CPI.txt")
Path = Common.Utility.GetRealPath(TestFile)
</code></pre>
<p>Correctly returns <code>\\SERVERNAME\Accounts\EXE\0984\CPI.txt</code></p>
<hr>
<pre class="lang-vb prettyprint-override"><code>' Not actually a file, but it should return the UNC path
TestFile = New IO.FileInfo("S:\EXE\0984")
Path = Common.Utility.GetRealPath(TestFile)
</code></pre>
<p>Correctly returns <code>\\SERVERNAME\Accounts\EXE\0984</code></p>
<hr>
<pre class="lang-vb prettyprint-override"><code>' Directory does not exist, but it should return the absolute path
TestFolder = New IO.DirectoryInfo("C:\EXE\0984\")
Path = Common.Utility.GetRealPath(TestFolder)
</code></pre>
<p>Correctly returns <code>C:\EXE\0984\</code></p>
<hr>
<pre class="lang-vb prettyprint-override"><code>' Random String
TestFile = New IO.FileInfo("Can I make it break?")
</code></pre>
<p>Throws an immediate exception before getting to the <code>GetRealPath()</code> method due to illegal characters in the path (<code>?</code>)</p>
<hr>
<pre class="lang-vb prettyprint-override"><code>' Random String
Path = Common.Utility.GetRealPath("Can I make it break?", Common.Utility.PathType.File)
</code></pre>
<p>Throws exception from inside the <code>GetRealPath()</code> method when attempting to convert the <code>String</code> value to an <code>IO.FileInfo</code> object (<em>line 29 in the method's code posted above</em>) due to illegal characters in the path (<code>?</code>)</p>
<hr>
<pre class="lang-vb prettyprint-override"><code>' Random String
Path = Common.Utility.GetRealPath("Can I make it break?", Common.Utility.PathType.Directory)
</code></pre>
<p>Throws exception from inside the <code>GetRealPath()</code> method when attempting to call <code>IO.Path.GetFullPath()</code> on the <code>String</code> value (<em>line 46 in the method's code posted above</em>) due to illegal characters in the path (<code>?</code>)</p>
<hr>
<pre class="lang-vb prettyprint-override"><code>' Random String
Path = Common.Utility.GetRealPath("Can I make it break", Common.Utility.PathType.Directory)
' AND
Path = Common.Utility.GetRealPath("Can I make it break", Common.Utility.PathType.File)
</code></pre>
<p>"Correctly" returns the path to a subfolder of the <code>Debug</code> folder of my project:
<code>D:\Programming\TestApp\bin\Debug\Can I make it break</code></p>
<p>I'm not 100% certain that's the behavior I want, but it's <em>technically</em> correct, and it makes sense for situations where relative paths can come into play. </p>
<hr>
<p><em>Heck, the act of posting these examples has already started answering a few questions in my own head and helped me to think through this a bit better.</em></p>
<p>Admittedly, I've thus far been unable to fully test the <code>SUBST</code> conditions because I don't have any drives that have been <code>SUBST</code>ed and I've been unable thus far to successfully <code>SUBST</code> a path that shows up as a valid drive on my Windows 10 machine.</p>
<hr>
<h2>EDIT</h2>
<p>I've successfully tested the <code>SUBST</code> condition on my local machine (<em>see how my ignorance and "over-confidence" caused me some grief in <a href="https://stackoverflow.com/questions/58345316/drive-created-by-subst-windows-10-not-reporting-full-path-to-querydosdevice">my question on SO</a></em>). It looks like this is all working correctly, even though, in the end, I may choose to make a few minor modifications, including:</p>
<ul>
<li>I may have to add a parameter to define whether or not I want to allow relative paths to be expanded, and/or possibly check for an appropriate character sequence (<code>./</code>, <code>/</code>, <code>..</code>, etc.) at the start of the string before "approving" the return value. Otherwise, pretty much <em>any</em> string value passed in could potentially result in a "legitimate" path. </li>
<li>I've been strongly considering making the "workhorse" overload (<code>GetRealPath(String, PathType)</code>) a <code>Private</code> method (along with the <code>PathType</code> <code>Enum</code>) to allow the validation intrinsic to the <code>IO.FileInfo</code> and <code>IO.DirectoryInfo</code> objects help prevent some of the "unexpected" or "unintended" results from allowing any random <code>String</code> input, such as in the last example.</li>
</ul>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-09T19:37:11.170",
"Id": "448911",
"Score": "2",
"body": "If you wouldn't mind, please explain the downvote. If this question is not appropriate for this site in some way, I will gladly delete it. I'm honestly just looking for some insight from those more experienced than myself."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-09T19:52:19.223",
"Id": "448914",
"Score": "1",
"body": "You tell us _I have created a working method (as far as all of my testing has shown thus far)_: do you mind sharing these tests with us? Also, since you have a lot of edge cases, it's imperative you document the function to show consumers the specification."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-09T19:55:42.590",
"Id": "448915",
"Score": "0",
"body": "I'll happily edit in some test/result information as far as I'm able to remember it. I haven't explicitly kept those tests, so I may have to \"fudge\" (and, of course, obfuscate) a little."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-09T21:03:09.953",
"Id": "448925",
"Score": "1",
"body": "@dfhwze - Thank you for asking for the examples of testing. I've edited some into the question and, in so doing, I've already found some places where I can do better, as well as \"remembered\" some issues I had forgotten I wanted to address."
}
] |
[
{
"body": "<p>Focusing only on <code>GetRealPath</code></p>\n\n<ul>\n<li>You can save some level of indentation by returning early. The code would become easier to read. </li>\n<li>The check <code>If TempFile.Name.IndexOfAny(Path.GetInvalidFileNameChars) >= 0 Then</code> is superflous because the constructor of <code>FileInfo</code> throws an <code>ArgumentException</code> if there are any invalid chars in the filename.</li>\n<li><code>FileInfo</code> doesn't hold unmanaged ressources hence you don't need to set it to <code>Nothing</code>.</li>\n<li>It is always better to catch specific exceptions. </li>\n<li>Throwing an Exception inside a <code>If</code> block makes the <code>Else</code> redundant. </li>\n<li>Checking if a string <code>Is Nothing OrElse IsNullOrEmpty</code> can be replaced by just the call to <code>IsNullOrEmpty</code>. </li>\n<li>You don't need to set <code>FullPath = String.Empty</code> if at the next line of code you are throwing an exception. </li>\n<li>Althought VB.NET is case insensitiv you should name your variables using <code>camelCase</code> casing.</li>\n</ul>\n\n<p>Summing up the mentioned changes (except for the specific exception part) will look like so </p>\n\n<pre><code>Public Shared Function GetRealPath(ByVal filePath As String, ByVal pathType As PathType) As String\n Dim fullPath As String = String.Empty\n\n If String.IsNullOrEmpty(filePath) Then\n Throw New ArgumentNullException(\"No path specified\")\n End If\n If filePath.IndexOfAny(IO.Path.GetInvalidPathChars) >= 0 Then\n Throw New ArgumentException(\"The specified path '\" & filePath & \"' is invalid\")\n End If\n\n If pathType = PathType.File Then\n Try\n Dim tempFile As New IO.FileInfo(filePath)\n Catch ex As Exception\n Throw New ArgumentException(\"The specified file name '\" & filePath & \"' is invalid\", ex)\n End Try\n End If\n\n ' The path should not contain any invalid characters. Start trying to populate the FullPath variable.\n If IO.Path.IsPathRooted(filePath) Then\n fullPath = filePath\n Else\n Try\n fullPath = IO.Path.GetFullPath(filePath)\n Catch ex As Exception\n Throw New ArgumentException(\"The specified path '\" & filePath & \"' is invalid\", ex)\n End Try\n End If\n\n If fullPath.StartsWith(\"\\\\\") Then\n Return fullPath\n End If\n\n Dim pathRoot As String = IO.Path.GetPathRoot(fullPath)\n\n If String.IsNullOrEmpty(pathRoot) Then\n Throw New ArgumentException(\"The specified path '\" & filePath & \"' is invalid\")\n End If\n\n If Not IO.Directory.GetLogicalDrives.Contains(pathRoot) Then\n Throw New ArgumentException(\"The specified path '\" & filePath & \"' is invalid. Drive '\" & pathRoot & \"' does not exist.\")\n End If\n\n Dim currentDrive As New System.IO.DriveInfo(pathRoot)\n\n If currentDrive.DriveType = DriveType.Network Then\n Using HKCU As Microsoft.Win32.RegistryKey = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(\"Network\\\" & fullPath(0))\n If Not HKCU Is Nothing Then\n fullPath = HKCU.GetValue(\"RemotePath\").ToString() & fullPath.Remove(0, 2).ToString()\n End If\n End Using\n ElseIf Not currentDrive.DriveType = DriveType.NoRootDirectory AndAlso Not currentDrive.DriveType = DriveType.Unknown Then\n Dim SubstPath As String = String.Empty\n\n If IsSubstPath(fullPath, SubstPath) Then\n fullPath = SubstPath\n End If\n Else\n Throw New ArgumentException(\"The specified path '\" & filePath & \"' is invalid. Drive '\" & currentDrive.Name & \"' does not exist.\")\n End If\n\n Return fullPath\nEnd Function\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-21T06:29:27.307",
"Id": "231077",
"ParentId": "230451",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-09T19:23:05.537",
"Id": "230451",
"Score": "2",
"Tags": [
"validation",
"file-system",
"api",
"vb.net"
],
"Title": "Validate (Possible) File/Directory Path"
}
|
230451
|
<p>I am interested in hearing your opinion on the approach I have taken to have inherited classes initialize their base class.</p>
<p>Here's a Machines collection class from that maintains a list of Machine objects. Each Machine needs to be able to inform its parent, using a delegate, of something they do but they do not have a reference to the parent:</p>
<pre><code>Public Delegate Sub MachineDelegate(ByRef item As Machine)
Public MustInherit Class Machines
Private _items As New List(Of Machine)
Public Function Create() As Machine
Dim item As Machine = CreateItem()
_items.Add(item)
PostCreationHandler(item)
Return item
End Function
' Create derived object
Public MustOverride Function CreateItem() As Machine
Public Sub ChildMachineDidSomething(ByRef item As Machine)
' Handle child object event
Debug.Print("Machine did something")
End Sub
' Called once object has been created
Protected Overridable Sub PostCreationHandler(ByRef item As Machine)
item.MachineDelegate = AddressOf ChildMachineDidSomething
End Sub
End Class
Public Class Machine
Public MachineDelegate As MachineDelegate
Public Sub DoMachineThing()
If Not MachineDelegate Is Nothing Then MachineDelegate(Me)
End Sub
End Class
</code></pre>
<p>The child objects will use a <code>MachineDelegate</code> to inform their parent, passing themselves as a reference.</p>
<p>Inherited Cars and Car classes would look like this and have their own delegate to handle Car-related notifications:</p>
<pre><code>Public Delegate Sub CarDelegate(ByRef item As Car)
Public Class Cars
Inherits Machines
' Create derived object
Public Overrides Function CreateItem() As Machine
Dim item As Car = New Car
CreateItem = item
End Function
Public Sub ChildCarDidSomething(ByRef item As Car)
' Handle child object event
Debug.Print("Car did something")
End Sub
' Called once object has been created
Protected Overrides Sub PostCreationHandler(ByRef item As Machine)
Dim car As Car = item
MyBase.PostCreationHandler(item)
car.CarDelegate = AddressOf ChildCarDidSomething
End Sub
End Class
Public Class Car
Inherits Machine
Public CarDelegate As CarDelegate
Public Sub DoCarThing()
If Not CarDelegate Is Nothing Then CarDelegate(Me)
End Sub
End Class
</code></pre>
<p>I create an overridable <code>PostCreationHandler</code> where object-specific initialization is to be handled once an object is created and I am using <code>MyBase.PostCreationHandler</code> to make sure the object gets properly initialized at every level in the inheritance chain.</p>
<p>My goal is to avoid giving child objects a reference to their parent.</p>
<p>My question is is this OK and is there a better approach to doing this?</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-09T19:30:02.937",
"Id": "230453",
"Score": "2",
"Tags": [
"vb.net",
"inheritance",
"delegates"
],
"Title": "Inherited class calls initialization code in base class"
}
|
230453
|
<p>I have this code below that copies data into a master workbook, in sheets "Inputs1", by matching the column headers from the master workbook with the source workbook. If a column header matches, it will copy and paste that column to the related column in the master workbook.</p>
<p>The macro works great for smaller files, but once I run it on larger files it takes almost 2 minutes to run. I also noticed it runs slower when called from a userform instead of from the developer tab directly.</p>
<p>How can I improve this code to run more efficiently and quickly? I still get page flickers too.</p>
<pre><code>Sub Import()
Application.ScreenUpdating = False
EventState = Application.EnableEvents
Application.EnableEvents = False
CalcState = Application.Calculation
Application.Calculation = xlCalculationManual
PageBreakState = ActiveSheet.DisplayPageBreaks
ActiveSheet.DisplayPageBreaks = False
Dim wbSource As Workbook
Dim wbDest As Workbook
Dim TargetSheet As Worksheet
Dim c As Range
Dim rng As Range
Dim i As Integer
Dim MyRange As Range
Dim SourceSheet As Worksheet
Dim source As String
Dim dest As String
Dim r As Range
Dim msg As String
'Source and destination workbooks defined by cell value
source = Worksheets("Set-Up").Range("B11")
dest = Worksheets("Set-Up").Range("B8")
Set wbSource = Workbooks(source)
Set SourceSheet = wbSource.Worksheets("HFL01 Extract")
Set wbDest = Workbooks(dest)
Set TargetSheet = wbDest.Worksheets("INPUTS1")
With SourceSheet.Range("A1").CurrentRegion
For Each r In TargetSheet.Range("A1:cc1")
Set c = .Rows(1).Find(r.Value, , , xlWhole, , 0)
If Not c Is Nothing Then
.Columns(c.Column).Copy
r.PasteSpecial xlPasteValues
End If
Next
Application.CutCopyMode = False
End With
Set fileDialog = Nothing
Set wbSource = Nothing
End Sub
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-14T23:06:34.170",
"Id": "449709",
"Score": "0",
"body": "You are copying entire columns, this will slow down your code. Try only copying the range. Test that for speed. Also test if copying your data into an array will help the speed. I regulary deal with 100,000+ lines in excel and my macros take mere seconds.."
}
] |
[
{
"body": "<p>Copying and pasting isn't necessary and interferes with the user's paste cache. Clear the target column of data and then set a range in the target the same size as the source. Then use an assignment statement:</p>\n\n<pre><code>TargetRange.Value = SourceRange.Value\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-26T14:22:37.353",
"Id": "231341",
"ParentId": "230455",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-09T21:50:39.390",
"Id": "230455",
"Score": "4",
"Tags": [
"vba",
"excel"
],
"Title": "Excel Import Data from Different Workbook Dynamic Headers"
}
|
230455
|
<p>We had a little bit of fun in the 2nd Monitor this morning, one user greeted another with a hex string. It turned out that the user being greeted deals with Hex Dumps enough that they were able to read the string, but I wasn't so I created this converter.</p>
<p>What could I have done to reduce the dependency on <code>cstring</code>?</p>
<p>How could I have made this more C++17 and less C Programming language.</p>
<pre><code>#include <iostream>
#include <vector>
#include <string>
#include <cstdlib>
#include <cstring>
class HexStringToAsciiStringConverter
{
std::vector<unsigned> HexValues;
const char* Remove0x(const char* hxv)
{
if (std::strstr(hxv, "0x") == hxv)
{
hxv += 2;
}
return hxv;
}
void ConvertStringToUnsigned(std::string HexStringToConvert)
{
const char *hxv = Remove0x(HexStringToConvert.c_str());
while (*hxv && *(hxv+1))
{
char hxva[3] = {'\0'};
std::strncpy(hxva, hxv, 2);
HexValues.push_back(std::strtol(hxva, nullptr, 16));
hxv += 2;
}
}
public:
HexStringToAsciiStringConverter::HexStringToAsciiStringConverter(std::string Original)
{
ConvertStringToUnsigned(Original);
}
std::string HexStringToAsciiStringConverter::ConvertHexToString()
{
std::vector<unsigned char> tmpcarray;
for (auto HexValue: HexValues)
{
tmpcarray.push_back(HexValue);
}
std::string output(tmpcarray.begin(), tmpcarray.end());
return output;
}
};
int main() {
std::string Original = "0x486920446f6e2c20686f7727732073706163653f";
HexStringToAsciiStringConverter Converter(Original);
std::cout << Converter.ConvertHexToString() << std::endl;
return EXIT_SUCCESS;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-10T09:49:52.570",
"Id": "449017",
"Score": "1",
"body": "It's only ASCII if that's the native encoding on your system. It would be better named as a \"hex to _raw text_ convertor\"."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-10T15:01:36.057",
"Id": "449057",
"Score": "0",
"body": "@TobySpeight Thank you for pointing that out."
}
] |
[
{
"body": "<p>I'm surprised that, according to your code, C++ doesn't have a <code>strip_prefix</code> or <code>without_beginning</code> or <code>skip_start</code> function to skip over the initial <code>\"0x\"</code>. If there were one, you should definitely use that instead of implementing your own. Do a little search, I'm sure such a function exists.</p>\n\n<p>Even though this is C++, there is no need to write a <code>class</code> for a simple conversion function like this. In my experience, this task can be solved in less than 20 lines of code, and there is no state that you need to save between method calls, therefore a class is unnecessary. Just write an ordinary <code>std::string hex_to_bytes(const std::string_view &hex)</code> function.</p>\n\n<p>As far as I remember, <code>std::string</code> has a <code>push_back</code> method, therefore there's no need to use an intermediate vector for building up the string.</p>\n\n<p>My rough idea is:</p>\n\n<pre class=\"lang-cpp prettyprint-override\"><code>std::string hex_to_bytes(const std::string_view &hex) {\n std::size_t i = 0, size = hex.size();\n if (size >= 2 && hex[0] == '0' && hex[1] == 'x')\n i += 2;\n\n std::string result;\n for (; i + 1 < size; i += 2) {\n char octet_chars[] = { hex[i], hex[i + 1], '\\0' };\n\n char *end;\n unsigned long octet = std::strtoul(octet_chars, &end, 16);\n if (end != octet_chars + 2)\n throw std::some_exception();\n\n result.push_back(static_cast<char>(octet));\n }\n\n if (i != size)\n throw std::some_exception();\n\n return result;\n}\n</code></pre>\n\n<p>I didn't test the above code.\nIt also doesn't look very C++-like to me because it accesses the character array directly. But probably, for this kind of functions, there is no high-level way of expressing the code.</p>\n\n<hr>\n\n<p>By the way, instead of writing all this code, you could also write a Perl one-liner:</p>\n\n<pre><code>perl -pe '$_ = pack(\"H*\", $1) if /([0-9a-f]+)/i'\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-10T14:59:21.040",
"Id": "449055",
"Score": "0",
"body": "I created a class because I plan to embed it in a tool later, however, the class will have to be able to go both ways so it will probably be renamed."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-10T04:03:25.877",
"Id": "230463",
"ParentId": "230458",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "230463",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-09T23:51:09.403",
"Id": "230458",
"Score": "6",
"Tags": [
"c++",
"converting",
"c++17"
],
"Title": "Convert a Hex value string to an ASCII Text String"
}
|
230458
|
<p>In the past three days, I've been developing a simple raycasting algorithm. I've made the renderer work as I'd like to. However, it is extremely slow (5 frames per second) because of two things (as far as I know).</p>
<ol>
<li>Finding the values of a pixel independently many times, and often it lands on the same pixel.</li>
<li>The large amount of times the code is run.</li>
</ol>
<p>I'm aiming for speed but the only programming language I have experience in is Python. What are the optimizations I can make to this code? Which other libraries can I use that are faster than Pygame or PIL for this use?
Also, how do I make the pixel coordinates loop (-1 = 1023) without if statements to prevent the game crashing if near the boundary?</p>
<pre><code>from PIL import Image
import pygame
cdef enum resolution:
resX=720
resY=540
qresX=180
cdef extern from "math.h":
double sin(double x)
double cos(double x)
screen = pygame.display.set_mode((resX,resY))
pygame.display.set_caption('VoxelSpace')
im=Image.open("data/height.png")
disp=im.load()
col = Image.open("data/colour.png")
rgb_im = col.convert('RGB')
rgb=rgb_im.load()
cdef unsigned char uu
cdef unsigned char height
cdef unsigned char prevHeight
cdef unsigned char heightBuffer
cdef float t
cdef float foga
cdef unsigned char fogb
cdef int x
cdef int y
cdef unsigned char r
cdef unsigned char g
cdef unsigned char b
cdef int pX
cdef int pY
cdef float pAngle
cdef unsigned char u
cdef int v
cdef unsigned char h
def Render(pX,pY,pAngle):
screen.fill((100,100,255))
heightBuffer=disp[pX,pY]
for v from -qresX <= v < qresX by 1:
prevHeight=0
for u from 1 <= u < 124 by 1:
if u<30:
uu=u
elif u<60:
uu=u*2-45
else:
uu=u*4-180
foga=u/60.0+1
fogb=u/2
t=v/float(qresX)+pAngle
x=int(sin(t)*-uu+pX)
y=int(cos(t)*-uu+pY)
height=(float(disp[x,y]-heightBuffer-10)/uu*101+135)*2
if height>prevHeight:
r,g,b=rgb[x,y]
pygame.draw.line(screen,(r/foga+fogb,g/foga+fogb,b/foga+u) , (2*(qresX+v),resY-prevHeight),(2*(qresX+v),resY-height),2)
prevHeight=height
pygame.display.flip()
</code></pre>
<p>I am compiling this code as a <code>.so</code> (via cython) and running it from another <code>.py</code>. Is it faster if I simply use PyPy instead?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-10T02:05:40.947",
"Id": "448940",
"Score": "0",
"body": "`cdef` is exotic and fragile. At this point, why aren't you just using C?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-10T02:12:12.407",
"Id": "448941",
"Score": "1",
"body": "Because I have no knowledge in C"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-10T02:13:48.077",
"Id": "448942",
"Score": "1",
"body": "Perhaps it's time to learn :) it'll buy you a lot more efficiency, at the cost of more awkward libraries."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-10T07:22:19.493",
"Id": "448990",
"Score": "1",
"body": "@Reinderien Let's be honest, C is a programming language for masochists ;-) A little bit awkward, and lots of opportunities to hurt yourself."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-11T12:01:33.473",
"Id": "449205",
"Score": "0",
"body": "I would suggest to either rewrite the for loops for the cython memoryview or to move the rendering to the GPU. There are a lot of different libraries for this, there is one that is compatible with pygame called `moderngl`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-11T17:04:39.923",
"Id": "449250",
"Score": "0",
"body": "There is plenty of room for improving performance from within cython based on the code you have posted. I will write up a more detailed answer, but even adding cdef types to your counter loop variables should help immensely."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-12T15:24:05.863",
"Id": "449378",
"Score": "0",
"body": "Do you have any example `height.png` and `colour.png` images that we can test with? Those would be helpful."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-13T07:31:59.613",
"Id": "449458",
"Score": "1",
"body": "You can find them on this website: https://github.com/s-macke/VoxelSpace\nScroll down until you find the MAPS section, and you can download heightmaps there"
}
] |
[
{
"body": "<p>Below is the code I have come up with. It basically follows the code used for the <a href=\"https://s-macke.github.io/VoxelSpace/VoxelSpace.html\" rel=\"nofollow noreferrer\">web demo</a> in the github repo you had linked to. I will add some explanation to this answer on how I had made some basic optimizations to better fit cython's memoryview model as well as potential room for improvement later, but figured I should post the code now as it might be another few days before I can get back to it.</p>\n\n<pre><code>cimport libc.math as c_math\nfrom libc.stdint cimport *\nimport math\nimport numpy as np\nfrom PIL import Image\n\nimport os\nos.environ['PYGAME_HIDE_SUPPORT_PROMPT'] = \"hide\"\nimport pygame\nimport sys\nimport time\n\nctypedef struct Point:\n float x\n float y\n\nctypedef struct Color:\n uint8_t r\n uint8_t g\n uint8_t b\n\ncdef class Camera:\n cdef:\n public int x\n public int y\n public int height\n public int angle\n public int horizon\n public int distance\n\n def __init__(self, int x, int y, int height, int angle, int horizon, int distance):\n self.x = x\n self.y = y\n self.height = height\n self.angle = angle\n self.horizon = horizon\n self.distance = distance\n\ncdef class Map:\n cdef:\n int width\n int height\n int shift\n const uint8_t[:, :, :] color_data\n const uint8_t[:, :] height_data\n\n def __init__(self, int width=1024, int height=1024, int shift=10):\n self.width = width\n self.height = height\n self.shift = shift\n self.color_data = None\n self.height_data = None\n\n def load_color_data(self, str color_path):\n cdef object image\n image = Image.open(color_path).convert(\"RGB\")\n self.color_data = np.asarray(image)\n\n def load_height_data(self, str height_path):\n cdef object image\n image = Image.open(height_path).convert(\"L\")\n self.height_data = np.asarray(image)\n\ncdef class Window:\n cdef:\n int width\n int height\n str title\n object screen\n object clock\n int32_t[:] hidden_y\n uint8_t[:, :, :] output\n Color background_color\n Camera camera\n Map map\n\n def __init__(self, int width, int height, str title):\n self.width = width\n self.height = height\n self.screen = pygame.display.set_mode((self.width, self.height))\n self.title = title\n pygame.display.set_caption(self.title)\n self.hidden_y = np.zeros(self.width, dtype=np.int32)\n self.output = np.zeros((self.width, self.height, 3), dtype=np.uint8)\n self.clock = pygame.time.Clock()\n\n def set_background_color(self, uint8_t r, uint8_t g, uint8_t b):\n self.background_color.r = r\n self.background_color.g = g\n self.background_color.b = b\n\n def set_camera(self, Camera camera):\n self.camera = camera\n\n def set_map(self, Map map):\n self.map = map\n\n cdef void draw_background(self):\n cdef int x, y\n for x in range(self.width):\n for y in range(self.height):\n self.output[x, y, 0] = self.background_color.r\n self.output[x, y, 1] = self.background_color.g\n self.output[x, y, 2] = self.background_color.b\n\n cdef void draw_vertical_line(self, int x, int y_top, int y_bottom, Color *color):\n cdef int y\n\n if y_top < 0:\n y_top = 0\n if y_top > y_bottom:\n return\n for y in range(y_top, y_bottom):\n self.output[x, y, 0] = color.r\n self.output[x, y, 1] = color.g\n self.output[x, y, 2] = color.b\n\n cdef display(self):\n surf = pygame.surfarray.make_surface(np.asarray(self.output))\n self.screen.blit(surf, (0, 0))\n pygame.display.flip()\n pygame.display.set_caption(\"{0}: {1} fps\".format(self.title, <int>self.clock.get_fps()))\n\n def render(self):\n cdef:\n int map_width_period = self.map.width - 1\n int map_height_period = self.map.height - 1\n float s = c_math.sin(self.camera.angle)\n float c = c_math.cos(self.camera.angle)\n\n float z = 1.0\n float delta_z = 1.0\n float inv_z\n Point left, right, delta\n int i\n int map_x\n int map_y\n int height_on_screen\n Color color\n\n for i in range(self.width):\n self.hidden_y[i] = self.height\n self.draw_background()\n while z < self.camera.distance:\n left = Point(\n (-c * z) - (s * z), \n (s * z) - (c * z),\n )\n right = Point(\n (c * z) - (s * z), \n (-s * z) - (c * z),\n )\n delta = Point(\n (right.x - left.x) / self.width,\n (right.y - left.y) / self.width,\n )\n left.x += self.camera.x\n left.y += self.camera.y\n\n inv_z = 1.0 / z * 240\n for i in range(self.width):\n map_x = <int>c_math.floor(left.x) & map_height_period\n map_y = <int>c_math.floor(left.y) & map_width_period\n height_on_screen = <int>((self.camera.height - self.map.height_data[map_x, map_y]) * inv_z + self.camera.horizon)\n color.r = self.map.color_data[map_x, map_y, 0]\n color.g = self.map.color_data[map_x, map_y, 1]\n color.b = self.map.color_data[map_x, map_y, 2]\n\n self.draw_vertical_line(i, height_on_screen, self.hidden_y[i], &color)\n if height_on_screen < self.hidden_y[i]:\n self.hidden_y[i] = height_on_screen\n left.x += delta.x\n left.y += delta.y\n\n delta_z += 0.005\n z += delta_z\n\n self.display()\n self.clock.tick(60)#60 fps\n\npygame.init()\n\nwindow = Window(width=800, height=600, title=\"VoxelSpace\")\nwindow.set_background_color(144, 144, 224)\n\nmap = Map()\nmap.load_color_data(\"./images/C1W.png\")\nmap.load_height_data(\"./images/D1.png\")\nwindow.set_map(map)\n\ncamera = Camera(x=512, y=800, height=78, angle=0, horizon=100, distance=800)\nwindow.set_camera(camera)\n\nwhile True:\n #win.handle_input()\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n pygame.quit()\n sys.exit()\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_UP:\n print(\"up\")\n\n camera.y -= 1\n window.render()\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-16T05:05:47.090",
"Id": "230802",
"ParentId": "230462",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-10T01:45:11.433",
"Id": "230462",
"Score": "6",
"Tags": [
"python",
"performance",
"beginner",
"pygame",
"cython"
],
"Title": "Optimizing a raycasting/voxelspace algorithm in Pygame"
}
|
230462
|
<blockquote>
<p>Given a string, return the sum of all the numbers in the string, 0 if none are present.</p>
</blockquote>
<p>Below is my solution for the problem above. I feel like this can be turned into one line. I would really only like suggestions on the actual algorithm, but anything else is appreciated.</p>
<pre><code>def sum_numbers(string: str) -> int:
"""
Returns the sum of all the numbers in the string
"""
num_sum = 0
for char in string:
if char.isnumeric():
num_sum += int(char)
return num_sum
if __name__ == '__main__':
# Test Cases #
assert sum_numbers("123") == 6
assert sum_numbers("abc") == 0
assert sum_numbers("4x7") == 11
assert sum_numbers("wefbyug87iqu") == 15
assert sum_numbers("123456789") == 45
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-10T20:55:37.443",
"Id": "449142",
"Score": "0",
"body": "@Downvoter, please explain what drew the downvote so I can fix it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-10T21:02:45.730",
"Id": "449143",
"Score": "2",
"body": "I feel like a better title would be \"Sum of all digits in a string.\" Digits imply \"abc10def10\" is 2, numbers implies 20."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-10T22:47:18.717",
"Id": "449152",
"Score": "0",
"body": "@rrauenza That would make more sense. Title changed accordingly."
}
] |
[
{
"body": "<p>You're right, it can be turned into one line using comprehension syntax which would be your best option of you're looking for a slightly more efficient code.</p>\n\n<ul>\n<li><code>isdecimal()</code> is better to use in this case than <code>isnumeric()</code> because the <code>isnumeric()</code> accepts types like ½ and ¼ and n² which might produce some side effects you don't want if you're using this function for some real application. Apart from this the code looks good, can be improved using the comprehension syntax which is more efficient and shorter.</li>\n</ul>\n\n<p><strong>Improved version:</strong></p>\n\n<pre><code>def sum_digits(chars: str) -> int:\n \"\"\"Return sum of numbers in chars\"\"\"\n return sum(int(char) for char in chars if char.isdecimal())\n\n\nif __name__ == '__main__':\n print(sum_digits('abcd173fg'))\n print(sum_digits('abcd'))\n print(sum_digits('173678'))\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-10T05:08:48.983",
"Id": "448956",
"Score": "0",
"body": "@AJNeufeld is it necessary to write functions in this form `def func(x: some_type) -> another_type:` ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-10T05:11:13.163",
"Id": "448957",
"Score": "0",
"body": "Necessary? No. `def func(x):` works just fine. But if you are adding type hints for the parameters, you should add the type hint for the return value as well."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-10T05:11:47.123",
"Id": "448959",
"Score": "0",
"body": "Sir, there may be a problem with this program. It will respond to `'16'` when it has a float value like `'2.53.6'`. If there is a solution to this."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-10T05:17:19.700",
"Id": "448960",
"Score": "3",
"body": "@brijeshkalkani what solution do you expect from the string `'2.53.6'?` It is not a valid float. There are several ways it could be interpreted:\n `2 + 5 + 3 + 6 = 16;\n 2.5 + 3.6 = 6.1;\n 2 + 53 + 6 = 61;\n 2.53 + 6 = 8.53`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-10T18:53:21.173",
"Id": "449120",
"Score": "1",
"body": "@IEatBagels Did you post your comment on the wrong answer? This answer only iterates through the string once. The [answer by c4llmeco4ch](https://codereview.stackexchange.com/a/230477/100620) iterates through the string multiple times."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-10T18:55:25.363",
"Id": "449121",
"Score": "2",
"body": "@IEatBagels to clarify AJNeufeld's comment, this code is using a [generator expression](https://www.python.org/dev/peps/pep-0289/) instead of a list comprehension, so the code does not iterate through the string multiple times."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-10T19:12:59.703",
"Id": "449122",
"Score": "1",
"body": "@oobug Well you (I) learn something new everyday!"
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-10T04:51:08.567",
"Id": "230467",
"ParentId": "230466",
"Score": "14"
}
},
{
"body": "<p>We could also do something like:</p>\n\n<pre><code>def sum_numbers(string: str) -> int:\n \"\"\"Return sum of numbers in string\"\"\"\n return sum([string.count(str(i)) * i for i in range(10)])\n\n\nif __name__ == '__main__':\n print(sum_numbers('hel3l4o55')) #should print 17\n print(sum_numbers('xdman')) #should print 0\n print(sum_numbers('123456789')) #should print 45\n</code></pre>\n\n<p>This differs from your implementation due to the fact that my loop iterates over the digits while yours loops through the string itself. This means a few things:</p>\n\n<ol>\n<li><p>If a string has at least one of every digit, this implementation skips out on checking for 0s. </p></li>\n<li><p>Depending on how Python internally runs the <code>list.count</code> function, there is a chance this implementation is wildly inefficient overall. I likely loop through the strings more times than its worth, so this becomes worse as the length of the string becomes sizeable enough.</p></li>\n</ol>\n\n<p>Ultimately, this is just a different idea on what we can loop around. As the number of things we need to search for (and in turn, the number of things we have to run a count on increases), the more times we search through the string, wasting time. However, if we are only looking for one thing or a small sample of possible results, list.count is a good option to have available.</p>\n\n<p>EDIT: might also depend on how floats are looked at as mentioned in the above comments. If they are supposed to just be read as individual chars then this works fine. If you're expected to parse whole sections to determine what is and isn't a float/multi-char number, this falls apart.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-10T08:00:54.377",
"Id": "448995",
"Score": "1",
"body": "Updated the edit to provide a bit more thought on when this would make sense. Hopefully that suffices but if not, let me know. Thanks and sorry for the trouble"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-10T08:02:27.027",
"Id": "448997",
"Score": "0",
"body": "You should write a full code as an answer and explain why it might be better than the Op's, please edit your answer that most likely will attract negative energy here."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-10T08:02:31.733",
"Id": "448998",
"Score": "0",
"body": "New to this channel so appreciate the feedback. Thanks again"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-10T08:03:57.087",
"Id": "448999",
"Score": "2",
"body": "@bullseye These are current guidelines for answering with a minimum of content: https://codereview.meta.stackexchange.com/questions/9308/alternate-solution-what-counts-as-an-insightful-observation"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-10T08:05:34.107",
"Id": "449000",
"Score": "0",
"body": "Fair, but I'll give it another shot to see if I can provide something more up-to-par. thanks guys"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-10T08:22:17.767",
"Id": "449003",
"Score": "2",
"body": "@bullseye hopefully provided a bit more in line with what you both find reasonable. appreciate you guys catching me up to speed on what we're looking for here."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-10T08:23:07.727",
"Id": "449004",
"Score": "0",
"body": "Yeah, that looks much better :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-10T09:24:04.510",
"Id": "449013",
"Score": "1",
"body": "Usually, alternative implementations are only valid as part of a review. They shouldn't be the start of a review. Point out what's wrong with the code first, and if you want, provide an alternative fixing that what's wrong further on. An alternative without pointing out what's wrong with the original isn't a review after all. Since this is Code *Review*, you know..."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-10T07:53:22.387",
"Id": "230477",
"ParentId": "230466",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "230467",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-10T04:33:51.807",
"Id": "230466",
"Score": "5",
"Tags": [
"python",
"algorithm",
"python-3.x",
"converting"
],
"Title": "Sum of all digits in a string"
}
|
230466
|
<blockquote>
<p>Given a string, assuming the string is numbers only, rearrange the string to that it is the greatest possible number.</p>
</blockquote>
<p>Below is my solution to the problem above. I'd like feedback mainly on the algorithm, as I wrote this up very quickly. I used comprehension syntax to find the largest num, which I'm trying to use more. Any other feedback is appreciated as well.</p>
<pre><code>def largest_number(string: str) -> str:
"""
Given a string, organize the numbers such as the
rearrangement is now the largest possible number
"""
string = list(string)
largest = ""
for _ in string:
largest_num = str(max([int(num) for num in string]))
largest += largest_num
string[string.index(largest_num)] = -1
return largest
if __name__ == '__main__':
# Test Cases #
assert largest_number("12345") == "54321"
assert largest_number("4689123") == "9864321"
assert largest_number("9") == "9"
assert largest_number("1923") == "9321"
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-10T05:46:07.410",
"Id": "448968",
"Score": "1",
"body": "Your solution runs in quadratic time \\$\\Theta(n^2)\\$. You could do the same in linearithmic time \\$\\Theta(n \\log n)\\$ simply by sorting the digit list into descending order."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-10T06:46:51.863",
"Id": "448983",
"Score": "0",
"body": "If this isn't reinventing-the-wheel, then `\"\".join(sorted(string), reverse=True)` is the best way to do it."
}
] |
[
{
"body": "<ul>\n<li><strong>Confusing names:</strong> the function <code>largest_number()</code> has a <code>string</code> parameter it's generally not a good practice to name parameters by their types and their is a type hint in your code indicating what that is so you can call the parameter <code>digits</code>.\nInside <code>largest_num()</code> there is <code>string = list(string)</code> where string is not a string(a list). This is super confusing when I'm looking at this part <code>string[string.index(largest_num)] = -1</code> which I mistook for some line that should produce an error (because you can't assign values to string indexes) and then I realized that string is a list. Don't use such confusing names. </li>\n<li><strong>Adding to strings:</strong> <code>largest += largest_num</code> This form is inefficient, a string is immutable in Python and each time you're adding to <code>largest</code> a new string is created and assigned to the new value. Whenever you find a similar situation, use list comprehension and join it using the <code>str.join()</code> method.</li>\n<li><p><strong>A better approach:</strong>\nAs 'coderodde' indicated in the comments, this is an <span class=\"math-container\">\\$O(N^2)\\$</span> solution which can be simplified into the following by just sorting the string:</p>\n\n<pre><code>def maximize_number(digits: str) -> str:\n \"\"\"Return the maximum number that can be formed using the digits.\"\"\"\n return ''.join(sorted(digits, reverse=True))\n</code></pre></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-10T06:12:06.967",
"Id": "230473",
"ParentId": "230469",
"Score": "4"
}
},
{
"body": "<p>Cannot comment on Python, but what comes to to the actual algorithm, you can do it in linear time <span class=\"math-container\">\\$\\Theta(n)\\$</span>:</p>\n\n<pre><code>def largest_number_3(string: str) -> str:\n counters = [0 for _ in range(10)]\n string = list(string)\n for ch in string:\n counters[ord(ch) - ord('0')] += 1\n i = 0\n for num in range(9, -1, -1):\n for _ in range(counters[num]):\n string[i] = chr(num + ord('0'))\n i += 1\n return ''.join(string)\n</code></pre>\n\n<p>The above is just a counting sort since there is only 10 digits to distinguish.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-10T06:56:55.370",
"Id": "448984",
"Score": "1",
"body": "For an input of size 50 ** 7 : Time1 (Your function): 29.697222855 seconds Time2 (My function): 5.580199974000003 seconds and might take a much longer for the OP's function, list comprehensions are much faster than explicit loops, your answer is an improvement of course to the OP's code however it's not the most efficient."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-10T06:36:55.053",
"Id": "230474",
"ParentId": "230469",
"Score": "4"
}
},
{
"body": "<p>This is an improvement on the <a href=\"https://codereview.stackexchange.com/a/230474/98493\">answer</a> by <a href=\"https://codereview.stackexchange.com/users/58360/coderodde\">@coderodde</a>. Just like they said, you can do this in <span class=\"math-container\">\\$\\mathcal{O}(n)\\$</span> time by counting how often each digit appears and then using a fixed output format. However, I would use <a href=\"https://docs.python.org/3/library/collections.html#collections.Counter\" rel=\"noreferrer\"><code>collections.Counter</code></a> from the standard library and string multiplication to achieve this goal:</p>\n\n<pre><code>from collections import Counter\n\ndef largest_number(string: str) -> str:\n counters = Counter(map(int, string))\n return \"\".join(str(d) * counters[d] for d in range(9, -1, -1))\n</code></pre>\n\n<p>Compared to sorting, as presented in the <a href=\"https://codereview.stackexchange.com/a/230473/98493\">answer</a> by <a href=\"https://codereview.stackexchange.com/users/209601/bullseye\">@bullseye</a>, and the original answer, this compares OK. It has a slight overhead for small strings due to the <code>Counter</code> object, but in the end it is faster than hardcoding character values and on the same level as sorting, but not better.</p>\n\n<p><a href=\"https://i.stack.imgur.com/pTao6.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/pTao6.png\" alt=\"enter image description here\"></a></p>\n\n<p>However, all three are vastly better than your <span class=\"math-container\">\\$\\mathcal{O}(n^2)\\$</span> algorithm (note the vastly different x limits):</p>\n\n<p><a href=\"https://i.stack.imgur.com/wyJwu.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/wyJwu.png\" alt=\"enter image description here\"></a></p>\n\n<p>As soon as you have three or more testcases, it might make sense to not repeat the testing code. Just put the input and expected output into a data structure (a list of tuples would do here), and iterate over it:</p>\n\n<pre><code>if __name__ == '__main__':\n test_cases = [(\"12345\", \"54321\"), (\"4689123\", \"9864321\"), (\"9\", \"9\"), (\"\", \"\")]\n for string, expected in test_cases:\n output = largest_number(string)\n if output != expected:\n raise AssertionError(f\"{string!r} gave back {output!r}\"\n f\" instead of {expected!r}\")\n</code></pre>\n\n<p>For more complicated programs you might want to look at a testing framework like <a href=\"https://docs.python.org/3/library/unittest.html\" rel=\"noreferrer\"><code>unittest</code></a>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-10T07:35:23.400",
"Id": "448991",
"Score": "5",
"body": "I like the graphs, good job :)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-10T07:23:17.607",
"Id": "230475",
"ParentId": "230469",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": "230475",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-10T05:15:30.147",
"Id": "230469",
"Score": "5",
"Tags": [
"python",
"algorithm",
"python-3.x"
],
"Title": "Largest number order in string"
}
|
230469
|
<p>I am building a generic Graph. I want to know whether the current design is fine. Are there any memory leaks ? Any suggestions are deeply appreciated. </p>
<h1>GraphCode</h1>
<pre><code>#include <iostream>
#include <memory>
#include <vector>
#include <atomic>
#include <map>
namespace AtomicOps
{
int GetID()
{
static std::atomic<int> id(0);
return id++;
}
} // namespace AtomicOps
template <typename T>
class Graph;
template <typename T>
class GraphFactory
{
public:
GraphFactory()
{
}
~GraphFactory()
{
mGraphDataMap.clear();
mCurrentPath.clear();
mTotalPath.clear();
}
//ID is provided by GETID fuction
Graph<T> &GetObject(T &data, int id = -1, bool addToPath = false)
{
return *GetObjectPTR(data, id, addToPath);
}
Graph<T> &GetObject(T &&data, int id = -1, bool addToPath = false)
{
//no need to move as we are creating copy of it
return *GetObjectPTR(data, id, addToPath);
}
//*************************************
//graph like (src node ---W--- dst-node)
void BuildGraph(T &&src, int weight, T &&dest, int srcID = -1, int dstID = -1, bool srcAddToPath = false, bool dstAddToPath = false)
{
BuildGraphHelper(src, weight, dest, srcID, dstID, srcAddToPath, dstAddToPath);
}
void BuildGraph(T &src, int weight, T &dest, int srcID = -1, int dstID = -1, bool srcAddToPath = false, bool dstAddToPath = false)
{
BuildGraphHelper(src, weight, dest, srcID, dstID, srcAddToPath, dstAddToPath);
}
std::vector<std::shared_ptr<Graph<T>>> GetAllNodes()
{
return mTotalPath;
}
std::vector<std::shared_ptr<Graph<T>>> GetCurrentPath()
{
return mCurrentPath;
}
void ClearCurrentPath()
{
mCurrentPath.clear();
}
void AddToCurrentPath(Graph<T> &obj, int id = -1)
{
auto pathPTR = GetObjectPTR(obj.mData, id);
mCurrentPath.push_back(pathPTR);
}
private:
std::shared_ptr<Graph<T>> &GetObjectPTR(T &data, int id, bool addToPath)
{
auto pair = std::make_pair<T &, int &>(data, id);
if (mGraphDataMap.find(pair) == mGraphDataMap.end())
{
mGraphDataMap[pair] = std::make_shared<Graph<T>>(Graph<T>(std::forward<T>(data)));
mGraphDataMap[pair]->mID = id;
mTotalPath.push_back(mGraphDataMap[pair]);
if (addToPath)
{
mCurrentPath.push_back(mGraphDataMap[pair]);
}
}
return (mGraphDataMap[pair]);
}
void BuildGraphHelper(T &src, int weight, T &dest, int srcID = -1, int dstID = -1, bool srcAddToPath = false, bool dstAddToPath = false)
{
auto &srcNode = (GetObject(src, srcID, srcAddToPath));
auto &dstNode = (GetObject(dest, dstID, dstAddToPath));
srcNode.AddEdge(dstNode, weight);
}
std::map<std::pair<T, int>, std::shared_ptr<Graph<T>>> mGraphDataMap;
std::vector<std::shared_ptr<Graph<T>>> mCurrentPath;
std::vector<std::shared_ptr<Graph<T>>> mTotalPath;
};
template <typename T>
class GraphAlgo
{
typedef std::shared_ptr<Graph<T>> GraphPTR;
public:
GraphAlgo(std::vector<GraphPTR> &path) : mPath(path)
{
}
void Clear()
{
for (auto& item : mPath)
{
item->ClearMeta();
}
}
const GraphPTR findMin()
{
int dist = INT32_MAX;
GraphPTR minNode;
int index = -1;
int last_index = 0;
for (auto &node : mPath)
{
if (dist > node->mDist && !node->mVisited)
{
dist = node->mDist;
minNode = node;
}
}
//nodes[last_index].mVisited= true;
minNode->mVisited = true;
return minNode;
}
//This node consider to be shortest node
std::vector<Graph<T>>
DijkstraShortestPath()
{
std::vector<GraphPTR> tmp;
std::vector<Graph<T>> pathToParent;
if (mPath.empty())
{
pathToParent;
}
//we should be knowing in advance which nodes are going to participate
//mPath variable should be static varable
mPath[0]->mDist = 0;
// or we can find all pair shortest path
for (int j = 0; j < mPath.size(); j++)
{
auto minNode = findMin();
int size = minNode->mEdges.size();
for (int i = 0; i < size; i++)
{
if (minNode->mEdges[i].weight < 0)
{
return pathToParent;
}
if (minNode->mEdges[i].edge->mDist > minNode->mDist + minNode->mEdges[i].weight)
{
minNode->mEdges[i].edge->mDist = minNode->mDist + minNode->mEdges[i].weight;
//std::swap(minNode->mEdges[i].edge->mParent, nullptr);
minNode->mEdges[i].edge->mParent = minNode;
// Front
}
}
}
GraphPTR graph = mPath[mPath.size() - 1];
while (graph)
{
pathToParent.push_back(*graph);
graph = graph->mParent;
}
return pathToParent;
}
private:
std::vector<GraphPTR> mPath;
};
template <typename T>
class Graph;
template <typename T>
void no_op(Graph<T> *)
{
}
template <typename T>
class Graph
{
typedef std::shared_ptr<Graph<T>> GraphPTR;
public:
T &GetData()
{
return mData;
}
~Graph()
{
mPath.clear();
}
void AddEdge(Graph<T> &edge, int weight = 1)
{
// Don't copy we need ref
// As client function is going
// to manage memory of obj we shouldn't be
// deleting obj;
// TODO : use instead raw pointer here
GraphPTR ptr(&edge, no_op<T>);
mEdges.push_back(GraphMeta(ptr, weight));
}
void SetPath(std::vector<GraphPTR> &gPtr)
{
mPath = gPtr;
}
void ClearPath()
{
mPath.clear();
}
void AddToPath(Graph<T> &edge)
{
//TODO : use insted raw pointer here
GraphPTR ptr(&edge, no_op<T>);
mPath.push_back(ptr);
}
Graph(const Graph<T> &&copy) : mID(copy.mID),
mData(std::move(copy.mData)),
mEdges(std::move(copy.mEdges)),
mDist(std::move(copy.mDist)),
mVisited(copy.mVisited)
{
// mParent(nullptr);
}
Graph(const Graph<T> &copy) : mID(copy.mID),
mData(copy.mData),
mEdges(copy.mEdges),
mDist(copy.mDist),
mVisited(copy.mVisited)
{
// mParent(nullptr);
}
Graph<T> &operator=(const Graph<T> &&copy)
{
mID = copy.mID;
mData = std::move(copy.mData);
mEdges = std::move(copy.mEdges);
mDist = std::move(copy.mDist);
mVisited = copy.mVisited;
mParent = std::move(mParent);
}
Graph<T> &operator=(const Graph<T> &copy)
{
mID = copy.mID;
mData = (copy.mData);
mEdges = (copy.mEdges);
mDist = (copy.mDist);
mVisited = copy.mVisited;
mParent = (mParent);
}
private:
Graph()
{
}
void clearMeta()
{
mParent = nullptr;
mVisited = false;
mDist = INT32_MAX;
}
Graph(T &data, int id = -1) : mData(data)
{
mDist = INT32_MAX;
mVisited = false;
mID = id;
}
Graph(T &&data, int id = -1) : mData(std::move(data))
{
mDist = INT32_MAX;
mVisited = false;
mID = id;
}
struct GraphMeta
{
GraphMeta(GraphPTR ptr, int wt) : edge(ptr), weight(wt)
{
}
GraphMeta(const GraphMeta &other) : weight(other.weight),
edge(other.edge)
{
}
GraphMeta &operator=(const GraphMeta &other)
{
weight = other.weight;
edge = other.edge;
}
int weight;
Graph::GraphPTR edge;
};
private:
friend class GraphFactory<T>;
friend class GraphAlgo<T>;
T mData;
int mDist;
GraphPTR mParent;
bool mVisited;
std::vector<GraphMeta> mEdges;
std::vector<GraphPTR> mPath;
int mID;
};
</code></pre>
<h1>Client Code</h1>
<pre><code>int main()
{
GraphFactory<int> obj;
obj.BuildGraph(1, 1, 2);
obj.BuildGraph(2, 1, 6);
//6 1 10, 10 1 11
obj.BuildGraph(6, 3, 10);
obj.BuildGraph(2, 1, 11);
obj.BuildGraph(10, 1, 11);
auto list = obj.GetAllNodes();
GraphAlgo<int> algoObj(list);
auto nodes = algoObj.DijkstraShortestPath();
for(auto item: nodes) {
std::cout << item.GetData() <<std::endl;
}
return 0;
}
</code></pre>
<h1>Compiler : MINGW(Windows)</h1>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-10T13:12:11.910",
"Id": "449042",
"Score": "1",
"body": "Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-10T13:13:13.260",
"Id": "449043",
"Score": "0",
"body": "Ok sorry i am reverting back"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-12T09:14:03.580",
"Id": "449349",
"Score": "0",
"body": "Why don't you `=default` your copy/move constructors and assignment operators? Seems redundant. I don't see why you would want the generic type T as a part of your graph. It doesn't seem like an integral part of the graph class, so I'd drop it. At most make a template child of graph that contains the data."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-12T14:34:53.387",
"Id": "449371",
"Score": "0",
"body": "1) Yes, you are right I can do it that way but now I have just written this code, so I want it easy to debug. I am getting complete flow of program how object is moving and copying. For example, as this graph any object you have added now and may have edge in future, if you have created copy of that object you will not able to have edge (As graph have reference to copied object not actual object).This kind of issues i was facing so created that.\n\n2) Thanks for suggestion for decoupling data and graph itself. I will refactor that way I don’t see any disadvantage."
}
] |
[
{
"body": "<p>This destructor is pointless:</p>\n\n<blockquote>\n<pre><code> ~GraphFactory()\n {\n mGraphDataMap.clear();\n mCurrentPath.clear();\n mTotalPath.clear();\n }\n</code></pre>\n</blockquote>\n\n<p>Those three members are going out of scope anyway, so <code>clear()</code> is redundant. Just omit the destructor entirely.</p>\n\n<p>Here's a useless statement:</p>\n\n<blockquote>\n<pre><code>if (mPath.empty())\n{\n pathToParent;\n}\n</code></pre>\n</blockquote>\n\n<p>Was that meant to be a <code>return</code>?</p>\n\n<p>Use consistent types for comparisons. For example, we have:</p>\n\n<blockquote>\n<pre><code>for (int j = 0; j < mPath.size(); j++)\n</code></pre>\n</blockquote>\n\n<p>A vector's <code>size()</code> is a <code>std::size_t</code>, so use the same type for <code>j</code>:</p>\n\n<pre><code>for (std::size_t j = 0; j < mPath.size(); ++j)\n</code></pre>\n\n<p>In initializer lists, it helps readers if you write the initializers in the order that they will be executed (which is the order in which the members are declared):</p>\n\n<pre><code>Graph(const Graph<T>&& copy)\n : mData(std::move(copy.mData)),\n mDist(std::move(copy.mDist)),\n mParent(),\n mVisited(copy.mVisited),\n mEdges(std::move(copy.mEdges)),\n mPath(),\n mID(copy.mID)\n{\n}\n</code></pre>\n\n<p>There's a couple of unused variables in <code>findMin()</code>:</p>\n\n<blockquote>\n<pre><code>int index = -1;\nint last_index = 0;\n</code></pre>\n</blockquote>\n\n<p>Prefer to use initializers rather than assignment in constructors:</p>\n\n<pre><code>Graph(T& data, int id = -1)\n : mData(data),\n mDist(INT32_MAX),\n mParent(),\n mVisited(false),\n mEdges(),\n mPath(),\n mID(id)\n{\n}\n</code></pre>\n\n<p>All the points above are found simply by compiling with a reasonable set of warnings (<code>g++ -Wall -Wextra -Wwrite-strings -Wno-parentheses -Wpedantic -Warray-bounds -Weffc++</code>), so easily fixed yourself.</p>\n\n<hr>\n\n<p>The <code>GraphMeta</code> member functions (constructors and assignment) add no value, as they are identical to the compiler-generated code, so we can omit them. We just need to change the member order to match the construction call, and use braces at the call site:</p>\n\n<pre><code>struct GraphMeta\n{\n Graph::GraphPTR edge;\n int weight;\n};\n</code></pre>\n\n\n\n<pre><code> mEdges.push_back(GraphMeta{ptr, weight});\n</code></pre>\n\n<hr>\n\n<p>I'd like to move in to look at <code>GetObjectPTR</code>.</p>\n\n<p>We're missing some of the point of <code>std::make_shared()</code>, in that we don't need to construct an object and copy it in; though we do need to read <em><a href=\"//stackoverflow.com/q/8147027/4850040\">How do I call <code>std::make_shared</code> on a class with only protected or private constructors?</a></em> (or to make the <code>Graph</code> constructor public).</p>\n\n<p>It doesn't make sense to make a <code>GraphFactory</code> of rvalue-references, so <code>std::forward()</code> is pointless in this method; we should accept a reference to <code>const T</code> instead.</p>\n\n<p>There's no need to return its shared pointer by reference - pointers should almost always be passed by value</p>\n\n<p>There's also much repetition of work here (repeated lookup in the map). We should keep a reference or iterator to avoid the re-work.</p>\n\n<p>I ended up with:</p>\n\n<pre><code>std::shared_ptr<Graph<T>> GetObjectPTR(const T& data, int id, bool addToPath)\n{\n auto pair = std::make_pair<const T&,const int&>(data, id);\n auto found = mGraphDataMap.find(pair);\n if (found != mGraphDataMap.end()) {\n return found->second;\n }\n\n auto p = std::make_shared<Graph<T>>(data, id);\n mGraphDataMap[pair] = p;\n mTotalPath.push_back(p);\n if (addToPath) {\n mCurrentPath.push_back(p);\n }\n\n return p;\n}\n</code></pre>\n\n<p>Additionally, a handful of <code>T&</code> arguments on other functions became <code>const T&</code> to match.</p>\n\n<hr>\n\n<p>This expression:</p>\n\n<blockquote>\n<pre><code> GraphPTR graph = mPath[mPath.size() - 1];\n</code></pre>\n</blockquote>\n\n<p>is normally written:</p>\n\n<pre><code> GraphPTR graph = mPath.back();\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-10T12:27:22.377",
"Id": "449035",
"Score": "0",
"body": "Thanks for great comment ."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-10T12:33:04.463",
"Id": "449036",
"Score": "0",
"body": "BTW, this isn't a complete review - I ran out of time, but I might be back to add to it if you don't get other answers."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-10T12:35:12.333",
"Id": "449037",
"Score": "0",
"body": "Thanks for great comment. I have opinion that we should always passing template object as ref because that object can be anything in future, I don't want to copy always. In Graph<T> class always passes object as ref because i want to create pointer to object so that if some modification in future (like add edge to that object) i should be keeping track of that. Shared_ptr by ref is fine https://stackoverflow.com/questions/3310737/should-we-pass-a-shared-ptr-by-reference-or-by-value"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-10T12:49:07.000",
"Id": "449039",
"Score": "1",
"body": "That question is slightly different - that's about how to pass the pointer *into* a function. Here, we were _returning_ a (mutable) reference to a map value. In principle, the receiving could could reset the referenced pointer, or hold onto it beyond its lifetime. Good practice for return values isn't the same as good practice for parameters!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-10T12:54:15.757",
"Id": "449040",
"Score": "0",
"body": "Gotcha Thanks :) but object passing by ref is batter here. Do you have opinion"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-10T11:17:07.193",
"Id": "230489",
"ParentId": "230476",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-10T07:36:39.007",
"Id": "230476",
"Score": "4",
"Tags": [
"c++",
"algorithm",
"graph"
],
"Title": "A Graph implementation in C++"
}
|
230476
|
<p>I have implemented a Ternary search tree. It works well. But if you think something needs to be improved, say it. This code was tested in Python 3.7.4.</p>
<pre><code>class Node(object):
def __init__(self, character):
self.character = character
self.leftNode = None
self.middleNode = None
self.rightNode = None
self.value = 0
class TST(object):
def __init__(self):
self.rootNode = None
def put(self,key,value):
self.rootNode = self.putItem(self.rootNode, key, value, 0)
def putItem(self, node, key, value, index):
c = key[index]
if node == None:
node = Node(c)
if c < node.character:
node.leftNode = self.putItem(node.leftNode, key, value, index)
elif c > node.character:
node.rightNode = self.putItem(node.rightNode, key, value, index)
elif index < len(key) - 1:
node.middleNode = self.putItem(node.middleNode, key, value, index+1)
else:
node.value = value
return node
def get(self, key):
node = self.getItem(self.rootNode, key, 0)
if node == None:
return -1
return node.value
def getItem(self, node, key, index):
if node == None:
return None
c = key[index]
if c < node.character:
return self.getItem(node.leftNode, key, index)
elif c > node.character:
return self.getItem(node.rightNode, key, index)
elif index < len(key) - 1:
return self.getItem(node.middleNode, key, index+1)
else:
return node
if __name__ == "__main__":
tst = TST()
tst.put("apple",100)
tst.put("orange",200)
print( tst.get("orange") )
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-10T11:41:33.517",
"Id": "449029",
"Score": "0",
"body": "AlexV, Thanks for editing my question."
}
] |
[
{
"body": "<p>Data structure-wise, it seems okay, and does what you're after.</p>\n\n<p>Code-style wise, I see a few things:</p>\n\n<ol>\n<li><p>It's not quite <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"noreferrer\">PEP8</a>, the coding style. Whilst you can read it, which is always good, there are tools to automatize the process, such as <a href=\"https://pypi.org/project/flake8/\" rel=\"noreferrer\"><code>flake8</code></a>, <a href=\"https://github.com/psf/black\" rel=\"noreferrer\"><code>black</code></a>. Most likely, your editor will have a plugin. </p>\n\n<p>This is include things like <code>underscore_names</code> in lieu of <code>camelCasing</code>.</p>\n\n<p>Note that this standard is a living document, and gets updated once in a while.</p></li>\n<li><p><code>None</code> is a singleton in Python, and thus you can use the <code>is</code> keyword instead.\nPython relies on its <code>id()</code> function to get a hash of an object, and compare them.\nAs <code>None</code> is a singleton, the hash is the same. </p>\n\n<p>So your line <code>if node == None:</code> could be <code>if node is None</code>.<br>\n<strike>Going further this way, <code>None</code> evaluates to <code>False</code> in a test, so you could go <code>if not node:</code></strike> (edit: as discussed with @Gloweye, it's indeed clearer and preferred to use the first variant).</p></li>\n<li><p>Python returns <code>None</code> when no value is being explicitly returned, whether you have no <code>return</code> in a function, or do a blank <code>return</code>.</p></li>\n</ol>\n\n<p>These two lines taken together could then be:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>if node is None:\n return\n</code></pre>\n\n<p>and would be considered idiomatic.</p>\n\n<ol start=\"4\">\n<li>Lastly, in Python3 (which you ought to be using), class definition have been revamped. The way you do it:</li>\n</ol>\n\n<pre class=\"lang-py prettyprint-override\"><code>class TST(object):\n</code></pre>\n\n<p>is now:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>class TST:\n</code></pre>\n\n<p>If you were inheriting from something, though, it would indeed be:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>class TST(ParentClass):\n</code></pre>\n\n<p>Maybe what you could try next is to implement unit tests with <a href=\"https://docs.python.org/3/library/unittest.html\" rel=\"noreferrer\">unittest</a> or <a href=\"https://pytest.org/en/latest/\" rel=\"noreferrer\">pytest</a> and see whether your structure holds on with more convoluted cases.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-10T14:07:14.313",
"Id": "449049",
"Score": "1",
"body": "In Python, if you're actively looking for None instead of falsy value in general, `if node is None` is preferred to `if not node`. This applies to this specific case."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-10T14:45:02.997",
"Id": "449052",
"Score": "1",
"body": "You're right, and I abuse that behaviour. Thanks for the reminder!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-10T15:00:20.187",
"Id": "449056",
"Score": "1",
"body": "The point isn't for the computer running the code, it's for the programmer reading it. When they read `if not node`, they'll wander what node can be other than Node or None. `if node is None` instead shows you that Nodes and None are the only valid values. That makes it more readable, and especially here on CodeReview, therefore preferable."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-10T17:02:44.347",
"Id": "449109",
"Score": "0",
"body": "Thank a lot Gloweye and Cyril D. to spend your valuable time to get the review of my code. Let me correct as per your suggestion and get back to you. Today I learned many coding fundamentals and styles from your suggestions. Thanks a lot once again."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-10T13:22:27.090",
"Id": "230494",
"ParentId": "230479",
"Score": "5"
}
},
{
"body": "<h1>Docstring</h1>\n<p>You can document the behaviour of the method with a <a href=\"https://www.python.org/dev/peps/pep-0257/\" rel=\"nofollow noreferrer\">docstring</a></p>\n<h1>typing</h1>\n<p>You can add typing, to clarify for the caller what type the different arguments and variables are</p>\n<h1><code>TST.putItem</code></h1>\n<p>Apart from the name, which according to PEP-8 would be better as <code>put_item</code>, should not be an ordinary method of the TST. The <code>self</code> is only used as to recursively call the same method. This can be a helper method in the global namespace, or a <a href=\"https://docs.python.org/3/library/functions.html#staticmethod\" rel=\"nofollow noreferrer\"><code>staticmethod</code></a></p>\n<p>The same comment goes for the <code>GetItem</code></p>\n<h1><code>get</code></h1>\n<pre><code>def get(self, key):\n\n node = self.getItem(self.rootNode, key, 0)\n\n if node == None:\n return -1\n\n return node.value\n</code></pre>\n<p>-1 is a bad sentinel value. How will the caller distinguish between a <code>node.value</code> of <code>-1</code> or a non-existent key?</p>\n<p>Better would be to either raise a <code>KeyError</code> if the value is not in the tree, or mimic the behaviour of <a href=\"https://docs.python.org/3/library/stdtypes.html#dict.get\" rel=\"nofollow noreferrer\"><code>dict.get(key\\[, default_value\\])</code></a>, with an explicit default value.</p>\n<h1>tuple unpacking</h1>\n<p>Instead of explicitly sending the index with it, you can use tuple unpacking.</p>\n<hr />\n<p>My take on your Ternary search tree:</p>\n<p>With added typing hints, implementing the <code>__getitem__</code> and <code>__setitem__</code> magic methods.</p>\n<p>The <code>put_item</code> and <code>get_item</code> can be put on the <code>Node</code> class as well. Which you choose is a matter of taste</p>\n<pre><code>import typing\n\nV = typing.TypeVar("V")\n\n\nclass Node:\n def __init__(\n self, character: str, value: typing.Optional[V] = None\n ) -> None:\n self.character: str = character\n self.left: typing.Optional[Node] = None\n self.middle: typing.Optional[Node] = None\n self.right: typing.Optional[Node] = None\n self.value: typing.Optional[V] = value\n\n\nclass TernarySearchTree:\n def __init__(self) -> None:\n self.root: typing.Optional[Node] = None\n\n def __setitem__(\n self, key: typing.Union[str, typing.Iterable[str]], value: V\n ) -> None:\n self.root = TernarySearchTree.put_item(self.root, key=key, value=value)\n\n put = __setitem__\n\n @staticmethod\n def put_item(\n node: typing.Optional[Node],\n key: typing.Union[str, typing.Iterable[str]],\n value: V,\n ) -> Node:\n c: str\n c, *rest = key\n\n if node is None:\n node = Node(c)\n\n if c < node.character:\n node.left = TernarySearchTree.put_item(\n node=node.left, key=key, value=value\n )\n elif c > node.character:\n node.right = TernarySearchTree.put_item(\n node=node.right, key=key, value=value\n )\n elif rest:\n node.middle = TernarySearchTree.put_item(\n node=node.middle, key=rest, value=value\n )\n else:\n node.value = value\n return node\n\n def __getitem__(self, key: typing.Union[str, typing.Iterable[str]]) -> V:\n return TernarySearchTree.get_item(self.root, key=key).value\n\n def get(\n self,\n key: typing.Union[str, typing.Iterable[str]],\n default_value: typing.Optional[V] = None,\n ) -> typing.Optional[V]:\n try:\n return self[key]\n except KeyError:\n return default_value\n\n @staticmethod\n def get_item(\n node: typing.Optional[Node],\n key: typing.Union[str, typing.Iterable[str]],\n ) -> Node:\n if node is None:\n raise KeyError\n\n c: str\n c, *rest = key\n\n if c == node.character and not rest:\n return node\n\n if c < node.character:\n return TernarySearchTree.get_item(node=node.left, key=key)\n if c > node.character:\n return TernarySearchTree.get_item(node=node.right, key=key)\n return TernarySearchTree.get_item(node=node.middle, key=rest)\n\n\nif __name__ == "__main__":\n\n tst = TernarySearchTree()\n\n tst.put("apple", 100)\n tst["orange"] = 200\n tst.put("orb", 150)\n\n print(tst["orange"])\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-28T13:28:56.460",
"Id": "246124",
"ParentId": "230479",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "230494",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-10T08:18:43.967",
"Id": "230479",
"Score": "2",
"Tags": [
"python",
"python-3.x",
"tree"
],
"Title": "Ternary search tree implementation in python 3"
}
|
230479
|
<p>I've written a module for repeating blocks of code, generally to cover issues related to eventual consistency and testing screen elements which may take some time to fully load. It looks like this:</p>
<pre class="lang-rb prettyprint-override"><code>class Repeater
def initialize(&block)
@repeat_block = block
end
def repeat(times: 25, delay: 0.2)
result = nil
times.times do
result = @repeat_block.call
break if @until_block.present? && @until_block.call
sleep(delay)
end
result
end
def until(&block)
@until_block = block
self
end
end
</code></pre>
<p>The Repeater takes two blocks of code, one to be run and the second to check for an exit criteria. Optionally the number of repeats and delays can be overwritten after the <code>.repeat</code> method.</p>
<p>This is implemented in many places throughout the codebase, an example of such is:</p>
<pre class="lang-rb prettyprint-override"><code> result = false
Repeater.new do
result = event_present_in_database
end.until do
result
end.repeat(times: 10, delay: 0.1)
result
</code></pre>
<p>In this case the <code>event_present_in_database</code> method is being repeated called until it returns true instead of false, which indicates that the event has been created as expected, or else times out indicating there's an issue.</p>
<p>This certainly works for what I want it to do, however it doesn't seem very neat and I'm sure it could be tidied up. I know Ruby has all sorts of tricks that I've yet to come across, is there a way to leverage these to make this nicer to use/easier to read.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-10T09:44:31.543",
"Id": "449016",
"Score": "0",
"body": "This isn't your actual code, is it? Code Review doesn't handle hypothetical code well, please upload an actual implementation so it can be meaningfully reviewed."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-10T10:05:31.273",
"Id": "449019",
"Score": "1",
"body": "The repeater I want to refactor is real world code, the implementation was generic as it's being used multiple times throughout the code. Have replaced the example with an actual usage if that clears things up"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-10T12:11:28.067",
"Id": "449032",
"Score": "0",
"body": "Thank you, that does help."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-10T18:37:39.683",
"Id": "449118",
"Score": "0",
"body": "This could become a good question, because I do find this code to be awkward. However, the example use case is too simplified and hypothetical, in my opinion. It's unclear what you would want to do with `result`, and how `event_present_in_database` goes about doing its work. There could be other polling/retrying mechanisms you could use, such as `try`-`catch`, but I can't give you good advice based on this sketchy code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-10T23:41:52.473",
"Id": "449156",
"Score": "2",
"body": "The Repeater class is being used in multiple different scenarios, the given code is just one such example which calls a method repeatedly until either it returns true or the maximum number of repeats is met, it is used to test that events are eventually being made even though there may be a small delay. Elsewhere in the project I'm using the repeater to check for an on-screen element to be present, but which can sometimes take a moment to load. As such the actual method being called isn't really relevant as it can be anything that returns a value, however I'll expand on how it currently works."
}
] |
[
{
"body": "<p>There's not much weak points I can see. </p>\n\n<p>The biggest one is the way to use it. One needs to declare a variable to be caught in the block (closure), and I think it's unnecessary. You should be able to do this:</p>\n\n<pre><code> Repeater.new do\n event_present_in_database\n end.until do |result|\n result\n end.repeat(times: 10, delay: 0.1)\n</code></pre>\n\n<p>If you changed the <code>break</code> like like this: </p>\n\n<pre><code> break if @until_block.present? && @until_block.call(result)\n</code></pre>\n\n<p>The second, tiny point would be: make it clearer to understand the extraction to method conditionals: </p>\n\n<pre><code> # ...\n break if exit_criteria_satisfied?(result)\n # ...\n\n private \n def exit_criteria_satisfied?(result)\n @until_block.present? && @until_block.call\n end\n</code></pre>\n\n<p>That's all I got. The rest of the code seems pretty clear to me. </p>\n\n<blockquote>\n <p>I know Ruby has all sorts of tricks</p>\n</blockquote>\n\n<p>Yeah, but I don't know a single one that could help with the readability here. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-19T11:28:58.003",
"Id": "454333",
"Score": "1",
"body": "This is interesting, and is the sort of thing that I had in mind. One question, is there a way to do this if I need to interrogate the result of the Repeater? For example, if I'm waiting until there is a record present in the database, but once it's there I want to use the values within the record to do something else. My first thought is to store result as an instance variable, any better ways to do it?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-19T14:24:14.617",
"Id": "454361",
"Score": "0",
"body": "Actually was just being a bit dense, you can assign the output of Repeater to a variable to have it accessible once it's finished running. Am going to experiment with this a bit and see how it handles real world applications"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-19T14:36:52.333",
"Id": "454364",
"Score": "0",
"body": "Yeah, `repeat` method still returns the last `result` from the block, so you can assign it to any variable."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-18T20:08:16.960",
"Id": "232613",
"ParentId": "230483",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-10T09:32:31.947",
"Id": "230483",
"Score": "4",
"Tags": [
"ruby"
],
"Title": "Repeater for blocks of Ruby"
}
|
230483
|
<pre><code>a = [5, 2, 4, 6, 1, 3]
def insert(arr):
if len(arr) == 1:
return arr
# outer loop
for i in range(1, len(arr)):
# inner loop
for j in range(i, 0, -1):
if arr[j] < arr[j-1]:
arr[j], arr[j-1] = arr[j-1], arr[j]
return arr
print(insert(a))
</code></pre>
<p>I am getting a time out for this program implementing bubble sort.
Where is the problem and how can I optimize this?
My hunch is that it might be the inner loop, which loops through the list backward, but I can't seem to understand why it would take like 4.5s to sort the above list.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-10T10:23:19.083",
"Id": "449020",
"Score": "2",
"body": "This doesn't look like [Quicksort](https://en.wikipedia.org/wiki/Quicksort) to me. More like a type of bubblesort."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-10T10:30:12.960",
"Id": "449021",
"Score": "1",
"body": "I agree with Gloweye, this looks like bubble sort and bubble sort is in fact one of the most inefficient sorting algorithms, so it's not unlikely to take some time sorting things"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-10T12:26:09.543",
"Id": "449034",
"Score": "0",
"body": "There is no reason to comment `# outer loop` and `# inner loop`. Anyone can see that for themselves. You really don't need comments for the obvious and the real goal is to write your code in a way that removes the need for comments by making the code readable. readability > shorter code. Of coarse there will be some cases where comments will be needed but for the most part you can avoid things like `# this loop does this thing` or `# setting up my variables and so on`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-10T12:39:54.957",
"Id": "449038",
"Score": "2",
"body": "If I run you exact code here, it runs quite fast. Fast enough for me to get the same timestamp before and after execution(python's `time.time()` - I dont bother with timeit for something like this). Could you sort this out and then edit that into the question ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-15T10:50:44.430",
"Id": "449754",
"Score": "3",
"body": "Why would you call a sorting function `insert`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-22T18:45:20.037",
"Id": "458607",
"Score": "0",
"body": "`why it would take like 4.5s to sort [5, 2, 4, 6, 1, 3]` How did you establish that timing? `getting a time out`/`getting a time out` where does the/a time limit come from?"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-10T10:20:13.897",
"Id": "230485",
"Score": "1",
"Tags": [
"python",
"algorithm",
"sorting",
"time-limit-exceeded"
],
"Title": "Python Bubble sort"
}
|
230485
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.