body
stringlengths 25
86.7k
| comments
list | answers
list | meta_data
dict | question_id
stringlengths 1
6
|
|---|---|---|---|---|
<p>I have implemented exponentiation with integer base and non-negative integer exponent for practicing purposes.</p>
<p>Of course there is some upper limit what numbers can be exponentiated within the int datatype, but I wasn't concerned about this at this point. But any suggestions how to handle it are welcome.</p>
<p>There are four variantions of the power function:</p>
<pre><code>// full runtime version
int ipow(int, unsigned int);
// full compile time version
template<int, unsigned int> int ipow();
// only base is known at compile time
template<int> int ipow_base(unsigned int);
// only exponent is known at compile time
template<unsigned int> int ipow_exp(int);
</code></pre>
<p>I am interested in a general review, if I'm doing something wrong, could I have made something more explicit, etc...</p>
<p>My only restriction is that I am not (yet) intersted in post C++17 features.</p>
<pre><code>#include <cstddef>
#include <stdexcept>
template<const unsigned int exponent>
constexpr int ipow_exp(int base)
{
if (exponent == 0) return 1;
return base * ipow_exp<exponent-1>(base);
}
template<>
constexpr int ipow_exp<1>(int base)
{
return base;
}
template<>
constexpr int ipow_exp<0>(int base)
{
if (base == 0) throw std::logic_error("0^0 is undefined.");
return 1;
}
template<const int base>
constexpr int ipow_base(unsigned int exponent)
{
if (exponent == 0) return 1;
return base * ipow_base<base>(exponent-1);
}
template<>
constexpr int ipow_base<2>(unsigned int exponent)
{
return 1 << exponent;
}
template<>
constexpr int ipow_base<1>(unsigned int exponent)
{
return 1;
}
template<>
constexpr int ipow_base<0>(unsigned int exponent)
{
if (exponent == 0) throw std::logic_error("0^0 is undefined.");
return 0;
}
template<const int base, const unsigned int exponent>
constexpr int ipow()
{
static_assert(exponent != 0 || base != 0, "0^0 is undefined.");
if (exponent == 1 || base == 0 || base == 1) {
return base;
}
return ipow_base<base>(exponent);
}
int ipow(int base, unsigned int exponent)
{
if (exponent == 0) {
if (base == 0) throw std::logic_error("0^0 is undefined.");
return 1;
}
int result = base;
while (--exponent > 0) {
result *= base;
}
return result;
}
#include <cassert>
int main()
{
int tmp;
bool thrown = false;
// full runtime version
assert(ipow(0,1) == 0);
assert(ipow(0,2) == 0);
assert(ipow(0,3) == 0);
assert(ipow(0,50) == 0);
assert(ipow(1,0) == 1);
assert(ipow(1,1) == 1);
assert(ipow(1,2) == 1);
assert(ipow(1,50) == 1);
assert(ipow(2,0) == 1);
assert(ipow(2,1) == 2);
assert(ipow(2,2) == 4);
assert(ipow(2,3) == 8);
assert(ipow(2,10) == 1024);
assert(ipow(3,0) == 1);
assert(ipow(3,1) == 3);
assert(ipow(3,2) == 9);
assert(ipow(3,3) == 27);
assert(ipow(3,4) == 81);
assert(ipow(5,0) == 1);
assert(ipow(5,1) == 5);
assert(ipow(5,2) == 25);
assert(ipow(5,3) == 125);
assert(ipow(5,4) == 625);
assert(ipow(-1,0) == 1);
assert(ipow(-1,1) == -1);
assert(ipow(-1,2) == 1);
assert(ipow(-1,3) == -1);
assert(ipow(-1,4) == 1);
assert(ipow(-1,31) == -1);
assert(ipow(-1,32) == 1);
assert(ipow(-2,0) == 1);
assert(ipow(-2,1) == -2);
assert(ipow(-2,2) == 4);
assert(ipow(-2,9) == -512);
assert(ipow(-2,10) == 1024);
assert(ipow(-5,0) == 1);
assert(ipow(-5,1) == -5);
assert(ipow(-5,2) == 25);
assert(ipow(-5,3) == -125);
assert(ipow(-5,4) == 625);
thrown = false;
try {
ipow(0,0);
} catch (std::logic_error e){
thrown = true;
}
assert(thrown);
// compile time exponent version
tmp = ipow_exp<1>(0); assert(tmp == 0);
tmp = ipow_exp<2>(0); assert(tmp == 0);
tmp = ipow_exp<3>(0); assert(tmp == 0);
tmp = ipow_exp<50>(0); assert(tmp == 0);
tmp = ipow_exp<0>(1); assert(tmp == 1);
tmp = ipow_exp<1>(1); assert(tmp == 1);
tmp = ipow_exp<2>(1); assert(tmp == 1);
tmp = ipow_exp<50>(1); assert(tmp == 1);
tmp = ipow_exp<0>(2); assert(tmp == 1);
tmp = ipow_exp<1>(2); assert(tmp == 2);
tmp = ipow_exp<2>(2); assert(tmp == 4);
tmp = ipow_exp<3>(2); assert(tmp == 8);
tmp = ipow_exp<10>(2); assert(tmp == 1024);
tmp = ipow_exp<0>(3); assert(tmp == 1);
tmp = ipow_exp<1>(3); assert(tmp == 3);
tmp = ipow_exp<2>(3); assert(tmp == 9);
tmp = ipow_exp<3>(3); assert(tmp == 27);
tmp = ipow_exp<4>(3); assert(tmp == 81);
tmp = ipow_exp<0>(5); assert(tmp == 1);
tmp = ipow_exp<1>(5); assert(tmp == 5);
tmp = ipow_exp<2>(5); assert(tmp == 25);
tmp = ipow_exp<3>(5); assert(tmp == 125);
tmp = ipow_exp<4>(5); assert(tmp == 625);
tmp = ipow_exp<0>(-1); assert(tmp == 1);
tmp = ipow_exp<1>(-1); assert(tmp == -1);
tmp = ipow_exp<2>(-1); assert(tmp == 1);
tmp = ipow_exp<3>(-1); assert(tmp == -1);
tmp = ipow_exp<4>(-1); assert(tmp == 1);
tmp = ipow_exp<31>(-1); assert(tmp == -1);
tmp = ipow_exp<32>(-1); assert(tmp == 1);
tmp = ipow_exp<0>(-2); assert(tmp == 1);
tmp = ipow_exp<1>(-2); assert(tmp == -2);
tmp = ipow_exp<2>(-2); assert(tmp == 4);
tmp = ipow_exp<9>(-2); assert(tmp == -512);
tmp = ipow_exp<10>(-2); assert(tmp == 1024);
tmp = ipow_exp<0>(-5); assert(tmp == 1);
tmp = ipow_exp<1>(-5); assert(tmp == -5);
tmp = ipow_exp<2>(-5); assert(tmp == 25);
tmp = ipow_exp<3>(-5); assert(tmp == -125);
tmp = ipow_exp<4>(-5); assert(tmp == 625);
thrown = false;
try {
ipow_exp<0>(0);
} catch (std::logic_error e){
thrown = true;
}
assert(thrown);
// compile time base version
tmp = ipow_base<0>(1); assert(tmp == 0);
tmp = ipow_base<0>(2); assert(tmp == 0);
tmp = ipow_base<0>(3); assert(tmp == 0);
tmp = ipow_base<0>(50); assert(tmp == 0);
tmp = ipow_base<1>(0); assert(tmp == 1);
tmp = ipow_base<1>(1); assert(tmp == 1);
tmp = ipow_base<1>(2); assert(tmp == 1);
tmp = ipow_base<1>(50); assert(tmp == 1);
tmp = ipow_base<2>(0); assert(tmp == 1);
tmp = ipow_base<2>(1); assert(tmp == 2);
tmp = ipow_base<2>(2); assert(tmp == 4);
tmp = ipow_base<2>(3); assert(tmp == 8);
tmp = ipow_base<2>(10); assert(tmp == 1024);
tmp = ipow_base<3>(0); assert(tmp == 1);
tmp = ipow_base<3>(1); assert(tmp == 3);
tmp = ipow_base<3>(2); assert(tmp == 9);
tmp = ipow_base<3>(3); assert(tmp == 27);
tmp = ipow_base<3>(4); assert(tmp == 81);
tmp = ipow_base<5>(0); assert(tmp == 1);
tmp = ipow_base<5>(1); assert(tmp == 5);
tmp = ipow_base<5>(2); assert(tmp == 25);
tmp = ipow_base<5>(3); assert(tmp == 125);
tmp = ipow_base<5>(4); assert(tmp == 625);
tmp = ipow_base<-1>(0); assert(tmp == 1);
tmp = ipow_base<-1>(1); assert(tmp == -1);
tmp = ipow_base<-1>(2); assert(tmp == 1);
tmp = ipow_base<-1>(3); assert(tmp == -1);
tmp = ipow_base<-1>(4); assert(tmp == 1);
tmp = ipow_base<-1>(31); assert(tmp == -1);
tmp = ipow_base<-1>(32); assert(tmp == 1);
tmp = ipow_base<-2>(0); assert(tmp == 1);
tmp = ipow_base<-2>(1); assert(tmp == -2);
tmp = ipow_base<-2>(2); assert(tmp == 4);
tmp = ipow_base<-2>(9); assert(tmp == -512);
tmp = ipow_base<-2>(10); assert(tmp == 1024);
tmp = ipow_base<-5>(0); assert(tmp == 1);
tmp = ipow_base<-5>(1); assert(tmp == -5);
tmp = ipow_base<-5>(2); assert(tmp == 25);
tmp = ipow_base<-5>(3); assert(tmp == -125);
tmp = ipow_base<-5>(4); assert(tmp == 625);
thrown = false;
try {
ipow_base<0>(0);
} catch (std::logic_error e){
thrown = true;
}
assert(thrown);
// full compile time version
tmp = ipow<0,1>(); assert(tmp == 0);
tmp = ipow<0,2>(); assert(tmp == 0);
tmp = ipow<0,3>(); assert(tmp == 0);
tmp = ipow<0,50>(); assert(tmp == 0);
tmp = ipow<1,0>(); assert(tmp == 1);
tmp = ipow<1,1>(); assert(tmp == 1);
tmp = ipow<1,2>(); assert(tmp == 1);
tmp = ipow<1,50>(); assert(tmp == 1);
tmp = ipow<2,0>(); assert(tmp == 1);
tmp = ipow<2,1>(); assert(tmp == 2);
tmp = ipow<2,2>(); assert(tmp == 4);
tmp = ipow<2,3>(); assert(tmp == 8);
tmp = ipow<2,10>(); assert(tmp == 1024);
tmp = ipow<3,0>(); assert(tmp == 1);
tmp = ipow<3,1>(); assert(tmp == 3);
tmp = ipow<3,2>(); assert(tmp == 9);
tmp = ipow<3,3>(); assert(tmp == 27);
tmp = ipow<3,4>(); assert(tmp == 81);
tmp = ipow<5,0>(); assert(tmp == 1);
tmp = ipow<5,1>(); assert(tmp == 5);
tmp = ipow<5,2>(); assert(tmp == 25);
tmp = ipow<5,3>(); assert(tmp == 125);
tmp = ipow<5,4>(); assert(tmp == 625);
tmp = ipow<-1,0>(); assert(tmp == 1);
tmp = ipow<-1,1>(); assert(tmp == -1);
tmp = ipow<-1,2>(); assert(tmp == 1);
tmp = ipow<-1,3>(); assert(tmp == -1);
tmp = ipow<-1,4>(); assert(tmp == 1);
tmp = ipow<-1,31>(); assert(tmp == -1);
tmp = ipow<-1,32>(); assert(tmp == 1);
tmp = ipow<-2,0>(); assert(tmp == 1);
tmp = ipow<-2,1>(); assert(tmp == -2);
tmp = ipow<-2,2>(); assert(tmp == 4);
tmp = ipow<-2,9>(); assert(tmp == -512);
tmp = ipow<-2,10>(); assert(tmp == 1024);
tmp = ipow<-5,0>(); assert(tmp == 1);
tmp = ipow<-5,1>(); assert(tmp == -5);
tmp = ipow<-5,2>(); assert(tmp == 25);
tmp = ipow<-5,3>(); assert(tmp == -125);
tmp = ipow<-5,4>(); assert(tmp == 625);
#ifdef TEST_COMPILE_ERRORS
ipow<0,0>();
#endif
return 0;
}
</code></pre>
<pre><code>$ g++ --version
g++ (Ubuntu 7.4.0-1ubuntu1~18.04.1) 7.4.0
</code></pre>
|
[] |
[
{
"body": "<h1>You might be able to use <code>std::pow()</code> in <code>constexpr</code> expressions in C++11</h1>\n\n<p>Since this post was not tagged \"reinventing-the-wheel\", I want to point out that some compilers (notably GCC) will compile the below C++11 code:</p>\n\n<pre><code>#include <cmath>\n\nconstexpr int ipow(int a, int b) {\n return std::pow(a, b);\n}\n\nint main(int argc, char *argv[]) {\n static_assert(ipow(-5, 3) == -125);\n return ipow(argc, 2);\n}\n</code></pre>\n\n<p>One drawback is that <code>std::pow()</code> converts integer arguments to <code>double</code>, which at run-time may or may not result in slower computation than using <code>int</code>. Also, while for <code>int</code> there is no loss of precision, if you would want to use <code>int64_t</code>, there is a potential loss of precision.</p>\n\n<p>The other drawback, as pointed out by Oliver Schonrock, is that not all compilers allow <code>constexpr</code> use of <code>std::pow()</code>. As explained in <a href=\"https://stackoverflow.com/questions/50477974/constexpr-exp-log-pow\">this post</a>,\n<code>constexpr</code> math functions were only allowed in C++11 but not in C++14. But there are libraries that provide <code>constexpr</code> math functions, see for example <a href=\"https://github.com/bolero-MURAKAMI/Sprout/blob/master/sprout/math/pow.hpp\" rel=\"nofollow noreferrer\">Sprout's <code>pow()</code> implementation</a>.</p>\n\n<h1>Zero to the power zero is one*</h1>\n\n<p>With most programming languages, one usually finds that <a href=\"https://en.wikipedia.org/wiki/Zero_to_the_power_of_zero#IEEE_floating-point_standard\" rel=\"nofollow noreferrer\"><code>pow(0, 0) == 1</code></a>. You should ensure your solution also returns one in that case, to ensure consistency, regardless of your personal feelings about zero to the power zero.</p>\n\n<p>As a bonus, by having a well-defined result for <code>ipow(0, 0)</code>, it no longer throws exceptions, and you can get rid of some of the specializations.</p>\n\n<h1>Catch exceptions by const reference</h1>\n\n<p>Make it a habit to catch exceptions by const reference. Apart from being a little bit faster (although this of course is the least of your worries when exceptions are being thrown), it ensures you don't lose information when the exception thrown is of a derived class. See <a href=\"https://stackoverflow.com/questions/2522299/c-catch-blocks-catch-exception-by-value-or-reference\">this StackOverflow question</a> for more information.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-06T03:33:58.017",
"Id": "460056",
"Score": "0",
"body": "\"following code is valid C++11\". Are you sure? It compiles for me under gcc-9.2. but clang-9 throws \"static_assert expression is not an integral constant expression\". This doesn't mention `constexpr`: https://en.cppreference.com/w/cpp/numeric/math/pow . This caught my eye because I recently personally implemented a limited compile time `pow` exactly because it only works in gcc as a non-standard extension?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-06T07:42:09.397",
"Id": "460080",
"Score": "1",
"body": "Summary of all 3 main compilers. Latest stable of each. https://godbolt.org/z/07b7Ww Only gcc seems to support it. Also tried trunk clang, which doesn't work either."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-06T10:25:40.920",
"Id": "460097",
"Score": "0",
"body": "Woops, it's indeed not guaranteed to be `constexpr`. Apparently it was only *allowed* to be `constexpr` in C++11. Thanks for the godbolt link!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-06T11:12:30.750",
"Id": "460104",
"Score": "0",
"body": "Thanks for the answer! Although I must say 0^0=1 gives me headache :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-06T17:28:14.757",
"Id": "460159",
"Score": "0",
"body": "Heya, sorry I removed the accepted answer. You made some valid points. But I find the other answer a bit more useful so I decided to accept that one instead..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-06T20:37:25.507",
"Id": "460175",
"Score": "0",
"body": "That's perfectly fine, you should indeed accept the answer that is most useful to you!"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-04T14:45:42.180",
"Id": "235072",
"ParentId": "235000",
"Score": "4"
}
},
{
"body": "<h1>Avoid large recursion</h1>\n\n<p>The unspecialized <code>ipow_base()</code> may recurse <code>exponent</code> times before multiplying. Just defer to the general case here:</p>\n\n<pre><code>template<const int base>\nconstexpr int ipow_base(unsigned int exponent)\n{\n return ipow(base, exponent);\n}\n</code></pre>\n\n<h1>Use binary exponentiation for efficiency with larger exponents</h1>\n\n<p>These functions (other than the specializations) scale linearly with the exponent value, but could scale logarithmically like this:</p>\n\n<pre><code>template<const unsigned int exponent>\nconstexpr int ipow_exp(int base)\n{\n return (exponent & 1 ? base : 1) * ipow_exp<exponent/2>(base*base);\n}\n\nconstexpr int ipow(int base, unsigned int exponent)\n{\n if (!exponent && !base) {\n throw std::logic_error(\"0^0 is undefined.\");\n }\n\n if (base == 2) {\n return 1 << exponent;\n }\n\n int result = 1;\n int term = base;\n while (exponent) {\n if (exponent & 1) {\n result *= term;\n }\n term *= term;\n exponent /= 2;\n }\n return result;\n}\n</code></pre>\n\n<h1>Extend to other integer types</h1>\n\n<p>Users would probably like to be able to use any <code>std::is_integral</code> type for <code>base</code> (e.g. <code>unsigned long</code>), so that ought to be a template type.</p>\n\n<h1>Simplify tests for throwing</h1>\n\n<p>We don't need the <code>thrown</code> variable here:</p>\n\n<blockquote>\n<pre><code>thrown = false;\ntry {\n ipow(0,0);\n} catch (std::logic_error e){\n thrown = true;\n}\nassert(thrown);\n</code></pre>\n</blockquote>\n\n<p>Just assert in the <code>try</code> block:</p>\n\n<pre><code>try {\n ipow(0,0);\n assert(false);\n} catch (std::logic_error& e) {\n // expected\n}\n</code></pre>\n\n<p>Better still, use one of the many available test frameworks rather than simple <code>assert()</code>. That would help in several ways, such as detecting multiple failures per run, and showing actual and expected values for comparison.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-06T11:21:35.497",
"Id": "235160",
"ParentId": "235000",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "235160",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-03T11:22:06.507",
"Id": "235000",
"Score": "6",
"Tags": [
"c++",
"template-meta-programming"
],
"Title": "Run-time and Compile-time Versions of Integer Power"
}
|
235000
|
<p>I have a function where I am trying to assign book ids to certain students on registration of a new student.</p>
<pre><code>FOR book_id IN
SELECT a.bookid
FROM books a
WHERE a.isdelete = false and published = true
LOOP
IF NOT EXISTS (select 1 from studentbooks where bookid = book_id and studentid = id) THEN
INSERT INTO studentbooks(bookid, studentid) values (book_id::uuid, id );
END IF;
END LOOP;
</code></pre>
<p>I wrote something like this and it works fine for smaller set of data and under performs when we have more books to loop through. I just wanted a have a review here.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-03T12:51:08.980",
"Id": "459747",
"Score": "0",
"body": "Where does `id` column come from in your code?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-03T13:08:37.230",
"Id": "459751",
"Score": "0",
"body": "I am sorry its an input parameter. The id for the new student"
}
] |
[
{
"body": "<p>Instead of extracting all <code>books</code> and execute a separate sub-query on each <code>FOR</code> loop iteration - we can select only the <em>books</em> that don't have matches in <code>studentbooks</code> table for specified <em>student</em> (presented by <code>id</code> argument) by running PostgreSQL <a href=\"https://www.postgresqltutorial.com/postgresql-left-join/\" rel=\"nofollow noreferrer\"><code>LEFT JOIN</code></a> with specific <code>WHERE</code> clause.</p>\n\n<p>Furthermore, to make it <em>one-shot action</em> - we can <em>insert data from query</em> using <code>INSERT INTO SELECT</code> statement.</p>\n\n<p>The query for the whole task:</p>\n\n<pre><code>INSERT INTO\n studentbooks(bookid, studentid) \n SELECT\n b.bookid, your_function_name.id \n FROM\n books b \n LEFT JOIN\n studentbooks sb \n ON sb.bookid = b.bookid AND studentid = id \n WHERE\n b.isdelete = false AND b.published = true\n AND sb.bookid is NULL;\n</code></pre>\n\n<p>replace <code>your_function_name</code> with your actual function name to refer the function's argument name.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-03T17:51:54.343",
"Id": "235029",
"ParentId": "235003",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "235029",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-03T12:05:06.113",
"Id": "235003",
"Score": "2",
"Tags": [
"sql",
"postgresql"
],
"Title": "Assigning book ids to certain students on registration of a new student"
}
|
235003
|
<p>So, I tried to solve this question and my code did not execute within time-limits.
<a href="https://www.hackerrank.com/challenges/acm-icpc-team" rel="nofollow noreferrer">https://www.hackerrank.com/challenges/acm-icpc-team</a></p>
<p>Here's my code,</p>
<pre><code>from itertools import combinations
nm =input().split()
n = int(nm[0])
m = int(nm[1])
mat=[]
z=[]
for i in range(n):
mat.append(input())
a=combinations(range(1,n+1),2)
for i in a:
count=0
for j in range(m):
if mat[i[0]-1][j]=="0" and mat[i[1]-1][j]=="0":
count=count+1
z.append(m-count)
print(max(z))
print(z.count(max(z)))
</code></pre>
<p>How can I improve it?</p>
|
[] |
[
{
"body": "<p>I don't have much time, and don't see any quick performance suggestions, but,</p>\n\n<pre><code>mat = []\nfor i in range(n):\n mat.append(input())\n</code></pre>\n\n<p>Can be written more terse as a list comprehension:</p>\n\n<pre><code>mat = [input() for _ in range(n)]\n</code></pre>\n\n<p>And note how you never use <code>i</code>. If you don't use a variable, you can indicate that it isn't needed by calling it <code>_</code>. That's a placeholder convention to say that \"I needed to create a variable, but I don't need it\".</p>\n\n<hr>\n\n<pre><code>count=count+1\n</code></pre>\n\n<p>can be</p>\n\n<pre><code>count += 1\n</code></pre>\n\n<hr>\n\n<p>Also, please be more careful with spaces around operators. In some places, you use no spaces, in some places you use one on each side, and then in one case, you have</p>\n\n<pre><code>nm =input().split()\n</code></pre>\n\n<p>I prefer one per side, but regardless of what you choose, you should be consistent. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-03T15:31:01.373",
"Id": "235018",
"ParentId": "235008",
"Score": "2"
}
},
{
"body": "<p><strong>Needless <code>for</code> loop usage</strong> </p>\n\n<p><code>for</code> loops in Python are heavy. Using <code>for</code> loops needlessly leads to performance loss. For instance, rather than doing this:</p>\n\n<pre><code>for j in range(m):\n if mat[i[0]-1][j]==\"0\" and mat[i[1]-1][j]==\"0\":\n</code></pre>\n\n<p>You could just count the number of ones using <code>int()</code>, <code>bin()</code> and <code>|</code> as below:</p>\n\n<pre><code>orResult = int(mat[i[0] - 1], 2) | int(mat[j[0] - 1], 2)\nnumberOfSubjects = bin(orResult).count(\"1\")\n</code></pre>\n\n<p><strong>Confusing usage of <code>count</code></strong></p>\n\n<p>Rather then counting the number of <code>0's</code> and then subtracting it from <code>m</code>, you could initialize <code>count</code> to <code>m</code> and then decrement it each time <code>0's</code> are encountered. Then, in the end, <code>count</code> would denote the number of <code>1's</code>.</p>\n\n<p><strong>Variable naming</strong></p>\n\n<p>Of course, I had to mention this. Variable names are not self-explanatory and it's difficult to understand what they represent exactly. For instance, <code>z</code> means nothing meaningless to me. Please come up with better names. For instance, change</p>\n\n<pre><code>a = combinations(range(1,n+1),2) \n</code></pre>\n\n<p>To</p>\n\n<pre><code>indexPairs = combinations(range(1,n+1),2) \n</code></pre>\n\n<p><strong>Optimised Code</strong></p>\n\n<pre><code>from itertools import combinations\n\nnm = input().split()\nn = int(nm[0])\nm = int(nm[1])\n\nattendees=[]\nfor i in range(n):\n attendees.append(input()) \nindexPairs = combinations(range(1,n+1),2) \n\nmaxNumberOfSubjects = 0\nnumberOfBestTeams = 0\nfor pair in indexPairs:\n orResult = int(attendees[pair[0] - 1], 2) | int(attendees[pair[1] - 1], 2)\n numberOfSubjects = bin(orResult).count(\"1\")\n if maxNumberOfSubjects == numberOfSubjects:\n numberOfBestTeams += 1\n elif maxNumberOfSubjects < numberOfSubjects:\n maxNumberOfSubjects = numberOfSubjects\n numberOfBestTeams = 1 \n\nprint (maxNumberOfSubjects)\nprint (numberOfBestTeams) \n</code></pre>\n\n<p>I tested the code and it passed all the test cases.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-03T18:40:31.380",
"Id": "235034",
"ParentId": "235008",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "235034",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-03T12:36:47.780",
"Id": "235008",
"Score": "2",
"Tags": [
"python",
"algorithm",
"python-3.x",
"programming-challenge",
"time-limit-exceeded"
],
"Title": "Find all pairs of numbers such that the number of binary 1's in their OR is maximum"
}
|
235008
|
<p>I have a List of Objects containing following structure</p>
<pre><code>public class DaySpan{
private LocalDate date;
private Integer numberOfDays;
..
..
//getters & setters
}
</code></pre>
<p>Lets say the list contains 3 instances of above classes with data (date is in dd/mm/yyyy)</p>
<ul>
<li>04/02/2020 3</li>
<li>03/02/2020 5</li>
<li>01/02/2020 1</li>
</ul>
<p>Then I need ouput for count of each day that is getting overlapped in number of days
For example the first record will translate to 04/02/2020, 05/02/2020, 06/02/2020
Second record will translate to 03/02/2020, 04/02/2020, 05/02/2020, 06/02/2020, 07/02/2019 and the final record will translate to 01/02/2020
So the output will be</p>
<ul>
<li>01/02/2020 - 1</li>
<li>03/02/2020 - 1</li>
<li>04/02/2020 - 2</li>
<li>05/02/2020 - 2</li>
<li>06/02/2020 - 2</li>
<li>07/02/2020 - 1</li>
</ul>
<p>The code I have written is </p>
<pre><code> public void getDayCount(List<DaySpan> daySpans){
Map<Object, Long> days = new HashMap();
days = daySpans.stream()
.map(this::getDays)
.collect(
Collector.of(ArrayList::new,
List::addAll,(left, right) -> { left.addAll(right); return left; }
)
)
.stream()
.collect(
Collectors.groupingBy(Function.identity(), Collectors.counting()));
days.entrySet().forEach(System.out::println);
}
public List<LocalDate> getDays(DaySpan daySpan) {
return Stream.iterate(daySpan.getStartDate(), d -> d.plusDays(1)).limit(daySpan.getNumberOfDays())
.collect(Collectors.toList());
}
</code></pre>
<p>Is there a better way?</p>
|
[] |
[
{
"body": "<p>Yes, you can use flatMap to convert a stream of streams into a single stream, which achieves your goal of accumulating the results of all the getDays calls into one collection:</p>\n\n<pre><code>public void getDayCount(List<DaySpan> daySpans) {\n Map<Object, Long> days = daySpans.stream()\n .map(this::getDays)\n .flatMap(o -> o.stream())\n .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));\n\n days.entrySet().forEach(System.out::println);\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-03T17:42:11.500",
"Id": "235027",
"ParentId": "235012",
"Score": "1"
}
},
{
"body": "<p>You came far to a good solution.</p>\n\n<pre><code>public void getDayCount(List<DaySpan> daySpans){\n Map<LocalDate, Long> freqs = daySpans.stream()\n .flatMap(daySpan ->\n IntStream.range(0, daySpan.numberOfDays)\n .mapToObj(i -> daySpan.date.plusDays(i)))\n .collect(\n Collectors.groupingBy(Function.identity(), Collectors.counting()));\n\n freqs.entrySet().stream()\n .sorted(Map.Entry::getKey)\n .forEach(System.out::println);\n}\n</code></pre>\n\n<ul>\n<li>Creating a <code>Stream<LocalDate></code> for some DaySpan is simply realized by an <code>IntStream.range</code>.</li>\n<li>A flatMap makes a larger Stream of LocalDates.</li>\n<li>Turning them into a counting map you already did.</li>\n<li>Sorting them on the date remains.</li>\n<li>You printed the entries as Entry, so I kept it that way.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-03T18:07:50.970",
"Id": "235031",
"ParentId": "235012",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "235031",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-03T13:50:01.300",
"Id": "235012",
"Score": "1",
"Tags": [
"java"
],
"Title": "Getting days count from start day and number of day for a group of days in Java 8"
}
|
235012
|
<p>I am working on a Units library for a personal project that is a physics-heavy C#/Unity3D game, and I am looking to improve it in a few areas:</p>
<ol>
<li><p>Is there a way to reduce the code duplication?</p>
</li>
<li><p>Is performance going to be a problem? Is there anything I can do to improve performance?</p>
</li>
<li><p>Can I hide the <code>value</code> member variable so it is not visible to the rest of the program, but only within this namespace?</p>
</li>
<li><p>Are the Equals() and GetHashCode() methods implemented correctly?</p>
</li>
<li><p>Are there other changes that I should do to make this more idiomatic C#?</p>
</li>
</ol>
<pre>[Serializable]
public struct Meter
{
[SerializeField]
internal double value;
public Meter(double value) => this.value = value;
public static Meter operator +(Meter m) => m;
public static Meter operator -(Meter m) => new Meter() { value = -m.value };
public static Meter operator +(Meter m1, Meter m2) => new Meter() { value = m1.value + m2.value };
public static Meter operator -(Meter m1, Meter m2) => new Meter() { value = m1.value - m2.value };
public static Meter operator *(Meter m, double d) => new Meter() { value = m.value * d };
public static Meter operator *(double d, Meter m) => new Meter() { value = m.value * d };
public static Meter operator /(Meter m, double d) => new Meter() { value = m.value / d };
public static double operator /(Meter m1, Meter m2) => m1.value / m2.value;
public static MeterSquared operator *(Meter m1, Meter m2) => new MeterSquared() { value = m1.value * m2.value };
public static MeterPerSecond operator /(Meter m, Second s) => new MeterPerSecond() { value = m.value / s.value };
public readonly static Meter zero = new Meter() { value = 0.0 };
public override bool Equals(object obj) => obj is Meter other ? value.Equals(other.value) : false;
public override int GetHashCode() => value.GetHashCode();
public static bool operator ==(Meter m1, Meter m2) => m1.value == m2.value;
public static bool operator !=(Meter m1, Meter m2) => m1.value != m2.value;
}
[Serializable]
public struct Second
{
[SerializeField]
internal double value;
public Second(double value) => this.value = value;
public static Second operator +(Second s) => s;
public static Second operator -(Second s) => new Second() { value = -s.value };
public static Second operator +(Second s1, Second s2) => new Second() { value = s1.value + s2.value };
public static Second operator -(Second s1, Second s2) => new Second() { value = s1.value - s2.value };
public static Second operator *(Second s, double d) => new Second() { value = s.value * d };
public static Second operator /(Second s, double d) => new Second() { value = s.value / d };
public static double operator /(Second s1, Second s2) => s1.value / s2.value;
public readonly static Second zero = new Second() { value = 0.0 };
public override bool Equals(object obj) => obj is Second other ? value.Equals(other.value) : false;
public override int GetHashCode() => value.GetHashCode();
public static bool operator ==(Second s1, Second s2) => s1.value == s2.value;
public static bool operator !=(Second s1, Second s2) => s1.value != s2.value;
}
/// <summary>
/// m / s, velocity
/// </summary>
[Serializable]
public struct MeterPerSecond
{
[SerializeField]
internal double value;
public MeterPerSecond(double value) => this.value = value;
public static MeterPerSecond operator +(MeterPerSecond m) => m;
public static MeterPerSecond operator -(MeterPerSecond m) => new MeterPerSecond() { value = -m.value };
public static MeterPerSecond operator +(MeterPerSecond m1, MeterPerSecond m2) => new MeterPerSecond() { value = m1.value + m2.value };
public static MeterPerSecond operator -(MeterPerSecond m1, MeterPerSecond m2) => new MeterPerSecond() { value = m1.value - m2.value };
public static MeterPerSecond operator *(MeterPerSecond m, double d) => new MeterPerSecond() { value = m.value * d };
public static MeterPerSecond operator /(MeterPerSecond m, double d) => new MeterPerSecond() { value = m.value / d };
public static Meter operator *(MeterPerSecond m, Second s) => new Meter() { value = m.value * s.value };
public static MeterPerSecondSquared operator /(MeterPerSecond m, Second s) => new MeterPerSecondSquared() { value = m.value * s.value };
public readonly static MeterPerSecond zero = new MeterPerSecond() { value = 0.0 };
public override bool Equals(object obj) => obj is MeterPerSecond other ? value.Equals(other.value) : false;
public override int GetHashCode() => value.GetHashCode();
public static bool operator ==(MeterPerSecond m1, MeterPerSecond m2) => m1.value == m2.value;
public static bool operator !=(MeterPerSecond m1, MeterPerSecond m2) => m1.value != m2.value;
}
</pre>
<p>Example usage:</p>
<pre>public class AstronomicalObject2 : MonoBehaviour
{
public string astronomicalName;
public Meter radius;
[Header("Provide One")]
public Kilogram mass;
public MeterPerSecondSquared surfaceGravity;
public KilogramPerCubicMeter meanDensity;
[Header("Calculated")]
public Meter circumference;
public MeterSquared surfaceArea;
public MeterCubed volume;
public StandardGravitationParameter gm;
[Header("Atmo-Required")]
public Pascal atmosphereSurfacePressure = new Pascal(101325);
public Meter atmosphereScaleHeight = new Meter(8500);
[Header("Atmo-Calculated")]
public Meter atmosphereMaxHeight;
public readonly Pascal atmospherePressureCutoff = new Pascal(1);
private Kilogram old_mass;
private MeterPerSecondSquared old_surfaceGravity;
private KilogramPerCubicMeter old_meanDensity;
void OnEnable()
{
old_mass = mass;
old_surfaceGravity = surfaceGravity;
old_meanDensity = meanDensity;
}
void OnValidate()
{
circumference = 2.0 * Math.PI * radius;
surfaceArea = circumference * 2.0 * radius; // 4.0 * Math.PI * radius * radius;
volume = surfaceArea * radius / 3.0; // 4.0 / 3.0 * Math.PI * radius * radius * radius;
if (mass != old_mass)
{
gm = GravitationConstant.G * mass;
surfaceGravity = gm / (radius * radius);
meanDensity = mass / volume;
}
else if (surfaceGravity != old_surfaceGravity)
{
mass = new Kilogram(surfaceGravity.value * radius.value * radius.value / GravitationConstant.G.value);
gm = GravitationConstant.G * mass;
meanDensity = mass / volume;
}
else if (meanDensity != old_meanDensity)
{
mass = meanDensity * volume;
gm = GravitationConstant.G * mass;
surfaceGravity = gm / (radius * radius);
}
else
{
// Something else changed
// Make sure all the calculated values are accurate, assuming that the mass is the desired value
gm = GravitationConstant.G * mass;
surfaceGravity = gm / (radius * radius);
meanDensity = mass / volume;
}
old_mass = mass;
old_surfaceGravity = surfaceGravity;
old_meanDensity = meanDensity;
// Atmo
if (atmosphereSurfacePressure.value > 0)
{
atmosphereMaxHeight = -atmosphereScaleHeight * Math.Log(atmospherePressureCutoff / atmosphereSurfacePressure);
}
else
{
atmosphereMaxHeight = Meter.zero;
}
}
}
</pre>
<p>Alternative without the Units classes:</p>
<pre>// Excerpt from the OnValidate() method:
circumference_m = 2.0 * Math.PI * radius_m; // m
surfaceArea_m2 = circumference_m * 2.0 * radius_m; // 4.0 * Math.PI * radius * radius = m^2
volume_m3 = surfaceArea_m2 * radius_m / 3.0; // 4.0 / 3.0 * Math.PI * radius * radius * radius = m^3
if (mass_kg != old_mass)
{
gm = PhysicsConstants.G * mass_kg; // (m^3/(kg*s^2)) * kg = m^3/s^2
surfaceGravity_m_s = gm / (radius_m * radius_m); // (m^3/s^2) / m^2 = m/s^2
meanDensity_kg_m3 = mass_kg / volume_m3; // kg / m^3 = kg/m^3
}
else if (surfaceGravity_m_s != old_surfaceGravity)
{
mass_kg = surfaceGravity_m_s * radius_m * radius_m / PhysicsConstants.G; // (m/s^2 * m * m) / (m^3/(kg*s^2)) = kg
gm = PhysicsConstants.G * mass_kg; // (m^3/(kg*s^2)) * kg = m^3/s^2
meanDensity_kg_m3 = mass_kg / volume_m3; // kg / m^3 = kg/m^3
}
else if (meanDensity_kg_m3 != old_meanDensity)
{
mass_kg = meanDensity_kg_m3 * volume_m3; // kg/m^3 * m^3 = kg
gm = PhysicsConstants.G * mass_kg; // (m^3/(kg*s^2)) * kg = m^3/s^2
surfaceGravity_m_s = gm / (radius_m * radius_m); // (m^3/s^2) / m^2 = m/s^2
}
else
{
// Something else changed
// Make sure all the calculated values are accurate, assuming that the mass is the desired value
gm = PhysicsConstants.G * mass_kg; // (m^3/(kg*s^2)) * kg = m^3/s^2
surfaceGravity_m_s = gm / (radius_m * radius_m); // (m^3/s^2) / m^2 = m/s^2
meanDensity_kg_m3 = mass_kg / volume_m3; // kg / m^3 = kg/m^3
}
</pre>
<p>Thanks for looking at this!</p>
<p><strong>Edit</strong>: Added the example usage, plus an example without the Units classes. The purpose of this library is to avoid units errors, like using velocity (m/s) when it should be length (m) or something like that. I am not sure if this is worth the extra effort though... On a work project in the past, I used a nice units library but it was in C++ and made extensive use of templates to make it easy to use and easy to maintain and performant. Not sure that I can achieve the same in C#.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-03T15:07:01.113",
"Id": "459767",
"Score": "0",
"body": "would you have to have a new struct for every new unit? so for kilometres or milliseconds?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-03T18:09:57.333",
"Id": "459783",
"Score": "0",
"body": "No, I was only thinking of having a type for the base unit, meters, and not one for each prefix (kilometer, millimeter, etc). I also do not think I will create a type for non-metric units (feet, etc)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-03T20:40:46.510",
"Id": "459809",
"Score": "0",
"body": "@Sirius5 whats the idea of those structs in the first place? Having fluent interfaces? Also, `MeterSquared` and `MeterPerSecondSquared` are not present."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-04T02:04:41.470",
"Id": "459834",
"Score": "0",
"body": "Having fluent interfaces and to prevent errors due to using the wrong units in a calculation (like multiplying mass times length instead of length times length, or something). These three structs are just an example of the more than a dozen that I have implemented so far."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-04T02:09:25.093",
"Id": "459836",
"Score": "0",
"body": "One example of a calculation in my code is: ```mass = surfaceGravity * radius * radius / PhysicsConstants.G;```, for which the units are: ```kg = m/s^2 * m * m / (m^3/(kg*s^2))```. So I need definitions for kg, m/s^2, m, and m^3/(kg*s^2). But I also need m^2/s^2, because it first multiplies m/s^2 * m, then m^3/s^2 because it multiplies by another m. The list of unit types is becoming unwieldy, especially with how many lines of code I have to maintain for each struct. If the definitions were shorter, this might be more manageable."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-04T08:47:33.183",
"Id": "459850",
"Score": "0",
"body": "@Sirius5 would you mind showing us some of the calculations part, and also some of the actual code that leaded you to this approach (or examples that covers most parts) to be on the same picture."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-04T08:56:47.013",
"Id": "459851",
"Score": "0",
"body": "@Sirius5 and what is the base unit in your application."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-20T17:18:03.087",
"Id": "461911",
"Score": "0",
"body": "@iSR5 Sorry, didn't mean to abandon this question. I edited in a usage example.\nI'm using SI units (https://en.wikipedia.org/wiki/International_System_of_Units), i.e. Meter/Kilogram/Seconds, as the base units within the program."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-25T15:28:12.263",
"Id": "480007",
"Score": "0",
"body": "So how does the user know how many meters there are in a given instance? Or how many seconds? I think you need the comparison operators against `double` as you have the arithmetic operators. It would probably also behoove you to override `ToString()` to have a coherent view of what the value should be."
}
] |
[
{
"body": "<blockquote>\n <p>Can I hide the <code>value</code> member variable so it is not visible to the rest of the program, but only within this namespace?</p>\n</blockquote>\n\n<p>I prefer to move independent modules to external dll library (libraries), in which case I may use <code>internals</code> magic and then expose only <code>public</code> classes to outer world. Unity3d's Assembly Definition system basically does the same thing.</p>\n\n<p>In your case you could make <code>value</code> private and create public property:</p>\n\n<pre><code>[SerializeField]\nprivate double value;\npublic double Value => value;\n</code></pre>\n\n<p>So now external scripts cannot modify internal state of the struct, which generally is desired behavior.</p>\n\n<blockquote>\n <p>Are the Equals() and GetHashCode() methods implemented correctly?</p>\n</blockquote>\n\n<p>Equals() can be simplified a little:</p>\n\n<pre><code>obj is Meter other && value.Equals(other.value);\n</code></pre>\n\n<p>GetHashCode(), on the other hand, references <code>value</code> field, which is mutable. Part of my answer already covered it, but if you'll keep your <code>value</code> internal, evil might happen:</p>\n\n<pre><code>var unit = new Unit(1);\nvar dictionary = new Dictionary<Unit, int> {[unit] = 1};\nunit.value = 2;\nAssert.True(dictionary.ContainsKey(unit)); // Is it true? Is it false?\n</code></pre>\n\n<p>You might think it's convenient that <code>Unit</code> with new value represents completely different entity which no longer exists inside the dictionary... Or you might think that <code>Unit</code> is still the same object whatever its value is. Or you might accidentally modify <code>value</code> and wonder why your dictionary returns KeyNotFoundException.</p>\n\n<blockquote>\n <p>Are there other changes that I should do to make this more idiomatic C#?</p>\n</blockquote>\n\n<p>There might be problem with equality operations. Consider following example:</p>\n\n<pre><code>double a = 0.1d;\ndouble b = 0.2d;\ndouble c = 0.3d;\nAssert.True(a + b == c); // Actually it's false.\n</code></pre>\n\n<p>I prefer instead of <code>m1.value == m2.value</code> use <code>Math.Abs(m1.value - m2.value) < tolerance</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-27T12:31:16.507",
"Id": "236227",
"ParentId": "235013",
"Score": "1"
}
},
{
"body": "<p>Extending from my comment on the question, I'd probably go ahead and implement the less than and greater than operators and a handful of interfaces like the underlying <code>double</code> has. I'm also a big proponent of the <code>struct</code> itself being immutable. The result looks something like (I only did <code>Meter</code> for this exercise):</p>\n<pre><code>[Serializable]\npublic struct Meter : IComparable, IFormattable, IConvertible, IComparable<Meter>, IEquatable<Meter>\n{\n public Meter(double value) => this.Value = value;\n\n public static Meter Zero { get; } = new Meter(0.0);\n\n internal double Value { get; }\n\n public static Meter operator +(Meter m) => m;\n\n public static Meter operator -(Meter m) => new Meter(-m.Value);\n\n public static Meter operator +(Meter m1, Meter m2) => new Meter(m1.Value + m2.Value);\n\n public static Meter operator -(Meter m1, Meter m2) => new Meter(m1.Value - m2.Value);\n\n public static Meter operator *(Meter m, double d) => new Meter(m.Value * d);\n\n public static Meter operator *(double d, Meter m) => new Meter(m.Value * d);\n\n public static Meter operator /(Meter m, double d) => new Meter(m.Value / d);\n\n public static double operator /(Meter m1, Meter m2) => m1.Value / m2.Value;\n\n public static MeterSquared operator *(Meter m1, Meter m2) => new MeterSquared(m1.Value * m2.Value);\n\n public static MeterPerSecond operator /(Meter m, Second s) => new MeterPerSecond(m.Value / s.Value);\n\n public static bool operator ==(Meter m1, Meter m2) => m1.Value == m2.Value;\n\n public static bool operator !=(Meter m1, Meter m2) => m1.Value != m2.Value;\n\n public static bool operator <(Meter m1, Meter m2) => m1.Value < m2.Value;\n\n public static bool operator <=(Meter m1, Meter m2) => m1.Value <= m2.Value;\n\n public static bool operator >(Meter m1, Meter m2) => m1.Value > m2.Value;\n\n public static bool operator >=(Meter m1, Meter m2) => m1.Value >= m2.Value;\n\n public override bool Equals(object obj) => obj is Meter other && this.Equals(other);\n\n public bool Equals(Meter other) => this.Value.Equals(other.Value);\n\n public override int GetHashCode()\n {\n unchecked\n {\n return 17 * this.Value.GetHashCode();\n }\n }\n\n public string ToString(string format, IFormatProvider formatProvider) => this.Value.ToString(format, formatProvider) + "m";\n\n public override string ToString() => this.ToString(null, CultureInfo.CurrentCulture);\n\n public string ToString(IFormatProvider provider) => this.ToString(null, provider);\n\n public int CompareTo(object obj)\n {\n if (obj is null)\n {\n return 1;\n }\n\n if (!(obj is Meter m))\n {\n throw new ArgumentException("Can only compare with another Meter.");\n }\n\n return this.CompareTo(m);\n }\n\n public int CompareTo(Meter other)\n {\n if (this < other)\n {\n return -1;\n }\n\n if (this > other)\n {\n return 1;\n }\n\n return 0;\n }\n\n public TypeCode GetTypeCode() => TypeCode.Double;\n\n public bool ToBoolean(IFormatProvider provider) => throw new InvalidCastException($"Cannot cast from {nameof(Meter)} to {nameof(Boolean)}");\n\n public char ToChar(IFormatProvider provider) => throw new InvalidCastException($"Cannot cast from {nameof(Meter)} to {nameof(Char)}");\n\n public sbyte ToSByte(IFormatProvider provider) => throw new InvalidCastException($"Cannot cast from {nameof(Meter)} to {nameof(SByte)}");\n\n public byte ToByte(IFormatProvider provider) => throw new InvalidCastException($"Cannot cast from {nameof(Meter)} to {nameof(Byte)}");\n\n public short ToInt16(IFormatProvider provider) => throw new InvalidCastException($"Cannot cast from {nameof(Meter)} to {nameof(Int16)}");\n\n public ushort ToUInt16(IFormatProvider provider) => throw new InvalidCastException($"Cannot cast from {nameof(Meter)} to {nameof(UInt16)}");\n\n public int ToInt32(IFormatProvider provider) => throw new InvalidCastException($"Cannot cast from {nameof(Meter)} to {nameof(Int32)}");\n\n public uint ToUInt32(IFormatProvider provider) => throw new InvalidCastException($"Cannot cast from {nameof(Meter)} to {nameof(UInt32)}");\n\n public long ToInt64(IFormatProvider provider) => throw new InvalidCastException($"Cannot cast from {nameof(Meter)} to {nameof(Int64)}");\n\n public ulong ToUInt64(IFormatProvider provider) => throw new InvalidCastException($"Cannot cast from {nameof(Meter)} to {nameof(UInt64)}");\n\n public float ToSingle(IFormatProvider provider) => throw new InvalidCastException($"Cannot cast from {nameof(Meter)} to {nameof(Single)}");\n\n public double ToDouble(IFormatProvider provider) => this.Value;\n\n public decimal ToDecimal(IFormatProvider provider) => throw new InvalidCastException($"Cannot cast from {nameof(Meter)} to {nameof(Decimal)}");\n\n public DateTime ToDateTime(IFormatProvider provider) => throw new InvalidCastException($"Cannot cast from {nameof(Meter)} to {nameof(DateTime)}");\n\n public object ToType(Type conversionType, IFormatProvider provider)\n {\n if (conversionType is null)\n {\n throw new ArgumentNullException(nameof(conversionType));\n }\n\n if (conversionType == typeof(Meter))\n {\n return this;\n }\n\n if (conversionType == typeof(double))\n {\n return this.Value;\n }\n\n if (conversionType == typeof(string))\n {\n return this.ToString(provider);\n }\n\n throw new InvalidCastException($"Cannot cast from {nameof(Meter)} to {conversionType.Name}");\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-25T18:29:32.853",
"Id": "244521",
"ParentId": "235013",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-03T13:50:37.167",
"Id": "235013",
"Score": "7",
"Tags": [
"c#",
"unity3d"
],
"Title": "Strongly typed unit system in C#"
}
|
235013
|
<p>I have wanna learn more of ways to improve my code and also, make it look different. I want to see different approach but have the same result.</p>
<pre><code>def text():
print('What message(s) are you trying to encrypt?')
return input()
def shift():
key = 0;
while True:
print('Enter the key number (1-%s)' % (keymax))
key = int(input())
if (key >= 1 and key <= keymax):
return key
def encrypt(string, shift):
hidden = ''
for char in string:
if char.isalpha() == False:
hidden = hidden + char
elif char.isupper():
hidden = hidden + chr((ord(char) + shift - 65) % 26 + 65)
else:
hidden = hidden + chr((ord(char) + shift - 97) % 26 + 97)
return hidden
text = text()
s = shift()
print("original string: ", text)
print("after encryption: ", encrypt(text, s))
</code></pre>
<p>It would be gladly appreciated if anyone could lend a hand or help out! :)</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-03T14:08:51.083",
"Id": "459760",
"Score": "2",
"body": "`text = text()` be careful! Try to call text again. ;-)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-03T14:37:58.200",
"Id": "459764",
"Score": "0",
"body": "@JaideepShekhar I see, thank you!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-03T14:41:43.233",
"Id": "459766",
"Score": "0",
"body": "keymax is missing."
}
] |
[
{
"body": "<p>Just a couple of small things you could improve/change on your code:</p>\n\n<ol>\n<li><p>Unnecessary function/print statement. You can just do <code>text = input('What message ... encrypt?\\n')</code> instead of making an extra function for it an using a seperate print statement.\nThe same goes for the input statement in the shift function, you can put the text of the print statement inside of the input. </p></li>\n<li><p>Unnecessary default value for variable.\nIn the shift function you assign the value 0 to the variable key on forehand. But as you never use it outside the <code>while True</code> statement this is unnecessary. This line can be removed.</p></li>\n<li><p>'Magic numbers'. Inside the encrypt function you use the ascii codes 65, 26 and 97 to quickly convert the characters. While their meaning might be obvious to you (and in this trivial case to most people) it is never a good idea to do this. It is cleaner to make a variable on top of your program in uppercase defining the value. So something like: <code>UPPER_ASCII_SHIFT = 65</code> and then using that variable in the rest of the code. This way it is much easier to read for someone else. This is also a big theme in the cs50 course where this programming problem is originally from. </p></li>\n<li><p>Try choosing clearer names for variables that immediately clarify their use and content. Something like <code>hidden</code> is a bit ambiguous, maybe <code>encrypted_string</code> is better? Also try to avoid single letter variable names like <code>s</code>, but rather call it something like <code>shift_distance</code>. </p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-03T14:38:10.277",
"Id": "459765",
"Score": "0",
"body": "Thanks a lot!, this was very helpful fro you!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-03T14:26:15.177",
"Id": "235016",
"ParentId": "235015",
"Score": "3"
}
},
{
"body": "<p>I spent a little time doing some cleanup and here's what I ended up with:</p>\n\n<pre><code>NUM_LETTERS = 26\n\ndef get_text() -> str:\n return input('What message(s) are you trying to encrypt? ')\n\ndef get_shift(shift_max: int) -> int:\n try:\n key = int(input('Enter the key number (1-%s) ' % (shift_max)))\n assert 1 <= key <= shift_max\n except (AssertionError, ValueError):\n return get_shift(shift_max)\n else:\n return key\n\ndef encrypt(text: str, shift: int) -> str:\n\n def encrypt_char(char: str) -> str:\n if not char.isalpha():\n return char\n alpha = ord('A') if char.isupper() else ord('a')\n return chr((ord(char) + shift - alpha) % NUM_LETTERS + alpha)\n\n return ''.join([encrypt_char(char) for char in text])\n\ntext = get_text()\nshift = get_shift(NUM_LETTERS)\n\nprint(\"original string: \", text)\nprint(\"after encryption: \", encrypt(text, shift))\n</code></pre>\n\n<p>Notable changes:</p>\n\n<ol>\n<li><p>No magic numbers. I used <code>ord('A')</code> for the ASCII codes and defined <code>NUM_LETTERS</code> for the shift operation.</p></li>\n<li><p>Changed function names to match what they're doing (e.g. your <code>shift</code> function didn't actually shift anything, it just got the shift value from the user, so I renamed it <code>get_shift</code>).</p></li>\n<li><p>Your shift function didn't handle non-int inputs, so I fixed that, and since that's driven by a raised exception I made the bounds check work that way too. Just for fun and to demonstrate other ways of doing the same thing, I made it loop via recursion since that lets you get rid of the <code>while</code> construct and reduces the indentation (this isn't necessarily always a good idea in Python because if you recurse enough times it'll blow the stack, but for this case if the user enters garbage ten thousand times it's probably fine to have the script exit, lol).</p></li>\n<li><p>I broke the character encryption logic into its own mini-function, which makes it easy to do the full string encryption as a list comprehension statement.</p></li>\n<li><p>DRY (Don't Repeat Yourself) -- since the character shifting logic is identical except for what the start of the alphabet is, I combined those two lines into one.</p></li>\n<li><p>Type annotations!</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-03T15:46:42.763",
"Id": "459771",
"Score": "0",
"body": "The recursion in `get_shift` does not look that good, I would replace it with a while loop. Also you missed the return type annotation of `encrypt`. Except for that - great."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-04T14:16:08.363",
"Id": "459883",
"Score": "0",
"body": "I see, this was very helpful. I really appreciate your time!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-26T19:12:51.183",
"Id": "462731",
"Score": "0",
"body": "can you add number also?"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-03T15:41:51.117",
"Id": "235020",
"ParentId": "235015",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-03T14:01:40.633",
"Id": "235015",
"Score": "1",
"Tags": [
"python"
],
"Title": "Improvements with caesar cipher encryption"
}
|
235015
|
<p>I am receiving JSON from a service API (Airtable) that returns an object with a single key <code>records</code> which is an array of objects. These objects have most of their information in a nested object called <code>fields</code> . Like so:</p>
<pre><code>{
"records": [
{
"id": "recC3HgjwICxlg9CE",
"fields": {
"Title": "Software engineer",
"Name": "Cameron Toth",
...
</code></pre>
<p>I wrote a function (currently an extension to <code>Data</code>, will move to i.e. Alamofire) that returns a flattened JSON list, with <code>fields</code> keys moved to the parent object, optionally remapping key names. </p>
<p>I'd especially appreciate feedback on my use of <code>guard</code>/<code>let</code>/<code>throw</code></p>
<pre><code>extension Data {
func airtableFlattenedJson(_ mapping: [String: String]? = nil) throws -> [[String : Any]] {
let json = try JSONSerialization.jsonObject(with: self, options: [])
guard let casted = json as? [String: [[String: Any]]] else { throw AirtableParsingError.jsonCouldNotCast }
guard var records = casted["records"] else { throw AirtableParsingError.noRecordsFound }
for (index, record) in records.enumerated() {
var updated = record
guard let fields = record["fields"] as? [String: Any] else { continue }
for (key, value) in fields {
if let mapped = mapping?[key] {
updated[mapped] = value
} else {
updated[key] = value
}
}
updated.removeValue(forKey: "fields")
records[index] = updated
}
return records
}
}
enum AirtableParsingError: Error {
case jsonCouldNotCast
case noRecordsFound
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-05T18:35:49.460",
"Id": "460023",
"Score": "1",
"body": "why are you not using [jsondecoder class](https://developer.apple.com/documentation/foundation/jsondecoder) to parse the JSON?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-08T19:44:22.513",
"Id": "460472",
"Score": "0",
"body": "1. Why you didn't create separate custom class `AirtableRecord` and parse data to array of `AirtableRecord`\n2. I would vote for parsing all fields to appropriate properties of model"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-09T21:46:46.750",
"Id": "460674",
"Score": "0",
"body": "@VitaliyGozhenko @Suryakant the code consuming this result expects an array of `[String: Any]` dictionaries"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-17T08:41:21.110",
"Id": "468798",
"Score": "0",
"body": "Are the keys in the `fields` field always the same ? as in, are they always the same object (`title`, `name`, ...)?"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-03T15:46:50.007",
"Id": "235021",
"Score": "0",
"Tags": [
"swift",
"ios"
],
"Title": "Swift for flattening JSON nested objects"
}
|
235021
|
<p>I need to write a VBA code routine with an efficient way to replace blank cells with values from another cell. For example, my worksheet has some blank cells on random rows in column D. I want to replace these with the value on the same row in column A. In other words, go down all the rows and if column D is blank, replace it with column A.</p>
<p>I wrote some code that "walks" down every row of the worksheet looking for blanks in column D and copying the values from A into D, but it's ridiculously slow (some of these worksheets have more than half a million rows!)</p>
<pre><code> .Range("D1", Range("D1048576").End(xlUp)).Select
Set A = XL.Selection
For Each B In A.Rows
If Len(B.Value & vbNullString) = 0 Then
B.FormulaR1C1 = "=RC[-3]"
End If
DoEvents
Next
</code></pre>
<p>Any suggestions?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-03T19:07:09.020",
"Id": "459793",
"Score": "0",
"body": "I set the xl application to Visible=False when this is running"
}
] |
[
{
"body": "<p>try this code. It assumes that the worksheet with data is active.</p>\n\n<pre><code>Sub ReplaceCodeReview235023()\n With ActiveSheet.Columns(\"D\")\n .SpecialCells(xlCellTypeBlanks).FormulaR1C1 = \"=RC[-3]\"\n End With\nEnd Sub\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-03T18:39:37.987",
"Id": "459788",
"Score": "4",
"body": "Welcome to code review, where we review code and provide insightful observations that can help the asker improve their code. Answers are required to make at least one insightful observation about the users code and can but generally don't include alternate solutions. Alternate solutions by themselves are considered poor answers and may be down voted and deleted."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-03T19:32:16.577",
"Id": "459794",
"Score": "0",
"body": "Wow, much fast than my way, Thanks!"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-03T17:49:39.900",
"Id": "235028",
"ParentId": "235023",
"Score": "1"
}
},
{
"body": "<p>It is good to use offset and find empty cells just using (.Value = \"\"). Declaring all variables will also help you at debugging. If this will become a habit, it may be helpful in case of more complicated algorithms.\nNo need to select anything for such an iteration.\nIf you use VBA, why using formulas which will increase the workbook size? </p>\n\n<pre><code>Dim sh As Worksheet, rng As Range, cel As Range, lastRow As Long\n Set sh = ActiveSheet 'change it with your necessary sheet\n lastRow = sh.Cells(sh.Rows.count, \"D\").End(xlUp).Row\n Set rng = sh.Range(\"D1:D\" & lastRow)\n For Each cel In rng\n If cel.Value = \"\" Then cel.Value = cel.Offset(0, -3)\n Next\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-06T09:05:16.257",
"Id": "235155",
"ParentId": "235023",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "235028",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-03T16:34:56.663",
"Id": "235023",
"Score": "2",
"Tags": [
"vba",
"excel"
],
"Title": "Excel VBE code find and replace"
}
|
235023
|
<p>I have been tormented by the question of how to handle parameter errors by consumers of my modules, and also in classes which are extended from base classes. The particular sort of concern I have is around map keys in various utility classes. What if the consumer provides a key that doesn't exist in the collection, or attempts to add a new member with a key that already exists.</p>
<p>For example, lets say I have a collection class called 'SortedMap' which enables a user to enter an item in a particular position in the collection and then enables the user to retrieve the item by its position in the collection or by its key, and also enables the user to change the position of an item in the collection by modifying its sort property:</p>
<pre><code>interface MapPosition {
sort: number;
index: number;
}
export interface MapItem {
id: string;
index: number;
sort: number;
}
export class SortedMap<T extends MapItem> {
private _list: Array<T>;
private _map: Map<string, T>;
private _sorting: boolean; //status variable to prevent recursive
//calls in sortChangehandler.
private _positionMap: Map<string, MapPosition>;
constructor() {
this._sorting = false;
this._list = Array<T>();
this._map = new Map<string, T>();
this._positionMap = new Map<string, MapPosition>();
}
get positionMap() {
return this._positionMap;
}
private addSortChangeHandler(item: T): T {
let self = this;
if (this._positionMap.has(item.id)) {
throw "This item is already in the collection!"
}
let myPosition = <MapPosition>{};
myPosition.index = 0;
myPosition.sort = 0;
self._positionMap.set(item.id, myPosition);
let watcher = <ProxyHandler<T>>{}
watcher.set = function (target, p, value, receiver) {
let myPosition: MapPosition;
let resortRequired = false;
myPosition = self._positionMap.get(receiver.id)!;
switch (p) {
case "sort":
if (value < 0) { value = -1 }
myPosition.sort = value;
if (!self._sorting) {
resortRequired = true;
}
break;
case "index":
myPosition.index = <number>value;
break;
case "id":
target.id = <string>value;
break;
}
if (resortRequired) {
resortRequired = false;
console.log("resort triggered by sort change");
self.sortIndex();
}
return true;
}
watcher.get = function (target: T, prop: string, receiver) {
let myId = item["id"];
let myPosition = self._positionMap.get(myId)!;
switch (prop) {
case 'index':
return myPosition.index;
case 'sort':
return myPosition.sort;
case 'id':
return myId;
default:
return Reflect.get(target, prop, receiver);
}
}
let proxy = new Proxy(item, watcher);
return proxy;
}
getItem(id: string): T {
if (!this._map.has(id)) {
throw `The id ${id} was not found in this Map`;
} else {
let value = this._map.get(id);
return this._map.get(id)!;
}
};
getAt(index: number): T {
if (!(this.existsIndex(index))) {
throw `error [SortedMap.getAt()] An invalid index (${index}) was supplied to getAt. The map has ${this.count} items.`;
}
return this._list[index];
}
get list(): Array<T> {
return this._list;
}
first(): T | null {
if (this.count > 0) {
return this.getAt(0);
}
return null;
}
last(): T | null {
let mycount = this.count;
if (mycount === 0) {
return null;
}
return this._list[mycount - 1];
}
add(item: T, key?: string): T {
if (key === undefined || key === "")
if (!item.id) {
throw "Can't add item with neither key or undefined id.";
} else {
{
key = item.id
};
}
if (this.exists(key)) {
throw "attempt to add duplicate key " + key;
}
let proxyItem = this.addSortChangeHandler(item);
this._list.push(proxyItem);
this._map.set(key, proxyItem);
this.makeIndex();
return proxyItem
}
remove(key: string): T | null {
if (this._map.has(key)) {
let item = this._map.get(key)!;
this._map.delete(key);
this._list = Array.from(this._map.values());
this.sortIndex();
return item;
}
return null;
}
exists(key: string): boolean {
if (!key) {
throw "Can't call exists on falsey key.";
}
return this._map.has(key);
}
existsIndex(index: number): boolean {
if ((index < 0) || (index > (this._list.length - 1))) { return false }
return true;
}
moveUp(id: string): void {
let f = this.getItem(id);
if (f.index === 0) {
return;
}
f.sort = ((f.index - 1) * 10) - 1
}
moveDown(id: string): void {
let f = this.getItem(id);
if (f.index >= this.count - 1) { return; }
f.sort = ((f.index + 1) * 10) + 1;
}
insertBeforeIndex(index: number, item: T): T {
if (this.exists(item.id)) { throw `duplicate key - ${item.id}` }
if (!this.existsIndex(index)) throw `index out of range - ${index}`;
this._sorting = true;
let olditem = this._list[index];
item.sort = olditem.sort - 1;
this._list.push(item);
this._map.set(item.id, item);
this._sorting = false;
this.sortIndex();
return item;
}
insertBeforeKey(beforeKey: string, item: T) {
if (this.exists(item.id)) { throw `duplicate key - ${item.id}` }
if (this.exists(beforeKey)) {
let insertAt = this.getItem(beforeKey)!.sort - 1;
this._sorting = true;
item.sort = insertAt;
this._list.push(item);
this._sorting = false;
this.sortIndex();
return item;
} else {
throw `beforeKey ${beforeKey} not found`;
}
}
/**sets the sort index property and the index property based on teh current
* position of each item in the list.
*/
private makeIndex(): void {
let counter: number = 0;
this._sorting = true;
this._list.forEach(function (item) {
item.index = counter;
item.sort = (counter * 10);
counter += 1;
});
this._sorting = false;
}
/**sorts the list by the current sort index, sets the index and
* sort property of each item based on its new position in the list.
*
**/
sortIndex(): void {
this._sorting = true
this._list.sort(function (a, b) {
return a.sort > b.sort ? 1 : -1;
});
this.makeIndex();
this._sorting = false;
}
get count(): number {
return this._list.length;
}
}
</code></pre>
<p>At one point, I decided that I should gracefully handle all errors where an "incorrect" parameter was supplied, for example, by returning "undefined" or "null" where a <code>getItem(key: string)</code> was supplied a non-existent key. However I discovered the approach of gracefully handling things so exceptions weren't thrown covered up bugs so that it was much harder to figure out why I had an error internal to the class. So I started throwing exceptions for errors like these, but I have a nagging concern that this approach makes it more likely that end user experience will be more seriously impaired when errors occur due to unforeseen edge cases, where the running program just stops altogether and returns an error message that's meaningless to anybody but a developer.</p>
<p>So for example, lets say somebody consumes a SortedMap as follows:</p>
<pre><code>import {SortedMap} from "../lib/util";
import {MapItem} from "../lib/util";
class Account implements MapItem {
id: string;
index: number = 0;
sort: number = 0;
name: string
balance: number;
constructor(id : string, name: string, balance: number) {
this.id = id;
this.name = name;
this.balance = balance;
}
}
class Accounts extends SortedMap<Account> {
getAccountById(id: string) : Account {
return this.getItem(id);
}
getTotal() {
let total=0;
for (let ac of this.list) {
total += ac.balance;
}
}
}
</code></pre>
<p>What would be the sensible way to handle an issue where the consumer of <code>Accounts</code> called <code>getAccountById</code> with an id that hadn't been added to the collection?</p>
<p>Assuming that this class is consumed by say a Angular application, would it make the most sense to </p>
<p> a) do nothing, and let the method call return the error thrown by SortedMap, ("The id {...} was not found in this Map.")<br>
b) check for existence of the key in Accounts.getAccountById using SortedMap.exists(id), and throw an error like "This account does not exist"<br>
c) return undefined or null or some object which represents a non-existent account</p>
<p>Or something else entirely. I guess the question is about balancing ease of debugging, how much time it takes to write parameter error traps all along the call chain, and the effect on end user encountering undiscovered errors that show up in production code.</p>
<p>I'm never quite sure how to balance these various competing priorities with a coherent error handling approach.</p>
<p>Advice welcome.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-03T18:35:45.520",
"Id": "235032",
"Score": "1",
"Tags": [
"object-oriented",
"typescript"
],
"Title": "Error handling approach for parameter errors in Typescript modules?"
}
|
235032
|
<p>I'm a junior developer. And I want to learn the good way to code. The code I will show you is working, but I feel like its all messy and longer that it should be. It is simply a .js, a .html and some css that render a list of informations about scans. The list come from Firebase (Google Analytics).</p>
<p>Here is the code I suspect of being messy - it's a script that sort the 'li' components of the list each time a date is entered or a selection is made (or both).</p>
<pre><code><script>
function myFunction() {
// Declare variables
var input, input2, filter, filter2, ul, li, a, i, txtFirstValue, txtThirdValue, txtFourthValue;
input = document.getElementById('myInput');
input2 = document.getElementById('myInput2');
filter = input.value.toUpperCase();
filter2 = input2.value.toUpperCase();
ul = document.getElementById("Scan-list");
li = ul.getElementsByTagName('li');
counter = 0;
test = li[0].getElementsByTagName("span")[3];
// Loop through all list items, and hide those who don't match the search query (date 1 to date 2)
for (i = 0; i < li.length; i++) {
scanFirstValue = li[i].getElementsByTagName("span")[0];
scanThirdValue = li[i].getElementsByTagName("span")[2];
scanFourthValue = li[i].getElementsByTagName("span")[3];
txtFirstValue = scanFirstValue.textContent;
txtThirdValue = scanThirdValue.textContent;
txtFourthValue = scanFourthValue.textContent;
var stringToDate = new Date(txtFirstValue);
var testSelectBox = dropdownBodypartsDeep.value;
var testvaluebiddon = "Scan Type Specialize : Dorsum";
if (input.value == ""){
if(
((txtThirdValue == "Scan Type : " + dropdownBodyparts.value)
&&
(txtFourthValue == "Scan Type Specialize : " + dropdownBodypartsDeep.value))
|
((txtThirdValue == "Scan Type : " + dropdownBodyparts.value)
&&
(txtFourthValue == "Scan Type Specialize : "))
)
{
li[i].style.display = "";
counter = counter +1;
}
else if (dropdownBodyparts.value == "All"){
li[i].style.display = "";
counter = counter +1;
}
else if (
(txtThirdValue == "Scan Type : " + dropdownBodyparts.value)
&&
(dropdownBodypartsDeep.value == "All")){
li[i].style.display = "";
counter = counter +1;
}
else {
li[i].style.display = "none";
}
}
else if(input.value != "" && dropdownBodyparts.value == "null") {
if(
(stringToDate.getTime() >= (new Date(input.value)).getTime() && stringToDate.getTime() <= (new Date(input2.value)).getTime())
)
{
li[i].style.display = "";
counter = counter +1;
}
else {
li[i].style.display = "none";
}
}
else if(input.value != "" && dropdownBodyparts.value != "null") {
if(
(stringToDate.getTime() >= (new Date(input.value)).getTime() && stringToDate.getTime() <= (new Date(input2.value)).getTime())
&&
((txtThirdValue == "Scan Type : " + dropdownBodyparts.value)
&&
(txtFourthValue == "Scan Type Specialize : " + dropdownBodypartsDeep.value))
|
((txtThirdValue == "Scan Type : " + dropdownBodyparts.value)
&&
(txtFourthValue == "Scan Type Specialize : "))
)
{
li[i].style.display = "";
counter = counter +1;
}
else if (dropdownBodyparts.value == "All"
&&
(stringToDate.getTime() >= (new Date(input.value)).getTime() && stringToDate.getTime() <= (new Date(input2.value)).getTime()))
{
li[i].style.display = "";
counter = counter +1;
}
else {
li[i].style.display = "none";
}
}
}
document.getElementById('counterLabel').innerHTML = counter;
}
</script>
</code></pre>
<p><strong>And here is the HTML for the web page :</strong></p>
<pre><code><body>
<h1 id="titleLabel" >TechMed3D Scan DataBase</h1>
<div id="imageTechMed">
<img src="css/3dsizeme2019.png" class="topRight" style="width:250px;height:45px;">
</div>
<div class="content">
<div class="container">
<label id="labelDate">Date de départ : </label>
<input type="text" id="myInput" name="a" onkeyup="myFunction()" placeholder="yyyy-mm-dd" >
<form>
<select name = "dropdown" id="dropdownBodyparts" onchange="if (this.selectedIndex) myFunction();">
<option disabled selected value = "null"> -- Select A Bodypart --</option>
<option value = "All" >All</option>
<option value = "Head">Head</option>
<option value = "Foot">Foot</option>
<option value = "Leg">Leg</option>
<option value = "Elbow">Elbow</option>
<option value = "Torso">Torso</option>
</select>
</form>
</div>
<div class="container">
<label id="labelDate">Date de fin : </label>
<input type="text" id="myInput2" name="b" onkeyup="myFunction()" placeholder="yyyy-mm-dd" >
<form>
<select name = "dropdown" id="dropdownBodypartsDeep" onchange="if (this.selectedIndex) myFunction();">
<option value = "Specialized" selected>Specialized</option>
</select>
</form>
<div id="scanNumberRight">
<label id="counterAnouncerLabel">Nombre de scan dans la liste : </label>
<label id="counterLabel">-</label>
</div>
</div>
<div style="text-align:center;">
<input type="button" id="first" onclick="firstPage()" value="first" />
<input type="button" id="next" onclick="nextPage()" value="next" />
<input type="button" id="previous" onclick="previousPage()" value="previous" />
<input type="button" id="last" onclick="lastPage()" value="last" />
</div>
<ul id="Scan-list"></ul>
</div>
</code></pre>
<p><strong>For the selectBox, i use this javascript code to render the good value :</strong></p>
<pre><code>//Set the second selectBox depending on the first one choice.
$(document).ready(function () {
$("#dropdownBodyparts").change(function () {
var val = $(this).val();
if (val == "All") {
$("#dropdownBodypartsDeep").html("<option value='All'>All</option>");
} else if (val == "Head") {
$("#dropdownBodypartsDeep").html("<option value='Specialized'>Specialized</option>");
} else if (val == "Foot") {
$("#dropdownBodypartsDeep").html("<option disabled selected value> -- Select A Specialized Bodypart</option><option value='All'>All</option><option value='Dorsum + Imprint'>Dorsum + Imprint</option><option value='Plantar Surface'>Plantar Surface</option><option value='Foam Box'>Foam Box</option><option value='Dorsum'>Dorsum</option><option value='for AFO'>for AFO</option>");
} else if (val == "Leg") {
$("#dropdownBodypartsDeep").html("<option disabled selected value> -- Select A Specialized Bodypart</option><option value='All'>All</option><option value='Knee'>Knee</option><option value='AK'>AK</option><option value='BK'>BK</option>");
} else if (val == "Elbow") {
$("#dropdownBodypartsDeep").html("<option value='Specialized'>Specialized</option>");
} else if (val == "Torso") {
$("#dropdownBodypartsDeep").html("<option disabled selected value> -- Select A Specialized Bodypart</option><option value='All'>All</option><option value='Normal'>Normal</option><option value='Two-sided'>Two-sided</option><option value='Mirror'>Mirror</option><option value='Seating'>Seating</option>");
}
});
});
</code></pre>
<p><strong>And here is the UI</strong></p>
<p><img src="https://i.stack.imgur.com/j6QKJ.png" alt="Image"></p>
|
[] |
[
{
"body": "<p>Use meaningful variable names (and element IDs), for example, <code>startDateInput</code> instead of <code>input</code>/<code>myInput</code>.</p>\n\n<p>Declare varables in the smallest needed scope instead all of them at the start of the function, and declare each variable in a separate statement. Use <code>let</code> or <code>const</code> instead of <code>var</code> (unless you need to support enviroments that don't support them).</p>\n\n<p>Move the variables that don't change for each execution of the function, such as the input references, outside the function.</p>\n\n<p>Use the <code>children</code> property to access the list items of the scan list.</p>\n\n<p>Example of these changes:</p>\n\n<pre><code>const startDateInput = document.getElementById('startDateInput');\nconst endDateInput = document.getElementById('endDateInput');\nconst scanList = document.getElementById(\"Scan-list\");\n\nfunction myFunction() {\n const startDateFilter = startDateInput.value.toUpperCase();\n const endDateFilter = endDateInput.value.toUpperCase();\n const li = scanList.children;\n let counter = 0;\n\n // ...\n}\n</code></pre>\n\n<hr>\n\n<p>Unless you exlipictly need the index use a <code>for ... of</code> loop to iterate over the <code>li</code>s.</p>\n\n<p>Don't repeat things like <code>getElementsByTagName(\"span\")</code>.</p>\n\n<pre><code>for (const item of li) {\n const spans = item.getElementsByTagName(\"span\")\n const itemDateString = spans[0].contentText; // Variable name describing content\n const itemBodyPart = spans[2].contentText;\n\n // ...\n }\n</code></pre>\n\n<hr>\n\n<p>Be careful using <code>new Date(...)</code> to convert arbitrarily strings into dates. Especially it will break if you use a different date format in the output.</p>\n\n<hr>\n\n<p>The big filtering <code>if</code> block is difficult to read. Don't repeat the same comparisons. Extract the large boolean expressions that go over multiple lines into separate functions.</p>\n\n<hr>\n\n<p>Don't hard code strings such as <code>\"All\"</code> and <code>\"Scan Type : \"</code> in your code. It makes translations diffcult. </p>\n\n<p>Generally parsing the data out of the output HTML is a bad idea. It would be better to filter the raw data that the list items represent instead, but that would require completely different code. </p>\n\n<p>At least consider encoding the relevant data in the list items in <a href=\"https://www.w3.org/TR/microdata/\" rel=\"nofollow noreferrer\">microdata attributes</a> or <a href=\"https://developer.mozilla.org/de/docs/Web/HTML/Globale_Attribute/data-*\" rel=\"nofollow noreferrer\"><code>data-</code> attributes</a>. </p>\n\n<p>For example, instead of </p>\n\n<pre><code><li> \n <span>2019-12-24</span>\n <span>Scan Type : Foot</span>\n</li>\n</code></pre>\n\n<p>have something like this (with microdata):</p>\n\n<pre><code> <li itemscope>\n <!-- Identify the elememt via the `itemprop` attribute instead of its index.\n Have the datetime attribute in a computer readable format and display\n the date to the user in a human readable format -->\n <time itemprop=\"date\" datetime=\"2019-12-24\">\n December 24th, 2019\n </time> \n <!-- `value` attribute contains the data in format the script understands\n and the text is translatable and human readable. -->\n <span itemprop=\"body-part\" value=\"Foot\">\n Scan Type : Pied\n </span>\n </li>\n</code></pre>\n\n<p>Or with data attributes:</p>\n\n<pre><code> <li>\n <span data-date=\"2019-12-24\">\n December 24th, 2019\n </span>\n <span data-body-part=\"Foot\">\n Scan Type : Pied\n </span>\n </li>\n</code></pre>\n\n<hr>\n\n<p><code>counter = counter +1;</code> can be simplified to <code>counter++</code>. </p>\n\n<p>Don't repeat <code>li[i].style.display = \"\"; counter = counter +1;</code>. Instead have your filtering <code>if</code> block return a boolean (<code>visible</code>), and then at the end say:</p>\n\n<pre><code>if (visible) {\n li[i].style.display = \"\";\n // Or `item.style.display = \"\";` in my example\n\n counter++;\n} else {\n li[i].style.display = \"none\";\n}\n</code></pre>\n\n<hr>\n\n<p>Don't assign event handlers in the HTML in the <code>on...</code> attributes. Instead assign them in the JavaScript code with <code>addEventListener</code>.</p>\n\n<p><code>disabled</code> and <code>selected</code> on the same <code>option</code> doesn't make much sense.</p>\n\n<hr>\n\n<p>You didn't use jQuery in <code>myFunction</code> so no need to start using it in the other JavaScript. Avoid jQuery as much as you can, especially in such simple scripts where its features aren't taken advantage of.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-06T21:13:43.040",
"Id": "460180",
"Score": "0",
"body": "First,@RoToRa I want to thank you for your time and all the help you gave me. I didnt catch all the info you gave me but it helped me a lot and now i feel like my code is more robust and cleaner. I still have to learn things to make the changes you suggest me. For exemple : i cant change my for loop to a \" for(const item of li)\" because i cant display my item afterward... Thanks again for your knowledge, I learned a lot!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-05T18:56:33.087",
"Id": "235126",
"ParentId": "235035",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "235126",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-03T19:11:41.453",
"Id": "235035",
"Score": "2",
"Tags": [
"javascript",
"jquery",
"html"
],
"Title": "JavaScript list sorting by date and type. better code?"
}
|
235035
|
<p>I am attempting to create a batch file that will execute multiple msi files in a particular location on our network. My intention is not to have any user interactions until they are prompted to do a reboot. We have an automated tool that I will use to rolls this out, just need some help with the batch file itself. Keep in mind I have minimal experience writing these out, so the syntax could be off. This is what I have so far:</p>
<pre><code>@echo off
:: Intended to update all 3 components prepping it for uninstallation
msiexec.exe /i "\\FileShare\Folder\install1" /QN /L*V c:\temp\update1.log REBOOT=reallysuppress
msiexec.exe /i "\\FileShare\Folder\install2" /QN /L*V c:\temp\update2.log REBOOT=reallysuppress
msiexec.exe /i "\\FileShare\Folder\install3" /QN /L*V c:\temp\update3.log REBOOT=reallysuppress
:: Genaric uninstallation of install1
wmic product where "name like 'Vendor%Product%Configuration'" uninstall
:: Uninstallation of install2
:: Check to see which version is identified within registry and uninstall
:: all versions within {} are registry keys
msiexec.exe " /X {version1} /qn REBOOT=reallysuppress"
msiexec.exe " /X {version2} /qn REBOOT=reallysuppress"
msiexec.exe " /X {version3} /qn REBOOT=reallysuppress"
msiexec.exe " /X {version4} /qn REBOOT=reallysuppress"
msiexec.exe " /X {version5} /qn REBOOT=reallysuppress"
msiexec.exe " /X {version6} /qn REBOOT=reallysuppress"
msiexec.exe " /X {version7} /qn REBOOT=reallysuppress"
:: Uninstallation of install3
:: Check to see which version is identified within registry and uninstall
:: all versions within {} are registry keys
msiexec.exe " /X {version1} /qn REBOOT=reallysuppress"
msiexec.exe " /X {version2} /qn REBOOT=reallysuppress"
msiexec.exe " /X {version3} /qn REBOOT=reallysuppress"
msiexec.exe " /X {version4} /qn REBOOT=reallysuppress"
msiexec.exe " /X {version5} /qn REBOOT=reallysuppress"
msiexec.exe " /X {version6} /qn REBOOT=reallysuppress"
msiexec.exe " /X {version7} /qn REBOOT=reallysuppress"
</code></pre>
<p>I hope this information is clear. Please let me know what does or does not make sense and I can answer questions promptly. This is written as a .bat file type. </p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-03T23:31:32.033",
"Id": "459817",
"Score": "0",
"body": "Why batch? Can't you move to PowerShell?"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-03T19:30:13.153",
"Id": "235037",
"Score": "1",
"Tags": [
"windows",
"batch"
],
"Title": "Batch file that executes multiple .msi files"
}
|
235037
|
<p>I am using the following code to format an address retrieved using the Google Places API. According to Googles docs they recommend looping through the response based on what you list in the <code>componentForm</code> array. Is there a way to optimize this code and simplify it without having to specify the individual if statements?</p>
<pre><code>var componentForm = {
street_number: 'short_name',
route: 'long_name',
locality: 'long_name',
administrative_area_level_1: 'short_name',
postal_code: 'short_name'
};
var place = searchaddress.getPlace();
for (var i = 0; i < place.address_components.length; i++) {
var addressType = place.address_components[i].types[0];
if (componentForm[addressType]) {
if (addressType == 'street_number') {
var streetNumber = place.address_components[i][componentForm[addressType]];
}
if (addressType == 'route') {
var route = place.address_components[i][componentForm[addressType]];
}
if (addressType == 'locality') {
var locality = place.address_components[i][componentForm[addressType]];
}
if (addressType == 'administrative_area_level_1') {
var state = place.address_components[i][componentForm[addressType]];
}
if (addressType == 'postal_code') {
var zipcode = place.address_components[i][componentForm[addressType]];
}
}
}
document.getElementById('fullAddress').value = streetNumber + ' ' + route + ', ' + locality + ', ' + state + ' ' + zipcode;
</code></pre>
|
[] |
[
{
"body": "<ol>\n<li><strong>Use if.else if.else if ladder:</strong>\nInstead of multiple conditions of if.if.if, you should use if.else if.else if ladder. The advantage of latter is that once a condition is met, the next conditions are skipped. But using only if.if.if means all the ifs are walked through irrespective of any if matching the condition. <a href=\"https://stackoverflow.com/questions/20259351/difference-between-if-and-else-if/20259384\">Read more about it here</a></li>\n</ol>\n<hr />\n<ol start=\"2\">\n<li>It is generally a good idea to save repeating variables like <code>place.address_components[i][componentForm[addressType]]</code> in a variable to avoid its repetition and errors</li>\n</ol>\n<hr />\n<ol start=\"3\">\n<li><strong>Use object to store address avoiding all if conditions:</strong>\nUse object to store the address. <code>place.address_components[i][componentForm[addressType]]</code> is common value to be store. The only thing changing is <code>addressType</code>. So, make <code>addressType</code> as key with value <code>place.address_components[i][componentForm[addressType]]</code>. <em>This will skip the need for if conditions</em>.</li>\n</ol>\n<p>You will get address object of like:</p>\n<pre><code>{\n "street_number": "1600",\n "route": "Amphitheatre Pkwy",\n "locality": "Mountain View",\n "administrative_area_level_1": "CA",\n "postal_code": "94043"\n}\n</code></pre>\n<p>And this can be printed where ever you want by using <code>Object.key</code></p>\n<p>If you want to preserve the naming conventions in code such as <code>state</code> instead of <code>administrative_area_level_1</code> that can also be done by creating another mapping object</p>\n<hr />\n<h3>Updated Code</h3>\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>var place = {\"address_components\":[{\"long_name\":\"1600\",\"short_name\":\"1600\",\"types\":[\"street_number\"]},{\"long_name\":\"Amphitheatre Pkwy\",\"short_name\":\"Amphitheatre Pkwy\",\"types\":[\"route\"]},{\"long_name\":\"Mountain View\",\"short_name\":\"Mountain View\",\"types\":[\"locality\",\"political\"]},{\"long_name\":\"Santa Clara County\",\"short_name\":\"Santa Clara County\",\"types\":[\"administrative_area_level_2\",\"political\"]},{\"long_name\":\"California\",\"short_name\":\"CA\",\"types\":[\"administrative_area_level_1\",\"political\"]},{\"long_name\":\"United States\",\"short_name\":\"US\",\"types\":[\"country\",\"political\"]},{\"long_name\":\"94043\",\"short_name\":\"94043\",\"types\":[\"postal_code\"]}],\"formatted_address\":\"1600 Amphitheatre Parkway, Mountain View, CA 94043, USA\",\"geometry\":{\"location\":{\"lat\":37.4224764,\"lng\":-122.0842499},\"location_type\":\"ROOFTOP\",\"viewport\":{\"northeast\":{\"lat\":37.4238253802915,\"lng\":-122.0829009197085},\"southwest\":{\"lat\":37.4211274197085,\"lng\":-122.0855988802915}}},\"place_id\":\"ChIJ2eUgeAK6j4ARbn5u_wAGqWA\",\"types\":[\"street_address\"]}\n\nvar componentForm = {\n street_number: 'short_name',\n route: 'long_name',\n locality: 'long_name',\n administrative_area_level_1: 'short_name',\n postal_code: 'short_name'\n};\n\nvar addressObj = {}\n\nfor (var i = 0; i < place.address_components.length; i++) {\n var addressType = place.address_components[i].types[0];\n if (componentForm[addressType]) {\n addressObj[addressType] = place.address_components[i][componentForm[addressType]]\n }\n}\n\nconsole.log(addressObj)\n\ndocument.getElementById('fullAddress').innerHTML = addressObj.street_number + ' ' + addressObj.route + ', ' + addressObj.locality + ', ' + addressObj.administrative_area_level_1 + ' ' + addressObj.postal_code;</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><div id=\"fullAddress\"></div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>The above json is copied from <a href=\"https://developers.google.com/maps/documentation/geocoding/intro\" rel=\"nofollow noreferrer\">https://developers.google.com/maps/documentation/geocoding/intro</a></p>\n<p>Hope it helps. Revert for any doubts.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-05T20:28:06.087",
"Id": "235131",
"ParentId": "235040",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "235131",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-03T21:39:50.240",
"Id": "235040",
"Score": "3",
"Tags": [
"javascript"
],
"Title": "Simplify Google places autocomplete address for loop"
}
|
235040
|
<p>I've decided to do a simple linked list question to brush up my Java & CS.</p>
<hr>
<p>This is the solution for</p>
<blockquote>
<p>Given a reference to the head of a doubly-linked list and an integer,
<span class="math-container">\$data\$</span> , create a new DoublyLinkedListNode object having data value
<span class="math-container">\$data\$</span>
and insert it into a sorted linked list while maintaining the sort.
<a href="https://www.hackerrank.com/challenges/insert-a-node-into-a-sorted-doubly-linked-list/problem" rel="nofollow noreferrer">Full question</a></p>
</blockquote>
<pre><code> /*
* For your reference:
*
* DoublyLinkedListNode {
* int data;
* DoublyLinkedListNode next;
* DoublyLinkedListNode prev;
* }
*
*/
static DoublyLinkedListNode sortedInsert(DoublyLinkedListNode head, int data) {
DoublyLinkedListNode nodeToInsert = new DoublyLinkedListNode(data);
if (head == null) return nodeToInsert;
DoublyLinkedListNode current = head;
while (current != null) {
if (data < current.data && current.prev == null) {
current.prev = nodeToInsert;
nodeToInsert.next = current;
return nodeToInsert;
}
if (data >= current.data && current.next == null) {
current.next = nodeToInsert;
nodeToInsert.prev = current;
break;
}
if (data >= current.data && data <= current.next.data) {
DoublyLinkedListNode temp = current.next;
current.next = nodeToInsert;
nodeToInsert.prev = current;
temp.prev = nodeToInsert;
nodeToInsert.next = temp;
break;
}
current = current.next;
}
return head;
}
</code></pre>
<p>This passes all test cases.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-03T22:26:12.837",
"Id": "459814",
"Score": "0",
"body": "Since you're brushing up, if this were real production code, I'd ding you pretty hard on your lack of Javadoc comments. Get a copy of *Effective Java* by Joshua Bloch and read his advice on proper in-code documentation."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-04T11:54:09.667",
"Id": "459872",
"Score": "0",
"body": "@markspace yes comment in my code above is kind of weired. :( It came with the question itself."
}
] |
[
{
"body": "<p>One thing I take issue with is that all of this code is in a <code>static</code>. If you're already drinking the Java kool-aid, you can have a brief static wrapper to do your <code>if (head == null)</code> shortcut, but the rest of the code should be one or more methods on <code>DoublyLinkedListNode</code>. Rather than continuing to reference your parameter <code>data</code>, the instance saved to <code>nodeToInsert</code> would, in the method you write, access its <code>this.data</code>.</p>\n\n<p>Overall the question asks you to do a thing that sucks, so it isn't your fault: sorted insertion to a linked list is O(n), but you can do much better with a different choice of data structure, such as an AVL tree. If you're interested, here's an <a href=\"https://blog.scottlogic.com/2010/12/22/sorted_lists_in_java.html\" rel=\"nofollow noreferrer\">implementation of a sorted list in Java</a>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-04T11:46:30.540",
"Id": "459871",
"Score": "0",
"body": "Yes it's just a silly question. I'm already aware of AVL & RB trees. `static` was unfortunately there in the question."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-03T23:10:54.147",
"Id": "235045",
"ParentId": "235043",
"Score": "2"
}
},
{
"body": "<p>To me, the main problem with your solution is readability. It took me some time to understand what exactly you're doing to solve a <strong>Hackerrank</strong> task.</p>\n\n<p><strong>Simplify Code</strong></p>\n\n<p>For instance, consider the following block of yours:</p>\n\n<pre><code>...\nif (data < current.data && current.prev == null) {\n current.prev = nodeToInsert;\n nodeToInsert.next = current;\n return nodeToInsert;\n}\n...\n</code></pre>\n\n<p>Doing it in a <code>while</code> loop is a bit confusing as you can directly compare <code>data</code> with <code>head.data</code> - as per problem statement the list is sorted and so the smallest element is in the current head. Move it out of the loop. Additionally, remove <code>current.prev == null</code> as the head is the first element by definition. </p>\n\n<pre><code>if (data < head.data) {\n head.prev = nodeToInsert;\n nodeToInsert.next = head;\n return nodeToInsert;\n}\n</code></pre>\n\n<p>Another block that can be simplified is:</p>\n\n<pre><code>if (data >= current.data && current.next == null) {\n current.next = nodeToInsert;\n nodeToInsert.prev = current;\n break;\n}\n</code></pre>\n\n<p>Here, you check if <code>current</code> is a tail (last element) and then add your <code>nodeToInsert</code> to it. But then <code>data >= current.data</code> is redundant since <code>current.next == null</code> is sufficient to say whether an element is a tail or not. Hence:</p>\n\n<pre><code>if (current.next == null) {\n current.next = nodeToInsert;\n nodeToInsert.prev = current;\n break;\n}\n</code></pre>\n\n<p>Or even here:</p>\n\n<pre><code>if (data >= current.data && data <= current.next.data) {\n DoublyLinkedListNode temp = current.next;\n current.next = nodeToInsert;\n nodeToInsert.prev = current;\n temp.prev = nodeToInsert;\n nodeToInsert.next = temp;\n break;\n}\n</code></pre>\n\n<p>You can remove <code>data >= current.data</code> as it's given (initially <code>current = head</code> and so the check was made before the loop started):</p>\n\n<pre><code>if (data <= current.next.data) {\n DoublyLinkedListNode temp = current.next;\n current.next = nodeToInsert;\n nodeToInsert.prev = current;\n temp.prev = nodeToInsert;\n nodeToInsert.next = temp;\n break;\n}\n</code></pre>\n\n<p><strong>Add useful comments</strong></p>\n\n<p>You could've commented crucial blocks of your code better to make it easier to understand what you're doing. For instance:</p>\n\n<pre><code>// if current is the last element then add the new element after it\nif (current.next == null) {\n current.next = nodeToInsert;\n nodeToInsert.prev = current;\n break;\n}\n</code></pre>\n\n<p>Or </p>\n\n<pre><code>// if the new element is not greater than the next one \n// then insert it between the current element and the next one\nif (data <= current.next.data) {\n DoublyLinkedListNode temp = current.next;\n current.next = nodeToInsert;\n nodeToInsert.prev = current;\n temp.prev = nodeToInsert;\n nodeToInsert.next = temp;\n break;\n}\n</code></pre>\n\n<p><strong>Static method</strong></p>\n\n<p>Well, I know, <strong>Hackerrank</strong> forces you to use the static <code>sortedInsert()</code> method so there's nothing you can do about it.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-04T00:12:06.350",
"Id": "235047",
"ParentId": "235043",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "235047",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-03T21:58:33.257",
"Id": "235043",
"Score": "3",
"Tags": [
"java",
"programming-challenge",
"linked-list"
],
"Title": "Sorted insert on a doubly linked list (HackerRank)"
}
|
235043
|
<p>I am self-taught when it comes to coding. I want to improve, so please give me advice if I have some bad habits or if there is in general a better way of doing this.</p>
<p>The idea of this code is to look up Excel files on a file server, check if they are flagged as "finalized" and if so, to create new records in a database with the key/ID from the excel file. Than, also copy further data from the Excel file to the record.</p>
<p>I think could have just created (aka inserted) a new record with all data, but to handle errors from wrong datatypes I decided to do it one-by-one.</p>
<p>There is also a <code>filesDone.txt</code> file that stores the full path of all files
already copied or that are older and don't contain the "finalized" property.</p>
<p>I plan to run this as a service. It should run the loop every 5 minutes. The code will later run as a service and loop through every 5 minutes.</p>
<p>So simply put the code does:</p>
<ol>
<li>loads file names from <code>filesDone.txt</code> to a set</li>
<li>loads file names from the filesystem/ a certain dir + subdirs to a set</li>
<li>creates a list of the difference of the two sets</li>
<li>iterates through the list (all remaining files)
<ul>
<li>looks, if they have been flagged as "finalized",</li>
<li>then for each row in the file:</li>
<li>creates a new record in the database</li>
<li>and adds values to given record (one by one)</li>
</ul></li>
<li>adds the processed file's name to the file of filenames.</li>
<li>waits 300 seconds.</li>
</ol>
<p>I am very new to coding so sorry for my dilettantish approach. At least it works so far.</p>
<pre><code>#modules
import pandas as pd
import pyodbc as db
import xlwings as xw
import glob
import os
from datetime import datetime, date
from pathlib import Path
import time
import sys
#constants
tick_time_seconds = 300
line = ("################################################################################### \n")
pathTodo = "c:\\myXlFiles\\**\\*"
pathDone = ("c:\\Done\\")
pathError = ("c:\\Error\\")
sqlServer = "MyMachine\\MySQLServer"
sqlDriver = "{SQL Server}"
sqlDatabase="master"
sqlUID="SA"
sqlPWD="PWD"
#functions
def get_list_of_files_by_extension(path:str, extension:str) -> list:
"""Recieves string patch and extension;
gets list of files with corresponding extension in path;
return list of file with full path."""
fileList = glob.glob(path+extension, recursive=True)
if not fileList:
print("no found files")
else:
print("found files")
return fileList
def write_error_to_log(description:str, errorString:str, optDetails=""):filesDone.txt
"""Recieves strings description errorstring and opt(ional)Details;
writes the error with date and time in logfile with the name of current date;
return nothing."""
logFileName = str(date.today())+".txt"
optDetails = optDetails+"\n"
dateTimeNow = datetime.now()
newError = "{0}\n{1}\n{2}{3}\n".format(line, str(dateTimeNow), optDetails, errorString)
print(newError)
with open(Path(pathError, logFileName), "a") as logFile:
logFile.write(newError)
def sql_connector():
"""sql_connector: Recieves nothing;
creates a connection to the sql server (conncetion details sould be constants);
returns a connection."""
return db.connect("DRIVER="+sqlDriver+"; \
SERVER="+sqlServer+"; \
DATABASE="+sqlDatabase+"; \
UID="+sqlUID+"; \
PWD="+sqlPWD+";")
def sql_update_builder(dbField:str, dbValue:str, dbKey:str) -> str:
""" sql_update_builder: takes strings dbField, dbValue and dbKey;
creates a sql syntax command with the purpose to update the value of the
corresponding field with the corresponding key;
returns a string with a sql command."""
return "\
UPDATE [tbl_Main] \
SET ["+dbField+"]='"+dbValue+"' \
WHERE ((([tbl_Main].MyKey)="+dbKey+"));"
def sql_insert_builder(dbKey: str) -> str:
""" sql_insert_builder: takes strings dbKey;
creates a sql syntax command with the purpose to create a new record;
returns a string with a sql command."""
return "\
INSERT INTO [tbl_Main] ([MyKey])\
VALUES ("+dbKey+")"
def append_filename_to_fileNameFile(xlFilename):
"""recieves anywthing xlFilename;
converts it to string and writes the filename (full path) to a file;
returns nothing."""
with open(Path(pathDone, "filesDone.txt"), "a") as logFile:
logFile.write(str(xlFilename)+"\n")
###################################################################################
###################################################################################
# main loop
while __name__ == "__main__":
###################################################################################
""" 1. load filesDone.txt into set"""
listDone = []
print(line+"reading filesDone.txt in "+pathDone)
try:
with open(Path(pathDone, "filesDone.txt"), "r") as filesDoneFile:
if filesDoneFile:
print("file contains entries")
for filePath in filesDoneFile:
filePath = filePath.replace("\n","")
listDone.append(Path(filePath))
except Exception as err:
errorDescription = "failed to read filesDone.txt from {0}".format(pathDone)
write_error_to_log(description=errorDescription, errorString=str(err))
continue
else: setDone = set(listDone)
###################################################################################
""" 2. load filenames of all .xlsm files into set"""
print(line+"trying to get list of files in filesystem...")
try:
listFileSystem = get_list_of_files_by_extension(path=pathTodo, extension=".xlsm")
except Exception as err:
errorDescription = "failed to read file system "
write_error_to_log(description=errorDescription, errorString=str(err))
continue
else:
listFiles = []
for filename in listFileSystem:
listFiles.append(Path(filename))
setFiles = set(listFiles)
###################################################################################
""" 3. create list of difference of setMatchingFiles and setDone"""
print(line+"trying to compare done files and files in filesystem...")
setDifference = setFiles.difference(setDone)
###################################################################################
""" 4. iterate thru list of files """
for filename in setDifference:
""" 4.1 try: look if file is marked as "finalized=True";
if the xlfile does not have sheet 7 (old ones)
just add the xlfilename to the xlfilenameFile"""
try:
print("{0}trying to read finalized state ... of {1}".format(line, filename))
filenameClean = str(filename).replace("\n","")
xlFile = pd.ExcelFile(filenameClean)
except Exception as err:
errorDescription = "failed to read finalized-state from {0} to dataframe".format(filename)
write_error_to_log(description=errorDescription, errorString=str(err))
continue
else:
if "finalized" in xlFile.sheet_names:
dataframe = xlFile.parse("finalized")
print("finalized state ="+str(dataframe.iloc[0]["finalized"]))
if dataframe.iloc[0]["finalized"] == False:
continue
else:
append_filename_to_fileNameFile(filename) #add the xlfilename to the xlfilenameFile"
continue
###################################################################################
""" 4.2 try: read values to dataframe"""
try:
dataframe = pd.read_excel(Path(filename), sheet_name=4)
except Exception as err:
errorDescription = "Failed to read values from {0} to dataframe".format(filename)
write_error_to_log(description=errorDescription, errorString=str(err))
continue
###################################################################################
""" 4.3 try: open connection to database"""
print("{0}Trying to open connection to database {1} on {2}".format(line, sqlDatabase, sqlServer))
try:
sql_connection = sql_connector() #create connection to server
stuff = sql_connection.cursor()
except Exception as err:
write_error_to_log(description="Failed to open connection:", errorString=str(err))
continue
###################################################################################
""" 4.4 try: write to database"""
headers = list(dataframe) #copy header from dataframe to list; easier to iterate
values = dataframe.values.tolist() #copy values from dataframe to list of lists [[row1][row2]...]; easier to iterate
for row in range(len(values)): #iterate over lines
dbKey = str(values[row][0]) #first col is key
sqlCommandString = sql_insert_builder(dbKey=dbKey)
""" 4.4.1 firts trying to create (aka insert) new record in db ..."""
try:
print("{0}Trying insert new record with the id {1}".format(line, dbKey))
stuff.execute(sqlCommandString)
sql_connection.commit()
print(sqlCommandString)
except Exception as err:
sql_log_string = " ".join(sqlCommandString.split()) #get rid of whitespace in sql command
write_error_to_log(description="Failed to create new record in DB:", errorString=str(err), optDetails=sql_log_string)
else: #if record was created add the values one by one:
print("{0}Trying to add values to record with the ID {1}".format(line, dbKey))
""" 4.4.2 ... than trying to add the values one by one"""
for col in range(1, len(headers)): #skip col 0 (the key)
dbField = str(headers[col]) #field in db is header in the excel sheet
dbValue = str(values[row][col]) #get the corresponding value
dbValue = (dbValue.replace("\"","")).replace("\'","") #getting rid of ' and " to prevent trouble with the sql command
sqlCommandString = sql_update_builder(dbField, dbValue, dbKey) # calling fuction to create a sql update command string
try: #try to commit the sql command
stuff.execute(sqlCommandString)
sql_connection.commit()
print(sqlCommandString)
except Exception as err:
sql_log_string = " ".join(sqlCommandString.split()) #get rid of whitespace in sql command
write_error_to_log(description="Failed to add values in DB:", errorString=str(err), optDetails=sql_log_string)
append_filename_to_fileNameFile(filename)
print(line)
# wait for a certain amount of time
for i in range(tick_time_seconds, 0, -1):
sys.stdout.write("\r" + str(i))
sys.stdout.flush()
time.sleep(1)
sys.stdout.flush()
print(line)
#break # this is for debuggung
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-04T00:35:48.893",
"Id": "459821",
"Score": "1",
"body": "There are more sections numbered 4.2 than with any other number. I wasn't fond of line numbering when BASIC interpreters looked easier to implement that way."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-04T14:53:30.967",
"Id": "459887",
"Score": "0",
"body": "I am not sure what you are trying to tell me. I like to structure my code with these numbers. And sometimes I add a point in between and then the numbering is all over the place and I have 4.2s twice. But do you think in general that structuring the code with comments like this is a bad habit?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-04T15:48:31.310",
"Id": "459892",
"Score": "0",
"body": "Regrettably, my comment doesn't read *4.1* which occurs twice. I think structuring code with whitespace useful. Comments are indispensable to document *what* shall be achieved by some code - for *by what mechanisms*, read/debug code. Numbering going *over the place* to the point of having numerical labels appearing twice in succession is an indication the approach is problematic, and going in the direction of Dewey Decimal(adding decimal points and decimals) is not a solution."
}
] |
[
{
"body": "<h2>Time constants</h2>\n\n<p>Rather than writing</p>\n\n<pre><code>tick_time_seconds = 300\n</code></pre>\n\n<p>you're better off using a more expressive built-in:</p>\n\n<pre><code>from datetime import timedelta\ntick_time = timedelta(minutes=5)\n</code></pre>\n\n<h2>Unnecessary parens</h2>\n\n<p>...around this:</p>\n\n<pre><code>line = (\"################################################################################### \\n\")\n</code></pre>\n\n<p>besides, you're better off writing</p>\n\n<pre><code>line = 80*'#'\n</code></pre>\n\n<h2>Windows paths</h2>\n\n<p>These:</p>\n\n<pre><code>pathTodo = \"c:\\\\myXlFiles\\\\**\\\\*\"\npathDone = (\"c:\\\\Done\\\\\")\npathError = (\"c:\\\\Error\\\\\")\n</code></pre>\n\n<p>have a few issues. First, declare them as raw strings (<code>r''</code>) so that you don't have to double up on backslashes. Also, none of those parens are necessary. Finally, the variable names here should probably be in all caps due to these things being global string constants.</p>\n\n<h2>Passwords</h2>\n\n<p>I sure hope that this:</p>\n\n<pre><code>sqlPWD=\"PWD\" \n</code></pre>\n\n<p>isn't what I think it is. Don't hard-code passwords in your code. This is a whole thing - you're best to google a reasonable way to have a wallet accessible from Python.</p>\n\n<h2>Spelling</h2>\n\n<p>Recieves = Receives</p>\n\n<p>firts = first</p>\n\n<h2>Manual path concatenation</h2>\n\n<pre><code>path+extension\n</code></pre>\n\n<p>is something you probably don't want to do yourself. Refer to <code>Path.with_suffix</code>.</p>\n\n<h2>Generators</h2>\n\n<pre><code> listFiles = []\n for filename in listFileSystem:\n listFiles.append(Path(filename))\n setFiles = set(listFiles)\n</code></pre>\n\n<p>should just be</p>\n\n<pre><code>files = {Path(filename) for filename in all_files}\n</code></pre>\n\n<p>Note that your variable names shouldn't include the type (i.e. <code>list</code>), just a useful description of what they actually hold.</p>\n\n<h2>f-strings</h2>\n\n<pre><code>print(\"{0}trying to read finalized state ... of {1}\".format(line, filename))\n</code></pre>\n\n<p>can be</p>\n\n<pre><code>print(line)\nprint(f'Trying to read finalized state of {filename}')\n</code></pre>\n\n<p>The <code>line</code> print should be separated for clarity, since it's a different line on the output.</p>\n\n<h2>Boolean comparison</h2>\n\n<pre><code>if dataframe.iloc[0][\"finalized\"] == False:\n</code></pre>\n\n<p>should be</p>\n\n<pre><code>if not dataframe.iloc[0][\"finalized\"]:\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-04T00:29:25.570",
"Id": "459820",
"Score": "0",
"body": "In general, thank you a lot, this really helps! >> Note that your variable names shouldn't include the type (i.e. list), just a useful description of what they actually hold.<< is there a specific reason to not do this? Or is this just a convention?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-04T02:36:54.093",
"Id": "459837",
"Score": "0",
"body": "The reason is that there are other, better, ways to indicate type - such as declarative type hinting."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-04T14:44:39.877",
"Id": "459885",
"Score": "0",
"body": "I found [PEP 526](https://www.python.org/dev/peps/pep-0526/). This is great! Thanks for that advice."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-03T23:29:11.577",
"Id": "235046",
"ParentId": "235044",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "235046",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-03T22:55:14.977",
"Id": "235044",
"Score": "5",
"Tags": [
"python",
"python-3.x",
"sql",
"sql-server"
],
"Title": "Excel to SQL server"
}
|
235044
|
<p>I am working towards a CSC degree right now and wanted to try and practice writing good code that could be easily maintained and read in industry. I wrote the following program in Java that takes a multi-dimensional array representing an Sudoku and uses recursive backtracking to find a solution. </p>
<p>If you were an industry professional looking for applicants to your position and I sent you this as an example of code I had worked on what would you look at? What are things that would be a strike against me and what are things that would would make me look good. </p>
<p>This is kind of a weird scenario but I am just trying to make myself as competitive as possible once I get out of school. Also I have dyslexia, please let me know if you find an misspelled words I really struggle with that.</p>
<p>And here is a <a href="https://github.com/LukeJelly/Sudoku-Solver" rel="nofollow noreferrer">link</a> to a repository where I pushed everything.</p>
<pre><code>import java.util.Stack;
/**
* A simple class that solves a Sudoky.
* @author Luke Kelly
* @version 1.0
*/
class SudokuSolver {
/**
* Solves the given Sudoku, preconditions:
* 1. Empty space is reperesnted by 0s.
* 2. The sudoku is not already invalid(No duplicates in a row, colum, or 3x3 box,except zeros).
* 3. The sudoku is a normal 9x9 sudoku.
* @return a solved sudoku is the sudoku is solvable, null if not.
*/
public static int[][] solveSudoku(int[][] original) {
//Clone the original so I don't change the original array
int[][] workingSudoku = cloneSudoku(original);
//Find all the emtpy indexes in the array, this simplifes the algorithm.
Stack<Integer[]> allEmtpyIndexes = findAllEmptySpaces(workingSudoku);
//Solve it, if they method returns false the sudoku is unsolvable.
if(solveSudoku(workingSudoku, allEmtpyIndexes)){
return workingSudoku;
}else{
return null;
}
}
/**
* Private recursive helper for solveSudoku
* @param workingSudoku the Sudoku we are trying to solve
* @param allEmptyIndexes a Stack holding all the emtpy locations
* @return true if the sudoku is solved, false if not.
*/
private static boolean solveSudoku(int[][] workingSudoku,
Stack<Integer[]> allEmptyIndexes) {
/* Algorithm Explanation:
1. Grab the first index that is empty from the stack,
2. Grab all information from that index.
3. Loop through all the numbers from 1-9 and see if they fit work in the empty space.
i. If the number is allowed, put it in that index, and restart the loop from the next index.
a. If the recursive call returns true then we know that number works in that location return true;
b. If the recursive call retruns false then we know that number does not work,
place a EMPTY_CELL back in that location and continue back at step 3.
ii. If none of the numbers work, we put this index back in the stack, and return false
4. If at top of stack and return false then we know all possible permutations were tried return false
else we return true because we have a solved puzzle.
*/
int EMPTY_CELL = 0; //Place holder for an Emtpy cell
while (!allEmptyIndexes.isEmpty()) {
//1.
Integer[] workingIndex = allEmptyIndexes.pop();
//2.
int row = workingIndex[0];
int col = workingIndex[1];
//3.
for (int number = 1; number <= 9; number++) {
if (isAllowed(workingSudoku, row, col, number)) {
//3 i.
workingSudoku[row][col] = number;
if (solveSudoku(workingSudoku, allEmptyIndexes)){
//3 i a.
return true;
} else {
//3 i b.
workingSudoku[row][col] = EMPTY_CELL;
}
}
}
//3 ii.
allEmptyIndexes.add(workingIndex);
return false;
}
return true;
}
/**
* Checks if that number is already in the row, colum, 3x3 box that our
* index is in.
* @param workingSudoku the Sudoku we are working in
* @param rowIndex the index of the row we are working in
* @param colIndex the index of the colum we are working in
* @param number the number we are trying to place there
* @return true if the number works, false if it doesn't.
*/
private static boolean isAllowed(int[][] workingSudoku, int rowIndex, int colIndex, int number) {
return !(containsInRow(workingSudoku, rowIndex, number) ||
containsInCol(workingSudoku, colIndex, number) ||
containsInBox(workingSudoku, rowIndex, colIndex, number));
}
/**
* Checks if the given number exists in this row.
* @param sudoku the Sudoku we are working in.
* @param rowIndex the index of the row.
* @param number The number we are checking against.
* @return true if the number is in there, false if not.
*/
private static boolean containsInRow(int[][] sudoku, int rowIndex, int number) {
for (int i = 0; i < 9; i++) {
if (sudoku[rowIndex][i] == number) {
return true;
}
}
return false;
}
/**
* Checks if the given number exists in this colum.
* @param sudoku the Sudoku we are working in.
* @param colIndex the index of the colum.
* @param number The number we are checking against.
* @return true if the number is in there, false if not.
*/
private static boolean containsInCol(int[][] sudoku, int colIndex, int number) {
for (int i = 0; i < 9; i++) {
if (sudoku[i][colIndex] == number) {
return true;
}
}
return false;
}
/**
* Checks if the given number exists in the box.
* @param sudoku the Sudoku we are working in.
* @param row the index of the row.
* @param col the index of the colum.
* @param number The number we are checking against.
* @return true if the number is in there, false if not.
*/
private static boolean containsInBox(int[][] sudoku, int row, int col, int number) {
int r = row - row % 3;
int c = col - col % 3;
for (int i = r; i < r + 3; i++) {
for (int j = c; j < c + 3; j++) {
if (sudoku[i][j] == number) {
return true;
}
}
}
return false;
}
/**
* Finds all the emtpy indexes in the Sudoku.
* @param sudoku the sudoku we are searching through.
* @return A stack with all the empty indexes in the Sudoku.
*/
private static Stack<Integer[]> findAllEmptySpaces(int[][] sudoku) {
Stack<Integer[]> allIndexes = new Stack<>();
int size = sudoku.length - 1;
for (int outer = size; outer >= 0; outer--) {
for (int inner = size; inner >= 0; inner--) {
if (sudoku[outer][inner] == 0) {
allIndexes.push(new Integer[] { outer, inner, 1 });
}
}
}
return allIndexes;
}
/**
* Clones the given sudoku, so we can make changes with out affecting the
* original.
* @param original the original Sudoku
* @return a copy of the original.
*/
private static int[][] cloneSudoku(int[][] original) {
int sizeSudoku = original.length;
int[][] newArr = new int[sizeSudoku][sizeSudoku];
for (int i = 0; i < sizeSudoku; i++) {
newArr[i] = original[i].clone();
}
return newArr;
}
}
</code></pre>
<p>I also wrote a simple JUnit test file.</p>
<pre><code>import static org.junit.Assert.fail;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Arrays;
import java.util.Scanner;
import org.junit.Before;
import org.junit.Test;
/**
* Simple test clas to test my Solve Sudoku.
*
* @author Luke Kelly
* @version 1.0
*/
public class TestSolver {
// The size of a sudoku
private int DIMENSIONS_OF_SUDOKU = 9;
// Interger representation of an emtpy space
private int EMPTY_SPACE = 0;
// The original sudoku generated every time.
int[][] sudoku = new int[DIMENSIONS_OF_SUDOKU][DIMENSIONS_OF_SUDOKU];
/*
* Generates a random sudoku from the python file I found online.
*/
@Before
public void generateRandomSudoku() {
// Python command to tell terminal
String command = "python ";
// Location of the file.
String pathToFile = "Path to Generator";//Change this before you run.
// The process that will run to create the file.
Process generator;
try {
// Run python script to generate a sudoku file.
generator = Runtime.getRuntime().exec(command + pathToFile);
/*
* Wait for file to be created, the python process will close itself
* when it is done.
*/
generator.waitFor();
} catch (IOException e) {
/*
* Used in the testCreateFile test to make sure the generator is
* working properly
*/
fail("Could not run the python script");
} catch (InterruptedException e) {
/*
* Used in the testCreateFile test to make sure the generator is
* working properly
*/
fail("The process was interrupted");
}
// File location of the file
File puzzle = new File("Path to puzzle");//Change this before you run
try {
// Scanner to read through the file.
Scanner inFile = new Scanner(puzzle);
int outer = 0;
while (inFile.hasNextLine()) {
String line = inFile.nextLine();
for (int i = 0; i < DIMENSIONS_OF_SUDOKU; i++) {
// Stores the int value of the char in the array.
sudoku[outer][i] = (line.charAt(i) - '0');
}
outer++;
}
inFile.close();
} catch (FileNotFoundException e) {
/*
* Used in the testCreateFile test to make sure the generator is
* working properly
*/
fail("Puzzle file was not created.");
}
}
@Test
/**
* Test to make sure the file generator is working properly.
*/
public void testCreateFile() {
generateRandomSudoku();
}
@Test
public void testSolver() {
// Check 10 different Sudokus.
int numTests = 10;
for (int testNumber = 0; testNumber < numTests; testNumber++) {
generateRandomSudoku();
int[][] solvedSudoku = SudokuSolver.solveSudoku(this.sudoku);
if (!checkSameSudoku(solvedSudoku))
fail("The sudoku was not the same as the original " + testNumber);
if (!isComplete(solvedSudoku)) {
for (int[] integers : solvedSudoku) {
System.out.println(Arrays.toString(integers));
}
fail("The sudoku was not correct " + testNumber);
}
}
}
/**
* Checks if the given sudoku is complete and that there are no duplicate
* nubmers.
*/
private boolean isComplete(int[][] compSudoku) {
// Check if all rows are correct first.
for (int outer = 0; outer < DIMENSIONS_OF_SUDOKU; outer++) {
// Add one to DIMENSIONS_OF_SUDOKU because the number 9 is allowed.
boolean[] hasBeenUsed = new boolean[DIMENSIONS_OF_SUDOKU + 1];
Arrays.fill(hasBeenUsed, false);
for (int inner = 0; inner < DIMENSIONS_OF_SUDOKU; inner++) {
int value = compSudoku[outer][inner];
boolean check = checkValue(hasBeenUsed, value);
if (!check)
return false;
}
}
// Check if all colums are correct second.
for (int outer = 0; outer < DIMENSIONS_OF_SUDOKU; outer++) {
// Add one to DIMENSIONS_OF_SUDOKU because the number 9 is allowed.
boolean[] hasBeenUsed = new boolean[DIMENSIONS_OF_SUDOKU + 1];
Arrays.fill(hasBeenUsed, false);
for (int inner = 0; inner < DIMENSIONS_OF_SUDOKU; inner++) {
int value = compSudoku[inner][outer];
boolean check = checkValue(hasBeenUsed, value);
if (!check)
return false;
}
}
/* If we get here then we know all colums and rows are correct */
return true;
}
private boolean checkValue(boolean[] hasBeenUsed, int value) {
boolean returnedValue = true;
//If the value has already been used.
if (hasBeenUsed[value] == true) {
returnedValue = false;
/*If the value is less than max number allowed
If the value is less than one
If the value is less is an Emtpy space.
return false.*/
} else if (value > DIMENSIONS_OF_SUDOKU || value < 1 || value == EMPTY_SPACE) {
returnedValue = false;
} else {
//Allowed number store it so it can't be used again.
hasBeenUsed[value] = true;
//ReturnedValue is already set to true so don't change it.
}
return returnedValue;
}
/**
* Checks if the given sudoku is the same as the original.
*/
private boolean checkSameSudoku(int[][] compSudoku) {
//Loop through every index.
for (int outer = 0; outer < DIMENSIONS_OF_SUDOKU; outer++) {
for (int inner = 0; inner < DIMENSIONS_OF_SUDOKU; inner++) {
/*
* If there isn't and empty space in the original at this index
* check this location agains the completed Sudoku.
*/
if (sudoku[outer][inner] != EMPTY_SPACE) {
if (sudoku[outer][inner] != compSudoku[outer][inner])
//If they are not the same return false.
return false;
}
}
}
return true;
}
}
</code></pre>
<p>Thanks in advance!</p>
|
[] |
[
{
"body": "<h2>Minor typos / grammar</h2>\n\n<p><em>Note: most IDEs have a spellchecker and will highlight wrongly spelled words</em></p>\n\n<p>You have an extra space between <code>static</code> and <code>int</code> on line 16. - Most code bases have checkstyle or similair processes to prevent this sort of error, so I wouldn't worry about these sort of things. I just wanted to include it for completeness.</p>\n\n<p>I suggest changing the class comment to \"solves a Sudoku board\" instead of \"solves a Sudoky\". A bit knit picky but same goes for the class comment \"solves the given sudoku\" vs \"solves the given Sudoku board\"</p>\n\n<p>\"reperesnted\" should be \"represented\"</p>\n\n<p>\"colum\" should be \"column\"</p>\n\n<p>\"emtpy\" should be \"empty\" ...</p>\n\n<h2>Javadoc</h2>\n\n<p>You can use formatting in your javadocs. Assuming you are using an IDE such as eclipse you can highlight the method to see what the javadoc looks like:</p>\n\n<pre><code>/**\n * Solves the given Sudoku, preconditions: \n * <ul>\n * <li>Empty space is reperesnted by 0s</li> \n * <li>The sudoku is not already invalid (No duplicates in a row, colum, or 3x3 box,except zeros)</li> \n * <li>The sudoku is a normal 9x9 sudoku</li>\n * </ul>\n * @return a solved sudoku if the sudoku is solvable, null if not\n */\npublic static int[][] solveSudoku(int[][] original) {\n</code></pre>\n\n<p><a href=\"https://i.stack.imgur.com/Bj6Wb.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/Bj6Wb.png\" alt=\"enter image description here\"></a></p>\n\n<p>Otherwise you can generate Javadoc documentation and see what it looks like.</p>\n\n<h2>Single responsibility principle</h2>\n\n<p>Try to think of methods by themselves. For example, the javadoc for 'solvesudoku' mentions it's a helper method for another method. Try to avoid this mindset. Reading the javadoc I'd like to know what the method does, without going through the javadoc for other methods.</p>\n\n<h2>Method / variable naming</h2>\n\n<p>\"solveSudoku\" does not make sense. \"isSudokuSolved\" or \"isSudokuBoardSolved\" makes more sense.</p>\n\n<h2>Avoid magic numbers / magic strings</h2>\n\n<p>For example numbers \"9\" and \"3\" could be declared as static variables at the top. I'd also suggest doing the same for your empty space variable (0) so it's easier to find / change.</p>\n\n<h2>Testing</h2>\n\n<p>I was disappointed to see your test references a Python file you found online. Tbh I didn't bother trying to test your code, there's just too much logic in the test classes for me to want to bother with.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-04T06:46:40.020",
"Id": "235056",
"ParentId": "235053",
"Score": "6"
}
},
{
"body": "<p>As an industry professional, here's what immediately comes to my mind:</p>\n\n<ul>\n<li><code>class SudokuSolver</code>: package private class? Why?</li>\n<li>inconsistent spacing (two spaces before the <code>int[][] solveSudoku</code>, sometimes spaces before opening braces, sometimes not, ... - yes, we notice these details!)</li>\n<li>Comments repeating the code.</li>\n<li>Use of <code>Stack</code> class (see opening comment in API-doc, e.g. <a href=\"https://docs.oracle.com/javase/10/docs/api/java/util/Stack.html\" rel=\"noreferrer\">https://docs.oracle.com/javase/10/docs/api/java/util/Stack.html</a>)</li>\n<li><code>Integer[]</code> to represent a set of coordinates. Ususally, if you have a business concept behind a given set of variables, it is worth to create a class which has a correct name for that, so that every reader can immediately grasp the concept. Better: create a <code>Coordinates</code> class (or <code>Point</code> or whatever)</li>\n<li><code>int EMPTY_CELL = 0</code> if this is a variable, this should be named <code>emptyCell</code>. As a constant, it should be <code>static final</code> in the class, and probably <code>public</code> as well, so that the user can utilize the constant to create the input.</li>\n<li>I like the explanatory comment for the algorithm combined with the simple commentens <code>// 1</code>, <code>// 2</code> etc. - makes it very clear to me.</li>\n<li>Use of recursion: even if the problem is small, (i.e. you'll have a maximum recursion depth of 81 - n where n is the number of initially filled fields) the technique of recursion itself is mostly a red light, as it tends to be uncontrollable very fast. So (in my book): either unroll the recursion to replace it with an iterative solution, or at least add a comment that you thought this out and why there is no risk in doing it recursively. (Note that this is not true in pure functional languages ;-))</li>\n<li>Unit test based on random generation: NO. There is no guarantee that after a given software change the random test will actually catch a new bug. (E.g. maybe you \"accidentally\" generate a sudoku which is solvable by only looking at rows and columns, and never even uses the box-check.)</li>\n</ul>\n\n<p>Hope that helps. (And BTW: with this code, you'd get my consent to start in the company as a junior software engineer :-))</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-04T07:15:48.847",
"Id": "459844",
"Score": "0",
"body": "Thanks for your input! I have a quick question about the use of Stack though. Are you saying I should of used something other than a Stack? I read the opening comments and it says use a Deque, should I have used that?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-04T07:18:37.157",
"Id": "459845",
"Score": "0",
"body": "I just noticed I was using add instead of push, is that what you were talking about?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-04T08:45:45.170",
"Id": "459849",
"Score": "0",
"body": "Yes, use a deque of any kind, e.g. a linked list."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-04T06:57:18.240",
"Id": "235057",
"ParentId": "235053",
"Score": "5"
}
},
{
"body": "<p>I did not bother to read your test code in detail, as that code looks totally unexpected to me.</p>\n\n<p>In the test for a sudoku solver there must be at least one full example sudoku that is solved and validated.</p>\n\n<p>The test must not depend on external files and it must not run external programs since a sudoku solver gets an incomplete sudoku board as input and returns a complete sudoku board as output. That's all.</p>\n\n<p>In a <a href=\"https://github.com/rillig/Phantom-Go-Android/blob/327ddd514779606fe13a742150bb1da0d26aae45/app/src/test/java/de/roland_illig/phantomgo/BoardTest.kt#L7\" rel=\"nofollow noreferrer\">completely unrelated project</a> I have some code that demonstrates how simple a unit test can be, and how the code can almost disappear behind the actually interesting test data.</p>\n\n<p>Regarding your main code: it is bad style to have several <code>static</code> methods that all operate on a two-imensional <code>int</code> array. It's much better to define a data type called <code>Sudoku</code> that encapsulates and hides the array. That way your code can concentrate on solving sudokus instead of dealing with the low-level array terminology.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-05T17:19:48.967",
"Id": "235121",
"ParentId": "235053",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "235056",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-04T02:13:58.673",
"Id": "235053",
"Score": "3",
"Tags": [
"java",
"beginner",
"recursion"
],
"Title": "Sudoku Solver questions on style and algorithm"
}
|
235053
|
<p>I have developed this script to find the counts of attachment records stored in a table in PostgreSQL for different other tables. I check if the <code>res_id</code> field of <code>ir_attachment</code> table is existed in it's corresponding table <code>(res_model)</code> and if it's not existed, I increase the counter. This script works fine and I get the desired result but it is slow with big number of records (9000000 -10000000). How can I improve this script's performance to optimize it? Should I use any SQL technic or bring changes in python code?</p>
<pre><code>def delete_attachment(self):
self.apps_cursor.execute("""
SELECT id,res_id,res_model FROM ir_attachment WHERE res_model IS NOT NULL AND res_id IS NOT NULL limit 5;
""")
counter = 0
attachment_records = self.apps_cursor.fetchall()
print '=========================================Checking attachment records started========================================='
self.apps_cursor.execute("""
SELECT model FROM ir_model WHERE model IS NOT NULL;
""")
apps_models = self.apps_cursor.fetchall()
apps_models = [model.get('model') for model in apps_models]
for record in attachment_records:
if record['res_model'] in apps_models:
model_name = str(record['res_model'].replace('.', '_'))
self.apps_cursor.execute("""
SELECT id FROM %s WHERE id=%s
""" % (model_name, record['res_id']))
model_record = self.apps_cursor.fetchall()
if not model_record:
counter += 1
print 'Total attachment records with out res_id field existed in corresponding model:', counter
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-04T05:32:49.030",
"Id": "459841",
"Score": "0",
"body": "I would recommend writing any future python programs in `python-3.x`, as [python2.x has reached it's end of life.](https://www.infoq.com/news/2019/09/python-2-end-of-life-approaching/)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-04T05:41:11.793",
"Id": "459842",
"Score": "0",
"body": "Thank you for nice suggestion, actually I did this in python 2 because of some limitation. Server not supporting python 3 and I can't run any python 3 code there."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-05T23:09:51.320",
"Id": "460040",
"Score": "0",
"body": "Then I would recommend upgrading your server to python 3."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-04T05:15:40.627",
"Id": "235055",
"Score": "1",
"Tags": [
"python",
"performance",
"python-2.x",
"postgresql"
],
"Title": "Reading attachment data from a PostgreSQL table with python"
}
|
235055
|
<p>I'm doing questions on HackerRank to brush up on Java & CS.</p>
<hr>
<p><strong>Problem</strong></p>
<p>This problem is called <em>Sparse Arrays</em> in HackerRank.</p>
<blockquote>
<p>There is a collection of input strings and a collection of query
strings. For each query string, determine how many times it occurs in
the list of input strings.</p>
<p>For example, given input <code>strings = ['ab', 'ab', 'bc']</code> and <code>queries =
['ab', 'abc', 'bc']</code>, result is <code>[2, 1, 0]</code></p>
<p><a href="https://www.hackerrank.com/challenges/sparse-arrays/problem" rel="nofollow noreferrer">Full Question</a></p>
</blockquote>
<p><strong>Solution</strong></p>
<pre><code>static int[] matchingStrings(String[] strings, String[] queries) {
Map<String, Integer> counter = new HashMap<>();
for (String current: strings) {
counter.put(current, counter.getOrDefault(current, 0) + 1);
}
int[] result = new int[queries.length];
for (int i = 0; i < queries.length; i++) {
result[i] = counter.getOrDefault(queries[i], 0);
}
return result;
}
</code></pre>
<p>This passes all the test cases. </p>
<ol>
<li>Can I do it in a better way? </li>
<li>Can this be simplified in Java-8, 11 or later?</li>
</ol>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-04T14:12:05.690",
"Id": "459882",
"Score": "1",
"body": "I checked the history of edits for your question and originally it didn't look very clear. Maybe that's why someone downvoted that version."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-04T14:27:13.273",
"Id": "459884",
"Score": "0",
"body": "Fair enough.. Sparse Array title might've been confusing. Hopefully new title makes more sense"
}
] |
[
{
"body": "<blockquote>\n <p>Can I do it in a better way?</p>\n</blockquote>\n\n<p>From the time complexity or space complexity your solution is good enough. Your store all your string frequencies beforehand so that to retrieve a frequency by any given string in <code>O(1)</code> time later. Also, it passes all the test cases so it's a good sign too.</p>\n\n<p>Below are a couple of concerns regarding other aspects of your code.</p>\n\n<p><strong>Variable Naming</strong></p>\n\n<p>Your choice of variable names should be improved. For instance, <code>Map<String, Integer> counter</code> doesn't really reflect for what it stands for. I would call it <code>stringFrequencyMap</code> or <code>stringCountMap</code>. </p>\n\n<p>Also, <code>result</code> sounds too generic here. How about <code>queryResults</code>?</p>\n\n<p>I'll leave it up to you to think about other variable names you have (luckily not many left :) ).</p>\n\n<p><strong>Static method</strong></p>\n\n<p>I guess you've kept this method <code>static</code> as it was like this by default and to avoid creating an instance of your <code>Solution</code> class in the <code>main()</code> method. While it's fine for a small challenge like yours, generally there should be a good reason to add <code>static</code> to your method.</p>\n\n<p><strong>Improvements</strong></p>\n\n<blockquote>\n <p>Can this be simplified in Java-8, 11 or later?</p>\n</blockquote>\n\n<p>Of course, if we just use <strong>JAVA 8</strong> then we can take advantage of <code>streams</code> and write a solution as :</p>\n\n<pre><code>static long[] matchingStrings(String[] strings, String[] queries) {\n Map<String, Long> stringCountMap = Arrays.stream(strings).collect(Collectors.groupingBy(Function.identity(), counting()));\n\n return Arrays.stream(queries).mapToLong(query -> stringCountMap.getOrDefault(query, 0L)).toArray();\n}\n</code></pre>\n\n<p>As you can see, we do this in 2 steps. First, we calculate a frequency map and then calculate an array of results using streams again. Please note that I changed the return type from <code>int[]</code> to <code>long[]</code>.</p>\n\n<p><strong>UPDATE</strong></p>\n\n<p>Since there was a question why I've used <code>Map<String, Long></code> rather than <code>Map<String, Integer></code> - well, <code>Long</code> can hold bigger numbers. But since it's irrelevant for this problem here's a solution for <code>Map<String, Integer></code>:</p>\n\n<pre><code>int[] matchingStrings(String[] strings, String[] queries) {\n Map<String, Integer> stringCountMap = Arrays.stream(strings).collect(Collectors.groupingBy(Function.identity(), summingInt(x -> 1)));\n\n return Arrays.stream(queries).mapToInt(query -> stringCountMap.getOrDefault(query, 0)).toArray();\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-04T15:10:45.490",
"Id": "235073",
"ParentId": "235068",
"Score": "4"
}
},
{
"body": "<p>I have some suggestions for your code.</p>\n\n<p>1) Since we know the size of the output, I suggest that you initialize the <code>java.util.HashMap</code> with the size + 1, since the default capacity of a <code>Map</code> is 16; this will prevent the map to do a rehashing if you have more than 16 values.</p>\n\n<p>If you want more information about the rehashing / load factor, you can read the <code>java.util.HashMap</code> <a href=\"https://docs.oracle.com/en/java/javase/13/docs/api/java.base/java/util/HashMap.html\" rel=\"nofollow noreferrer\">javadoc</a>.</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>//[...]\nint queryLength = queries.length;\nMap<String, Integer> counter = new HashMap<>(queryLength + 1);\n//[...]\n</code></pre>\n\n<p>2) I suggest that you create a method to create a <code>Map</code> containing the count of the similar string; instead of building it in the method.</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>\nstatic int[] matchingStrings(String[] strings, String[] queries) {\n int queryLength = queries.length;\n Map<String, Integer> counter = getSimilarStringCountMap(strings, queryLength);\n //[...]\n}\n\n\nprivate static Map<String, Integer> getSimilarStringCountMap(String[] strings, int queryLength) {\n Map<String, Integer> counter = new HashMap<>(queryLength + 1);\n\n for (String current : strings) {\n counter.put(current, counter.getOrDefault(current, 0) + 1);\n }\n return counter;\n}\n</code></pre>\n\n<p><strong>Refactored code</strong></p>\n\n<pre class=\"lang-java prettyprint-override\"><code> public static void main(String[] args) {\n String[] strings = {\"ab\", \"ab\", \"bc\"};\n String[] queries = {\"ab\", \"abc\", \"bc\"};\n\n System.out.println(Arrays.toString(matchingStrings(strings, queries)));\n }\n\n static int[] matchingStrings(String[] strings, String[] queries) {\n int queryLength = queries.length;\n\n Map<String, Integer> counter = getSimilarStringCountMap(strings, queryLength);\n\n int[] result = new int[queryLength];\n for (int i = 0; i < queryLength; i++) {\n result[i] = counter.getOrDefault(queries[i], 0);\n }\n\n return result;\n }\n\n private static Map<String, Integer> getSimilarStringCountMap(String[] strings, int queryLength) {\n Map<String, Integer> counter = new HashMap<>(queryLength + 1);\n\n for (String current : strings) {\n counter.put(current, counter.getOrDefault(current, 0) + 1);\n }\n\n return counter;\n }\n<span class=\"math-container\">```</span>\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-04T17:01:45.657",
"Id": "235081",
"ParentId": "235068",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "235073",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-04T13:53:43.883",
"Id": "235068",
"Score": "4",
"Tags": [
"java",
"programming-challenge"
],
"Title": "Given n input strings and m query strings, find each query frequency in the list of input strings"
}
|
235068
|
<p>I am currently completing "The Odin Project" and one of the first projects was to create a google homepage. I was wondering if some people could tell me all the long winded and unnecessary code I added and also tell me how I can better go about sticking the footer to the bottom of the page.</p>
<p><a href="https://github.com/LHUF/google-homepage" rel="nofollow noreferrer">https://github.com/LHUF/google-homepage</a></p>
<p>HTML:</p>
<pre class="lang-html prettyprint-override"><code> <!DOCTYPE html>
<html>
<head>
<title>Google</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="aboutstore"><a href="about.html" id="about" class="links">About</a> <a href="store.html" class="links">Store</a></div>
<div class="gmailimages"><a href=gmail.html id="gmail" class="links">Gmail</a> <a href="images.html" class="links">Images</a></div>
<div id="searcharea"><h1><a href="file:///home/louis/TOP_Projects/google-homepage/index.html"><img src="https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png" width="300dp" height="100dp" alt="Google"></h1></a>
<form method="GET">
<input type="text" id="searchbar"></input><br>
<input type="submit" value="Google Search" class="searchbuttons"></input>
<input type="submit" value="I'm Feeling Lucky" class="searchbuttons" id="imfeelinglucky"></input>
</form></div>
<div id="unitedkingdom">United Kingdom</div>
<div id="bottomleftoptions"><a href="advertising.html" class="links">Advertising</a> <a href="business.html" class="links">Business</a> <a href="howsearchworks.html" class="links">How Search Works</a></div>
<div id="bottomrightoptions"><a href="privacy.html" class="links">Privacy</a> <a href="terms.html" class="links">Terms</a> <a href="Settings" class="links">Settings</a></div>
</body>
</html>
</code></pre>
<p>CSS:</p>
<pre class="lang-css prettyprint-override"><code>#imfeelinglucky {
margin-left: 10px;
}
.searchbuttons {
margin-top: 20px;
text-align: center;
height: 30px;
}
img {
display: block;
margin-left: auto;
margin-right: auto;
}
#searchbar {
width: 400px;
height: 25px;
margin-top: -30px;
}
#searcharea {
text-align: center;
padding-top: 200px;
}
#unitedkingdom {
position: relative;
bottom: 5%;
border-top-style: solid;
border-bottom-style: solid;
border-top: 1px;
border-bottom: 1px;
padding-top: 5px;
padding-bottom: 5px;
margin-top: 505px;
color: rgba(0,0,0,.54);
background: #f2f2f2;
padding-left: 25px;
font-size: 15px;
}
.gmailimages {
position: absolute;
top: 1%;
right: 1%;
}
.aboutstore {
position: absolute;
top: 1%;
left: 1%;
}
#bottomrightoptions {
padding-right: 25px;
font-size: 13px;
padding-top: 15px;
color: rgba(0,0,0,.54);
background: #f2f2f2;
position: absolute;
float: right;
padding-left: 800px;
bottom: 0.5%;
right: 0%;
}
#bottomleftoptions {
padding-left: 25px;
font-size: 13px;
padding-top: 15px;
color: rgba(0,0,0,.54);
background: #f2f2f2;
position: absolute;
float: left;
padding-right: 800px;
bottom: 0.5%;
left: 0%;
}
#about {
margin-right: 5px;
}
#gmail {
margin-right: 5px;
}
.links {
color: #000;
text-decoration: none;
font-size: 13px;
}
body {
font-family: Arial, sans-serif;
margin:0;
padding:0;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-04T14:59:04.087",
"Id": "459889",
"Score": "1",
"body": "Welcome to code review where we review working code and provide solutions on how to improve that code. Questions such as `tell me how I can better go about sticking the footer to the bottom of the page` may indicate the code is not working as intended."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-04T20:06:16.910",
"Id": "459927",
"Score": "0",
"body": "Yes this is working on my browser I was looking for a review of how I could maybe achieve this better and so it works on phone etc"
}
] |
[
{
"body": "<p>while your code runs, personally I would change the formatting to start with</p>\n\n<p>I noticed your search area div has a mistake in it, your H1 encloses the Anchor tag and the image but you close the H1 tag before closing the anchor tag, which is syntactically incorrect. I also noticed that you were missing quotation marks around the value of one of your anchor tags in the gmailimages,\nI will make these changes in the suggestions I post below.</p>\n\n<p>Some things like your anchor tags inside of your divs could be on new lines to make the code more readable, let me show you what it looks like when I move the tags to their own lines.</p>\n\n<pre><code><body>\n <div class=\"aboutstore\">\n <a href=\"about.html\" id=\"about\" class=\"links\">About</a> \n <a href=\"store.html\" class=\"links\">Store</a>\n </div>\n\n <div class=\"gmailimages\">\n <a href=gmail.html id=\"gmail\" class=\"links\">Gmail</a> \n <a href=\"images.html\" class=\"links\">Images</a>\n </div>\n\n <div id=\"searcharea\">\n <h1>\n <a href=\"file:///home/louis/TOP_Projects/google-homepage/index.html\">\n <img src=\"https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png\" width=\"300dp\" height=\"100dp\" alt=\"Google\">\n </a>\n </h1>\n <form method=\"GET\">\n <input type=\"text\" id=\"searchbar\"></input><br>\n <input type=\"submit\" value=\"Google Search\" class=\"searchbuttons\"></input>\n <input type=\"submit\" value=\"I'm Feeling Lucky\" class=\"searchbuttons\" id=\"imfeelinglucky\"></input>\n </form>\n </div>\n\n <div id=\"unitedkingdom\">United Kingdom</div>\n <div id=\"bottomleftoptions\">\n <a href=\"advertising.html\" class=\"links\">Advertising</a> \n <a href=\"business.html\" class=\"links\">Business</a> \n <a href=\"howsearchworks.html\" class=\"links\">How Search Works</a>\n </div>\n <div id=\"bottomrightoptions\">\n <a href=\"privacy.html\" class=\"links\">Privacy</a> \n <a href=\"terms.html\" class=\"links\">Terms</a> \n <a href=\"Settings\" class=\"links\">Settings</a>\n </div>\n</body>\n</code></pre>\n\n<p>The next thing that I would suggest is to look into HTML5, there are nice tags for things like</p>\n\n<ul>\n<li>Navigation Menus</li>\n<li>Headers</li>\n<li>Footers</li>\n<li>etc.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-05T03:18:11.863",
"Id": "235101",
"ParentId": "235069",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-04T14:07:28.740",
"Id": "235069",
"Score": "3",
"Tags": [
"html",
"css"
],
"Title": "First ever webpage (Google homepage)"
}
|
235069
|
<p>I am using Java 7</p>
<p><strong>Problem:</strong> I need to retrieve records from a database table based on a condition, orig_setting = 1. This query could return ~1000 records. Parameters from 1-7 of the Params object are set with this query. </p>
<p>In the next query, I need to retrieve records from the same table based on another condition, curr_setting = 1. This query could return ~900 records. Parameter 8 of Params object is set with this query. </p>
<p>Params object has 9 fields altogether, of which paramId maps to the the primary key of the database table.</p>
<p><strong>Solution proposed by me:</strong> I have decided that when query 1 is run, all the records will be stored in a hashmap with the key being the paramId of the Params object and the value being the Params object itself</p>
<p>When the second query is fired, a get in performed on the hashmap based on the param id; if Param object is returned, then paramater 8 is set. </p>
<pre><code>import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class DisplayGrid {
public static void main(String[] args) {
DisplayGrid displayGrid = new DisplayGrid();
displayGrid.showGridDetails();
}
private void showGridDetails() {
Params paramsDO = null;
Map<Integer, Params> gridData = new HashMap<>();
// This could return ~1000 records
// In the Params object, 8 fields out of 9 are set with one field(param_id) being the primary key
String selectQuery = "SELECT * FROM table1 WHERE orig_setting = 1";
try (Connection connection = DriverManager.getConnection("DB Settings");
Statement stmt = connection.createStatement();
ResultSet resultSet = stmt.executeQuery(selectQuery);) {
while (resultSet.next()) {
paramsDO = new Params();
paramsDO.setParamId(resultSet.getInt("PARAM_ID"));
paramsDO.setParam1(resultSet.getString("PARAM_1"));
paramsDO.setParam2(resultSet.getString("PARAM_2"));
paramsDO.setParam3(resultSet.getString("PARAM_3"));
paramsDO.setParam4(resultSet.getString("PARAM_4"));
paramsDO.setParam5(resultSet.getString("PARAM_5"));
paramsDO.setParam6(resultSet.getString("PARAM_6"));
paramsDO.setParam7(resultSet.getString("PARAM_7"));
// key is the primary key(param_id)
gridData.put(new Integer(paramsDO.getParamId()), paramsDO);
}
} catch (Exception e) {
throw e;
}
// This could return ~900 records
// from this query, the 9th field is set based on the paramId
selectQuery = "SELECT * FROM table1 WHERE curr_setting = 1";
try (Connection connection = DriverManager.getConnection("DB Settings");
Statement stmt = connection.createStatement();
ResultSet resultSet = stmt.executeQuery(selectQuery);) {
while (resultSet.next()) {
paramsDO = null;
int currParamId = resultSet.getInt("PARAM_ID");
paramsDO = gridData.get(currParamId);
if (paramsDO != null)
paramsDO.setParam8(resultSet.getString("PARAM_8"));
}
} catch (Exception e) {
throw e;
}
}
private class Params {
private int paramId; // Primary Key
private String param1;
private String param2;
private String param3;
private String param4;
private String param5;
private String param6;
private String param7;
private String param8;
public Params() {
super();
}
public Params(int paramId, String param1, String param2, String param3,
String param4, String param5, String param6, String param7,
String param8) {
super();
this.paramId = paramId;
this.param1 = param1;
this.param2 = param2;
this.param3 = param3;
this.param4 = param4;
this.param5 = param5;
this.param6 = param6;
this.param7 = param7;
this.param8 = param8;
}
public int getParamId() {
return paramId;
}
public void setParamId(int paramId) {
this.paramId = paramId;
}
public String getParam1() {
return param1;
}
public void setParam1(String param1) {
this.param1 = param1;
}
public String getParam2() {
return param2;
}
public void setParam2(String param2) {
this.param2 = param2;
}
public String getParam3() {
return param3;
}
public void setParam3(String param3) {
this.param3 = param3;
}
public String getParam4() {
return param4;
}
public void setParam4(String param4) {
this.param4 = param4;
}
public String getParam5() {
return param5;
}
public void setParam5(String param5) {
this.param5 = param5;
}
public String getParam6() {
return param6;
}
public void setParam6(String param6) {
this.param6 = param6;
}
public String getParam7() {
return param7;
}
public void setParam7(String param7) {
this.param7 = param7;
}
public String getParam8() {
return param8;
}
public void setParam8(String param8) {
this.param8 = param8;
}
@Override
public String toString() {
return "Params [paramId=" + paramId + ", param1=" + param1
+ ", param2=" + param2 + ", param3=" + param3 + ", param4="
+ param4 + ", param5=" + param5 + ", param6=" + param6
+ ", param7=" + param7 + ", param8=" + param8 + "]";
}
}
}
</code></pre>
<p>Kindly suggest how this code can be improved to increase the performance. Also, suggest other possible solutions. </p>
<p>What other java data structure can I use for this purpose; could be one from other java libraries too</p>
<p>Posting the sample database table </p>
<pre><code>+----+-----+-------+---------+---------+
| Id | Key | Value | Is_Orig | Is_Prev |
+----+-----+-------+---------+---------+
| 1 | 10 | 1000 | 1 | 0 |
| 2 | 10 | 2000 | 0 | 0 |
| 3 | 10 | 3000 | 0 | 1 |
| 4 | 10 | 4000 | 0 | 0 |
| 5 | 20 | 100 | 1 | 0 |
| 6 | 20 | 300 | 0 | 1 |
| 7 | 20 | 400 | 0 | 0 |
| 8 | 30 | 10 | 1 | 0 |
+----+-----+-------+---------+---------+
</code></pre>
<p>Expected result </p>
<pre><code>+-----+------------+------------+
| Key | Orig Value | Prev Value |
+-----+------------+------------+
| 10 | 1000 | 3000 |
| 20 | 100 | 300 |
| 30 | 10 | n/a |
+-----+------------+------------+
</code></pre>
|
[] |
[
{
"body": "<p>there was an issue with the code, I was obligated to add the <code>SQLException</code> to the method, since the code was not compiling otherwise.</p>\n\n<p><strong>Before</strong></p>\n\n<pre class=\"lang-java prettyprint-override\"><code>//[...]\nprivate void showGridDetails() {}\n//[...]\n</code></pre>\n\n<p><strong>After</strong></p>\n\n<pre class=\"lang-java prettyprint-override\"><code>//[...]\nprivate void showGridDetails() throws SQLException {}\n//[...]\n</code></pre>\n\n<p>For the review, here what I suggest:</p>\n\n<h2>SQL</h2>\n\n<p>I suggest that you put an example of the table with false data and the name / kind (MySQL, Oracle, PostgreSQL) of the database that you are using, so we can have a better understanding of it.</p>\n\n<h2>Code</h2>\n\n<h3>Method <code>showGridDetails</code></h3>\n\n<p>1) Extract the variable <code>selectQuery</code> into two constants, this will be better since it will make the code shorter and the string won’t be recreated each time the method is called.</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>public static final String FIRST_QUERY = \"SELECT * FROM table1 WHERE orig_setting = 1\";\npublic static final String SECOND_QUERY = \"SELECT * FROM table1 WHERE curr_setting = 1\";\n</code></pre>\n\n<p>2) In my opinion, when I have multiples <code>java.lang.AutoCloseable</code> to chain, I prefer to have multiples <code>try</code>.</p>\n\n<p><strong>Before</strong></p>\n\n<pre class=\"lang-java prettyprint-override\"><code>try (Connection connection = DriverManager.getConnection(\"DB Settings\");\n Statement stmt = connection.createStatement();\n ResultSet resultSet = stmt.executeQuery(FIRST_QUERY);) {\n // [...]\n} catch (Exception e) {\n throw e;\n}\n</code></pre>\n\n<p><strong>After</strong></p>\n\n<pre class=\"lang-java prettyprint-override\"><code>try (Connection connection = DriverManager.getConnection(\"DB Settings\")) {\n try (Statement stmt = connection.createStatement()) {\n try (ResultSet resultSet = stmt.executeQuery(FIRST_QUERY)) {\n //[...]\n }\n }\n} catch (Exception e) {\n throw e;\n}\n</code></pre>\n\n<p>3) Instead of using the <code>Statement</code> and passing the parameter, I suggest that you use the <code>java.sql.PreparedStatement</code>. In my opinion, the <code>java.sql.PreparedStatement</code> is a better choice even if the parameter is hardcoded. This will offer better performances and security (SQL injection), if the parameter changes and comes from the user, external source, etc.</p>\n\n<p>If you want more arguments, I suggest <a href=\"https://stackoverflow.com/questions/3271249/difference-between-statement-and-preparedstatement\">Difference between Statement and PreparedStatement</a> on stackoverflow.</p>\n\n<p>Examples: <a href=\"https://docs.oracle.com/javase/tutorial/jdbc/basics/prepared.html\" rel=\"nofollow noreferrer\">https://docs.oracle.com/javase/tutorial/jdbc/basics/prepared.html</a></p>\n\n<pre class=\"lang-java prettyprint-override\"><code>try (Connection connection = DriverManager.getConnection(\"DB Settings\")) {\n try (PreparedStatement stmt = connection.prepareStatement(FIRST_QUERY)) {\n stmt.setInt(1, 1);\n\n try (ResultSet resultSet = stmt.executeQuery()) {\n while (resultSet.next()) {\n paramsDO = new Params();\n paramsDO.setParamId(resultSet.getInt(\"PARAM_ID\"));\n paramsDO.setParam1(resultSet.getString(\"PARAM_1\"));\n paramsDO.setParam2(resultSet.getString(\"PARAM_2\"));\n paramsDO.setParam3(resultSet.getString(\"PARAM_3\"));\n paramsDO.setParam4(resultSet.getString(\"PARAM_4\"));\n paramsDO.setParam5(resultSet.getString(\"PARAM_5\"));\n paramsDO.setParam6(resultSet.getString(\"PARAM_6\"));\n paramsDO.setParam7(resultSet.getString(\"PARAM_7\"));\n// key is the primary key(param_id)\n gridData.put(new Integer(paramsDO.getParamId()), paramsDO);\n }\n }\n }\n} catch (Exception e) {\n throw e;\n}\n\n</code></pre>\n\n<p>4) The creation of a new <code>Integer</code> is useless, since the <code>Params#paramId</code> is already an int.</p>\n\n<p><strong>Before</strong></p>\n\n<pre class=\"lang-java prettyprint-override\"><code>gridData.put(new Integer(paramsDO.getParamId()), paramsDO);\n</code></pre>\n\n<p><strong>After</strong></p>\n\n<pre class=\"lang-java prettyprint-override\"><code>gridData.put(paramsDO.getParamId(), paramsDO);\n</code></pre>\n\n<p>5) Since the method is throwing the exception, both of the <code>catch</code> can be removed.</p>\n\n<p>6) The initialisation of the variable <code>paramsDO</code> to null is useless, since it's updated (in the start & second query).</p>\n\n<p>7) You can use the <code>java.sql.Connection</code> for multiples statements.</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>try (Connection connection = DriverManager.getConnection(\"DB Settings\")) {\n try (PreparedStatement stmt = connection.prepareStatement(FIRST_QUERY)) {\n stmt.setInt(1, 1);\n\n try (ResultSet resultSet = stmt.executeQuery()) {\n while (resultSet.next()) {\n paramsDO = new Params();\n paramsDO.setParamId(resultSet.getInt(\"PARAM_ID\"));\n paramsDO.setParam1(resultSet.getString(\"PARAM_1\"));\n paramsDO.setParam2(resultSet.getString(\"PARAM_2\"));\n paramsDO.setParam3(resultSet.getString(\"PARAM_3\"));\n paramsDO.setParam4(resultSet.getString(\"PARAM_4\"));\n paramsDO.setParam5(resultSet.getString(\"PARAM_5\"));\n paramsDO.setParam6(resultSet.getString(\"PARAM_6\"));\n paramsDO.setParam7(resultSet.getString(\"PARAM_7\"));\n // key is the primary key(param_id)\n gridData.put(paramsDO.getParamId(), paramsDO);\n }\n }\n }\n\n // This could return ~900 records\n // from this query, the 9th field is set based on the paramId\n try (PreparedStatement stmt = connection.prepareStatement(SECOND_QUERY)) {\n stmt.setInt(1, 1);\n try (ResultSet resultSet = stmt.executeQuery()) {\n while (resultSet.next()) {\n int currParamId = resultSet.getInt(\"PARAM_ID\");\n paramsDO = gridData.get(currParamId);\n if (paramsDO != null)\n paramsDO.setParam8(resultSet.getString(\"PARAM_8\"));\n }\n }\n }\n}\n</code></pre>\n\n<p>8) For the comments, I suggest that you use the <code>block-comment (/**/)</code> for the comments with more than one line.</p>\n\n<p><strong>Edited code</strong></p>\n\n<pre class=\"lang-java prettyprint-override\"><code>\npublic static final String FIRST_QUERY = \"SELECT * FROM table1 WHERE orig_setting = ?\";\npublic static final String SECOND_QUERY = \"SELECT * FROM table1 WHERE curr_setting = ?\";\n\nprivate void showGridDetails() throws SQLException {\n Params paramsDO;\n Map<Integer, Params> gridData = new HashMap<>();\n\n /*\n This could return ~1000 records\n In the Params object, 8 fields out of 9 are set with one field(param_id) being the primary key\n */\n try (Connection connection = DriverManager.getConnection(\"DB Settings\")) {\n try (PreparedStatement stmt = connection.prepareStatement(FIRST_QUERY)) {\n stmt.setInt(1, 1);\n\n try (ResultSet resultSet = stmt.executeQuery()) {\n while (resultSet.next()) {\n paramsDO = new Params();\n paramsDO.setParamId(resultSet.getInt(\"PARAM_ID\"));\n paramsDO.setParam1(resultSet.getString(\"PARAM_1\"));\n paramsDO.setParam2(resultSet.getString(\"PARAM_2\"));\n paramsDO.setParam3(resultSet.getString(\"PARAM_3\"));\n paramsDO.setParam4(resultSet.getString(\"PARAM_4\"));\n paramsDO.setParam5(resultSet.getString(\"PARAM_5\"));\n paramsDO.setParam6(resultSet.getString(\"PARAM_6\"));\n paramsDO.setParam7(resultSet.getString(\"PARAM_7\"));\n // key is the primary key(param_id)\n gridData.put(paramsDO.getParamId(), paramsDO);\n }\n }\n }\n\n /*\n This could return ~900 records\n from this query, the 9th field is set based on the paramId\n */\n try (PreparedStatement stmt = connection.prepareStatement(SECOND_QUERY)) {\n stmt.setInt(1, 1);\n try (ResultSet resultSet = stmt.executeQuery()) {\n while (resultSet.next()) {\n int currParamId = resultSet.getInt(\"PARAM_ID\");\n paramsDO = gridData.get(currParamId);\n if (paramsDO != null)\n paramsDO.setParam8(resultSet.getString(\"PARAM_8\"));\n }\n }\n }\n }\n }\n<span class=\"math-container\">```</span>\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-04T16:59:18.943",
"Id": "459897",
"Score": "0",
"body": "Thank you for your review. Is there a better data structure apart from hashmap that can be used for this purpose?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-04T17:38:43.993",
"Id": "459905",
"Score": "0",
"body": "In my opinion, the best way would be to do the mapping on the database side, but if not possible, the `java.util.HashMap` is probably the best way to do the mapping, since the basic operations are constant time (get and put)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-05T17:05:27.003",
"Id": "460013",
"Score": "0",
"body": "I'll incorporate the suggested changes. Thank you for your inputs."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-04T16:13:03.087",
"Id": "235078",
"ParentId": "235070",
"Score": "2"
}
},
{
"body": "<p>My first question has to be: Why Java 7? If this is production code, then your environment urgently needs to be upgraded since 7 hasn't beeen supported by Oracle for over 5 years. And if this is just practice code there is no reason not to use a more (preferably the most) current version.</p>\n\n<hr>\n\n<p>Is this production (or at least realistic) code? It doesn't seem so, since the method doesn't return (or use) the data extracted.</p>\n\n<hr>\n\n<p>You shouldn't be handling the database connection yourself (especially if the is supposed to be production code). At the very least you should not be opening and closing the connection for the two queries. Instead the (open) database connection (or a database connection pool) should be provided from the outside.</p>\n\n<hr>\n\n<p>Then my next question would be: Why have two queries? It seems that both queries are supposed to return the same records (or at least the second queries returns a subset of the records from the first query). That means the first query already contains all the information needed.</p>\n\n<p>So the reading of the records can be:</p>\n\n<pre><code>// Map no longer needed. Store the data in a list instead.\nList<Params> gridData = new ArrayList<>();\n\n// Get results here\n\nwhile (resultSet.next()) {\n int paramId = resultSet.getInt(\"PARAM_ID\"));\n String param1 = resultSet.getString(\"PARAM_1\");\n // Further params omitted\n\n int currSetting = resultSet.getInt(\"curr_setting\");\n String param8 = currSetting == 1 ? resultSet.getString(\"PARAM_8\") : null;\n\n // Declare the paramsDO variable here, and not outsided the loop, \n // because its the smallest needed scope.\n // Also you have the constructor so use it.\n Params paramsDO = new Params(paramId, param1, /* ..., */ param8);\n\n gridData.add(paramsDO);\n}\n\n// Actually do somethign with the data\nreturn gridData;\n</code></pre>\n\n<hr>\n\n<p>Finally especially in data classes such as <code>Params</code> make sure you actually need setters. Even if you keep the two queries you only need <code>setParam8</code> and not the others. In my example you don't need any setters at all. Immutable data objects have many advantages over mutable ones.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-05T16:53:46.703",
"Id": "460007",
"Score": "0",
"body": "This is, unfortunately, production code. I do not have any authority of choosing the version. I have edited the method for code review. Yes, there is a connection available from a utility class; I would be using that. Also, this DO object would be displayed on the UI. The method would return the map that is used in my original code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-05T16:58:58.617",
"Id": "460009",
"Score": "0",
"body": "Both the queries return different set of records. The conditions orig_setting=1 and curr_setting=1 are mutually exclusive."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-05T17:02:57.690",
"Id": "460010",
"Score": "0",
"body": "Setter for only param8 seems sensible. Will incorporate that change."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-05T17:28:25.600",
"Id": "460016",
"Score": "0",
"body": "How are the result sets mutually exclusive? They query the same table, and any records that second query returns, that haven't been returned by the first query are ignored by your code. Can you post example content of the table with expected query results and expected result of your code?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-08T01:28:58.097",
"Id": "460342",
"Score": "0",
"body": "I have edit the OP to include a sample database table."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-08T07:55:27.643",
"Id": "460369",
"Score": "0",
"body": "The problem with this code is that you don't distinguish between the primary key and the separate field \"key\", but this has been solved in your other question."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-05T16:49:26.247",
"Id": "235118",
"ParentId": "235070",
"Score": "1"
}
},
{
"body": "<p>It is possible to join the queries into one query by having two separate queries on <code>table1</code> that join on the primary key:</p>\n\n<pre><code>SELECT orig_setting_tbl.PARAM_ID, PARAM_1, PARAM_2, PARAM_3, PARAM_4, PARAM_5, PARAM_6, PARAM_7, PARAM_8\nFROM\n(SELECT PARAM_ID, PARAM_1, PARAM_2, PARAM_3, PARAM_4, PARAM_5, PARAM_6, PARAM_7\nFROM table1 WHERE orig_setting = 1) AS orig_setting_tbl\nLEFT OUTER JOIN\n(SELECT PARAM_ID, PARAM_8\nFROM table1 WHERE curr_setting = 1) AS curr_setting_tbl\nON orig_setting_tbl.PARAM_ID = curr_setting_tbl.PARAM_ID \n</code></pre>\n\n<p>this gives you the correct complete set of params for the same PARAM_ID. all rows where orig_setting = 1 are fetched. rows that do not have matching curr_setting = 1, will have null value in PARAM_8.<br>\nI believe this will perform better than iterating over two queries.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-07T08:04:43.973",
"Id": "235207",
"ParentId": "235070",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-04T14:24:38.240",
"Id": "235070",
"Score": "4",
"Tags": [
"java",
"performance",
"hash-map",
"jdbc",
"oracle"
],
"Title": "Updating a huge hashmap from a resultset"
}
|
235070
|
<p><strong>Background</strong></p>
<p>I'm trying to check equality between cells in an irregular, non-continuous range of cells. For this purpose I would like to know if all cells are equal to the first <code>Cell</code> in the <code>Range</code>. The <code>Range</code> can be anything, but let's say it could be the following (don't mind the implicit reference for now):</p>
<pre><code>Range("A1:C1,F1,K1,X1,AA1")
</code></pre>
<hr>
<p><strong>Sample Code:</strong></p>
<p>Because the <code>Range</code> is non-continuous, there is no way to use the <code>COUNTIF</code> as a <code>WorksheetFunction</code>, nor can I implement some sort of <code>INDIRECT</code> within <code>Evaluate</code>. So I was looking for the easiest way to do this. I came up with the following:</p>
<pre><code>'Get a 1D-array from columns of interest
Dim arr As Variant: arr = Application.Index(Range("A1:AA1").Value, 1, Array(1, 2, 3, 6, 11, 24, 27))
'Join the 1D-array and check against 7* the value of A1
If Join(arr, "") = Replace("???????", "?", Range("A1").Value) Then
Debug.Print "All equal to first cell"
Else
Debug.Print "Not all equal to first cell"
End If
</code></pre>
<hr>
<p><strong>Question:</strong></p>
<p>I've spent quite some time trying to come up with some code that would avoid iteration over the <code>Range</code> object's <code>Cells</code> (or iteration of any type), for example like below:</p>
<pre><code>'Get dictionary ready
Dim dict As Object: Set dict = CreateObject("Scripting.Dictionary")
'Get range of cells
Dim rng As Range: Set rng = Range("A1:C1,F1,K1,X1,AA1")
'Iterate over cells
For Each cl In rng
dict(cl.Value) = 1
Next cl
'Test for same values
If dict.Count = 1 Then
Debug.Print "All equal to first cell"
Else
Debug.Print "Not all equal to first cell"
End If
</code></pre>
<p>It has also become clear to me that there is no simple <code>COUNTIF</code> of an <code>Array</code>. And also something like <code>Filter</code> has proven to not be "error" proof.</p>
<p>While this is working code, I was hoping to find out the <strong>best</strong> way to know if all values in an irregular, non-continuous range of cells are the same. And therefor hope CR is the right place to ask.</p>
|
[] |
[
{
"body": "<p>It is possible to combine Application.Find with Application.Sum (arr2 in the code below) on the extracted array (arr in the code) to get the same result as Countif. The reason is that Application.Find returns an array filled with 1 if the value is found in the corresponding element (See picture below.)</p>\n\n<p><a href=\"https://i.stack.imgur.com/hIiZz.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/hIiZz.png\" alt=\"enter image description here\"></a></p>\n\n<p>But Application.Find will return false positives if the first cell is empty (Vide here.)\n<a href=\"https://i.stack.imgur.com/MK9r7.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/MK9r7.png\" alt=\"enter image description here\"></a></p>\n\n<p>And Application.Sum will return an error if one of the elements is different from the first one.\n<a href=\"https://i.stack.imgur.com/iqGg6.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/iqGg6.png\" alt=\"enter image description here\"></a></p>\n\n<p>Beside that, the number of times the value of the first cell is found should match the number of elements of the array (7 in this case.)</p>\n\n<p>Here is the code:</p>\n\n<pre><code>Option Explicit\n\nSub CountIfCodeReview235075()\n\n Dim arr As Variant, arr2 As Variant\n\n With ActiveSheet.Range(\"A1:AA1\")\n 'Get a 1D-array from columns of interest\n arr = Application.Index(.Value2, 1, Array(1, 2, 3, 6, 11, 24, 27))\n End With\n\n If Not IsEmpty(arr(1)) Then\n With Application\n arr2 = .Find(arr(1), arr)\n\n Select Case True\n Case IsError(.Sum(arr2))\n Debug.Print \"Not all equal to first cell\"\n Case .Sum(arr2) <> UBound(arr)\n Debug.Print \"Not all equal to first cell\"\n Case Else\n Debug.Print \"All equal to first cell\"\n End Select\n End With\n End If\nEnd Sub\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-06T08:55:18.823",
"Id": "460085",
"Score": "0",
"body": "Thanks for that valuable insight. In terms of which is the \"better\" method it's hard to tell. Maybe a matter of personal preference? Either way, upvoted for the technique used as this comes close to the `COUNTIF` approach that would avoid iteration in a continuous range. =)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-06T14:46:30.060",
"Id": "460131",
"Score": "0",
"body": "Found a way to utilize `Application.Match` with `Application.Count` to not have to deal with false positives or `IsError`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-06T17:23:14.413",
"Id": "460158",
"Score": "0",
"body": "@JvdV That's nice!"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-04T23:18:20.867",
"Id": "235094",
"ParentId": "235075",
"Score": "2"
}
},
{
"body": "<p>Using a Dictionary to count the occurences of a single value is overkill. If the question was count the number of values that match the first then <code>If FirstValue = cl.Value Then Count = Count + 1</code> would be far more efficient than using a Dictionary.</p>\n\n<blockquote>\n <p>I would like to know if all cells are equal to the first Cell in the Range</p>\n</blockquote>\n\n<p>It seems to me that you are over complicating things. Based on the objective above we are looking for a simple True or False answer. Currently, you have to iterate over all the cells before you can determine whether all the cell value match. So it takes the same amount of time whether all cells match or not. It would be far better to set a flag and exit the loop when a unmatched value is found.</p>\n\n<pre><code>'Get range of cells\nDim rng As Range\nSet rng = Range(\"A1:C1,F1,K1,X1,AA1\")\n\nDim Value As Variant\nValue = rng.Cells(1, 1).Value\nDim flag As Boolean\n\nFor Each cl In rng\n If cl.Value <> Value Then\n flag = True\n Exit For\n End If\nNext cl\n\n'Test for same values\nIf Not flag Then\n Debug.Print \"All equal to first cell\"\nElse\n Debug.Print \"Not all equal to first cell\"\nEnd If\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-05T15:01:28.147",
"Id": "459983",
"Score": "0",
"body": "That would indeed be overkill, good call. I added the example because I would like to avoid such iteration over the Range completely. Dictionary is used because in the back of my head I was probably thinking about how to count unique values in an irregular non-continuous range. For this purpose your solution would definitely be the better oner one. Thank you for your answer."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-05T14:22:53.180",
"Id": "235114",
"ParentId": "235075",
"Score": "3"
}
},
{
"body": "<p>Since, there is an array of values, no need to iterate in the range, I think. Why not iterating between the array elements?</p>\n\n<pre><code>Dim arr As Variant, sh As Worksheet, El As Variant\nDim refVal As Variant, boolWrong As Boolean, strDif As String\n Set sh = ActiveSheet\n arr = Application.Index(sh.Range(\"A1:AA1\").Value, 1, Array(1, 2, 3, 6, 11, 24, 27))\n refVal = arr(1)\n For Each El In arr\n If El <> refVal Then\n boolWrong = True\n strDif = El\n Exit For\n End If\n Next\nIf boolWrong Then\n Debug.Print \"Not all equal to first cell\" & vbCrLf & _\n strDif & \" instead of \" & refVal\nElse\n Debug.Print \"All equal to first cell\"\nEnd If\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-06T08:56:20.900",
"Id": "460086",
"Score": "0",
"body": "Thanks for your contribution @FaneDuru. Indeed, iteration through memory is faster in general. So this would avoid the `Range` object. It's good practice."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-06T08:43:13.017",
"Id": "235152",
"ParentId": "235075",
"Score": "3"
}
},
{
"body": "<p>I think I found a solution that seemed the most elegant:</p>\n\n<pre><code>Sub Test()\n\n'Get a 1D-array from columns of interest\nDim arr As Variant: arr = Application.Index(Range(\"A1:AA1\").Value, 1, Array(1, 2, 3, 6, 11, 24, 27))\n\n'Check if all elements in array match the first element\nWith Application\n If .Count(.Match(arr, Array(arr(1)), 0)) = 7 Then\n Debug.Print \"All equal to first cell\"\n Else\n Debug.Print \"Not all equal to first cell\"\n End If\nEnd With\n\nEnd Sub\n</code></pre>\n\n<p>So effectively; <code>Application.Count</code> and <code>Application.Match</code> work together to replace the <code>WorksheetFunction.CountIf</code> quite seamlessly on any irregular non-continuous range. And therefor we prevent any iteration.</p>\n\n<p>This would however not take into consideration exact matches (not case-sensitive). For that I would revert back to my initial attempt.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-06T14:40:47.907",
"Id": "235170",
"ParentId": "235075",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "235170",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-04T15:47:27.753",
"Id": "235075",
"Score": "4",
"Tags": [
"array",
"vba",
"excel"
],
"Title": "Check non-continuous range for equal values"
}
|
235075
|
<p>I wrote a program that is supposed to be a breadth-first search algorithm, but I'm very new to search algorithm so I don't know if my method is very effective or if there is a simpler way to do this. So I'm asking if there is a way to improve my code.</p>
<p>In this case, I have made the program search for the closest <code>1</code> in a 2d list where you can enter the start position and it will then find the shortest path between the start position and the <code>1</code>. Of course, this can be changed in a variety of ways.</p>
<p>I tried to make the variables and function names as clear as possible, so I don't think I need to explain everything about my code, but that's easy for me to say so please comment if you need clarification.</p>
<pre><code>m = [[1, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 1, 0],
[0, 0, 1, 0, 0, 0],
[0, 0, 0, 0, 0, 1],
[0, 0, 0, 0, 1, 0],
[1, 0, 1, 0, 0, 0],
[1, 0, 0, 0, 0, 1],
[0, 0, 0, 0, 1, 0],
[1, 0, 1, 0, 0, 0]]
visited = []
queue = []
parent = {}
num = 0
def breadth_first(maze, x, y):
queue.append((x, y))
visited.append((x, y))
while queue:
pos = queue[0]
x = pos[0]
y = pos[1]
# remove from queue
queue.remove(pos)
# find neighbor
for dir_x, dir_y in ((-1, 0), (1, 0), (0, -1), (0, 1)):
newx = x + dir_x
newy = y + dir_y
neighbor = (newx, newy)
# add to queue
if len(maze[0]) > newx >= 0 and len(maze) > newy >= 0 and neighbor not in visited and neighbor not in queue:
if m[newy][newx] == 1:
parent[neighbor] = pos
return neighbor
queue.append(neighbor)
visited.append(neighbor)
parent[neighbor] = pos
closest = breadth_first(m, 0, 0)
path = [closest]
def search(traceback):
while traceback != (0, 0):
for key, value in parent.items():
if traceback == key:
path.append(value)
traceback = value
return path
def solved(maze, input_path):
for pos in input_path[1:-1]:
maze[pos[1]][pos[0]] = '+'
return maze
print(solved(m, search(closest)))
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-04T17:02:31.903",
"Id": "459898",
"Score": "2",
"body": "Welcome to cod review where we review working code and provide suggestions on how the code can be improved. The title may indicate that you don't know if the code is working or not. Does the code do what it is supposed to do? Can you clarify the question a little bit more."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-04T19:25:33.347",
"Id": "459923",
"Score": "0",
"body": "@pacmaninbw It does what it is supposed to do, but I would like suggestions on improvements"
}
] |
[
{
"body": "<ul>\n<li><p>The code uses <code>pos=queue[0]</code> and <code>queue.remove(pos)</code>. Instead, you could use <code>pos=queue.pop(0)</code>. Be aware that popping from the front isn't really efficient, it's O(n), which is bad for big lists.</p></li>\n<li><p>You could use the fact that you can assign to two variables at once: <code>x, y = queue.pop(0)</code>. This removes <code>pos</code> completely, fewer variables are easier to understand.</p></li>\n<li><p>You pass a maze and the start position to the BFS. However, the queue and others are global. That's very bad design. Keep things in as small a scope as possible. You can always return a tuple from a function if a single value is not sufficient, if that was the reason.</p></li>\n<li><p>What are <code>len(maze[0])</code> and <code>len(maze)</code>? Call those width and height and compute them at the start of the function to answer that question.</p></li>\n<li><p>The if-clause in the loop has too many conditions at once, which is really hard to read. There's nothing wrong with a <code>continue</code> when the computed position was already visited, just to illustrate one check that could be extracted.</p></li>\n<li><p><code>parent[neighbor] = pos</code> is done at two places. Do that exactly once when you first visit a new place.</p></li>\n<li><p><code>visited</code> seems to be the list of places that were already visited. The type is a Python <code>list</code>, but a <code>set</code> would be a more suitable datatype for that, unless the order of the elements matters.</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-06T18:41:33.513",
"Id": "236802",
"ParentId": "235076",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-04T15:57:32.310",
"Id": "235076",
"Score": "2",
"Tags": [
"python",
"algorithm",
"queue",
"search",
"breadth-first-search"
],
"Title": "Is this breadth-first search correct?"
}
|
235076
|
<p>I wrote a Singleton template, with examples, google tests and README
<a href="https://github.com/erez-strauss/init_singleton/blob/master/singleton.h" rel="nofollow noreferrer">https://github.com/erez-strauss/init_singleton/blob/master/singleton.h</a></p>
<p>The usage can be as simple as:</p>
<pre><code>#include <singleton.h>
int main()
{
es::init::singleton<int>::instance() =
4; // a singleton of a type int, initialized before main() starts, destroyed after main() exits.
return 0;
}
</code></pre>
<p>That is a singleton of a type int, it is being created before the main() starts, and destroyed after main() exists.</p>
<p>A bit more useful example would be:</p>
<pre><code>#include <app_singletons.h>
class DataA { public: DataA(){std::cout << "DataA()\n";
es::init::args.for_each(
[](int index, auto& arg) { std::cout << "DataA: arg[" << index << "]: '" << arg << "'" << std::endl; });
es::init::env.for_each(
[](int index, auto& earg) { std::cout << "DataA: env[" << index << "]: '" << earg << "'" << std::endl; });
} ~DataA() {std::cout << "~DataA()\n";}};
int main()
{
std::cout << "main() start\n";
es::init::singleton<DataA>::instance(); // a singleton of a type DataA, initialized before main() starts, destroyed after main() exits.
std::cout << "main() end\n";
return 0;
}
$ ./singleton8 a b c
DataA()
DataA: arg[0]: './singleton8'
DataA: arg[1]: 'a'
DataA: arg[2]: 'b'
DataA: arg[3]: 'c'
DataA: env[0]: 'SHELL=/bin/bash'
.....
DataA: env[63]: '_=./singleton8'
main() start
main() end
~DataA()
</code></pre>
<p>The singleton template is using an atomic<> pointer to a function, which returns the address of the singleton object.
This atomic pointer first points to an initialization function, which creates the singleton and changes the pointer to point to another function which just return the reference to the singleton with no condition.</p>
<p>The above example shows two features of the singleton early_initializer</p>
<ol>
<li><p>access to std::cout/std::cerr is available from the early initialized constructors - for this the init function need to create instance of the std::ios_base::Init object, which initializes them, on first such object creation.</p></li>
<li><p>the access to command line arguments and environment from early initialized constructors, by two singletons that are defined in app_singleton.h, the args singleton init function is a constructor function that expects the argc, argv parameters.</p></li>
</ol>
<p>Singleton objects can be of any type, and if you choose a class that depends on other singletons, that is fully supported, so they will be crated as needed, there are examples in github that show it.</p>
<p>If there is a circular dependency of the singletons, the singleton template will detect it at initialization time and will throw an exception.</p>
<p>This singleton implementation also solves the multiple compile units / object files initialization order, as the required order is specified, by accessing the other singletons <em>es::init::singleton<>::instance()</em>.
The full header file also takes care of the destruction of the singleton objects.</p>
<pre class="lang-cpp prettyprint-override"><code>//
// The efficient Singleton with proper initialization and destruction order
//
// 1. Efficient, with no condition on every access
// 2. Multi dependency on other Singleton(s)
// 3. Multi thread safe
// 4. Proper initialization order with multiple compile units
// 5. Early initialization, lazy initialization
// 6. Detects circular dependency - generates exception
// 7. Proper destruction order
// 8. None intrusive, requires only default constructor, supports native types.
//
// See README.md for details.
// Discussion Proper Initialization / Destruction order:
// Simple Singleton can initialize properly when accessing one by one the singletons that require / depend on others.
// As each one of them is being initialized on the first instance() call.
// In order to solve their destructors order, their respective destructors need to be pushed into an atomic stack, and
// counter of active singletons should be increased. The SpecialDeleter of each one of the uniq_ptr<> of them,
// just reduces the counter of live singletons, and calls the deleter in the stack when the counter gets to Zero.
//
// reference to a singleton will be valid in the block scope.
// *** handle multiple calls to firstTimeGetInstance():
// -- one after the other() , as the unique pointer objects are "reinitialized" by the compiler.
// --> should return pointer to the same object.
// -- one call during the firstTimeActive() - if same-thread - circular dependency
//
// MIT License
//
// Copyright (c) 2019,2020 Erez Strauss, erez@erezstrauss.com
// http://github.com/erez-strauss/init_singleton/
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
#pragma once
#include <atomic>
#include <exception>
#include <iostream>
#include <mutex>
#include <string_view>
#include <thread>
#include <type_traits>
namespace es::init {
__extension__ using uint128_t = unsigned __int128;
constexpr const bool verbose_singletons{false};
static constexpr bool USE_BUILTIN_16B
{
#if defined(__GNUC__) && defined(__clang__)
false // clang++ uses builtin for std::atomic<__int128>
#elif defined(__GNUC__)
true // enable the __sync... builtin functions instead of std::atomic<> that call atomic library.
#else
false // other compilers
#endif
};
template<typename T>
struct sequenced_ptr
{
union
{
uint128_t _unit;
struct
{
T* _p;
uint64_t _seq;
} _s;
} _u;
sequenced_ptr load() noexcept
{
if constexpr (USE_BUILTIN_16B)
return sequenced_ptr{__sync_val_compare_and_swap(&this->_u._unit, 0, 0)};
else
return sequenced_ptr{reinterpret_cast<std::atomic<uint128_t>*>(this)->load()};
}
bool cas(sequenced_ptr expected_value, const sequenced_ptr new_value)
{
if constexpr (USE_BUILTIN_16B)
return __sync_bool_compare_and_swap(&this->_u._unit, expected_value._u._unit, new_value._u._unit);
else
return reinterpret_cast<std::atomic<uint128_t>*>(this)->compare_exchange_strong(expected_value._u._unit,
new_value._u._unit);
}
};
static_assert(sizeof(sequenced_ptr<int>) == 16, "Wrong size for sequenced_ptr");
struct singleton_base
{
};
struct singletons_meta_data
{
singletons_meta_data* _next{nullptr};
void (*_func)(singletons_meta_data*){nullptr};
void* _p{nullptr};
const char* _func_name{nullptr};
uint32_t _useCount{0};
uint32_t _flags{0};
};
class singletons_counter
{
inline static std::atomic<int64_t> global_counter{0};
public:
static auto get() { return global_counter.load(); };
template<typename T, template<typename TT> class EI, typename M, typename InitT>
friend class singleton;
};
template<typename T>
struct static_obj_stack
{
inline static sequenced_ptr<T> top{0UL};
inline static std::mutex stack_mutex{};
static void push(T* p)
{
sequenced_ptr<T> stack_top;
sequenced_ptr<T> new_top;
do
{
stack_top = top.load();
new_top = stack_top;
p->_next = stack_top._u._s._p;
new_top._u._s._p = p;
++new_top._u._s._seq;
} while (!top.cas(stack_top, new_top));
}
static T* pop()
{
sequenced_ptr<T> stack_top;
sequenced_ptr<T> new_top;
do
{
stack_top = top.load();
if (!stack_top._u._s._p) return nullptr;
new_top = stack_top;
new_top._u._s._p = stack_top._u._s._p->_next;
++new_top._u._s._seq;
} while (!top.cas(stack_top, new_top));
return stack_top._u._s._p;
}
static uint64_t size()
{
std::lock_guard<std::mutex> guard(stack_mutex);
uint64_t n{0};
for (T* p = top._u._s._p; p != nullptr; p = p->_next) ++n;
return n;
}
};
using stack = static_obj_stack<singletons_meta_data>;
static inline std::atomic<bool> clean_up_phase{false};
static inline int app_argc{0};
static inline char** app_argv{nullptr};
inline void emptyStack()
{
std::lock_guard<std::mutex> guard(stack::stack_mutex);
clean_up_phase = true;
uint64_t n{0};
while (auto p = stack::pop())
{
if constexpr (es::init::verbose_singletons)
{
std::cout << "emptyStack[" << n++ << "]: node: " << (void*)p << " func_name: " << p->_func_name
<< std::endl;
}
if (auto f = p->_func)
{
p->_func = nullptr;
f(p);
}
}
}
inline void report_singletons_stack()
{
std::lock_guard<std::mutex> guard(stack::stack_mutex);
uint64_t n{0};
for (singletons_meta_data* p = stack::top._u._s._p; p != nullptr; p = p->_next)
{
std::cout << "singletons_stack_meta_data_node[" << ++n << "]: " << (void*)p << " func_name: " << p->_func_name
<< std::endl;
}
}
template<typename T>
struct early_initializer_no_args
{
[[using gnu: used, constructor]] static void early_init()
{
std::ios_base::Init z;
T::instance();
}
};
template<typename T>
struct early_initializer
{
[[using gnu: used, constructor]] static void early_init(int argc, char** argv)
{
std::ios_base::Init z;
if (es::init::app_argc != argc) es::init::app_argc = argc;
if (es::init::app_argv != argv) es::init::app_argv = argv;
T::instance();
}
};
template<typename T>
struct lazy_initializer
{ // empty - do nothing.
};
template<typename T, template<typename TT> class EI = early_initializer, typename M = void,
typename InitT = ::std::ios_base::Init>
class singleton : public singleton_base, EI<singleton<T, EI, M, InitT>>
{
struct SpecialDeleter
{
void operator()(T* p) const
{
static bool activated{false};
if constexpr (verbose_singletons)
{
std::cout << "SpecialDeleter start " << singletons_counter::global_counter.load() << " "
<< __PRETTY_FUNCTION__ << " " << (void*)p << " " << (activated ? 'T' : 'F') << std::endl;
}
activated = true;
if (p)
{
std::lock_guard<std::mutex> guard(_mutex);
if (_getInstance == optGetInstance) _getInstance = firstTimeGetInstance;
singleton_meta_data_node._p = (void*)p;
--singletons_counter::global_counter;
if constexpr (es::init::verbose_singletons)
{
std::cout << "SpecialDeleter - done " << singletons_counter::global_counter.load() << " "
<< __PRETTY_FUNCTION__ << std::endl;
}
if (!singletons_counter::global_counter) emptyStack();
}
}
};
static void activeDelete(singletons_meta_data* np)
{
static uint64_t active_delete_count{0};
++active_delete_count;
if constexpr (es::init::verbose_singletons)
{
std::cerr << "activeDelete - " << __PRETTY_FUNCTION__ << " " << (void*)np->_p << " " << active_delete_count
<< std::endl;
}
delete static_cast<T*>(np->_p);
np->_p = nullptr;
}
static T& firstTimeGetInstance()
{
volatile InitT init_object{}; // make sure, one can use the std::cout std::cerr streams from Singletons code
if (clean_up_phase)
std::cerr << "Warning: initializing at clean up phase - " << __PRETTY_FUNCTION__ << std::endl;
if (!_instance)
{
if (singleton_meta_data_node._flags & 0x1)
{
throw std::logic_error(std::string{"Error: circular dependency "} + __PRETTY_FUNCTION__);
}
std::lock_guard<std::mutex> guard(_mutex);
if (!_instance)
{
singleton_meta_data_node._flags = 0x1;
_instance = std::unique_ptr<T, SpecialDeleter>{new T{}, SpecialDeleter{}};
++singletons_counter::global_counter;
if (!singleton_meta_data_node._p)
{
singleton_meta_data_node._func = activeDelete;
singleton_meta_data_node._p = (void*)&*_instance;
singleton_meta_data_node._func_name = __PRETTY_FUNCTION__;
stack::push(&singleton_meta_data_node);
}
}
}
_getInstance = optGetInstance;
singleton_meta_data_node._flags &= ~0x1U;
return *_instance;
}
static T& optGetInstance() { return *_instance; }
inline static std::atomic<T& (*)()> _getInstance{firstTimeGetInstance};
inline static std::unique_ptr<T, SpecialDeleter> _instance{nullptr};
inline static std::mutex _mutex{};
inline static singletons_meta_data singleton_meta_data_node{nullptr, nullptr, nullptr, nullptr, 0, 0};
static_assert(sizeof(_instance) == 8, "instace size should be 8 bytes");
public:
[[using gnu: hot]] static T& instance()
{
auto f = _getInstance.load();
return f();
}
};
} // namespace es::init
</code></pre>
<p>Here are two use cases, more examples are available on the github repo:</p>
<ul>
<li><p>Initialization order of application components holding references or using other components at init time, using singlton<> of different types.
The following example (examples/singleton10.cpp) shows few classes (I use struct to simpify the example text)</p>
<ul>
<li>ComponentE - has no dependencies - used as singleton inside ComponentC constructor</li>
<li>ComponentD - has no dependencies - used as singleton as initialization value to ComponenD reference in componentC</li>
<li>ComponentC - depends on D and E</li>
<li>ComponentB - depend on C, as it access the C singleton</li>
<li>ComponentA - depends on B, and indirectly on all the others</li>
<li>Engine - depends on ComponentA</li>
</ul>
<p>All the above component can be in a single cpp file or each in its own cpp files, and their initialization order
is well defined, and does not depent on linkage order.</p></li>
</ul>
<pre><code>#include <app_singletons.h>
#include <iostream>
template<typename T>
struct CDReporter
{
CDReporter() { std::cout << "inside: " << __PRETTY_FUNCTION__ << " this: " << (void*)this << std::endl; }
~CDReporter() { std::cout << "inside: " << __PRETTY_FUNCTION__ << " this: " << (void*)this << std::endl; }
};
struct ComponentE : public CDReporter<ComponentE> { ComponentE() { } };
struct ComponentD : public CDReporter<ComponentD> { ComponentD() { } };
struct ComponentC : public CDReporter<ComponentC> { ComponentC() : _d(es::init::singleton<ComponentD>::instance()) { es::init::singleton<ComponentE>::instance(); } ComponentD& _d; };
struct ComponentB : public CDReporter<ComponentB> { ComponentB() { es::init::singleton<ComponentC>::instance(); } };
struct ComponentA : public CDReporter<ComponentA> { ComponentA() { es::init::singleton<ComponentB>::instance(); } };
class Engine { public: Engine() : _a(es::init::singleton<ComponentA>::instance()) {} ComponentA& _a; };
int main() { Engine e{}; return 0; }
</code></pre>
<ul>
<li><p>Deep nested function that internally needs access to a singleton information for decision</p>
<p>This example9.cpp shows access to command-line arguments from the SetupInfo object.
It eliminate the need to pass references to singleton<> objects from containing Objects down to their internal objects (ProcessorA - internal to B, while B internal to C)
As this implementation is faster than others it reduces the overhead of accessing singletons objects.</p></li>
</ul>
<pre><code>#include <app_singletons.h>
#include <iostream>
class SetupInfo {
bool _verbose{false};
public:
SetupInfo() {
es::init::args.for_each([&](auto, auto opt) {
if (opt && opt[0] == '-' && opt[1] == 'v' && !opt[2]) _verbose = true; });
}
bool verbose() { return _verbose; }
};
class ProcessorA {
public:
int action() {
if (es::init::singleton<SetupInfo>::instance().verbose()) {
// real action.
std::cout << "verbose\n";
return 1;
}
return 0;
}
};
class ProcessorB {
public:
ProcessorB(ProcessorA& pa) : _processorA(pa) {}
int action() { return _processorA.action(); }
ProcessorA& _processorA;
};
class ProcessorC {
public:
ProcessorC(ProcessorB& pb) : _processorB(pb) {}
int action() { return _processorB.action(); }
ProcessorB& _processorB;
};
int main()
{
ProcessorA a;
ProcessorB b{a};
ProcessorC c{b};
c.action();
}
</code></pre>
<p>My questions:</p>
<ol>
<li>Please review the above code and suggest improvements and changes.</li>
<li>Does the above singleton pattern implementation follows the current C++17/C++2a best practice.</li>
<li>How to improve it, and make it more useful?</li>
<li>How to make it portable, Windows environment and intel compiler?</li>
</ol>
<p>Thanks, Erez</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-04T17:22:51.750",
"Id": "459900",
"Score": "2",
"body": "Can you also specify some concrete use cases, where using that code should be used in production please?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-05T21:24:37.223",
"Id": "460033",
"Score": "0",
"body": "I added the use cases to the question text above, thank you."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-05T21:31:34.917",
"Id": "460034",
"Score": "0",
"body": "The atomic pointer doesn't do much. Simply follow Scott Meyer's singleton, approach to achieve thread safety of creation of the instance."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-06T02:17:54.447",
"Id": "460054",
"Score": "0",
"body": "πάντα ῥεῖ - using atomic<> is not intended to provide locking, the creation of the specific object is done under proper mutex lock, only once per Singleton at init time. The atomic<> usage prevents the compiler from over optimization, and in case of lazy_initializer, one thread will to the firstTimeGetInstance() and the other threads will do the optimized version."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-06T17:50:11.763",
"Id": "460161",
"Score": "0",
"body": "\"That is a singleton of a type int, it is being created **before the main() starts**, and destroyed after main() exists.\" Before main starts? How are the other examples processing command line arguments if they don't get them from `main`? `early_init` never seems to be called either? What compiler / platform does this compile on?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-07T02:29:50.733",
"Id": "460215",
"Score": "0",
"body": "in order to call a static function at program initialization, one can use the attribute: [[ using gnu : constructor, used ]] the constructor tell the loading library to call the function at startup before main, the used attribute tells the compiler not to optimize out the function. - see template early_initializer , using CRTP to call the specialized instance(), which will call the firstTimeGetInstance."
}
] |
[
{
"body": "<p>style nit: </p>\n\n<pre><code>inline static singletons_meta_data singleton_meta_data_node{nullptr, nullptr, nullptr, nullptr, 0, 0};\n</code></pre>\n\n<p>Specifying all the member values like this decreases readability. Setting everything to nullptrs doesn't tell the reader anything useful. Either explicitly set the members like <code>._next = nullptr</code>, or better, just let it default construct.</p>\n\n<p>Also, does <code>inline</code> do anything here?</p>\n\n<hr>\n\n<p>Isn't it a problem when static_obj_stack is destroyed? The mutex destructor would be called and nothing else would be able to be use it anymore. <code>_instance</code>s would call emptyStack which uses <code>static_obj_stack</code>. AFAIK, static destruction order is not guaranteed.</p>\n\n<hr>\n\n<pre class=\"lang-html prettyprint-override\"><code> [[using gnu: hot]] static T& instance()\n {\n auto f = _getInstance.load();\n return f();\n }\n</code></pre>\n\n\n\n<p>Can you explain how this works? If two threads enter here, they could both load <code>firstTimeGetInstance</code>. </p>\n\n<p>Then inside that method it looks like it will erroneously throw a circular dependency error, because one thread might set the flag to 1 and the other might test it:</p>\n\n<pre class=\"lang-html prettyprint-override\"><code> if (!_instance)\n {\n if (singleton_meta_data_node._flags & 0x1)\n {\n throw std::logic_error(std::string{\"Error: circular dependency \"} + __PRETTY_FUNCTION__);\n }\n std::lock_guard<std::mutex> guard(_mutex);\n if (!_instance)\n {\n singleton_meta_data_node._flags = 0x1;\n _instance = std::unique_ptr<T, SpecialDeleter>{new T{}, SpecialDeleter{}};\n ++singletons_counter::global_counter;\n\n if (!singleton_meta_data_node._p)\n {\n singleton_meta_data_node._func = activeDelete;\n singleton_meta_data_node._p = (void*)&*_instance;\n singleton_meta_data_node._func_name = __PRETTY_FUNCTION__;\n stack::push(&singleton_meta_data_node);\n }\n }\n }\n</code></pre>\n\n\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-07T03:20:05.570",
"Id": "460217",
"Score": "0",
"body": "the singleton_meta_data_node should be plain old data, with no function initializer, but simple data. the 'inline' enable multiple header file to user these class static variable with initialization value. regarding the _flags=01 - thanks, fixed it in github repo, unsetting the flag bit, inside the guard scope."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-07T22:17:58.353",
"Id": "460323",
"Score": "0",
"body": "singletons_meta_data_node still has a generated constructor that you can use, and you're even explicitly setting all the members to 0s. Both of these are unnecessary:\nhttps://en.cppreference.com/w/cpp/language/initialization\n`For all other non-local static and thread-local variables, Zero initialization takes place`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-14T03:13:05.217",
"Id": "461220",
"Score": "0",
"body": "I changed the mutex to a trivially constructed spin lock, so there is no generated function that is being called. Regarding the initialization to zero, thank you, I'm in this case prefer to state the obvious, and be explicit, to avoid later on someone \"fixing\" it with constructor values which will mess things. \nregarding two threads getting into the firstTimeGetInstance() function, only one of them will get the lock (on the spin lock, see github code) and will create the object, the other will spin, waiting for the object to be created, then return the reference to it."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-06T22:48:58.567",
"Id": "235195",
"ParentId": "235082",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-04T17:14:55.373",
"Id": "235082",
"Score": "-1",
"Tags": [
"c++",
"design-patterns",
"c++17",
"singleton"
],
"Title": "Fast efficient C++ Singleton template with proper constructor and destruction order"
}
|
235082
|
<p>I have a customized function to accomplish the business requirement I mentioned, but this one takes a very long time to run. I was wondering if there was any way to shorten that time?</p>
<pre><code>import json
import numpy as np
import pandas as pd
import os
assert os.path.isfile("train-v1.1.json"),"Non-existent file"
from tensorflow.python.client import device_lib
import tensorflow.compat.v1 as tf
#import keras
from keras.preprocessing.text import Tokenizer
from keras.preprocessing.sequence import pad_sequences
import re
regex = re.compile(r'\W+')
#Reading the files.
def readFile(filename):
with open(filename) as file:
fields = []
JSON = json.loads(file.read())
articles = []
for article in JSON["data"]:
articleTitle = article["title"]
article_body = []
for paragraph in article["paragraphs"]:
paragraphContext = paragraph["context"]
article_body.append(paragraphContext)
for qas in paragraph["qas"]:
question = qas["question"]
answer = qas["answers"][0]
fields.append({"question":question,"answer_text":answer["text"],"answer_start":answer["answer_start"],"paragraph_context":paragraphContext,"article_title":articleTitle})
article_body = "\\n".join(article_body)
article = {"title":articleTitle,"body":article_body}
articles.append(article)
fields = pd.DataFrame(fields)
fields["question"] = fields["question"].str.replace(regex," ")
assert not (fields["question"].str.contains("catalanswhat").any())
fields["paragraph_context"] = fields["paragraph_context"].str.replace(regex," ")
fields["answer_text"] = fields["answer_text"].str.replace(regex," ")
assert not (fields["paragraph_context"].str.contains("catalanswhat").any())
fields["article_title"] = fields["article_title"].str.replace("_"," ")
assert not (fields["article_title"].str.contains("catalanswhat").any())
return fields,JSON["data"]
trainingData,training_JSON = readFile("train-v1.1.json")
print("JSON dataset read.")
#Text preprocessing
## Converting text to skipgrams
print("Tokenizing sentences.")
strings = trainingData.drop("answer_start",axis=1)
strings = strings.values.flatten()
textTokenizer = Tokenizer()
textTokenizer.fit_on_texts(strings)
questionsTokenized_train = pad_sequences(textTokenizer.texts_to_sequences(trainingData["question"]))
print(questionsTokenized_train.shape)
contextTokenized_train = pad_sequences(textTokenizer.texts_to_sequences(trainingData["paragraph_context"]))
print("Sentences tokenized.")
from tensorflow.keras.preprocessing.text import *
from tensorflow.keras.preprocessing.sequence import skipgrams,make_sampling_table
def skipgrams_labels(sequence,vocabulary_length,window_size=3):
try:
couples,labels = skipgrams(sequence,vocabulary_length,window_size=window_size)
assert len(couples) > 0
target_word,context = zip(*couples)
return np.array([target_word,context,labels]).T
except Exception as e:
raise ValueError("Exception in skipgrams_labels")
print("questionsTokenized shape" + str(questionsTokenized_train.shape))
# This is to train word2vec.
def word2vec_batch(sequences,vocabulary_length,batch_size=20):
batch_indices = np.random.choice(sequences.shape[0], batch_size, replace=False)
batch = sequences[batch_indices,:]
assert batch.ndim == 2
skipgrams_and_labels = [skipgrams_labels(sequence,vocabulary_length) for sequence in sequences]
print("Maximum question length" + str(max([len(question) for question in batch])))
shape_zero = len(skipgrams_and_labels)
shape_one = max([len(x) for x in skipgrams_and_labels])
shape_two = max([len(y) for x in skipgrams_and_labels for y in x])
b = np.zeros((shape_zero,
shape_one,
shape_two))
print(b.shape)
for i in range(len(skipgrams_and_labels)):
for j in range(len(skipgrams_and_labels[i])):
for k in range(len(skipgrams_and_labels[i][j])):
b[i][j][k] = skipgrams_and_labels[i][j][k]
skipgrams_and_labels = b
return skipgrams_and_labels
print("Test of skipgrams_labels")
questions_indices = np.random.randint(0,high=questionsTokenized_train.shape[0],size=1)
questions_sample = questionsTokenized_train[questions_indices,:]
vocabulary_length = len(textTokenizer.word_index) + 1
print("vocabulary length" + str(vocabulary_length))
i = skipgrams_labels(questions_sample[0],vocabulary_length)
print(i.shape)
print(i.dtype)
print("Test of word2vec_batch")
batch_tokens = word2vec_batch(questionsTokenized_train,vocabulary_length,batch_size=100)
print(batch_tokens.dtype)
for row in batch_tokens:
print(row.shape)
</code></pre>
<p>According to my profiling tests, skipgrams_and_labels appears to be where the function spends most of its time. How can I improve this part of my code?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-04T18:16:29.933",
"Id": "459909",
"Score": "0",
"body": "What exceptions are you trying to catch in `skipgrams_labels`? Is the `try... catch` necessary?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-04T19:41:32.210",
"Id": "459926",
"Score": "0",
"body": "@Zchpyvr The try-catch blocks are not strictly necessary."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-05T11:45:17.467",
"Id": "459973",
"Score": "2",
"body": "Can you add some description of your code in the question body. Change the title to represent your business requirement? \nInclude `How can I make x faster` in the question body and not the title."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-06T18:00:10.620",
"Id": "460162",
"Score": "0",
"body": "@bhathiya-perera: Change the title? Done."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-06T18:22:38.357",
"Id": "460165",
"Score": "0",
"body": "@MontanaBurr looks like you misunderstood what I meant by business requirement. Ex: \"Finding highest score\" is a business requirement, & \"How can I make my sorting and getting first element in an array faster\" only highlights implementation and not the actual requirement."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-06T18:48:35.227",
"Id": "460167",
"Score": "0",
"body": "@bhathiya-perera: Noted."
}
] |
[
{
"body": "<p>This is just some minor optimization, but it should already be faster.\nInstead of looping over the length of <code>skipgrams_and_labels</code> and then do a triple index lookup with <code>skipgrams_and_labels[i][j][k]</code>, we loop directly over the elements and use enumerate to still get the index for b.</p>\n\n<pre><code>def word2vec_batch(sequences, vocabulary_length, batch_size=20):\n batch_indices = np.random.choice(sequences.shape[0], batch_size, replace=False)\n batch = sequences[batch_indices, :]\n assert batch.ndim == 2\n skipgrams_and_labels = [skipgrams_labels(sequence, vocabulary_length) for sequence in sequences]\n print(f\"Maximum question length {max(len(question) for question in batch)}\")\n shape_zero = len(skipgrams_and_labels)\n shape_one = max(len(x) for x in skipgrams_and_labels)\n shape_two = max(len(y) for x in skipgrams_and_labels for y in x)\n b = np.zeros((shape_zero, shape_one, shape_two))\n print(b.shape)\n for i, a in enumerate(skipgrams_and_labels):\n for j, b in enumerate(a):\n for k, c in enumerate(b):\n b[i][j][k] = c\n return b\n</code></pre>\n\n<p>EDIT:\nThis should be even faster because it gets rid of the other triple index lookup <code>b[i][j][k]</code>:</p>\n\n<pre><code>def word2vec_batch(sequences, vocabulary_length, batch_size=20):\n batch_indices = np.random.choice(sequences.shape[0], batch_size, replace=False)\n batch = sequences[batch_indices, :]\n assert batch.ndim == 2\n skipgrams_and_labels = [skipgrams_labels(sequence, vocabulary_length) for sequence in sequences]\n print(f\"Maximum question length {max(len(question) for question in batch)}\")\n shape_zero = len(skipgrams_and_labels)\n shape_one = max(len(x) for x in skipgrams_and_labels)\n shape_two = max(len(y) for x in skipgrams_and_labels for y in x)\n b = [c for a in skipgrams_and_labels for c in b for b in a]\n return np.array(b).reshape(shape_zero,shape_one,shape_two)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-04T22:56:49.640",
"Id": "235093",
"ParentId": "235083",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "235093",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-04T18:14:07.853",
"Id": "235083",
"Score": "2",
"Tags": [
"python",
"numpy"
],
"Title": "I need to process a list of already-tokenized sentences into skipgram samples. How do I do this efficiently?"
}
|
235083
|
<p>This is a console version of the famous Rock Paper Scissors game part of <a href="https://theodinproject.com" rel="nofollow noreferrer">The Odin Project</a> curriculum. Please review this code and provide suggestions. Please comment whether the code is DRY and if it is simplified.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function computerPlay() {
let choices = ['rock', 'paper', 'scissors'];
return choices[Math.floor(Math.random() * choices.length)];
}
function playRound(playerSelection, computerSelection) {
const capitalize = word => { return word.charAt(0).toUpperCase() + word.slice(1); }
const winStatement = (winner, loser) => { return `You Win! ${capitalize(winner)} beats ${capitalize(loser)}`; }
const loseStatement = (winner, loser) => { return `You Lose! ${capitalize(winner)} beats ${capitalize(loser)}`; }
const winningChoice = {'rock': 'paper', 'paper': 'scissors', 'scissors': 'rock'};
playerSelection = playerSelection.toLowerCase();
if(playerSelection === computerSelection) return "Oh! It's a tie";
else if(playerSelection === winningChoice[computerSelection]) return winStatement(playerSelection, computerSelection);
else return loseStatement(computerSelection, playerSelection);
}
const playerSelection = 'rock';
const computerSelection = computerPlay();
console.log(playRound(playerSelection, computerSelection));</code></pre>
</div>
</div>
</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-04T19:03:42.370",
"Id": "459918",
"Score": "0",
"body": "Welcome to CodeReview@SE. Can you tell a) why you coded this b) what concerns about it make you ask for suggestions?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-04T19:03:48.227",
"Id": "459919",
"Score": "0",
"body": "(This is the third *Rock, Paper, Scissors* implementation I notice here in a week.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-04T19:33:27.763",
"Id": "459925",
"Score": "0",
"body": "@greybeard This is part of [The Odin Project](https://theodinproject.com) curriculum. I would like to know if there's a more simplified code for the question."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-04T21:35:43.573",
"Id": "459929",
"Score": "3",
"body": "Inspecting a solution for possible simplifications: look for things that occur more than once: literally, structurally, temporally. Check whether what you read is what you want have said. When asked something in comments, consider enhancing your post first. When you find your post to be clear and complete enough, comment on comments - but, fundamentally, this is not chat."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-05T07:04:22.913",
"Id": "459957",
"Score": "0",
"body": "Noted @greybeard."
}
] |
[
{
"body": "<p>All in all, a basic review of your question shows that you are creating objects numerous times, when they do not need to be. Other things are pointed out in comments.</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>const choices = ['rock', 'paper', 'scissors'],\n capitalize = word => word.charAt(0).toUpperCase() + word.slice(1),\n // Should these be made into 1 function, that takes another argument, 'condition', which is 'Win' or 'Lose'?\n winStatement = (winner, loser) => `You Win! ${capitalize(winner)} beats ${capitalize(loser)}`,\n loseStatement = (winner, loser) => `You Lose! ${capitalize(winner)} beats ${capitalize(loser)},\n winningChoice = {'rock': 'paper', 'paper': 'scissors', 'scissors': 'rock'};\n\nfunction computerPlay() {\n return choices[Math.floor(Math.random() * choices.length)];\n}\n\nfunction playRound(playerSelection, computerSelection) {\n playerSelection = playerSelection.toLowerCase();\n\n // Also, Consecutive if statements that all return need not be else-if.\n if(playerSelection === computerSelection) {\n return \"Oh! It's a tie\";\n }\n if(playerSelection === winningChoice[computerSelection]) {\n return winStatement(playerSelection, computerSelection);\n }\n return loseStatement(computerSelection, playerSelection);\n}\n\n// Should be improved upon? Actually take input?\nconst playerSelection = 'rock';\nconst computerSelection = computerPlay();\nconsole.log(playRound(playerSelection, computerSelection));\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-05T23:20:10.913",
"Id": "235135",
"ParentId": "235084",
"Score": "3"
}
},
{
"body": "<pre><code>function computerPlay() {\n let choices = ['rock', 'paper', 'scissors'];\n return choices[Math.floor(Math.random() * choices.length)];\n}\n</code></pre>\n\n<p>In the above function, you create the <code>choices</code> array again and again. This is a waste of time and memory. It's better to create the choices once and for all:</p>\n\n<pre><code>const choices = ['rock', 'paper', 'scissors'];\n\nfunction computerPlay() {\n return choices[Math.floor(Math.random() * choices.length)];\n}\n</code></pre>\n\n<p>On the other hand, the JavaScript compiler may be able to prove that creating this array each time is not necessary. In that case the code might stay as it is. I don't know how advanced the optimization techniques for JavaScript compilers are in 2020. You would have to measure this using a memory profiler.</p>\n\n<p>The <code>playRound</code> function is quite big, and having all these inner functions does not increase the readability. Especially since you are inconsistent: The message for a tie is in the lower half while the two other messages are in the upper half. All these messages belong together, therefore they should be written in the same area of the code.</p>\n\n<pre><code>function playRound(playerSelection, computerSelection) {\n const capitalize = word => { return word.charAt(0).toUpperCase() + word.slice(1); }\n const winStatement = (winner, loser) => { return `You Win! ${capitalize(winner)} beats ${capitalize(loser)}`; }\n const loseStatement = (winner, loser) => { return `You Lose! ${capitalize(winner)} beats ${capitalize(loser)}`; }\n const winningChoice = {'rock': 'paper', 'paper': 'scissors', 'scissors': 'rock'};\n</code></pre>\n\n<p>In all these inner functions, you can remove the <code>{ return</code> at the beginning and the <code>}</code> at the end. This makes them shorter and easier to understand since they now look more similar to the mathematical concept of a function, which is written as <span class=\"math-container\">\\$f\\colon A \\to B\\$</span>, and not <span class=\"math-container\">\\$f\\colon A \\to \\left\\{ \\mathop{\\text{return}} B \\right\\}\\$</span>.</p>\n\n<p>The <code>winningChoice</code> should be moved outside of this function, just like the <code>choices</code> in <code>computerPlay</code>.</p>\n\n<pre><code> playerSelection = playerSelection.toLowerCase();\n</code></pre>\n\n<p>Having to deal with uppercase and lowercase words makes this function more complicated than necessary. Normalizing the user input should be done somewhere else. This way, the <code>playRound</code> function can focus on its single purpose, which is deciding the outcome of the game.</p>\n\n<pre><code> if(playerSelection === computerSelection) return \"Oh! It's a tie\";\n else if(playerSelection === winningChoice[computerSelection]) return winStatement(playerSelection, computerSelection);\n else return loseStatement(computerSelection, playerSelection);\n}\n</code></pre>\n\n<p>This code looks quite condensed. The usual style is to write <code>if (</code>, with a space.</p>\n\n<p>A general guideline is that your code should not require horizontal scrollbars. Therefore you should place all the <code>return</code> statements into separate lines, like this:</p>\n\n<pre><code> if (playerSelection === computerSelection)\n return \"Oh! It's a tie\";\n else if (playerSelection === winningChoice[computerSelection])\n return winStatement(playerSelection, computerSelection);\n else\n return loseStatement(computerSelection, playerSelection);\n</code></pre>\n\n<p>This way you can clearly see the structure of the code by reading only the leftmost word of each line: if return else return else return.</p>\n\n<p>When I copied your code duringthe review, I made some other changes, and this is the final result:</p>\n\n<pre><code>const choices = ['rock', 'paper', 'scissors'];\nconst beats = {'rock': 'paper', 'paper': 'scissors', 'scissors': 'rock'};\nconst upper = {'rock': 'Rock', 'paper': 'Paper', 'scissors': 'Scissors'};\n\nfunction computerPlay() {\n return choices[Math.floor(Math.random() * choices.length)];\n}\n\nfunction playRound(human, computer) {\n return human === computer\n ? `Oh! It's a tie`\n : human === beats[computer]\n ? `You win! ${upper[human]} beats ${computer}`\n : `You lose! ${upper[computer]} beats ${human}`;\n}\n\nconst playerSelection = choices[0];\nconst computerSelection = computerPlay();\nconsole.log(playRound(playerSelection, computerSelection));\n</code></pre>\n\n<p>As you can see, I decided to only capitalize one of the words, and I also created a fixed translation table instead of capitalizing the words on-the-fly. Again, I did this to avoid unnecessary object creation. This kind of performance optimization is not necessary for a simple Rock Paper Scissors game, but I tried to be consistent in the code. Oh well, except that the <code>You win</code> and <code>You lose</code> strings are still templates that have to be created dynamically.</p>\n\n<p>I also made the variable names a bit shorter: <code>human</code> instead of <code>playerSelection</code>. I removed the <code>selection</code> since that was not an essential part of the name. I renamed the variable from <code>player</code> to <code>human</code> since both the human and the computer are <em>players</em> of the game, which makes the variable name <code>player</code> ambiguous.</p>\n\n<p>In <code>playRound</code> it's a stylistic choice whether to use the <code>?:</code> operator or an <code>if else</code> chain. At first I used an <code>if (human === computer) return 'tie'</code> combined with a <code>?:</code> operator for deciding between <code>you win</code> and <code>you lose</code>. I didn't like this mixture because it felt inconsistent. I had to settle on either using the <code>?:</code> operator throughout or the <code>if else</code> chain. I chose the <code>?:</code> operator because it is shorter. On the other hand, the <code>if else</code> chain would have probably been clearer.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-06T01:47:42.757",
"Id": "460053",
"Score": "0",
"body": "Thanks for the in-depth report - I always get a nag when I make an answer that is just a scraping and fearing that the user might accept it and think that is all there is to fix - and that the community may think that it is all - but at the same time I don't want to not put it down, because it may get missed."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-06T02:18:11.617",
"Id": "460055",
"Score": "0",
"body": "However, I personally would not use continuous ternaries like that, I would use parenthesis. Variables names are not as much of a problem really"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-06T00:52:54.947",
"Id": "235142",
"ParentId": "235084",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-04T18:21:06.140",
"Id": "235084",
"Score": "3",
"Tags": [
"javascript",
"ecmascript-6",
"rock-paper-scissors"
],
"Title": "Rock Paper Scissors game- JavaScript"
}
|
235084
|
<p>Before the interview for the Junior (i hope:)) position of Java developer, I was asked to do a test task. Kindly ask you to review my code. Riht now program arguments are hardcoded and not from args[], tomorrow I will add arguments processing.</p>
<p>You can see my code on <a href="https://github.com/DannPeterson/Raintree-homework" rel="nofollow noreferrer">GitHub</a> also.
I would appreciate any feedback. Thanks!</p>
<p>Project structure:</p>
<p><a href="https://i.stack.imgur.com/psoop.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/psoop.png" alt="enter image description here"></a></p>
<p>Task description:</p>
<blockquote>
<p>Write a JAVA program that will:<br>
1. Generate a file with random numeric (range from 1 to 2^64 − 1 integers) data. Filesize is limited by command line options. The default file size limit is 64 MB. Each random number is separated by space (ASCII code 32). Program will require 1 argument, which is the file name to be generated.<br>
2. Read the file generated in step #1, analyze it and output it to the console. The
output should include:<br>
1. 10 most frequently appeared numbers in bar chart form.<br>
2. The count of Prime numbers.<br>
3. The count of Armstrong numbers.<br>
4. Output separately the time taken to read and analyze the file.<br>
Pay attention:<br>
1. Check error handling.<br>
2. Keep the code clean and formatted, follow the basic JAVA naming conventions.<br>
3. Program speed matters, you may use parallel processing. </p>
</blockquote>
<p>Main Class:</p>
<pre><code>package ee.raintree.test.numbers;
import java.io.File;
import java.io.IOException;
import java.math.BigInteger;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class Main {
private final static String SPACE = " ";
private static int fileSize = 67108864;
private static String fileName;
public static void main(String args[]) throws InterruptedException, ExecutionException, IOException {
fileName = "result";
File result = new File(fileName);
int coreCount = Runtime.getRuntime().availableProcessors();
ExecutorService service = Executors.newFixedThreadPool(coreCount);
// Part 1: Generate numbers and write them to file
List<File> tmpFiles = new ArrayList<>();
List<Future> futureTmpFiles = new ArrayList<>();
for (int i = 0; i < coreCount; i++) {
Future<File> futureTmpFile = service.submit(new TmpNumbersFileCreator(fileSize / coreCount));
futureTmpFiles.add(futureTmpFile);
}
for (int i = 0; i < coreCount; i++) {
Future<File> futureTmpFile = futureTmpFiles.get(i);
tmpFiles.add(futureTmpFile.get());
}
IOCopier.joinFiles(result, tmpFiles);
// Part 2: Read numbers from file and analyze them
long readAndAnalyzeStart = System.currentTimeMillis();
List<BigInteger> numbers = new ArrayList<>();
for (String line : Files.readAllLines(result.toPath())) {
for (String part : line.split(SPACE)) {
numbers.add(new BigInteger(part));
}
}
int listSize = numbers.size();
int chunkListSize = listSize / coreCount + 1;
List<List<BigInteger>> lists = ListSplitter.ofSize(numbers, chunkListSize);
int countOfPrimeNumbers = 0;
int countOfArmstrongNumbers = 0;
List<Future> futurePrimeCounts = new ArrayList<>();
for(int i = 0; i < coreCount; i++) {
final int j = i;
Future<Integer> futurePrimeCount = service.submit(new Callable<Integer>() {
@Override
public Integer call() throws Exception {
int primeCount = 0;
for(BigInteger number : lists.get(j)) {
if(number.isProbablePrime(128)) {
primeCount++;
}
}
return primeCount;
}
});
futurePrimeCounts.add(futurePrimeCount);
}
for (int i = 0; i < coreCount; i++) {
Future<Integer> futurePrimeCount = futurePrimeCounts.get(i);
countOfPrimeNumbers = countOfPrimeNumbers + futurePrimeCount.get();
}
List<Future> futureArmstrongCounts = new ArrayList<>();
for(int i = 0; i < coreCount; i++) {
final int j = i;
Future<Integer> futureArmstrongCount = service.submit(new Callable<Integer>() {
@Override
public Integer call() throws Exception {
int armstrongCount = 0;
for(BigInteger number : lists.get(j)) {
if(MathUtils.isArmstrongNumber(number)) {
armstrongCount++;
}
}
return armstrongCount;
}
});
futureArmstrongCounts.add(futureArmstrongCount);
}
for (int i = 0; i < coreCount; i++) {
Future<Integer> futureArmstrongCount = futureArmstrongCounts.get(i);
countOfArmstrongNumbers = countOfArmstrongNumbers + futureArmstrongCount.get();
}
service.shutdown();
long readAndAnalyzeEnd = System.currentTimeMillis();
// Part 3: Printing result
System.out.println("Read and analysis done. Thak took " + (readAndAnalyzeEnd - readAndAnalyzeStart) + " milliseconds.");
System.out.println("Prime numbers count: " + countOfPrimeNumbers);
System.out.println("Prime numbers count: " + countOfArmstrongNumbers);
System.out.println("10 most frequently appeared numbers in bar chart form:");
Map<BigInteger, Integer> numbersFreqMap = MapUtils.getSortedFreqMapFromList(numbers);
BarChartPrinter printer = new BarChartPrinter(numbersFreqMap);
printer.print();
}
}
</code></pre>
<p>BarChartPrinter Class:</p>
<pre><code>package ee.raintree.test.numbers;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
public class BarChartPrinter<T> {
private final static String BAR = "|";
private final static String SPACE = " ";
List<Entry<T, Integer>> listOfEntries;
private int chartsCount = 10;
private int longestEntrySize;
private int barChartStep;
public BarChartPrinter(Map<T, Integer> map) {
listOfEntries = new ArrayList<Entry<T, Integer>>(map.entrySet());
if (listOfEntries.size() < chartsCount) {
chartsCount = listOfEntries.size();
}
barChartStep = listOfEntries.get(chartsCount - 1).getValue();
}
public void print() {
setLongestEntrySize();
printBarChart();
}
private void printBarChart() {
for (int i = 0; i < chartsCount; i++) {
Entry<T, Integer> entry = listOfEntries.get(i);
int barsCount = entry.getValue() / barChartStep;
System.out.print(entry.getKey() + getAdditionalSpaces(entry.getKey().toString()) + SPACE);
for (int bars = 0; bars < barsCount; bars++) {
System.out.print(BAR);
}
System.out.println();
}
}
private void setLongestEntrySize() {
int longest = 0;
for(int i = 0; i < chartsCount; i++) {
if(listOfEntries.get(i).getKey().toString().length() > longest) {
longest = listOfEntries.get(i).getKey().toString().length();
}
}
longestEntrySize = longest;
}
private String getAdditionalSpaces(String string) {
StringBuilder sb = new StringBuilder();
int needSpaces = longestEntrySize - string.length();
for(int i = 0; i < needSpaces; i++) {
sb.append(SPACE);
}
return sb.toString();
}
}
</code></pre>
<p>IOCopier Class, totally copied from some semi-official source:</p>
<pre><code>package ee.raintree.test.numbers;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
import org.apache.commons.io.IOUtils;
class IOCopier {
public static void joinFiles(File destination, List<File> sources) {
try (OutputStream output = createAppendableStream(destination)) {
for (File source : sources) {
appendFile(output, source);
}
} catch (IOException e) {
System.out.println("Error joining files");
}
}
private static BufferedOutputStream createAppendableStream(File destination) throws FileNotFoundException {
return new BufferedOutputStream(new FileOutputStream(destination, true));
}
private static void appendFile(OutputStream output, File source) {
try (InputStream input = new BufferedInputStream(new FileInputStream(source))) {
IOUtils.copy(input, output);
} catch (IOException e) {
System.out.println("Error appending file");
}
}
}
</code></pre>
<p>ListSplitter, totally copied from some semi-official source:</p>
<pre><code>package ee.raintree.test.numbers;
import java.util.AbstractList;
import java.util.ArrayList;
import java.util.List;
public class ListSplitter<T> extends AbstractList<List<T>> {
private final List<T> list;
private final int chunkSize;
public ListSplitter(List<T> list, int chunkSize) {
this.list = new ArrayList<>(list);
this.chunkSize = chunkSize;
}
public static <T> ListSplitter<T> ofSize(List<T> list, int chunkSize) {
return new ListSplitter<>(list, chunkSize);
}
@Override
public List<T> get(int index) {
int start = index * chunkSize;
int end = Math.min(start + chunkSize, list.size());
if (start > end) {
throw new IndexOutOfBoundsException("Index " + index + " is out of the list range <0," + (size() - 1) + ">");
}
return new ArrayList<>(list.subList(start, end));
}
@Override
public int size() {
return (int) Math.ceil((double) list.size() / (double) chunkSize);
}
}
</code></pre>
<p>MapUtils Class:</p>
<pre><code>package ee.raintree.test.numbers;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;
public class MapUtils {
public static <T> Map<T, Integer> getSortedFreqMapFromList(List<T> list) {
Map<T, Integer> map = getFreqMapFromList(list);
Set<Entry<T, Integer>> entries = map.entrySet();
List<Entry<T, Integer>> listOfEntries = new ArrayList<Entry<T, Integer>>(entries);
Collections.sort(listOfEntries, getValueDescComparator());
Map<T, Integer> sortedByValue = new LinkedHashMap<T, Integer>(listOfEntries.size());
for (Entry<T, Integer> entry : listOfEntries) {
sortedByValue.put(entry.getKey(), entry.getValue());
}
return sortedByValue;
}
private static <T> Map<T, Integer> getFreqMapFromList(List<T> list) {
Map<T, Integer> result = new HashMap<>();
for (T item : list) {
if (result.get(item) == null) {
result.put(item, 1);
} else {
result.put(item, result.get(item) + 1);
}
}
return result;
}
private static <T> Comparator<Entry<T, Integer>> getValueDescComparator() {
Comparator<Entry<T, Integer>> valueComparator = new Comparator<Entry<T, Integer>>() {
@Override
public int compare(Entry<T, Integer> e1, Entry<T, Integer> e2) {
Integer v1 = e1.getValue();
Integer v2 = e2.getValue();
return v2.compareTo(v1);
}
};
return valueComparator;
}
}
</code></pre>
<p>MathUtilsClass:</p>
<pre><code>package ee.raintree.test.numbers;
import java.math.BigInteger;
public class MathUtils {
public static boolean isArmstrongNumber(BigInteger number) {
String numberInString = number.toString();
int digitsCount = number.toString().length();
int power = digitsCount;
BigInteger sum = BigInteger.ZERO;
for (int i = 0; i < digitsCount; i++) {
int digit = Character.getNumericValue(numberInString.charAt(i));
BigInteger digitInPower = BigInteger.valueOf(digit).pow(power);
sum = sum.add(digitInPower);
}
return sum.compareTo(number) == 0;
}
}
</code></pre>
<p>TmpNumbersFileCreator Class:</p>
<pre><code>package ee.raintree.test.numbers;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.util.Random;
import java.util.concurrent.Callable;
public class TmpNumbersFileCreator implements Callable<File> {
private File file;
private PrintWriter printWriter;
private static final String SEPARATOR = " ";
private int size;
public TmpNumbersFileCreator(int size) {
this.size = size;
}
@Override
public File call() throws Exception {
return getTempFile();
}
public File getTempFile() {
createTempFile();
writeNumbersToFile();
return file;
}
private void createTempFile() {
try {
file = File.createTempFile("numbers-", "-txt");
file.deleteOnExit();
} catch (IOException e) {
System.out.println("Temporary file creation failed");
}
}
private void writeNumbersToFile() {
try {
printWriter = new PrintWriter(file);
} catch (FileNotFoundException e) {
System.out.println("Temporary file not found");
}
while (!isFileSizeMax()) {
printWriter.write(getRandomNumber().toString() + SEPARATOR);
}
printWriter.flush();
printWriter.close();
}
private BigInteger getRandomNumber() {
Random random = new Random();
BigInteger number;
do {
number = new BigInteger(64, random);
} while (number.equals(BigInteger.ZERO));
return number;
}
private boolean isFileSizeMax() {
if (file.length() <= size) {
return false;
}
return true;
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-04T23:14:49.777",
"Id": "459934",
"Score": "2",
"body": "This is a pretty extensive and complex task just to get invited to a job interview. The bar chart requirement is pretty off the hook (and underspecified, what do they actually want here, just a line of asterisks?) I'd seriously consider not working for this company."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-05T09:00:50.577",
"Id": "459961",
"Score": "0",
"body": "@markspace Thank you very much for your feedback! In fact, this is a fairly well-known and old company in our area. In any case, I am now in search of my first IT job and, with my resume and lack of experience, I have no way to choose which company to work in."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-06T19:40:08.253",
"Id": "460171",
"Score": "0",
"body": "If an interview task is incomplete it is always because they want to see if and what kind of questions you ask to get clarifications. It doesn't tell anything about the company."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-07T08:39:21.800",
"Id": "460235",
"Score": "0",
"body": "The task explicitly asks for a couple of things you haven't implemented yet. When working on such projects, make sure you keep a feature-list you check-off. Tests are useful for this too."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-07T11:54:13.117",
"Id": "460254",
"Score": "0",
"body": "@Mast thank you for your comment! Did you mean \"Check error handling\" or something else also?"
}
] |
[
{
"body": "<p>Before handing the company any code you wrote, you should ask for clarification of the task.</p>\n\n<blockquote>\n <p>Write a JAVA program that will:</p>\n</blockquote>\n\n<p>The correct spelling is Java, not JAVA.</p>\n\n<blockquote>\n <ol>\n <li>Generate a file with random numeric (range from 1 to 2^64 − 1 integers) data.</li>\n </ol>\n</blockquote>\n\n<p>The grammar is slightly wrong here. They should have written \"with random integers in the range from 1 to 2^64 - 1\". I don't think you are supposed to squeeze 2^64 integers into a file that is only 64 MB in size.</p>\n\n<p>Are duplicate numbers allowed? What is the purpose of these random numbers, after all?</p>\n\n<p>Should the random numbers follow a certain distribution?</p>\n\n<blockquote>\n <p>Filesize is limited by command line options.</p>\n</blockquote>\n\n<p>What does this mean? In another part of the task they say \"Program will require 1 argument\", which contradicts this sentence.</p>\n\n<p>Also, how is the file size specified? It could be <code>-max 64MB</code> or <code>-max-file-size=64m</code> or <code>--maximal-file-size 32M</code> or <code>max=16000k</code>. Also, when they say <code>MB</code>, do they mean <code>1_000_000</code> or rather <code>1_048_576</code>?</p>\n\n<blockquote>\n <ol start=\"2\">\n <li>Read the file generated in step #1, analyze it and output it to the console.</li>\n </ol>\n</blockquote>\n\n<p>This could mean you are supposed to write the whole 64 MB to the output in a single line. Is that really what they want, and if so, why?</p>\n\n<blockquote>\n <p>The output should include:</p>\n</blockquote>\n\n<p>Does the word \"include\" here mean you are allowed to output arbitrary other things?</p>\n\n<blockquote>\n <ol>\n <li>10 most frequently appeared numbers in bar chart form.</li>\n </ol>\n</blockquote>\n\n<p>How wide should the bar chart be? Should that be configurable by command line arguments?</p>\n\n<blockquote>\n <ol start=\"2\">\n <li>The count of Prime numbers.</li>\n </ol>\n</blockquote>\n\n<p>Is it sufficient if the program outputs the count of <em>probable primes</em> (like your code currently does)?</p>\n\n<p>Should the program output some example prime numbers, in addition to the count? This would allow a human reader to crosscheck whether the program works reliably.</p>\n\n<blockquote>\n <ol start=\"4\">\n <li>Output separately the time taken to read and analyze the file.</li>\n </ol>\n</blockquote>\n\n<p>Wall time or CPU time?</p>\n\n<blockquote>\n <p>Program speed matters</p>\n</blockquote>\n\n<p>That's too imprecise. What run time is acceptable for the program? Is 5 minutes ok, or does it have to be less than 10 seconds? How many CPUs are available for parallel processing?</p>\n\n<hr>\n\n<p>All these questions are typical for your future everyday job. Often the people who give you tasks like these don't know exactly what they <em>really</em> want. By asking these questions in a polite and calm way, you make them think again about their requirements and whether they make sense at all.</p>\n\n<hr>\n\n<p>Regarding your code: You should install IntelliJ and load your code there. IntelliJ will produce many warnings and hints how you can improve your code. In many situations IntelliJ can also fix the code for you. Just place the text cursor on a warning and press Alt+Enter to see whether there is a fix or a refactoring for that warning.</p>\n\n<p>For example, starting with Java 8 it is no longer usual to write the verbose <code>implements Callable<X></code>. Instead, unnamed functions are used. These are also called lambda functions.</p>\n\n<p>Your error handling is broken. If nothing else is said, when an error occurs while writing the file with the random numbers, it does not make sense to continue at all. Therefore it is wrong to just write an error message to <code>System.out</code>. Just let the <code>IOException</code> bubble up until some code really knows what to do with this exception. In your case you don't know at all, therefore no part of your code should catch this exception.</p>\n\n<p>In <code>MathUtils</code> there should be a method <code>isPrime</code>. Your current code is inconsistent since <code>isArmstrongNumber</code> is implemented there but <code>isPrime</code> isn't.</p>\n\n<p>You should add some unit tests to your code, just to prove that you tested the basic cases.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-05T10:09:06.693",
"Id": "459964",
"Score": "0",
"body": "Thank you @Roland for your detailed comment! Actually I was also a little bit confused about \"Filesize is limited by command line options\" and I asked for clarification and get answer, that program can take 2 arguments. Yes, task description is not very clear. Also I did as you adviced with IntelliJ and MathUtils class - now code is cleaner, thank you for that!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-04T21:16:02.633",
"Id": "235091",
"ParentId": "235086",
"Score": "5"
}
},
{
"body": "<p>Did you measure run time before implementing the multi threaded random number generator and analyser? I'm betting that combining the files takes a lot more time than you gain from concurrency (IO is slow). This would be premature optimization and a red flag.</p>\n\n<p>The main method should not contain any logic other than parsing arguments to a format understood by the business logic. You should have the number generator, number analyser and number printer as a self contained classes and have the main method pass data between them. Study the single responsibility principle.</p>\n\n<p>I think you were supposed to print two times: reading time and analysis time.</p>\n\n<p>You read the numbers to memory and loop over them three times (so four loops). You should have been able to do the analysis while reading the numbers from the file (one loop). Again, did you measure the effect of the multi threaded analysis versus single threaded? The task did not specify upper limit to the file size so by reading the data to memory you created an unnecessary artificial limit from the JVM memory.</p>\n\n<p>I was expecting some comments explaining <em>why</em> you chose to code as you did.</p>\n\n<p><code>ListSplitter</code> does a lot of unnecessary copying. It should not extend <code>AbstractList</code> as a simple utility method would suffice. If you submit copied code, always try to copy good code. :)</p>\n\n<p>You're creating a new instance of <code>Random</code> every time you create a random number. That's unnecessary and complete waste of time. The Random should be an instance variable.</p>\n\n<p>Concatenating the separator to the number before writing is unnecessary waste of time as it creates a new immediately disposed string object. Write the number first and then write the separator (as a character, not string).</p>\n\n<p>The if-statement in the file size checking that returns true or false only creates unnecessary cognitive load. Just write:</p>\n\n<pre><code>return file.length() > size;\n</code></pre>\n\n<p>Checking the number of bytes written by calling <code>file.length()</code> is quite expensive as it goes all the way to the file system to get the result. It also fails to take into account any buffering that may occur during the writing, possibly causin errors. It would be more efficient to simply keep an integer counter of the number of bytes written.</p>\n\n<p>You're using <code>PrintWriter</code> to write the numbers but you are not using any special functionality from it. It gives the impression that you're not familiar with the IO-classes. You should use <code>BufferedWriter</code> instead to get the speed benefit of buffered writing (you need to count the written bytes manually now).</p>\n\n<p><strong>Don't forget to specify the character encoding of the file!</strong> Even though you're only writing numbers and spaces and the resulting file will most likely always be ASCII-compatible, explicitely specifying it tells the reader you're not one of the people who cause character encoding problems in production by always relying on system default encoding.</p>\n\n<p>This one is particularly bad copy-pasting as it is hard to read and very inefficient. You should first get the value to a variable and use it in the if-statement and assignment.</p>\n\n<pre><code>if(listOfEntries.get(i).getKey().toString().length() > longest) {\n longest = listOfEntries.get(i).getKey().toString().length();\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-07T11:30:26.867",
"Id": "460247",
"Score": "0",
"body": "Thank you for your useful comments, I'm already rewriting my code now. I was also thinking that Main class have too much logics, that should be in other classes. After editing TmpNumbersFileCreator (one time new Random() instantiation, checking syze by written bytes amount comparing) file creation speed increases drammatycally, thank you for that! About speeds: I cheked on my machine that file creation with MT is about 4 times faster than ST and List<BigInteger> analysis with MT is about 2.5 times faster. Merging files is surprisingly fast - about 150ms to create 64MB file."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-07T11:39:01.243",
"Id": "460248",
"Score": "0",
"body": "I'm also want to read file byte-by-byte with FileInputStream and analyze numbers during this reading, but now I dont know how to speed up this process and use parallel processing in this."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-07T12:45:01.483",
"Id": "460259",
"Score": "0",
"body": "Actually now I was testing this \"analyze-on-fly\" approach and that analysis took 5 minutes with 64MB file! With my old splitted-list-approach is was 13 seconds."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-07T12:54:22.663",
"Id": "460263",
"Score": "0",
"body": "Did you remove buffering from the reading too?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-07T14:45:04.420",
"Id": "460275",
"Score": "0",
"body": "I created [this](https://codeshare.io/a3l4gv) analyzer class"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-07T16:29:50.590",
"Id": "460292",
"Score": "0",
"body": "You could make another post about that. There's a couple of things wrong with it (lack of buffering is causing the excess time)."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-06T20:09:18.747",
"Id": "235183",
"ParentId": "235086",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "235091",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-04T19:23:39.677",
"Id": "235086",
"Score": "6",
"Tags": [
"java",
"multithreading",
"interview-questions"
],
"Title": "Data analysis program for job interview"
}
|
235086
|
<p>For learning purposes, I wanted to create a header-only C++ wrapper library around HTTP CURL functionality. At the moment the library only implements GET and POST, but I will add other HTTP methods later. Additionally, right now it only supports calling <code>get()</code> or <code>post()</code> with a fully constructed <code>RequestConfig</code> object. I plan on adding overloads that allow the user to pass only some of the parameters (URL, URL & parameters, etc).</p>
<p>Any pointers or guidance would be greatly appreciated! </p>
<p><strong>httplib.hpp</strong></p>
<pre class="lang-cpp prettyprint-override"><code>#pragma once
#include <map>
#include <iterator>
#include <curl/curl.h>
#include <sstream>
#include <chrono>
namespace easyhttp {
enum class HttpRequestType { get, post };
enum class RequestError { none, timeout, socket_error, error_misc };
struct BasicAuthentication {
std::string username;
std::string password;
};
struct HttpResponse {
RequestError error;
std::string response_code;
std::string content;
};
class Parameters {
public:
using iterator = std::map<std::string, std::string>::iterator;
Parameters() {}
explicit Parameters(const std::initializer_list<std::pair<std::string, std::string>>& list) {
for (auto itr = list.begin(); itr != list.end(); itr++) {
if (!itr->first.empty()) {
items_[itr->first] = itr->second;
}
}
}
explicit Parameters(const std::pair<std::string, std::string>& x) {
items_[x.first] = x.second;
}
explicit Parameters(const std::map<std::string, std::string> x) : items_{ x } {}
void add(std::pair<std::string, std::string> p) {
if (!p.first.empty()) {
items_[p.first] = p.second;
}
}
void remove(std::string key) {
items_.erase(key);
}
size_t size() {
return items_.size();
}
std::string get_value(std::string key) {
return (items_.find(key) == items_.end()) ? "" : items_[key];
}
void clear() {
items_.clear();
}
std::map<std::string, std::string>::iterator begin() {
return items_.begin();
}
std::map<std::string, std::string>::iterator end() {
return items_.end();
}
protected:
std::map<std::string, std::string> items_;
};
class UrlParameters : public Parameters {
public:
UrlParameters() : Parameters() {}
explicit UrlParameters(std::initializer_list<std::pair<std::string, std::string>> list)
: Parameters(list) {}
explicit UrlParameters(const std::pair<std::string, std::string>& x)
: Parameters(x) {}
explicit UrlParameters(const std::map<std::string, std::string>& x)
: Parameters(x) {}
std::string get_string() {
if (str_.empty()) {
encode();
return str_;
}
return str_;
}
std::string get_encoded_string() {
if (encoded_str_.empty()) {
return encode();
}
return encoded_str_;
}
std::string encode() {
if (items_.size() == 0) {
return "";
}
str_.clear();
encoded_str_.clear();
str_ = "?";
encoded_str_ = "?";
for (auto& [k, v] : items_) {
str_ += ("&" + k + "=" + v);
encoded_str_ += ("&" + url_escape_str(std::string(k)) + "=" + url_escape_str(std::string(v)));
}
str_.erase(1, 1);
encoded_str_.erase(1, 1);
return encoded_str_;
}
private:
std::string url_escape_str(std::string& orig) {
// Think about a possible try catch here
// Technically, std::strings ctor can throw
char *res = curl_easy_escape(nullptr, orig.c_str(), orig.length());
std::string escaped_str = std::string(res);
curl_free(res);
return escaped_str;
}
std::string str_;
std::string encoded_str_;
};
class Headers : public Parameters {
public:
Headers() : Parameters() {}
explicit Headers(std::initializer_list<std::pair<std::string, std::string>> list)
: Parameters(list) {}
explicit Headers(const std::pair<std::string, std::string>& x)
: Parameters(x) {}
explicit Headers(const std::map<std::string, std::string>& x)
: Parameters(x) {}
std::string encode(const std::string key) {
return (items_.find(key) == items_.end()) ? "" : key + ": " + items_[key];
}
};
struct RequestConfig {
std::string url;
UrlParameters params;
Headers headers;
BasicAuthentication auth;
std::chrono::seconds timeout_sec;
};
namespace{
size_t http_request_impl_response_write(char* ptr, size_t size, size_t numb, void* ud) {
size_t response_size = size * numb;
std::stringstream* ss = (std::stringstream*)ud;
ss->write(ptr, response_size);
return response_size;
}
}
class Request {
public:
HttpResponse post(RequestConfig& c) {
HttpResponse resp = http_request_impl(HttpRequestType::post, c);
return resp;
}
HttpResponse get(RequestConfig& c) {
HttpResponse resp = http_request_impl(HttpRequestType::get, c);
return resp;
}
private:
HttpResponse http_request_impl(const HttpRequestType r, RequestConfig& c) {
CURL* curl;
struct curl_slist* chunk = NULL;
curl_global_init(CURL_GLOBAL_ALL);
curl = curl_easy_init();
std::stringstream response_stream;
HttpResponse resp;
curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, static_cast<long>(c.timeout_sec.count()));
curl_easy_setopt(curl, CURLOPT_URL, (c.url + c.params.get_encoded_string()).c_str());
if (c.headers.size() > 0) {
for (const auto& [k,v] : c.headers) {
chunk = curl_slist_append(chunk, c.headers.encode(k).c_str());
}
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, chunk);
}
if (r == HttpRequestType::post) {
curl_easy_setopt(curl, CURLOPT_POST, 1);
if (c.params.size() > 0) {
std::string temp = c.params.get_encoded_string();
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, temp.c_str());
}
else {
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, "");
}
}
if (!c.auth.username.empty() && !c.auth.password.empty()) {
curl_easy_setopt(curl, CURLOPT_USERNAME, c.auth.username.c_str());
curl_easy_setopt(curl, CURLOPT_PASSWORD, c.auth.password.c_str());
}
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, http_request_impl_response_write);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response_stream);
CURLcode res = curl_easy_perform(curl);
auto http_code = 0L;
curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &http_code);
curl_easy_cleanup(curl);
curl_slist_free_all(chunk);
if (res == CURLE_OK) {
resp.content = response_stream.str();
resp.error = RequestError::none;
resp.response_code = std::to_string(http_code);
}
else if (res == CURLE_OPERATION_TIMEDOUT) {
resp.content = "Operation timed out.";
resp.error = RequestError::timeout;
resp.response_code = "-1";
}
else {
resp.content = "Request encountered error: " + std::string(curl_easy_strerror(res));
resp.error = RequestError::error_misc;
resp.response_code = "-1";
}
return resp;
}
};
};
</code></pre>
|
[] |
[
{
"body": "<p>Quite a bit of code to look at. This is not a complete review, but I did two simple things, which may prompt thought / improvements:</p>\n\n<ol>\n<li>I ran a static analyser over your code (clang-tidy V9). The output is below. It is pointing many of the stylistic things I would say too. And it highlights some actual issues.</li>\n<li>I added a <code>main()</code> method and i tried to use your code. ie, I made it \"work\". This also highlighted a couple of small issues. Try it yourself. Is this the API you want for the users of your library? How could it be improved? </li>\n</ol>\n\n<p>my <code>main()</code>:</p>\n\n<pre><code>int main()\n{\n auto req_params = easyhttp::UrlParameters{{\"q\",\"test\"}};\n auto req_config = easyhttp::RequestConfig{\n \"https://www.google.com\",\n req_params,\n {},\n {},\n std::chrono::duration<long>{10}\n };\n auto req = easyhttp::Request();\n auto response = req.get(req_config);\n std::cout << response.content << \"\\n\";\n return 0;\n}\n\n</code></pre>\n\n<p>clang-tidy output</p>\n\n<pre><code>curl2.cpp:18:8: warning: constructor does not initialize these fields: error [hicpp-member-init]\nstruct HttpResponse {\n ^\ncurl2.cpp:29:3: warning: use '= default' to define a trivial default constructor [hicpp-use-equals-default]\n Parameters() {}\n ^ ~~\n = default;\ncurl2.cpp:31:12: warning: initializer-list constructor should not be declared explicit [google-explicit-constructor]\n explicit Parameters(const std::initializer_list<std::pair<std::string, std::string>>& list) {\n ~~~~~~~~~^\ncurl2.cpp:32:5: warning: use range-based for loop instead [modernize-loop-convert]\n for (auto itr = list.begin(); itr != list.end(); itr++) {\n ^ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n (const auto & itr : list)\ncurl2.cpp:41:64: warning: the const qualified parameter 'x' is copied for each invocation; consider making it a reference [performance-unnecessary-value-param]\n explicit Parameters(const std::map<std::string, std::string> x) : items_{x} {}\n ^\n &\ncurl2.cpp:43:48: warning: the parameter 'p' is copied for each invocation but only used as a const reference; consider making it a const reference [performance-unnecessary-value-param]\n void add(std::pair<std::string, std::string> p) {\n ^\n const &\ncurl2.cpp:49:27: warning: the parameter 'key' is copied for each invocation but only used as a const reference; consider making it a const reference [performance-unnecessary-value-param]\n void remove(std::string key) { items_.erase(key); }\n ^\n const &\ncurl2.cpp:53:37: warning: the parameter 'key' is copied for each invocation but only used as a const reference; consider making it a const reference [performance-unnecessary-value-param]\n std::string get_value(std::string key) {\n ^\n const &\ncurl2.cpp:64:38: warning: member variable 'items_' has protected visibility [cppcoreguidelines-non-private-member-variables-in-classes]\n std::map<std::string, std::string> items_;\n ^\ncurl2.cpp:69:21: warning: initializer for base class 'easyhttp::Parameters' is redundant [readability-redundant-member-init]\n UrlParameters() : Parameters() {}\n ^~~~~~~~~~~~~\ncurl2.cpp:71:12: warning: initializer-list constructor should not be declared explicit [google-explicit-constructor]\n explicit UrlParameters(std::initializer_list<std::pair<std::string, std::string>> list)\n ~~~~~~~~~^\ncurl2.cpp:96:9: warning: the 'empty' method should be used to check for emptiness instead of 'size' [readability-container-size-empty]\n if (items_.size() == 0) {\n ^~~~~~~~~~~~~~~~~~\n items_.empty()\n/usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c++/9/bits/stl_map.h:463:7: note: method 'map'::empty() defined here\n empty() const _GLIBCXX_NOEXCEPT\n ^\ncurl2.cpp:107:30: warning: string concatenation results in allocation of unnecessary temporary strings; consider using 'operator+=' or 'string::append()' instead [performance-inefficient-string-concatenation]\n str_ += (\"&\" + k + \"=\" + v);\n ^\ncurl2.cpp:118:15: warning: method 'url_escape_str' can be made static [readability-convert-member-functions-to-static]\n std::string url_escape_str(const std::string& orig) {\n ^\n static\ncurl2.cpp:135:15: warning: initializer for base class 'easyhttp::Parameters' is redundant [readability-redundant-member-init]\n Headers() : Parameters() {}\n ^~~~~~~~~~~~~\ncurl2.cpp:137:12: warning: initializer-list constructor should not be declared explicit [google-explicit-constructor]\n explicit Headers(std::initializer_list<std::pair<std::string, std::string>> list)\n ~~~~~~~~~^\ncurl2.cpp:144:40: warning: the const qualified parameter 'key' is copied for each invocation; consider making it a reference [performance-unnecessary-value-param]\n std::string encode(const std::string key) {\n ^\n &\ncurl2.cpp:161:3: warning: use auto when initializing with a cast to avoid duplicating the type name [hicpp-use-auto]\n std::stringstream* ss = (std::stringstream*)ud;\n ^~~~~~~~~~~~~~~~~\n auto\ncurl2.cpp:161:38: warning: C-style casts are discouraged; use static_cast [google-readability-casting]\n std::stringstream* ss = (std::stringstream*)ud;\n ^~~~~~~~~~~~~~~~~~~~\n static_cast<std::stringstream*>( )\ncurl2.cpp:161:38: warning: do not use C-style cast to convert between unrelated types [cppcoreguidelines-pro-type-cstyle-cast]\ncurl2.cpp:180:16: warning: method 'http_request_impl' can be made static [readability-convert-member-functions-to-static]\n HttpResponse http_request_impl(const HttpRequestType r, RequestConfig& c) {\n ^\n static\ncurl2.cpp:183:32: warning: use nullptr [modernize-use-nullptr]\n struct curl_slist* chunk = NULL;\n ^~~~\n nullptr\n\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-05T18:35:47.163",
"Id": "235123",
"ParentId": "235087",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "235123",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-04T19:50:11.570",
"Id": "235087",
"Score": "2",
"Tags": [
"c++",
"c++11",
"c++14",
"c++17"
],
"Title": "Header only HTTP client library that is a wrapper around CURL"
}
|
235087
|
<p>So I'm starting out and doing some code challenges in between book and tutorial learning and was hoping to get some general feedback on code readability and use of comments.</p>
<p>I know it's sometimes hard to understand your own code after you wrote it so my question is - how easy is it to understand this one based on comments?</p>
<p>Do you think I'm missing anything crucial? Any general feedback welcome, thanks.</p>
<pre><code>/*
https://edabit.com/challenge/SEzYX5qtTR4WcZeR3
An isogram is a word that has no repeating letters, consecutive or
nonconsecutive.Create a function that takes a string and returns
either true or false depending on whether or not it's an "isogram".
Examples
isIsogram("Algorism") ➞ true
isIsogram("PasSword") ➞ false
// Not case sensitive.
isIsogram("Consecutive") ➞ false
*/
#include <iostream>
#include <ctype.h> // to use the toupper function which takes a letter
character and returns the upper case ASCII integer
using namespace std;
int main()
{
string input_string;
string output_string;
bool isogram_check = true; // by default the program assumes that everything is an isogram and then tries to find repeating letters to assert that it's not an isogram
cout << "Enter a string." << endl;
cin >> input_string;
for (int i = 0; i < input_string.length(); i++) // this loop takes the input string and converts it to all upper case letters.
{
output_string = output_string + char(toupper(input_string[i]));
}
// cout << output_string << endl;
// the above line is to test the toupper output
for (int i = 0; i < output_string.length(); i++) // the first loop decides WHAT to compare to something else, the second loops decides what that SOMETHING ELSE is.
{
for (int o = i+1; o < output_string.length(); o++) // this loop takes the character at position i and compares it to the character at i+1 then i+2, etc. by iterating o.
{ // in the above comment, i+1 = o since we iterated i once right at the beginning.
if (output_string[i] == output_string[o]) // when the loop finds two of the same character within the string it brakes out of both loops
{
isogram_check = false;
break;
}
}
if (isogram_check == false)
{
break;
}
}
if (isogram_check == false)
{
cout << input_string << " is not an isogram.\n";
}
else
{
cout << input_string << " is an isogram.\n";
}
}
</code></pre>
|
[] |
[
{
"body": "<p>You have two <code>while</code> loops that have a counter <code>i</code> that is incremented. You should really use a <code>for</code> loop.</p>\n\n<p>Your algorithm has quadratic complexity. Can you come up with something that is linear? To be fair, I can immediately only think of a linear solution that has a way higher proportionality constant, so it will be faster only for very long strings. Still.... worth exploring.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-05T00:05:24.563",
"Id": "459936",
"Score": "0",
"body": "Thanks, I changed both while loops to for loops and got rid of the global i."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-05T00:12:31.237",
"Id": "459937",
"Score": "0",
"body": "so `!isogram_check` works, just to clarify my understanding that is the same as `isogram_check != initialized value` ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-05T00:15:02.263",
"Id": "459939",
"Score": "0",
"body": "right, `something==false` is the same as `!something`"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-04T23:37:54.210",
"Id": "235095",
"ParentId": "235089",
"Score": "3"
}
},
{
"body": "<p><a href=\"https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice?r=SearchResults&s=1|1145.5940\">Avoid</a> <code>using namespace std</code>.</p>\n\n<p>Keep your lines shorter. Having to constantly scroll back and forth to read lines is unpleasant. Most of your comments should be on one (or more) lines right before the statement being commented on. Also, avoid obvious things in comments (like \"resets i to use in the next loop.\").</p>\n\n<p>Declare variables as close as possible to their first use.</p>\n\n<p>Since <code>isogram_check</code> is a <code>bool</code>, you can test it with <code>!isogram_check</code> instead of <code>isogram_check == false</code>.</p>\n\n<p>With a slight change in algorithm (searching characters before the ith one), your two <code>while</code> loops can be combined into one. Although there are other ways to do this that could be better (for some definition of \"better\"), your implementation is a quick first pass that works well for short strings (but less well as the strings get longer).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-05T00:03:22.090",
"Id": "459935",
"Score": "1",
"body": "Thanks. I am intentionally using the namespace declaration since I know I won't be using other namespaces. Should I avoid it even knowing the issue that can come up?\n\n\nWhat would I use to combine the 2 loops? My idea is that since I need to iterate both the WHAT I'm comparing and the what I'm comparing TO that I need 2 loops."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-05T11:37:23.050",
"Id": "459972",
"Score": "0",
"body": "@ChirilRussu you never know which namespace you need in the future, so it's best to avoid that. One of my employers' projects uses `namespace std` everywhere and causes a lot of name clashes problems that we have to do some workaround to avoid to much code change"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-05T15:35:38.230",
"Id": "459990",
"Score": "0",
"body": "@ChirilRussu - Quoting from the zen of python, \"Namespaces are one honking great idea — let's do more of those!\" The same concept very much applies to C++. The key intent of namespaces is to avoid collisions. It's best to avoid \"using namespace <namespace_name>\", ever."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-04T23:46:52.783",
"Id": "235096",
"ParentId": "235089",
"Score": "8"
}
},
{
"body": "<p>I am not an expert in <a href=\"/questions/tagged/c%2b%2b\" class=\"post-tag\" title=\"show questions tagged 'c++'\" rel=\"tag\">c++</a> but your code seems verbose. You can try to make it more explicit for a person who knows better <a href=\"/questions/tagged/c%2b%2b\" class=\"post-tag\" title=\"show questions tagged 'c++'\" rel=\"tag\">c++</a> better. Plus the algorithm is not that hard to digest so writing some built-in constructions will not overcome the ability to understand the whole flow.</p>\n\n<p>Unless your task is not bound by memory you can use <code>std::set</code> to do the counting of unique characters for you and squeeze out some lines of code.</p>\n\n<pre><code>#include <iostream>\n#include <algorithm>\n#include <unordered_set>\n#include <ctype.h>\n\nint main()\n{\n std::string input_string;\n std::cout << \"Enter a string.\" << std::endl;\n std::cin >> input_string;\n\n std::unordered_set<char> chars;\n\n std::cout << input_string << (std::all_of(\n input_string.begin(), \n input_string.end(),\n [&chars](const char c) {\n auto upper = toupper(static_cast<unsigned char>(c));\n // ^ ^ ^\n // avoid undefined behaviour\n return chars.insert(upper).second;\n }\n ) ?\n \" is an isogram.\\n\" :\n \" is not an isogram.\\n\");\n\n}\n</code></pre>\n\n<p>I see you're probably trying to practice for coding interviews or just exercising your problem-solving skills, either way, you should think about using the stl of the given language.</p>\n\n<p>What I mean is not using sorting functions when you are asked to do sorting challenge, but rather use some built-in algorithms as an intermediary step before achieving what your goal is. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-05T00:19:00.047",
"Id": "459940",
"Score": "0",
"body": "Thanks, I'm just learning that's why I don't know the best ways to do things. For example I don't know how `transform` works, never used `.begin` or `.end.` Don't know how `set` works, etc. Now that you wrote them for me I can just look it up and figure it out, but it's sort of I don't know what I don't know type of situation while I'm still learning."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-05T00:26:01.033",
"Id": "459942",
"Score": "0",
"body": "@ChirilRussu, well `set` is a data structure that only keeps unique elements, so it maintains uniqueness for you. So now you probably see that if `set.size()` is equal to `input_string.size()` this means that all chars from `input_string` got into the `set` => they are all unique"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-05T00:28:06.097",
"Id": "459943",
"Score": "0",
"body": "@ChirilRussu `.begin` and `.end` are methods that return `iterator` to a certain point of the caller - in this case the `set`. You can think of them as start and end indexes until you feel comfortable to dig down into https://en.wikipedia.org/wiki/Iterator_pattern"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-05T00:30:07.880",
"Id": "459944",
"Score": "0",
"body": "@ChirilRussu, `transform` is just a function that takes start and end iterator (you can think of index) and applies some function to each element that this iterator is traversing in this case its the `string`"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-05T00:09:59.523",
"Id": "235097",
"ParentId": "235089",
"Score": "6"
}
},
{
"body": "<p>Many good comments have been made already, eg:</p>\n\n<ul>\n<li>code in a function</li>\n<li>limit source code witdth to to 80-100 columns</li>\n<li>code is overly complex for the task, hard to digest it</li>\n</ul>\n\n<p>Try to use the <a href=\"https://en.cppreference.com/w/cpp/algorithm\" rel=\"nofollow noreferrer\">available algorithms</a> and <a href=\"https://en.cppreference.com/w/cpp/container\" rel=\"nofollow noreferrer\">data structures</a>. Those are reference links, but many good articles and <a href=\"https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list\">books have been written</a>. </p>\n\n<p>One good way to solve many problems related to \"frequency of occurrence\" is to produce a \"count of unique occurrence\" or \"frequency\". Arguably the canonical tool for this is <code>std:unordered_map</code>, which uses a <code>hashtable</code> internally. Often it is combined with <code>std::partial_sort_copy</code> to find the \"10 most frequent\" or similar. We don't need <code>sort_copy</code> here because we can return false on first repeat. There is an suggested code for the <code>is_isogram()</code> function using <code>std::unordered_map</code> with some static calls from <code>main()</code> below. </p>\n\n<p>But the problem here is even simpler, because we don't actually need to know how many repeats there are I have provide a second function <code>is_isogram_set()</code> which uses an <code>std::unordered_set</code>. I ran some quick benchmarks and the <code>std::unordered_set</code> is about 5-10% faster than the <code>std::unordered_map</code>. </p>\n\n<p>If we can assume \"ASCII only\" text, and ignore nonalpha completely, then all uppercase'd characters will be between 'A' - 'Z' and we could sensibly use something like a <code>std::array<bool></code> for which I have provided a third sample <code>is_isogram_array()</code>. This is signignificantly (~10-15x !) faster than the other 2 options. </p>\n\n<p>Any of these should be easily understood by anyone with C++ experience, rather than unpicking \"<a href=\"https://youtu.be/qH6sSOr-yk8\" rel=\"nofollow noreferrer\">several custom raw loops</a>\". Using the standard containers allows us to focus on clean efficient code, rather than \"loop correctness\". So we were easily able to find significant speed/feature trade-offs. </p>\n\n<p><strong>EDIT</strong>: Based on a suggestion from @LaurentLARIZZA I added an alternative version of the <code>std::array</code> variant which uses the STL algorithm <code>std::all_of</code>. I named it <code>is_isogram_array_algo()</code>. I doesn't fundamentally change anything, but it does allow us to avoid the ranged for loop and to make the code slightly more self documenting. ie we can name the lambda \"unseen\" and write \"all of unseen\", which arguably makes it slightly clearer what is going on. Code is slightly longer, but has identical performance. </p>\n\n<pre><code>#include <iostream>\n#include <string>\n#include <cctype>\n#include <unordered_map>\n#include <unordered_set>\n#include <array>\n\nbool is_isogram(const std::string& str) {\n auto freqs = std::unordered_map<char, int>{};\n for (auto&& c: str) {\n if (auto uc = static_cast<unsigned char>(c); std::isalpha(uc)) {\n int& count = freqs[std::toupper(static_cast<unsigned char>(uc))];\n if (count > 0) return false;\n count++;\n }\n }\n return true;\n}\n\nbool is_isogram_set(const std::string& str) {\n auto freqs = std::unordered_set<char>{};\n for (auto&& c: str) {\n if (auto uc = static_cast<unsigned char>(c); std::isalpha(uc)) {\n auto [iter, was_new] = freqs.insert(std::toupper(uc));\n if (!was_new) return false;\n }\n }\n return true;\n}\n\nbool is_isogram_array(const std::string& str) {\n auto freqs = std::array<bool, 26>{false};\n for (auto&& c: str) {\n if (auto uc = static_cast<unsigned char>(c); std::isalpha(uc)) {\n int idx = std::toupper(uc) - 'A';\n if (freqs[idx]) return false;\n freqs[idx] = true;\n }\n }\n return true;\n}\n\nbool is_isogram_array_algo(const std::string& str) {\n auto freqs = std::array<bool, 26>{false};\n\n auto unseen = [&freqs](char c) {\n if (auto uc = static_cast<unsigned char>(c); std::isalpha(uc)) {\n int idx = std::toupper(uc) - 'A';\n if (freqs[idx]) return false;\n freqs[idx] = true;\n }\n return true;\n };\n\n return std::all_of(str.begin(), str.end(), unseen);\n}\n\n\n\nint main() {\n\n std::cout << std::boolalpha\n << \"Algorism=\" << is_isogram(\"Algorism\") << '\\n'\n << \"PasSword=\" << is_isogram(\"PasSword\") << '\\n'\n << \"Consecutive=\" << is_isogram(\"Consecutive\") << '\\n';\n return 0;\n}\n\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-05T16:15:30.790",
"Id": "459998",
"Score": "0",
"body": "I think it would be better to use `auto c : str` here. For why I wouldn't use `auto&&` is [here](https://stackoverflow.com/questions/13130708/what-is-the-advantage-of-using-forwarding-references-in-range-based-for-loops/13130795#13130795), and copying chars is cheap."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-05T16:17:50.870",
"Id": "459999",
"Score": "1",
"body": "I don't disagree. In fact i had it that way and changed last minute before posting. Trying to make `for (auto&& e: ..)` a habit because \"it always works\": https://quuxplusone.github.io/blog/2018/12/15/autorefref-always-works/"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-05T16:26:59.653",
"Id": "460000",
"Score": "0",
"body": "Thanks for the link, interesting point as well!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-05T16:34:44.783",
"Id": "460001",
"Score": "0",
"body": "Just did a test for a simplified (to get rid of map and iostream boilerplate code) example on godbolt: https://godbolt.org/z/2R3YdU I copy pasted the ASM for auto and for auto&& and the diff is precisely `nil`. I am not saying it will always be, in fact this example is \"too simple\" as it gets SIMD vector optimised etc etc. But in general could we assume that auto&& will not gen \"worse\" code? I agree it looks \"fishy\" if you're not used to it though..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-05T16:42:03.760",
"Id": "460002",
"Score": "0",
"body": "Would an [`unordered_multiset`](http://cplusplus.com/reference/unordered_set/unordered_multiset/) also be a fitting data structure to represent the concept of a \"histogram\"? I don't know C++, but that's what I would use in a different language (https://codereview.stackexchange.com/a/233584/1581), even going so far as to implement my own (https://stackoverflow.com/a/57644639/2988)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-05T16:46:50.633",
"Id": "460004",
"Score": "0",
"body": "@JörgWMittag I would not reach for a multiset here, no. The use case is about frequency (at least in my mind), any freq > 1 must return false. A multiset will store all the characters, inclduding the repeats. So we feed it the complete works of shakespeare http://www.gutenberg.org/ebooks/100 . Then you will get a very large (!) multiset. Where an unordered_map (with toupper and assuming ASCII only) will give you at most 26 entries. We want to store unique(!) chars -> int counts. and unordered_map does exactly that."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-05T17:51:36.893",
"Id": "460018",
"Score": "0",
"body": "Ah, I see. So, C++'s multiset actually behaves less like a multiset but more like a *bag* (\"unordered vector\"). I missed that. Today I learned something new!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-06T10:18:20.620",
"Id": "460095",
"Score": "0",
"body": "Well, your algorithm is the same in all 3 cases, it is basically `std::all_of` with a stateful predicate that determines \"whether the current character has never been encountered before\". (noting this just because you suggest to use *the available algorithms*) You're making your predicate implementation vary."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-06T13:12:27.890",
"Id": "460121",
"Score": "0",
"body": "@LaurentLARIZZA Yep you could do that. We could debate what \"std::all_of\" adds here? The key part of the algorithm would go into the predicate lambda, ie tracking which letters have been seen. Why don't you provide an answer that does that, and we can compare?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-06T13:52:07.893",
"Id": "460123",
"Score": "0",
"body": "@OliverSchonrock: Sure. Here you go https://codereview.stackexchange.com/a/235167/35322"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-06T13:52:15.730",
"Id": "460124",
"Score": "0",
"body": "@LaurentLARIZZA I added such a version above. Is this what you had in mind?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-06T13:56:54.027",
"Id": "460126",
"Score": "0",
"body": "@OliverSchonrock : No. Have a look at my answer, Your `freqs` variables belong to the predicate. I made them full-fledged funciton objects instead of lambdas."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-06T14:00:04.660",
"Id": "460127",
"Score": "0",
"body": "@LaurentLARIZZA\nYeah I saw. Yours is good too. This entire question has all got hefty smell of over engineering to it now. The task is trivial. The OP made a meal of it. The highest rated answer is not great. But hey. I am kinda done with it. ;-)"
}
],
"meta_data": {
"CommentCount": "13",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-05T16:10:16.453",
"Id": "235116",
"ParentId": "235089",
"Score": "3"
}
},
{
"body": "<p>Building on <a href=\"https://codereview.stackexchange.com/a/235116/35322\">Oliver Schonrock's answer</a>, here is an equivalent version of the code leveraging the <code>std::all_of</code> algorithm. Note that I did not try to change the semantics of given in Oliver's answer, as all three structures could be made much shorter by always counting, and using bitwise operations.</p>\n\n<pre><code>#include <iostream>\n#include <string>\n#include <cctype>\n#include <unordered_map>\n#include <unordered_set>\n#include <array>\n\n\nstruct IsFirstOccurrence_UM {\n bool operator()(char c) {\n int& count = freqs[std::toupper(static_cast<unsigned char>(uc))];\n if (count > 0) {\n return false;\n } else {\n count++;\n return true;\n }\n }\nprivate:\n std::unordered_map<char, int> freqs;\n};\n\nstruct IsFirstOccurrence_Set {\n bool operator()(char c) {\n if (auto uc = static_cast<unsigned char>(c); std::isalpha(uc)) {\n auto [iter, was_new] = freqs.insert(std::toupper(uc));\n return was_new;\n } else {\n return true; // Note that non-alpha characters are always considered first-occurrence\n }\n }\nprivate:\n std::unordered_set<char> freqs;\n};\n\nstruct IsFirstOccurrence_Array {\n bool operator()(char c) {\n if (auto uc = static_cast<unsigned char>(c); std::isalpha(uc)) {\n int idx = std::toupper(uc) - 'A';\n if (freqs[idx]) {\n return false;\n } else {\n freqs[idx] = true;\n return true;\n }\n } else {\n return true; // Note that non-alpha characters are always considered first-occurrence\n }\n }\nprivate:\n std::array<bool, 26> freqs{false};\n};\n\ntemplate<typename IsFirstOccurrencePedicate>\nbool is_isogram(const std::string& str, IsFirstOccurrencePedicate is_first_occurrence) {\n return std::all_of(str.begin(), str.end(), std::move(is_first_occurrence));\n}\n\nint main() {\n\n std::cout << std::boolalpha\n << \"Algorism=\" << is_isogram(\"Algorism\", IsFirstOccurrence_UM()) << '\\n'\n << \"PasSword=\" << is_isogram(\"PasSword\", IsFirstOccurrence_UM()) << '\\n'\n << \"Consecutive=\" << is_isogram(\"Consecutive\", IsFirstOccurrence_UM()) << '\\n';\n return 0;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-06T13:56:37.863",
"Id": "460125",
"Score": "0",
"body": "Yeah, nice. Demonstrates something slightly different. I also added a version above using `std::all_of` using a lambda, so without the templated reuse. I viewed the 3 options as mutually exclusive alternatives, and you would keep only one. I think we are beginning to overthink this trivial problem ;-)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-06T14:01:51.357",
"Id": "460128",
"Score": "0",
"body": "Yes we are. That's why I avoided fleshing out the `IsFirstOccurrencePredicate` concept :)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-06T13:51:24.430",
"Id": "235167",
"ParentId": "235089",
"Score": "1"
}
},
{
"body": "<p>As an alternative to the \"efficiency\" focused options in my other answer, here is an option which is just very terse. Given we can't have words > 26 characters which are isograms, this might be just enough? </p>\n\n<pre><code>#include <algorithm>\n#include <unordered_set>\n#include <cctype>\n\nbool is_isogram(std::string s) {\n std::transform(s.begin(), s.end(), s.begin(), [](unsigned char c) { return std::toupper(c); });\n return std::unordered_set<char>(s.begin(), s.end()).size() == s.size();\n}\n\n</code></pre>\n\n<p>It's closer (!) to what one might write in a language like python. </p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def is_isogram(s):\n return len(s) == len(set(s.upper()))\n\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-06T15:10:35.433",
"Id": "235172",
"ParentId": "235089",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-04T20:48:55.870",
"Id": "235089",
"Score": "7",
"Tags": [
"c++"
],
"Title": "c++ Checking if a string is an isogram"
}
|
235089
|
<p>The function removes rows from a pandas df if that row doesn't have the value of <code>important_1</code> inside of <code>important_2</code>. For example if <code>important_1</code> is <code>"blue"</code> and <code>important_2</code> is <code>"M"</code> then that row would be removed, but if <code>important_2</code> were <code>"redbluegreen"</code> then the row would be kept.</p>
<p>On my ~125mb files this code runs really slow. Only about 3 iterations a second. In this example it runs faster maybe because it is a much smaller csv.
How can I speed this up?</p>
<pre><code>import pandas as pd
import numpy as np
from io import StringIO
df = """
valid,important_1,important_2,unrelated_1,unrelated_2
2015-07-10 01:47:00,blue,,blabla,foobar56
2015-07-10 01:51:00,blue,M,blabla,foobar32
2015-07-10 02:37:00,blue,M,blab004la,foobar
2015-07-10 02:51:00,blue,M,blabla,foobar343
2015-07-10 03:19:00,blue,blue green,blabla,foobar
2015-07-10 03:51:00,blue,,blabla1,foobar6543
2015-07-10 04:11:00,blue,green red,blabla,foobar
2015-07-10 04:51:00,blue,red,blabla,foobar2466
2015-07-10 05:51:00,blue,blue,blabla,foobar
2015-07-10 06:27:00,blue,,blabla4,foobar
2015-07-10 06:51:00,blue,,blab605la3,foobar6543
2015-07-10 07:27:00,blue,M,blabla,foobar
2015-07-10 07:51:00,blue,M,blab445la2,foobar2334
2015-07-10 08:51:00,blue,blue green red,blabla,foobar7666
2015-07-10 09:51:00,blue,blue green,blabla,foobar
"""
df = StringIO(df)
df = pd.read_csv(df)
def remove_rows_that_dont_have_important_1_in_important_2(df):
"""
Removes all rows of the dataframe that do not have important_1 inside of important_2.
Note: All rows have the same value for important_1.
Note: Every row can have a different value for important_2.
Note: There are unrelated columns in the df that cannot be dropped from the df. But rows still can.
"""
important_1 = df.at[0, 'important_1'] # get the icao fro the df from the first ob
important_2_column_index = df.columns.get_loc('important_2') # column order won't always be the same, so find the right column first
iter_index = len(df) # the start point of the loop
while iter_index > 0: # start from the end of the df and work forwards
print(iter_index) # DEBUG printing
iter_index -= 1 # every loop move forward one item. This is at the top of the loop because that way every loop we ensure to move down one (or up a row depending on how you look at it).
value_of_important_2_for_this_row = df.iat[iter_index, important_2_column_index] # the value of important_2 for the row we are currently on
# check for np.NaN first because it is cheaper then checking str in str
if value_of_important_2_for_this_row is np.NaN: # if the value of important_2 is np.NaN then there is now way important_1 can be in it
pass
# str in str check
elif important_1 not in value_of_important_2_for_this_row: # safe to assume the important_2 is off type str
pass
else: # safe to assume that important_1 is indeed in important_2
continue # skip deletion because important_1 is in important_2 Yay!
df.drop([iter_index], inplace=True) # delete the row
return df # reset the index before returning the df
df = remove_rows_that_dont_have_important_1_in_important_2(df=df)
print(df)
</code></pre>
<p><strong>OUTPUT</strong></p>
<pre><code> valid important_1 important_2 unrelated_1 unrelated_2
4 2015-07-10 03:19:00 blue blue green blabla foobar
8 2015-07-10 05:51:00 blue blue blabla foobar
13 2015-07-10 08:51:00 blue blue green red blabla foobar7666
14 2015-07-10 09:51:00 blue blue green blabla foobar
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-05T01:07:07.660",
"Id": "459946",
"Score": "0",
"body": "It's running a lot faster on this example then on my actual csv that is about 125mb and ~450k lines"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-05T08:18:57.980",
"Id": "459960",
"Score": "0",
"body": "why aren't you using pandas methods to handle this? Could you please try `def myf(df): return df[[a in b.split() for a,b in zip(df['important_1'],df['important_2'].fillna(''))]]` and `print(myf(df))` . Works nicely for me and is fast"
}
] |
[
{
"body": "<p>I don't really know the libraries that you're using, but maybe the overhead of dropping rows from the CSV one by one is significant? You could try batching the drop (it looks like that <code>drop</code> function takes a list of indices but you're only passing it one at a time) and see if that speeds things up:</p>\n\n<pre><code>from pandas import DataFrame\nfrom typing import List\n\ndef remove_rows_that_dont_have_important_1_in_important_2(df: DataFrame) -> DataFrame:\n \"\"\"\n Removes all rows of the dataframe that do not have important_1 inside of important_2.\n Note: All rows have the same value for important_1.\n Note: Every row can have a different value for important_2.\n Note: There are unrelated columns in the df that cannot be dropped from the df. But rows still can.\n \"\"\"\n important_1 = df.at[0, 'important_1'] # get the icao fro the df from the first ob\n important_2_col = df.columns.get_loc('important_2') # column order won't always be the same, so find the right column first\n\n indices_to_drop: List[int] = []\n\n for i in range(len(df), 0, -1):\n print(i) # DEBUG printing\n\n important_2 = df.iat[i, important_2_col]\n if important_2 == np.NaN or important_1 not in important_2:\n indices_to_drop.append(i)\n\n df.drop(indices_to_drop, inplace=True)\n return df\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-05T02:21:38.050",
"Id": "459947",
"Score": "0",
"body": "That produces some error for me, First IndexError which I was abel to fix and then a TypeError"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-05T02:27:30.327",
"Id": "459949",
"Score": "0",
"body": "Also I using using the pandas and numpy library."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-05T01:55:28.800",
"Id": "235100",
"ParentId": "235098",
"Score": "5"
}
},
{
"body": "<p>If you use the <code>.str</code> attribute of the column, you get most of the standard Python string functions. In particular, with Python strings you can ask if a string contains another string with the <code>__contains__()</code> method (i.e. the <code>in</code> operator):</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>>>> \"asdf\" in \"asdfqwerty\"\nTrue\n>>> \"asdfqwerty\".__contains__(\"asdf\") # equivalently\nTrue\n</code></pre>\n\n<p>Pandas exposes this as the <code>.contains()</code> method on the <code>.str</code> attribute, as discussed in the <a href=\"https://pandas.pydata.org/pandas-docs/stable/user_guide/text.html\" rel=\"nofollow noreferrer\">working with text data</a> section of the docs. Annoyingly, you cannot operate on two columns---but your code snippet specifically states:</p>\n\n<blockquote>\n <p>Note: All rows have the same value for important_1.</p>\n</blockquote>\n\n<p>So, you actually just need to operate on <code>important_2</code> and check if the single string in <code>important_1</code> is contained in each row, and that you <em>can</em> do with the string methods. This one-liner would do what you want:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>reduced_df = df[df[\"important_2\"].str.contains(df[\"important_1\"][0]) == True]\n</code></pre>\n\n<p>Most of the work is done via </p>\n\n<pre><code>df[\"important_2\"].str.contains(df[\"important_1\"][0])\n</code></pre>\n\n<p>which is checking if the strings in <code>important_2</code> have the string which is in the first row of <code>important_1</code>. Since your column has <code>NaN</code> in it¹, you will get <code>NaN</code> values on the comparison, so you have to specifically check if the value is equal to <code>True</code> (or otherwise cast to boolean) to get a boolean array you can index with. Then, using that boolean result you can index your dataframe to drop the irrelevant rows. So to fully explain the line in one sentence, it's \"select the rows of my dataframe where the column <code>important_2</code> contains the string in the first row of <code>important_1</code>\".</p>\n\n<hr>\n\n<p>¹ this is bad practice FWIW, as you're mixing datatypes--<code>NaN</code> is a floating point value and you have it in a column of strings. You <em>can</em> use empty strings for null-values <em>sometimes</em> with strings, but better practice altogether is to have another column which tells you whether or not a value is present; that way an empty string could still be a valid input.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-11T01:22:06.610",
"Id": "460865",
"Score": "0",
"body": "Thank you, this solution works"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-05T08:35:13.633",
"Id": "235105",
"ParentId": "235098",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "235105",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-05T00:52:37.277",
"Id": "235098",
"Score": "4",
"Tags": [
"python",
"performance",
"algorithm",
"pandas"
],
"Title": "Pandas - 3 iterations per second on simple conditional"
}
|
235098
|
<pre><code>fun readLines(path: String): Stream<String> =
try {
Files.lines(Paths.get(path)).use { it }
} catch (ex: Exception) {
ex.printStackTrace()
Stream.empty<String>()
}
</code></pre>
<p>I added <code>.use { it }</code> to tack on try-with-resources like behaviour for autoclosing the file handle (?) in case of exceptions.</p>
<ol>
<li>Is this required?</li>
<li>Are there better approaches?</li>
</ol>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-06T10:29:14.860",
"Id": "460098",
"Score": "1",
"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": "2020-01-06T17:07:51.730",
"Id": "460153",
"Score": "0",
"body": "Your code doesn't work. It always throws a `java.lang.IllegalStateException: stream has already been operated upon or closed`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-07T07:51:06.513",
"Id": "460230",
"Score": "1",
"body": "Maybe reformat the post to a stackoverflow post which asks how to return sequence that closes file at the end, or something like that?"
}
] |
[
{
"body": "<h2>Your situation</h2>\n<p>Use closes the resource at the end of the block (lambda).<br />\nThis means that the stream is closed before returning it.</p>\n<h2>The problem with reading lines</h2>\n<p>The file needs to be closed once you have read the needed lines.<br />\nThe stream could close the file once the stream last item is reached.<br />\nThe problem with this approach is that functions like <code>limit</code>, <code>take</code>, <code>splititerator</code> etc. are making it possible that the last item is never reached.<br />\nTherefor, you can do two things.\nThe first option is to let the caller close the file or sequence/stream/whatever you return.</p>\n<p>The second option is to close inside your function, but then you need to do all the reading inside the function, so before you return from the function.</p>\n<h2>Options</h2>\n<p>You can read everything immediately by storing everything in a list using <a href=\"https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.io/java.io.-file/read-lines.html\" rel=\"nofollow noreferrer\">readlines</a>.\n(This means you read the whole file into memory, which means you should not do this for huge, huge, huge files, you almost always can ignore this warning).</p>\n<pre><code>fun readLines(path: String): List<String> = try{\n Paths.get(path).toFile().readLines()\n} catch(ex: Exception) {\n ex.printStackTrace()\n emptyList<String>()\n}\n</code></pre>\n<p>The other approaches work by moving the code you would normally do outside the function inside the function.</p>\n<p>For example the <a href=\"https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.io/java.io.-file/for-each-line.html\" rel=\"nofollow noreferrer\">forEachLine</a>:</p>\n<pre><code>fun forEachLine(path: String, action: (String)->Unit){\n try{\n Paths.get(path).toFile().forEachLine(action)\n } catch(ex: Exception) {\n ex.printStackTrace()\n }\n}\n</code></pre>\n<p>With that function you could rewrite</p>\n<pre><code>val t = readLines("somePath")\n .filter{ it.startsWith("ok:") }\nt.forEach{ println(it) }\nt.close()\n</code></pre>\n<p>with</p>\n<pre><code>forEachLine("somePath"){\n if(it.startsWith("ok:")\n println(it)\n}\n</code></pre>\n<p>If you have functions that operates on a sequence of strings, or want more than a simple forEach, you can access the sequence itself by using <a href=\"https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.io/java.io.-reader/use-lines.html\" rel=\"nofollow noreferrer\">useLines</a>, but again move the reading inside the function:</p>\n<pre><code>fun useLines(path: String, action: (Sequence<String>)->Unit){\n try{\n Paths.get(path).toFile().useLines(action)\n } catch(ex: Exception) {\n ex.printStackTrace()\n }\n}\n</code></pre>\n<p>Can replace the former example with:</p>\n<pre><code>useLines("somePath"){ lines->\n lines.filter{ it.startsWith("ok") }\n .forEach{ println("it") }\n} \n</code></pre>\n<p>NOTE: this function is not for extracting or returning the sequence.<br />\nall the functions needs to be done in the lambda,until you come across a terminal operation, an operation that no longer returns a sequence.</p>\n<p>NOTE: sequence is the Kotlin-version of streams with <a href=\"https://www.reddit.com/r/Kotlin/comments/edboro/jake_wharton_on_kotlin_vs_java_debate/fbprkaa?utm_source=share&utm_medium=web2x\" rel=\"nofollow noreferrer\">lots of benefits</a>.</p>\n<h1>Is closing required</h1>\n<p>from the <a href=\"https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html\" rel=\"nofollow noreferrer\">javadoc</a></p>\n<blockquote>\n<p>"...Generally, only streams whose source is an IO channel (such as those returned by Files.lines(Path, Charset)) will require closing ..."</p>\n</blockquote>\n<p>so yes.</p>\n<h3>huge files</h3>\n<p>You should not use readlines on huge files.<br />\nWhat is a huge file?</p>\n<p>The bible has around 31,000 lines which can have 20 bytes reference, so 620,000 bytes or roughly 0,5 mb.<br />\nThe bible has 3,000,000 characters which is roughly 12 mb.<br />\nAcording to <a href=\"https://stackoverflow.com/a/15369204/3193776\">this post</a>, Android has a memory limit from around 15mb (in the worst case).<br />\nThis means that reading the bible in it entirely would theoretically be OK.<br />\nSo, untill you run into problems, this is nothing to worry about.</p>\n<h1>Edit:</h1>\n<p>I don't completely know how flatmap in Java excactly works at the moment.<br />\nThere was a bug that flatmap was not lazy.\nThis means that calling <code>fileNames.flatMap(::readLines)</code> with the readLines from your code was calculating the complete list before moving on: <a href=\"https://stackoverflow.com/a/29230939/3193776\">link</a>.<br />\nThis bug is fixed, so I don't know what it does at the moment.<br />\nIf it still works the same way, it always closes the file for you, but it does so because it always parses the complete file.</p>\n<p>In every case, if you are returning the Java-stream, calling close on the returning Stream is enough to close the file.\nWith sequences, this is not possible, as sequences are not closeable (They also don't know about AutoCloseable/Closeable).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-06T12:04:59.520",
"Id": "460112",
"Score": "0",
"body": "So now I'm returning `File(path).useLines { it }` as a `Sequence`. I understand from the doc that it _\"closes the reader once the processing is complete\"_. However, nowhere is it mentioned if that is still done if an exception occurs. Any insights/ resources (this is server-side code and not Android, btw)?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-06T16:56:38.753",
"Id": "460148",
"Score": "1",
"body": "@Slaiyer Changed to examples, you can only access the sequence from inside the lambda. (otherwise the result is the same as your initial post)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-07T00:11:25.920",
"Id": "460209",
"Score": "0",
"body": "I like the `Paths.get(path).toFile().useLines(action)` syntax, but I don't want to perform any action here. I just want to return a `Sequence<String>` of raw lines from each file from the surrounding `flatMap` that will be processed in a chain defined in the outer scope like `.flatMap(::readLines).filter(CharSequence::isNotEmpty)`, as opposed to bringing in the `filter` in as an `action` block. What can I do with `useLines` to achieve this, if not `.useLines { it }`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-07T00:52:28.720",
"Id": "460211",
"Score": "0",
"body": "The ideal would be a generic, non-blocking line reader that enables lazy evaluation of arbitrary operations without sacrificing flexibity (no mandatory `action` block) or housekeeping (autoclosing resources irrespective of exceptions), with fairly readable, concise syntax."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-07T07:34:02.840",
"Id": "460225",
"Score": "1",
"body": "If you are lazy reading, it is not possible for the function to know when you stop reading. Therefor, the function cannot close the stream for you. So, you need to call close in the stream once you stop reading. The other solution would be to implement the entire stream yourself. Note: if you would call flatmap on the stream (not on sequence), it would close the file for you. I bet, however, that you won't remember this all the time and so will run into problems problems later. It you need to place flatmap inside the function, but that would be strange, I think. So, your goal is impossible."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-06T10:40:54.437",
"Id": "235159",
"ParentId": "235099",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-05T01:54:08.647",
"Id": "235099",
"Score": "1",
"Tags": [
"error-handling",
"stream",
"kotlin"
],
"Title": "Ensuring file handle is closed in case of an exception"
}
|
235099
|
<p>I would like <code>Autofac</code> to instantiate components based on connection strings in the form of the URI:</p>
<pre><code>autofac://assembly-name/full-class-name?param1=arg1&param2=arg2
</code></pre>
<p>So the following test will work:</p>
<pre><code>[TestClass]
public class Locator_Should
{
[TestMethod]
public void Resolve()
{
var builder = new ContainerBuilder();
builder.RegisterType<DiskFolder>();
var container = builder.Build();
var folder = container.Resolve<IFolder>(
"autofac://LocatorTest/LocatorTest.DiskFolder?path=\\Windows");
Assert.IsTrue(folder.Any());
}
}
</code></pre>
<p>Where:</p>
<pre><code>public interface IFolder : IEnumerable<string>
{
}
public class DiskFolder : ReadOnlyCollection<string>, IFolder
{
public DiskFolder(string path)
: base(Directory.GetFiles(path))
{
}
}
</code></pre>
<p>The library code is:</p>
<pre><code>public static class AutofacLocator
{
public static T Resolve<T>(this ILifetimeScope scope, string uri) =>
scope.Resolve<T>(new Uri(uri));
public static object Resolve(this ILifetimeScope scope, string uri) =>
scope.Resolve(new Uri(uri));
public static T Resolve<T>(this ILifetimeScope scope, Uri uri) =>
(T)scope.Resolve(uri);
public static object Resolve(this ILifetimeScope scope, Uri uri)
{
if (uri.Scheme != "autofac")
throw new NotSupportedException("Schema not supported.");
var factory = (Delegate)scope.Resolve(GetFactory(uri));
return factory.DynamicInvoke(GetArguments(uri));
}
static Type GetFactory(Uri uri)
{
Func<Type[], Type> getType = Expression.GetFuncType;
var types = GetParameters(uri)
.Select(p => p.ParameterType)
.Append(GetReturnType(uri));
return getType(types.ToArray());
}
static object[] GetArguments(Uri uri)
{
var arguments = uri.Query
.TrimStart('?')
.Split('&')
.Select(p => p.Split('='))
.ToDictionary(nv => nv[0], nv => Uri.UnescapeDataString(nv[1]));
return GetParameters(uri)
.Select(p => Convert.ChangeType(arguments[p.Name], p.ParameterType))
.ToArray();
}
static ParameterInfo[] GetParameters(Uri uri) =>
GetReturnType(uri)
.GetConstructors()
.First()
.GetParameters();
static Type GetReturnType(Uri uri) =>
Type.GetType($"{uri.Segments[1]}, {uri.Host}");
}
</code></pre>
|
[] |
[
{
"body": "<p><a href=\"https://github.com/dmitrynogin/x-utils/tree/master/X.ComponentModel\" rel=\"nofollow noreferrer\">GitHub</a> and <a href=\"https://www.nuget.org/packages/X.ComponentModel/1.0.6\" rel=\"nofollow noreferrer\">NuGet</a></p>\n\n<p>The right way would be to do not depend on <code>Autofac</code> but support it through <code>AutofacSeriveProvider</code> as many other IoC containers. So now I have this for <code>ioc://</code>:</p>\n\n<pre><code>namespace System\n{\n public static class ServiceLocator\n {\n public static T GetService<T>(this IServiceProvider provider, string uri) =>\n provider.GetService<T>(new Uri(uri));\n\n public static object GetService(this IServiceProvider provider, string uri) =>\n provider.GetService(new Uri(uri));\n\n public static T GetService<T>(this IServiceProvider provider, Uri uri) =>\n (T)provider.GetService(uri);\n\n public static object GetService(this IServiceProvider provider, Uri uri)\n {\n if (uri.Scheme != \"ioc\")\n throw new NotSupportedException(\"Schema not supported.\");\n\n var factory = (Delegate)provider.GetService(GetFactory(uri));\n return factory.DynamicInvoke(GetArguments(uri));\n }\n\n static Type GetFactory(Uri uri)\n {\n Func<Type[], Type> getType = Expression.GetFuncType;\n var types = GetParameters(uri)\n .Select(p => p.ParameterType)\n .Append(GetReturnType(uri));\n\n return getType(types.ToArray());\n }\n\n static object[] GetArguments(Uri uri)\n {\n var arguments = uri.Query\n .TrimStart('?')\n .Split('&')\n .Select(p => p.Split('='))\n .ToDictionary(nv => nv[0], nv => Uri.UnescapeDataString(nv[1]));\n\n return GetParameters(uri)\n .Select(p => Convert.ChangeType(arguments[p.Name], p.ParameterType))\n .ToArray();\n }\n\n static ParameterInfo[] GetParameters(Uri uri) =>\n GetReturnType(uri)\n .GetConstructors()\n .First()\n .GetParameters();\n\n static Type GetReturnType(Uri uri) =>\n Type.GetType($\"{uri.Segments[1]}, {uri.Host}\");\n }\n}\n</code></pre>\n\n<p>And the following for <code>clr://</code>:</p>\n\n<pre><code>namespace System\n{\n public static class Activator<T>\n {\n public static T CreateInstance(string uri) =>\n CreateInstance(new Uri(uri));\n\n public static T CreateInstance(Uri uri) =>\n uri.Scheme != \"clr\"\n ? throw new NotSupportedException()\n : (T)Activator.CreateInstance(GetReturnType(uri), GetArguments(uri));\n\n static object[] GetArguments(Uri uri)\n {\n var arguments = uri.Query\n .TrimStart('?')\n .Split('&')\n .Select(p => p.Split('='))\n .ToDictionary(nv => nv[0], nv => Uri.UnescapeDataString(nv[1]));\n\n return GetParameters(uri)\n .Select(p => Convert.ChangeType(arguments[p.Name], p.ParameterType))\n .ToArray();\n }\n\n static ParameterInfo[] GetParameters(Uri uri) =>\n GetReturnType(uri)\n .GetConstructors()\n .First()\n .GetParameters();\n\n static Type GetReturnType(Uri uri) =>\n Type.GetType($\"{uri.Segments[1]}, {uri.Host}\");\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-05T18:34:49.843",
"Id": "235122",
"ParentId": "235102",
"Score": "1"
}
},
{
"body": "<p>It appears the goal here is to provide parameters to a resolve operation using a different format, something string-based. This appears to be primarily useful in a service location (manually executing <code>Resolve</code>) scenario rather than true DI, so I would caution you to be careful.</p>\n\n<p>Since this started as an Autofac solution, I'll post an answer based on Autofac.</p>\n\n<p>My first recommendation would be to <strong>implement <a href=\"https://github.com/autofac/Autofac/blob/1c9ce9926f/src/Autofac/Core/Parameter.cs\" rel=\"nofollow noreferrer\">a new <code>Parameter</code> type</a></strong> rather than entirely separate handling of strings. This would make the solution more interoperable with other parameter types and Autofac on the whole. You can see how other parameter types like <a href=\"https://github.com/autofac/Autofac/blob/1c9ce9926f/src/Autofac/Core/ResolvedParameter.cs\" rel=\"nofollow noreferrer\"><code>ResolvedParameter</code></a> and <a href=\"https://github.com/autofac/Autofac/blob/1c9ce9926f/src/Autofac/NamedParameter.cs\" rel=\"nofollow noreferrer\"><code>NamedParameter</code></a> are implemented to give you examples.</p>\n\n<p>My second recommendation would be to <strong><a href=\"https://github.com/autofac/Autofac.Configuration/blob/e1cf62b26e2177f975253496e8bf671ec9b09c2c/src/Autofac.Configuration/Util/TypeManipulation.cs#L54\" rel=\"nofollow noreferrer\">look at how Autofac.Configuration handles parsing the string values into objects</a></strong>. <code>Convert.ChangeType</code> doesn't work on a lot of things and having a more robust mechanism will be valuable.</p>\n\n<p>Finally... if possible, I might <strong>consider looking at the design that requires this and see if it can be changed.</strong> As I mentioned, this appears to be primarily useful in service location and it'd be better if you can switch your solution to use actual dependency injection. That'd mean the parameters need to be available either during registration time (e.g., read them from config and include their values when registering things); or during runtime, in which case you'd likely <a href=\"https://autofac.readthedocs.io/en/latest/resolve/relationships.html#parameterized-instantiation-func-x-y-b\" rel=\"nofollow noreferrer\">resolve a <code>Func<Xy, Y, B></code> or something similar</a> in your consuming class and not use a lifetime scope. In either case, the utility of this mechanism once you switch to DI is much more limited. It could be that just using Autofac.Configuration will suffice.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-06T18:26:03.837",
"Id": "235179",
"ParentId": "235102",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "235179",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-05T06:02:51.690",
"Id": "235102",
"Score": "1",
"Tags": [
"c#",
"autofac"
],
"Title": "Autofac support for connection strings"
}
|
235102
|
<p>I am a Java + Angular developer. My new job is as a Senior Python developer ... but I've never written a Python program in my life. In order to teach myself the language, I've started writing some simple projects. </p>
<p>This is a console-based Hangman game in Python 3.7. The game picks a 'secret word' from a list, and then enters a game loop prompting the user to guess letters. After 6 incorrect guesses, the game is over and the user loses. Otherwise if the user guesses all the letters, the user wins. After the game finishes, the user is prompted to start a new game, which reruns the method with a new secret word.</p>
<p>The word list and the hangman drawing I have omitted because I cribbed them from <a href="https://gist.github.com/chrishorton/8510732aa9a80a03c829b09f12e20d9c" rel="noreferrer">this gist on GitHub</a> as a direct copy-paste (renaming the hangman array to <code>HANGMAN_STAGES</code> and the word list to <code>WORDS</code>). I can include it in the post if need be, but it seems like an extra 60 lines which really aren't needed.</p>
<pre class="lang-py prettyprint-override"><code>import random
import sys
from typing import Tuple
# Omitted declarations: https://gist.github.com/chrishorton/8510732aa9a80a03c829b09f12e20d9c
# HANGMAN_STAGES = [...]
# WORDS = ...
def run_game() -> None:
"""The main game loop. Will prompt the user if they would like to start a new game at the end."""
print("WELCOME TO HANGMAN.")
secret_word = pick_secret_word()
guessed_letters = []
incorrect_guesses = 0
won = False
round = 1
while won == False and incorrect_guesses < 6:
print('\n\nROUND ' + str(round))
incorrect_guesses, won = process_turn(incorrect_guesses, secret_word, guessed_letters)
round += 1
print("\n\n")
if won == False:
print("GAME OVER! You lost.")
draw_hangman(6)
else:
print("Congratulations! You won!", end=" ")
print("The secret word was: " + secret_word)
if play_again():
run_game()
def pick_secret_word() -> str:
"""
Chooses a new secret word from the list of available secret words. The word is chosen psuedo-randomly.
:return: the new secret word
"""
index = random.randint(0, len(WORDS))
return WORDS[index].upper()
def process_turn(incorrect_guess_count: int, secret_word: str, guessed_letters: list) -> Tuple[int, bool]:
"""
Processes a user's turn. First draws the current state of the game: current hangman, partially-guessed word, and
list of previously guessed letters. Then prompts the user for their next guess, evaluates that guess to see if it
was correct, and then updates the game state.
:param incorrect_guess_count: the number of previous incorrect guesses
:param secret_word: the secret word
:param guessed_letters: the list of previously guessed letters
:return: (updated number of inccorect guesses, True/False indication of whether the user has won)
"""
draw_hangman(incorrect_guess_count)
draw_secret_word(secret_word, guessed_letters)
print_guessed_letters(guessed_letters)
next_letter = prompt_for_guess(guessed_letters)
return apply_guess(next_letter, secret_word, incorrect_guess_count, guessed_letters)
def print_guessed_letters(guessed_letters: list) -> None:
"""
Sorts the list of previously-guessed letters and prints it to screen.
:param guessed_letters: the list of previously guessed letters
:return: Nothing
"""
guessed_letters.sort()
print("Guesses: " + str(guessed_letters))
def apply_guess(next_letter: str, secret_word: str, incorrect_guess_count: int, guessed_letters: list) -> Tuple[int, bool]:
"""
Checks the validity of the user's guess. If the guess was incorrect, increments the number of incorrect guesses by
1. If the user has guessed all of the letters in the secret word, return an indication that the user has won the
game.
:param next_letter: the user's guess
:param secret_word: the secret word
:param incorrect_guess_count: the number of previously incorrect guesses
:param guessed_letters: the list of previously guessed letters
:return: (the updated number of incorrected guesses, True/False indicating if the user has won the game)
"""
guessed_letters.append(next_letter)
correct, letters_remaining = check_guess_against_secret(next_letter, secret_word, guessed_letters)
if correct == False:
incorrect_guess_count += 1
if letters_remaining == 0:
return incorrect_guess_count, True
return incorrect_guess_count, False
def check_guess_against_secret(next_letter: str, secret_word: str, guessed_letters: list) -> Tuple[bool, int]:
"""
Determines if the user has guessed correctly. Also evaluates the secret word to determine if there are more letters
left for the user to guess.
:param next_letter: the user's guessed letter
:param secret_word: the secret word
:param guessed_letters: the list of previously guessed letters
:return: (True/False indicating if the guess was correct, 0 if no letters left and positive integer otherwise)
"""
correct = next_letter in secret_word
letters_remaining = 0
for letter in secret_word:
# Known issue: if a letter is present in the secret multiple times, and is not guessed,
# letters_remaining incremented by more than one.
if letter not in guessed_letters:
letters_remaining += 1
return correct, letters_remaining
def prompt_for_guess(guessed_letters: list) -> str:
"""
Prompts the user for their next guess. Rejects guesses that are more than a single letter, and guesses which were
already made previously. Returns the (validated) guess.
:param guessed_letters: the list of previously guessed letters
:return: the user's next guess
"""
guess = input("Your guess? ").strip().upper()
if len(guess) > 1:
print("Sorry, you can only guess one letter at a time.")
return prompt_for_guess(guessed_letters)
elif guess in guessed_letters:
print("Sorry, you already guessed that letter.")
return prompt_for_guess(guessed_letters)
return guess
def draw_hangman(number_of_incorrect_guesses: int) -> None:
"""
Draws the appropriate hangman stage, given the number of incorrect guesses. 0 or fewer will draw the empty scaffold.
6 or more will draw the fully hanged man.
:param number_of_incorrect_guesses: the number of incorrect guesses the player has made in the current game
:return: Nothing
"""
if (number_of_guesses < 0):
number_of_guesses = 0
if (number_of_guesses > 6):
number_of_guesses = 6
print(HANGMAN_STAGES[number_of_guesses])
def draw_secret_word(secret_word: str, guessed_letters: list) -> None:
"""
Prints the secret word, with underscores representing unknown letters and with any correctly-guessed leters printed
in the appropriate location within the word.
:param secret_word: The secret word
:param guessed_letters: All previous guesses
:return: Nothing
"""
for letter in secret_word:
to_print = letter if letter in guessed_letters else '_'
print(to_print, end=' ')
print("\n")
def play_again() -> bool:
"""
Prompts the user if they would like to play again. If the user enters something other than Y/y/N/n, it will continue
prompting until the use enters a valid value. If the user indicates Y or y, this method returns True; N or n will
return False
:return: True if the user would like to start a new game; False otherwise
"""
choice = ''
while choice != "Y" and choice != "N":
choice = input("Play again? (Y/N)").strip().upper()
return choice == "Y"
run_game()
</code></pre>
<p>Things I know are an issue:</p>
<ul>
<li>No unit tests. I'm still trying to figure out how to test <code>input()</code> and <code>print()</code> statements</li>
<li>I attempted pydoc docstring comments on all of the methods, but couldn't figure out how to properly document a returned tuple. </li>
<li>I'm a bit inconsistent in my string quotation mark usage because of my dual background with Java (double quotes) and Angular/Typescript (single quotes)</li>
<li>The <code>check_guess_against_secret</code> method doesn't accurately count how many unique letters remain; duplicate unguessed letters in the secret are counted twice. But since we only evaluate whether that value is 0, it could be swapped over to a boolean flag on refactor</li>
</ul>
<p>In addition to a general review, I would very much appreciate it if folks could point out places where I'm doing things in a more Java (or Typescript!) way rather than a Python way.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-06T13:12:03.447",
"Id": "460120",
"Score": "0",
"body": "Using `upper` or `lower` for case insensitive string comparisons is as bad a practice in Python as it is in Java, although admittedly Python makes it unnecessarily hard to do it correctly. You want to use `str.casefold()`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-06T16:49:30.837",
"Id": "460145",
"Score": "0",
"body": "To help with formatting issues like consistency in single or double quotes, I like to use [black](https://github.com/psf/black) (other similar tools exist in Python as well). Combined with, e.g., [precommit](https://github.com/pre-commit/pre-commit), this will handle a lot of little formatting things automatically whenever you commit."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-06T19:53:31.643",
"Id": "460173",
"Score": "0",
"body": "@Voo thanks for the suggestion, I will look into it. I was intending to look into an equivalent to Java's `equalsIgnoreCase()` and this sounds like a step in the right direction"
}
] |
[
{
"body": "<h1>Good points</h1>\n\n<ul>\n<li>Your code follows a lot of the suggested styles when using Python.</li>\n<li>Typed Python. This is fairly new, but I've found it to be very helpful. Given that it supports gradual typing it also allows my dodgy metaprogramming to work fine too.</li>\n<li>Docstrings, these seem good. You seem to have elected to use a Sphinx format. If you've not chosen a documentation generator then Sphinx looks like a good fit for you.</li>\n<li>You seem to know about single and multi-line docstring styles.</li>\n</ul>\n\n<h1>Code Review</h1>\n\n<ul>\n<li><p>When comparing to singletons you should use <code>is</code>. Because the equality operator isn't guaranteed to perform the check you want it to.</p>\n\n<pre><code>>>> False == 0\nTrue\n</code></pre></li>\n<li><p>It's more Pythonic to perform truthy and falsy checks.</p>\n\n<pre><code># if foo == True:\nif foo:\n ...\n</code></pre></li>\n<li><p>I'm unsure if you're a Java or JavaScript developer, but in either case you should know about the limitations of recursion. Recursion creates a stack frame for each and every call. If you call the function in itself then when you make the second frame, the first still exists. Once the second exits then the first resumes.</p>\n\n<p>This means that <code>run_game</code> can only run a finite amount of times. Implementing a main loop with recursion is pretty insensible.</p></li>\n<li><code>run_game</code> should be split into two functions, one that is in charge of the main loop and one for a hangman's main loop.</li>\n<li><p>I would prefer a class to encapsulate state. I don't know much about Java but I've heard that it loves OOP, maybe wholly dedicated to OOP would better describe the relationship. But Python is different. If something can be better described as a class use a class. If it's better as a function use a function.</p>\n\n<p>Than again I read online that Python's butchered OOP and it's impossible to follow OOP in Python. Which is a pedantic misinterpretation at best, so maybe you're used to functional Java?</p></li>\n<li><p>Your choice of random function, <code>random.randint</code>, is susceptible to cause the following indexing to <code>IndexError</code>. You should use <code>random.randrange</code> which doesn't include the end value.</p></li>\n<li>It's better if you use <code>random.choice</code> rather than <code>random.randint</code> or <code>random.randrange</code>.</li>\n<li>It doesn't matter if you use <code>'</code> or <code>\"</code> but stick to one. Using the other should only be used when the string contains your preferred delimiter, solely as a form of syntactic sugar.</li>\n<li>You can use <code>sorted</code> to sort <code>guessed_letters</code>.</li>\n<li>I would prefer to see a list without it wrapped in <code>[]</code>. Just use <code>str.join</code>.</li>\n<li>You can simplify your buggy <code>check_guess_against_secret</code> check by using sets. Given that you always display a sorted guessed list, there's not much point in having the <code>guessed_letters</code> as a list.</li>\n<li>It's unPythonoic to use brackets around if statements. Unless you need them.</li>\n<li>Don't fail silently in <code>draw_hangman</code> if the input is not between 0 and 6 then you should fix your broken code, not monkey patch the problem and pray to god it never reappears.</li>\n<li>Calling <code>print</code> by default flushes the stream, and so is fairly expensive. The simple solution to this is <code>print(..., flush=False)</code>. However, why not just build a string and print once? You can use a comprehension of sorts to make the code look nice too.</li>\n<li>Rather than a do-while loop I would prefer a <code>while True</code> loop in <code>play_again</code>. You can just return to exit the function cleanly.</li>\n<li>You should use a <code>if __name__ == '__main__':</code> guard to protect your code from accidentally running main.</li>\n</ul>\n\n<h1>Additional comments</h1>\n\n<p>Your naming convention seems poor to me.</p>\n\n<ul>\n<li>You use both <code>draw</code> and <code>print</code> to mean the same thing. They're different words with different meanings.</li>\n<li>You have <code>play_again</code> and <code>prompt_for_guess</code>. Both of the functions prompt for user input, but <code>play_agin</code> doesn't tell us that.</li>\n<li>You have a function <code>play_again</code> that doesn't sound like a function. That sounds like it should just be a plain old Boolean variable.</li>\n<li><p>Your names to me seem needlessly long, or cryptic. What are the benefits to:</p>\n\n<ul>\n<li><code>secret_word</code> over <code>word</code> or <code>secret</code>,</li>\n<li><code>guessed_letters</code> over <code>guesses</code>, or</li>\n<li><code>run_game</code> over <code>main</code>.</li>\n</ul></li>\n<li><p>Furthermore I can't think of a short name for <code>_check_guess_against_secret</code> because it's doing <em>two</em> things. This breaks SRP.</p></li>\n</ul>\n\n<p>Overall I think your code looks ok at a glance. You've got documentation, static typing and you've linted your code to be PEP 8 compliant. But I don't think your code is amazing when you actually look deeper into it.</p>\n\n<pre><code>import random\nimport sys\nfrom typing import Tuple\n\n# Omitted declarations: https://gist.github.com/chrishorton/8510732aa9a80a03c829b09f12e20d9c\n# HANGMAN_STAGES = [...]\n# WORDS = ...\n\n\nclass Hangman:\n _secret_word: str\n _guessed_letters: set\n _incorrect_guesses: int\n _round: int\n _won: bool\n\n def __init__(self, secret_word: str) -> None:\n self._secret_word = secret_word\n self._guessed_letters = set()\n self._incorrect_guesses = 0\n self._round = 1\n self._won = False\n\n def _turn(self) -> None:\n \"\"\"\n Processes a user's turn. First draws the current state of the game: current hangman, partially-guessed word, and\n list of previously guessed letters. Then prompts the user for their next guess, evaluates that guess to see if it\n was correct, and then updates the game state.\n\n :param guessed_letters: the list of previously guessed letters\n \"\"\"\n draw_hangman(incorrect_guess_count)\n self._draw_secret_word(secret_word, guessed_letters)\n self._print_guessed_letters()\n next_letter = self._prompt_for_guess()\n return self._apply_guess(next_letter)\n\n def _print_guessed_letters(self) -> None:\n \"\"\"Print the guessed letters to the screen.\"\"\"\n print('Guesses: ' + ', '.join(sorted(self.guessed_letters)))\n\n def _apply_guess(self, next_letter: str) -> None:\n \"\"\"\n Checks the validity of the user's guess. If the guess was incorrect, increments the number of incorrect guesses by\n 1. If the user has guessed all of the letters in the secret word, return an indication that the user has won the\n game.\n\n :param next_letter: the user's guess\n \"\"\"\n self._guessed_letters.add(next_letter)\n correct, letters_remaining = self._check_guess_against_secret(next_letter, secret_word, guessed_letters)\n\n if not correct:\n self._incorrect_guess_count += 1\n\n if letters_remaining == 0:\n self._won = True\n\n def _check_guess_against_secret(self, next_letter: str) -> Tuple[bool, int]:\n \"\"\"\n Determines if the user has guessed correctly. Also evaluates the secret word to determine if there are more letters\n left for the user to guess.\n\n :param next_letter: the user's guessed letter\n :return: (True/False indicating if the guess was correct, 0 if no letters left and positive integer otherwise)\n \"\"\"\n return (\n next_letter in secret_word,\n len(set(self._secret_word) - self._guessed_letters)\n )\n\n def _prompt_for_guess(self) -> str:\n \"\"\"\n Prompts the user for their next guess. Rejects guesses that are more than a single letter, and guesses which were\n already made previously. Returns the (validated) guess.\n\n :return: the user's next guess\n \"\"\"\n while True:\n guess = input('Your guess? ').strip().upper()\n if len(guess) > 1:\n print('Sorry, you can only guess one letter at a time.')\n continue\n elif guess in guessed_letters:\n print('Sorry, you already guessed that letter.')\n continue\n return guess\n\n def _draw_secret_word(self) -> None:\n \"\"\"\n Prints the secret word, with underscores representing unknown letters and with any correctly-guessed leters printed\n in the appropriate location within the word.\n\n :param secret_word: The secret word\n :param guessed_letters: All previous guesses\n :return: Nothing\n \"\"\"\n print(\n ' '.join(\n letter if letter in self._guessed_letters else '_'\n for letter is self._secret_word\n )\n + '\\n'\n )\n\n def run(self) -> None:\n while not self._won and self._incorrect_guesses < 6:\n print('\\n\\nROUND ' + str(round))\n self._turn()\n self._round += 1\n\n print('\\n\\n')\n\n if self._won:\n print('Congratulations! You won!', end=' ')\n else:\n print('GAME OVER! You lost.')\n draw_hangman(6)\n\n\ndef main() -> None:\n \"\"\"The main game loop. Will prompt the user if they would like to start a new game at the end.\"\"\"\n print('WELCOME TO HANGMAN.')\n while True:\n Hangman(pick_secret_word()).run()\n if not play_again():\n return\n\n\ndef pick_secret_word() -> str:\n \"\"\"\n Chooses a new secret word from the list of available secret words. The word is chosen psuedo-randomly.\n :return: the new secret word\n \"\"\"\n return random.choice(WORDS).upper()\n\n\ndef draw_hangman(number_of_incorrect_guesses: int) -> None:\n \"\"\"\n Draws the appropriate hangman stage, given the number of incorrect guesses. 0 or fewer will draw the empty scaffold.\n 6 or more will draw the fully hanged man.\n\n :param number_of_incorrect_guesses: the number of incorrect guesses the player has made in the current game\n :return: Nothing\n \"\"\"\n if (number_of_guesses < 0\n or 6 < number_of_guesses\n ):\n raise ValueError('Hangman can only support upto 6 incorrect guesses.')\n print(HANGMAN_STAGES[number_of_guesses])\n\n\ndef play_again() -> bool:\n \"\"\"\n Prompts the user if they would like to play again. If the user enters something other than Y/y/N/n, it will continue\n prompting until the use enters a valid value. If the user indicates Y or y, this method returns True; N or n will\n return False\n\n :return: True if the user would like to start a new game; False otherwise\n \"\"\"\n while True:\n choice = input('Play again? (Y/N)').strip().upper()\n if choice in 'YN':\n return choice\n\n\nif __name__ == '__main__':\n main()\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-06T03:59:43.707",
"Id": "460060",
"Score": "1",
"body": "Can you link me to something that elaborates on why one should prefer `random.choice` over `randint` and `randrange`? I've tried googling but I'm not getting anything definitive. When I Googled how to get a random integer when writing the original, both posts I looked at (one on StackOverflow, the other elsewhere) recommended `randint`, which is why I used it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-06T04:11:48.360",
"Id": "460064",
"Score": "0",
"body": "With regards to using classes and sets ... I'm actually using a book to teach myself the Python concepts and haven't gotten to that part yet. I'll be sure to keep reading and do a refactor with your suggestions in mind. :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-06T06:28:58.390",
"Id": "460074",
"Score": "5",
"body": "@RoddyoftheFrozenPeas In terms of why `random.choice()` over alternatives: it's mainly because of simplicity. Using `rand.randint()` and then choosing an index is two steps, and could lead to an IndexError depending on the circumstances/synchronicity. `random.choice()` is one step, is very straightforward (chooses one element from the list), and has no chance of IndexError unless the list is empty (again, only one step). \"Take a random element from this list\" is a cleaner and simpler expression than \"Find a random index less than the size of the list, and take the element at that index\"."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-06T10:48:41.080",
"Id": "460100",
"Score": "0",
"body": "@RoddyoftheFrozenPeas: It is also *very* easy to introduce bias when rolling your own sampling functions; I would generally trust the standard library implementations more than my own. (Although of course, standard library implementations of PRNGs and sampling have been known to be wrong, and sometimes quite spectactularly so.)"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-05T10:04:52.850",
"Id": "235106",
"ParentId": "235103",
"Score": "22"
}
},
{
"body": "<p>Handling <code>input</code> can be done with <code>try</code> to handle <code>exceptions</code>. For instance:</p>\n\n<pre><code>try:\n user_in = int(input('Enter number: ')\n ...\nexcept ValueError:\n print('Integers only!')\n</code></pre>\n\n<p>Using quotations are your choice really but it is better to be consistent. If you use <code>'</code> or <code>\"</code> throughout your code make it one or the other. The benefits of using something like triple quote allow for simple data placement and calculations. In example:</p>\n\n<pre><code>print('''\ndata_1 > {}\ndata_2 > {}\ndata_3 > {}\n'''.format(data_1, sum(data_1), len(data_1))\n</code></pre>\n\n<p>In regards to the secret word and what is left. Python is good for comprehension although it can be heavy on process time with more complex functions. </p>\n\n<p>I saw a similar post not too long ago and it used classes to keep closely related functions together, which is what classes ideally are used for. I don't see the point in using them for a simple game, which would be something along the lines of:</p>\n\n<pre><code>import random\n\nwords = ['cheese', 'biscuits', 'hammer', 'evidence'] \nword_choice = [i.lower() for i in random.choice(words)] # List comprehension\nlives = 3\ncor_guess = []\nwhile True:\n print('Letters found: {}\\nWord length: {}'.format(cor_guess, len(word_choice)))\n if lives == 0:\n print('Your dead homie!\\nThe word was: ', word_choice)\n break\n guess = str(input('Guess a letter: '))\n if guess in word_choice:\n print(guess, 'is in the word!\\n')\n cor_guess.append(guess)\n else:\n print('Your dying slowly!\\n')\n lives -= 1\n ...\n ...\n</code></pre>\n\n<p>Using list comprehension I have selected a object from a variable and converted it all to lowercase for simplicity if I need to open a file with capital letters in etc and then got every object of that object. This populates the list with one word separated in to separate letters. The data can then be compared to the user input. This way the data to begin with is very flexible and can be manipulated easily and it is much easier to follow the code. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-06T04:10:12.670",
"Id": "460063",
"Score": "0",
"body": "In your try-catch example, the exception is raised if the input is not an integer. However all of my inputs are strings, so I don't really understand how I could go about using try-catch in this fashion unless I start raising the exceptions myself. Does Python really recommend using exception handling for control flow in this way? I've always understood this to be an anti-pattern and bad practice."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-06T14:56:07.820",
"Id": "460132",
"Score": "1",
"body": "https://docs.python.org/3/tutorial/errors.html Here is some documentation on try and except clauses. In the code above I have basically forced the user to input integers only and stay in the loop while checking that the conditions are met. Generally try/exceptions are used for specific conditional errors. It just saves time from creating a conditional `type` function. For instance not matter what you enter into `str(input(''))` it will be treated as a string. You then have to check if the input `.isdigit()` or convert it, handling it accordingly. Read some of the documentation its very helpful"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-05T14:15:31.370",
"Id": "235113",
"ParentId": "235103",
"Score": "6"
}
},
{
"body": "<p>When presenting code, you should take the width of the code into consideration. The comment \"Processes a user's turn. First draws the current state of the game: current hangman, partially-guessed word, and\" is 116 characters long. The line of code \"def process_turn(incorrect_guess_count: int, secret_word: str, guessed_letters: list) -> Tuple[int, bool]:\" is 106 characters long. You can break function declarations into several lines:</p>\n\n<pre><code>def process_turn(\n incorrect_guess_count: int, \n secret_word: str, \n guessed_letters: list\n ) -> Tuple[int, bool]:\n</code></pre>\n\n<p>While Python allows you to have a function call another function that is defined later, it's easier to read if functions call functions that are previously defined.</p>\n\n<p>You should use <code>==</code> to compare Boolean variables to constants. <code>A == True</code> just returns <code>A</code> and <code>A == False</code> returns <code>not A</code>.</p>\n\n<p>Your <code>pick_secret_word()</code> function can be replaced by the single line <code>'secret_word = random.choice(WORDS)</code>.</p>\n\n<p>Maybe it's personal taste, but I find the use of functions excessive. You spend a lot of your time passing parameters back and forth, and documenting what each parameter is.</p>\n\n<p>If you use a for-loop rather than a while-loop for your rounds, you don't have to increment <code>round</code>. Also, <code>round</code> is a builtin function in Python, so you should use another name, such as <code>turn</code>. I'm using Spyder, which color codes builtins and keywords. If you're not using an IDE that does so, you might consider doing so.</p>\n\n<p>6 is a \"magic number\". You can put it in as a parameter with a default value instead.</p>\n\n<p>You should give the user more feedback about what's wrong if they don't give a valid response to whether they want to play again, or you could just take anything other than <code>Y</code> as a \"no\".</p>\n\n<p><code>WORDS</code> and <code>HANGMAN_STAGES</code> aren't defined anywhere.</p>\n\n<pre><code>def run_game(WORDS, HANGMAN_STAGES, max_turns = 26, max_guesses = 6) -> None:\n while True:\n print(\"WELCOME TO HANGMAN.\")\n secret_word = random.choice(WORDS)\n guessed_letters = []\n incorrect_guesses = 0\n max_turns = 26\n max_guesses = 6\n letters_remaining = len(secret_word)\n for turn in max_turns:\n print('\\n\\nROUND ' + str(turn)) \n print(HANGMAN_STAGES[number_of_guesses])\n print(''.join([letter for letter in secret_word\n if letter in guessed_letters \n else '_'])+'/n')\n guessed_letters.sort()\n print(\"Guesses: \" + str(guessed_letters))\n while True:\n guess = input(\"Your guess? \").strip().upper()\n if len(guess) > 1:\n print(\"Sorry, you can only guess one letter at a time.\")\n continue\n elif guess in guessed_letters:\n print(\"Sorry, you already guessed that letter.\")\n continue\n break\n guessed_letters.append(guess)\n if guess in secret_word:\n if letters_remaining == 0:\n print(\"\\n\\n\")\n print(\"Congratulations! You won!\", end=\" \")\n break\n else:\n letter_remaining -= \n sum([letter == guess for letter in secret_word])\n else:\n incorrect_guess +=1\n if incorrect_guesses == max_guesses:\n print(\"\\n\\n\")\n print(\"GAME OVER! You lost.\")\n print(HANGMAN_STAGES[6]\n break\n print(\"The secret word was: \" + secret_word)\n choice = input(\"Press Y to play again\").strip().upper()\n if choice != 'Y':\n break\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-06T03:41:42.777",
"Id": "460057",
"Score": "0",
"body": "I was using 120 characters as my line-length limit, since that's what I'm used to and what my IDE has set as a default. My understanding of PEP-8 is that the 80-character limit is a recommendation not a requirement."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-06T04:13:26.160",
"Id": "460066",
"Score": "0",
"body": "re: WORDS and HANGMAN_STAGES -- I mentioned in the original question that they're cribbed from a public Gist on GitHub and I omitted them intentionally because I had made no changes but renaming the variables, and didn't feel it was useful copy-pasting 60 lines of someone else's code (of indeterminate licensing). There's a link to the Gist in the post."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-06T02:18:19.433",
"Id": "235145",
"ParentId": "235103",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "235106",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-05T06:08:23.050",
"Id": "235103",
"Score": "22",
"Tags": [
"python"
],
"Title": "Console-based hangman in Python"
}
|
235103
|
<p>Wondering if I can get a review of the following script.</p>
<p>I used to be a Python dev back when 2.7 was the norm and haven't really touched Python3, so interested to see where some new features might tidy things up. And obviously any improvements / direction on general style.</p>
<p>The script consumes an API that provides data that I take and format into an Excel spreadsheet. Eventually, it should live in a Lambda on AWS to be run periodically.</p>
<pre><code>import os
import json
import requests
import xlsxwriter
from datetime import datetime
from collections import OrderedDict
from xlsxwriter.utility import xl_col_to_name
ACCESS_TOKEN = ''
WORKBOOK = ''
def create_daysheet():
worksheet = create_worksheet()
races = get_races_today()
write_meetings_to_sheet(worksheet=worksheet, races=races)
favourites = write_all_races_to_sheet(worksheet=worksheet, races=races)
write_fav_label_column(
row=0,
column=28,
worksheet=worksheet,
number_of_favourites=len(favourites)
)
write_races_list_to_sheet(
row=0,
column=29,
worksheet=worksheet,
races=races
)
write_protect_message(worksheet=worksheet)
write_race_percentages(
worksheet=worksheet,
number_of_favourites=len(favourites)
)
WORKBOOK.close()
def create_workbook():
today = datetime.today()
return xlsxwriter.Workbook(
'day-sheet-%s.xlsx' % today.strftime('%d-%m-%y')
)
def create_worksheet():
worksheet = WORKBOOK.add_worksheet()
worksheet.protect('123')
locked_format = get_locked_format()
worksheet.set_column('A:XDF', None, locked_format)
worksheet.set_default_row(12.6)
worksheet.set_column('A:A', 4.11)
worksheet.set_column('AA:AA', 3.11)
worksheet.set_column('AB:AB', 5.56)
cell_format = get_spacer_format()
worksheet.set_column('AC:AC', 0.63, cell_format)
worksheet.set_column('AF:AF', 4.56)
worksheet.set_column('AG:AG', 14.11)
worksheet.set_column('AH:AJ', 6.56)
worksheet.set_column('B:K', 2.56)
worksheet.set_column('L:L', 3.11)
worksheet.set_column('P:P', 4.11)
worksheet.set_column('Q:AA', 2.56)
worksheet.set_column('M:M', 5.22)
worksheet.set_column('N:N', 5.33)
worksheet.set_column('O:O', 1.67)
return worksheet
def get_spacer_format():
cell_format = WORKBOOK.add_format()
cell_format.set_bg_color('#000000')
return cell_format
def get_locked_format():
locked_format = WORKBOOK.add_format()
locked_format.set_locked(True)
return locked_format
def get_day_of_week_number():
return int(datetime.today().strftime('%w')) + 1
def get_week_number():
return int(datetime.today().strftime('%U')) + 1
def get_races_today():
day = get_day_of_week_number()
week = get_week_number()
year = datetime.today().year
url = ('xxx'
'xxx/{year}-{week}-{day}'
.format(
**{'day': day, 'week': week, 'year': year}
))
headers = {
'x-api-key': 'xxx',
'content-type': 'application/json; charset=UTF-8',
'referer': 'xxx',
'x-betfair-token': 'xxx',
'authorization': ACCESS_TOKEN
}
response = requests.get(url, headers=headers)
return response.json()
def get_racing_data(track_names):
url = 'xx'
headers = {
'x-api-key': 'xxx',
'content-type': 'application/json; charset=UTF-8',
'referer': 'xxx',
'authorization': ACCESS_TOKEN
}
day = get_day_of_week_number()
week = get_week_number()
data = {
"bz02_ip_gt": 0,
"bz04_ip_lt": 1002,
"bz06_sp_gt": 1,
"bz08_sp_lt": 1002,
"bz10_wk_from": week,
"bz12_wk_to": week,
"bz14_ran_from": 1,
"bz16_ran_to": 50,
"bz18_distance": "",
"bz20_ran": 0,
"bz22_race_type": "",
"bz24_fav": 0,
"bz26_days_of_week": "%s" % day,
"bz28_track": ', '.join(track_names),
"bz30_ire_uk": "",
"bz32_fav_sp1": 0,
"bz33_fav_sp2": 0,
"bz35_fav2_sp1": 0,
"bz36_fav2_sp2": 0,
"bz40_time_only1": 1.25,
"bz41_time_only2": 1.958333,
"bz43_fav_h": 0,
"bz72_loser_winner": 0,
"bz74_day": 0,
"bz76_month": 0,
"bz79_sp_gt": 0,
"bz81_sp_lt": 0,
"bz83_jmp_flat": 0,
"years": "2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018",
"bz38_hide_days": 0,
"bz69_raceno": 0,
"win_streak": 0,
"bz65_ire_plus": 0,
"bz49_racetype_2": "",
"bz47_dis_2": ""
}
raw_response = requests.post(
url,
data=json.dumps(data).replace(' ', ''),
headers=headers
)
return raw_response.json()
def split_races(races):
track_names = list(
set(
[
race['G_track']
for race in races
]
)
)
return {
track_name: [
race['N_time']
for race in races
if race['G_track'] == track_name
]
for track_name in track_names
}
def write_all_races_to_sheet(worksheet, races):
races_split = split_races(races=races)
track_names = races_split.keys()
racing_data = get_racing_data(track_names=track_names)
favourites = get_relevant_favourites(
favourites=racing_data['yrs']['Fav']
)
write_meeting_to_sheet(
worksheet=worksheet,
favourites=favourites,
row=0,
start_column=16
)
set_this_year_all_formulas(
row=2,
worksheet=worksheet,
number_of_favourites=len(favourites)
)
return favourites
def set_this_year_all_formulas(row, worksheet, number_of_favourites):
winner_format = get_winner_format()
for race_number in range(0, number_of_favourites):
target_cell = 'AA{row}'.format(
**{
'row': row + race_number
}
)
formula = 'COUNTIF(O:O,"{favourite_number}")'.format(
**{
'start_row': row,
'end_row': row + number_of_favourites,
'favourite_number': race_number + 1
}
)
worksheet.write_formula(target_cell, formula, winner_format)
def write_meetings_to_sheet(worksheet, races):
races_split = split_races(races=races)
row = 0
for track_name, times in races_split.items():
racing_data = get_racing_data(track_names=[track_name])
favourites = get_relevant_favourites(
favourites=racing_data['yrs']['Fav']
)
if not bool(favourites):
continue
write_track_and_time_to_sheet(
row=row,
worksheet=worksheet,
track_name=track_name,
times=times
)
write_meeting_to_sheet(
worksheet=worksheet,
favourites=favourites,
row=row,
start_column=1
)
set_this_year_races_formula(
row=row + 2,
worksheet=worksheet,
number_of_favourites=len(favourites),
number_of_races=len(times)
)
row += len(favourites) + 4
def set_this_year_races_formula(row, worksheet, number_of_favourites, number_of_races):
winner_format = get_winner_format()
for favourite_number in range(0, number_of_favourites):
target_cell = 'L{row}'.format(
**{
'row': row + favourite_number
}
)
formula = 'COUNTIF(O{start_row}:O{end_row},"{favourite_number}")'.format(
**{
'start_row': row,
'end_row': row + number_of_races,
'favourite_number': favourite_number + 1
}
)
worksheet.write_formula(target_cell, formula, winner_format)
def get_winner_format():
winner_format = create_base_format()
winner_format.set_align('center')
winner_format.set_align('vcenter')
winner_format.set_border(1)
winner_format.set_border_color('#a6a6a6')
return winner_format
def write_meeting_to_sheet(worksheet, favourites, row, start_column):
write_race_headers(
row=row,
column=start_column,
worksheet=worksheet,
number_of_favourites=len(favourites.keys())
)
row += 1
winner_format = get_winner_format()
for favourite, years in favourites.items():
column = start_column
del years['all']
for year, winners in years.items():
if winners != 0:
worksheet.write(row, column, winners, winner_format)
else:
worksheet.write(row, column, '', winner_format)
column += 1
worksheet.write(row, column, 0, winner_format)
row += 1
set_race_winners_conditional_format(
row=row,
start_column=start_column,
number_of_favourites=len(favourites.keys()),
worksheet=worksheet
)
write_totals_line(
row=row,
start_column=start_column,
worksheet=worksheet,
number_of_favourites=len(favourites.keys())
)
def get_time_format():
time_format = create_base_format()
time_format.set_font_size(9)
time_format.set_num_format('@')
time_format.set_border(1)
time_format.set_border_color('#000000')
time_format.set_align('right')
return time_format
def get_track_name_format():
track_name_format = create_base_format()
track_name_format.set_border(1)
track_name_format.set_border_color('#000000')
track_name_format.set_font_size(9)
return track_name_format
def write_track_and_time_to_sheet(row, worksheet, track_name, times):
column = 12
set_winner_conditional_format(
format_range='O1:O100',
worksheet=worksheet
)
time_format = get_time_format()
track_name_format = get_track_name_format()
for time in times:
row += 1
worksheet.write(row, column, time, time_format)
worksheet.write(row, column + 1, track_name, track_name_format)
set_race_time_forumula(row=row + 1, column=column + 2, worksheet=worksheet)
def set_race_time_forumula(row, column, worksheet):
track_name_format = get_track_name_format()
start_column = xl_col_to_name(column)
target_cell = '{column}{row}'.format(
**{
'column': start_column,
'row': row
}
)
formula = ('=IF(LEN(VLOOKUP({start_column}{start_row},AD:AF,3,FALSE))=0,"",'
'VLOOKUP({start_column}{start_row},AD:AF,3,FALSE))').format(
**{
'start_column': xl_col_to_name(column - 2),
'start_row': row
}
)
worksheet.write_formula(target_cell, formula, track_name_format)
def set_winner_conditional_format(format_range, worksheet):
fav_format = get_fav_format()
outsider_format = get_outsider_format()
blank_format = get_blank_format()
worksheet.conditional_format(
format_range,
{
'type': 'blanks',
'format': blank_format,
'stop_if_true': True
}
)
worksheet.conditional_format(
format_range,
{
'type': 'cell',
'criteria': '<=',
'value': 2,
'format': fav_format,
'stop_if_true': True
}
)
worksheet.conditional_format(
format_range,
{
'type': 'cell',
'criteria': '>=',
'value': 3,
'format': outsider_format,
'stop_if_true': True
}
)
def get_fav_format():
fav_format = create_base_format()
fav_format.set_pattern(1)
fav_format.set_align('center')
fav_format.set_align('vcenter')
fav_format.set_bg_color('#FFFF00')
return fav_format
def get_blank_format():
blank_format = create_base_format()
blank_format.set_align('center')
blank_format.set_align('vcenter')
return blank_format
def get_outsider_format():
outsider_format = create_base_format()
outsider_format.set_pattern(1)
outsider_format.set_align('center')
outsider_format.set_align('vcenter')
outsider_format.set_font_color('#FFFFFF')
outsider_format.set_bg_color('#203764')
return outsider_format
def get_danger_format():
danger_format = create_base_format()
danger_format.set_pattern(1)
danger_format.set_align('center')
danger_format.set_align('vcenter')
danger_format.set_font_color('#9c0000')
danger_format.set_bg_color('#ffc7ce')
return danger_format
def set_race_winners_conditional_format(row, start_column, number_of_favourites, worksheet):
fav_format = get_fav_format()
outsider_format = get_outsider_format()
fav_format_range = '{start_column}{start_row}:{end_column}{end_row}'.format(
**{
'start_column': xl_col_to_name(start_column),
'start_row': row - number_of_favourites + 1,
'end_column': xl_col_to_name(start_column + 10),
'end_row': row - number_of_favourites + 2
}
)
outsider_format_range = '{start_column}{start_row}:{end_column}{end_row}'.format(
**{
'start_column': xl_col_to_name(start_column),
'start_row': row - number_of_favourites + 3,
'end_column': xl_col_to_name(start_column + 10),
'end_row': row
}
)
set_fav_conditional_format(
format_range=fav_format_range,
worksheet=worksheet,
cell_format=fav_format
)
set_outsider_conditional_format(
format_range=outsider_format_range,
worksheet=worksheet,
cell_format=outsider_format
)
def set_fav_conditional_format(format_range, worksheet, cell_format):
blank_format = get_blank_format()
danger_format = get_danger_format()
worksheet.conditional_format(
format_range,
{
'type': 'cell',
'criteria': '>=',
'value': 1,
'format': cell_format,
'stop_if_true': True
}
)
worksheet.conditional_format(
format_range,
{
'type': 'blanks',
'format': blank_format,
'stop_if_true': True
}
)
worksheet.conditional_format(
format_range,
{
'type': 'cell',
'criteria': 'equal to',
'value': 0,
'format': danger_format,
'stop_if_true': True
}
)
def set_outsider_conditional_format(format_range, worksheet, cell_format):
blank_format = get_blank_format()
danger_format = get_danger_format()
worksheet.conditional_format(
format_range,
{
'type': 'cell',
'criteria': '>=',
'value': 1,
'format': cell_format,
'stop_if_true': True
}
)
worksheet.conditional_format(
format_range,
{
'type': 'blanks',
'format': blank_format,
'stop_if_true': True
}
)
worksheet.conditional_format(
format_range,
{
'type': 'cell',
'criteria': 'equal to',
'value': 0,
'format': danger_format,
'stop_if_true': True
}
)
def get_total_format():
total_format = create_base_format()
total_format.set_pattern(1)
total_format.set_align('center')
total_format.set_align('vcenter')
total_format.set_bg_color('#5E943C')
total_format.set_font_color('#FFFFFF')
return total_format
def write_totals_line(row, start_column, worksheet, number_of_favourites):
for column_number in range(start_column, start_column + 11):
column = xl_col_to_name(column_number)
target_cell = '{column}{row}'.format(
**{
'column': column,
'row': row + 1
}
)
formula = '=SUM({column}{row_start}:{column}{row_end})'.format(
**{
'column': column,
'row_start': row - number_of_favourites + 1,
'row_end': row
}
)
total_format = get_total_format()
worksheet.write_formula(target_cell, formula, total_format)
def get_relevant_favourites(favourites):
favourites = OrderedDict(favourites)
to_delete = []
del favourites['total']
for favourite, years in reversed(favourites.items()):
if favourites_not_empty(years=years):
break
to_delete.append(favourite)
for favourite in to_delete:
del favourites[favourite]
return favourites
def write_race_headers(row, column, worksheet, number_of_favourites):
cell_format = get_race_header_format()
write_column_headers(
row=row,
column=column,
worksheet=worksheet,
number_of_favourites=number_of_favourites,
cell_format=cell_format
)
worksheet.write(row, column - 1, 'Fav No', cell_format)
write_row_headers(
row=row,
column=column,
worksheet=worksheet,
cell_format=cell_format
)
def write_row_headers(row, column, worksheet, cell_format):
for year in range(2009, 2020):
if year != 2019:
worksheet.write(row, column, str(year)[-2:], cell_format)
else:
worksheet.write(row, column, year, cell_format)
column += 1
def write_column_headers(row, column, worksheet, number_of_favourites, cell_format):
special_cases = {
1: 'Fav',
2: '2nd',
3: '3rd',
21: '21st',
22: '22nd',
23: '23rd'
}
for favourite in range(1, number_of_favourites + 1):
row += 1
if favourite in special_cases:
worksheet.write(row, column - 1, special_cases[favourite], cell_format)
else:
worksheet.write(row, column - 1, '%sth' % favourite, cell_format)
def write_fav_label_column(row, column, worksheet, number_of_favourites):
write_column_headers(
row=row,
column=column,
worksheet=worksheet,
number_of_favourites=number_of_favourites,
cell_format=get_winner_format()
)
def favourites_not_empty(years):
for year, winners in years.items():
if winners > 0:
return True
return False
def get_race_header_format():
header_format = create_base_format()
header_format.set_bold()
header_format.set_pattern(1)
header_format.set_align('center')
header_format.set_align('vcenter')
header_format.set_bg_color('#D9D9D9')
header_format.set_font_color('#002060')
header_format.set_border(1)
header_format.set_border_color('#a6a6a6')
header_format.set_num_format('@')
return header_format
def create_base_format():
workbook_format = WORKBOOK.add_format()
workbook_format.set_font_name('Calibri')
workbook_format.set_font_size(8)
return workbook_format
def write_races_list_headers(row, column, worksheet):
cell_format = get_race_header_format()
cell_format.set_locked(False)
worksheet.write(row, column, 'Time', cell_format)
worksheet.write(row, column + 1, 'Track', cell_format)
worksheet.write(row, column + 2, 'Winner', cell_format)
worksheet.write(row, column + 3, 'Winner name', cell_format)
def write_races_list_to_sheet(row, column, worksheet, races):
write_races_list_headers(row=row, column=column, worksheet=worksheet)
cell_format = get_track_name_format()
cell_format.set_locked(False)
time_format = get_time_format()
time_format.set_locked(False)
for index, race in enumerate(races):
worksheet.write(row + index + 1, column, race['N_time'], time_format)
worksheet.write(row + index + 1, column + 1, race['G_track'], cell_format)
if 'Winner' in race:
winner = race['Winner']
else:
winner = ''
if 'WinnerName' in race:
winner_name = race['WinnerName']
else:
winner_name = ''
worksheet.write(row + index + 1, column + 2, winner, cell_format)
worksheet.write(row + index + 1, column + 3, winner_name, cell_format)
start_column = xl_col_to_name(column + 2)
start_row = row + 2
end_row = row + len(races) + 1
format_range = '{start_column}{start_row}:{end_column}{end_row}'.format(
**{
'start_column': start_column,
'start_row': start_row,
'end_column': start_column,
'end_row': end_row
}
)
set_winner_conditional_format(format_range=format_range, worksheet=worksheet)
def write_protect_message(worksheet):
worksheet.write(0, 33, 'Password to unlock the sheet is 123')
worksheet.write(2, 33, 'Only reason it is locked is to protect the formulas')
def write_race_percentages(worksheet, number_of_favourites):
start_row = 4
start_target_row = 2
for favourite_number in range(0, number_of_favourites):
worksheet.write(start_row + favourite_number, 33, favourite_number + 1)
set_percentage_win_count_formula(
start_row=start_row,
favourite_number=favourite_number,
worksheet=worksheet,
start_target_row=start_target_row
)
set_percentage_win_formula(
start_row=start_row,
favourite_number=favourite_number,
worksheet=worksheet,
number_of_favourites=number_of_favourites
)
set_percentage_win_sum_formula(
start_row=start_row,
worksheet=worksheet,
number_of_favourites=number_of_favourites
)
def set_percentage_win_formula(start_row, favourite_number, worksheet, number_of_favourites):
target_cell = 'AJ{row}'.format(
**{
'row': start_row + favourite_number + 1
}
)
formula = '=IF($AI{total_row}=0,0.0,SUM(AI{row}/AI{total_row}))'.format(
**{
'row': start_row + favourite_number + 1,
'total_row': start_row + number_of_favourites + 1
}
)
cell_format = create_base_format()
cell_format.set_num_format('0.00%')
worksheet.write_formula(target_cell, formula, cell_format)
def set_percentage_win_sum_formula(start_row, worksheet, number_of_favourites):
target_cell = 'AI{row}'.format(
**{
'row': start_row + number_of_favourites + 1
}
)
formula = '=SUM(AI{start_row}:AI{end_row})'.format(
**{
'start_row': start_row + 1,
'end_row': start_row + number_of_favourites - 1,
}
)
cell_format = create_base_format()
worksheet.write_formula(target_cell, formula, cell_format)
def set_percentage_win_count_formula(start_row, favourite_number, worksheet, start_target_row):
target_cell = 'AI{row}'.format(
**{
'row': start_row + favourite_number + 1
}
)
formula = '=AA{row}'.format(
**{
'row': start_target_row + favourite_number,
}
)
cell_format = create_base_format()
worksheet.write_formula(target_cell, formula, cell_format)
def login():
url = 'xxx'
headers = {
'x-api-key': 'xxx',
'content-type': 'application/json; charset=UTF-8',
'referer': 'xxx'
}
data = '{"user":"xxx","pass":"%s"}' % os.environ.get("RSA_PASSWORD")
raw_response = requests.post(url, data=data, headers=headers)
response = raw_response.json()
return response['accessToken']
if __name__ == '__main__':
ACCESS_TOKEN = login()
WORKBOOK = create_workbook()
create_daysheet()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-09T01:16:20.557",
"Id": "460508",
"Score": "1",
"body": "Is there any way you could share a runnable version?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-09T06:18:00.297",
"Id": "460520",
"Score": "0",
"body": "Unfortunately not as the APIs are behind a paid user account for racing software."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-10T01:09:22.237",
"Id": "460700",
"Score": "0",
"body": "Oh, nice, what kind of software?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-10T08:28:09.310",
"Id": "460724",
"Score": "0",
"body": "It's an interface to historical racing data."
}
] |
[
{
"body": "<h2>Your workbook</h2>\n<p>It has a few issues:</p>\n<ul>\n<li>It should not be a global</li>\n<li>It should not be assigned an empty string, since it actually (eventually) takes a <code>Workbook</code> instance</li>\n<li>Ideally it should be opened and closed in the same function, not different functions</li>\n</ul>\n<p>Also, based on the <a href=\"https://xlsxwriter.readthedocs.io/workbook.html\" rel=\"nofollow noreferrer\">documentation</a>:</p>\n<blockquote>\n<p>The <code>Workbook()</code> method also works using the with context manager. In which case it doesn’t need an explicit <code>close()</code> statement</p>\n</blockquote>\n<p>So do that.</p>\n<h2>Date formatting</h2>\n<pre><code>'day-sheet-%s.xlsx' % today.strftime('%d-%m-%y')\n</code></pre>\n<p>can be</p>\n<pre><code>f'day-sheet-{today:%d-%m-%y}.xlsx'\n</code></pre>\n<p>This uses string interpolation and inline <code>datetime</code> formatting.</p>\n<h2>Cell defaults</h2>\n<pre><code>worksheet.set_default_row(12.6)\nworksheet.set_column('A:A', 4.11)\nworksheet.set_column('AA:AA', 3.11)\nworksheet.set_column('AB:AB', 5.56)\ncell_format = get_spacer_format()\nworksheet.set_column('AC:AC', 0.63, cell_format)\nworksheet.set_column('AF:AF', 4.56)\nworksheet.set_column('AG:AG', 14.11)\nworksheet.set_column('AH:AJ', 6.56)\nworksheet.set_column('B:K', 2.56)\nworksheet.set_column('L:L', 3.11)\nworksheet.set_column('P:P', 4.11)\nworksheet.set_column('Q:AA', 2.56)\nworksheet.set_column('M:M', 5.22)\nworksheet.set_column('N:N', 5.33)\nworksheet.set_column('O:O', 1.67)\n</code></pre>\n<p>These constants, ideally, should be externalized - possibly to a (maybe-global) constant tuple of floats, decoupled from the column specifications.</p>\n<h2>Day of week</h2>\n<pre><code>int(datetime.today().strftime('%w'))\n</code></pre>\n<p>should not go through string formatting. Instead, call into <a href=\"https://docs.python.org/3/library/datetime.html#datetime.date.weekday\" rel=\"nofollow noreferrer\">https://docs.python.org/3/library/datetime.html#datetime.date.weekday</a></p>\n<h2>More string interpolation</h2>\n<pre><code>url = ('xxx'\n 'xxx/{year}-{week}-{day}'\n .format(\n **{'day': day, 'week': week, 'year': year}\n ))\n</code></pre>\n<p>is simpler as</p>\n<pre><code>url = (\n 'xxx'\n f'xxx/{year}-{week}-{day}'\n)\n</code></pre>\n<h2>Header case</h2>\n<p>Even though these will work, technically:</p>\n<pre><code>headers = {\n 'x-api-key': 'xxx',\n 'content-type': 'application/json; charset=UTF-8',\n 'referer': 'xxx',\n 'x-betfair-token': 'xxx',\n 'authorization': ACCESS_TOKEN\n}\n</code></pre>\n<p>The standard capitalization for header keys is <a href=\"https://www.iana.org/assignments/message-headers/message-headers.xml#perm-headers\" rel=\"nofollow noreferrer\">TitleCase</a>, and you should use it.</p>\n<h2>Posting JSON</h2>\n<pre><code>requests.post(\n url,\n data=json.dumps(data).replace(' ', ''),\n headers=headers\n)\n</code></pre>\n<p>Don't call <code>json.dumps</code>. You can just pass a dictionary to the <code>json</code> kwarg.</p>\n<h2>Set comprehensions</h2>\n<pre><code> set(\n [\n race['G_track']\n for race in races\n ]\n )\n</code></pre>\n<p>can be</p>\n<pre><code>{\n race['G_track']\n for race in races\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-31T08:28:09.723",
"Id": "483924",
"Score": "0",
"body": "Excellent advice - thank you"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-26T14:21:52.543",
"Id": "246039",
"ParentId": "235108",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "246039",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-05T10:37:56.757",
"Id": "235108",
"Score": "3",
"Tags": [
"python",
"python-3.x"
],
"Title": "Python script that consumes an API and generates an Excel spreadsheet"
}
|
235108
|
<p>I am new to Reactive Extensions, I have the requirement to consume <code>PairCollection<IPointCloud></code> which are fed into a service which performs a very expensive multi-threaded process but has limited concurrency (which I base on the number of machine cores). The process of getting the <code>PairCollection<IPointCloud></code> objects is itself expensive as there are many, but can be done in parallel with no thread restriction so I have have decided to use ReactiveExtensions (why not) for this. </p>
<p>I have setup a LinqPAD example which simulates what I want, however, there are a few aspects of what I have done that do not feel right. I have started a <code>Task</code> to ensure the observable subscriptions do not block, however, I would like to do this using another Observable subscription, but one that is asynchronious, I would like some advice to ensure that </p>
<ol>
<li>What I have done so far is correct?</li>
<li>How can I replace the Task.Run in the Main method with some form of async IObservable that does not block? </li>
<li>Is the method is use for cancellation support correct? </li>
</ol>
<p>The pseudo data files that I read from "C:\Data" are available from here <a href="https://1drv.ms/u/s!AuCd_PcRnNWpn3qhr0MskrbhEoC2?e=M6d1zo" rel="nofollow noreferrer">https://1drv.ms/u/s!AuCd_PcRnNWpn3qhr0MskrbhEoC2?e=M6d1zo</a>.</p>
<pre><code>void Main()
{
Task.Run(() =>
{
int index = 0;
var pairCollectionProducer = PairCollectionProducer(CancellationToken.None);
pairCollectionProducer.Subscribe(cp =>
{
// Now run expensive process using pair collection.
// _pointCloudMergingService.Merge(cp);
Console.WriteLine($"PairCollection count = {cp.Count:N0}, Index = {index++:N0}");
},
ex =>
{
Console.WriteLine("ERROR");
},
() =>
{
Console.WriteLine("COMPLETED");
});
});
Console.WriteLine("LAST LINE");
Console.ReadLine();
}
public IObservable<PairCollection<IPointCloud>> PairCollectionProducer(CancellationToken token)
{
return Observable.Create<PairCollection<IPointCloud>>(
observer =>
{
Parallel.ForEach(
Utils.GetFileBatches(@"C:\Data"),
(fileBatch) =>
{
Console.WriteLine($"{fileBatch[0]} file loop");
if (fileBatch[0] == @"C:\Data\bb.0000.exr")
Thread.Sleep(200);
var producer = RawDepthMapsProducer(fileBatch[0], token);
int index = 0;
ConcurrentBag<IPointCloud> bag = new ConcurrentBag<IPointCloud>();
IDisposable subscriber = producer.Subscribe(rawDepthMap =>
{
Thread.Sleep(50);
bag.Add(new PointCloud() { Index = index++ });
},
ex => { },
() =>
{
PointCloudPartitioningService ps = new PointCloudPartitioningService();
observer.OnNext(ps.Partition(bag.ToList()));
});
});
observer.OnCompleted();
return () => { };
});
}
public IObservable<RawDepthMap> RawDepthMapsProducer(string filePath, CancellationToken token)
{
return Observable.Create<RawDepthMap>(
observer =>
{
for (int i = 0; i < 10; ++i)
{
Thread.Sleep(50);
Console.WriteLine($"filePath = {filePath}, i = {i:N0}");
observer.OnNext(new RawDepthMap() { Height = i, Width = 1 });
}
observer.OnCompleted();
return () => { };
});
}
public interface IPointCloud
{
Vertex[] Vertices { get; set; }
bool ContainsNormals { get; }
int? Index { get; set; }
}
public class PointCloud : IPointCloud
{
public PointCloud() { }
public PointCloud(Vertex[] vertices)
{
Vertices = vertices;
}
public Vertex[] Vertices { get; set; }
public bool ContainsNormals => Vertices.Any(v =>
v.Normal.X != 0.0f ||
v.Normal.Y != 0.0f ||
v.Normal.Z != 0.0f);
public int? Index { get; set; }
}
public struct Vertex
{
public Vertex(Vector3 point, Vector3 normal)
{
Point = point;
Normal = normal;
}
public Vertex(Vector3 point)
: this(point, new Vector3()) { }
public Vector3 Point;
public Vector3 Normal;
}
public class PairCollection<T> where T : class
{
public PairCollection()
{
Partitions = new List<IndexedPair<T>>();
Last = null;
}
public List<T> Flatten()
{
List<T> l = new List<T>();
foreach (var it in Partitions)
{
l.Add(it.Pair.Item1);
l.Add(it.Pair.Item2);
}
if (Last != null)
l.Add(Last);
return l;
}
public IList<IndexedPair<T>> Partitions { get; set; }
public T Last { get; set; }
public int Count { get { return Partitions.Count * 2 + (Last != null ? 1 : 0); } }
}
public class IndexedPair<T>
{
public IndexedPair(int index, T item1, T item2)
: this(index, new Tuple<T, T>(item1, item2)) { }
public IndexedPair(int index, Tuple<T, T> tuple)
{
Index = index;
Pair = tuple;
}
public int Index { get; set; }
public Tuple<T, T> Pair { get; set; }
}
public class RawDepthMap
{
public string Source { get; set; }
public List<double> DepthMapArray { get; set; }
public int Height { get; set; }
public int Width { get; set; }
public override string ToString()
{
string source = !String.IsNullOrEmpty(Source) ? Source : "N/A";
StringBuilder builder = new StringBuilder($"RawDepthMap: Source \"{source}\"");
if (DepthMapArray != null)
builder.Append($", Array size {DepthMapArray:N0}");
builder.Append($", Width {Width:N0}, Height {Height:N0}");
return builder.ToString();
}
}
public interface IPartitioningService<T> where T : class
{
PairCollection<T> Partition(IList<T> itemList);
}
public class PointCloudPartitioningService : PartitioningServiceBase<IPointCloud>
{
public override PairCollection<IPointCloud> Partition(IList<IPointCloud> pointCloudCollection)
{
if (pointCloudCollection == null || pointCloudCollection.Count < 2)
throw new ArgumentException("Point cloud collection cannot be null or less than 2");
if (pointCloudCollection.Any(pc => pc.Index == null))
throw new ArgumentNullException("All point clouds must be indexed");
List<IPointCloud> orderedPointClouds = pointCloudCollection
.OrderBy(f => (int)f.Index)
.ToList();
return PartitioningCore(orderedPointClouds);
}
}
public abstract class PartitioningServiceBase<T> : IPartitioningService<T> where T : class
{
public abstract PairCollection<T> Partition(IList<T> itemList);
protected PairCollection<T> PartitioningCore(IList<T> itemList)
{
int index = 0;
PairCollection<T> partitionedCollection = new PairCollection<T>();
for (int i = 0; i < itemList.Count; i += 2)
{
if (i + 1 >= itemList.Count)
break;
IndexedPair<T> it = new IndexedPair<T>(
index++, itemList[i], itemList[i + 1]);
partitionedCollection.Partitions.Add(it);
}
if (itemList.Count % 2 != 0)
partitionedCollection.Last = itemList.Last();
return partitionedCollection;
}
}
public static class Utils
{
public static List<List<string>> GetFileBatches(string directory)
{
if (!Directory.Exists(directory))
throw new IOException($"Directory \"{directory}\" does not exist");
var fileInfoCollection = Directory.GetFiles(directory).Select(f => new FileInfo(f));
if (fileInfoCollection.Any(fi => !DepthMapSourceMappings.SupportedDepthMapSourceTypes.ContainsKey(Path.GetExtension(fi.Name))))
{
string tmp = String.Join(", ", DepthMapSourceMappings.SupportedDepthMapSourceTypes.Select(kvp => kvp.Key));
throw new IOException($"Only source files of type ({tmp.Trim()}) are currently supported");
}
Regex regex = new Regex(@"^\w+");
return fileInfoCollection
.GroupBy(fi => regex.Match(fi.Name).ToString())
.Select(group => group.Select(fi => fi.FullName).ToList())
.ToList();
}
}
public enum DepthMapSourceType
{
Exr
};
public static class DepthMapSourceMappings
{
public static Dictionary<string, DepthMapSourceType> SupportedDepthMapSourceTypes { get; } =
new Dictionary<string, DepthMapSourceType>()
{
{ ".exr", DepthMapSourceType.Exr }
};
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-06T18:54:43.933",
"Id": "460168",
"Score": "0",
"body": "Anyway you can make this less abstract? There are thread sleeps. I assume to account for work? Rx isn't usually used for fan out work unless you are using Tasks. What might work better is TPL Data Flow and creating a data flow mesh which would also help with back pressure. If processing the file take a long time do you really want to create and queue up unlimited objects of files? I have more questions but without more concrete sample it's hard to know what's right. For Ex why is RawDepthMapsProducer another observable create with a loop of 10 instead of just .Select or.SelectMany?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-06T22:51:19.323",
"Id": "460197",
"Score": "0",
"body": "The thread sleeps are to simulate work, yes. The process that creates the `IPointCloud`s is relatively inexpensive and I want this process to be done using max parrallelisation. Likewise with RawDepthMap production. However, the processing in the main method will be very expensive and the threading is throttled using a limited concurrency TaskScheduler. I think this is a good candidate for the user of Rx. I have decided I need to await the Parrallel.ForEach so it does not fire the OnCompleted right away, so I am going to swap this out for an array of Tasks and await all of these."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-06T22:51:56.327",
"Id": "460198",
"Score": "0",
"body": "I'll struggle to make this less abstract unless I re-write all of the code using primitive types."
}
] |
[
{
"body": "<p>GetFileBatches is enumerating fileInfoCollection twice. One for Any and once for groupby. </p>\n\n<p>By default Rx runs same thread. You could test this by logging Thread.CurrentThread.ManagedThreadId and seeing the values. The RawDepthMapsProducer isn't adding anything and just adding over head since its all on the same thread. You can read more <a href=\"http://introtorx.com/Content/v1.0.10621.0/15_SchedulingAndThreading.html\" rel=\"nofollow noreferrer\">here</a>. Right now it's just the code inside the Parallel.ForEach that is using different threads, but the Observable inside are using the same thread.</p>\n\n<p>Rx running by default on the same thread is why the Task.Run needed to be there to get it off the main thread. ObserveOn would be a more Rx option or using SelectMany for Tasks. </p>\n\n<p>Hard to give more feedback with this so much abstracted and if you can use Task or not. You could switch to the ObserveOn to use ThreadPool but this might cause too much back pressure. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-07T02:42:32.783",
"Id": "235203",
"ParentId": "235110",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-05T11:37:59.333",
"Id": "235110",
"Score": "1",
"Tags": [
"c#",
"asynchronous",
"system.reactive"
],
"Title": "Using Reactive Extensions in an Asynchronious Way"
}
|
235110
|
<p>This is a an implementation of Binary Indexed Tree. This passes all the test cases listed below and works as intended. I'm using Java 11.</p>
<p><em>What I need reviewed:</em></p>
<ul>
<li>Can this be simplified with any new feature in Java versions 8-11?</li>
<li>Any other improvements?</li>
</ul>
<hr>
<blockquote>
<p><strong>Binary Indexed Tree</strong></p>
<p>A Fenwick tree or binary indexed tree is a data structure that can
efficiently update elements and calculate prefix sums in a table of
numbers. Both operations are <span class="math-container">\$O(log(n))\$</span></p>
<p><a href="https://en.wikipedia.org/wiki/Fenwick_tree" rel="nofollow noreferrer">Wikipedia Article</a></p>
</blockquote>
<p><strong>BinaryIndexedTree.java</strong></p>
<pre><code>import java.util.Objects;
/**
* BinaryIndexedTree allows faster ranges sums of O(log(n))
* However increasing a single index with delta is also O(log(n))
* Note: This doesn't check for overflow
*
* @author Bhathiya
*/
public class BinaryIndexedTree {
private final long[] internalData;
private final int size;
/**
* Construct from given array
*
* @param originalArray original array to process
*/
public BinaryIndexedTree(long[] originalArray) {
Objects.requireNonNull(originalArray);
this.size = originalArray.length;
internalData = new long[size + 1];
for (int i = 0; i < size; i++) {
increase(i, originalArray[i]);
}
}
/**
* Construct an empty BinaryIndexedTree
*
* @param size element count
*/
public BinaryIndexedTree(int size) {
if (size < 0) throw new IllegalArgumentException("Size cannot be less than zero");
this.size = size;
internalData = new long[size + 1];
}
/**
* Increase given index with value delta
* similar to array[index] += delta
*
* @param index index in array
* @param delta value to add to specific index
*/
public void increase(int index, long delta) {
if (index < 0 || index >= size) throw new IndexOutOfBoundsException(index);
index += 1;
while (index <= this.size) {
internalData[index] += delta;
// WHY:
// Faster way to get the last set bit of index using 2's complement
// then we add it to index to find all cells that needs to be incremented
index += index & (-index);
}
}
/**
* Calculate sum of values in array[0] ... array[index] (inclusive)
*
* @param index index in array
* @return sum
*/
public long sumUpTo(int index) {
if (index < 0 || index >= size) throw new IndexOutOfBoundsException(index);
int sum = 0;
index += 1;
while (index > 0) {
sum += internalData[index];
// WHY:
// Faster way to get the last set bit of index using 2's complement
// then we subtract it from index to find all cells that contains values that
// we need to add to `sum` variable so we can find sumUpTo given original index
index -= index & (-index);
}
return sum;
}
/**
* Calculate sum of array[fromIndex] .. array[toIndex]
*
* @param fromIndex range from index in array
* @param toIndex range to index in array
* @return sum of elements in specified index range
*/
public long rangeSum(int fromIndex, int toIndex) {
if (fromIndex == 0) {
return sumUpTo(toIndex);
}
return sumUpTo(toIndex) - sumUpTo(fromIndex - 1);
}
/**
* @return size of BinaryIndexedTree
*/
public int size() {
return this.size;
}
}
</code></pre>
<p><strong>BinaryIndexedTreeTest.java</strong></p>
<pre><code>import org.testng.Assert;
import org.testng.annotations.Test;
public class BinaryIndexedTreeTest {
@Test
public void testIncrease() {
long[] original = {1, 2, 3, 4, 5};
BinaryIndexedTree binaryIndexedTree = new BinaryIndexedTree(original);
binaryIndexedTree.increase(0, 5);
// now first element should be 6, therefore sum of element 0 .. 0 is 6.
Assert.assertEquals(binaryIndexedTree.sumUpTo(0), 6);
// sum of elements at indexes 0 .. 1 is 8
Assert.assertEquals(binaryIndexedTree.sumUpTo(1), 8);
}
@Test
public void testIncreaseSingleElement() {
long[] original = {1};
BinaryIndexedTree binaryIndexedTree = new BinaryIndexedTree(original);
binaryIndexedTree.increase(0, 5);
// now first element should be 6, therefore sum of element 0 .. 0 is 6.
Assert.assertEquals(binaryIndexedTree.sumUpTo(0), 6);
}
@Test(expectedExceptions = IndexOutOfBoundsException.class)
public void testEmptyArraySum() {
long[] original = {};
BinaryIndexedTree binaryIndexedTree = new BinaryIndexedTree(original);
Assert.assertEquals(binaryIndexedTree.sumUpTo(0), 0);
}
@Test(expectedExceptions = IndexOutOfBoundsException.class)
public void testEmptyArraySumWithSizeConstructor() {
BinaryIndexedTree binaryIndexedTree = new BinaryIndexedTree(0);
Assert.assertEquals(binaryIndexedTree.sumUpTo(0), 0);
}
@Test(expectedExceptions = IndexOutOfBoundsException.class)
public void testEmptyArrayIncrease() {
long[] original = {};
BinaryIndexedTree binaryIndexedTree = new BinaryIndexedTree(original);
binaryIndexedTree.increase(0, 1);
}
@Test(expectedExceptions = NullPointerException.class)
public void testNoNullArrayAllowed() {
new BinaryIndexedTree(null);
}
@Test
public void testSumUpTo() {
BinaryIndexedTree binaryIndexedTree = new BinaryIndexedTree(4);
binaryIndexedTree.increase(0, 1);
binaryIndexedTree.increase(1, 2);
binaryIndexedTree.increase(2, 3);
binaryIndexedTree.increase(3, 4);
Assert.assertEquals(binaryIndexedTree.sumUpTo(3), 1 + 2 + 3 + 4);
}
@Test
public void testSize() {
Assert.assertEquals(new BinaryIndexedTree(0).size(), 0);
Assert.assertEquals(new BinaryIndexedTree(2).size(), 2);
Assert.assertEquals(new BinaryIndexedTree(array(1, 2, 3)).size(), 3);
Assert.assertEquals(new BinaryIndexedTree(array()).size(), 0);
}
@Test(expectedExceptions = IllegalArgumentException.class)
public void testSizeNegativeResultsInProblem() {
BinaryIndexedTree binaryIndexedTree = new BinaryIndexedTree(-1);
}
@Test
public void testRangeSum() {
BinaryIndexedTree binaryIndexedTree = new BinaryIndexedTree(4);
binaryIndexedTree.increase(0, 1);
binaryIndexedTree.increase(1, 2);
binaryIndexedTree.increase(2, 3);
binaryIndexedTree.increase(3, 4);
Assert.assertEquals(binaryIndexedTree.rangeSum(1, 2), 2 + 3);
Assert.assertEquals(binaryIndexedTree.rangeSum(0, 0), 1);
Assert.assertEquals(binaryIndexedTree.rangeSum(1, 1), 2);
Assert.assertEquals(binaryIndexedTree.rangeSum(2, 2), 3);
Assert.assertEquals(binaryIndexedTree.rangeSum(3, 3), 4);
Assert.assertEquals(binaryIndexedTree.rangeSum(1, 3), 2 + 3 + 4);
}
@Test
public void testWithNegativeNumbers() {
BinaryIndexedTree binaryIndexedTree = new BinaryIndexedTree(array(0, 1, 2, -1, -2, 0, 0));
Assert.assertEquals(binaryIndexedTree.sumUpTo(binaryIndexedTree.size() - 1), 0);
}
private static long[] array(long... elements) {
return elements;
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-05T18:03:22.093",
"Id": "460019",
"Score": "0",
"body": "Hello, the constructor `IndexOutOfBoundsException(int index)` is available only from Java 9."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-05T18:13:00.203",
"Id": "460022",
"Score": "0",
"body": "I'm using Java 11"
}
] |
[
{
"body": "<p>I have two suggestions for your code.</p>\n\n<p>1) Make a method to get the last set of bits, instead of repeating the code & comment.</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>/**\n* Faster way to get the last set bit of index using 2's complement\n* @param index index in array\n*/\nprivate int getLastSetOfBits(int index) {\n return index & (-index);\n}\n</code></pre>\n\n<p>2) In the method <code>BinaryIndexedTree#rangeSum</code>, since you are using the expression <code>sumUpTo(toIndex)</code> in all cases, I suggest that you extract it in a variable.</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>public long rangeSum(int fromIndex, int toIndex) {\n long sumUpToFromIndex = sumUpTo(toIndex);\n\n if (fromIndex == 0) {\n return sumUpToFromIndex;\n }\n\n return sumUpToFromIndex - sumUpTo(fromIndex - 1);\n}\n<span class=\"math-container\">```</span>\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-05T19:39:02.130",
"Id": "235128",
"ParentId": "235117",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "235128",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-05T16:15:07.630",
"Id": "235117",
"Score": "4",
"Tags": [
"java"
],
"Title": "Binary Indexed Tree implementation with test cases"
}
|
235117
|
<p>I am new to Python and am trying to optimize the following code:</p>
<pre><code>import sys
import numpy as np
def LSMPut(T, r, sigma, K, S0, TimeSteps, Paths, k):
dt = T/TimeSteps
t = np.arange(0, T+dt, dt).tolist()
z=[np.random.standard_normal() for _ in range(Paths)]
w = (r-sigma**2/2)*T + sigma*np.sqrt(T)*np.array(z)
S = S0*np.exp(np.array(w))
P=np.maximum(K-np.array(S),0)
for i in range(TimeSteps-1, -1, -1):
z=[np.random.standard_normal() for _ in range(Paths)]
w = t[i]*np.array(w)/t[i+1] + sigma*np.sqrt(dt*t[i]/t[i+1])*np.array(z)
S = S0*np.exp(np.array(w))
itmPaths = [index for index,value in enumerate(K-np.array(S)) if value > 0]
itmS = S[itmPaths]
Pt = K - np.array(itmS)
itmDiscP = P[itmPaths]*np.exp(-r*dt)
A = BasisFunct(itmS, k)
beta = np.linalg.lstsq(A,itmDiscP)[0]
C = np.dot(A,beta)
exPaths = [itmPaths[i] for i, value in enumerate(zip(Pt, C)) if value[0] > value[1]]
restPaths = np.setdiff1d(np.arange(0, Paths-1, 1).tolist(), exPaths) # Rest of the paths
P[exPaths] = [Pt[i] for i, value in enumerate(zip(Pt, C)) if value[0] > value[1]]
P[restPaths] = np.array(P[restPaths])*np.exp(-r*dt)
u=np.mean(P*np.exp(-r*dt))
return u
def BasisFunct(X, k):
Ones=[1 for _ in range(len(X))]
if k == 1:
A = np.column_stack((Ones,1 - np.array(X)))
elif k == 2:
A = np.column_stack((Ones,1 - np.array(X),1/2*(2-4*np.array(X) + np.array(X)**2)))
elif k == 3:
A = np.column_stack((Ones,1 - np.array(X),1/2*(2-4*np.array(X) + np.array(X)**2), 1/6*(6-18*np.array(X) + 9*np.array(X)**2-np.array(X)**3)))
elif k == 4:
A = np.column_stack((Ones,1 - np.array(X),1/2*(2-4*np.array(X) + np.array(X)**2), 1/6*(6-18*np.array(X) + 9*np.array(X)**2-np.array(X)**3),1/24*(24 - 96*np.array(X) + 72*np.array(X)**2 - 16*np.array(X)**3 + np.array(X)**4)))
elif k == 5:
A = np.column_stack((Ones,1 - np.array(X),1/2*(2-4*np.array(X) + np.array(X)**2), 1/6*(6-18*np.array(X) + 9*np.array(X)**2-np.array(X)**3),1/24*(24 - 96*np.array(X) + 72*np.array(X)**2 - 16*np.array(X)**3 + np.array(X)**4),1/120*(120-600*np.array(X)+600*np.array(X)**2-200*np.array(X)**3+25*np.array(X)**4-np.array(X)**5)))
else:
sys.exit("Too many basis functions requested")
return A
print(LSMPut(1, 0.06, 0.15, 100, 90, 20, 1000000, 5))
</code></pre>
<p>The purpose of the code is to calculate the price of an American put option. The time to execute if <code>Paths > 1,000,000</code> takes a long time, especially if I perform a sensitivity analysis. I would like to find out if there is any way for me to optimize the code or accelerate the processing time. Thank you.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-05T20:58:32.730",
"Id": "460032",
"Score": "0",
"body": "Welcome to StackOverflow! Someone has downvoted your question because it's not specific enough or because it's not compiling or because it's not clear for which input it times out."
}
] |
[
{
"body": "<p>I changed the main part of the script to:</p>\n\n<pre><code>from time import time\nstart = time()\nval = LSMPut(1, 0.06, 0.15, 100, 90, 20, 40_000, 5)\nprint(f'Done in {time() - start:.3} seconds')\nprint(val)\n</code></pre>\n\n<p>The point is that Python will print how long the calculation took to\nrun. Before modifications, the script takes 3.05 seconds to run on my\ncomputer.</p>\n\n<p>Now I can modify <code>lsmput</code> (I renamed <code>LSMPut</code> and some other functions\nand variables because they names shouldn't contain capital letters\naccording to the Python style guide) and see which changes makes it\nrun faster.</p>\n\n<p>Here follows the changes that impacted the runtime the most. Changing</p>\n\n<pre><code>z=np.array([np.random.standard_normal() for _ in range(paths)])\n</code></pre>\n\n<p>to</p>\n\n<pre><code>z = np.random.standard_normal(paths)\n</code></pre>\n\n<p>brings the runtime down to 2.43 seconds. Changing</p>\n\n<pre><code>ones=[1 for _ in range(len(X))]\n</code></pre>\n\n<p>to</p>\n\n<pre><code>ones = np.ones(len(X))\n</code></pre>\n\n<p>reduces the runtime further to 2.21 seconds. Precalculating the powers\nof <code>X</code> in <code>basis_funct</code> like this</p>\n\n<pre><code>X2 = X**2\nX3 = X**3\nX4 = X**4\nX5 = X**5\n...\nA = np.column_stack((ones, 1 - X, 1/2 * (2 - 4*X + X2), ...\n</code></pre>\n\n<p>saves an additional 100 milliseconds. Changing</p>\n\n<pre><code>itmPaths = [index for index,value in enumerate(K - S) if value > 0]\n</code></pre>\n\n<p>to</p>\n\n<pre><code>itmPaths = np.nonzero((K - S) > 0)[0]\n</code></pre>\n\n<p>brings the runtime down to about 1.60 seconds. I think you see the\npattern now; anytime you loop over a numpy array there's a numpy\nbuiltin function to do the job better and faster.</p>\n\n<p>Then in the calculation of <code>rest_paths</code>:</p>\n\n<pre><code>rest_paths = np.setdiff1d(np.arange(0, paths - 1, 1), exPaths)\n</code></pre>\n\n<p>Is the <code>paths - 1</code> intentional here? Looks like a bug to me. Assuming\nit is a bug, updating <code>P</code> can be done more efficiently, like this:</p>\n\n<pre><code>mask = np.zeros(P.shape, dtype = bool)\n...\nmask.fill(False)\nmask[itmPaths[Pt > C]] = True\n\nP[mask] = Pt[Pt > C]\nP[~mask] *= e_r_dt\n</code></pre>\n\n<h2>Final code</h2>\n\n<p>The modified code runs in about 420 milliseconds on my computer. Note\nthat I have removed all branches except for the <code>k == 5</code> one from the\n<code>basis_funct</code> function. It should be straightforward for you to add it\nback.</p>\n\n<pre><code>import sys\nimport numpy as np\n\n# Uncomment this line during development to always get the same random\n# numbers.\n# np.random.seed(1234)\n\ndef lsmput(T, r, sigma, K, S0, TimeSteps, paths, k):\n dt = T/TimeSteps\n t = np.arange(0, T+dt, dt).tolist()\n\n z = np.random.standard_normal(paths)\n w = (r-sigma**2/2)*T + sigma*np.sqrt(T)*z\n\n S = S0*np.exp(w)\n P = np.maximum(K - S,0)\n\n e_r_dt = np.exp(-r * dt)\n mask = np.zeros(P.shape, dtype = bool)\n for i in range(TimeSteps-1, -1, -1):\n z = np.random.standard_normal(paths)\n w = t[i]*w/t[i+1] + sigma*np.sqrt(dt*t[i]/t[i+1])*z\n\n S = S0 * np.exp(w)\n itmPaths = np.nonzero(K > S)[0]\n itmS = S[itmPaths]\n Pt = K - itmS\n\n itmDiscP = P[itmPaths] * e_r_dt\n\n A = basis_funct(itmS, k)\n beta = np.linalg.lstsq(A, itmDiscP)[0]\n C = np.dot(A, beta)\n\n mask.fill(False)\n mask[itmPaths[Pt > C]] = True\n\n P[mask] = Pt[Pt > C]\n P[~mask] *= e_r_dt\n return np.mean(P * e_r_dt)\n\ndef basis_funct(X, k):\n ones = np.ones(len(X))\n assert k == 5\n X2 = X**2\n X3 = X**3\n X4 = X**4\n X5 = X**5\n A = np.column_stack((ones, 1 - X,\n 1/2 * (2 - 4*X + X2),\n 1/6 * (6 - 18*X + 9*X2 - X3),\n 1/24 * (24 - 96*X + 72*X2 - 16*X3 + X4),\n 1/120 * (120 - 600*X + 600*X2 - 200*X3 + 25*X4 - X5)))\n return A\n\nfrom time import time\nstart = time()\nval = lsmput(1, 0.06, 0.15, 100, 90, 20, 40_000, 5)\nprint(f'Done in {time() - start:.3} seconds')\nprint(val)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-06T06:21:13.697",
"Id": "460073",
"Score": "0",
"body": "Hi Björn. Thank you so much. It works perfectly. I will go through your code in detail to understand the changes you made and learn from it."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-06T06:02:43.540",
"Id": "235150",
"ParentId": "235119",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "235150",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-05T16:56:54.423",
"Id": "235119",
"Score": "1",
"Tags": [
"python",
"performance",
"numpy",
"numba"
],
"Title": "Optimize option pricing code"
}
|
235119
|
<p>I am working on a little Python project to track how much time I am spending coding and doing things outdoors. Coding subtracts and outdoors stuff adds.</p>
<p>My code is looking pretty bad. Any suggestions on how to make it better?</p>
<pre class="lang-py prettyprint-override"><code>import tkinter as tk
import time
import json
import atexit
from flask import Flask
root = None
start_time = 0
end_time = 0
_add = False
_sub = False
entries_num = 0
_click = False
name = ''
_name = None
run_txt = None
def simplify(_time):
return time.strftime('%H:%M:%S', time.localtime(_time))
def simple_mode(mode):
if mode == 0:
return "Add"
elif mode == 1:
return "Subtract"
def start():
global start_time
start_time = int(time.time())
run_txt.configure(text="Running", fg="green")
def end():
global end_time
end_time = int(time.time())
run_txt.configure(text="Not Running", fg="red")
time_manager()
def find_mode():
if _add and not _sub:
return 0
elif _sub and not _add:
return 1
# 0 is add 1 is subtract
def time_manager():
global entries_num
entries_num += 1
mode = simple_mode(find_mode())
entry_raw = {'name': _name.get(), 'mode': mode, 'start': simplify(start_time), 'end': simplify(end_time), 'total_time': simplify(end_time-start_time-(-2211688800))}
entries.update({str(entries_num): entry_raw})
display()
def add():
global _add
global _sub
_add = True
_sub = False
def sub():
global _add
global _sub
_add = False
_sub = True
def display():
height = 1
width = 5
cells = {}
for i in range(height): # Rows
for j in range(width): # Columns
b = tk.Label(root, text="")
b.grid(row=i + 16 + entries_num, column=j)
cells[(i, j)] = b
cells[(0, 0)]['text'] = entries[str(entries_num)]['name']
cells[(0, 1)]['text'] = entries[str(entries_num)]['total_time']
cells[(0, 2)]['text'] = entries[str(entries_num)]['mode']
cells[(0, 3)]['text'] = entries[str(entries_num)]['start']
cells[(0, 4)]['text'] = entries[str(entries_num)]['end']
class MainApplication(tk.Frame):
def __init__(self, parent, *args, **kwargs):
tk.Frame.__init__(self, parent, *args, **kwargs)
self.parent = parent
title_lbl = tk.Label(root)
title_lbl['text'] = 'TimeTracker'
title_lbl.configure(font=('Roboto', 20))
title_lbl.grid(row=0, column=0, sticky='ew')
srt_btn = tk.Button(root, text="Start", command=start, font=('Roboto', 8)).grid(row=10, column=0, sticky='sw')
end_btn = tk.Button(root, text="End", command=end, font=('Roboto', 8)).grid(row=10, column=0, sticky='se')
add_btn = tk.Button(root, text="Add Time", command=add, font=('Roboto', 8)).grid(row=11, column=0, sticky='se')
sub_btn = tk.Button(root, text="Subtract Time", command=sub, font=('Roboto', 8))
sub_btn.grid(row=12, column=0, sticky='se')
global _name
_name = tk.Entry(root, width=50)
_name.grid(row=10, column=2)
_name.insert(0, "Entry Name")
_name.configure(state=tk.DISABLED)
def on_click(event):
_name.configure(state=tk.NORMAL)
_name.delete(0, tk.END)
# make the callback only work once
_name.unbind('<Button-1>', on_click_id)
on_click_id = _name.bind('<Button-1>', on_click)
global run_txt
run_txt = tk.Label(root)
run_txt.configure(text="Not Running", fg="red")
run_txt.grid(row=11, column=2)
def save():
with open('data.json', 'w') as fb:
_json = json.dumps(entries)
fb.write(_json)
if __name__ == "__main__":
root = tk.Tk()
with open('data.json', 'r') as fr:
text = fr.read()
entries = json.loads(text)
keys = entries.keys()
for key in keys:
entries_num = int(key)
display()
root.title("TimeTracker")
root.minsize(200, 400)
atexit.register(save)
MainApplication(root).grid()
root.mainloop()
</code></pre>
|
[] |
[
{
"body": "<p>The way you're handling add \"modes\" is a little clunky. It seems that only one of <code>_add</code> or <code>_sub</code> should ever be true at the same time. By making these two separate variables, you need to make sure that invariant is maintained everywhere. You've definitely helped make sure it's safe by using the <code>add</code> and <code>sub</code> functions, but those are band-aids on an awkward design.</p>\n\n<p>The easiest way to simplify this is just to have one variable. Something like:</p>\n\n<pre><code>_is_adding = True\n</code></pre>\n\n<p>If this is true you're adding, if it's not, you're subtracting. Now <code>find_mode</code> can be much simpler:</p>\n\n<pre><code>def find_mode():\n return 0 if _is_adding else 1\n</code></pre>\n\n<p>And <code>add</code> and <code>sub</code> simply becomes:</p>\n\n<pre><code>def add():\n global is_adding\n is_adding = True\n\ndef sub():\n global is_adding\n is_adding = False\n</code></pre>\n\n<p>Although,</p>\n\n<hr>\n\n<p>I think you're overusing globals here. In some cases, like UI callbacks, they may be the cleaner (but not only) option. <code>find_mode</code> for example though itself does not need to rely on globals. <em>If</em> you can cleanly pass data in instead of relying on globals, you should. I'd change it to:</p>\n\n<pre><code>def mode_number(is_adding: bool) -> int: # I added some type hints in and renamed it\n return 0 if is_adding else 1\n\n. . .\n\nmode = simple_mode(mode_number(_is_adding))\n</code></pre>\n\n<p>The gain here is incredibly small because of how simple the functions involved are. In general though, it's a good habit to get into. Functions that explicitly take as arguments all the data they need, and return all the data that they produce are much easier to understand. </p>\n\n<p><code>simple_mode</code> and <code>find_mode</code> are kind of odd though if you think about them. Why translate add/sub into a number just to then translate it back to <code>\"Add\"</code>/<code>\"Subtract\"</code>? I think this makes more sense:</p>\n\n<pre><code>def format_mode(is_adding: bool) -> str:\n return \"Add\" if is_adding else \"Subtracting\"\n\n. . .\n\nmode = format_mode(_is_adding)\n</code></pre>\n\n<hr>\n\n<p>I think <code>simplify</code> is a bad name for a function. What's it \"simplifying\"? If I'm writing a function that turns something into a string, I usually call it <code>format_*</code> (although that's just a habit of mine). Give some description though. I'd probably call it <code>format_time</code>, and adding some simple type hints make the types clearer:</p>\n\n<pre><code>def format_time(_time: int) -> str:\n return time.strftime('%H:%M:%S', time.localtime(_time))\n</code></pre>\n\n<p>I'm not sure I 100% agree with calling the parameter <code>_time</code> to avoid the name collision, since a prefix <code>_</code> typically means a \"private\" attribute, but I can't offhand think of a better name either, since the function is pretty broad in its purpose.</p>\n\n<hr>\n\n<pre><code>end_time-start_time-(-2211688800))\n</code></pre>\n\n<p>What the heck is -2211688800? That seems to offset the date by 70.1 years. Whatever it's purpose I see two problems:</p>\n\n<ul>\n<li><p>If that's meant to offset today's date to reach a certain format, it'll be outdated from the second it's written. You should see if you can automate the creation of that number.</p></li>\n<li><p>Magic numbers, especially large unusual like that should be named. Something like:</p>\n\n<pre><code>TIME_OFFSET = 2211688800\n\n. . .\n\nend_time - start_time - (-TIME_OFFSET)\n</code></pre></li>\n</ul>\n\n<p>Also, <code>x - (-y)</code> is the same as <code>x + y</code> (unless <code>x</code> and <code>y</code> are some custom type with odd math laws). It should just be:</p>\n\n<pre><code>end_time - start_time + TIME_OFFSET\n</code></pre>\n\n<hr>\n\n<p>The <code>Flask</code> import seems to be unneeded.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-05T23:35:06.860",
"Id": "460042",
"Score": "0",
"body": "Thank you! The Flask import is for later. I am planning to turn it into a web based system so multiple computers can use it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-05T23:44:26.057",
"Id": "460044",
"Score": "0",
"body": "I would like to implement a \"total time\" ticker and alarm, but, when I work with epoch time it starts adding hours like 00:00:01 + 00:00:02 = 06:00:03. The 2211688800 is because when I don't do that, the time adds 18:00:00 to the clock. With the number, It's fixed."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-06T00:10:06.080",
"Id": "460045",
"Score": "0",
"body": "I'm not sure I entirely understand what you mean, but I think you're adjusting for timezones there. You're in Chicago (I'm assuming), and I'm in Calgary; one hour apart in timezones. When I run this, the total time starts at 23:00:00, not 00:00:00. I'm honestly tired now so I don't think I'll be effective at looking into it in too much depth, but I think you offsetting it is just covering up a timezone bug. When you don't offset it, it's probably showing a time based on UTC."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-06T01:04:54.380",
"Id": "460048",
"Score": "0",
"body": "That makes more sense. I will update it to not offset at all and be accurate."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-06T01:10:23.957",
"Id": "460049",
"Score": "0",
"body": "@CruiseLickerman I'm not sure if you meant your actual code, or what you have posted here, but please don't change code in questions once it's been posted if you meant the latter."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-06T16:38:55.903",
"Id": "460142",
"Score": "0",
"body": "I meant my actual code."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-05T23:31:33.033",
"Id": "235136",
"ParentId": "235124",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "235136",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-05T18:37:43.320",
"Id": "235124",
"Score": "5",
"Tags": [
"python",
"python-3.x",
"json",
"tkinter"
],
"Title": "Time Tracker Project"
}
|
235124
|
<p>I've built a small utility in Python which is going to <em>supposedly</em> send an SMS (using <a href="https://www.twilio.com/" rel="noreferrer">Twilio</a>) each time an earthquake with the magnitude > 4 is to be happening.</p>
<blockquote>
<p><strong>NOTE:</strong></p>
<p>This simple script was mainly done for testing purposes and learning
activities. <strong>DO NOT</strong> take the information for granted as there might
be big delays between the time the earthquake occurs and the time the
SMS arrives.</p>
<p>More, this works only for <em>Romania, Europe</em> and it's using the data
from <a href="http://alerta.infp.ro" rel="noreferrer">this website</a> which is in a testing phase
(BETA).</p>
</blockquote>
<p>This should eventually run as a daemon on a UNIX OS. </p>
<p>I'd like to receive any kind of feedback regarding this and what could possibly be improved. </p>
<pre class="lang-py prettyprint-override"><code>"""
This projects aims to send an SMS to a specific number using Twilio
if an earthquake with magnitude > 4 is going to occur (depending on
your location, this can warn you (best case scenario within 25-30
seconds before you feel the earthquake wave).
"""
import datetime
import json
import re
import time
import requests
from exceptions import EmptyCredentialsFile
from lxml.html import fromstring
from twilio.rest import Client
BASE_URL = 'http://alerta.infp.ro'
DATA_URL = f'{BASE_URL}/server.php'
CREDENTIALS_FILE = 'credentials.json'
DELAY = 1 # seconds
def read_credentials_file(filepath: str) -> dict:
"""Return secrets from `credentials_file` file as a dict.
The file looks like this:
{
"TWILIO_ACCOUNT_SID": "Your twilio account SID",
"TWILIO_AUTH_TOKEN": "Your twilio account auth token",
"FROM": "The number from which you'll receive the alert",
"TO": "The number the message is sent to"
}
Args:
filepath (str): Path to credentials JSON file.
Returns:
dict: The return value.
"""
with open(filepath) as credentials_file:
credentials = json.load(credentials_file)
if not credentials:
raise EmptyCredentialsFile('Credentials file should not be empty.')
return credentials
def get_credential(name: str) -> str:
"""Return a specific credential value based on its name.
Args:
name (str): Name of the desired credential
Returns:
str: The return value
"""
credentials = read_credentials_file(CREDENTIALS_FILE)
return credentials.get(name)
def get_earthquake_data() -> dict:
"""Get earthquake data from `DATA_URL`.
Returns:
dict: A dict containing the following data:
{
'mag': '0.1',
'heart': '2020-01-04 13:30:04 HEARTBEAT',
'sec': '30',
'key': 'NjY2NDYyMzAzNjMwNjM2MzM1Mz...=='
}
"""
session = requests.Session()
with session as page_session:
html_page = page_session.get(BASE_URL).content
html_script = fromstring(html_page).xpath('//script[contains(., "source")]/text()')[0]
key = {
'keyto': re.search(
r"var source = new EventSource\('server\.php\?keyto=(.*)'\);", html_script
).group(1)
}
earthquake_data = page_session.get(f'{DATA_URL}', params=key).content
earthquake_data = earthquake_data.decode('utf8').replace("data", '"data"').strip()
return json.loads(f'{{{earthquake_data}}}')
def send_message() -> None:
"""Send a message via Twilio if the magnitude of an earthquake
is bigger than 4.
"""
twilio_client = Client(
get_credential('TWILIO_ACCOUNT_SID'),
get_credential('TWILIO_AUTH_TOKEN')
)
data = get_earthquake_data().get('data')
eq_magnitude = data.get('mag')
if float(eq_magnitude) >= 4:
body = f"""ATTENTION!!!
Earthquake with magnitude: {eq_magnitude}
at {datetime.datetime.strftime(datetime.datetime.now(), '%Y-%m-%d %H:%M:%S')}!
"""
try:
twilio_client.messages.create(
body=body,
from_=get_credential('FROM'),
to=get_credential('TO')
)
except Exception as error:
print(f'Twilio API error: {error}')
else:
print('No need to worry. YET!')
def main() -> None:
"""Main entry to the program."""
while True:
try:
send_message()
time.sleep(DELAY)
except KeyboardInterrupt:
print('Closing the program...')
if __name__ == '__main__':
main()
</code></pre>
<p>And the custom exception from <code>exceptions.py</code> looks like this:</p>
<pre class="lang-py prettyprint-override"><code>"""
Main module for all the exceptions across project.
"""
class EmptyCredentialsFile(Exception):
"""
Exception to be raised when credentials file is empty and valid
"""
pass
</code></pre>
<blockquote>
<p><strong>NOTE 2:</strong></p>
<p>If you'd like to run the whole script and don't have a Twilio account,
just call <code>get_earthquake_data()</code> instead of <code>send_message()</code>
function.</p>
</blockquote>
|
[] |
[
{
"body": "<p>I don't really see much that's notable. This is some nice looking code.</p>\n\n<p>Minor things though:</p>\n\n<p>If you're going to use type-hints, I think I'd take it a step further and use the generic <code>Dict</code> to specify what types the dictionaries hold:</p>\n\n<pre><code>from typing import Dict\n\n. . .\n\ndef get_earthquake_data() -> Dict[str, str]:\n . . .\n</code></pre>\n\n<p>And then similarly for the other cases. <code>dict</code> (currently?) doesn't support generic type hints, so <code>Dict</code>, a generic type alias, can be used. Now, for example:</p>\n\n<pre><code>data = get_earthquake_data()\nval = data[some_key] # It can typecheck the key now\nval # And it knows that this is a String\n</code></pre>\n\n<p>That also better communicates to the reader what types are involved. </p>\n\n<hr>\n\n<p>I'm on my phone so it's a pain to check, but here:</p>\n\n<pre><code>except Exception as error: \n print(f'Twilio API error: {error}')\n</code></pre>\n\n<p>Is there really not a more specific exception that Twilio throws? I'd see if it has its own base class that you can catch. You don't want to accidentally catch a non-API error there and mask a bug.</p>\n\n<hr>\n\n<pre><code>data = get_earthquake_data().get('data')\neq_magnitude = data.get('mag')\n</code></pre>\n\n<p>I'd probably use subscripting there instead of <code>get</code>. Sure, that will allow for a <code>KeyError</code>, but that will cause a more sensical error than it will if <code>None</code> is returned by <code>get</code> and you end up with <code>float(None)</code>. I only use <code>get</code> if I'm expecting a potentially invalid key and I want to handle it by checking the return for <code>None</code> (or a sentinal that I specify). I think avoiding the <code>KeyError</code> like this causes more issues than it solves by allowing bad data to be passed on instead of just dying where the error happened. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-06T06:56:08.543",
"Id": "460077",
"Score": "0",
"body": "Nice answer! +1. Those are all things that I've given a thought but didn't really do anything about it. What can you say about the naming? For me (and probably most developers) that's the hardest thing ^_^"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-06T14:42:36.223",
"Id": "460130",
"Score": "0",
"body": "@GrajdeanuAlex. No complaints they're all PEP8 compliant and descriptive."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-05T19:58:04.980",
"Id": "235129",
"ParentId": "235127",
"Score": "10"
}
},
{
"body": "<blockquote>\n <p><strong>NOTE 2:</strong></p>\n \n <p>If you'd like to run the whole script and don't have a Twilio account, just call <code>get_earthquake_data()</code> instead of <code>send_message()</code> function.</p>\n</blockquote>\n\n<p>You could improve this part by providing a command line option, so that</p>\n\n<pre><code>python eatrhquake.py\n</code></pre>\n\n<p>Would run <code>get_earthquake_data()</code>;</p>\n\n<pre><code>python earthquake.py --twilio\n</code></pre>\n\n<p>Would run <code>send_message()</code> with the default (credentials.json) file; and</p>\n\n<pre><code>python earthquake.py --twilio /path/to/my/credentials.json\n</code></pre>\n\n<p>Would run <code>send_message()</code> with a user provided file path.</p>\n\n<hr>\n\n<p>Python provides the <a href=\"https://docs.python.org/3/library/argparse.html#module-argparse\" rel=\"nofollow noreferrer\"><code>argparse</code></a> module for such case that you can define along the lines of</p>\n\n<pre><code>def command_line_parser():\n parser = argparse.ArgumentParser(description='Earthquake Listener')\n parser.add_argument(\n '-t', '--twilio',\n nargs='?',\n type=argparse.FileType('r'),\n const='credentials.json',\n help='<describe the file and its content here>')\n return parser\n</code></pre>\n\n<p>You can then use <code>parser.parse_args().twilio</code> to know which function to call depending on wether it is <code>None</code> or an opened file object.</p>\n\n<hr>\n\n<p>You also call <code>get_credentials()</code> a lot during the script lifetime, when you could call it only once and store the resulting dict in a variable instead. This is especially wasteful as it opens the file each time.</p>\n\n<p>In the same vein, you create a Twilio client at each loop even if you don't send anything. Art the very least you could create it only when you need to send something; at best you could create it once at the beginning of the script and reuse the same for each send, but I'm not familiar with the API and there may be some timeouts limiting this option.</p>\n\n<hr>\n\n<p>Proposed improvements:</p>\n\n<pre><code>\"\"\"\nThis projects aims to send an SMS to a specific number using Twilio\nif an earthquake with magnitude > 4 is going to occur (depending on\nyour location, this can warn you (best case scenario within 25-30\nseconds before you feel the earthquake wave).\n\"\"\"\n\nimport argparse\nimport datetime\nimport json\nimport re\nimport time\nfrom functools import partial\n\nimport requests\nfrom lxml.html import fromstring\nfrom twilio.rest import Client\n\n\nBASE_URL = 'http://alerta.infp.ro'\nDATA_URL = f'{BASE_URL}/server.php'\n\n\ndef command_line_parser():\n parser = argparse.ArgumentParser(description='Earthquake Listener')\n parser.add_argument(\n '-t', '--twilio',\n nargs='?',\n type=credentials,\n const='credentials.json',\n help='<???>')\n parser.add_argument(\n '-d', '--delay',\n type=float,\n default=1.0,\n help='delay in seconds between two calls to the earthquake API')\n return parser\n\n\ndef credentials(filepath: str) -> dict:\n \"\"\"Return secrets from `filepath` file as a dict.\n\n The file looks like this:\n\n {\n \"TWILIO_ACCOUNT_SID\": \"Your twilio account SID\",\n \"TWILIO_AUTH_TOKEN\": \"Your twilio account auth token\",\n \"FROM\": \"The number from which you'll receive the alert\",\n \"TO\": \"The number the message is sent to\"\n }\n\n\n Args:\n filepath (str): Path to credentials JSON file.\n\n Returns:\n dict: The return value.\n \"\"\"\n\n with open(filepath) as credentials_file:\n credentials = json.load(credentials_file)\n\n if not credentials:\n raise ValueError('Credentials file should not be empty.')\n\n return credentials\n\n\ndef get_earthquake_data() -> dict:\n \"\"\"Get earthquake data from `DATA_URL`.\n\n Returns:\n dict: A dict containing the following data:\n {\n 'mag': '0.1',\n 'heart': '2020-01-04 13:30:04 HEARTBEAT',\n 'sec': '30',\n 'key': 'NjY2NDYyMzAzNjMwNjM2MzM1Mz...=='\n }\n \"\"\"\n\n session = requests.Session()\n with session as page_session:\n html_page = page_session.get(BASE_URL).content\n html_script = fromstring(html_page).xpath('//script[contains(., \"source\")]/text()')[0]\n key = {\n 'keyto': re.search(\n r\"var source = new EventSource\\('server\\.php\\?keyto=(.*)'\\);\", html_script\n ).group(1)\n }\n earthquake_data = page_session.get(f'{DATA_URL}', params=key).content\n earthquake_data = earthquake_data.decode('utf8').replace(\"data\", '\"data\"').strip()\n return json.loads(f'{{{earthquake_data}}}')\n\n\ndef send_message(twilio_client, send_to, sent_from) -> None:\n \"\"\"Send a message via Twilio if the magnitude of an earthquake\n is bigger than 4.\n \"\"\"\n\n data = get_earthquake_data().get('data')\n eq_magnitude = data.get('mag')\n\n if float(eq_magnitude) >= 4:\n body = f\"\"\"ATTENTION!!!\n\n Earthquake with magnitude: {eq_magnitude} \n at {datetime.datetime.strftime(datetime.datetime.now(), '%Y-%m-%d %H:%M:%S')}!\n \"\"\"\n\n try:\n twilio_client.messages.create(body=body, from_=sent_from, to=send_to)\n except Exception as error:\n print(f'Twilio API error: {error}')\n else:\n print('No need to worry. YET!')\n\n\ndef main(credentials=None, delay=1.0) -> None:\n \"\"\"Main entry to the program.\"\"\"\n\n if credentials is None:\n action = get_earthquake_data\n else:\n twilio_client = Client(\n credentials['TWILIO_ACCOUNT_SID'],\n credentials['TWILIO_AUTH_TOKEN'])\n sender = credentials['FROM']\n receiver = credentials['TO']\n action = partial(send_message, twilio_client, receiver, sender)\n\n while True:\n try:\n action()\n time.sleep(delay)\n except KeyboardInterrupt:\n print('Closing the program...')\n\n\nif __name__ == '__main__':\n args = command_line_parser.parse_args()\n main(args.twilio, args.delay)\n</code></pre>\n\n<p>Note that I changed your custom exception to a <code>ValueError</code> to integrate better with <code>argparse</code>'s exception handling.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-09T13:18:24.190",
"Id": "235357",
"ParentId": "235127",
"Score": "3"
}
},
{
"body": "<p>In your main loop, you catch <code>KeyBoardInterrupt</code> without handling it or exiting, so if you press <code>Ctrl-C</code> during execution it prints the message and continues looping forever. You should add a <code>break</code> statement after the print statement to get out of this.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-09T16:19:24.733",
"Id": "460611",
"Score": "1",
"body": "Oupsiee, fair enough ^_^ That's why I love CR. Haven't even spotted something that obvious."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-09T15:50:31.357",
"Id": "235373",
"ParentId": "235127",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "235129",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-05T19:16:31.800",
"Id": "235127",
"Score": "9",
"Tags": [
"python",
"python-3.x"
],
"Title": "Will there be an earthquake?"
}
|
235127
|
<p>I am dipping my fingers in external apis that a user would login and retrieve a code to exchange for a token.
In my case, it is for the SpotifyAPI. </p>
<p>All the web app does it return the users top tracks of x amount of time.</p>
<p>Please note I havent done much cleaning up as im not entire sure whether my flow is secure and the correct way to do it</p>
<p>I have a basic flow of:</p>
<ol>
<li>User explicitly presses an Authorize Button</li>
<li>When authorized via the spotify api, they are redirected to a callback function where an authorization code is retrieved from the URL and passed to the server</li>
<li>The code is then used to exchange for a token and then I am able to perform api requests</li>
</ol>
<p><code>HomeComponent</code> which contains the button press to authorize the user - Step 1</p>
<pre><code>export class HomeComponent {
baseUrl: string;
http: HttpClient;
constructor(@Inject('BASE_URL') baseUrl: string, http: HttpClient){
this.baseUrl = baseUrl;
this.http = http;
}
//Called on button press
authenticate() {
this.http.get<string>(this.baseUrl + 'spotify/authenticate').subscribe(result => {
}, error => console.error(error));
}
}
</code></pre>
<p>authenticate calls through to an angular component which passed the code to this Web API method (will remove singleton in future) - Step 2</p>
<pre><code>[HttpGet]
[Route("authenticate")]
public void Authenticate()
{
AuthSingleton.auth = new AuthorizationCodeAuth(
"clientID",
"secretID",
"https://localhost:44345/top",
"http://localhost:4002",
Scope.UserTopRead
);
AuthSingleton.auth.Start(); // Starts an internal HTTP Server
AuthSingleton.auth.OpenBrowser();
}
</code></pre>
<p>This starts the authentication where the Spotify "login page" appears.</p>
<p>Once logged in, the callback then calls this Web API method - Step 3</p>
<pre><code>[HttpGet]
[Route("top")]
public async Task<OkObjectResult> Top(string code)
{
AuthSingleton.auth.Stop();
if (code != null)
{
//Code used to get token
Token token = await AuthSingleton.auth.ExchangeCode(code);
SpotifyWebAPI api = new SpotifyWebAPI();
if (token.IsExpired())
{
Token refreshToken = await AuthSingleton.auth.RefreshToken(token.RefreshToken);
api.AccessToken = refreshToken.AccessToken;
api.TokenType = refreshToken.TokenType;
}
else
{
api.TokenType = token.TokenType;
api.AccessToken = token.AccessToken;
}
//Api Requests
Paging<FullTrack> shortTermTracks = api.GetUsersTopTracks(TimeRangeType.ShortTerm);
MappedTracks mappedTracks = TrackMapper.MapTracks(shortTermTracks);
//Return the top tracks
return Ok(mappedTracks);
}
return null;
}
</code></pre>
<p>Is this an okay way of doing what I am trying to achieve?</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-05T20:13:43.377",
"Id": "235130",
"Score": "3",
"Tags": [
"c#",
"angular-2+"
],
"Title": "Correct and safe way of performing token exchange?"
}
|
235130
|
<p>I wrote this program for a Sudoku solver in Python. It utilizes <code>tkinter</code> GUI. I've uploaded the project to my <a href="https://github.com/MGedney1/Sudoku_Solver" rel="nofollow noreferrer">GitHub</a>.</p>
<p>Please can you have a look and let me know of any ideas or improvements you think I should make?</p>
<pre class="lang-py prettyprint-override"><code>from tkinter import Frame,Entry,Button,messagebox
class app(Frame):
def __init__(self): #Initialising
Frame.__init__(self)
self.grid()
self.create_grid() #Creating the sudoku grid
self.create_buttons() #Creating the reset and solve buttons
def create_grid(self):
self.cells = {} #Creating a dict for the cells in the grid
self.tableheight = 9
self.tablewidth = 9
counter = 0
for row in range(self.tableheight): #Iterating through the rows and columns creating entries
for col in range(self.tablewidth):
self.cells[counter] = Entry(self,width=5,justify='center') #Creating the Entry
if (counter % 3==2): #Creating extra vertical breaks to split into 3x3 boxes
pad_x = (3,10)
else:
pad_x = 3
if ((counter // 9) == 2) or ((counter // 9) == 5): #Creating extra horizontal breaks to split into 3x3 boxes
pad_y = (3,10)
else:
pad_y = 3
if (counter % 9) == 0: #Extra space to the sides of the board
pad_x = (25,3)
elif (counter % 9) == 8:
pad_x = (3,25)
if (counter // 9) == 0:
pad_y = (25,3)
elif (counter // 9) == 8:
pad_y = (3,25)
self.cells[counter].grid(row=row,column=col,padx=pad_x,pady=pad_y) #Setting in a grid and adding padding
counter+=1
self.master.bind('<Up>',self.up) #Key bindings to move between cells
self.master.bind('<Left>',self.left)
self.master.bind('<Right>',self.right)
self.master.bind('<Down>',self.down)
def up(self,event):
current_cell = str(self.focus_get())[12:] #Splitting the string of default entry names to get the number
if len(current_cell) == 0: #Naming started with no number at the end so setting to 1
current_cell = '1'
current_cell = int(current_cell) - 1 #Getting the current cell index
row = current_cell//9 #Finding the row the cell is on
if row == 0: #Getting new row
new_row = 8
else:
new_row = row -1
next_cell = new_row*9 + (current_cell % 9) #Getting index of target cell
self.cells[next_cell].focus_set() #Setting focus to new entry
def left(self,event):
current_cell = str(self.focus_get())[12:] #Splitting the string of default entry names to get the number
if len(current_cell) == 0: #Naming started with no number at the end so setting to 1
current_cell = '1'
current_cell = int(current_cell) - 1 #Getting the current cell index
if (current_cell == 0): #Index of new entry
next_cell = 80
else:
next_cell = current_cell - 1
self.cells[next_cell].focus_set() #Setting focus to new entry
def right(self,event):
current_cell = str(self.focus_get())[12:] #Splitting the string of default entry names to get the number
if len(current_cell) == 0: #Naming started with no number at the end so setting to 1
current_cell = '1'
current_cell = int(current_cell) - 1 #Getting the current cell index
if (current_cell == 80): #Index of new entry
next_cell = 0
else:
next_cell = current_cell + 1
self.cells[next_cell].focus_set() #Setting focus to new entry
def down(self,event):
current_cell = str(self.focus_get())[12:] #Splitting the string of default entry names to get the number
if len(current_cell) == 0: #Naming started with no number at the end so setting to 1
current_cell = '1'
current_cell = int(current_cell) - 1 #Getting the current cell index
row = current_cell//9 #Finding the row the cell is on
if row == 8: #Getting new row
new_row = 0
else:
new_row = row + 1
next_cell = new_row*9 + (current_cell % 9) #Getting index of target cell
self.cells[next_cell].focus_set() #Setting focus to new entry
def create_buttons(self): #Creating buttons
self.reset = Button(self,text='Reset',command=self.reset_values) #Reset
self.reset.grid(row=11,column=1)
self.solve = Button(self,text='Solve',command=self.solve_sudoku) #Solve
self.solve.grid(row = 11, column=7)
def reset_values(self): #Reset entries
for counter in range(81):
self.cells[counter].delete(0,'end')
self.cells[counter].configure(fg='black')
def check_values(self): #Checks cell values are allowed
self.fetch_values () #Fetching values
self.cells_given = 0
for x in self.cells_list: #Checking the number of cells intially filled is greater than 17 to allow for unique solution
if x != 0:
self.cells_given += 1
if (self.cells_given < 17): #Less than 17 enteries results in non unique solution
messagebox.showwarning('Non Unique Solution','Entering less that 17 initial cells means the solution can not be unique')
self.different_values_given = len(list(set(self.cells_list))) #Getting length of the list of unique cell values given
if self.different_values_given < 9: #Checking the number of different values given is greater than 9 (8 for unique sudoku but this also counts 0)
messagebox.showwarning('Non Unique Solution','Entering less than 8 different intial values means the solution can not be unique.')
self.convert_to_board() #Getting the list of cell values in a board format
for row in range(9): #iterating through each cell
for col in range(9):
value = self.board[row][col]
if value!=0:
if (self.check_valid(row,col,value)): #Check for violations of sudoku rules at start
print(row,col)
messagebox.showerror('Entry Error','Initial board contains violation of Sudoku rules')
def fetch_values(self): #Gets cell values from board
self.cells_list = list(self.cells.values()) #Getting the cell values as a list
for x in range(81):
self.cells_list[x] = self.cells_list[x].get()
if (self.cells_list[x] not in ['','0','1','2','3','4','5','6','7','8','9']): #Checking the cell values are allowed
messagebox.showerror('Value Error','Please ensure all enteries are between 1-9.\nLeave empty cells blank.')
self.reset_values()
raise Sudoku_Error()
if (self.cells_list[x] == ''): #Converting empty cells to 0s
self.cells_list[x] = '0'
self.cells[x].configure(fg='blue')
self.cells_list[x] = int(self.cells_list[x]) #Converting cell values from strings to integers
def convert_to_board(self): #Converting from a list length 81 to list of 9 lists length 9
self.board = []
for iteration in range(9): #Iterating through different rows
row = []
for pos in range(iteration*9,(iteration+1)*9): #Iterating through different columns in the set row
row.append(self.cells_list[pos]) #Appending to the current rows list
self.board.append(row) #Appending row list to the board
def check_valid(self,row,col,value): #Checking if a test value is valid
row_valid = all([value != x for x in self.board[row]])#grid[row][x] for x in range(9)]) #Check if value violates row condition
col_valid = all([value != self.board[y][col] for y in range(9)]) #Check if value violates column condition
if not(row_valid and col_valid): #Returning false unless value is valid for both row and column constraints
return False
box_start_row,box_start_col = 3*(row//3),3*(col//3) #Finding the position values for top left of the 3x3 box which the current test cell resides in
for y in range(box_start_row,box_start_row + 3): #Checking if test value violates box condition
for x in range(box_start_col,box_start_col + 3):
if self.board[y][x] == value:
return False
return True
def solve_sudoku(self): #Solving
self.check_values() #Checking intitial
self.solve_initial() #Initial solving algorithm
self.publish_answer() #Publishing results
def solve_initial(self):
repeat = False #Setting a variable to repeat if grid was changed this iteration
for row in range(9):
for col in range(9):
if self.board[row][col] == 0:
possible_values = [1,2,3,4,5,6,7,8,9] #Setting possible values before other cell's value contraints
row_values = [self.board[row][x] for x in range(9)] #Getting values from the cells row
col_values = [self.board[y][col] for y in range(9)] #Getting values from the cells column
box_values = []
box_start_row,box_start_col = 3*(row//3),3*(col//3)
for y in range(box_start_row,box_start_row + 3): #Getting values from the cells box
for x in range(box_start_col,box_start_col + 3):
box_values.append(self.board[y][x])
restricted_values = row_values + col_values + box_values #Combining to get the total list of values not allowed
restricted_values = list(set(restricted_values)) #Removing duplicates
restricted_values.remove(0) #Have to remove 0 as that isnt a possible value for completed suduko
for value in restricted_values: #Removing the restricted values from the possible value list
possible_values.remove(value)
if len(possible_values) == 1: #If only one possible value, set that value and set repeat to true
self.board[row][col] = possible_values[0]
repeat = True
if repeat: #Repeating if repeat is true
self.solve_initial()
if (self.solve_brute()): #If not repeating attempt brute force to check if solved and if not then finish
return
def solve_brute(self,row = 0,col = 0): #Solve function with inital params for row and col set
row, col = self.next_cell(row,col)
if (row == -1) and (col == -1): #If no more cells to solve, return completed grid
return True
for value in range(1,10):
if self.check_valid(row,col,value):
self.board[row][col] = value #Updating the cell to the new value if it is valid
if self.solve_brute(row,col):
return True
self.board[row][col] = 0 #Reset the current cell to unfilled for backtracking
return False
def next_cell(self,row,col): #Finding the next cell to fill
for y in range(row,9): #Check grid from min row col values for unfilled cells (treating 0 as unfilled)
for x in range(col,9):
if self.board[y][x] == 0:
return y,x
for y in range(9): #Check entire grid for unfilled cells
for x in range(9):
if self.board[y][x] == 0:
return y,x
return -1,-1 #Returns -1,-1 if all cells filled
def publish_answer(self):
self.answer_cells = []
for y in range(9):
for x in range(9):
self.answer_cells.append(self.board[y][x])
for pos in range(81):
if (self.cells_list[pos] == 0):
self.cells[pos].insert(0,self.answer_cells[pos])
class Sudoku_Error(Exception):
pass
prog = app()
prog.master.title('Sudoku Solver')
prog.mainloop()
</code></pre>
|
[] |
[
{
"body": "<h1>Class Names</h1>\n\n<p>Classes should be in <code>PascalCase</code>, not <code>lowercase</code>. So your class should be <code>App</code>.</p>\n\n<h1>Operator Spacing</h1>\n\n<p>There should be a space before and after every operator (<code>+-*/=</code>, etc) in your program. It improves the readability of your code greatly.</p>\n\n<h1>Comments</h1>\n\n<p>When commenting, it's common to put them a line before, so the reader sees the comment then the preceding line of code that the comment addresses. Inline comments, especially when really long like yours, are unnecessary.</p>\n\n<h1><code>check_valid</code></h1>\n\n<p>You can greatly simplify how you check a valid sudoku board. Using <a href=\"https://docs.python.org/3/library/functions.html#any\" rel=\"nofollow noreferrer\"><code>any</code></a>, it will return True if any of the element in the iterator are True. But in this case, since you want all <code>False</code> values to be checked, simply do <code>not any(...)</code>. Take a look:</p>\n\n<pre><code>def check_valid(self,row,col,value):\n\n row_valid = all([value != x for x in self.board[row]])\n col_valid = all([value != self.board[y][col] for y in range(9)])\n\n if not(row_valid and col_valid):\n return False\n\n box_start_row, box_start_col = 3 * (row // 3), 3 * (col // 3)\n\n return not any(\n self.board[y][x] == value\n for y in range(box_start_row, box_start_row + 3)\n for x in range(box_start_col, box_start_col + 3)\n )\n</code></pre>\n\n<h1>Contants</h1>\n\n<p>I see you've defined <code>self.tableheight</code> and <code>self.tablewidth</code> as constants (although they should be <code>snake_case</code> then <code>UPPER_CASE</code>). That's good. But you only use them once and never again! Then you have stray <code>9</code> values all over your code. You should utilize these class constants.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-18T22:52:10.610",
"Id": "237518",
"ParentId": "235133",
"Score": "1"
}
},
{
"body": "<p>I strongly feel that you should separate the logic of the graphics and the algorithm of solving the sudoku. The algorithm is just some operation defined on some data structure of your choosing (actually a good way to regard solving sudokus is as extending a colouring of a graph). </p>\n\n<p>I would write this algorithm to act on whatever data structure is most convenient and makes the algorithm as evident as possible. </p>\n\n<p>Then have functions to adapt between the algorithm representation and the board internal representation.</p>\n\n<p>Then have functions which take you from the boards internal representation to the GUI representation.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-18T23:02:59.207",
"Id": "237521",
"ParentId": "235133",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-05T21:01:07.957",
"Id": "235133",
"Score": "2",
"Tags": [
"python",
"algorithm",
"python-3.x",
"sudoku"
],
"Title": "Python Sudoku Solver"
}
|
235133
|
<p>I created a script supposed to use python to autocomplete Python commands. The full code is available <a href="https://gist.github.com/gndu91/d09f7bb42956eea08a0f4a6b3d6d5b93" rel="nofollow noreferrer">here</a>, however, I can give you an example. For instance, let's consider:</p>
<ul>
<li><code>command</code>, the command I want to give completion to (it does not have to actually exist).</li>
<li><code>script.py</code>, the auto completion script.</li>
</ul>
<pre class="lang-py prettyprint-override"><code>import os, shlex
def complete(current_word, full_line):
split = shlex.split(full_line)
prefixes = ("test", "test-中文", 'test-한글')
items = list(i + "-level-" + current_word for i in prefixes)
word = "" if len(split) - 1 < int(current_word) else split[int(current_word)]
return list(i for i in items if i.startswith(word))
if __name__ == "__main__":
os.sys.stdout.write(" ".join(complete(
*os.sys.argv.__getitem__(slice(2, None)))))
os.sys.stdout.flush()
</code></pre>
<p>The following script can be executed directly into the shell, or added in the .bashrc to keep the changes persistent.</p>
<pre class="lang-bsh prettyprint-override"><code>__complete_command() {
COMPREPLY=($(python3 script.py complete $COMP_CWORD "${COMP_LINE}"));
};
complete -F __complete_command command
</code></pre>
<p>Tested on Ubuntu 18.04 with python 3.8.
If you want, you can type the following in a new console</p>
<pre class="lang-bsh prettyprint-override"><code>cd $(mktemp -d)
__complete_command() {
COMPREPLY=($(python3 script.py complete $COMP_CWORD "${COMP_LINE}"));
};
complete -F __complete_command command
echo '
import os, shlex
def complete(current_word, full_line):
split = shlex.split(full_line)
prefixes = ("test", "test-中文", "test-한글")
items = list(i + "-level-" + current_word for i in prefixes)
word = "" if len(split) - 1 < int(current_word) else split[int(current_word)]
return list(i for i in items if i.startswith(word))
if __name__ == "__main__":
os.sys.stdout.write(" ".join(complete(
*os.sys.argv.__getitem__(slice(2, None)))))
os.sys.stdout.flush()' > script.py
</code></pre>
<p>Is it the most efficient way to do this?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-08T09:00:14.060",
"Id": "460380",
"Score": "0",
"body": "The documentation for `complete` is in the Bash man page, under \"Builtin Commands\". On some systems there's a separate `bash-builtins` man page for convenience."
}
] |
[
{
"body": "<pre><code>list(i for i in items if i.startswith(word))\n</code></pre>\n\n<p>This is just a list comprehension with extra steps (and overhead). If you want a list as an end result, wrap the comprehension in <code>[]</code>, not <code>()</code>.</p>\n\n<pre><code>[i for i in items if i.startswith(word)]\n</code></pre>\n\n<p>You were using a generator expression to produce a generator, then forcing it by putting it into a list.</p>\n\n<p>Then, the same change can be made to the definition of <code>items</code>. This will be more efficient, and looks cleaner anyway.</p>\n\n<hr>\n\n<p>If you're only supporting newer versions of Python (3.7+), I think <a href=\"https://www.python.org/dev/peps/pep-0498/#rationale\" rel=\"nofollow noreferrer\">f-strings</a> would also neaten up <code>items</code>:</p>\n\n<pre><code>items = [f\"{i}-level-{current_word}\" for i in prefixes]\n</code></pre>\n\n<hr>\n\n<pre><code>\"\" if len(split) - 1 < int(current_word) else split[int(current_word)]\n</code></pre>\n\n<p>I think the condition is complex/varied enough that it takes a couple looks to see the <code>else</code>. Personally, I'd wrap the condition in parenthesis:</p>\n\n<pre><code>\"\" if (len(split) - 1 < int(current_word)) else split[int(current_word)]\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-06T23:16:03.977",
"Id": "460201",
"Score": "0",
"body": "Do you have an idea of where to search for the 'complete' definition, because I even looked up COMP_LINE in the entire linux repository (https://github.com/torvalds/linux/search?q=COMP_LINE&type=Code), the coreutil one (I downloaded it and ran \"grep -r . -e 'COMP_LINE'\"), but nothing appears, I even tried xterm, gnome-terminal, but there is no trace of this function. I tried to use forkstat to get the process but nothing."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-06T23:18:22.257",
"Id": "460202",
"Score": "0",
"body": "@NadirGhoul Couldn't tell you. Coincidently, I just used Linux for the first time today."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-14T06:24:14.177",
"Id": "461232",
"Score": "0",
"body": "You have searched a lot of unrelated sources, but not the Bash sources. https://github.com/bminor/bash/search?q=COMP_LINE&unscoped_q=COMP_LINE"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-14T11:19:45.730",
"Id": "461251",
"Score": "0",
"body": "@tripleee Nope. I only started using the bash and Linux a little over a week ago like I said. I'm still becoming familiar with it myself."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-05T23:56:54.247",
"Id": "235140",
"ParentId": "235134",
"Score": "6"
}
},
{
"body": "<h3>Splitting words</h3>\n\n<p>The Python script splits the shell command's full line to words using <code>shlex</code>.\nI see a few issues with this:</p>\n\n<ol>\n<li><p>I'm not sure this will split the line exactly the same way as the shell would. Looking at <code>help(shlex)</code>, I see <em>\"A lexical analyzer class for simple shell-like syntaxes\"</em>, and I find that not very reassuring.</p></li>\n<li><p>I think command line completion should be blazingly fast, so I look suspiciously at anything that needs to be <code>import</code>-ed, such as <code>shlex</code>.</p></li>\n<li><p>Looking at the <strong>Programmable Completion</strong> section in <code>man bash</code>, it seems that Bash populates the <code>COMP_WORDS</code> array with the result of the split.</p></li>\n</ol>\n\n<p>Therefore, it would be good to pass <code>COMP_WORDS</code> to the Python script,\nwhich would eliminate all the above concerns.</p>\n\n<p>One way to achieve this would be to call the Python script with:</p>\n\n<pre><code>python3 script.py complete \"$COMP_CWORD\" \"${COMP_WORDS[@]}\"\n</code></pre>\n\n<p>And then change the Python script accordingly:</p>\n\n<pre><code>#!/usr/bin/env python3\n\nimport sys\n\n\ndef complete(comp_cword, *comp_words):\n prefixes = (\"test\", \"test-中文\", \"test-한글\")\n word = comp_words[int(comp_cword)]\n items = (prefix + \"-level-\" + comp_cword for prefix in prefixes)\n return (item for item in items if item.startswith(word))\n\n\nif __name__ == \"__main__\":\n sys.stdout.write(\" \".join(complete(*sys.argv[2:])))\n sys.stdout.flush()\n</code></pre>\n\n<h3>Avoid converting generators to list when not needed</h3>\n\n<p>No lists were needed in the original script, everything could have been just generator expressions.</p>\n\n<h3>Keep it simple</h3>\n\n<p>I don't understand why the script imports <code>os</code> and uses <code>os.sys</code> and nothing else in <code>os</code>.\nYou could just <code>import sys</code> instead.</p>\n\n<p>I don't understand why <code>sys.argv.__getitem__(slice(2, None))</code> was used instead of the simple and natural <code>sys.argv[2:]</code>.</p>\n\n<hr>\n\n<p>This line is complex, it takes attention to understand:</p>\n\n<blockquote>\n<pre><code>word = \"\" if len(split) - 1 < int(current_word) else split[int(current_word)]\n</code></pre>\n</blockquote>\n\n<p>This is a lot easier to understand:</p>\n\n<pre><code>if len(split) - 1 < int(current_word):\n word = \"\"\nelse:\n word = split[int(current_word)]\n</code></pre>\n\n<p>Looking further, <code>word</code> is used only in a filter <code>.startswith(word)</code>.\nThat filter will match every string.\nIn which case, to maximize performance,\nit would be best to not create <code>word</code>, and not do any filtering,\nbut return <code>items</code> directly:</p>\n\n<pre><code>if len(split) - 1 < int(current_word):\n return items\n</code></pre>\n\n<p>On even closer look,\nI don't see how <code>COMP_CWORD</code> can ever be an index out of range.\nSo the check for bounds was unnecessary.\n(Strictly speaking, an index out of bounds may be possible when splitting words with <code>shlex</code>, since that might not be identical to the shell's own word splitting. Even then, it would be a highly unlikely case, therefore a more Pythonic way to handle the situation would be using a <code>try-expect</code> for a <code>IndexError</code>.)</p>\n\n<h3>Use better names</h3>\n\n<p>The name <code>i</code> is really best reserved for loop counters.\n(Even then, often you may find better names...)</p>\n\n<p>In the suggested solution above I renamed the parameter names to match the shell variables they come from.\nI find this reduces the cognitive burden when reading the documentation of the variables in <code>man bash</code>, and the implementation of the completion code in Python.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-20T19:17:10.647",
"Id": "472610",
"Score": "0",
"body": "Thanks for the answer, `man bash` was the resource I was looking for (I could find the necessary explanations about the variables). Also, the reason I used __getitem__ was because my keyboard was broken and I was unable to type [."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-20T19:20:21.177",
"Id": "472612",
"Score": "0",
"body": "The line `word = \"\" if len(split) - 1 < int(current_word) else split[int(current_word)]` was here because, for instance if I am at the beginning of a new word, the split list will only contain the completed words, but not the current word (because empty)."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-11T22:20:20.347",
"Id": "235487",
"ParentId": "235134",
"Score": "7"
}
},
{
"body": "<p>Your <code>sys.stdout.write</code> + <code>flush</code> is a fancy <code>print</code> call... You could just write</p>\n\n<pre><code>if __name__ == '__main__':\n print(*complete(*sys.argv[2:]), end='', flush=True)\n</code></pre>\n\n<p>instead.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-13T12:25:57.413",
"Id": "235554",
"ParentId": "235134",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "235487",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-05T22:49:05.163",
"Id": "235134",
"Score": "6",
"Tags": [
"python",
"python-3.x",
"bash",
"autocomplete"
],
"Title": "Implement bash auto completion in Python"
}
|
235134
|
<p>I am trying to solve this question <a href="https://leetcode.com/problems/count-of-smaller-numbers-after-self/" rel="nofollow noreferrer">https://leetcode.com/problems/count-of-smaller-numbers-after-self/</a></p>
<blockquote>
<p>You are given an integer array nums and you have to return a new
counts array. The counts array has the property where counts[i] is the
number of smaller elements to the right of nums[i].</p>
</blockquote>
<p>My code:</p>
<pre><code>import bisect
from functools import lru_cache
def merge(a, b):
i, j = 0, 0
res = []
while i < len(a) and j < len(b):
if a[i] < b[j]:
res.append(a[i])
i += 1
else:
res.append(b[j])
j += 1
while i < len(a):
res.append(a[i])
i += 1
while j < len(b):
res.append(b[j])
j += 1
return res
class SegmentTree:
def __init__(self, nums):
self.nums = nums
self.tree = [0] * (len(nums)*4)
if len(nums)>0:
self._build()
def _build(self):
def build(l, r, index):
if l == r:
self.tree[index] = [self.nums[l]]
return self.tree[index]
else:
mid = (l+r)//2
left_set = build(l, mid, index*2)
right_set = build(mid+1, r, index*2+1)
m = merge(left_set, right_set)
self.tree[index] = m
return m
build(0, len(self.nums)-1, 1)
def get_range(self, l, r):
@lru_cache(maxsize=None)
def get_range(left_boundary, right_boudndary, index, l, r):
if l > r:
return []
if left_boundary == right_boudndary:
return self.tree[index]
if left_boundary == l and right_boudndary == r:
return self.tree[index]
else:
mid = (left_boundary + right_boudndary)//2
left = get_range(left_boundary, mid, index*2, l, min(r, mid))
right = get_range(mid+1, right_boudndary,
index*2+1, max(l, mid+1), r)
return merge(left, right)
return get_range(0, len(self.nums)-1, 1, l, r)
class Solution:
def countSmaller(self, nums: List[int]) -> List[int]:
s = SegmentTree(nums)
result = []
for i in range(len(nums)):
res = s.get_range(i+1, len(nums)-1)
ans = bisect.bisect(res, nums[i]-1)
result.append(ans)
return result
</code></pre>
<p>Sadly this times out on the last case :(</p>
<p>How do I speed this up? </p>
<p>(To be clear: I am looking for a faster solution with segment trees, not fenwick tree)</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-06T12:36:59.777",
"Id": "460116",
"Score": "0",
"body": "Could you please add some test cases?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-06T12:37:59.967",
"Id": "460117",
"Score": "0",
"body": "Note: you can probably just build the tree down-up and not up-down. This will remove the recursion and will be alot faster."
}
] |
[
{
"body": "<p>So, the time complexity of the solution posted in the question is <code>O(n^2 log(n))</code>.</p>\n\n<p>Answering each query takes <code>n log(n)</code>, and we have <code>n</code> queries in total. </p>\n\n<p>We don't necessarily need to merge the left and right subtrees to find the inversion count; given that the sublists are sorted, we can exploit binary search.</p>\n\n<pre><code>import bisect\n\nfrom functools import lru_cache\n\ndef merge(left, right):\n res = []\n i, j = 0, 0 \n while i<len(left) and j<len(right):\n if left[i]<right[j]:\n res.append(left[i])\n i+=1 \n else:\n res.append(right[j])\n j+=1 \n\n while i<len(left):\n res.append(left[i])\n i+=1 \n while j<len(right):\n res.append(right[j])\n j+=1 \n return res\n\n\nclass SegmentTree:\n def __init__(self, nums):\n self.nums = nums \n self.tree = {}\n if len(nums)>0:\n self._build(0, len(nums)-1, 1)\n def _build(self, l, r, index):\n if l==r:\n self.tree[index] = [self.nums[r]]\n return self.tree[index]\n else:\n mid = (l+r)//2 \n left= self._build(l, mid, index*2)\n right = self._build(mid+1, r, index*2+1)\n self.tree[index] = merge(left, right)\n return self.tree[index]\n\n def get_range(self, l,r, target):\n def get_range(left_boundary, right_boundary, l, r, index):\n if l>r:\n return 0 \n if left_boundary == right_boundary or (left_boundary == l and right_boundary==r):\n return bisect.bisect(self.tree[index], target)\n else:\n mid = (left_boundary+ right_boundary)//2 \n left = get_range(left_boundary, mid, l, min(r, mid), index*2)\n right = get_range(mid+1, right_boundary, max(l, mid+1), r, index*2+1)\n return left+right\n return get_range(0, len(self.nums)-1, l, r, 1)\n\nclass Solution:\n def countSmaller(self, nums: List[int]) -> List[int]:\n s = SegmentTree(nums)\n result = []\n for i in range(len(nums)):\n res = s.get_range(i+1, len(nums)-1, nums[i]-1)\n result.append(res)\n return result\n\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-06T12:48:18.567",
"Id": "235163",
"ParentId": "235139",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "235163",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-05T23:54:58.080",
"Id": "235139",
"Score": "2",
"Tags": [
"python",
"algorithm",
"time-limit-exceeded"
],
"Title": "python segment tree - count of smaller numbers after self"
}
|
235139
|
<p>The following is the entire function for implementing a doubly linked list. Can anyone show me if there is a better way to write these functions, especially the <code>delete_at</code> function please?</p>
<pre><code>#include<stdio.h>
#include<stdlib.h>
typedef struct linked_list
{
int point;
struct linked_list *p_node;
struct linked_list *n_node;
}node;
node *create_head_node(node *, int);
node *insert_head(node *, int);
void insert_tail(node *, int);
node *insert_at(node *, int, int);
int count_node(node *);
void print_list(node *);
node *delete_tail(node *);
node *delete_head(node *);
node *delete_at(node *, int);
node *create_head_node(node *head, int point){
head->point=point;
head->p_node=NULL;
head->n_node=NULL;
return head;
}
node *insert_head(node *head, int point){
if (head==NULL){
printf("no head exist");
return 0;
}
node *temp=(node*)malloc(sizeof(node));
temp->point=point;
temp->p_node=NULL;
temp->n_node=head;
head->p_node=temp;
head=temp;
return head;
}
void insert_tail(node *head, int point){
if (head==NULL){
printf("no head exist");
return;
}
node *p=head;
node *temp=(node*)malloc(sizeof(node));
temp->point=point;
temp->n_node=NULL;
while (p->n_node!=NULL)
{
p=p->n_node;
}
p->n_node=temp;
temp->p_node=p;
}
node *insert_at(node *head, int point, int pos){
if (head==NULL){
printf("no head exist");
return 0;
}
int count=count_node(head);
while (pos>count)
{
printf("choose %d positions to add. choose again: ", count); scanf("%d", &pos);
}
node *p=head;
for (int i = 0; i < pos; i++)
{
p=p->n_node;
}
node *temp=(node*)malloc(sizeof(node));
temp->point=point;
temp->n_node=p;
temp->p_node=p->p_node;
if(p->p_node!=NULL) p->p_node->n_node=temp;
p->p_node=temp;
return head;
}
int count_node(node *head){
node *p=head;
int count=0;
while (p!=NULL)
{
count++;
p=p->n_node;
}
free(p);
return count;
}
void print_list(node *head){
if (head==NULL){ printf("nothing to print"); return;}
node *p=head;
while (p!=NULL)
{
printf("%d ", p->point);
p=p->n_node;
}
}
node *delete_head(node *head){
if (head==NULL){
printf("no head exist\n");
return 0;
}
node *p=head;
// head->p_node=NULL;
if(p->n_node!=NULL){
head=p->n_node;
free(p);
}
else head=NULL;
return head;
}
node *delete_tail(node *head){
if (head==NULL){
printf("no head exist\n");
return 0;
}
node *p=head;
while (p->n_node!=NULL)
{
p=p->n_node;
}
if (p->p_node!=NULL){
p->p_node->n_node=NULL;
free(p);
}
else head=NULL;
return head;
}
node *delete_at(node *head, int pos){
int count=count_node(head);
if(head==NULL){
printf("no head exist");
return 0;
}
while (count<pos)
{
printf("choose %d positions to delete. choose again", count); scanf("%d", &pos);
}
node *p=head;
if(pos==0) head=delete_head(head);
else if(pos==count-1) head=delete_tail(head);
else{
for (int i = 0; i < pos; i++)
{
p=p->n_node;
}
p->p_node->n_node=p->n_node;
p->n_node->p_node=p->p_node;
free(p);
}
return head;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-06T06:03:56.993",
"Id": "460068",
"Score": "1",
"body": "Better in what way?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-06T09:28:45.530",
"Id": "460089",
"Score": "0",
"body": "I don't think your code is working. Your node is designed for double linked list, but you don't use it. In insert_head there is no `head->n_node =` insert_tail runs through the list (if head->n_node is set anywhere) instead of using the head->p_node."
}
] |
[
{
"body": "<h2>Design</h2>\n\n<p>Why do you need a <code>create_head_node()</code> that takes a node as the first parameter? Seems counter intuitive. Personally I would just remove that function does not seem needed to me.</p>\n\n<p>The other thing is that you don't seem to have a way to initialize an empty list (yes this can simply be the NULL pointer but it does leave it easy to accidentally have an uninitialized list).</p>\n\n<p>You can make the design better by separating Node and the list into different types. That way a lot of the work for tail is removed.</p>\n\n<p>i.e. It is easy to have A List and a Node.</p>\n\n<pre><code>struct Node;\nstruct List;\ntypedef struct Node Node;\ntypedef struct List List;\n\nstruct List\n{\n Node* head;\n Node* tail;\n int count;\n};\n\nstruct Node\n{\n int value;\n Node* next;\n Node* prev;\n};\n</code></pre>\n\n<h2>Code Review</h2>\n\n<p>The <code>create_head_node()</code> seem to be more like reset the head node to this value and leak the rest of the list.</p>\n\n<pre><code>node *create_head_node(node *head, int point){\n head->point=point;\n head->p_node=NULL;\n head->n_node=NULL;\n return head;\n}\n----\nnode* list = NULL;\nlist = insert_head(list, 10);\nlist = insert_head(list, 20);\n\n/*\n * now lets reset the head to 30 and leak the tail (20)\n */\nlist = create_head_node(list, 30);\n</code></pre>\n\n<hr>\n\n<p>Why does it matter if there is currently no head node?</p>\n\n<pre><code>node *insert_head(node *head, int point){\n if (head==NULL){\n printf(\"no head exist\");\n return 0;\n }\n</code></pre>\n\n<p>Can't I add to the head of an empty list?<br>\nAlso why are you returning <code>0</code>. That is an integer. An empty pointer is represented by <code>NULL</code>.</p>\n\n<hr>\n\n<p>Again I am not sure we I can add to the tail of an empty list.</p>\n\n<pre><code>void insert_tail(node *head, int point){\n if (head==NULL){\n printf(\"no head exist\");\n return;\n }\n</code></pre>\n\n<hr>\n\n<pre><code>node *insert_at(node *head, int point, int pos){\n</code></pre>\n\n<p>Yes sure it is an error.</p>\n\n<pre><code> while (pos>count)\n {\n printf(\"choose %d positions to add. choose again: \", count); scanf(\"%d\", &pos);\n }\n</code></pre>\n\n<p>But this code can not determine the context that it is being used within. So it should not be generating an error message. You should be returning some form of status for the calling code to check. If the calling code decides an error message is appropriate then it can print the error message.</p>\n\n<p>This is called the separation of concerns. Code either handles resource management (creating an maintaining a linked list) or it handles business logic (deciding if an error is critical or how to inform the user about errors).</p>\n\n<p>Does this section not look exectly like <code>insert_head()</code>?</p>\n\n<pre><code> node *temp=(node*)malloc(sizeof(node));\n temp->point=point;\n temp->n_node=p;\n temp->p_node=p->p_node;\n if(p->p_node!=NULL) p->p_node->n_node=temp;\n p->p_node=temp;\n return head;\n</code></pre>\n\n<hr>\n\n<pre><code>int count_node(node *head){\n ....\n free(p);\n</code></pre>\n\n<p>You are freeing nodes that are still in the list?</p>\n\n<h3>A Simpler version;</h3>\n\n<pre><code>#include <stdlib.h>\n#include <stdbool.h>\n#include <stdio.h>\n\nstruct Node;\nstruct List;\ntypedef struct Node Node;\ntypedef struct List List;\n\nstruct List\n{\n Node* head;\n Node* tail;\n int count;\n};\n\nstruct Node\n{\n int value;\n Node* next;\n Node* prev;\n};\n\nList* createList();\nvoid destroyList(List* list);\n\nint countList(List* list);\n\nbool insertHead(List* list, int value);\nbool insertTail(List* list, int value);\nbool insertAt(List* list, int value, int pos);\n\nbool deleteHead(List* list);\nbool deleteTail(List* list);\nbool deleteAt(List* list, int pos);\n\ntypedef void (*Action)(int);\nvoid visitNode(List* list, Action action);\n\n/* Don't define a print function.\n * Use the visitor pattern to visit each node.\n * Then printing the list can simply be a function that prints each node as it is visited.\n */\n\n\n/* Private Function */\nNode* allocateNewNode(int value, Node* next, Node* prev)\n{\n Node* newNode = (Node*)malloc(sizeof(Node));\n newNode->value = value;\n newNode->next = next;\n newNode->prev = NULL;\n return newNode;\n}\n\nList* createList()\n{\n List* newList = (List*)malloc(sizeof(List));\n newList->head = NULL;\n newList->tail = NULL;\n newList->count = 0;\n return newList;\n}\nvoid destroyList(List* list)\n{\n /*\n * remove all elements\n */\n Node* head;\n Node* next;\n for(head = list->head;head;head = next) {\n next = head->next;\n free(head);\n }\n /*\n * remove the list\n */\n free(list);\n}\nint countList(List* list)\n{\n return list->count;\n}\n\nbool insertHead(List* list, int value)\n{\n Node* newNode = allocateNewNode(value, list->head, NULL);\n if (list->head) {\n list->head->prev = newNode;\n }\n list->head = newNode;\n if (list->tail == NULL) {\n list->tail = newNode;\n }\n ++newList->count;\n return true;\n}\nbool insertTail(List* list, int value)\n{\n Node* newNode = allocateNewNode(value, NULL, list->tail);\n if (list->tail) {\n list->tail->next = newNode;\n }\n list->tail = newNode;\n if (list->head == NULL) {\n list->head = newNode;\n }\n ++newList->count;\n return true;\n}\nbool insertAt(List* list, int value, int pos)\n{\n if (pos == 0) {\n return insertHead(list, value);\n }\n if (pos >= list->count) {\n return insertTail(list, value);\n }\n\n Node* loop = list->head;\n while(--pos) {\n loop = loop->next;\n }\n Node* newNode = allocateNewNode(value, loop->next, loop);\n if (newNode->next) {\n newNode->next->prev = newNode;\n }\n if (newNode->prev) {\n newNode->prev->next = newNode;\n }\n ++newList->count;\n return true;\n}\n\nbool deleteHead(List* list)\n{\n Node* old = list->head;\n if (list->head) {\n list->head = list->head->next;\n if (list->head == NULL) {\n list->tail = NULL;\n }\n --newList->count;\n }\n free(old);\n return true;\n}\nbool deleteTail(List* list)\n{\n Node* old = list->tail;\n if (list->tail) {\n list->tail = list->tail->prev;\n if (list->tail == NULL) {\n list->head = NULL;\n }\n --newList->count;\n }\n free(old);\n return true;\n}\nvoid visitNode(List* list, Action action)\n{\n Node* loop = list->head;\n for(;loop;loop = loop->next) {\n action(loop->value);\n }\n}\n\nvoid printInt(int value) {fprintf(stdout, \"%d \", value);}\nvoid printList(List* list) {visitNode(list, printInt);}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-06T09:43:51.783",
"Id": "235156",
"ParentId": "235146",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "235156",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-06T02:46:59.607",
"Id": "235146",
"Score": "1",
"Tags": [
"c",
"linked-list"
],
"Title": "Implement function in doubly linked list"
}
|
235146
|
<p>I have written a small program to convert numeric cardinal numbers (i.e, 4, 35) into Spanish. Currently, it only supports numbers 1-99, however I would like to increase it to support numbers of any length. </p>
<p>Before I do this, I am seeking some feedback on my code structure. I feel that I have too many if statements and do not abstract my code enough, and I do not wish for it to be an elongated nightmare of if statements. I am also unsure how I should split up numbers of different sizes, and what variable names to use.</p>
<pre><code>getSpanishCardinal = cardinal => {
if (0 <= cardinal && cardinal <= 15) {
return getCardinals()[cardinal];
}
if (16 <= cardinal && cardinal <= 19) {
return sixteenToNineteen(cardinal);
}
if (cardinal >= 20 && cardinal <= 99) {
return twentyToNinetynine(cardinal);
}
};
twentyToNinetynine = cardinal => {
if (cardinal % 10 == 0) {
return getCardinals()[cardinal];
}
if (21 <= cardinal && cardinal <= 29) {
return "veinti" + getSpanishCardinal(rightMostDigit(cardinal)).toString();
}
return (
getCardinals()[leftMostMultiplier(cardinal)].toString() +
" y " +
getSpanishCardinal(rightMostDigit(cardinal)).toString()
);
};
sixteenToNineteen = cardinal => {
let rightMost = rightMostDigit(cardinal);
return "dieci" + getSpanishCardinal(rightMost).toString();
};
leftMostMultiplier = cardinal => {
let newDigit = cardinal.toString()[0];
const cardinalString = cardinal.toString();
const length = cardinalString.length;
for (let i = 1; i < length; i++) {
newDigit += "0";
}
return parseFloat(newDigit);
};
rightMostDigit = cardinal => {
return cardinal % 10;
};
getCardinals = () => {
return {
0: "cero",
1: "uno",
2: "dos",
3: "tres",
4: "cuatro",
5: "cinco",
6: "seis",
7: "siete",
8: "ocho",
9: "nueve",
10: "diez",
11: "once",
12: "doce",
13: "trece",
14: "catorce",
15: "quince",
20: "veinte",
30: "treinta",
40: "cuarenta",
50: "cincuenta",
60: "sesenta",
70: "setenta",
80: "ochenta",
90: "noventa",
100: "cien",
200: "doscientos",
300: "trescientos",
400: "cuatrocientos",
500: "quinientos",
600: "seiscientos",
700: "setecientos",
800: "ochocientos",
900: "novecientos",
1000: "mil",
1000000: "millón"
};
};
console.log(getSpanishCardinal(56));
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-06T18:05:29.260",
"Id": "460164",
"Score": "0",
"body": "Hint: Any numeric literal in english is the same, except with \",\" and \".\" reversed to be \".\" and \",\"; As such, 1,000.4 is 1.000,4"
}
] |
[
{
"body": "<p>The function declarations are at least lacking a <code>const</code> statement (or <code>let</code> or <code>var</code> if you prefer):</p>\n\n<pre><code>const getSpanishCardinal = cardinal => {\n</code></pre>\n\n<p>However I would suggest to using regular <code>function</code> statements instead.</p>\n\n<hr>\n\n<p>The <code>getCardinals</code> function is a bit pointless. A simple constant instead would make more sense:</p>\n\n<pre><code>const CARDINALS = {\n 0: \"cero\",\n 1: \"uno\",\n // ...\n}\n</code></pre>\n\n<p>For readability I'd also suggest to split it up into separate objects for 0 to 15, the tens, the hundreds, etc. </p>\n\n<p>This would also allow to assign assign the tens to the base number e.g.: </p>\n\n<pre><code>const TENS = {\n 2: \"veinte\",\n 3: \"treinta\",\n 4: \"cuarenta\",\n // ...\n}\n</code></pre>\n\n<p>and then you don't need to \"build\" numbers in <code>leftMostMultiplier</code>:</p>\n\n<pre><code>const twentyToNinetynine = cardinal => {\n // ...\n return (\n TENS[cardinal / 10] +\n \" y \" +\n getSpanishCardinal(rightMostDigit(cardinal))\n );\n};\n</code></pre>\n\n<p>(BTW, there seem to be a lot of unnessecary <code>toString()</code>s.)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-07T07:46:19.813",
"Id": "235206",
"ParentId": "235148",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "235206",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-06T05:43:45.627",
"Id": "235148",
"Score": "0",
"Tags": [
"javascript"
],
"Title": "Converting numbers 1-99 to Spanish in Javascript"
}
|
235148
|
<p>I have custom code where I check request params for existing and make query to database with model</p>
<pre><code>public function search(Request $request)
{
$position = $request->get("position") ?? null;
$location = $request->get("location") ?? null;
$employment = $request->get("employment") ?? null;
$jobsBy = null;
$jobs = null;
if($position) {
$jobs = Job::where('title', 'LIKE', '%'.$position.'%');
if($location) {
$locations = [];
if(is_array($location)) {
foreach ($location as $name) {
$locations[] = $name;
}
} else $locations[] = $location;
$jobs = $jobs->whereMetaIn("location", $locations);
}
if($employment) {
$employments = [];
if(is_array($employment)) {
foreach ($employment as $name) {
$employments[] = $name;
}
} else $employments[] = $employment;
$jobs = $jobs->withAnyTag($employments);
}
if($jobs->get()->count()) $jobsBy = "position";
}
if($location && $jobsBy === null) {
$locations = [];
if(is_array($location)) {
foreach ($location as $name) {
$locations[] = $name;
}
} else $locations[] = $location;
$jobs = Job::whereMetaIn('location', $locations);
if($employment) {
$employments = [];
if(is_array($employment)) {
foreach ($employment as $name) {
$employments[] = $name;
}
} else $employments[] = $employment;
$jobs = $jobs->withAnyTag($employments);
}
if($jobs->get()->count()) $jobsBy = "location";
}
if($employment && $jobsBy === null) {
$employments = [];
if(is_array($employment)) {
foreach ($employment as $name) {
$employments[] = $name;
}
} else $employments[] = $employment;
$jobs = Job::withAnyTag($employments);
if($jobs->get()->count()) $jobsBy = "employment";
}
if($jobs == null || !$jobs->get()->count()) {
$jobs = Job::where("status", '<', 2);
$jobsBy = "latest";
}
if(isset($jobs) && $jobs instanceof \Illuminate\Database\Eloquent\Builder && $jobsBy != null) {
$IDS = $jobs->where('status', '<', 2)->pluck('id');
$partnerCompanyJobs = Job::with(['user' => function($user) {
$user->without('roles', 'companies')
->select('id', 'name');
}])->withCount('views')->where('type', 0)
->whereIn('id', $IDS)
->where('status', 1)
->orderBy('updated_at', 'DESC')
->get();
$companyJobs = Job::with(['user' => function($user) {
$user->without('roles', 'companies')
->select('id', 'name');
}])->withCount('views')->where('type', 1)
->where('status', 1)
->whereIn('id', $IDS)
->orderBy('updated_at', 'DESC')
->get();
$sampleJobs = Job::with(['user' => function($user) {
$user->without('roles', 'companies')
->select('id', 'name');
}])->withCount('views')->where('type', 2)
->where('status', 1)
->whereIn('id', $IDS)
->orderBy('updated_at', 'DESC')
->get();
$somonJobs = Job::withCount('views')->whereIn('type', [3,4])
->whereIn('id', $IDS)
->where('status', 1)
->orderBy('updated_at', 'DESC')
->get();
$jobs = $partnerCompanyJobs->merge($companyJobs)
->merge($sampleJobs)
->merge($somonJobs);
if(count($jobs)) {
$page = $request->page ?? 1;
$items = $jobs->forPage($page, 5);
return response()->json([
'data' => JobResource::collection($items),
'total' => count($jobs),
'jobsBy' => $jobsBy
]);
}
}
return response()->json([
'data' => [],
'total' => 0,
'jobsBy' => ""
]);
}
</code></pre>
<p>How can I avoid duplication of code here and create an optimal database query in my case? I have a problem processing request parameters. Because of this, much is duplicated in my code. How can I fix such a case?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-06T06:12:16.670",
"Id": "460070",
"Score": "0",
"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."
}
] |
[
{
"body": "<p>I'd like to recommend condensing some of your script so that it is easier on the eyes.</p>\n\n<p>This:</p>\n\n<pre><code>if($location) {\n $locations = [];\n if(is_array($location)) {\n foreach ($location as $name) {\n $locations[] = $name;\n }\n } else $locations[] = $location;\n $jobs = $jobs->whereMetaIn(\"location\", $locations);\n}\n\nif($employment) {\n $employments = [];\n if(is_array($employment)) {\n foreach ($employment as $name) {\n $employments[] = $name;\n }\n } else $employments[] = $employment;\n $jobs = $jobs->withAnyTag($employments);\n}\n</code></pre>\n\n<p>is more simply written as:</p>\n\n<pre><code>if ($location) {\n $jobs = $jobs->whereMetaIn(\"location\", (array)$location);\n}\n\nif ($employment) {\n $jobs = $jobs->withAnyTag((array)$employment);\n}\n</code></pre>\n\n<p>because casting the input as an array will convert a string into a single-element array. If the variable is already an array, then nothing changes.</p>\n\n<p>But do you <em>really</em> want to overwrite the <code>$jobs</code> data formed from <code>$location</code>, if <code>$employment</code> is truthy? Either way that you answer that question, I think an <code>elseif()</code> is in order.</p>\n\n<p>Please be precise with your conditionals. <code>$jobs == null</code> is more concisely written as <code>!$jobs</code>, but is not the same as <code>$jobs === null</code>. Likewise regarding <code>$jobsBy != null</code>.</p>\n\n<p>Since <code>$jobs</code> is unconditionally declared, you can omit the <code>isset()</code> check.</p>\n\n<p>Unless I misunderstand, it also feels like a good idea to execute and cache the following as a variable so that it can be used multiple times:</p>\n\n<pre><code>['user' => function($user) { $user->without('roles', 'companies')->select('id', 'name'); }]\n</code></pre>\n\n<p>You should also cache <code>count($jobs)</code> before or within your conditional, so that you are not making the same <code>count()</code> call twice.</p>\n\n<hr>\n\n<p>Some more thoughts after initially posting my review:</p>\n\n<ol>\n<li><p><code>withAnyTag()</code> will happily accept mixed data (string or array).<br>\n<a href=\"https://github.com/rtconner/laravel-tagging/blob/laravel-5/docs/usage-examples.md\" rel=\"nofollow noreferrer\">https://github.com/rtconner/laravel-tagging/blob/laravel-5/docs/usage-examples.md</a></p></li>\n<li><p>When executing method calls on an object, just use the arrow syntax without <code>=</code>. In other words, you don't need to re-declare <code>$jobs</code> each time.</p></li>\n</ol>\n\n<p>I don't have a Laravel project to play/test with (so there is no guarantee that this will work seamlessly, just consider it a collection of suggestions), but these are some of my thoughts on a script rewrite:</p>\n\n<pre><code>public function search(Request $request)\n{\n $position = $request->get(\"position\") ?? null;\n $location = $request->get(\"location\") ?? null;\n $employment = $request->get(\"employment\") ?? null;\n\n $jobsBy = null;\n $jobs = null;\n if ($position) {\n $jobs = Job::where('title', 'LIKE', '%' . $position . '%');\n $jobs->where('status', '<', 2);\n if ($location) {\n $jobs->whereMetaIn(\"location\", (array)$location);\n }\n if ($employment) {\n $jobs->withAnyTag($employment);\n }\n if ($jobs->get()->count()) {\n $jobsBy = \"position\";\n }\n }\n\n // if no jobs by position, try with location...\n if ($location && !$jobsBy) {\n $jobs = Job::whereMetaIn('location', (array)$location);\n $jobs->where('status', '<', 2);\n if ($employment) {\n $jobs->withAnyTag($employment);\n }\n if ($jobs->get()->count()) {\n $jobsBy = \"location\";\n }\n }\n\n // if no jobs by location, try with employment...\n if ($employment && !$jobsBy) {\n $jobs = Job::withAnyTag($employment);\n $jobs->where('status', '<', 2);\n if ($jobs->get()->count()) {\n $jobsBy = \"employment\";\n }\n }\n\n // if not jobs, fallback to latest jobs...\n if (!$jobsBy) {\n $jobs = Job::where(\"status\", '<', 2);\n $jobsBy = \"latest\";\n }\n\n if ($jobs !== null && $jobs instanceof \\Illuminate\\Database\\Eloquent\\Builder) {\n $ids = $jobs->pluck('id');\n\n $userFilter = ['user' => function($user) {\n $user->without('roles', 'companies')\n ->select('id', 'name');\n }];\n\n $partnerCompanyJobs = Job::with($userFilter)\n ->withCount('views')\n ->where('type', 0)\n ->whereIn('id', $ids)\n ->where('status', 1)\n ->orderBy('updated_at', 'DESC')\n ->get();\n\n $companyJobs = Job::with($userFilter)\n ->withCount('views')->where('type', 1)\n ->where('status', 1)\n ->whereIn('id', $ids)\n ->orderBy('updated_at', 'DESC')\n ->get();\n\n $sampleJobs = Job::with($userFilter)\n ->withCount('views')->where('type', 2)\n ->where('status', 1)\n ->whereIn('id', $ids)\n ->orderBy('updated_at', 'DESC')\n ->get();\n\n $somonJobs = Job::withCount('views')\n ->whereIn('type', [3, 4])\n ->whereIn('id', $ids)\n ->where('status', 1)\n ->orderBy('updated_at', 'DESC')\n ->get();\n\n $jobs = $partnerCompanyJobs\n ->merge($companyJobs)\n ->merge($sampleJobs)\n ->merge($somonJobs);\n\n $jobCount = count($jobs);\n if ($jobCount) {\n $page = $request->page ?? 1;\n $items = $jobs->forPage($page, 5);\n return response()->json([\n 'data' => JobResource::collection($items),\n 'total' => $jobCount,\n 'jobsBy' => $jobsBy\n ]);\n }\n }\n\n return response()->json([\n 'data' => [],\n 'total' => 0,\n 'jobsBy' => \"\"\n ]);\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-06T09:58:03.910",
"Id": "460092",
"Score": "0",
"body": "Idk why it was important to remove the keys, but just casting to Array no longer removes the keys. array_values could be used to retain the original behaviour."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-06T12:26:44.907",
"Id": "460114",
"Score": "0",
"body": "Why are the keys important? Do you see something to suggest that the array _needs_ to be reindexed, or that it isn't already indexed?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-06T16:54:30.230",
"Id": "460146",
"Score": "0",
"body": "I have no idea, those arrays are passed to methods I know nothing about. But OP got rid of the keys, so I was just pointing out that your solution is not equivalent. OP should know whether it matters in his case..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-08T06:26:33.130",
"Id": "460358",
"Score": "0",
"body": "I've change part of your code. Because it is not work for me correctly. You can see changed part of code [here](https://3v4l.org/JoTN1). Please update your answer then I'll accept it. @mickmackusa"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-08T06:40:32.543",
"Id": "460359",
"Score": "0",
"body": "Does that `$userFilter` declaration work as intended?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-08T08:03:49.677",
"Id": "460370",
"Score": "0",
"body": "Yes it is work @mickmackusa"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-06T07:44:07.677",
"Id": "235151",
"ParentId": "235149",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "235151",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-06T05:48:44.037",
"Id": "235149",
"Score": "4",
"Tags": [
"performance",
"php",
"laravel"
],
"Title": "Laravel controller method that searches jobs using variable criteria"
}
|
235149
|
<p>I'm working on an AWS lambda function that take data from two mongodb databases, find the matching records between two collections by 'id' and calculate each record commission by fixed rate. Then export data to a xls file and upload it to s3.</p>
<p>connect.js</p>
<pre><code>const MongoClient = require('mongodb').MongoClient;
const getAllDocument = async (dbString, dbName, collectionName) => {
console.log('Initializing connection');
const client = await MongoClient.connect(dbString, { useUnifiedTopology: true }).catch(err => {
console.error(err);
});
if(!client){
return;
}
// Get collection data
try {
return await client.db(dbName).collection(collectionName).find().toArray();
} catch(err) {
console.error(err);
} finally {
client.close();
}
};
const getDocument = async(dbString, dbName, collectionName, property) => {
const client = await MongoClient.connect(dbString, {useUnifiedTopology: true }).catch(err => {
console.error(err);
});
if(!client){
return;
}
try {
let query = { name: property };
return await client.db(dbName).collection(collectionName).findOne(query);
} catch(err) {
console.error(err);
} finally {
client.close();
}
};
module.exports.getAllDocument = getAllDocument;
module.exports.getDocument = getDocument;
</code></pre>
<p>lambda.js</p>
<pre><code>const XLSX = require('xlsx');
const fs = require('fs');
const AWS = require('aws-sdk');
const getAllDocument = require("./connect.js").getAllDocument;
const getDocument = require("./connect.js").getDocument;
var bucketName = process.env.S3_BUCKET;
const db_host_seller = process.env.DB_HOST_SELLER;
const db_name_seller = process.env.DB_NAME_SELLER;
const db_host_retail = process.env.DB_HOST_RETAIL;
const db_name_retail = process.env.DB_NAME_RETAIL;
const sellerName = process.env.SELLER;
const retailerName = process.env.RETAILER;
s3 = new AWS.S3();
loadData = async () => {
retailData = await getAllDocument(db_host_retail, db_name_retail, "retailerCollection");
sellerData = await getAllDocument(db_host_seller, db_name_seller, "sellerCollection");
seller = await getDocument(db_host_seller, db_name_seller, "sellerCollection", sellerName);
};
exports.handler = (event) => {
// TODO implement
loadData().then(() => {
// Find retailer's rate
let rate = seller.retailers.find(obj => {
return obj.name === retailerName;
}).rate;
// Match records between seller and retailer data
let matchedItem = [];
for (var i in sellerData) {
// Convert date format
sellerData[i]["Connection Date"] = sellerData[i]["Connection Date"].toDateString()
delete sellerData[i]['_id'];
if (sellerData[i]["Disconnection Date"] !== "") {
sellerData[i]["Disconnection Date"] = sellerData[i]["Disconnection Date"].toDateString();
}
for( var j in retailData){
if (sellerData[i]["id"] == retailData[j]["id"]) {
sellerData[i]['Commission'] = rate * sellerData[i]['TotalPayment'] ;
matchedItem.push(sellerData[i]);
}
}
}
// Export to xls file
let worksheet = XLSX.utils.json_to_sheet(matchedItem);
let workbook = XLSX.utils.book_new();
XLSX.utils.book_append_sheet(workbook, worksheet, 'Commission')
XLSX.writeFile(workbook, '/tmp/Commission.xls');
const file = fs.readFileSync('/tmp/Commission.xls');
const params = {
Bucket: bucketName,
Key: 'Commission.xls', // File name to save in S3
Body: file
};
// Uploading files to the bucket
s3.upload(params, function(err, data) {
if (err) {
throw err;
}
console.log(`File uploaded to: ` + data.Location);
});
});
};
</code></pre>
<p>I would like to find out if there is any way for me to improve the code in terms of readability and performance.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-06T10:21:48.367",
"Id": "235157",
"Score": "2",
"Tags": [
"javascript",
"node.js",
"mongodb"
],
"Title": "Process data from mongodb and upload result to S3"
}
|
235157
|
<h1>Objective:</h1>
<p>Manage what happens when users interact with Excel Tables (ListObjects)</p>
<hr>
<p><strong>Possible interactions:</strong></p>
<ul>
<li>Update an existing Excel table
<ul>
<li>Add rows/columns to the table</li>
<li>Update a cell or a range of cells</li>
<li>Delete rows/columns to the table</li>
<li>Add a new Excel table</li>
</ul></li>
<li>Delete an Excel table</li>
<li>Add a new Excel table</li>
</ul>
<hr>
<p><strong>Specifications:</strong></p>
<ul>
<li><code>Actions</code> that are executed depend on the sheet that the table (ListObject) is located, <em>i.e.</em>, if table is located in <code>sheet x</code> the <code>Action</code> that is executed should be <code>generic action</code> and if table is located in <code>sheet y</code> the <code>Action</code> that is executed should be <code>create a task</code></li>
<li><code>Actions</code> depend on what is happening with the <code>table</code>, <em>i.e.</em>, there should be an <code>Action</code> for the event of <code>Adding</code> rows and a different one for <code>Deleting</code> rows</li>
<li><code>Actions</code> should know what triggered them, <em>e.g.</em>, <code>Sheet</code>, <code>Table</code> and <code>Cell</code></li>
<li>If user adds a new <code>Table</code> to a <code>Sheet</code> it should also respond to the <code>Actions</code> performed in it's <code>cells</code></li>
</ul>
<hr>
<p><strong>Code design standards:</strong></p>
<ul>
<li>Use <em>classes</em></li>
<li>Use <em>interfaces</em></li>
<li>Implement <em>strategy patterns</em></li>
</ul>
<blockquote>
<ul>
<li><p>Implement <em>factory patterns</em> <- This one I still don't understand quite well how to apply the
concept</p></li>
<li><p>Implement <em>Unit tests</em> <- This one I'm far from understanding</p></li>
</ul>
</blockquote>
<hr>
<p><strong>Sample use case #1:</strong></p>
<ul>
<li>User modifies a <code>cell</code> or a <code>range</code> inside an Excel <code>Table</code>
<ul>
<li>Directly edit a cell</li>
<li>Copy paste a cell or a range</li>
<li>Use autofill from a cell and copy it to the next one (this couldn't find how to respond)</li>
</ul></li>
<li>An <code>action</code> is executed:
<ul>
<li>Program displays what was the <em>previous</em> value and the <em>new</em> value in the modified <code>cell</code> </li>
</ul></li>
</ul>
<p><strong>Sample use case #2:</strong></p>
<ul>
<li>User adds a new Excel <code>Table</code> (ListObject) to SheetY</li>
<li>User modifies a <code>cell</code> in the new Excel <code>Table</code></li>
<li>An <code>action</code> is executed:
<ul>
<li>Program displays what was the <em>previous</em> value and the <em>new</em> value in the modified <code>cell</code> </li>
</ul></li>
</ul>
<p><strong>Sample use case #3:</strong></p>
<ul>
<li>User deletes an Excel <code>Table</code> (ListObject) from SheetY</li>
<li>User modifies a <code>cell</code> in another Excel <code>Table</code></li>
<li>An <code>action</code> is executed:
<ul>
<li>Program displays what was the <em>previous</em> value and the <em>new</em> value in the modified <code>cell</code> </li>
</ul></li>
</ul>
<hr>
<h2>Would appreciate your review to find out:</h2>
<ol>
<li>If <em>code design</em> expectations are correctly implemented</li>
<li>How to implement a factory pattern (if it's useful in this case)</li>
<li>How to implement unit tests</li>
<li>If this approach is efficient (e.g. the way I'm handling how to store the table range previous values)</li>
<li>Any other insight you may consider</li>
</ol>
<hr>
<h3>Reference</h3>
<ul>
<li><a href="https://rubberduckvba.wordpress.com/" rel="noreferrer">Rubberduck-VBA</a> blog
<ul>
<li><a href="https://rubberduckvba.wordpress.com/2018/08/28/oop-battleship-part-1-the-patterns/" rel="noreferrer">OOP Battleship Part 1: The Patterns</a></li>
<li><a href="https://rubberduckvba.wordpress.com/2018/04/24/factories-parameterized-object-initialization/" rel="noreferrer">Factories: Parameterized Object Initialization</a></li>
<li><a href="https://rubberduckvba.wordpress.com/2018/04/25/private-this-as-tsomething/" rel="noreferrer">Private this As TSomething</a></li>
<li><a href="https://rubberduckvba.wordpress.com/2017/10/19/how-to-unit-test-vba-code/" rel="noreferrer">How to unit test VBA code?</a></li>
<li><a href="https://rubberduckvba.wordpress.com/2016/06/16/oop-vba-pt-1-debunking-stuff/" rel="noreferrer">OOP VBA pt.1: Debunking Stuff</a></li>
<li><a href="https://rubberduckvba.wordpress.com/2016/07/05/oop-vba-pt-2-factories-and-cheap-hotels/" rel="noreferrer">OOP VBA pt.2: Factories and Cheap Hotels</a></li>
</ul></li>
<li>Answers related to these subjects from <a href="https://stackoverflow.com/users/1188513/mathieu-guindon">Mathieu Guindon</a>
<ul>
<li><a href="https://stackoverflow.com/search?q=user%3A1188513+%5Bobject-oriented%5D+%5Bvba%5D">Tags vba and object-oriented</a></li>
</ul></li>
</ul>
<hr>
<h3>Current file</h3>
<p>You can download the <a href="https://1drv.ms/x/s!ArAKssDW3T7wnLwTP1-vjW_hFWJdzA?e=3XKsT1" rel="noreferrer">demo file from here</a></p>
<p>File structure:</p>
<p><a href="https://i.stack.imgur.com/yqfKu.png" rel="noreferrer"><img src="https://i.stack.imgur.com/yqfKu.png" alt="File structure"></a></p>
<ul>
<li>SheetX contains a table (ListObject) called TableX</li>
<li>SheetY contains two tables (ListObjects) called TableY1 and TableY2</li>
</ul>
<hr>
<h2>Code</h2>
<blockquote>
<p>Code has annotations from <a href="http://rubberduckvba.com/" rel="noreferrer">Rubberduck add-in</a></p>
</blockquote>
<p>If you don't have Rubberduck installed you can:</p>
<ul>
<li>Go and download it now...this is a must when you're developing in VBA!...and follow these <a href="https://stackoverflow.com/q/58600560/1521579">instructions</a> - Special thanks to Mathieu and his team ;)</li>
<li>You must follow <a href="https://rubberduckvba.wordpress.com/2018/04/24/factories-parameterized-object-initialization/" rel="noreferrer">these instructions</a> to set the predeclared attribute to true in the corresponding classes (look for "where to put it" in the article)</li>
</ul>
<p><a href="https://i.stack.imgur.com/sWuQn.png" rel="noreferrer"><img src="https://i.stack.imgur.com/sWuQn.png" alt="Rubberduck code explorer view"></a></p>
<p><strong>Components</strong></p>
<p>Sheet: <code>SheetX</code></p>
<pre><code>'@Version(1)
'@Folder("App.TableTest")
Option Explicit
' Copywrite (C) 2019 Ricardo Diaz
' This file is distributed under the GPL-3.0 license
' Obtain a copy of the GPL-3.0 license <http://opensource.org/licenses/GPL-3.0>
Private newAppTables As ITables
Private Sub Worksheet_Activate()
InitializeTablesGeneric
End Sub
Private Sub Worksheet_Deactivate()
If Not newAppTables Is Nothing Then
newAppTables.RemoveTables
Set newAppTables = Nothing
End If
End Sub
Private Sub InitializeTablesGeneric()
On Error GoTo CleanFail
Dim TableActions As Collection
Dim ActionUpdate As TableActionGeneric
Set TableActions = New Collection
Set ActionUpdate = New TableActionGeneric
TableActions.Add ActionUpdate, "Update"
If newAppTables Is Nothing Then
Set newAppTables = Tables.Create(TableActions, Me)
End If
CleanExit:
Exit Sub
CleanFail:
Stop: Resume CleanExit
End Sub
</code></pre>
<p>Sheet: <code>SheetY</code></p>
<pre><code>'@Version(1)
'@Folder("App.TableTest")
Option Explicit
' Copywrite (C) 2019 Ricardo Diaz
' This file is distributed under the GPL-3.0 license
' Obtain a copy of the GPL-3.0 license <http://opensource.org/licenses/GPL-3.0>
Private newAppTables As ITables
Private Sub Worksheet_Activate()
InitializeTablesCreateTask
End Sub
Private Sub Worksheet_Deactivate()
If Not newAppTables Is Nothing Then
newAppTables.RemoveTables
Set newAppTables = Nothing
End If
End Sub
Private Sub InitializeTablesCreateTask()
On Error GoTo CleanFail
Dim TableActions As Collection
Dim ActionUpdate As TableActionUpdateCreateTask
Set TableActions = New Collection
Set ActionUpdate = New TableActionUpdateCreateTask
TableActions.Add ActionUpdate, "Update"
If newAppTables Is Nothing Then
Set newAppTables = Tables.Create(TableActions, Me)
End If
CleanExit:
Exit Sub
CleanFail:
Stop: Resume CleanExit
End Sub
</code></pre>
<p>Class: <code>Tables</code></p>
<pre><code>'@Folder("App.Tables")
Option Explicit
'@PredeclaredId
Private Type TTables
Sheet As Worksheet
Tables As Collection
TableManagerActions As Collection
Counter As Long
End Type
Private this As TTables
Implements ITables
Public Property Get Tables() As Collection
Set Tables = this.Tables
End Property
Friend Property Set Tables(ByVal Value As Collection)
Set this.Tables = Value
End Property
Public Property Get TableManagerActions() As Collection
Set TableManagerActions = this.TableManagerActions
End Property
Friend Property Set TableManagerActions(ByVal Value As Collection)
Set this.TableManagerActions = Value
End Property
Public Property Get Sheet() As Worksheet
Set Sheet = this.Sheet
End Property
Friend Property Set Sheet(ByVal Value As Worksheet)
Set this.Sheet = Value
End Property
Public Property Get Counter() As Long
Counter = this.Counter
End Property
Friend Property Let Counter(ByVal Value As Long)
this.Counter = Value
End Property
'
' Public Members
' --------------
'
Public Property Get Self() As Tables
Set Self = Me
End Property
'
' Public Methods
' ---------------
'
Public Sub AddTables()
Select Case True
Case Counter = 0 Or Counter > Sheet.ListObjects.Count
AddAllTablesInSheet
Case Sheet.ListObjects.Count > Counter
AddNewTable Sheet.ListObjects(Sheet.ListObjects.Count)
End Select
Counter = Sheet.ListObjects.Count
End Sub
Private Sub AddAllTablesInSheet()
Dim evalTable As ListObject
Set Tables = New Collection
For Each evalTable In Sheet.ListObjects
AddNewTable evalTable
Next evalTable
End Sub
Private Sub AddNewTable(ByVal evalTable As ListObject)
Dim NewTable As Table
Set NewTable = Table.Create(TableManagerActions, evalTable)
Tables.Add Item:=NewTable, Key:=evalTable.name
End Sub
Public Sub RemoveTables()
Dim evalTable As ListObject
For Each evalTable In Sheet.ListObjects
Tables.Remove evalTable.name
Next evalTable
End Sub
Public Function Create(ByVal Actions As Collection, ByVal SourceSheet As Worksheet) As ITables
With New Tables
Set .TableManagerActions = Actions
Set .Sheet = SourceSheet
Set Create = .Self
.AddTables
End With
End Function
Private Sub ITables_AddTables()
AddTables
End Sub
Private Property Get ITables_Counter() As Long
ITables_Counter = this.Counter
End Property
Private Sub ITables_RemoveTables()
RemoveTables
End Sub
</code></pre>
<p>Class (Interface): <code>ITables</code></p>
<pre><code>'@Folder("App.Tables")
Option Explicit
Public Property Get Counter() As Long
End Property
Public Sub AddTables()
End Sub
Public Sub RemoveTables()
End Sub
</code></pre>
<p>Class: <code>Table</code></p>
<pre><code>'@Folder("App.Tables")
Option Explicit
'@PredeclaredId
Private Type TListObjectProtector
RefTable As ListObject
TableManagerActions As Collection
TableValues As Variant
RowsCount As Long
ColumnsCount As Long
PreviousRowsCount As Long
End Type
Private this As TListObjectProtector
'@MemberAttribute VB_VarHelpID, -1
Private WithEvents appExcel As Excel.Application
Public Property Get RefTable() As ListObject
Set RefTable = this.RefTable
End Property
Public Property Set RefTable(ByVal objectRef As ListObject)
Set this.RefTable = objectRef
End Property
Public Property Get TableManagerActions() As Collection
Set TableManagerActions = this.TableManagerActions
End Property
Friend Property Set TableManagerActions(ByVal Value As Collection)
Set this.TableManagerActions = Value
End Property
Public Property Get TableValues() As Variant
TableValues = this.TableValues
End Property
Friend Property Let TableValues(ByVal Value As Variant)
this.TableValues = Value
End Property
Public Property Get RowsCount() As Long
RowsCount = this.RowsCount
End Property
Friend Property Let RowsCount(ByVal Value As Long)
this.RowsCount = Value
End Property
Public Property Get ColumnsCount() As Long
ColumnsCount = this.ColumnsCount
End Property
Friend Property Let ColumnsCount(ByVal Value As Long)
this.ColumnsCount = Value
End Property
Public Property Get Self() As Table
Set Self = Me
End Property
'
' Private Methods
' ---------------
'
Private Function GetAction() As String
Select Case True
Case RowsCount < RefTable.DataBodyRange.Rows.Count Or ColumnsCount < RefTable.ListColumns.Count
GetAction = "Add"
Case RowsCount > RefTable.DataBodyRange.Rows.Count Or ColumnsCount > RefTable.ListColumns.Count
GetAction = "Delete"
Case RowsCount = RefTable.DataBodyRange.Rows.Count And ColumnsCount = RefTable.ListColumns.Count
GetAction = "Update"
End Select
End Function
Private Sub LoadFromRange(ByVal Target As Range)
Dim evalRange As Range
Set evalRange = Intersect(Target, RefTable.DataBodyRange)
If Not evalRange Is Nothing Then
TableValues = RangeUtilities.RangeToArray(RefTable.DataBodyRange, False)
End If
ColumnsCount = RefTable.ListColumns.Count
RowsCount = RefTable.DataBodyRange.Rows.Count
End Sub
Private Sub ProcessRange(ByVal Target As Range)
Select Case GetAction
Case "Add"
MsgBox "Add"
Case "Delete"
MsgBox "delete"
Case "Update"
UpdateRange Target, "Update"
End Select
End Sub
Private Sub UpdateRange(ByVal Target As Range, ByVal Action As String)
Dim evalRange As Range
Dim EvalCell As Range
Dim previousValue As Variant
Dim evalRow As Long
Dim evalColumn As Long
Set evalRange = Intersect(Target, RefTable.DataBodyRange)
If evalRange Is Nothing Then Exit Sub
For Each EvalCell In Target
evalRow = ListObjectUtilities.GetCellRow(RefTable, EvalCell)
evalColumn = ListObjectUtilities.GetCellColumn(RefTable, EvalCell)
If IsArray(TableValues) Then
previousValue = TableValues(evalRow, evalColumn)
Else
previousValue = TableValues
End If
If previousValue <> EvalCell.Value2 Then
ProcessCell EvalCell, EvalCell.Value2, previousValue, Action
End If
Next EvalCell
End Sub
Private Sub ProcessCell(ByVal EvalCell As Range, ByVal CurrentValue As Variant, ByVal previousValue As Variant, ByVal Action As String)
Dim strategy As ITableAction
Set strategy = TableManagerActions.Item(Action)
strategy.Run EvalCell, CurrentValue, previousValue
End Sub
Public Function Create(ByVal Actions As Collection, ByVal Table As ListObject) As Table
With New Table
Set .TableManagerActions = Actions
Set .RefTable = Table
.ColumnsCount = .RefTable.ListColumns.Count
.RowsCount = .RefTable.DataBodyRange.Rows.Count
Set Create = .Self
End With
End Function
Private Sub Class_Initialize()
Set appExcel = Excel.Application
Set TableManagerActions = New Collection
End Sub
Private Sub Class_Terminate()
Set Table = Nothing
Set appExcel = Nothing
Set TableManagerActions = Nothing
End Sub
Private Sub appExcel_SheetChange(ByVal Sh As Object, ByVal Target As Range)
Dim evalRange As Range
On Error Resume Next
LogAction Sh.name, RefTable.name, "Change"
On Error GoTo 0
If RefTable Is Nothing Or Not ObjectUtilities.IsConnected(RefTable) Then Exit Sub
If Not Sh Is RefTable.Parent Then Exit Sub
Set evalRange = Intersect(Target, RefTable.DataBodyRange)
If Not evalRange Is Nothing Then
ProcessRange Target
End If
End Sub
Private Sub appExcel_SheetSelectionChange(ByVal Sh As Object, ByVal Target As Range)
Dim evalRange As Range
On Error Resume Next
LogAction Sh.name, RefTable.name, "SelectionChange"
On Error GoTo 0
If RefTable Is Nothing Or Not ObjectUtilities.IsConnected(RefTable) Then Exit Sub
If Not Sh Is RefTable.Parent Then Exit Sub
Set evalRange = Intersect(Target, RefTable.DataBodyRange)
If Not evalRange Is Nothing Then
LoadFromRange Target
End If
End Sub
Private Sub LogAction(ByVal SheetName As String, ByVal TableName As String, ByVal ActionName As String)
If SheetName = "Logger" Then Exit Sub
Application.EnableEvents = False
Logger.Cells(Logger.Rows.Count, "A").End(xlUp).Offset(1, 0).Value2 = SheetName
Logger.Cells(Logger.Rows.Count, "B").End(xlUp).Offset(1, 0).Value2 = TableName
Logger.Cells(Logger.Rows.Count, "C").End(xlUp).Offset(1, 0).Value2 = ActionName
Application.EnableEvents = True
End Sub
</code></pre>
<p>Class (Interface): <code>ITableAction</code></p>
<pre><code>'@Version(1)
'@Folder("App.Tables")
Option Explicit
' Copywrite (C) 2019 Ricardo Diaz
' This file is distributed under the GPL-3.0 license
' Obtain a copy of the GPL-3.0 license <http://opensource.org/licenses/GPL-3.0>
Public Sub Run(ByVal EvalCell As Range, ByVal CurrentValue As Variant, ByVal previousValue As Variant)
End Sub
</code></pre>
<p>Class: <code>TableActionGeneric</code></p>
<pre><code>'@Version(1)
'@Folder("App.Tables.Actions")
Option Explicit
' Copywrite (C) 2019 Ricardo Diaz
' This file is distributed under the GPL-3.0 license
' Obtain a copy of the GPL-3.0 license <http://opensource.org/licenses/GPL-3.0>
Implements ITableAction
Private Sub ITableAction_Run(ByVal EvalCell As Range, ByVal CurrentValue As Variant, ByVal previousValue As Variant)
MsgBox "Generic Action in table: " & EvalCell.ListObject.name & " from: " & previousValue & " To: " & CurrentValue & " in Cell: " & EvalCell.Address
End Sub
</code></pre>
<p>Class: <code>TableActionUpdateCreateTask</code></p>
<pre><code>'@Version(1)
'@Folder("App.Tables.Actions")
Option Explicit
' Copywrite (C) 2019 Ricardo Diaz
' This file is distributed under the GPL-3.0 license
' Obtain a copy of the GPL-3.0 license <http://opensource.org/licenses/GPL-3.0>
Implements ITableAction
Private Sub ITableAction_Run(ByVal EvalCell As Range, ByVal CurrentValue As Variant, ByVal previousValue As Variant)
MsgBox "CreateTask Action in table: " & EvalCell.ListObject.name & " from: " & previousValue & " To: " & CurrentValue & " in Cell: " & EvalCell.Address
End Sub
</code></pre>
<p><strong>Components - Utilities -</strong></p>
<p>Class: <code>ListObjectUtilities</code></p>
<pre><code>'@Version(1)
'@Folder("Framework.Utilities")
Option Explicit
'@PredeclaredId
Public Function GetCellRow(ByVal evalTable As ListObject, ByVal EvalCell As Range) As Long
If Intersect(EvalCell, evalTable.DataBodyRange) Is Nothing Then Exit Function
GetCellRow = EvalCell.Row - evalTable.HeaderRowRange.Row
End Function
Public Function GetCellColumn(ByVal evalTable As ListObject, ByVal EvalCell As Range) As Long
If Intersect(EvalCell, evalTable.DataBodyRange) Is Nothing Then Exit Function
GetCellColumn = EvalCell.Column - evalTable.HeaderRowRange.Column + 1
End Function
' ----------------------------------------------------------------
' Procedure Name: AgregarReferenciar
' Purpose: Agregar una tabla estructurada para registrar información resultados
' Procedure Kind: Function
' Procedure Access: Public
' Parameter targetSheetResultados (Worksheet): targetSheet donde se almacena la tabla
' Parameter tableName (String): Nombre de la tabla
' Parameter ColumnList (Variant): Listado con nombres de columnas
' Return Type: ListObject
' Author: RicardoDiaz
' Date: 10/09/2019
' ----------------------------------------------------------------
'@Ignore AssignedByValParameter, ProcedureNotUsed
Public Function AddAndReference(ByVal TableName As String, Optional ByVal ColumnList As Variant, Optional ByVal TargetCell As Range, Optional ByVal ClearTableContents As Boolean = False, Optional ByVal TableStyleName As String) As ListObject
Dim ExcelTable As ListObject
If Exists(TableName) = False Then
If TargetCell Is Nothing Then
Set TargetCell = Application.InputBox(Prompt:= _
"La tabla " & TableName & " no existe, seleccione una ubicación para crearla", _
title:="Defina la ubicación", Type:=8)
End If
' Agregar tabla estructurada
Set ExcelTable = TargetCell.Parent.ListObjects.Add(SourceType:=xlSrcRange, source:=TargetCell)
With ExcelTable
.name = TableName
ExcelTable.Resize .Range.Resize(, UBound(ColumnList) + 1)
.HeaderRowRange.Value2 = ColumnList
End With
Else
Set ExcelTable = Range(TableName).ListObject
End If
If TableStyleName <> vbNullString Then
ExcelTable.TableStyle = TableStyleName
End If
If ClearTableContents = True Then
If Not ExcelTable.DataBodyRange Is Nothing Then
ExcelTable.DataBodyRange.Delete
End If
End If
Set AddAndReference = ExcelTable
End Function
'@Ignore ProcedureNotUsed
Public Function AddAndReferenceRow(ByVal ExcelTable As ListObject, ByVal ColumnValues As Variant) As ListRow
Dim newRow As ListRow
Dim Counter As Long
Set newRow = ExcelTable.ListRows.Add
With newRow
For Counter = 0 To UBound(ColumnValues)
.Range(Counter + 1) = ColumnValues(Counter)
Next Counter
End With
Set AddAndReferenceRow = newRow
End Function
'@Ignore ProcedureNotUsed
Public Function Exists(ByVal ListObjectName As String) As Boolean
Dim evalListObject As ListObject
On Error Resume Next
Set evalListObject = Range(ListObjectName).ListObject
On Error GoTo 0
Exists = Not evalListObject Is Nothing
End Function
'@Ignore ProcedureNotUsed
Public Function GetRowByCriteria(ByVal ExcelTable As ListObject, ByVal Column1Header As String, _
ByVal Column1Criteria As String, _
Optional ByVal Column2Header As String, _
Optional ByVal Column2Criteria As String, _
Optional ByVal Column3Header As String, _
Optional ByVal Column3Criteria As String) As ListRow
Dim evalRow As ListRow
Dim matchedRow As ListRow
For Each evalRow In ExcelTable.DataBodyRange.ListObject.ListRows
If Column2Header = vbNullString And Column3Header = vbNullString Then
If (Intersect(evalRow.Range, ExcelTable.ListColumns(Column1Header).Range).Value = Column1Criteria) = True Then Set matchedRow = evalRow: Exit For
ElseIf Column2Header <> vbNullString And Column3Header = vbNullString Then
If (Intersect(evalRow.Range, ExcelTable.ListColumns(Column1Header).Range).Value = Column1Criteria) And _
(Intersect(evalRow.Range, ExcelTable.ListColumns(Column2Header).Range).Value = Column2Criteria) = True Then Set matchedRow = evalRow: Exit For
ElseIf Column2Header <> vbNullString And Column3Header <> vbNullString Then
If (Intersect(evalRow.Range, ExcelTable.ListColumns(Column1Header).Range).Value = Column1Criteria) And _
(Intersect(evalRow.Range, ExcelTable.ListColumns(Column2Header).Range).Value = Column2Criteria) And _
(Intersect(evalRow.Range, ExcelTable.ListColumns(Column3Header).Range).Value = Column3Criteria) = True Then Set matchedRow = evalRow: Exit For
End If
Next evalRow
Set GetRowByCriteria = matchedRow
End Function
'@Ignore ProcedureNotUsed
Public Function HasExternalConnection(ByVal ListObjectName As String) As Boolean
Dim evalSheet As Worksheet
Dim evalListObject As ListObject
For Each evalSheet In ThisWorkbook.Worksheets
For Each evalListObject In evalSheet.ListObjects
If evalListObject.name = ListObjectName Then
If evalListObject.SourceType = xlSrcModel Or evalListObject.SourceType = xlSrcExternal Or evalListObject.SourceType = xlSrcQuery Then
HasExternalConnection = True
Exit For
End If
End If
Next evalListObject
Next evalSheet
End Function
'@Ignore ProcedureNotUsed
Public Sub DeleteRowsByCriteria(ByVal ExcelTable As ListObject, ByVal Column1Header As String, _
ByVal Column1Criteria As String, _
Optional ByVal Column2Header As String, _
Optional ByVal Column2Criteria As String, _
Optional ByVal Column3Header As String, _
Optional ByVal Column3Criteria As String)
Dim evalRow As ListRow
Dim Counter As Long
Dim totalRows As Long
Dim deleteRow As Boolean
totalRows = ExcelTable.ListRows.Count
For Counter = totalRows To 1 Step -1
Set evalRow = ExcelTable.ListRows(Counter)
If Column2Header = vbNullString And Column3Header = vbNullString Then
deleteRow = (Intersect(evalRow.Range, ExcelTable.ListColumns(Column1Header).Range).Value = Column1Criteria)
ElseIf Column2Header <> vbNullString And Column3Header = vbNullString Then
deleteRow = (Intersect(evalRow.Range, ExcelTable.ListColumns(Column1Header).Range).Value = Column1Criteria) And _
(Intersect(evalRow.Range, ExcelTable.ListColumns(Column2Header).Range).Value = Column2Criteria)
ElseIf Column2Header <> vbNullString And Column3Header <> vbNullString Then
deleteRow = (Intersect(evalRow.Range, ExcelTable.ListColumns(Column1Header).Range).Value = Column1Criteria) And _
(Intersect(evalRow.Range, ExcelTable.ListColumns(Column2Header).Range).Value = Column2Criteria) And _
(Intersect(evalRow.Range, ExcelTable.ListColumns(Column3Header).Range).Value = Column3Criteria)
End If
If deleteRow = True Then
evalRow.Delete
End If
Next Counter
End Sub
</code></pre>
<p>Class: <code>ObjectUtilities</code></p>
<pre><code>'@Folder("Framework.Utilities")
Option Explicit
'@PredeclaredId
Private Const C_ERR_NO_ERROR = 0&
Private Const C_ERR_OBJECT_VARIABLE_NOT_SET = 91&
Private Const C_ERR_OBJECT_REQUIRED = 424&
Private Const C_ERR_DOES_NOT_SUPPORT_PROPERTY = 438&
Private Const C_ERR_APPLICATION_OR_OBJECT_ERROR = 1004&
Public Function IsConnected(ByVal Obj As Object) As Boolean
' Credits: http://www.cpearson.com/excel/ConnectedObject.htm
' Adapted by: Ricardo Diaz
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' IsConnected
' By Chip Pearson, chip@cpearson.com, www.cpearson.com
' http://www.cpearson.com/excel/ConnectedObject.htm
'
' This procedure determines whether an object type variable is still connected
' to its target. An object variable can become disconnected from its target
' when the target object is destroyed. For example, the following code will
' raise an automation error because the target of the variable WS had been
' destoryed.
'
' Dim WS As Worksheet
' Set WS = ActiveSheet
' ActiveSheet.Delete
' Debug.Print WS.Name
'
' This code will fail on the "Debug.Print WS.Name" because the worksheet to
' which WS referenced was destoryed. It is important to note that WS will NOT
' be set to Nothing when the worksheet is deleted.
'
' This procedure attempts to call the Name method of the Obj variable and
' then tests the result of Err.Number. We'll get the following error
' numbers:
' C_ERR_NO_ERROR
' No error occurred. We successfully retrieved the Name
' property. This indicates Obj is still connected to its
' target. Return TRUE.
'
' C_ERR_OBJECT_VARIABLE_NOT_SET
' We'll get this error if the Obj variable has been
' disconnected from its target. Return FALSE.
'
' C_ERR_DOES_NOT_SUPPORT_PROPERTY
' We'll get this error if the Obj variable does not have
' a name property. In this case, the Obj variable is still
' connected to its target. Return True.
'
' C_ERR_APPLICATION_OR_OBJECT_ERROR
' This is a generic error message. If we get this error, we need to
' do further testing to get the connected state.
'
' These are the only values that Err.Number should return. If we receive
' another error, err on the side of caution and return False.
'
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'@Ignore VariableNotUsed
Dim NameProp As String
'@Ignore VariableNotUsed
Dim ParentObj As Object
On Error Resume Next
Err.Clear
NameProp = Obj.name
On Error GoTo 0
Select Case Err.Number
Case C_ERR_NO_ERROR
' We'll get this result if we retrieve the Name property of Obj.
' Obj is connected.
IsConnected = True
Case C_ERR_DOES_NOT_SUPPORT_PROPERTY
' We'll get this result if Obj does not have a name property. This
' still indicates that Obj is connected.
IsConnected = True
Case C_ERR_OBJECT_VARIABLE_NOT_SET
' This indicates that Obj was Nothing, which we will treat
' as disconnected. If you want Nothing to indicate connected,
' test the variable Is Nothing before calling this procedure.
IsConnected = False
Case C_ERR_OBJECT_REQUIRED
' This indicates the object is disconnected. Return False
IsConnected = False
Case C_ERR_APPLICATION_OR_OBJECT_ERROR
' This error may occur when the object is either connected or disconnected.
' In this case, attempt to get the Parent property of the object.
Err.Clear
Set ParentObj = Obj.Parent
Select Case Err.Number
Case C_ERR_NO_ERROR
' we succuesfully got the parent object. Obj is connected.
IsConnected = True
Case C_ERR_DOES_NOT_SUPPORT_PROPERTY
' we'll get this error if Obj does not have a Parent property. This
' still indicates that Obj is connected.
IsConnected = True
Case C_ERR_OBJECT_VARIABLE_NOT_SET
' we'll get this error if Obj is disconnected
IsConnected = False
Case Else
IsConnected = False
End Select
Case Else
' we should never get here, but return False if we do
IsConnected = False
End Select
End Function
</code></pre>
<p>Class: <code>RangeUtilities</code></p>
<pre><code>'@Version(1)
'@PredeclaredId
'@Folder("Framework.Utilities")
Option Explicit
'@Ignore ProcedureNotUsed
Public Function ToString(ByVal evalRange As Range, Optional ByVal separator As String) As String
Dim EvalCell As Range
Dim result As String
For Each EvalCell In evalRange.Cells
result = result & EvalCell.Value & separator
Next EvalCell
ToString = Left$(result, Len(result) - Len(separator))
End Function
'@Ignore ProcedureNotUsed
Public Function GetRangeName(ByVal Target As Range) As String
On Error Resume Next
GetRangeName = Target.name.name
On Error GoTo 0
End Function
'@Ignore ProcedureNotUsed
Public Function RangeToArray(ByVal evalRange As Range, ByVal Transpose As Boolean) As Variant
' When Transpose = true the result will be a 1D array if there is only one row or one column
If Transpose = True Then
Select Case True
Case evalRange.Rows.Count = 1 And evalRange.Columns.Count > 1
RangeToArray = Application.WorksheetFunction.Transpose(Application.WorksheetFunction.Transpose(evalRange))
Case evalRange.Rows.Count > 1 And evalRange.Columns.Count = 1
RangeToArray = Application.WorksheetFunction.Transpose(evalRange)
Case Else
RangeToArray = evalRange.Value2
End Select
Else
RangeToArray = evalRange.Value2
End If
End Function
</code></pre>
|
[] |
[
{
"body": "<p>On the whole nice work! This is actually a problem I've looked at in the past, and as a result I'd like to review the approach you've taken and the API/ way users can interact with your code.</p>\n\n<hr>\n\n<p>As I understand it you have 3 main classes</p>\n\n<ol>\n<li><code>Tables</code> - responsible for instantiating a collection of <code>Table</code> objects (with some automagic methods to allow client code to attempt to keep this collection in sync so it reflects what's on the sheet)</li>\n<li><code>ITableAction</code> implementations which are essentially callback functions with a strict interface that are triggered by updates to the tables</li>\n<li>The <code>Table</code> class - what actually wraps <code>ListObjects</code> and converts Application level events into triggers to run those <code>TableActions</code></li>\n</ol>\n\n<p>The rest is mostly just utility stuff and example code. Now I'd argue that classes 1. (mostly) and 2. are actually redundant and making your life a lot harder, let's take a step back and see how the approach could perhaps be simplified and made more VBA-idiomatic.</p>\n\n<hr>\n\n<p>Starting with the constructor for the <code>Table</code> class:</p>\n\n<blockquote>\n<pre><code>Public Function Create(ByVal Actions As Collection, ByVal Table As ListObject) As Table\n With New Table\n Set .TableManagerActions = Actions\n Set .RefTable = Table\n .ColumnsCount = .RefTable.ListColumns.Count\n .RowsCount = .RefTable.DataBodyRange.Rows.Count\n Set Create = .Self\n End With\nEnd Function\n\nPrivate Sub Class_Initialize()\n Set appExcel = Excel.Application\n Set TableManagerActions = New Collection\nEnd Sub\n</code></pre>\n</blockquote>\n\n<p>The <code>Create</code> method takes a <code>Collection</code> of actions, so why does the <code>Class_Initialize</code> method need to <code>New</code> one up? </p>\n\n<p>And what about that <code>appExcel</code> - in this case you're lucky that <code>Excel.Application</code> will probably always refer to the same object, but better to supply that in the <code>Create</code> method too (dependency injection) - that will also make it easier to Unit Test as you can use a mock <code>Excel.Application</code> to raise events when you are testing.</p>\n\n<hr>\n\n<p>While we're here, do we even need a reference to the Application? The only events you hook into are <code>appExcel_SheetChange</code> and <code>appExcel_SheetSelectionChange</code> - since a ListObject can never span multiple worksheets, why not declare</p>\n\n<pre><code>Private WithEvents listObjectParentSheet As Excel.Worksheet\n</code></pre>\n\n<p>and use the sheet level <code>Change</code> and <code>SelectionChange</code> events instead?</p>\n\n<p>Better still, you can then use</p>\n\n<pre><code>Set listObjectParentSheet = Table.Parent\n</code></pre>\n\n<p>in the constructor to get the worksheet reference without passing it explicitly</p>\n\n<hr>\n\n<p>I don't really like these names:</p>\n\n<blockquote>\n<pre><code>.ColumnsCount = .RefTable.ListColumns.Count\n.RowsCount = .RefTable.DataBodyRange.Rows.Count\n</code></pre>\n</blockquote>\n\n<p>It looks like they might be the current value when really they are a cached value that's used in <code>GetAction</code> to see whether the dimensions of the table have changed. So name them as such: <code>cachedColumnCount</code> / <code>previousColumnCount</code> (drop the s too)</p>\n\n<hr>\n\n<p>Now what about those <em>actions</em>. As I say, currently they are being used as callbacks; that is <code>GetAction</code> enumerates various changes to the table, <code>ProcessRange</code>uses these enumerated action strings to call various routines which ultimately lead to invoking the action somewhere down the line:</p>\n\n<blockquote>\n<pre><code>Set strategy = TableManagerActions.Item(Action)\nstrategy.Run EvalCell, CurrentValue, previousValue\n</code></pre>\n</blockquote>\n\n<p>VBA already has a syntax for dealing with callbacks - Events. Instead of calling <code>ITableAction_Run</code>, your <code>Table</code> class could raise a custom <code>Add</code> or <code>Delete</code> or <code>Update</code> event. This way client code can <em>listen</em> for changes to the table, and hook any event handlers it fancies. You can then have different methods for handling events of different tables and don't need to construct a load of action objects.</p>\n\n<p>In summary, the <code>Table</code> class then does the following things:</p>\n\n<ol>\n<li>Listen to the encapsulated <code>ListObject</code>'s parent sheet for any changes</li>\n<li>Check whether these changes affect the encapsulated table, if so determine what kind of change occured (column added, row added, cell changed, table moved, row/column deleted etc.) by comparing to a cached version of the table.</li>\n<li>Generate any useful data you want the event listener to know about (If a row was added, which <code>ListRow</code> was it? If a cell was updated, then which cell and what was its previous value? If the table was moved, where from and to etc.)</li>\n<li><code>RaiseEvent ChangeKind(usefulData)</code> to notify any listeners of the change and run their event handlers (instead of calling an <code>ITableAction</code> directly)</li>\n</ol>\n\n<hr>\n\n<p>With those changes there will no longer be a need for <code>TableActions</code>. There will also be no <code>TableManagerActions</code> to save in the <code>Tables</code> collection, and therefore nothing in common between <code>Table</code> objects in the <code>Tables</code> collection except that they all live on the same worksheet. </p>\n\n<p>At this point I'd do away with the <code>Tables</code> class entirely - the <code>AddAllTablesInSheet</code> method can become a module function that takes a sheet as a parameter and spits out a simple collection of <code>Table</code> objects, or maybe passes them to a class that does the event listening and handling.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-08T15:10:53.783",
"Id": "460409",
"Score": "0",
"body": "Great insights! what you're suggesting **simplificates** the whole deal. thank you @greedo. I have really limited knowledge in `events`, so I'll try to implement them and post a follow up question to check if I correctly understood them."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-11T01:10:58.773",
"Id": "460862",
"Score": "0",
"body": "This is my follow up [question](https://codereview.stackexchange.com/q/235449/197645). Again thanks for the time you spent reviewing my code. Would appreciate if you can have a look at the new code."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-08T14:37:56.430",
"Id": "235295",
"ParentId": "235164",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "235295",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-06T12:55:15.157",
"Id": "235164",
"Score": "5",
"Tags": [
"object-oriented",
"vba",
"excel",
"rubberduck"
],
"Title": "Managing Excel Tables (ListObjects) with OOP Approach"
}
|
235164
|
<p>Please review this program because I wrote something in Python for the first time. This code is to be used for device authorization in oauth2 device flow.</p>
<pre><code>import requests
import webbrowser
import time
API_ENDPOINT = "<url>"
RESPONSE_TYPE = "device_code"
GRANT_TYPE = "device"
CLIENT_ID = "<client_id>"
data = {'response_type':RESPONSE_TYPE,
'client_id':CLIENT_ID}
response = requests.post(url = API_ENDPOINT, data = data) # sending post request and saving response as response object
json_response = response.json()
print("The user_code is:%s"%json_response['user_code'])
DEVICE_CODE = json_response['device_code']
webbrowser.open(json_response['verification_uri']) # open browser with idenity screen
data = {'grant_type':GRANT_TYPE,
'client_id':CLIENT_ID,
'code': DEVICE_CODE}
while True:
response = requests.post(url = API_ENDPOINT, data = data)
if response.status_code == 200:
json_response = response.json()
print("The access_token is:%s"%json_response['access_token'])
break
else:
print(response.text)
time.sleep(json_response['interval'])
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-06T14:01:12.450",
"Id": "235168",
"Score": "2",
"Tags": [
"python",
"python-3.x",
"oauth"
],
"Title": "Implementation of OAuth2 device flow using Python"
}
|
235168
|
<p>The <a href="https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes" rel="nofollow noreferrer">Sieve of Eratosthenes</a> is one of the oldest known algorithms and yet it is still the best method for sieving prime numbers in bulk in many situations. It is brutally simple, but to make it brutally fast requires adding a quite few complications. </p>
<p>A lot of information about these complications is availabe here on <a href="https://codereview.stackexchange.com/">Code Review</a>, on <a href="https://stackoverflow.com/">Stack Overflow</a> and elsewhere on the Web, but yet it seems surprisingly difficult to locate that information when one needs it, as it is scattered far and wide and intermingled with incredible amounts of noise. Hence I propose this series of articles which takes a simple, naive textbook implementation and introduces interesting complications one by one, including all the whys and wherefores. That way you can pick and choose when you craft your own version of the sieve for a specific purpose, or you can post your own version of a certain complication for others to study and admire.</p>
<p>I'll be using C# because it is readable for many programmers with other language backgrounds as well, and things like the built-in array bounds checking are big boon when doing rapid prototyping. Moreover, C# can be used with the free <a href="https://www.linqpad.net/" rel="nofollow noreferrer">LINQPad</a> which allows code & run cycles with a minimum of fuss and which adds a neat <code>Dump()</code> method to every class under the hood so that you can do things like</p>
<pre class="lang-cs prettyprint-override"><code>remaining_numbers(sieve_up_to(100)).Dump()
</code></pre>
<p>and see your results as a nicely formatted table. I usually use LINQPad to study algorithms and to prototype algorithmic optimisations, even if the final implementation language will be C++ or Delphi (or even T-SQL, in the case of check digit algorithms).</p>
<p>Here is a transcribed version of the algorithm given in the Wikipedia article <a href="https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes" rel="nofollow noreferrer">Sieve of Eratosthenes</a>:</p>
<pre><code>static bool[] sieve_up_to (uint n)
{
Trace.Assert(n < int.MaxValue); // in .NET, size_t is signed integer (!)
var eliminated = new bool[1 + n]; // arrays are 0-based but we will index by number
eliminated[0] = true; // 0 is not a prime, but the loop is unable to eliminate it
eliminated[1] = true; // 1 is not a prime, but the loop is unable to eliminate it
for (uint i = 2, sqrt_n = (uint)Math.Sqrt(n); i <= sqrt_n; ++i)
if (!eliminated[i])
for (uint j = i * i; j <= n; j += i)
eliminated[j] = true;
return eliminated;
}
</code></pre>
<p>The outer loop can terminate once <code>i</code> exceeds the square root of <code>n</code> because every composite <code>c ≤ n</code> must have at least one prime factor <code>p ≤ sqrt(n)</code> and thus will have been crossed off during the round for that <code>p</code>. </p>
<p>The inner loop can start at <code>i * i</code> for an analogous reason: all composites <code>c < i * i</code> must already have been crossed off because for a given prime <code>p</code> the number <code>p * p</code> is the smallest composite that does <em>not</em> contain prime factors smaller than <code>p</code>.</p>
<p>The logic of the sieve array is the opposite of that in the Wikipedia pseudo code; that is, it contains <code>true</code> for crossed-off numbers (non-primes). </p>
<p>There are three reasons for this. First, the old Greek didn't say 'make a cross next to all numbers that you want to sieve and then start removing the crosses in the following manner...'. Second, it is more logical. We're trying hard to something unto all composites and at the end we look at what's left unscathed; hence it makes sense to record what we're doing unto composites, instead of <em>undoing</em> a superfluous operation that was applied undiscriminately to all numbers in the range. Third, it is both less error-prone <em>and</em> more efficient to rely on the implicit 0/false/null initialisation guaranteed by the runtime, especially as it cannot be suppressed anyway. <em>(Sidenote: For more advanced sieves it can make sense to use different conventions, in order facilitate efficient decoding.)</em></p>
<p>The nested loop structure shows that the algorithm operates on two levels: on the outer level it enumerates the sieving primes, and on the inner level it does the actual sieving which - among other things - also produces new sieving primes. This is possible because the sieving range is anchored at the bottom and thus also includes any sieving primes that may be needed. </p>
<p>If the job of obtaining the sieving primes is delegated to a different function then the algorithm can be written like this, to make its structure and logic more apparent:</p>
<pre><code>foreach (var prime in primes_up_to((uint)Math.Sqrt(n)))
for (uint i = prime * prime; i <= n; i += prime)
eliminated[i] = true;
</code></pre>
<p>Of course, this offers no advantage if there is only ever one sieving to be done during a program run. It is, however, the first step towards sieving ranges that are not anchored at zero and which might therefore not include the necessary sieving primes.</p>
<p>The ability to sieve an arbitrary interval <code>[m, n]</code> instead of a zero-anchored range <code>[0, n]</code> can be helpful in several contexts - like when partitioning a range for the distribution of work in time or across several processors, or when solving coding challenges like the SPOJ problem <a href="https://www.spoj.com/problems/PRIME1/" rel="nofollow noreferrer">PRIME1</a>.</p>
<p>PRIME1 asks for the primes in a window that can go as high as 1,000,000,000 but which is at most 100,000 numbers wide. In such a case, sieving all primes up to the upper end of the window instead of just the primes in the target window would mean doing up to 10,000 times the amount of work that's necessary. A well-written sieve could still beat the generous time limit of 6 seconds but a windowed sieve takes only a fraction of a millisecond, a speed gain of four orders of magnitude.</p>
<p>Windowed sieving adds the complication of having to compute the point where the crossing-off sequence for a prime <code>p</code> first intersects with the sieving window. There are two cases:</p>
<p>1) If the starting point <code>p * p</code> of the striding sequence lies at or above the start of the window then this is as simple as subtracting the window base.</p>
<p>2) If the starting point lies before the start of the window then a bit of modulo magic is required. With window base <code>W</code>, starting point <code>K</code> and stride <code>S</code>, the expression <code>S - (W - K) % S</code> gives the right result except for the the special case <code>(W - K) % S == 0</code>. In that case the desired result is 0 but the expression gives <code>S</code>. This can be fixed by aiming the expression at <code>W - 1</code> instead of <code>W</code>, since adding a value between 1 and <code>S</code> to <code>W - 1</code> results in a value between <code>W + 0</code> and <code>W + S - 1</code> as desired. Hence the expression becomes </p>
<pre><code>(S - 1) - (W - 1 - K) % S
</code></pre>
<p>Et voilà, we can now sieve an arbitrary range of numbers:</p>
<pre><code>static bool[] sieve_between (uint m, uint n)
{
Trace.Assert(n - m < int.MaxValue);
uint sieve_bits = n - m + 1;
var eliminated = new bool[sieve_bits];
for (uint i = m; i < 2; ++i)
eliminated[i] = true;
foreach (uint prime in primes_up_to((uint)Math.Sqrt(n)))
{
uint start = prime * prime, stride = prime;
if (start >= m)
start -= m;
else
start = (stride - 1) - (m - start - 1) % stride;
for (uint j = start; j < sieve_bits; j += stride)
eliminated[j] = true;
}
return eliminated;
}
</code></pre>
<p>There is a separate variable <code>stride</code> for the step width because this value does not have to be equal to the current prime. </p>
<p>For example, for all primes <code>p</code> greater than 2 the number <code>p * p + p</code> must necessarily be even and hence must already have been crossed off. The same goes for all other slots whose distance from <code>p * p</code> is an odd multiple of <code>p</code>. This means we can skip the even multiples by setting</p>
<pre><code>stride = prime == 2 ? prime : 2 * prime;
</code></pre>
<p>for all primes > 2 and so save quite a bit of work. One simple way of accomplishing this without a conditional is by using the following initialising expression:</p>
<pre><code>stride = prime << (byte)(prime & 1); // cast necessary because of a C# language quirk
</code></pre>
<p>This is the simplest form of 'wheeled striding' - i.e. skipping multiples of small primes when stepping through the sieve array. IOW, we step only on slots where the corresponding wheel has a potentially prime-bearing spoke. For the mod 2 wheel, only the odd spoke can bear primes whereas the even spoke is always composite, with the exception of the slot for the wheel prime 2 itself.</p>
<p>Using wheeled striding in a sieve that is not wheeled or has a lesser wheel order realises only some of the possible benefits. In the example here we still had to allocate space for all even numbers, and the even numbers still had to be crossed off during the first round of the outer loop (the one for the prime 2). But we did halve the number of all subsequent crossings-off with just a minor index calculation trick, and this resulted in a noticeable speed-up. Wheeled striding can also be used profitably when enumerating ranges of numbers in a loop, like in a divisibility pre-check for big numbers.</p>
<p>Here are the timings for sieving a window of the given width whose lower end is 0, without and with the double stride trick:</p>
<pre><code> window stride = prime stride = p << (p & 1)
--------------------------------------------------------------------------------
32768 @ 0: 3514 primes 0,0 ms 1043,6 k/ms 0,0 ms 1588,1 k/ms
100000 @ 0: 9594 primes 0,2 ms 657,9 k/ms 0,1 ms 812,1 k/ms
1000000 @ 0: 78500 primes 2,5 ms 407,1 k/ms 1,6 ms 643,3 k/ms
10000000 @ 0: 664581 primes 36,1 ms 277,3 k/ms 25,0 ms 400,7 k/ms
100000000 @ 0: 5761457 primes 835,8 ms 119,6 k/ms 518,9 ms 192,7 k/ms
1000000000 @ 0: 50847536 primes 9995,7 ms 100,0 k/ms 5947,3 ms 168,1 k/ms
</code></pre>
<p>The timings show clearly that the simple sleight-of-hand trick with <code>stride</code> results in a noticeable speed-up.</p>
<p>Another option for the double stride thing would be to split out the round for the prime 2 and let the <code>for</code> loop start with the prime 3, so that all rounds can use the same value for the stride. The round for the prime 2 could then be replaced with blasting the pattern <code>true, false, true, false, ...</code> over the sieve with some buffer copy magic and adjusting for the prime 2 itself afterwards. </p>
<p>This is a simple example of the technique called 'presieving', whose speed gain comes from avoiding the crossing-off work for the handful for tiny primes that have the most 'hopping' to do because their strides ares so tiny. However, it is absolutely not worth it doing this here - there will be a separate article for this after we have harvested all the lower-hanging fruit. Besides, the sleight-of-hand trick with even multiples will become superfluous when odds-only sieving is introduced in the next article of this series.</p>
<p>And now the timings for sieving windows whose upper end is 10^9. This means that all sievings are using the exactly same number of sieve primes, and this in turn means that the speed differences are mostly due to the relation between the sieve size and the size of the memory caches of the CPU:</p>
<pre><code> window stride = prime stride = p << (p & 1)
---------------------------------------------------------------------------------------------------
32768 just before 1000000000: 1572 primes 0,1 ms 481,0 k/ms 0,0 ms 667,9 k/ms
100000 just before 1000000000: 4832 primes 0,3 ms 386,8 k/ms 0,2 ms 588,1 k/ms
1000000 just before 1000000000: 47957 primes 3,4 ms 296,0 k/ms 2,0 ms 495,8 k/ms
10000000 just before 1000000000: 482825 primes 57,2 ms 174,9 k/ms 40,8 ms 245,4 k/ms
100000000 just before 1000000000: 4838319 primes 1023,5 ms 97,7 k/ms 621,1 ms 161,0 k/ms
1000000000 just before 1000000000: 50847536 primes 9965,5 ms 100,3 k/ms 6080,9 ms 164,4 k/ms
</code></pre>
<p>As you can see, the sieving speed decreases as the sieve size exceeds first the L1 cache (32 KiB) and then the L2 cache (256 KiB), and it finally plateaus after significantly exceeding the L3 cache size of 8 MiB. Optimising the sieve for efficient cache usage is one goal of segmented sieving, which will be dealt with in a later article of this series.</p>
<p>Please observe the second line, which deals with the worst case for the PRIME1 scenario. As promised, just fractions of a millisecond.</p>
<p>Sidenote: apart from some special cases it can be advantageous to leave the sieving part and the part that extracts the primes from the sieve separate. For one thing, the separation facilitates unit testing and experimentation with various optimised implementations. For another, the specific task at hand may not require the actual primes at all but rather their count or sum or digest, or it may ask only for every thousandth prime. So you can leave the actual sieving code unchanged and simply write a processing function tailored to the task at hand.</p>
<p>Here is a little helper function for reading out the numbers that haven't been crossed off:</p>
<pre><code>static List<uint> remaining_numbers (bool[] eliminated, uint sieve_base = 0)
{
var result = new List<uint>();
for (uint i = 0, e = (uint)eliminated.Length; i < e; ++i)
if (!eliminated[i])
result.Add(sieve_base + i);
return result;
}
</code></pre>
<p>This can be used to obtain the primes in a given range <code>[m, n]</code> without having to compute <em>all</em> the primes up to <code>n</code>:</p>
<pre><code>static List<uint> primes_between (uint m, uint n)
{
return remaining_numbers(sieve_between(m, n), m);
}
</code></pre>
<p>That's it, the foundations of sieving à la Eratosthenes are all there. All that's left to do for further instalments is to take this poor code and disfigure it by adding one complication after the other - just for the sake of making it faster by orders of magnitude...</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-06T14:26:00.020",
"Id": "235169",
"Score": "1",
"Tags": [
"c#",
"primes",
"sieve-of-eratosthenes"
],
"Title": "Zen and the Sieve of Eratosthenes - Part 1: A Basic Windowed Sieve"
}
|
235169
|
<p>Hey everyone I have a very simple go REST API that is running CRUD operations on an in-memory object. I would love some feedback on how I can refactor this code, and how/if I should break this up into more than one file (<strong>main.go</strong>). I am extremely new to Go and want to learn the best way to write something like this.</p>
<p>Some areas that I think could use improvement:</p>
<ol>
<li>The way my code is handling 500s</li>
<li>JSON Request field validation feels like I am repeating it a lot</li>
<li>File structure/organization</li>
</ol>
<p>Any help would be greatly appreciated. Below is my code:</p>
<pre><code>type Trade struct {
ClientTradeId string `json:"client_trade_id" validate:"nonzero, min=1, max=256"`
Date int `json:"date" validate:"nonzero, min=20010101, max=21000101"`
Quantity string `json:"quantity" validate:"regexp=^[-]?[0-9]*\\.?[0-9]+$"`
Price string `json:"price" validate:"nonzero, regexp=^[-]?[0-9]*\\.?[0-9]+$"`
Ticker string `json:"ticker" validate:"nonzero"`
}
type InternalTrade struct {
Id string `json:"Id" validate:"nonzero"`
Trade *Trade `json:"Trade"`
}
type TradeSubmitted struct {
TradeId string `json:"TradeId" validate:"nonzero"`
ClientTradeId string `json:"clientTradeId" validate:"nonzero"`
}
type Error struct {
Message string `json:"Message"`
}
var trades []InternalTrade
var submitArray []TradeSubmitted
var (
tradeValidator = validator.NewValidator()
)
func getTrades(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
err := json.NewEncoder(w).Encode(trades)
if err != nil {
e := Error{Message:"Internal Server Error"}
w.WriteHeader(http.StatusInternalServerError)
_ = json.NewEncoder(w).Encode(e)
return
}
}
func getTradeById(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
params := mux.Vars(r)
for _, trade := range trades {
if trade.Id == params["trade_id"] {
_ = json.NewEncoder(w).Encode(trade)
return
}
}
e := Error{Message: "ID Not Found"}
w.WriteHeader(http.StatusNotFound)
if err := json.NewEncoder(w).Encode(e); err != nil {
e := Error{Message:"Internal Server Error"}
http.Error(w, e.Message, http.StatusInternalServerError)
}
}
func createTrade(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
var tradeArray []Trade
if err := json.NewDecoder(r.Body).Decode(&tradeArray); err != nil {
e := Error{Message:"Not processable - Missing Required"}
w.WriteHeader(http.StatusBadRequest)
_ = json.NewEncoder(w).Encode(e)
return
}
for _, trade := range tradeArray {
th := trade
if errs := tradeValidator.Validate(&th); errs != nil {
e := Error{Message: "Bad Request - Improper Types Passed"}
w.WriteHeader(http.StatusUnprocessableEntity)
_ = json.NewEncoder(w).Encode(e)
return
}
}
for i := range tradeArray {
internal := InternalTrade{
Id: strconv.Itoa(rand.Intn(1000000)),
Trade: &tradeArray[i],
}
submit := TradeSubmitted{
TradeId: internal.Id,
ClientTradeId: internal.Trade.ClientTradeId,
}
submitArray = append(submitArray, submit)
trades = append(trades, internal)
}
if err := json.NewEncoder(w).Encode(submitArray); err != nil {
e := Error{Message:"Internal Server Error"}
w.WriteHeader(http.StatusInternalServerError)
_ = json.NewEncoder(w).Encode(e)
return
}
}
func deleteTrade(w http.ResponseWriter, r *http.Request) {
params := mux.Vars(r)
for idx, trade := range trades {
if trade.Id == params["trade_id"] {
trades = append(trades[:idx], trades[idx+1:]...)
w.WriteHeader(http.StatusNoContent)
return
}
}
e := Error{Message:"ID Not Found"}
w.WriteHeader(http.StatusNotFound)
if err := json.NewEncoder(w).Encode(e); err != nil {
e := Error{Message:"Internal Server Error"}
http.Error(w, e.Message, http.StatusInternalServerError)
}
}
func updateTrade(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
params := mux.Vars(r)
for idx, trade := range trades {
if trade.Id == params["trade_id"] {
trades = append(trades[:idx], trades[idx+1:]...)
var internal InternalTrade
_ = json.NewDecoder(r.Body).Decode(&internal.Trade)
internal.Id = params["trade_id"]
trades = append(trades, internal)
json.NewEncoder(w).Encode(internal)
return
}
}
e := Error{Message:"ID Not Found"}
w.WriteHeader(http.StatusNotFound)
if err := json.NewEncoder(w).Encode(e); err != nil {
e := Error{Message:"Internal Server Error"}
http.Error(w, e.Message, http.StatusInternalServerError)
}
}
func main() {
router := mux.NewRouter()
trades = append(trades, InternalTrade{ Id:"1", Trade: &Trade{ClientTradeId: "T-50264430-bc41", Date:20200101,
Quantity:"100", Price:"10.00", Ticker:"APPL"}})
trades = append(trades, InternalTrade{ Id:"2", Trade: &Trade{ClientTradeId: "T-99999999-ab14", Date:20200101,
Quantity:"100", Price:"420.00", Ticker:"TSLA"}})
router.HandleFunc("/v1/trades", getTrades).Methods("GET")
router.HandleFunc("/v1/trades/{trade_id}", getTradeById).Methods("GET")
router.HandleFunc("/v1/trades", createTrade).Methods("POST")
router.HandleFunc("/v1/trades/{trade_id}", deleteTrade).Methods("DELETE")
router.HandleFunc("/v1/trades/{trade_id}", updateTrade).Methods("PUT")
log.Fatal(http.ListenAndServe(":8080", router))
}
</code></pre>
|
[] |
[
{
"body": "<p>For your first Go program this looks very good, apart from the global\nvariables the code looks easy to read; the annotations for JSON\nprocessing and validation are fine and you're also using a standard\nlibrary for the routing. Overall, doesn't raise any big issues for me.</p>\n\n<hr>\n\n<p>Firstly though, I'd highly suggest that the <code>trades</code> and <code>submitArray</code>\nglobal variables are changed into member variables in a handler\nstructure and secondly protected against concurrent access. The first\nbit will help organising code in larger projects, you almost never want\nglobals lying around like that. The second one is simply necessary when\ndata is modified from potentially multiple threads.</p>\n\n<p>The handler functions share a lot of code for setup; it'd be good to\nextract some common functionality perhaps, or to use a library that\ndeals with, say, JSON and REST routes specifically.</p>\n\n<p>There's some error handling missing where the error results are\nexplicitly discarded, that's somewhat of a bad style, though\nunderstandable for things like the JSON encoding. How about simply\nlogging those errors at least?</p>\n\n<p>Also again the JSON error handling deserves its own function to make it\nall less repetitive.</p>\n\n<hr>\n\n<p>Specifically regarding your questions:</p>\n\n<ol>\n<li>The error handling is fine, even though the error messages themselves\ncould be more expressive, if you choose to not return the error\nmessage itself, at least log it for your own debugging purposes.</li>\n<li>Validation looks okay to me? Apart from <code>Data</code>, there's a lot of\ndates that the validation here accepts that can never be real dates.\nConsider stronger validation for a real project, otherwise you might\nend up with lots of \"month 99\" in your data.</li>\n<li>Looks okay, ordering this way definitely makes sense, although with\nmore definitions you might have to split things up into multiple\nfiles.</li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-14T11:19:11.803",
"Id": "235599",
"ParentId": "235173",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "235599",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-06T15:46:27.127",
"Id": "235173",
"Score": "2",
"Tags": [
"json",
"go",
"rest"
],
"Title": "Golang REST API that CRUDS in-memory object"
}
|
235173
|
<p>I was recently tasked to write an implementation of the <a href="https://en.wikipedia.org/wiki/Berlekamp%E2%80%93Massey_algorithm" rel="nofollow noreferrer">Berlekamp–Massey algorithm</a> (for GF2) from a given inductional proof and decided to fresh up on my Haskell, since converting a proof by induction into a recursive algorithm should be quite straight-forward.</p>
<p>The variable names have been taken from the given proof (and thus can't be changed, although they differ from other notations or are rather short); here's a map:</p>
<ul>
<li><code>ks</code>: the input bit stream</li>
<li><code>len</code>: the length of <code>ks</code></li>
<li><code>n</code>: degree of the current annihilating polynomial</li>
<li><code>phi</code>: said polynomial, where a "bit" set at position <span class="math-container">\$i\$</span> indicates that the the <span class="math-container">\$i\$</span>-th power is "part" of the polynomial, ie.:
<span class="math-container">$$
\varphi(X) = \sum_{i=0}^n \text{phi}[i] \cdot X^i
$$</span></li>
<li><code>s</code>, <code>psi</code>: analogously the degree and the polynomial itself of the last iteration that had different values</li>
<li><code>r</code>: the maximum length of the prefix of <code>ks</code> that <code>psi</code> annihilates successfully</li>
<li><code>dl</code>: the discrepancy between the annihilation by <code>phi</code> and the <span class="math-container">\$l\$</span>-prefix of <code>ks</code></li>
<li><code>eta</code>: The new polynomial, calculated as:
<span class="math-container">$$
\eta(X) = \varphi(X) + X^{l-r} \cdot \psi(X)
$$</span></li>
</ul>
<pre class="lang-haskell prettyprint-override"><code>data State = State { n :: Int
, phi :: [Int]
, s :: Int
, psi :: [Int]
, r :: Int
}
deriving Show
discr :: Int -> [Int] -> Int -> [Int] -> Int
discr l ks n phi = foldr (\ a k -> (a+k) `mod` 2) 0
(zipWith (*) (take (n+1) phi) (reverse $ take (n+1) $ drop (l-n) ks))
buildEta :: [Int] -> [Int] -> Int -> Int -> Int -> [Int]
buildEta phi psi l r s
= (take (l-r) phi) ++
(zipWith (\ c b -> (c+b) `mod` 2) (take (s+1) $ drop (l-r) phi) (take (s+1) psi)) ++
(drop (l-r+s+1) phi)
bk' :: Int -> [Int] -> State
bk' (-1) ks = State 0 (1:lenzeroes) 0 (1:lenzeroes) (-1)
where lenzeroes = replicate (length ks) 0
bk' l ks
| dl == 0 = State n phi s psi r
| n*2 <= l = State (l+1-n) eta n phi l
| otherwise = State n eta s psi r
where State n phi s psi r = bk' (l-1) (ks)
dl = discr l ks n phi
eta = buildEta phi psi l r s
bk :: [Int] -> (Int,[Int])
bk ks = (n,phi)
where State n phi _ _ _ = bk' (length ks) ks
</code></pre>
<p>I'm not quite happy with the result though, especially the <code>buildEta</code> function and the use of <code>length</code>. I think the latter could be improved by reversing <code>ks</code> and then giving only the tail to the recursive call, but somehow I still need to build the <code>phi</code> and <code>psi</code> lists correctly, which I fail to do "nicely".</p>
<p>Style aside, the code works (as far as I know), eg.:</p>
<pre><code>*Main> bk [1, 0, 1, 0, 0, 1, 1, 0, 1]
(5,[1,0,1,0,1,1,0,0,0])
</code></pre>
<p>Which means that the degree of the polynomial is <span class="math-container">\$n\$</span> and it has the following form:
<span class="math-container">$$
\varphi = X^0 + X^2 + X^4 + X^5
$$</span>
Or, as an LSFR, <code>A=[1,1,0,1,0]</code> which indeed generates <code>ks</code> with <code>[1, 0, 1, 0, 0]</code> as initialization sequence.</p>
<hr>
<p>Edit: Had someone review my code offline and did some minor style fixes already:</p>
<ul>
<li>some point-free style where appropriate</li>
<li>replacing some lambda with just <code>(*)</code></li>
<li>replacing <code>sum ()</code>mod<code>2</code> with <code>foldr</code> and lambda</li>
<li>found a way to rewrite the if-then-else into nice guards</li>
<li>replaced the list-comprehension for zeroes with <code>replicate</code></li>
<li>line breaks :-)</li>
</ul>
|
[] |
[
{
"body": "<p>A central question I ask myself on these is whether the explicit recursion follows an abstractable pattern. In this case, only <code>bk'</code> has explicit recursion, and its pattern is simple - the call tree is always linear and brings <code>l</code> incrementally down to <code>-1</code>.</p>\n\n<p><code>buildEta</code> applies a transformation to a particular slice of <code>phi</code>.</p>\n\n<p>Why are you working with <code>Int</code>s? These are <code>Bool</code>s.</p>\n\n<pre><code>bk :: [Bool] -> (Int,[Bool])\nbk ks = (n,phi) where\n State n phi _ _ _ = foldr (bk' ks) (State 0 lenzeroes 0 lenzeroes (-1)) [l,l-1..0]\n lenzeroes = True : replicate l False\n l = length ks\n\nbk' :: [Bool] -> Int -> State -> State\nbk' ks l (State n phi s psi r)\n | not dl = State n phi s psi r\n | n*2 <= l = State (l+1-n) eta n phi l\n | otherwise = State n eta s psi r\n where dl = discr l ks n phi\n eta = overSlice (l-r) (s+1) (zipWith xor psi) phi\n\ndiscr :: Int -> [Bool] -> Int -> [Bool] -> Bool\ndiscr l ks n = foldr xor False . zipWith (&&) (reverse $ take (n+1) $ drop (l-n) ks)\n\noverSlice :: Int -> Int -> ([a] -> [a]) -> ([a] -> [a])\noverSlice from size f a = b ++ f d ++ e where\n (b, c) = splitAt from a\n (d, e) = splitAt size c\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-07T14:48:05.710",
"Id": "235229",
"ParentId": "235174",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "235229",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-06T16:21:10.510",
"Id": "235174",
"Score": "2",
"Tags": [
"haskell",
"recursion",
"mathematics",
"cryptography"
],
"Title": "Berlekamp–Massey Algorithm in Haskell"
}
|
235174
|
<p>There is a table in Oracle database with the following data </p>
<pre><code>+----+-----+-------+---------+---------+---------+
| Id | Key | Value | Is_Orig | Is_Prev | Is_Curr |
+----+-----+-------+---------+---------+---------+
| 1 | 10 | 1000 | 1 | 0 | 0 |
| 2 | 10 | 2000 | 0 | 0 | 0 |
| 3 | 10 | 3000 | 0 | 1 | 0 |
| 4 | 10 | 4000 | 0 | 0 | 1 |
| 5 | 20 | 100 | 1 | 0 | 0 |
| 6 | 20 | 300 | 0 | 1 | 0 |
| 7 | 20 | 400 | 0 | 0 | 1 |
| 8 | 30 | 10 | 1 | 0 | 0 |
+----+-----+-------+---------+---------+---------+
</code></pre>
<p>I need to query the table and display the data as follows </p>
<pre><code>+-----+------------+------------+------------+
| Key | Orig Value | Prev Value | Curr Value |
+-----+------------+------------+------------+
| 10 | 1000 | 3000 | 4000 |
| 20 | 100 | 300 | 400 |
| 30 | 10 | n/a | n/a |
+-----+------------+------------+------------+
</code></pre>
<p>I was thinking on the following lines. </p>
<pre><code>SELECT t1.key, t1.orig_value, t2.prev_value, t3.curr_value
FROM (
(SELECT key, value as orig_value
FROM statistics
WHERE is_orig = 1
) AS t1,
(SELECT key, value as prev_value
FROM statistics
WHERE is_prev = 1
) AS t2,
(SELECT key, value as curr_value
FROM statistics
WHERE is_curr = 1
) AS t3
)
</code></pre>
<p>This works; but is there a better way to get the desired result? </p>
<p>Kindly note that is_orig=1, is_prev=1, and is_curr=1 are all mutually exclusive of each other. Hence, the three separate queries. </p>
|
[] |
[
{
"body": "<p>You can use aggregation like this:</p>\n\n<pre><code>select \"Key\", \n MAX(CASE WHEN \"Is_Orig\" = 1 THEN \"Value\" END) \"Orig Value\",\n MAX(CASE WHEN \"Is_Prev\" = 1 THEN \"Value\" END) \"Prev Value\",\n MAX(CASE WHEN \"Is_Curr\" = 1 THEN \"Value\" END) \"Curr Value\"\nfrom statistics\ngroup by \"Key\"\n</code></pre>\n\n<p>The <code>CASE</code> statements select the value in each case and return <code>NULL</code> in the other cases. <code>MAX</code> is just to get that one value from the nulls.</p>\n\n<p>Have a look at <a href=\"https://modern-sql.com/use-case/pivot\" rel=\"nofollow noreferrer\">https://modern-sql.com/use-case/pivot</a> for some background. It also refers to an Oracle specific feature called \"modeling\" that allows a similar thing.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-08T05:36:03.033",
"Id": "460355",
"Score": "0",
"body": "Works like a charm; cannot thank you enough for this one."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-07T09:09:34.840",
"Id": "235210",
"ParentId": "235175",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-06T16:43:06.803",
"Id": "235175",
"Score": "1",
"Tags": [
"performance",
"sql",
"oracle"
],
"Title": "Clubbing three queries that return mutually exclusive records"
}
|
235175
|
<p>I've made this GUI program for my workplace that checks whether measured coordinates on machined components are within spec.</p>
<p>It takes in specified coordinates, tolerance and measured coordinates and uses Pythagoras to check whether the tolerance has been exceeded.</p>
<p>It then plots the measured point relative to the 'true point' on a tkinter canvas which can be scaled up and down with the slider widget (points are scaled proportionally - this was the challenging bit for me). The tolerance value determines the radius of the circle shown below.</p>
<p><a href="https://i.stack.imgur.com/TZVal.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/TZVal.png" alt="enter image description here"></a></p>
<p>I've ran the program through pylint and am now getting good results (9.72). I'm now hoping for a bit of feedback on anything I could have done better. I was also trying to work to OOP ideas. Any comments about these or other areas would be much appreciated.</p>
<p>The code posted here is a revision of that posted in: <a href="https://codereview.stackexchange.com/questions/234976/plotting-whether-measured-locations-for-components-are-within-spec">Plotting Whether Measured Locations for Components are Within Spec</a></p>
<pre class="lang-py prettyprint-override"><code>"""Validates points against engineering drawing according to specified tolerance"""
from tkinter import Tk, Label, Entry, GROOVE, Button, IntVar, Canvas, Scale, Checkbutton, DoubleVar, Widget, Variable
import math
class TruePosition:
"""Populates Tk window object with widgets"""
def __init__(self, master):
self.master = master
master.title('True Position Validator')
self.h_cor = DoubleVar()
self.k_cor = DoubleVar()
self.tol_cor = DoubleVar()
self.x_cor = DoubleVar()
self.y_cor = DoubleVar()
self.checkvar = IntVar()
self.entries = []
self.heading('True Point Location Details')
self.row('Point Loc:', self.h_cor, ',', self.k_cor)
self.row('Tolerance:', self.tol_cor)
self.heading('Measured Point Location Details')
self.row('Point Loc:', self.x_cor, ',', self.y_cor)
btn = Button(master, text='Submit', font=('Technic', 10),
command=lambda: self.submit_action())
self.row(None, None, None, btn)
self.labelout = self.row("")[0]
self.labelout.grid(columnspan = 4)
self.display_canvas = Canvas(master, bg='white', border=2, highlightthickness=1,
highlightbackground='black')
self.display_canvas.grid(row=8, columnspan=4, sticky='s')
bclear = Button(master, text='Clear', font=('Technic', 10),
command=lambda: self.clearcrosses())
retain = Checkbutton(master, text='Retain plots', variable=self.checkvar,
command=lambda: self.box_check())
self.row(retain, None, None, bclear)[1].grid(sticky = 'n')
self.slider = Scale(master, orient='horizontal', from_=0, to=100,
command=lambda factor: self.scalar(factor=float(factor)))
self.slider.set(100)
self.slider.grid(row=9, columnspan=4)
self.master.bind("<Return>", lambda t: self.submit_action())
self.canvas_width = self.display_canvas.winfo_reqwidth()
self.canvas_height = self.display_canvas.winfo_reqheight()
# Running Variables
self.cross = False
self.stored_points = []
self.line_length = 10
self.h_val = None
self.k_val = None
self.tol_val = DoubleVar()
self.x_val = None
self.y_val = None
self.real = None
self.clearance = None
self.radius = DoubleVar()
self.linea_x1 = None
self.linea_x2 = None
self.linea_y = None
self.lineb_y1 = None
self.lineb_y2 = None
self.lineb_x = None
self.linea = None
self.lineb = None
self.meas_point(self.canvas_width/2, self.canvas_height/2)
self.create_points()
self.truecircle = self.display_canvas.create_oval(0, 0, 0, 0, outline='black', dash=(4, 5))
# Functions
def heading(self, title):
_, rows = self.master.grid_size()
label = Label(self.master, text=title, font=('Technic', 14))
label.grid(row=rows, columnspan=4, sticky='w')
def row(self, *fields):
_, rows = self.master.grid_size()
widgets = [] # resets list every time, so when I pass in the one label item, it is the only widget in the list
for col, field in enumerate(fields):
widget = None
if isinstance(field, str):
widget = Label(self.master, text=field, font=('Technic', 14))
elif isinstance(field, Variable):
widget = Entry(self.master, textvar=field, relief=GROOVE)
self.entries.append(field)
elif isinstance(field, Widget):
widget = field
if widget:
widget.grid(row=rows, column=col, sticky ='w')
widgets.append(widget)
return widgets
def box_check(self):
"""Acknowledges box check & stores existing point if switching from-non retention mode"""
if self.checkvar.get() == 1 and self.cross:
self.store_points()
elif self.checkvar.get() == 0:
self.clearcrosses()
print('ran box_check\n')
def submit_action(self):
"""Accepts user input and runs subsequent functions"""
try:
self.calctrue()
self.showtrue()
self.meas_point(self.x_val, self.y_val, 'cross')
if not self.cross or self.checkvar.get() == 1:
self.create_points('cross')
self.cross = True
if self.checkvar.get() == 1:
self.store_points()
else:
pass
elif self.cross:
self.move_points(self.linea, self.lineb)
except ValueError: # Accounts for accidental pressing of submit before all data is entered
self.labelout.config(fg='black')
self.labelout['text'] = 'ValueError : Make sure all fields have been completed.'
except ZeroDivisionError: # Accounts for accidental pressing of submit before all data is entered
self.labelout.config(fg='black')
self.labelout['text'] = 'ValueError : Make sure all fields have been completed.'
print('ran submit_action()\n')
def scalar(self, factor):
"""Runs logic that changes circle size in response to
slider and remeasures & shifts existing points"""
self.getplot_circ(factor)
if self.checkvar.get() == 0 and self.cross:
self.meas_point(self.x_val, self.y_val, 'cross')
self.move_points(self.linea, self.lineb)
elif self.checkvar.get() == 1 and self.cross:
for pnt0, pnt1 in self.stored_points:
self.meas_point(*pnt1, 'cross')
self.move_points(*pnt0)
elif not self.cross:
pass
print('ran scalar\n')
def getplot_circ(self, factor):
"""Changes circle size"""
factor = 192 - (factor*1.27)
self.radius = (self.canvas_width/2)- factor
c1_x = (self.canvas_width/2) - self.radius
c1_y = (self.canvas_height/2) - self.radius
c2_x = (self.canvas_width/2) + self.radius
c2_y = (self.canvas_height/2) + self.radius
self.display_canvas.coords(self.truecircle, c1_x, c1_y, c2_x, c2_y)
print('ran getplot_circ()')
def calctrue(self):
"""Determines if point is within spec"""
self.h_val = self.h_cor.get()
self.k_val = self.k_cor.get()
self.tol_val = self.tol_cor.get()
self.x_val = self.x_cor.get()
self.y_val = self.y_cor.get()
self.real = math.hypot(self.x_val - self.h_val, self.y_val - self.k_val)
self.clearance = self.tol_val - self.real
print('ran calctrue()')
def showtrue(self):
"""Provides non-graphical feedback about results of calctrue"""
if self.tol_val >= self.real:
self.labelout.config(fg='green')
self.labelout['text'] = f'Position is within spec by {round(self.clearance, 4)}'
self.display_canvas.itemconfig(self.truecircle, outline='green')
elif self.tol_val < self.real:
self.labelout.config(fg='red')
self.labelout['text'] = f'Position is outwith spec by {round(abs(self.clearance), 4)}'
self.display_canvas.itemconfig(self.truecircle, outline='red')
def meas_point(self, loc_x, loc_y, tag='all'):
"""defines new point in terms of current circle & canvas geometry"""
pix_x = 5
if tag == 'all':
pix_x = loc_x
pix_y = loc_y
elif tag == 'cross':
scale = self.radius/self.tol_val
print('scale')
pix_x = (scale * (loc_x-self.h_val)) + self.canvas_width/2
pix_y = (-scale * (loc_y-self.k_val)) + self.canvas_height/2
self.linea_x1 = (pix_x - (self.line_length/2))
self.linea_x2 = (pix_x + (self.line_length/2))
self.linea_y = (pix_y)
self.lineb_y1 = (pix_y - (self.line_length/2))
self.lineb_y2 = (pix_y + (self.line_length/2))
self.lineb_x = (pix_x)
print('ran meas_point')
def create_points(self, tag='all'):
"""Plots new cross point"""
self.linea = self.display_canvas.create_line(self.linea_x1, self.linea_y,
self.linea_x2, self.linea_y, tag=tag)
self.lineb = self.display_canvas.create_line(self.lineb_x, self.lineb_y1,
self.lineb_x, self.lineb_y2, tag=tag)
print('ran create_points()')
def move_points(self, linea, lineb):
"""Shifts cross point to measured locations"""
self.display_canvas.coords(linea, self.linea_x1, self.linea_y,
self.linea_x2, self.linea_y)
self.display_canvas.coords(lineb, self.lineb_x, self.lineb_y1,
self.lineb_x, self.lineb_y2)
print('ran move_points()')
def store_points(self):
"""stores points for rescaling if slider is used"""
self.stored_points.append(((self.linea, self.lineb), (self.x_val, self.y_val)))
print('ran store_points()')
def clearcrosses(self):
"""deletes all user input"""
for item in self.display_canvas.find_withtag('cross'):
self.display_canvas.delete(item)
self.labelout['text'] = ''
self.display_canvas.itemconfig(self.truecircle, outline='black')
self.cross = False
self.stored_points = []
for instance in self.entries:
instance.set('')
print('ran clearcrosses()\n')
ROOT = Tk()
MYAPP = TruePosition(ROOT)
ROOT.mainloop()
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-06T17:12:08.690",
"Id": "235177",
"Score": "2",
"Tags": [
"python",
"python-3.x",
"object-oriented",
"gui",
"tkinter"
],
"Title": "Plotting Whether Measured Locations for Components are Within Spec - follow-up"
}
|
235177
|
<p>I wrote a code that retrieves categories from DB and act as dynamic category search. I kindly ask you to review my code and tell me if the code can be optimized/improved. Thank you for your help.</p>
<p>This is the html code.</p>
<pre><code><!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
.dropbtn {
background-color: #4CAF50;
color: white;
padding: 16px;
font-size: 16px;
border: none;
cursor: pointer;
}
.dropbtn:hover, .dropbtn:focus {
background-color: #3e8e41;
}
#myInput {
box-sizing: border-box;
background-image: url('searchicon.png');
background-position: 14px 12px;
background-repeat: no-repeat;
font-size: 16px;
padding: 14px 20px 12px 45px;
border: none;
border-bottom: 1px solid #ddd;
}
#myInput:focus {outline: 3px solid #ddd;}
.dropdown {
position: relative;
display: inline-block;
}
.dropdown-content {
display: none;
position: absolute;
background-color: #f6f6f6;
min-width: 200px;
overflow: auto;
border: 1px solid #ddd;
z-index: 1;
}
.dropdown-content a {
color: black;
padding: 12px 16px;
text-decoration: none;
display: block;
}
.show {display: block;}
.selected {
background:#efefef;
}
</style>
</head>
<body>
<h2>Search/Filter Dropdown</h2>
<p>Click on the button to open the dropdown menu, and use the input field to search for a specific dropdown link.</p>
<input name="cat" id="test" type="text" placeholder="220" value="" readonly="readonly" size="4">
<div class="dropdown">
<button onclick="loadXmlDoc(0)" class="dropbtn"><span id="categoriego">Dropdown</span></button>
<div id="myDropdown" class="dropdown-content">
<input type="text" placeholder="Cauta..." id="cautare" oninput="filterFunction()">
<span id="innermenu"></span>
</div>
</div><br>
<script>
rezultat=[];
filteredarr = [];
flag=0;
gos=0;
cautare = document.getElementById("cautare");
innermenu = document.getElementById("innermenu");
myDropdown=document.getElementById("myDropdown");
categoriego=document.getElementById("categoriego");
test=document.getElementById("test");
async function loadXmlDoc(cat){
let reposResponse = await fetch(`post.php?cat=`+cat);
rezultat = await reposResponse.json();
var eacha=[];
for (i = 0; i < rezultat.length; i++) {
eacha[i] = "<a id="+ i +">"+rezultat[i][1]+"("+rezultat[i][0]+")"+"</a>";
}
cautare.value="";
innermenu.innerHTML=eacha.join("");
myDropdown.classList.toggle("show");
cautare.focus();
flag=0;
document.getElementById(0).style.background = "#ddd";
}
function filterFunction(){
var eachb=[];
filteredarr = [];
counter=0;
filter = cautare.value.toUpperCase();
for (i = 0; i < rezultat.length; i++) {
defiltrat=rezultat[i][0]+rezultat[i][1];
if (defiltrat.toUpperCase().indexOf(filter) > -1) {
eachb[i] = "<a id="+counter+">"+rezultat[i][1]+"("+rezultat[i][0]+")"+"</a>";
filteredarr.push([rezultat[i][0],rezultat[i][1]]);
counter++;
flag=1;
gos=0;
}
}
innermenu.innerHTML=eachb.join("");
document.getElementById(0).style.background = "#ddd";
}
innermenu.addEventListener('mouseover', function(e){
lennt=rezultat;
if(flag==1){
lennt=filteredarr;
}
for (i = 0; i < lennt.length; i++) {
document.getElementById(i).style.background = "";
}
gos=e.target.id;
document.getElementById(gos).style.background = "#ddd";
}, false);
innermenu.addEventListener('click', function(e){
lennt=rezultat;
if(flag==1){
lennt=filteredarr;
}
myDropdown.classList.toggle("show");
categoriego.innerHTML=lennt[gos][1];
test.value=lennt[gos][0];
gos=0;
}, false);
cautare.addEventListener('keydown', function(e){
document.getElementById(gos).style.background = "";
lennt=rezultat;
if(flag==1){
lennt=filteredarr;
}
if(e.which == 38){
gos--;
if(gos<0)
{
gos=0;
}
}
if(e.which == 40){
gos++;
if(gos==lennt.length)
{
gos=lennt.length-1;
}
}
if(e.which == 13){
categoriego.innerHTML=lennt[gos][1];
myDropdown.classList.toggle("show");
test.value=lennt[gos][0];
gos=0;
}
document.getElementById(gos).style.background = "#ddd";
console.log(gos);
});
</script>
</body>
</html>
</code></pre>
<p>and this is the post.php for testing purposes</p>
<pre><code><?php
$cars = array
(
array(55,"Volvo"),
array(42,"BMW"),
array(13,"Saab"),
array(71,"Renault"),
array(88,"Toyota"),
array(99,"Peugeot"),
array(21,"Land Rover")
);
echo json_encode($cars);
?>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-08T16:18:56.330",
"Id": "460420",
"Score": "1",
"body": "Please use one language, either romanian either english. And for next posts try to use english, will be more easier for the reviewers to read the variables and understand what are you trying to do. :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-08T18:06:06.827",
"Id": "460447",
"Score": "0",
"body": "Thanks for the heads up."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-06T18:02:43.297",
"Id": "235178",
"Score": "3",
"Tags": [
"javascript"
],
"Title": "Drop-down menu with autofilter and click/enter for selection and navigation by mouse/arrow keys"
}
|
235178
|
<p>I have the following function in Django to download the Fasta sequences (protein) through the selected categories as a file. This works well. I would like to improve the following script.</p>
<pre><code>import textwrap
from io import StringIO
from django.shortcuts import render
from django.http import HttpResponse
from database.models import PesticidalProteinDatabase
def download_data(request):
"""List the categories for download."""
categories = \
PesticidalProteinDatabase.objects.order_by(
'name').values_list('name').distinct()
category_prefixes = []
for category in categories:
prefix = category[0][:3]
if prefix not in category_prefixes:
category_prefixes.append(prefix)
context = {
'proteins': PesticidalProteinDatabase.objects.all(),
'category_prefixes': category_prefixes
}
return render(request, 'database/download_category.html', context)
def download_category(request, category=None):
"""Download the fasta sequences for the category."""
context = {
'proteins': PesticidalProteinDatabase.objects.all()
}
category = category.title()
file = StringIO()
data = list(context.get('proteins'))
for item in data:
if category in item.name:
fasta = textwrap.fill(item.fastasequence, 80)
str_to_write = f">{item.name}\n{fasta}\n"
file.write(str_to_write)
else:
pass
if 'All' in category:
for item in data:
fasta = textwrap.fill(item.fastasequence, 80)
str_to_write = f">{item.name}\n{fasta}\n"
file.write(str_to_write)
response = HttpResponse(file.getvalue(), content_type="text/plain")
download_file = f"{category}_fasta_sequences.txt"
response['Content-Disposition'] = 'attachment;filename='+download_file
response['Content-Length'] = file.tell()
return response
</code></pre>
<p>The template data</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>{% extends "database/base.html" %}
{% load static %}
{% block content %}
<!doctype html>
<div id="wrapper">
<p> <b> Download the fasta sequences by categories </b> </p>
{% for prefix in category_prefixes %}
<li>
<a href="/download_category_{{ prefix|lower }}" >
{{ prefix }}
{% endfor %}
<br>
<li>
<a href="/download_category_all" > All
</li>
</div>
{% endblock content %}</code></pre>
</div>
</div>
</p>
<p>The url data</p>
<pre><code>from django.urls import path
from database import views
path('download_data/', views.download_data, name='download_data'),
path('download_category_<str:category>', views.download_category,
name='download_category'),
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-07T06:52:59.787",
"Id": "460223",
"Score": "0",
"body": "It's fine you want a focus on this particular function, but I'm sure there's more to the script. Could you add that as well?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-07T18:13:12.910",
"Id": "460310",
"Score": "1",
"body": "I have added the script. Also here is the full [database](https://codereview.stackexchange.com/q/228912/181325)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-08T22:58:58.987",
"Id": "460498",
"Score": "0",
"body": "@catuf How is the program used, though? Also, I believe the indentation in your post is broken."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-09T00:45:54.637",
"Id": "460505",
"Score": "0",
"body": "I forgot to mention that anything more than minor optimizations will require other parts of the program."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-09T19:13:18.640",
"Id": "460647",
"Score": "1",
"body": "Can you add all your imports?"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-06T18:41:00.727",
"Id": "235181",
"Score": "4",
"Tags": [
"python",
"python-3.x",
"django"
],
"Title": "Download Fasta protein sequences as a file from the selected categories"
}
|
235181
|
<p>Sometimes we have this code blocks that is repeated in the same controller again and again, I reviewed the Repository Pattern but I didn't understand how to deal with some kind of these duplication.</p>
<p>Here is a sample of what I got here:</p>
<pre><code>$orders = ( new OrderList() )
->where( 'order_state_id', '!=', null )
->where( 'address_id', '!=', null )
->where( 'user_id', '!=', null )
->where( 'id', '>', $this->idLimitation )
->whereHas( 'orderDetail', function ( $query ) use ( $supplier_mega ) {
//In case he is not the super user supplier check for conditions
if ( Auth::guard( 'supplier' )->user()->super_user != 1 ) {
if ( Auth::guard( 'supplier' )->user()->role == 1 ) {
$query->where( 'supplier_id', Auth::guard( 'supplier' )->user()->id );
} elseif ( in_array( Auth::guard( 'supplier' )->user()->role, [ 2, 3, 4 ] ) ) {
$supplier_id = ( new Supplier() )->where( 'id', Auth::guard( 'supplier' )->user()->accountant_id )->first();
$query->where( 'supplier_id', $supplier_id->id );
}
}
</code></pre>
<p>Now starting from <code>->whereHas( 'orderDetail', function ( $query ) use ( $supplier_mega ) {</code> is repeated in this controller about 6 times but the rest of the function is not.</p>
<p>How can I deal with such duplication?</p>
<p>Another example here (upload multiple images):</p>
<pre><code>if ( $request->hasFile( 'side_image' ) ) {
foreach ( $request->side_image as $side_image ) {
$input['campaign_ads_id'] = $campaignAdsId;
$filename = Str::random( 10 ) . '.' . $side_image->getClientOriginalExtension();
Image::make( $side_image )->save( 'images/campaignAds/' . $filename );
$input['side_image'] = $filename;
( new CampaignAdsImage() )->create( $input );
}
}
</code></pre>
<p>This code is repeated in my code twice but of-course the some parts is different like the path where I store the images for instance.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-27T04:04:13.667",
"Id": "462764",
"Score": "0",
"body": "The current question title, which states your concerns about the code, is too general to be useful here. The site standard is for the title to simply state the task accomplished by the code. Please see [ask] for examples, and revise the title accordingly."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-17T17:36:06.087",
"Id": "465606",
"Score": "1",
"body": "write a scope as explained here https://laravel.com/docs/5.8/eloquent#query-scopes . This results in a function like `Order::myCustomScopeFunction()->where(..)`"
}
] |
[
{
"body": "<p>I think you can DRY this up pretty well by refactoring.</p>\n\n<p>This feels like a “ifs are evil” code smell to me. There are three “if” statements within that whereHas. They are packed in fairly tightly, and it makes that part of the code more difficult to read. Trying to refactor that as much as possible can resolve the duplication along the way, and ultimately make things much more readable and manageable. </p>\n\n<ul>\n<li><p>Try to give every “if” it’s own method, if for no other reason than the opportunity to give it a very concise name explaining what it does. This greatly improves code readability. </p></li>\n<li><p>The “if\"s being repeated is a good indicator that you can flip the control around. Try to find a way to visit each “if” once and do all the things you need to do based on the results in one place. In this case, that means breaking the construction of the query into a couple of pieces. </p></li>\n<li><p>“if\"s are decision points. They are apt to be the focus in future debugging efforts. Push these decision points to as early in the process as you can, and obsess over making that code as simple and as readable as possible. </p></li>\n<li><p><code>Auth::guard( 'supplier' )->user()</code> gets resolved a number of times. Instead, resolve it once as early as possible and catch the results in a class attribute or parameter.</p></li>\n<li><p>The “if/elseif” is overreaching; much of the content is the same. Narrow the scope to just resolving the required supplier id, encapsulate it in a method, and call that within the required context. Furthermore, this looks to be a second important variable which gets used multiple times, so resolve this as early as possible as well and get it into an attribute or parameter.</p></li>\n<li><p>Inline role ids is a bad idea. It’s possible that the database will change, or a problem will occur on data recover or seeding on deploy to a new environment, leaving different role to id mapping. Even a short exposure to this problem will mean non-admins could be logged in as admins. Further, using the full name inline instead of ids helps improve code readability as it tells more of a story. “This happens for admins” instead of “this happens for some user role, I could look in the database to know which...” Using the name adds a bit of overhead, but it can be eager loaded with the user and makes the code a lot more readable. </p></li>\n<li><p>No need to load the accountant user record as we only need the id, which we have account_id anyway. Referencing that directly will save a query here, or more as this block is repeated. </p></li>\n<li><p>Database field names can be used to help improve readability, too. $user->role_id would help identify that it’s a foreign key rather than a string. Likewise, putting ‘is_’ or ‘has_’ on the front of booleans helps make them quickly obvious, such as $user->is_superuser. Along with that, setting <code>$casts = [‘us_superuser’ => ‘boolean’,]</code> ; in the models lets you compare it against true/false instead of 1 or 0, which is a lot more readable. </p></li>\n<li><p><code>whereNotNull(‘order_state_id’)</code> is slightly more readable than <code>where(‘order_state_id’, ‘!=’, null)</code>. This can be applied to a number of the where() clauses</p></li>\n<li><p>Refactor this query builder into a “plain old php” class. Call it a repository if you think it fits, but don’t get too hung up on the name. It could be as easy as a new app/Queries/OrderList.php folder and class. That new class can be injected into the controller. Make it fluent, and abstract decisions out of it. The class should do the lifting, but be dumb. The calling entity should encapsulate the decision making and directing, and only that. </p></li>\n<li><p>Replace eloquent with whereHas with query builder, joins, and where clauses. The eloquent and whereHas approach can certainly still work and be much cleaner than it currently is, but I find query builder to be much more readable and consistent across different models and needs when the queries start to get complicated. Perhaps this one is down to a personal preference. </p></li>\n</ul>\n\n<p>With all of that in mind, here’s where I would land given my understanding of the posted code. </p>\n\n<p>app/Queries/OrderList: </p>\n\n<pre><code><?php\n\nnamespace App\\Queries;\n\nuse App\\Models\\OrderList;\nuse Illuminate\\Support\\Collection;\nuse Illuminate\\Support\\Facades\\DB;\n\nclass OrderLists\n{\n protected $query;\n\n public function buildQuery(int $idLimitation): self\n {\n $this->query = DB::table('order_lists')\n ->select([\n 'order_lists.id as id',\n //etc\n ])\n ->whereNotNull('order_state_id')\n ->whereNotNull('address_id')\n ->whereNotNull('user_id')\n ->where('id', '>', $idLimitation);\n\n return $this;\n }\n\n protected function applyNonSuperUserClauses(int $requiredSupplierId):self\n {\n $this->query->leftJoin('order_details', 'order_lists.id', '=', 'order_details.order_list_id');\n $this->query->where('order_details.supplier_id', '=', $requiredSupplierId);\n\n //Other join and where clauses as appropriate\n\n return $this;\n }\n\n protected function fetchResults():Collection{\n\n return $this->query->get();\n }\n</code></pre>\n\n<p>controller: </p>\n\n<pre><code> public function index(OrderList $orderListQuery)\n {\n $user = Auth::guard('supplier')->user();\n\n $idLimitation = $this->fetchIdLimitation();\n\n if ($this->isSuperUser($user)) {\n return view('your.view', [\n 'orderList' => $orderListQuery\n ->buildQuery($idLimitation)\n ->fetchResults(),\n ]);\n }\n\n //More secured version is the default behavior.\n return view('your.view', [\n 'orderList' => $orderListQuery\n ->buildQuery($idLimitation)\n ->applyNonSuperUserClauses($this->getRequiredSupplierIdByRole($user))\n ->fetchResults(),\n ]);\n\n }\n\n protected function isSuperUser($user): bool\n {\n return $user->is_super_user;\n }\n\n protected function getRequiredSupplierIdByRole($user): ?int\n {\n if ($this->hasAdminRole()) {\n return $user->id;\n }\n\n if ($this->hasLimitedUserRole()) {\n return $user->accountant_id;\n }\n return null;\n }\n\n //'Admin' and 'LimitedUser' based on assumptions about role ids 1,2,3,4.\n // Change these to be as concise as possible.\n protected function hasAdminRole($user): bool\n {\n return (in_array($user->role->name, $this->getAdminRoles()));\n }\n\n protected function getAdminRoles(): array\n {\n return [\n 'Admin',\n ];\n }\n\n protected function hasLimitedUserRole($user): bool\n {\n return (in_array($user->role->name, $this->getLimitedRoles()));\n }\n\n protected function getLimitedRoles(): array\n {\n return [\n 'Middle Manager',\n 'Secretary',\n 'Janitor',\n ];\n }\n</code></pre>\n\n<p>This turned into a long reply. Hopefully something here helps!</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-23T17:53:08.243",
"Id": "237791",
"ParentId": "235185",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-06T21:05:45.607",
"Id": "235185",
"Score": "1",
"Tags": [
"php",
"design-patterns",
"laravel",
"repository"
],
"Title": "Laravel 5.8: prevent duplicated code"
}
|
235185
|
<p>For school, I made a pathfinder for a weighted grid, but anything beyond a 7x7 grid takes a significant portion of time. I was wondering if I can improve my code at all, or if there is a way to reduce the time complexity.</p>
<p>I would appreciate any pointers for improving my code whether it's readability or efficiency.</p>
<pre><code>import math
import random
class Grid:
def __init__(self,width,height):
self.board = []
self.width = width;
self.height = height;
for x in range(width*height):
self.board.append([])
for x in range(width):
for y in range(height):
rand = random.randint(0,3)
self.board[x].append(rand)
def display(self):
for x in range(self.width):
for y in range(self.height):
print(str(self.board[x][y]) + " ",end="")
print()
class Point:
def __init__(self,x,y):
self.x = x
self.y = y
def add(self,x,y):
return Point(self.x+x,self.y+y)
def sub(self,x,y):
return Point(self.x-x,self.y-y)
class Node:
def __init__(self,start,end):
self.start = start
self.end = end
self.elements = [start]
def size(self):
return len(self.elements)
def get(self,index):
return self.elements[index]
def append(self,element):
self.elements.append(element)
def calc(self,grid):
cur_point = self.elements[self.size()-1]
total = distance(cur_point,end)
for x in range(self.size()):
point = self.elements[x]
total += grid.board[point.x][point.y]
return total
def clone(self):
node = Node(self.start,self.end)
node.elements = self.elements[:]
return node
def display_path(self,grid):
for x in range(self.size()):
point = self.elements[x]
grid.board[point.x][point.y] = "P"
grid.display()
class PriorityList:
def __init__(self,node):
self.elements = [node]
def size(self):
return len(self.elements)
def get(self,index):
return self.elements[index]
def append(self,element):
self.elements.append(element)
def sort(self,grid):
index = 1
while index < self.size():
node = self.elements[index]
n = self.elements[index-1]
if node.calc(grid) < n.calc(grid):
self.elements[index] = n
self.elements[index-1] = node
index = 1
index += 1
def distance(p1,p2):
return math.sqrt( math.pow(p2.x-p1.x,2) + math.pow(p2.y-p1.y,2) )
def getPoint(x,y):
x = int(input("Enter " + x + ": "))
y = int(input("Enter " + y + ": "))
return Point(x,y)
print("Customize grid...")
dimensions = getPoint("Width","Height")
print("Enter the starting point...")
start = getPoint("X","Y").sub(1,1)
print("Enter the ending point...")
end = getPoint("X","Y").sub(1,1)
grid = Grid(dimensions.x,dimensions.y)
grid.display()
print()
n = Node(start,end)
queue = PriorityList(n)
class Pathfinder(Exception): pass
try:
while True:
queue.sort(grid)
node = queue.get(0)
discovered = False
for x in range(-1,2):
for y in range(-1,2):
point = node.get(node.size()-1)
if point.x + x >= 0 and point.y + y >= 0 and point.x + x < grid.width and point.y + y < grid.height:
if x != 0 or y != 0:
discovered = True
new = node.clone()
new.append(point.add(x,y))
queue.append(new)
if point.x+x == end.x and point.y+y == end.y:
score = new.calc(grid)
new.display_path(grid)
print("Score: " + str(score))
raise Pathfinder
discovered = True
if discovered:
queue.elements.remove(queue.get(0))
except Pathfinder:
pass
</code></pre>
|
[] |
[
{
"body": "<p>I suggest to use <a href=\"https://numpy.org/\" rel=\"nofollow noreferrer\"><code>numpy</code></a> instead of Python lists. \nFor example your <code>Grid</code> class</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>class YourGrid:\n def __init__(self,width,height):\n self.board = []\n self.width = width;\n self.height = height; \n for x in range(width*height):\n self.board.append([])\n for x in range(width):\n for y in range(height):\n rand = random.randint(0,3)\n self.board[x].append(rand)\n def display(self):\n for x in range(self.width):\n for y in range(self.height):\n print(str(self.board[x][y]) + \" \",end=\"\")\n print()\n</code></pre>\n\n<p>can be reduced to just:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>class NumpyGrid:\n def __init__(self, width, height): \n self.width = width\n self.height = height\n self.board = np.random.randint(0, 4, size=(width, height))\n\n def display(self):\n print(self.board)\n</code></pre>\n\n<p>To compare it with bigger boardsize:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>>>> %timeit YourGrid(100, 100)\n17.6 ms ± 215 µs per loop\n>>> %timeit NumpyGrid(100, 100)\n73.7 µs ± 3.38 µs per loop\n</code></pre>\n\n<p>and this will of course scale up: the straight Python list implementation will become slower as you increase sizes. Avoid for loops, append methods as much as you can, these will make your code inefficient. There is a <a href=\"https://www.youtube.com/watch?v=EEUXKG97YRw\" rel=\"nofollow noreferrer\">nice talk</a> about this by Jake VanderPlas at PyCon. This is particularly true to your <code>while True</code> section: too much list manipulation there, which slows it down.</p>\n\n<p>I think your <code>Point</code> class should implement more functionality. Make a distance method for example, it's not hard:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code> def distance(self, other):\n if not isinstance(other, Point):\n raise TypeError(\"Point object is expected.\")\n return math.sqrt(math.pow(other.x-self.x,2) + math.pow(other.y-self.y,2)) \n</code></pre>\n\n<p>If you don't use any class functionality, why make it object oriented?</p>\n\n<p>Also, calculating the distance between points is much-much faster with <a href=\"https://docs.scipy.org/doc/numpy/reference/generated/numpy.linalg.norm.html\" rel=\"nofollow noreferrer\"><code>numpy.linalg.norm</code></a> or <a href=\"https://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.distance.cdist.html\" rel=\"nofollow noreferrer\"><code>scipy.spatial.distance.cdist</code></a>, but that's probably an overkill.</p>\n\n<p>This</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def size(self):\n return len(self.elements)\n</code></pre>\n\n<p>should be</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def __len__(self):\n return len(self.elements)\n</code></pre>\n\n<p>and it can be accessed via <code>len(object)</code>.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def get(self, index):\n</code></pre>\n\n<p>should be</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def __getitem__(self, indeces):\n</code></pre>\n\n<p>In the <code>Point</code> class you return new instances of itself. I don't think you should do that. Maybe you just want to modify the x and y inplace, so it can be</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def add(self, x, y):\n self.x += x\n self.y += y\n</code></pre>\n\n<p>Note that there is also a built-in method called <code>__add__</code>.</p>\n\n<p>Your whole main script should be in a <code>__main__</code> guard:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>if __name__=='__main__':\n print(\"Customize grid...\")\n dimensions = getPoint(\"Width\",\"Height\")\n...\n</code></pre>\n\n<p>You don't validate any user input.</p>\n\n<p>You break out the main <code>while</code> loop with a custom exception. I think it can be just <code>break</code>, there is no point of the <code>try-except</code>. Or move the condition to while loop. A little sketch what I mean:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>condition = False\nwhile not condition:\n for x in range(1000):\n if x == 100:\n condition=True\n</code></pre>\n\n<p>According the style, you should follow <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP8</a>.</p>\n\n<p>I won't try to rewrite this, but probably there is a lot more to improve besides I posted above. Also you should add comments, it's hard to figure out what are you doing with each step.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-06T19:21:26.197",
"Id": "460182",
"Score": "0",
"body": "Thank you! This is very informative, but I do have a question. You said I could break, but I don't think you can break from the outer loop without a custom exception. Correct me if I'm wrong."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-06T19:32:05.557",
"Id": "460183",
"Score": "0",
"body": "You should be able to break out. Also instead of `while True` might be worth to change it to something like`while not condition`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-09T00:47:53.800",
"Id": "460507",
"Score": "0",
"body": "@ZL11378 You can break out of any loop, no exceptions required, if that's what you were asking."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-06T18:00:24.750",
"Id": "235187",
"ParentId": "235186",
"Score": "1"
}
},
{
"body": "<p>The thing that sticks out the most is that your <code>PriorityList</code>, a priority queue, is <strong>a list instead of a heap</strong>.</p>\n\n<p>You <code>sort()</code> the list every iteration, which (if implemented correctly) would be <code>O(n log n)</code>, but in a proper priority queue adding/removing elements should be <code>O(log n)</code></p>\n\n<p>Your actual comparison-sort implementation is <code>O(n)</code>, which is impossible, meaning it doesn't even work correctly as-is.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-06T22:15:54.447",
"Id": "235191",
"ParentId": "235186",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-06T16:28:09.747",
"Id": "235186",
"Score": "3",
"Tags": [
"python",
"algorithm"
],
"Title": "Reducing time complexity of weighted grid pathfinder"
}
|
235186
|
<pre class="lang-py prettyprint-override"><code>def combine_in_place(first, second):
combined = []
maxLength = max(len(first), len(second))
for i in range(maxLength):
if len(first) < i+1:
combined.append(second[i])
elif len(second) < i+1:
combined.append(first[i])
else:
if not first[i]:
combined.append(second[i])
elif not second[i]:
combined.append(first[i])
else:
combined.append(first[i] + second[i])
return combined
print combine_in_place([['f'], ['j', 't'], [], ['s'], [], []], [['h', 'd'], [], [], []])
# prints: [['f', 'h', 'd'], ['d', 't'], [], ['s'], [], []]
</code></pre>
<p>So I know to program (been programming in Java for some time now). I am trying to learn Python but I am not sure what's the best way to do some stuff. My question is:<br>
How to write the function in a more <em>Pythonic</em> way?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-06T22:41:02.257",
"Id": "460196",
"Score": "2",
"body": "The title should describe what the code does. Please [edit] it. Maybe you missed the placeholder on the title element: \"_State the task that your code accomplishes. Make your title distinctive._\". Also from [How to Ask](https://codereview.stackexchange.com/questions/how-to-ask): \"_State what your code does in your title, not your main concerns about it._\"."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-07T07:35:30.257",
"Id": "460226",
"Score": "0",
"body": "(Sorry for jumping in and coercing the title during suggested edit review.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-07T07:37:45.830",
"Id": "460227",
"Score": "0",
"body": "`I know to program` & `combine_in_place([['f'], ['j', 't'], …], [['h', 'd'], …])`& `# prints: [['f', 'h', 'd'], ['d', 't'], …]` hm, hm, hm, hm."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-07T12:53:03.577",
"Id": "460262",
"Score": "0",
"body": "What does `in_place` mean in the name? Surely our definition differ as you are returning a _new_ list."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-07T13:06:28.633",
"Id": "460266",
"Score": "0",
"body": "I'm fairly shocked that no-one's dropped the 1 line `itertools` way. It's just `return map(chain.from_iterable, zip_longest(*args, fillvalue=()))`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-07T14:07:22.373",
"Id": "460272",
"Score": "0",
"body": "@Peilonrayz Depending on what you expect as a result, [that's close enough](https://codereview.stackexchange.com/questions/235188/combine-lists-from-two-lists-of-list-into-a-single-list-of-lists#comment460265_235194)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-10T02:19:04.080",
"Id": "460707",
"Score": "0",
"body": "Can you describe the algorithm for combining them? It seems slightly odd."
}
] |
[
{
"body": "<p>I would write something like that:</p>\n\n<pre><code>def combine(first, second):\n ret_list = []\n for i, j in zip(first, second):\n add = []\n if i is not None:\n add.extend(i)\n if j is not None:\n add.extend(j)\n ret_list.append(add)\n return ret_list\n</code></pre>\n\n<p>I don't know if it is the most python-ish way but it is ok I think...</p>\n\n<p>I mean you can also write something like this:</p>\n\n<pre><code>def combine(first, second):\n return [(i.extend(j) if not (i is None or j is None) else i if j is None else j) for i, j in zip(first, second)]\n</code></pre>\n\n<p>But you cannot read and debug that. So I would strongly recommend against it.</p>\n\n<p>Btw: Did not test the last one so I hope I did not forget a closing bracket ;)</p>\n\n<p><strong>Edit:</strong></p>\n\n<p>In order to keep all elements you have to add something to the end. The zip() function stops iterating after the shortest element reached its end.\nThis is why the following method is needed instead of zip:</p>\n\n<pre><code>def combine(first, second):\n ret_list = []\n for i, j in itertools.zip_longest(first, second):\n add = []\n if i is not None:\n add.extend(i)\n if j is not None:\n add.extend(j)\n ret_list.append(add)\n return ret_list\n</code></pre>\n\n<p>Note: Itertools simply must be imported first. (For Python2 it is <code>itertools.izip_longest()</code>...)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-06T22:05:33.617",
"Id": "460191",
"Score": "0",
"body": "This works but I want to keep empty lists at the end as well (which I did not make clear in my question). I edited my question to include that request."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-06T22:19:26.633",
"Id": "460193",
"Score": "0",
"body": "When I tested the combine function, it removed the empty ones at the end."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-06T22:20:43.210",
"Id": "460194",
"Score": "0",
"body": "@ShehabEllithy yeah forgot something. Wait a sec."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-07T06:43:53.227",
"Id": "460222",
"Score": "0",
"body": "Perfect, that is what I needed."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-06T21:53:15.663",
"Id": "235190",
"ParentId": "235188",
"Score": "4"
}
},
{
"body": "<p>Here's how I might do it:</p>\n\n<pre><code>from itertools import chain\nfrom typing import List\n\ndef combine_in_place(*lists: List[List[str]]) -> List[List[str]]:\n return [\n list(chain(*[a[i] if i < len(a) else [] for a in lists])) \n for i in range(max(len(a) for a in lists))\n ]\n</code></pre>\n\n<p>Some general principles I've attempted to follow:</p>\n\n<ol>\n<li>When you're operating on multiple things, try to express them as a single iterable rather than individual named variables</li>\n<li>If you can replace a bunch of individual <code>if x < y</code> with a single call to <code>min()</code> or <code>max()</code>, do that</li>\n<li>It's generally preferable to build a list through comprehension rather than using <code>extend</code>/<code>append</code>.</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-07T13:01:26.280",
"Id": "460265",
"Score": "2",
"body": "Since you reached for `itertools`, I’d use [`zip_longest`](https://docs.python.org/3/library/itertools.html#itertools.zip_longest) with a `fillvalue` of `[]` or `()`. Then you can have the simpler `[list(chain.from_iterable(elements)) for elements in zip_longest(*lists, fillvalue=[])]`"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-06T22:29:23.980",
"Id": "235194",
"ParentId": "235188",
"Score": "3"
}
},
{
"body": "<p>The Pythonic way may include:<br>\n • <em>know and follow your <a href=\"https://www.python.org/dev/peps/#introduction\" rel=\"nofollow noreferrer\">Python Enhancement Proposals</a></em> and<br>\n • <em>know and exploit your <a href=\"https://docs.python.org/library/#the-python-standard-library\" rel=\"nofollow noreferrer\">Python Standard Library</a></em>;<br>\n • <em>follow sound development practices</em> is debatably language oblivious</p>\n\n<p>The code presented does not violate <em>PEP 8</em> <a href=\"https://www.python.org/dev/peps/pep-0008/#a-foolish-consistency-is-the-hobgoblin-of-little-minds\" rel=\"nofollow noreferrer\">Style Guide for Python Code</a><br>\nIt does not follow <em>PEP 257</em> <a href=\"https://www.python.org/dev/peps/pep-0257/#what-is-a-docstring\" rel=\"nofollow noreferrer\">Docstring Conventions</a><br>\nor <em>PEP 484</em> <a href=\"https://www.python.org/dev/peps/pep-0484/#abstract\" rel=\"nofollow noreferrer\">Type Hints</a></p>\n\n<p>Documenting code, in Python using docstrings, is one of my pet programming peeves:<br>\nNote how implementations in answers follow the one in the question in <em>not</em> combining <em>in place</em>, neither in the inner lists, nor in the outer one.<br>\nNote also how <code>_in_place</code> got omitted in <a href=\"https://codereview.stackexchange.com/a/235190/93149\">Cedced_Bro's accepted answer</a>.<br>\nNo (previous) answer has suggested using/returning a <a href=\"https://docs.python.org/tutorial/classes.html#generators\" rel=\"nofollow noreferrer\">generator</a> or allowing <a href=\"https://docs.python.org/tutorial/controlflow.html#arbitrary-argument-lists\" rel=\"nofollow noreferrer\">an arbitrary number of lists</a>, given the advantages, this, too, may be due to lacking documentation of <code>combine_in_place()</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-07T08:21:35.323",
"Id": "235208",
"ParentId": "235188",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "235190",
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-06T21:33:23.847",
"Id": "235188",
"Score": "1",
"Tags": [
"python"
],
"Title": "Combine lists from two lists of list into a single list of lists"
}
|
235188
|
<p>I'm coding a simple hangman for the MIT Online Course Ps.</p>
<p>Here's what I wrote so far:</p>
<pre><code>
from string import ascii_lowercase
import random
def hint(word_so_far):
pass
def is_word_guessed(secret_word, c_letters):
for char in secret_word:
if char not in c_letters:
return False
return True
def rem_letters(l_guessed):
rem_letters = ''
for char in ascii_lowercase:
if char not in l_guessed:
rem_letters += char +' '
return rem_letters.upper()
def word_so_far(secret_word, c_letters):
word_so_far = ''
for char in secret_word:
if char not in c_letters:
word_so_far += '_ '
else:
word_so_far += char + ' '
return word_so_far
def print_war_msg(wars_rem, g_rem, is_not_valid, is_not_one_letter):
if g_rem >= 1:
if is_not_valid:
print('Please enter a valid character')
elif is_not_one_letter:
print('Please enter one letter at a time')
else:
print('You already guessed that letter')
print()
if wars_rem == 1:
print('You have one more warning.')
elif wars_rem == 0:
print('You have no warnings remaining so you lose one guess!')
print('... You now have 3 warning.')
else:
print('You have', wars_rem, 'warnings left.')
print()
def game_start_msg(secret_word):
print()
print('Welcome to the game Hangman!')
print('I\'m thinking of a game that is', len(secret_word), 'letters long.')
def guess_start_msg(g_rem, secret_word, l_guessed):
print('-' * 40)
print()
if g_rem == 1:
print('You have one more guess')
else:
print('You have', g_rem, 'guesses left.')
print()
print('Word so far:', word_so_far(secret_word, l_guessed))
print()
print('Available Letters :', rem_letters(l_guessed))
print()
def end_game_msg(g_rem, secret_word):
def total_score(g_rem, secret_word):
uniq = ''
for char in secret_word:
if char not in uniq:
uniq += char
return len(uniq) * g_rem
if g_rem <= 0:
print('Unfortunately you ran out of guesses,\nThe Secret word was: >>>', secret_word, '<<<')
else:
print('Congrats, You win! Your total score is', total_score(g_rem, secret_word))
def hangman(secret_word):
l_guessed = []
c_letters = []
wars_rem = 3
g_rem = 6
game_start_msg(secret_word)
print(is_word_guessed(c_letters, secret_word))
while not is_word_guessed(secret_word, c_letters) and g_rem > 0:
guess_start_msg(g_rem, secret_word, l_guessed)
guess = input('Please guess a letter: ').lower()
print()
if guess == 'q':
break
elif guess == '*':
pass
# Conditions for the guessed letter
is_not_valid = not guess.isalpha()
is_not_one_letter = len(guess) != 1 and guess != 'cmd'
is_guessed = guess in l_guessed
while guess == 'cmd':
print('Enter Command...')
cmd = input ()
if cmd == 'raise guess':
by = int(input('Raise by?'))
g_rem += by
print(f'Gusses Remaining increased by {by} , current guesses are {g_rem}.')
elif cmd == 'reveal':
win_game = input('Do You Want To Win? (Y/N)').upper()
if win_game == 'Y':
c_letters = [lett for lett in secret_word]
else:
print(f'Secret word is {secret_word}')
elif cmd == 'exit':
break
else:
print('''List Of Possible Commands:\
\nraise guess
\nreveal
\nexit
''')
continue
if guess == 'cmd':
continue
if is_not_valid or is_not_one_letter or is_guessed:
wars_rem -= 1
print_war_msg(wars_rem, g_rem, is_not_valid, is_not_one_letter)
else:
l_guessed.append(guess)
if guess in secret_word:
c_letters.append(guess)
print('Good Guess!')
print()
else:
if guess in 'aeiou':
g_rem -= 2
print('You lose two guesses because you guessed a wrong vowel')
else:
g_rem -= 1
if guess not in 'aeiou' :
print('Oops, that letter is not in my word')
print()
if wars_rem == 0:
g_rem -= 1
wars_rem = 3
end_game_msg(g_rem, secret_word)
list_of_words = ['hello', 'say', 'zebra', 'jake', 'man', 'human', 'god', 'fuel', 'car', 'sea', 'cat', 'dog', 'building']
secret_word = random.choice(list_of_words)
hangman(secret_word)
</code></pre>
<p>Any recommendations on ways I can improve this?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-07T09:21:16.527",
"Id": "460239",
"Score": "0",
"body": "I didn't look in detail yet but... 1) You can use callback functions to return the results to the user, in this case, \"print()\" works fine because you are using CLI (command line interface). If you want to send the results to a GUI, etc. 2) You can also create at least two classes in this program, one for your callbacks (prints, flags, whatever) and another for the game. 3) Use fstrings (more readable) ex: `print(f'You have {g_rem} guesses left.')`. If you need help just ping."
}
] |
[
{
"body": "<h3>Avoid mixing import styles</h3>\n\n<pre><code>from string import ascii_lowercase\nimport random\n</code></pre>\n\n<p>Either way of importing is fine. But try and stick with one style\nrather than mixing different ones. So:</p>\n\n<pre><code>from string import ascii_lowercase\nfrom random import choice\n</code></pre>\n\n<h3>Names</h3>\n\n<p>Names should be familiar and self-explanatory to the reader. You have\nabbreviated \"warning\" as \"war\" which I've never seen before and which\nI find confusing.</p>\n\n<p>Same thing for <code>l_guessed</code>. What is l? And \"rem\" seem to stand for\n\"remaining.\" I changed all those to \"left\" because \"left\" is\nsynonymous with \"remaining\" and easy to type. And \"char\" is a\nwell-established abbrevation for \"character\" and \"char\" is easier to\ntype (and read!) than \"letter\" so I changed that too.</p>\n\n<p>I've renamed the following:</p>\n\n<ul>\n<li><code>c_letters => correct_chars</code></li>\n<li><code>g_rem => guesses_left</code></li>\n<li><code>l_guessed => guessed_chars</code></li>\n<li><code>lett => char</code></li>\n<li><code>list_of_words => words</code></li>\n<li><code>print_war_msg => print_warning_msg</code></li>\n<li><code>rem_letters = chars_left</code></li>\n<li><code>wars_rem => warnings_left</code></li>\n</ul>\n\n<h3>Sets</h3>\n\n<p>A useful feature one step up from the beginner level is sets. Sets\nshould almost always be used instead of lists when you don't care\nabout the order of the items contained. For example, you don't care\nabout the order of the guesses, or the correct characters so both\n<code>guessed_chars</code> and <code>correct_chars</code> should be sets.</p>\n\n<p>Using sets, you can calculate the total score for a winning player\nlike this:</p>\n\n<pre><code>score = len(set(secret_word)) * guesses_left\n</code></pre>\n\n<h3>Consistent string formatting</h3>\n\n<p>In some parts of the code, you use f-strings for formatting but not in\nother parts. It's better to be consistent and use the same formatting\nstyle wherever possible.</p>\n\n<h3>Avoid using nested functions</h3>\n\n<p>It is legal and sometimes useful to nest function in Python, like this:</p>\n\n<pre><code>def end_game_msg(g_rem, secret_word):\n def total_score(g_rem, secret_word):\n ...\n</code></pre>\n\n<p>But more often than not, it makes the code harder to read for no added\nbenefit.</p>\n\n<h3>Don't define variables before they are needed</h3>\n\n<p>In your main loop, you seem to have some kind of superuser mode:</p>\n\n<pre><code># Conditions for the guessed letter\nis_not_valid = not guess.isalpha()\nis_not_one_letter = len(guess) != 1 and guess != 'cmd'\nis_guessed = guess in guessed_chars\nwhile guess == 'cmd':\n print('Enter Command...')\n ...\nif guess == 'cmd':\n continue\nif is_not_valid or is_not_one_letter or is_guessed:\n</code></pre>\n\n<p>Observe that <code>is_not_valid</code>, <code>is_not_one_letter</code> and <code>is_guessed</code> are\ndefined many lines before the if-statement in which they are used. You\nshould move them downwards so that they are adjacent to the\nif-statement.</p>\n\n<h3>Final code</h3>\n\n<pre><code>from string import ascii_lowercase\nfrom random import choice\n\ndef is_word_guessed(secret_word, c_letters):\n for char in secret_word:\n if char not in c_letters:\n return False\n return True\n\ndef chars_left(guessed_chars):\n chars_left = ''\n for char in ascii_lowercase:\n if char not in guessed_chars:\n chars_left += char + ' '\n return chars_left.upper()\n\ndef word_so_far(secret_word, correct_chars):\n word_so_far = ''\n for char in secret_word:\n if char not in correct_chars:\n word_so_far += '_ '\n else:\n word_so_far += char + ' '\n return word_so_far\n\ndef print_warning_msg(warnings_left, is_not_valid, is_not_one_letter):\n if is_not_valid:\n print('Please enter a valid character')\n elif is_not_one_letter:\n print('Please enter one letter at a time')\n else:\n print('You already guessed that letter')\n print()\n if warnings_left == 1:\n print('You have one more warning.')\n elif warnings_left == 0:\n print('You have no warnings remaining so you lose one guess!')\n print('... You now have 3 warning.')\n else:\n print(f'You have {warnings_left} warnings left.')\n print()\n\ndef game_start_msg(secret_word):\n print()\n print('Welcome to the game Hangman!')\n print(f'I\\'m thinking of a word that is {len(secret_word)} letters long.')\n\ndef guess_start_msg(guesses_left, secret_word, guessed_chars):\n print('-' * 40)\n print()\n if guesses_left == 1:\n print('You have one more guess')\n else:\n print(f'You have {guesses_left} guesses left.')\n print()\n print(f'Word so far: {word_so_far(secret_word, guessed_chars)}')\n print()\n print(f'Available Letters: {chars_left(guessed_chars)}')\n print()\n\ndef end_game_msg(guesses_left, secret_word):\n if guesses_left <= 0:\n print('Unfortunately you ran out of guesses,')\n print(f'The Secret word was: >>>{secret_word}<<<')\n else:\n score = len(set(secret_word)) * guesses_left\n print(f'Congrats, You win! Your score is {score}.')\n\ndef hangman(secret_word):\n guessed_chars = set()\n correct_chars = set()\n warnings_left = 3\n guesses_left = 10\n game_start_msg(secret_word)\n while not is_word_guessed(secret_word, correct_chars) and guesses_left > 0:\n guess_start_msg(guesses_left, secret_word, guessed_chars)\n guess = input('Please guess a letter: ').lower()\n print()\n if guess == 'q':\n break\n while guess == 'cmd':\n print('Enter Command...')\n cmd = input ()\n if cmd == 'raise guess':\n by = int(input('Raise by?'))\n guesses_left += by\n print(f'Gusses Remaining increased by {by},'\n f'current guesses are {guesses_left}.')\n elif cmd == 'reveal':\n win_game = input('Do You Want To Win? (Y/N)').upper()\n if win_game == 'Y':\n correct_chars = set(secret_word)\n else:\n print(f'Secret word is {secret_word}')\n elif cmd == 'exit':\n break\n else:\n print('''List Of Possible Commands:\\\n \\nraise guess\n \\nreveal\n \\nexit\n ''')\n continue\n if guess == 'cmd':\n continue\n is_not_valid = not guess.isalpha()\n is_not_one_letter = len(guess) != 1\n is_guessed = guess in guessed_chars\n if is_not_valid or is_not_one_letter or is_guessed:\n warnings_left -= 1\n print_warning_msg(warnings_left, is_not_valid, is_not_one_letter)\n else:\n guessed_chars.add(guess)\n if guess in secret_word:\n correct_chars.add(guess)\n print('Good Guess!')\n print()\n else:\n if guess in 'aeiou':\n guesses_left -= 2\n print('You lose two guesses because you guessed a wrong vowel')\n else:\n guesses_left -= 1\n print('Oops, that letter is not in my word')\n print()\n if warnings_left == 0:\n guesses_left -= 1\n warnings_left = 3\n\n end_game_msg(guesses_left, secret_word)\n\nwords = [\n 'hello', 'say', 'zebra', 'jake', 'man', 'human',\n 'god', 'fuel', 'car', 'sea', 'cat', 'dog', 'building'\n]\nsecret_word = choice(words)\nhangman(secret_word)\n</code></pre>\n\n<h3>More suggestions</h3>\n\n<p>A very useful string function in Python is\nthe\n<a href=\"https://appdividend.com/2019/01/31/python-string-join-example-python-join-method-tutorial/\" rel=\"nofollow noreferrer\">join</a> function. By\nlearning about it, you'll improve your Python programming a lot.</p>\n\n<pre><code> +----\\\n | o\n | /|\\\n | \\\\\n / \\\n</code></pre>\n\n<p>What's a hangman game without a hanging man? :)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-07T20:19:43.953",
"Id": "460320",
"Score": "0",
"body": "10/10 for the answer man."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-07T20:11:12.377",
"Id": "235248",
"ParentId": "235189",
"Score": "1"
}
},
{
"body": "<p>You have 147 lines of code in your program. It is very complex running backwards and forward through functions when it can be handled with straight forward logic. Below is an unfinished simple example of just 18 lines of code that handles pretty much all of the foundation without the need to define functions. It includes list comprehension and a just few conditional catch statements.</p>\n\n<pre><code>import random\n\nwords = ['cheese', 'biscuits', 'hammer', 'evidence'] \nword_choice = [i.lower() for i in random.choice(words)]\nlives = 3\ncor_guess = []\nwhile True:\n print('Letters found: {}\\nWord length: {}'.format(cor_guess, len(word_choice)))\n if lives == 0:\n print('Your dead homie!\\nThe word was: ', word_choice)\n break\n guess = str(input('Guess a letter: '))\n if guess in word_choice:\n print(guess, 'is in the word!\\n')\n cor_guess.append(guess)\n else:\n print('Your dying slowly!\\n')\n lives -= 1\n ...\n ...\n</code></pre>\n\n<p>With <code>print</code> you do not need to add extra print line to get another blank line, you can use triple quotation marks and place the information where ever you like. For instance:</p>\n\n<pre><code>print('''\nlives = {}\n#hangman picture#\n\n\n\nletters found: {}\n'''.format(lives, letters_found)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-07T20:49:59.890",
"Id": "235252",
"ParentId": "235189",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "235248",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-06T21:34:04.513",
"Id": "235189",
"Score": "4",
"Tags": [
"python",
"python-3.x"
],
"Title": "A simple hangman game"
}
|
235189
|
<p>I am currently working on implementing some data structures as a way to learn C++. I'm coming mostly from a Java background so I was hoping to get some feedback regarding this implementation of a singly linked list in C++ using templates. This singly linked list will only support insertions at the head and tail positions and deletions from the head position. The plan is to use this as a base to build further data structures. I would like to create a rather complete library of data structures, so I was hoping to make them as extensible and reusable as possible. </p>
<p>Below follows the class definition. </p>
<pre class="lang-cpp prettyprint-override"><code>#ifndef LINKEDLISTS_SINGLYLINKEDLIST_H_
#define LINKEDLISTS_SINGLYLINKEDLIST_H_
#include <cstddef>
#include <iostream>
template <typename E>
class SinglyLinkedList {
private:
/** BEGIN NESTED NODE CLASS **/
class Node {
private:
E data; //Should this be a reference?
Node* next;
public:
Node(Node* n, const E& d) : data(d), next(n) {};
Node* getNext() const { return next; }
E& getData() { return data; }
void setNext(Node* n) { next = n; }
}; /** END NESTED NODE CLASS **/
/** Begin fields of SinglyLinkedList class **/
Node* head;
Node* tail;
int listSize;
/** End fields of SinglyLinkedList class **/
public:
SinglyLinkedList();
~SinglyLinkedList();
//Accessor methods
bool isEmpty() const;
int size() const;
const E& first() const;
const E& last() const;
//Update methods
void addFirst(const E&);
void addLast(const E&);
E* removeFirst();
void print() const;
}; /** END SINGLYLINKEDLIST CLASS HEADER **/
#include "SinglyLinkedList.tpp" //Include implementations of template code.
#endif /* LINKEDLISTS_SINGLYLINKEDLIST_H_ */
</code></pre>
<p>The implementations of the functions follow below: </p>
<pre class="lang-cpp prettyprint-override"><code>/*
* SinglyLinkedList.tpp
*
* Created on: Jan 5, 2020
* Author: dii
*/
/** Constructor **/
template<typename E>SinglyLinkedList<E>::SinglyLinkedList() : head(nullptr), tail(nullptr), listSize(0) {}
/** Destructor **/
template<typename E>SinglyLinkedList<E>::~SinglyLinkedList() {
while(!isEmpty()) {
delete removeFirst();
}
}
/** Begin functions **/
template<typename E> bool SinglyLinkedList<E>::isEmpty() const { return listSize == 0; }
template<typename E> int SinglyLinkedList<E>::size() const { return listSize; }
template<typename E> const E& SinglyLinkedList<E>::first() const { return head->getData(); }
template<typename E> const E& SinglyLinkedList<E>::last() const { return tail->getData(); }
template<typename E> void SinglyLinkedList<E>::addFirst(const E& d) {
Node* temp = new Node(head->getNext(), d); //Create a new node.
head = temp; // Set the head pointer to point to this object.
listSize++; // Increase size of list by 1.
}
template<typename E> void SinglyLinkedList<E>::addLast(const E& d) {
Node* temp = new Node(nullptr, d);
if(isEmpty()) {
head = temp;
tail = temp;
} else {
tail->setNext(temp);
tail = temp;
}
listSize++;
}
template<typename E> E* SinglyLinkedList<E>::removeFirst() {
if(isEmpty()) {
return nullptr;
}
E* temp = &(head->getData());
head = head->getNext();
listSize--;
return temp;
}
template<typename E> void SinglyLinkedList<E>::print() const {
Node* walk = head;
while(walk != nullptr) {
std::cout << walk->getData() << std::endl;
walk = walk->getNext();
}
}
</code></pre>
<p>I have a feeling that the destructor is not implemented as well as it could be. I am also still not entirely sure about when to use references, e.g., should the <code>data</code> field of the <code>Node</code> class be of type <code>E&</code> or is just <code>E</code> ok? </p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-07T02:26:09.977",
"Id": "460213",
"Score": "0",
"body": "A doubly linked list actually makes the whole processes easier."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-07T03:38:46.607",
"Id": "460218",
"Score": "0",
"body": "Correct, a doubly linked list would be a lot easier, but my idea was to implement a singly linked list to get a general idea of writing this type of data structure in C++."
}
] |
[
{
"body": "<p><code>forward_list</code> exists, so I assume this is a learning exercise? </p>\n\n<hr>\n\n<p>style nit:\nYou're using nonstandard naming conventions compared to the STL; though many people don't like those anyway. <code>addFirst</code> may be surprising to readers who are more used to something like \"push front\" or \"enqueue\". </p>\n\n<hr>\n\n<p>You're not deleting head here. std::unique_ptr could help here, but might not make sense if you're doing this as an exercise. Still, you should try to figure out a way to prevent memory leaks in a robust way.</p>\n\n<pre><code>template<typename E> E* SinglyLinkedList<E>::removeFirst() {\n\n if(isEmpty()) {\n return nullptr;\n }\n\n E* temp = &(head->getData());\n head = head->getNext();\n listSize--;\n\n return temp;\n\n}\n</code></pre>\n\n<hr>\n\n<p>This interface only supports storing const values that are copy-constructable. This is a severe limitation -- you wouldn't be able to make a list of <code>std::unique_ptr</code>s for example, because those cannot be copied. Supporting non-copyable types would be a good exercise (see forward_list for reference).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-06T23:18:26.333",
"Id": "460203",
"Score": "0",
"body": "Thank you for the feedback. Yes, this is an exercise ultimately, but I would like it to be as legit, robust, and complete as possible. The naming conventions I am still learning, so thank you for pointing that out. I notice now that there is indeed a memory leak in the ```removeFirst``` function, so I will work on fixing that. I don't particularly understand the part about supporting non-copyable types. Is this due to the fact that the field data in the nested node class is of type ```E``` rather than something like ```E&```?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-06T23:34:11.007",
"Id": "460204",
"Score": "0",
"body": "Just want to note that `std::forward_list` is designed around splicing, so it omits features (like `size()`) that you would find in a hand-rolled singly linked list because of time/space overhead."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-06T23:55:26.537",
"Id": "460205",
"Score": "0",
"body": "Consider the signature of https://en.cppreference.com/w/cpp/container/forward_list/emplace_front:\nThis supports types that have no default constructor and no copy-constructor. \n\nLearning r-value references was very difficult for me, but I now find them stupendously valuable. There's really two things to learn here: why std::forward_list has the interface it does, and separately, how it's implemented."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-06T23:56:57.570",
"Id": "460206",
"Score": "0",
"body": "Additionally, try making sensible copy and move semantics for the data structure itself. E.g. what happens if you make a SinglyLinkedList<SinglyLinkedList<int>> ? It doesn't *need* to be copyable, but if you don't want it to be, it should be explicitly prevented so that someone using it doesn't make a mistake."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-06T23:03:46.333",
"Id": "235197",
"ParentId": "235192",
"Score": "1"
}
},
{
"body": "<blockquote>\n <p>I am also still not entirely sure about when to use references, e.g., should the <code>data</code> field of the <code>Node</code> class be of type <code>E&</code> or is just <code>E</code> ok?</p>\n</blockquote>\n\n<p>It should not be stored as a reference. Using a reference would create ownership and lifetime issues, and can make the class harder to use (since you can't copy or move it).</p>\n\n<p><code>addFirst</code> will crash if the list is empty (when <code>head</code> is <code>nullptr</code>).</p>\n\n<p><code>removeFirst</code> should not return a pointer. Currently you leak the memory you allocated for the <code>Node</code> that holds the data, and return a pointer to that. When you fix the memory leak, you'll return a dangling pointer (or, worse, a pointer that the caller will have to delete). It would be better to return a copy of the item in the list. If the list is empty, either throw an exception or return a default constructed <code>T</code> object. You will then need to make some changes to your destructor.</p>\n\n<p>Your <code>while</code> loop in <code>print</code> can be more concisely stated using a <code>for</code> loop.</p>\n\n<pre><code>template<typename E> void SinglyLinkedList<E>::print() const {\n for (Node* walk = head; walk != nullptr; walk = walk->getNext()) {\n std::cout << walk->getData() << '\\n';\n }\n}\n</code></pre>\n\n<p>I've also changed the <code>std::endl</code> to a <code>'\\n'</code> character. Since <code>endl</code> flushes the output buffer, there can be performance issues when using it.</p>\n\n<p>You can also look into using rvalue references (<code>T &&</code>) for things, which will let you move objects rather than having to copy them.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-07T02:04:51.060",
"Id": "235202",
"ParentId": "235192",
"Score": "0"
}
},
{
"body": "<h1>Design</h1>\n\n<p>It's relatively simple to create a double linked list!</p>\n\n<hr>\n\n<p>Some things you should think about some more:</p>\n\n<ol>\n<li>Please put your code into a namespace. Do you think that <code>SinglyLinkedList</code> is a very unique name in the global scope?</li>\n<li>You need to look into const correctness.</li>\n<li>You need to look into move semantics.</li>\n</ol>\n\n<hr>\n\n<p>Major Bug.</p>\n\n<p>You have not implemented the rule of three (or five). When a class contains an owned pointer the compiler generated copy constructor, copy assignment operator and destructor are not going to work correctly.</p>\n\n<p>Your <code>SinglyLinkedList</code> contains the owned pointer: <code>head</code>. An owned pointer is one that you have taken responsibility for the lifespan of (and are thus going to call delete on it when it the object is destroyed.</p>\n\n<pre><code>{\n SinglyLinkedList<int> list1;\n list1.addFirst(1);\n\n SinglyLinkedList<int> list2(list1);\n}\n// This code is broken as you have a double delete.\n</code></pre>\n\n<hr>\n\n<p>Upgrade you need to do.</p>\n\n<p>The standard library defines things called concepts. A concept is a set of properties that a class has. One of the big concepts of the standard is the concept of a \"Container\" (of which a singly linked list is). Ao you should probably make your list \"Container\" compliant.</p>\n\n<h1>Code Review</h1>\n\n<p>I hate useless comments.</p>\n\n<pre><code> /** BEGIN NESTED NODE CLASS **/\n class Node {\n</code></pre>\n\n<p>That counts as a useless comment.</p>\n\n<hr>\n\n<p>OK good start.</p>\n\n<pre><code> Node(Node* n, const E& d) : data(d), next(n) {} ;\n // Not Needed ^^^\n</code></pre>\n\n<p>But it does mean that you are required to copy the object into the list. Modern C++ has the concept of move semantics. So you should allow for moving the object into the list.</p>\n\n<pre><code> Node(Node* n, E&& d) : data(std::move(d)), next(n) {}\n</code></pre>\n\n<p>Also you should allow the object to be constructed in place:</p>\n\n<pre><code> template<typename... Args>\n Node(Node* n, Args&&... args)\n : data(std::forward<Args>(args)...)\n , next(n)\n {}\n</code></pre>\n\n<hr>\n\n<p>Here you get a reference to the object.<br>\nThat's fine.</p>\n\n<pre><code> E& getData() { return data; }\n</code></pre>\n\n<p>But what happens if your list has been passed by const reference to a function. Now you can no longer accesses the data as you can't get a const reference to the data.</p>\n\n<pre><code> E const& getData() const {return data;}\n</code></pre>\n\n<p>Its a bit strange that you only return reference from the node. But you return only const references from the list?</p>\n\n<pre><code> const E& first() const;\n const E& last() const;\n</code></pre>\n\n<hr>\n\n<p>I actually hate your get/set mentatility here. I see no need for it inside the node object itself.</p>\n\n<pre><code> void setNext(Node* n) { next = n; }\n</code></pre>\n\n<hr>\n\n<p>That's fine.</p>\n\n<pre><code> void print() const;\n</code></pre>\n\n<p>But two things to note.</p>\n\n<ol>\n<li>There is more streams than the <code>std::cout</code> so allow this to be pramertized.</li>\n<li><p>The normal way of streaming is via the output operator: <code>operator<<()</code></p>\n\n<pre><code>void print(std::ostream& stream = std::cout);\nfriend std::ostream& operator<<(std::ostream& str, SinglyLinkedList const& data)\n{\n data.print(str);\n return str;\n}\n</code></pre></li>\n</ol>\n\n<hr>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-07T03:07:37.163",
"Id": "235204",
"ParentId": "235192",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "235204",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-06T22:16:03.287",
"Id": "235192",
"Score": "3",
"Tags": [
"c++",
"linked-list",
"reinventing-the-wheel"
],
"Title": "Generic Singly Linked List in C++"
}
|
235192
|
<p>Attached below is my code for generating the confidence maps for the joint locations, it is in the same vein as the maps generated for the paper Convolutional Pose Machines and OpenPose. I am wondering if anyone has input on how to speed up the process, as when I try to train my own variant of OpenPose or Convolutional Pose machines, my generator times out for batch sizes larger than one.... Just as a note so everyone knows the structure of the keypoint data, as I am training on MS COCO: for each image there can be N people and each person has 18 keypoints associated with them, and each keypoint comes with a list [y,x,o] where the x,y are self explanatory and o is an inclusion/occlusion indicator. </p>
<pre><code>import numpy as np
import cv2
import os
def GeneratorMaskFiller(ImgPath,keys,string_ids,bs,mode="train",aug=None):
os.chdir(ImgPath)
while True:
loop_count=0
imgs=[]
masks=[]
for i in range(loop_count * bs,bs+loop_count * bs):
img=cv2.imread(string_ids[i]+'.jpg')
resized_img = cv2.resize(img,(224,224))
imgs.append(resized_img)
length = len(keys[i])
num_people=int(length/18)
sigma=7
zeros=np.zeros((img.shape[0],img.shape[1],18,num_people))
for part in range(18):
for x in range(img.shape[0]):
for y in range(img.shape[1]):
for people in range(num_people):
zeros[x][y][part][people]=np.exp((-(pow(x-keys[loop_count][part+people*18][1],2)+pow(y-keys[loop_count][part+people*18][0],2)))/sigma)
mask=np.zeros((img.shape[0],img.shape[1],18))
for x in range(img.shape[0]):
for y in range(img.shape[1]):
for part in range(18):
mask[x][y][part]=max(zeros[x,y,part,:])
mask=cv2.resize(mask,(224,224))
masks.append(mask)
imgs = np.asarray(imgs)
masks=np.asarray(masks)
loop_count+=1
if loop_count == len(keys):
loop_count=0
yield (imgs,masks)
</code></pre>
<p>Edits**:
For clarification the the argument keys is the a list of lists, where each element of the list corresponds to the keypoints for each image, so say there are three individuals in one image then there are 54 elements in that list where each element is a list of three elements. Out of the 18 masks each mask corresponds to a specific joint and will have disks centered at the true joint location for dependent on the number of people in the image and if the joints are visible. I am curious if there is a way for me to remove the multiple for loops I currently have in my code to generate these ground truth confident maps. </p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-07T02:29:03.993",
"Id": "460214",
"Score": "0",
"body": "Welcome to CodeReview@SE. Please include the main imports, and elaborate, in your question, on `my generator times out for batch sizes larger than one`. E.g., what does `times out` mean; do you have an idea about the time taken by `imread()` and `resize()`, respectively; at what batch size does it happen using, say, 7 \"people\" and a resolution of 99×99?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-07T02:47:24.667",
"Id": "460216",
"Score": "0",
"body": "Added main imports, I mean times out when I call .fit_generator from keras. Resize/imread are not the issue."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-06T22:28:39.597",
"Id": "235193",
"Score": "2",
"Tags": [
"python",
"performance",
"image",
"numpy"
],
"Title": "Generate Black and White confidence map masks for joints, same as OpenPose/Convolutional Pose Machines"
}
|
235193
|
<p>I have two worksheets in my workbook. The first worksheet ("home"), the user will enter information in cells B7-B14, not all of the fields are required in order for the macro to proceed.
I need each of the aforementioned fields to be copied over (in addition to B18-B28 & B31-B34) onto the second worksheet ("tracking"), based on the header in each column (this will allow the macro to continue to work should the user add columns).
Furthermore, in the home worksheet there is a field that dictates whether this data should be repeated. Meaning if the user enters a value of "2" in cell B15 then all of the fields should be copied on to one row and then the again on next row, where the only difference between the two rows is that the value of B18 when copied over to the "tracking" worksheet should go up by an increment of 1, this cell needs to have 3 leading zeros.
The macro should identify the last row and copy the information over to the next blank row.</p>
<p>right now my code just copies and pastes based on the exact range rather than searching for the column header and then pasting the data.</p>
<p>i thought it might be helpful to include the headers on my tracking tab it is attached. <a href="https://i.stack.imgur.com/MH8C1.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/MH8C1.png" alt="enter image description here"></a></p>
<p>i also haven't figured out the last piece, please help!</p>
<pre><code>Option Explicit
Sub EnterInfo()
Dim LastRow As Long
Dim InvoiceNo As String
LastRow = Track.Range("A" & Rows.Count).End(xlUp).Row
'Required Fields
If IsEmpty(Home.Range("B7")) Then
MsgBox ("Please enter the Delivery Date before continuing.")
Exit Sub
ElseIf IsEmpty(Home.Range("B8")) Then
MsgBox ("Please enter the Harvest Date before continuing.")
Exit Sub
ElseIf IsEmpty(Home.Range("B12")) Then
MsgBox ("Please enter the Package Date before continuing.")
Exit Sub
ElseIf IsEmpty(Home.Range("B13")) Then
MsgBox ("Please enter the Purchase Order Date before continuing.")
Exit Sub
ElseIf IsEmpty(Home.Range("B14")) Then
MsgBox ("Please enter the Purchase Order Number before continuing.")
Exit Sub
ElseIf IsEmpty(Home.Range("B15")) Then
MsgBox ("Please enter the Number of Boxes before continuing.")
Exit Sub
Else
Home.Range("B7").Copy
Track.Cells(LastRow + 1, "C").PasteSpecial Paste:=xlPasteValuesAndNumberFormats
Home.Range("B8").Copy
Track.Cells(LastRow + 1, "G").PasteSpecial Paste:=xlPasteValuesAndNumberFormats
Home.Range("B12").Copy
Track.Cells(LastRow + 1, "K").PasteSpecial Paste:=xlPasteValuesAndNumberFormats
Home.Range("B13").Copy
Track.Cells(LastRow + 1, "R").PasteSpecial Paste:=xlPasteValuesAndNumberFormats
Home.Range("B14").Copy
Track.Cells(LastRow + 1, "S").PasteSpecial Paste:=xlPasteValuesAndNumberFormats
Home.Range("B19").Copy
Track.Cells(LastRow + 1, "T").PasteSpecial Paste:=xlPasteValuesAndNumberFormats
Home.Range("B20").Copy
Track.Cells(LastRow + 1, "P").PasteSpecial Paste:=xlPasteValuesAndNumberFormats
Home.Range("B21").Copy
Track.Cells(LastRow + 1, "L").PasteSpecial Paste:=xlPasteValuesAndNumberFormats
Home.Range("B25").Copy
Track.Cells(LastRow + 1, "E").PasteSpecial Paste:=xlPasteValuesAndNumberFormats
Home.Range("B26").Copy
Track.Cells(LastRow + 1, "B").PasteSpecial Paste:=xlPasteValuesAndNumberFormats
Home.Range("B31").Copy
Track.Cells(LastRow + 1, "D").PasteSpecial Paste:=xlPasteValuesAndNumberFormats
Home.Range("B32").Copy
Track.Cells(LastRow + 1, "F").PasteSpecial Paste:=xlPasteValuesAndNumberFormats
Home.Range("B33").Copy
Track.Cells(LastRow + 1, "V").PasteSpecial Paste:=xlPasteValuesAndNumberFormats
Home.Range("B34").Copy
Track.Cells(LastRow + 1, "W").PasteSpecial Paste:=xlPasteValuesAndNumberFormats
End If
If Home.Range("B9") <> "" Then
Home.Range("B9").Copy
Track.Cells(LastRow + 1, "H").PasteSpecial Paste:=xlPasteValuesAndNumberFormats
Home.Range("B22").Copy
Track.Cells(LastRow + 1, "M").PasteSpecial Paste:=xlPasteValuesAndNumberFormats
End If
If Home.Range("B10") <> "" Then
Home.Range("B10").Copy
Track.Cells(LastRow + 1, "I").PasteSpecial Paste:=xlPasteValuesAndNumberFormats
Home.Range("B23").Copy
Track.Cells(LastRow + 1, "N").PasteSpecial Paste:=xlPasteValuesAndNumberFormats
End If
If Home.Range("B11") <> "" Then
Home.Range("B11").Copy
Track.Cells(LastRow + 1, "J").PasteSpecial Paste:=xlPasteValuesAndNumberFormats
Home.Range("B24").Copy
Track.Cells(LastRow + 1, "O").PasteSpecial Paste:=xlPasteValuesAndNumberFormats
End If
End Sub
</code></pre>
|
[] |
[
{
"body": "<p>A function able to set the column number according to the column header would be the next one. Please replace ActiveSheet from the <code>Track</code> worksheet definition</p>\n\n<pre><code>Private Function HdN(strHead As String) As Long\n Dim hdArr As Variant, Track As Worksheet, i As Long, lastCol As Long\n Set Track = ActiveSheet 'Attention! define here your real sheet. I used it for testing\n lastCol = Track.Cells(1, Track.Columns.count).End(xlToLeft).Column\n hdArr = Track.Range(\"A1:\" & Cells(1, lastCol).Address).Value\n HdN = Application.WorksheetFunction.Match(strHead, hdArr, 0)\nEnd Function\n</code></pre>\n\n<p>It can be used in the next way:</p>\n\n<p>Instead of <code>Track.Cells(LastRow + 1, \"C\")</code> you can use <code>Track.Cells(LastRow + 1, HdN(\"Delivery Date\"))</code>.\nIf the actual column will be cut and inserted in a different place, it can be identified.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-07T20:14:56.723",
"Id": "235250",
"ParentId": "235196",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-06T22:59:27.090",
"Id": "235196",
"Score": "2",
"Tags": [
"vba",
"excel"
],
"Title": "Copy Certain Cells over to another worksheet based on column headers"
}
|
235196
|
<p>I'm going to simulate diffraction patterns of a normal incident gaussian profile beam from a 2D array of point scatterers with a distribution in heights. </p>
<p>The 2D array of scatterer positions <code>X</code>, <code>Y</code> and <code>Z</code> each have size <code>N x N</code> and these are summed-over in each call to <code>E_ab(a, b, positions, w_beam)</code>. This is done <code>M x M</code> times to build up the diffraction pattern.</p>
<p>If I estimate ten floating point operations per scatter site per pixel and a nanosecond per flop (what my laptop does for small numpy arrays) I'd expect the time to be <code>10 M^2 N^2 1E-09</code> seconds. For small N this runs a factor of 50 or 100 slower than that, and for large <code>N</code> (larger than say 2000) it slows down even further. I am guessing these have something to do with the paging of the large arrays in memory.</p>
<p>What can I do to increase the speed for large <code>N</code>?</p>
<p><strong>note:</strong> Right now the height variation <code>Z</code> is random, in the future I plan to include an additional systematic height variation term as well, so even though purely gaussian variation might have an analytical solution, I need to do this numerically.</p>
<hr>
<p>Since I'm distributing Z height randomly here, plots will look a little different each time. My output (run on a laptop) is as follows, and I can not even begin to understand why it takes longer (~ 16 seconds) when <code>w_beam</code> is small than when it is large (~6 seconds). (When I run this on an older Python 2 that came with IDLE all four are between 10 and 10.5 seconds)</p>
<p>My estimator <code>10 M^2 N^2 1E-09</code> suggests 0.25 seconds, these are roughly 50 times slower so there may be room for substantial improvement.</p>
<pre><code>1 16.460583925247192
2 14.861294031143188
4 8.405776023864746
8 6.4988932609558105
</code></pre>
<p><strong>Total time:</strong> about 46 seconds on 2012 MacBook and recent Anaconda Python 3 installation.</p>
<p>Python script:</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
import time
def E_ab(a, b, positions, w_beam, k0):
X, Y, Z = positions
Rsq = X**2 + Y**2
phases = k0 * (a*X + b*Y + (1 + np.sqrt(1 - a**2 - b**2))*Z)
E = np.exp(-Rsq/w_beam**2) * np.exp(-j*phases)
return E.sum() / w_beam**2 # rough normalization
twopi, j = 2*np.pi, np.complex(0, 1)
wavelength = 0.08
k0 = twopi/wavelength
z_noise = 0.05 * wavelength
N, M = 100, 50
x = np.arange(-N, N+1)
X, Y = np.meshgrid(x, x)
Z = z_noise * np.random.normal(size=X.shape) # use random Z noise for now
positions = [X, Y, Z]
A = np.linspace(0, 0.2, M)
answers = []
for w_beam in (1, 2, 4, 8):
E = []
tstart = time.time()
for i, a in enumerate(A):
EE = []
for b in A:
e = E_ab(a, b, positions, w_beam, k0)
EE.append(e)
E.append(EE)
print(w_beam, time.time() - tstart)
answers.append(np.array(E))
if True:
plt.figure()
for i, E in enumerate(answers):
plt.subplot(2, 2, i+1)
plt.imshow(np.log10(np.abs(E)), vmin=0.0001)
plt.colorbar()
plt.show()
</code></pre>
<p><a href="https://i.stack.imgur.com/nhuwz.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/nhuwz.png" alt="plot of a diffraction pattern"></a></p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-07T04:44:24.717",
"Id": "460220",
"Score": "1",
"body": "Is `k0` supposed to be a global? It is used in `E_ab` but not passes as an argument."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-07T07:31:24.200",
"Id": "460224",
"Score": "0",
"body": "@BjörnLindqvist either way is okay with me but your way would be better so I've made `k0` an argument."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-07T09:23:29.777",
"Id": "460240",
"Score": "1",
"body": "It probably takes longer for small `w_beam`, because the exponent in `np.exp(-Rsq/w_beam**2)` is larger and takes longer to compute."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-07T16:39:28.093",
"Id": "460295",
"Score": "0",
"body": "@Graipher ah that makes sense! I was thinking \"but they're all small numbers, almost zero\" but forgot to think about how they got that way. Interestingly my Python 2 uses numpy version 1.13.0 and all four times are between 10 and 11 seconds (reproducibly) while my Python 3 Anaconda installation with numpy version 1.17.3 shows the times from 16 to 6 seconds as shown. I'll be surprised if `np.exp()` has changed, doesn't it call some transcendental functions built into my laptop's CPU?"
}
] |
[
{
"body": "<p>I managed to make your script a bit faster. See the comments in the\nsource code:</p>\n\n<pre><code>import numpy as np\nimport matplotlib.pyplot as plt\nimport time\n\n# Makes it so numpy always outputs the same random numbers which is\n# useful during development. Comment out the line in production.\nnp.random.seed(1234)\n\ndef main():\n twopi, img = 2*np.pi, np.complex(0, 1)\n\n wavelength = 0.08\n k0 = twopi/wavelength\n\n z_noise = 0.05 * wavelength\n\n N, M = 100, 50\n x = np.arange(-N, N+1)\n\n # Use random Z noise for now\n Z = z_noise * np.random.normal(size = (x.shape[0], x.shape[0]))\n\n A = np.linspace(0, 0.2, M)\n\n tstart = time.time()\n answers = []\n\n # X and Y with shapes (x, 1) and (1, x) contains the same data.\n X = x[np.newaxis,:]\n Y = x[:,np.newaxis]\n\n # Compute squared Euclidean distances with shape (x, x).\n Rsq = X**2 + Y**2\n\n # Compute other distances with shape (M, M).\n a = A[:,np.newaxis]\n b = A[np.newaxis,:]\n SQ = 1 + np.sqrt(1 - a**2 - b**2)\n\n # Add noise thing (M, M, x, x).\n SQ_Z = SQ[:,:,np.newaxis,np.newaxis] * Z\n\n # Gets shape (M, 1, x) and (M, x, 1).\n A_X = A[:,np.newaxis,np.newaxis] * X\n A_Y = A[:,np.newaxis,np.newaxis] * Y\n\n # Calculates A*X + A*Y with shape (M, M, x, x).\n A_X_Y = A_X[:,np.newaxis] + A_Y[np.newaxis,:]\n\n # e^{-j*phases} with shape (M, M, x, x).\n A_stuff = np.exp(-img * k0 * (A_X_Y + SQ_Z))\n for w_beam in (1, 2, 4, 8):\n coeff = np.exp(-Rsq/w_beam**2)\n # Sums over the last two dimensions, shape becomes (M, M).\n E = np.sum(A_stuff * coeff, axis = (2, 3)) / w_beam**2\n answers.append(E)\n\n print(f'Time: {time.time() - tstart:.3}')\n # Print checksum. Useful for debugging.\n print(sum(np.sum(E) for e in answers))\n if True:\n plt.figure()\n for i, E in enumerate(answers):\n plt.subplot(2, 2, i+1)\n plt.imshow(np.log10(np.abs(E)), vmin=0.0001)\n plt.colorbar()\n plt.show()\n\nmain()\n</code></pre>\n\n<p>I have wrapped all your code in a <code>main</code> function. It is good practice\nto do so, even for small scripts, but it makes it easy to see if\nthere's any dependencies on global variables.</p>\n\n<p>The script runs about four times faster. Most of the speedup comes\nfrom replacing your explicit loop with vector functions. So instead of</p>\n\n<pre><code>for i, a in enumerate(A):\n EE = []\n for b in A:\n e = E_ab(a, b, positions, w_beam, k0)\n EE.append(e)\n E.append(EE)\n</code></pre>\n\n<p>those lines now read</p>\n\n<pre><code>coeff = np.exp(-Rsq/w_beam**2)\nE = np.sum(A_stuff * coeff, axis = (2, 3)) / w_beam**2\nanswers.append(E)\n</code></pre>\n\n<p>To get the data in a format that vector functions can handle I've\nadded a lot of\n<a href=\"https://docs.scipy.org/doc/numpy/user/basics.broadcasting.html\" rel=\"nofollow noreferrer\">broadcasting</a>. It\ncan be used to compute, for example, the <a href=\"https://scicomp.stackexchange.com/questions/10748/cartesian-products-in-numpy\">cartesian\nproduct</a>\nof arbitrary numpy arrays.</p>\n\n<p>I think someone who understands the math (which I don't) could\noptimize your script even more. Some of the calculations seem\nredundant to me, but I have no idea how to factor them out.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-07T17:15:55.147",
"Id": "460302",
"Score": "0",
"body": "I did a quick test and I'm wondering what time you got when you say \"a bit faster\" because this is *far slower* on my laptop (2012 MacBook). Total execution time is now 116 seconds and that breaks down to 29.6 seconds of overhead before the loop, and then the four loops through `w_beam` are 9.6, 8.4, 30.9 and 37.5 seconds. My version runs in 47.7 second total, with the four times shown in the question (and no overhead). Could you mention the \"faster\" time that you obtained and some information on the computer used? As I mention in the question I think my speed is limited by memory paging."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-07T17:38:15.187",
"Id": "460305",
"Score": "0",
"body": "Odd. I'm benchmarking by running the script and not doing anything else with the computer. With N=100, your version runs in 35s and mine in 7s and with N=200, yours in 140s and mine in 29s. Perhaps you're using an old version of Numpy which doesn't do broadcasting as well? My Numpy version is 1.17.4."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-07T17:44:43.447",
"Id": "460308",
"Score": "0",
"body": "see [this comment](https://codereview.stackexchange.com/questions/235200/improving-speed-of-this-numpy-based-diffraction-calculator/235222#comment460295_235200) for my Numpy versions. I get similar total times in 1.17.3 and the older 1.13.0 (in Python 2). But things can still suddenly change [as in this SciPy update](https://stackoverflow.com/a/49428804/3904031) . I'll look into updating from 1.17.3 to 1.17.4 tomorrow; I'll feel safer being around some developers when I try."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-08T07:29:16.707",
"Id": "460363",
"Score": "0",
"body": "The running time will probably depend on your available memory and CPU L1 cache size, since in the OP only an M x N array had to be kept in memory, but here it is an M x N x 50 x 50 array, 50 being the default number of values produced by `linspace`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-08T12:13:36.527",
"Id": "460394",
"Score": "1",
"body": "@Graipher yes I think that the larger array combined with my laptop (including CPU) being circa 2012 and having low remaining disk space might be why this is so much slower for me on this particular computer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-08T12:15:09.083",
"Id": "460395",
"Score": "0",
"body": "@BjörnLindqvist I've just had a friend run on numpy 1.13.1 and it's much faster than my 1.17.3, so once I move to a better computer I expect to be able to take advantage of this. Thanks!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-09T08:24:52.710",
"Id": "460539",
"Score": "0",
"body": "@BjörnLindqvist example of a performance hit for swapping pieces of large arrays in and out of cache. Paging slows things down tremendously! [How large is my 2012 MacBook Air's L1 cache? Are they larger now?](https://apple.stackexchange.com/q/379323/143729)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-09T11:07:24.957",
"Id": "460562",
"Score": "0",
"body": "If the array is large enough that it causes swapping, then that explains why it runs slower. However, with N = 100, M = 50, the size is \"only\" about 1.6 GB which should be fine if you have 4 GB of memory. You can try and reduce the parameters to see if you can find some \"cliff\" where performance starts to suffer. Or you can use single precision math by adding `dtype = 'f4'` to all array constructors. That roughly halves the execution time on my computer but the simulation accuracy may suffer."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-07T13:19:29.393",
"Id": "235222",
"ParentId": "235200",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "235222",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-07T01:28:50.667",
"Id": "235200",
"Score": "4",
"Tags": [
"python",
"performance",
"python-3.x",
"numpy"
],
"Title": "improving speed of this numpy-based diffraction calculator"
}
|
235200
|
<p>I'm new to the Developers world and I have project that I've been working on. It's to calculate the Bowling Game Score (similar to the Hdcp Score done by this tool: <a href="https://bowlinggenius.com/" rel="nofollow noreferrer">https://bowlinggenius.com/</a> )</p>
<p>I'm looking for a feedback to my code, from:
- Readability;
- the OOP SOLID principles and best-practice point of views (Encapsulation, Abstraction etc.)</p>
<p>Any suggestions on how to better refactor it?</p>
<p>Here is my code:</p>
<p>Game.cs</p>
<pre><code> using System;
using TenPinsBowlingGameHdcp.Common;
using TenPinsBowlingGameHdcp.Handlers;
namespace TenPinsBowlingGameHdcp.Modules
{
public class Game
{
Frame[] ArrayOfFrames = new Frame[_maxFrameNumber];
private int _currentFrameIndex = 0;
private const int _maxFrameNumber = ConstTenPinsGameData.MaxFramesNumber;
private readonly int _startingPinsNumber = ConstTenPinsGameData.StartingPinsNumber;
private readonly int _finalFrameIndex = _maxFrameNumber - 1;
private readonly GameHandler _gameHandler = new GameHandler();
private bool _currentFrameIsNotSetYet => ArrayOfFrames[_currentFrameIndex] == null;
private bool _isFinalFrame => _currentFrameIndex == _finalFrameIndex;
private bool _frameBeforeLastIsAvailable => (_currentFrameIndex > 1) ? true : false;
private bool _previousFrameIsAvailable => (_currentFrameIndex > 0) ? true : false;
private bool _isCurrentFrameFinalWithBonus =>
(ArrayOfFrames[_currentFrameIndex].FrameStatus == FrameStatus.TenthFrameWithBonus) ? true : false;
public int Bowl(int kickedPins)
{
int gameScore = 0;
ValidateKickedPinsInput(kickedPins);
ValidateIfNewThrowAllowedForFinalFrame(ArrayOfFrames[_currentFrameIndex]);
if (_currentFrameIsNotSetYet)
{
ArrayOfFrames[_currentFrameIndex] = new Frame();
OrchestrateFramesWithFirstThrowScore(kickedPins);
}
else
{
OrchestrateFramesWithSecondThrowScore(kickedPins);
}
gameScore = ScoreCalculator.CalculateCurrentHdcpScoreFor(ArrayOfFrames, _currentFrameIndex);
SetFrameIndexForNoneFinalFrame(ArrayOfFrames[_currentFrameIndex], kickedPins);
return gameScore;
}
private void OrchestrateFramesWithFirstThrowScore(int kickedPins)
{
int previousFrameIndex = _currentFrameIndex - 1;
int beforeLastFrameIndex = _currentFrameIndex - 2;
if (_isFinalFrame)
_gameHandler.SetFinalFrameFlagIfApplicable(ArrayOfFrames[_currentFrameIndex]);
_gameHandler.SetFirstScoreForNewFrame(ArrayOfFrames[_currentFrameIndex], kickedPins);
if (_frameBeforeLastIsAvailable)
_gameHandler.SetDifferentPropertiesForFrame(ArrayOfFrames[beforeLastFrameIndex], kickedPins);
if (_previousFrameIsAvailable)
_gameHandler.SetDifferentPropertiesForFrame(ArrayOfFrames[previousFrameIndex], kickedPins);
_gameHandler.SetStatusForCurrentFrame(ArrayOfFrames[_currentFrameIndex]);
_gameHandler.SetFrameClosedFlagIfStrike(ArrayOfFrames[_currentFrameIndex]);
}
private void OrchestrateFramesWithSecondThrowScore(int kickedPins)
{
int previousFrameIndex = _currentFrameIndex - 1;
if (_previousFrameIsAvailable)
_gameHandler.SetDifferentPropertiesForFrame(ArrayOfFrames[previousFrameIndex], kickedPins);
if (_isCurrentFrameFinalWithBonus)
_gameHandler.SetDifferentPropertiesForFrame(ArrayOfFrames[_currentFrameIndex], kickedPins);
else
_gameHandler.SetPropertiesForCurrentFrame(ArrayOfFrames[_currentFrameIndex], kickedPins);
}
private void ValidateKickedPinsInput(int kickedPins)
{
if (kickedPins < 0 || kickedPins > _startingPinsNumber)
throw new ArgumentException($"Sorry, your kickedPins '{kickedPins}' is out of allowed range 0-{_startingPinsNumber}. Pls check.");
}
private void ValidateIfNewThrowAllowedForFinalFrame(Frame currentFrame)
{
if (currentFrame != null && currentFrame.IsFinalFrame && currentFrame.IsFrameReadyForScore)
throw new ArgumentException("Sorry, you have played All available bowl-throws for this game. Pls start a new game.");
}
private void SetFrameIndexForNoneFinalFrame(Frame currentFrame, int kickedPins)
{
if (!currentFrame.IsFinalFrame)
SetFrameIndexBasedOnKickedPins(currentFrame, kickedPins);
}
private void SetFrameIndexBasedOnKickedPins(Frame currentFrame, int kickedPins)
{
if (kickedPins == _startingPinsNumber)
_currentFrameIndex++;
else if (currentFrame.IsFrameClose)
_currentFrameIndex++;
}
}
}
</code></pre>
<p>GameHandler.cs</p>
<pre><code> using System;
using TenPinsBowlingGameHdcp.Common;
using TenPinsBowlingGameHdcp.Modules;
namespace TenPinsBowlingGameHdcp.Handlers
{
public class GameHandler
{
private readonly int _initialValueForBowlThrow = ConstTenPinsGameData.InitialValueForTheBowlThrow;
private readonly int _startingPinsNumber = ConstTenPinsGameData.StartingPinsNumber;
private readonly FrameHandler _frameHandler = new FrameHandler();
private const int _thirdBowlForFrameWithoutBonus = 0;
public void SetFirstScoreForNewFrame(Frame currentFrame, int kickedPins)
{
_frameHandler.SetFirstBowlForFrame(currentFrame, kickedPins);
}
public void SetFinalFrameFlagIfApplicable(Frame currentFrame)
{
_frameHandler.SetIsFinalFrameFlagToTrue(currentFrame);
}
public void SetPropertiesForCurrentFrame(Frame currentFrame, int kickedPins)
{
ValidateFrameInputIsNotNull(currentFrame);
ValidateSecondBowlValueForFrame(currentFrame, kickedPins);
_frameHandler.SetSecondBowlForFrame(currentFrame, kickedPins);
SetStatusForCurrentFrame(currentFrame);
CompleteRegularFrame(currentFrame);
_frameHandler.SetIsFrameClosedFlagToTrue(currentFrame);
}
public void SetStatusForCurrentFrame(Frame currentFrame)
{
ValidateFrameInputIsNotNull(currentFrame);
if (currentFrame.FirstBowlScore == _startingPinsNumber)
_frameHandler.SetStatusForFrame(currentFrame, FrameStatus.Strike);
else if (currentFrame.FirstBowlScore + currentFrame.SecondBowlScore == _startingPinsNumber)
_frameHandler.SetStatusForFrame(currentFrame, FrameStatus.Spare);
if (currentFrame.IsFinalFrame && (currentFrame.FrameStatus == FrameStatus.Strike ||
currentFrame.FrameStatus == FrameStatus.Spare))
_frameHandler.SetStatusForFrame(currentFrame, FrameStatus.TenthFrameWithBonus);
}
private void CompleteRegularFrame(Frame currentFrame)
{
ValidateFrameInputIsNotNull(currentFrame);
if (currentFrame.FirstBowlScore + currentFrame.SecondBowlScore != _startingPinsNumber)
CompleteSettingPropertiesForFrame(currentFrame, _thirdBowlForFrameWithoutBonus);
}
public void SetFrameClosedFlagIfStrike(Frame currentFrame)
{
ValidateFrameInputIsNotNull(currentFrame);
if (currentFrame.FirstBowlScore == _startingPinsNumber)
_frameHandler.SetIsFrameClosedFlagToTrue(currentFrame);
}
public void SetDifferentPropertiesForFrame(Frame frame, int kickedPins)
{
ValidateFrameInputIsNotNull(frame);
if (frame.SecondBowlScore == _initialValueForBowlThrow)
_frameHandler.SetSecondBowlForFrame(frame, kickedPins);
else if (frame.ThirdBowlBonusScore == _initialValueForBowlThrow)
CompleteSettingPropertiesForFrame(frame, kickedPins);
}
private void CompleteSettingPropertiesForFrame(Frame frame, int kickedPins)
{
_frameHandler.SetThirdBowlForFrame(frame, kickedPins);
_frameHandler.SetIsReadyToScoreForFrameToTrue(frame);
}
private void ValidateSecondBowlValueForFrame(Frame frame, int kickedPins)
{
if (frame.FirstBowlScore + kickedPins > _startingPinsNumber)
throw new ArgumentException($"The 2nd throw pins of {kickedPins} is higher than allowed for this frame. Pls check.");
}
private void ValidateFrameInputIsNotNull(Frame frame)
{
if (frame == null)
throw new ArgumentNullException($"The Frame provided {frame} is Null. Pls check.");
}
}
}
</code></pre>
<p>Frame.cs</p>
<pre><code> using System;
using TenPinsBowlingGameHdcp.Common;
namespace TenPinsBowlingGameHdcp.Modules
{
public enum FrameStatus
{
Regular,
Strike,
Spare,
TenthFrameWithBonus
}
public class Frame
{
private readonly int _startingPinsNumber = ConstTenPinsGameData.StartingPinsNumber;
public FrameStatus FrameStatus { get; private set; }
public int FirstBowlScore { get; private set; } = -1;
public int SecondBowlScore { get; private set; } = -1;
public int ThirdBowlBonusScore { get; private set; } = -1;
public bool IsFrameClose { get; private set; } = false;
public bool IsFrameReadyForScore { get; private set; } = false;
public bool IsFinalFrame { get; private set; } = false;
public void SetFirstBowlScore(int kickedPinsCount)
{
if (kickedPinsCount >= 0 && kickedPinsCount <= _startingPinsNumber)
FirstBowlScore = kickedPinsCount;
else
throw new ArgumentException($"The kicked pins count for 1st throw is '{kickedPinsCount}', but has to be between 0 and {_startingPinsNumber}.");
}
public void SetSecondBowlScore(int kickedPinsCount)
{
if (kickedPinsCount >= 0 && kickedPinsCount <= _startingPinsNumber)
SecondBowlScore = kickedPinsCount;
else
throw new ArgumentException($"The kicked pins count for 2nd throw is '{kickedPinsCount}', but has to be between 0 and {_startingPinsNumber}.");
}
public void SetThirdBowlBonusScore(int kickedPinsCount)
{
if (kickedPinsCount >= 0 && kickedPinsCount <= _startingPinsNumber)
ThirdBowlBonusScore = kickedPinsCount;
else
throw new ArgumentException($"The kicked pins count for 3rd (Bonus) throw is '{kickedPinsCount}', but has to be between 0 and {_startingPinsNumber}.");
}
public void SetIsFrameClosed(bool isSet)
{
IsFrameClose = isSet;
}
public void SetIsFrameReadyForScore(bool isSet)
{
IsFrameReadyForScore = isSet;
}
public void SetIsFinalFrame(bool isSet)
{
IsFinalFrame = isSet;
}
public void SetFrameStatus(FrameStatus frameStatus)
{
if (frameStatus == null)
throw new ArgumentNullException("The FrameStatus provided, is Null. Pls check.");
FrameStatus = frameStatus;
}
}
}
</code></pre>
<p>FrameHandler.cs</p>
<pre><code> using System;
using TenPinsBowlingGameHdcp.Common;
using TenPinsBowlingGameHdcp.Modules;
namespace TenPinsBowlingGameHdcp.Handlers
{
public class FrameHandler
{
private readonly int _initialValueForBowlThrow = ConstTenPinsGameData.InitialValueForTheBowlThrow;
public void SetFirstBowlForFrame(Frame frame, int kickedPins)
{
ValidateForNull(frame);
frame.SetFirstBowlScore(kickedPins);
}
public void SetSecondBowlForFrame(Frame frame, int kickedPins)
{
ValidateForNull(frame);
if (frame.SecondBowlScore == _initialValueForBowlThrow)
{
frame.SetSecondBowlScore(kickedPins);
}
}
public void SetThirdBowlForFrame(Frame frame, int kickedPins)
{
ValidateForNull(frame);
if (frame.ThirdBowlBonusScore == _initialValueForBowlThrow)
{
frame.SetThirdBowlBonusScore(kickedPins);
}
}
public void SetIsReadyToScoreForFrameToTrue(Frame frame)
{
ValidateForNull(frame);
if (frame.ThirdBowlBonusScore != _initialValueForBowlThrow)
{
frame.SetIsFrameReadyForScore(true);
}
}
public void SetIsFrameClosedFlagToTrue(Frame frame)
{
ValidateForNull(frame);
frame.SetIsFrameClosed(true);
}
public void SetStatusForFrame(Frame frame, FrameStatus frameStatus)
{
ValidateForNull(frame);
frame.SetFrameStatus(frameStatus);
}
public void SetIsFinalFrameFlagToTrue(Frame frame)
{
ValidateForNull(frame);
frame.SetIsFinalFrame(true);
}
private void ValidateForNull(Frame frame)
{
if (frame == null)
throw new ArgumentNullException("The Frame is Null. Pls check.");
}
}
}
</code></pre>
<p>ScoreCalculator.cs</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BowlingGameHdcp
{
public class ScoreCalculator
{
public static int CalculateCurrentHdcpScore(Frame[] arrayOfFrames, int currentFrameIndex)
{
var gameScore = 0;
for (int countIndex = 0; countIndex <= currentFrameIndex; countIndex++)
{
if (arrayOfFrames[countIndex].IsFrameRedyForScore)
gameScore += arrayOfFrames[countIndex].FirstBowlScore +
arrayOfFrames[countIndex].SecondBowlScore +
arrayOfFrames[countIndex].ThirdBowlBonusScore;
}
return gameScore;
}
}
}
</code></pre>
<p>ConstTenPinsGameData.cs</p>
<pre><code>namespace TenPinsBowlingGameHdcp.Common
{
public static class ConstTenPinsGameData
{
public const int MaxFramesNumber = 10;
public const int StartingPinsNumber = 10;
public const int InitialValueForTheBowlThrow = -1;
}
}
</code></pre>
<p>Program.cs (NOTE: This part is not of my concern, or at least not the biggest one :) )</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BowlingGameHdcp
{
public class Program
{
public static void Main(string[] args)
{
var inputListFrom = gameInput.Split(',');
List<int> intInputList = new List<int>();
var gameInputArray = new[]
{
"1",
"1,1",
"1, 1, 5",
"10, 10",
"10,10,10",
"10,10,10,0",
"10, 7, 3, 9, 0, 10, 0, 8, 8, 2, 0, 6, 10, 10, 10, 8, 1",
"9, 0, 9,0, 9,0,9, 0, 9, 0, 9, 0, 9,0 , 9,0, 9,0, 9,0",
"5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5",
"0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0",
"0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0",
"0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,5",
"0,0,0,0,0,0,10,0,0,0,0,10,0,0,0,0,0,0",
"0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,10,2",
"0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,10,2,0",
};
foreach (var singleGameInput in gameInputArray)
{
Game game= new Game();
var inputListFrom = singleGameInput.Split(',');
List<int> intInputList = new List<int>();
foreach (var input in inputListFrom)
{
input.Trim();
int charIntoIntInput = Convert.ToInt32(input);
intInputList.Add(charIntoIntInput);
}
int score = 0;
foreach (var i in intInputList)
{
score = game.Bowl(i);
}
Console.WriteLine($"Current game input: `{singleGameInput}`");
Console.WriteLine($" \t\t\t\t\t\t\t Current Total Score: {score}");
}
Console.WriteLine("Hit any key to Quit.");
Console.ReadKey();
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-07T12:08:55.307",
"Id": "460255",
"Score": "0",
"body": "Why is `gameInputArray` an array of strings which you then need to split and convert to `int`s? Why not use a `List<List<int>>`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-07T15:02:09.267",
"Id": "460277",
"Score": "0",
"body": "Thanks @BCdotWEB. I'll check on it (the Program.cs, is not of a big concern to me, as it was merely just a check of the work, and not the request). Any concerns on the other classes? Should I split them more, or i.e. move GameHamdler part into FrameHandler class, and move most of the private methods from Game.cs into GameHandler.cs?"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-07T01:47:50.973",
"Id": "235201",
"Score": "3",
"Tags": [
"c#",
"object-oriented"
],
"Title": "bowling game score calculator"
}
|
235201
|
<p>Hello I have a NodeJS which act like an interface it connects the client(mobile app) to the actual server
My node JS API receives data from the client to verify it and send it to the server. </p>
<p>I want to know does this code looks good?<br>
Is that how API should be written in NodeJS?<br>
Does this code violate any of the SOLID principles?<br>
How can I improve this code? </p>
<pre><code>const axios = require("axios")
require("express-async-errors")
const bodyParser = require("body-parser")
const express = require("express")
const LOLTrackingSystem = require("../methods/onlineGamesTracking/LOLTracking")
const getUserData = require("../methods/leagueOfLegends/getUserData")
//======[Gizmo Operator Settings]=======
// userId = token
//========[Gizmo API URL]==========
apiRoute = (api) => {
api.use(bodyParser.json())
// api.use(bodyParser.urlencoded({ extended: false }));
// api.use(express.json());
api.post("/api/auth", (req, res) => {
const clientAuth = {
username: req.body.username,
password: req.body.password
}
const loginValidationURL = `http://${process.env.HOST}/api/users/${clientAuth.username}/${clientAuth.password}/valid`
axios
.get(loginValidationURL, { headers: { Authorization: process.env.AUTH } })
.then((response) => {
let token = response.data.result.identity.userId
response.data.result.result == 0
? res.json({ status: "Authenticated", result: 1, token: hash })
: res.json({ status: "Wrong Username or Password", result: 0 })
})
.catch((error) => {
console.log("error " + error)
res.json({
status: `Couldn't reach Arena Gaming Server. Try again later`,
result: 404
})
})
})
api.post("/api/memberProfile", (req, res) => {
var token = req.headers["authorization"]
// bcrypt.compare(token, hash).then(function(res) {
// // res == true
// });
const memberProfileURL = `http://${process.env.HOST}/api/users/${encryptedId}`
axios
.get(memberProfileURL, { headers: { Authorization: process.env.AUTH } })
.then((response) => {
response.data
})
.catch((error) => {
console.log("error " + error)
res.json({
status: `Couldn't reach Arena Gaming Server. Try again later`,
result: 404
})
})
})
//=============================================================================
// Gizmo Related API
//=============================================================================
// MemberState Get The UserId & HostId when member login or logout of Gizmo
api.post("/api/gizmo/memberState/:userId/:host/:state", async (req, res) => {
const member = {
state: req.params.state,
userId: req.params.userId,
hostComputer: req.params.host
}
if (Number(member.state)) {
console.log(
"[Logged In] Member with userId: " +
member.userId +
" To HostId: " +
member.hostComputer +
"[Sent From GizmoServer]"
)
await getUserData(member.userId, async (subscribed) => {
// Check if the user is subscribed to the tracking system or not
//*TODO* Add a list of currently tracking members that we can see
if (subscribed) {
LOLTrackingSystem(member.userId) // Start tracking that member
res.json("[Started] Member " + member.userId + " Tracking")
} else {
res.json(
"[Started] Member " +
member.userId +
" is not subscribed to the tracking system"
)
}
})
} else {
console.log(
"[Logged Out] Member with userId: " +
member.userId +
" From HostId: " +
member.hostComputer +
"[Sent From GizmoServer]"
)
}
})
}
module.exports = apiRoute
</code></pre>
<p>Thanks</p>
|
[] |
[
{
"body": "<p>the code has plenty of room for improvement, and yes it violates the solid principals like the Single responsibility principle \"your functions are way too big and the module in itself has too many responsibilities \", to clarify there are no rules on how API should be written in NodeJS there are code practices and design patterns that help us developers write more maintainable code, so don't try to follow every single rule you will get stuck in optimizing and it really depends on your project needs. \nNow for the improvement here are some suggestions you can work on :</p>\n\n<ul>\n<li>separate your endpoints in different files, take a look at my answer <a href=\"https://codereview.stackexchange.com/questions/235224/nodejs-apis-folder-structure/235254#235254\">here</a>, you can use the express router</li>\n<li>move your constant variables like \"loginValidationURL \" in a different file like config.js then import and use it</li>\n<li>don't overuse URL params use post request to get objects to your server</li>\n<li>Build the application with a framework independent mindset</li>\n<li>Make your functions lighter separate them by roles like this take this example on your \"/api/auth endpoint\" it will explain many things</li>\n</ul>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>// Your implimation\n\napi.post(\"/api/auth\", (req, res) => {\n const clientAuth = {\n username: req.body.username,\n password: req.body.password\n };\n\n const loginValidationURL = `http://${process.env.HOST}/api/users/${clientAuth.username}/${clientAuth.password}/valid`;\n\n axios\n .get(loginValidationURL, { headers: { Authorization: process.env.AUTH } })\n .then(response => {\n let token = response.data.result.identity.userId;\n response.data.result.result == 0\n ? res.json({ status: \"Authenticated\", result: 1, token: hash })\n : res.json({ status: \"Wrong Username or Password\", result: 0 });\n })\n .catch(error => {\n console.log(\"error \" + error);\n res.json({\n status: `Couldn't reach Arena Gaming Server. Try again later`,\n result: 404\n });\n });\n});\n\n/* Api Handler\n * file path : routes/api/client.js\n * in this file i only write the client api endpoints /client/auth /client/logout /client/:id the basic crud\n * i have seperate the main job in a controller module like that the api is mucj cleanter\n */\nconst express = require(\"express\");\nconst router = express.Router();\nconst { authClient } = require(\"../controller/clientcontroller\");\n\nrouter.post(\"/client/auth\", (req, res) => {\n authClient(req, res)\n});\n\n/* controller\n * file path : routes/controller/clientcontroller.js\n * in this file i only write the client controllers for each api call\n */\n\nconst { extractClientAuth } = require(\"./api/client/reqHandler\"); // this module will be responsible for extracting and validation req objects\nconst { loginValidationUrlBuilder } = require(\"../../config\"); // this module is responsible for all your static and config objects like axios custom headers\nconst { apiClient } = require(\"./services/externalJobs\"); // this for exrtenal jobs and api calls\nconst { responseBuilder } = require(\"./api/tools\"); // this module for creating response objects\n\nfunction authClient(req, res) {\n const clientAuth = extractClientAuth(req);\n const loginValidationURL = loginValidationUrlBuilder(clientAuth);\n apiClient\n .login(loginValidationURL)\n .then(response => res.json(responseBuilder.authSuccess(response)))\n .catch(error => {\n res.json(responseBuilder.authFailed(error));\n });\n}</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<ul>\n<li>this is by no mean the best way it's just a way to structures your project take from it what you like another this I can recommend this video on youtube channel Dev Mastry he does an excellent job of explaining how to create a scalable node application using express and MongoDB <a href=\"https://www.youtube.com/watch?v=fy6-LSE_zjI\" rel=\"nofollow noreferrer\">https://www.youtube.com/watch?v=fy6-LSE_zjI</a></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-08T16:44:53.300",
"Id": "235305",
"ParentId": "235212",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "235305",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-07T09:22:52.310",
"Id": "235212",
"Score": "1",
"Tags": [
"javascript",
"node.js",
"express.js"
],
"Title": "API using NodeJS to recive data from client and send it to a server"
}
|
235212
|
<p>I've been learning a ton of c++ lately on Codecademy and I'm soon done with the course of c++.</p>
<p>(Still need to learn classes, object-oriented programming and harder projects.)</p>
<p>But I wanted to get a review of my recent program.</p>
<p>And I also wanted to know if its possible to make an Unique ID, that only fits me, kinda like the cicada.</p>
<p>Psst, the program is to solve Ohm's Formular in physics and actively takes input to solve exactly your case.</p>
<p>Leave suggestions on what I could do better in this project + what I should try to program next too.</p>
<pre><code>//Include
#include <iostream>
#include <string>
using namespace std;
int main(){
//Declare variables
double Wolt;
double Ohm;
double Amp;
std::string Formular;
std::string Username;
std::string Whitelist;
//Login sequence:
std::cout << "Hvad er dit username?: ";
cin >> Username;
//Whitelist
Whitelist = "Fred267s", "Seb4572s", "Popp4593s";
//Check if username is on whitelist
if (Username == Whitelist){
std::cout << "Velkommen til fysik formel udregner til strøm " << Username << " \n";
std::cout << "Lavet af Frederik Schmidt 1.S \n";
}
//If username is NOT on the whitelist
else if (Username != "Fred267s", "Seb4572s", "Popp4593s" ){
std::cout << "Sorry, you do not have access! \n";
return 0;
}
//Questions
std::cout << "Hvad er det du skal udregne? ";
cin >> Formular;
//Wolt formular
if (Formular == "Wolt"){
//Questions
std::cout << "Hvad er Ohmen?: ";
cin >>Ohm;
std::cout << "Hvad er Amperen?: ";
cin >> Amp;
//Formular
Wolt = Ohm*Amp;
//Return
std::cout << "Volten er: " << Wolt << " \n";
}
//Amp formular
else if (Formular == "Amp"){
//Questions
std::cout << "Hvad er Volten?: ";
cin >>Wolt;
std::cout << "Hvad er Ohmen?: ";
cin >>Ohm;
//Formular
Amp = Wolt/Ohm;
//Return
std::cout << "Amperen er: " << Amp << " \n";
}
//Ohm formular
else if (Formular == "Ohm"){
//Questions
std::cout << "Hvad er Volten?: ";
cin >>Wolt;
std::cout << "Hvad er Amperen?: ";
cin >>Amp;
//Formular
Ohm = Wolt/Amp;
//Return
cout << "Ohmen er: " << Ohm << " \n";
}
//If the Formular inputtet is NOT on the list.
else {
cout << "Error in the formular, please try again!";
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-07T12:54:26.330",
"Id": "460264",
"Score": "0",
"body": "Wolt or Volt?:)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-07T14:55:42.317",
"Id": "460276",
"Score": "0",
"body": "@slepic Not English, so quite possibly Wolt."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-07T19:36:35.453",
"Id": "460313",
"Score": "0",
"body": "Nope, even in Norwegian it's Volt."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-08T02:32:25.863",
"Id": "460346",
"Score": "0",
"body": "Just a small comment (from a non C++ professional, though): people usually recommends against `using namespace std;`, so that you don't pollute your namespace with lots of stuff you probably don't need anyway. However, if you _do_ add it, it's redundant to write code like `std::cout`, you can write `cout` only"
}
] |
[
{
"body": "<p>Don't </p>\n\n<pre><code>using namespace std;\n</code></pre>\n\n<p>This doesn't do what you want (only first one works):</p>\n\n<pre><code> //Whitelist\n Whitelist = \"Fred267s\", \"Seb4572s\", \"Popp4593s\";\n\n //Check if username is on whitelist\n if (Username == Whitelist){\n\n</code></pre>\n\n<p>[It's also a VERY dodgy access control mechanism!]</p>\n\n<p>I don't like asking user for a string describing the \"Formula\". How does the user know they should type \"Wolt\"? What if they type \"wolt\" instead? I think it would be more reasonable to show 3 choices:</p>\n\n<pre><code>1 - Wolt 2 - Amp 3 - Ohm\n\nPlease Enter (1-3): \n</code></pre>\n\n<p>And then clean the user input checking if it is a valid integer between 1-3 and then represent the choice internally using a <a href=\"https://en.cppreference.com/w/cpp/language/enum\" rel=\"noreferrer\">Class enum</a> in your code. </p>\n\n<p>This will open up a range of oppotunities to <strong>use functions</strong> in your code. </p>\n\n<pre><code>\nenum class Formula ( wolt = 1, amp = 2, ohm = 3 );\n\n...\n\nFormula prompt_formula() {\n // code to read from std::cin clean input and cast to enum class\n}\n</code></pre>\n\n<p>Then try to find a way to add even more structure to your program rather than one huge if/elseif/else statement. I am not going to give you the code, because that would defeat the purpose, but your <code>main</code> function should be more like this:</p>\n\n<pre><code>int main() {\n explain_usage();\n Formular form = prompt_formular();\n auto [label, answer] = compute(form);\n print_answer(label, answer);\n}\n</code></pre>\n\n<p>I could go on, but that's probably plenty to get on with for now.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-07T14:07:33.250",
"Id": "235228",
"ParentId": "235214",
"Score": "8"
}
},
{
"body": "<p>Apart from Oliver Schonrock's suggestions, I'd like to add:</p>\n\n<h1>Be consistent</h1>\n\n<p>You write <code>std::cout</code> but <code>cin</code>. Either consistently prefix standard library symbols with <code>std::</code> (the preferred way), or leave it out everywhere in files where you have <code>using namespace std</code>.</p>\n\n<p>Also, be consistent in the language you are using. Some of the lines you print are in Norwegian, others in English. In fact, in some sentences you mix both.</p>\n\n<p>I'd recommend you switch to English everywhere, unless there is a requirement for Norwegian variable names, comments and/or output.</p>\n\n<h1>Focus on one thing</h1>\n\n<p>Why is this program checking usernames? It makes no sense to me. If the assignment is to implement a program that calculates volts, ohms and amperes based on Ohm's law, then just focus on that.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-08T08:54:40.370",
"Id": "460379",
"Score": "0",
"body": "I do not think OP has written a single Norwegian line."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-07T19:44:56.200",
"Id": "235246",
"ParentId": "235214",
"Score": "7"
}
},
{
"body": "<p>People are so weird about <code>using namespace std;</code>. If it's a main.cpp file and you promise not to rename it like main.h to include into something else, it's fine and reduces noise. Are you <strong>seriously</strong> worried about <strong>needing</strong> to write colliding names like cout or string? It's a reasonable habit to build to qualify names since it will be necessary in larger codebases, but that rationale is premature for single file learning code. </p>\n\n<p>Mixing std::cout with cin is a mistake though. To a reader, that implies there's some sort of significant difference between the two, like cin is not of the std:: namespace because otherwise why would the author specifically qualify cout? </p>\n\n<hr>\n\n<p>Use a formatter like clang-format. Your main function is indented by 1 which I'm pretty sure is unintentional. You should never need to think too much about formatting in any language.</p>\n\n<hr>\n\n<p>Compile your code with warnings on, e.g. <code>-Wall</code>. I got:</p>\n\n<pre><code><source>: In function 'int main()':\n\n<source>:21:41: warning: right operand of comma operator has no effect [-Wunused-value]\n\n 21 | Whitelist = \"Fred267s\", \"Seb4572s\", \"Popp4593s\";\n\n | ^~~~~~~~~~~\n\n<source>:21:52: warning: right operand of comma operator has no effect [-Wunused-value]\n\n 21 | Whitelist = \"Fred267s\", \"Seb4572s\", \"Popp4593s\";\n\n | ^\n\n<source>:31:50: warning: right operand of comma operator has no effect [-Wunused-value]\n\n 31 | else if (Username != \"Fred267s\", \"Seb4572s\", \"Popp4593s\" ){\n\n | ^~~~~~~~~~~\n</code></pre>\n\n<p>Which would have clued you into that issue automatically.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-07T22:50:35.013",
"Id": "460324",
"Score": "1",
"body": "The namespace std point is just about the habbit. nothing more at this point. Yes the , delimited assignment statements and comparisons were covered earlier."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-08T00:14:41.450",
"Id": "460338",
"Score": "0",
"body": "Yeah I saw, with warnings on the author could have caught it before sending out to review though"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-08T00:46:28.567",
"Id": "460340",
"Score": "0",
"body": "That's very true. I don't think he has a good setup yet. It's not that easy to do. ..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-08T12:35:30.510",
"Id": "460396",
"Score": "1",
"body": "One can easily \"reduce noise\" AND not use `using namespace std;` ... simply by begin specific via `using std::cout;` etc."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-14T10:50:10.923",
"Id": "461247",
"Score": "0",
"body": "Since you are a new contributor to Code Review, please note that Code Review aims for *readable* and *production quality* code. Reviewing practice code is a good opportunity to teach the OP proper programming habits. Besides, remember that Code Review, like every other Stack Exchange site, is designed to benefit the whole community, rather than just the OP."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-14T18:52:48.343",
"Id": "461296",
"Score": "0",
"body": "I don't agree that it's a proper programming habit, and I think thoughtless dismissal is not conducive to cultivating good habits. It seems peculiar that the community heaps praise on to posts like \"don't do X\" that could have been made by a bot, while exploring concepts of readability is met with scorn. I also don't think pointing out someone's newness as a way of leveraging a point is a prosocial interaction."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-17T03:22:52.317",
"Id": "461601",
"Score": "0",
"body": "(Remember to ping me by typing @L.F. so I don't miss your comment! Only the poster of the answer is pinged automatically, not the authors of the comments.) I downvoted your answer solely because I disagree with it, not because you are new. (I have upvoted many of your other answers.) Just note that sentences like \"People are so weird\" or \"met with scorn\" are ... not very welcomed by the community."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-07T22:10:17.730",
"Id": "235259",
"ParentId": "235214",
"Score": "-1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-07T11:07:40.430",
"Id": "235214",
"Score": "3",
"Tags": [
"c++"
],
"Title": "Ohms law calculator + whitelist of user. Learning use"
}
|
235214
|
<p>I'm just starting my adventure with python and I wanted to share my first project with you and ask for feedback and advice. This is a script for my friend to automate all calculations and database operations.</p>
<p><strong>What my code does:</strong></p>
<ol>
<li>Merge together the csv files in the specified folder forming two sets.</li>
<li>Calculate the difference in days between the two date columns.</li>
<li>Filter the data over a given date range.</li>
<li>Checking that the id from the data frame L is not part of the M.</li>
<li>Creates output tables where the results will be stored.</li>
<li>Mainly calculation of the average of individual columns after preparation</li>
<li>Saving the results in a table</li>
</ol>
<pre class="lang-py prettyprint-override"><code>import re
from datetime import datetime
import pandas as pd
import numpy as np
from tkinter import filedialog
from tkinter import *
import os, sys
import glob
from matplotlib.backends.backend_pdf import PdfPages
import time
listOfFiles = []
tempDF = pd.DataFrame()
tempDF2 = pd.DataFrame()
def get_filenames():
Tk().withdraw()
print("Initializing Dialogue... \\nPlease select a file.")
tk_filenames = filedialog.askdirectory()
tempDir = tk_filenames
return tempDir
choosen_dir = get_filenames()
os.chdir(choosen_dir)
for file in glob.glob("*.csv"):
listOfFiles.append(file)
for file in listOfFiles:
if file.startswith('L'):
Table = pd.read_csv(file, sep=';')
DF1 = pd.DataFrame(Table)
tempDF = tempDF.append(DF1, sort=False)
elif file.startswith('M'):
Table2 = pd.read_csv(file, sep=';')
DF2 = pd.DataFrame(Table2)
tempDF2 = tempDF2.append(DF2, sort=False)
else:
print('404')
DFL = tempDF
DFM = tempDF2
class ToDate():
def change_to_date(self, a, b):
a[b] = pd.to_datetime(a[b])
dat = ToDate()
dat.change_to_date(DFL, 'LDUR')
dat.change_to_date(DFL, 'LDOP')
dat.change_to_date(DFM, 'LDOP')
dat.change_to_date(DFM, 'LDUR')
DFL['M_WAGUR'] = DFL['LDOP'] - DFL['LDUR']
DFM['M_WAGUR'] = DFM['LDUR'] - DFM['LDOP']
DFL['M_WAGUR'] = DFL['M_WAGUR'] / np.timedelta64(1, 'D')
DFM['M_WAGUR'] = DFM['M_WAGUR'] / np.timedelta64(1, 'D')
date1 = input('Date range from YYYY-MM-DD')
date2 = input('Date range to YYYY-MM-DD')
DFL = DFL[(DFL['LDOP'] >= date1) & (DFL['LDOP'] <= date2)]
DFM = DFM[(DFM['LDUR'] >= date1) & (DFM['LDUR'] <= date2)]
DFM_BL = DFM
ListL = DFL.ID1.tolist()
DFM_BL = DFM_BL[~DFM_BL.ID1.isin(ListL)]
def createDT(name):
temp = pd.DataFrame(columns = ['Race','number of individuals','littering youngsters',
'first litter.','more than first litter',
'amount_21','lose_21','nip_count',
'age','between_litter'],index =[1])
temp['Race'] = name
return temp
def sortedDT(DT, col, number):
newDT = DT[DT[col] == number]
return newDT
def months(DT, col, col2):
newDT = DT[DT[col] != DT[col2]]
return newDT
def birth(DFL, DFM):
if len(DFL) > 0:
pigs = DFL[['LIL11', 'LIL21']]
pigs2 = DFM[['LIL11', 'LIL21']]
pigs = pigs.append(pigs2)
pigs['loses'] = pigs['LIL11'] - pigs['LIL21']
pigs['ST21'] = (pigs['loses'] / pigs['LIL11']) * 100
return pigs
else:
pigs = DFM[['LIL11', 'LIL21']]
pigs['loses'] = pigs['LIL11'] - pigs['LIL21']
pigs['ST21'] = (pigs['loses'] / pigs['LIL11']) * 100
return pigs
def sum_digits(n):
s = 0
while n.all():
s += n % 10
n //= 10
return s
def all_count(DFL, DFM, DFM_BL, n, new):
if len(DFL) > 0:
s = sum_digits(n)
pigs = birth(DFL, DFM)
DFM_BL = DFM_BL.drop_duplicates(subset='ID1', keep="first").copy()
new['first litter'] = len(DFL)
new['more than first litter'] = len(DFL) + len(DFM)
new['number of individuals'] = len(DFL) + len(DFM_BL)
new['littering youngsters'] = np.around(pigs['LIL11'].mean(), decimals=2)
new['amount_21'] = np.around(pigs['LIL21'].mean(), decimals=2)
new['lose_21'] = np.around(pigs['ST21'].mean(), decimals=2)
new['age'] = np.around(DFL['M_WAGUR'].mean())
new['between_litter'] = np.around(DFM['M_WAGUR'].mean())
new['nip_count'] = np.around(s.mean(), decimals=2)
return new
else:
pigs = birth(DFL, DFM)
dfm = DFM.drop_duplicates(subset='LPROS1', keep="first").copy()
new['first litter'] = "-"
new['more than first litter'] = len(DFM)
new['number of individuals'] = len(dfm)
new['littering youngsters'] = np.around(pigs['LIL11'].mean(), decimals=2)
new['amount_21'] = np.around(pigs['LIL21'].mean(), decimals=2)
new['lose_21'] = np.around(pigs['ST21'].mean(), decimals=2)
new['age'] = "-"
new['between_litter'] = np.around(DFM['M_WAGUR'].mean())
new['nip_count'] = "-"
return new
W1R43 = createDT('W1R43')
L_W1R43 = sortedDT(DFL,'ID1',10).copy()
M_W1R43 = sortedDT(DFM,'ID1',10).copy()
BL_W1R43 = sortedDT(DFM_BL,'ID1',10).copy()
all_count(L_W1R43,MW1R43,BL_W1R43,W1R43['LSUT1'],W1R43)
last = pd.concat([W1R43, ... ])
last.to_csv('Results.txt', header=True, index=False, sep='\t', mode='w')
last.to_html('Results.html',index=False)
</code></pre>
<p>In the future, I would like to transfer this code to Django as one of the tools.</p>
<p>Please advise me what I should change, what I should avoid and if there is something correct in this code you can also let me know. </p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-07T12:31:46.217",
"Id": "460257",
"Score": "0",
"body": "I would begin to use MVP since you want to use Django. Separate the view from the logic. You have several functions spread in the code together with dataframes definitions etc. Put them into classes (one specifically for the view, Tkinter in this case). Another for callbacks (you use tkinter and CLI at the same time, use callbacks to return values to the user via Tkinter, CLI, Django etc.). Also use `if __name__ == '__main__':` and a `main()` so it's easier to know where we should begin to read your code. If you need help, just ping."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-07T13:14:48.090",
"Id": "460267",
"Score": "0",
"body": "@Raphael Please post answers in the answer boxes."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-07T15:33:14.583",
"Id": "460282",
"Score": "0",
"body": "@Peilonrayz This is far from be an answer in my opinion, just some tips."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-08T02:18:42.103",
"Id": "460345",
"Score": "0",
"body": "@Raphael, I agree with Peilonrayz. I think that you should take your comment and make it into a review, it sounds like you have some good information there, why not get some recognition for it?"
}
] |
[
{
"body": "<p>The first thing I would do is change the </p>\n\n<pre class=\"lang-py prettyprint-override\"><code>from tkinter import filedialog\nfrom tkinter import *\n</code></pre>\n\n<p>to </p>\n\n<pre class=\"lang-py prettyprint-override\"><code>import tkinter as tk\n</code></pre>\n\n<p>It is generally seen as bad form to 'pollute' the namespace by doing <code>from tkinter import *</code>, see the last paragraph in <a href=\"https://www.python.org/dev/peps/pep-0008/#imports\" rel=\"nofollow noreferrer\">PEP 8's section on imports</a>. By using <code>import tkinter as tk</code> and referencing everything as e.g. <code>tk.filedialog</code> it stays clear where the function came from.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-08T02:13:27.047",
"Id": "460343",
"Score": "0",
"body": "Welcome to Code Review! Would you please explain your reasoning a little bit, add some meat to your answer?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-07T13:46:54.860",
"Id": "235225",
"ParentId": "235216",
"Score": "1"
}
},
{
"body": "<p>Here are some of the issues I've found with your code. But there are\nmany more left and it is very hard to review your code without seeing\nsome sample data files. Consider rewriting your code, taking these\nsuggestions into account and then posting another request for code\nreview.</p>\n\n<h3>Avoid mixing import styles</h3>\n\n<pre><code>import re\nfrom datetime import datetime\nimport pandas as pd\nimport numpy as np\nfrom tkinter import filedialog\nfrom tkinter import *\nimport os, sys\nimport glob\nfrom matplotlib.backends.backend_pdf import PdfPages\nimport time\n</code></pre>\n\n<p>It is ugly and can be confusing to mix import styles. Choose the one\nyou like, either <code>from foo import bar</code> or <code>import foo [as bar]</code>, and\nstick with that as much as possible.</p>\n\n<h3>Wrap code in <code>main</code></h3>\n\n<p>Writing code at the module level means that the global namespace is\nmodified when the code runs. Suppose you have the following code:</p>\n\n<pre><code>y = ...\n...\nfor i in range(x):\n ...\nfor i in range(y):\n ...\n</code></pre>\n\n<p>You decide to refactor the second for-loop into its own function, but\nyou forget to pass <code>y</code> as a parameter:</p>\n\n<pre><code>def new_fun():\n for i in range(y):\n ...\ny = ...\n...\nfor i in range(x):\n ...\nnew_fun()\n</code></pre>\n\n<p>The code contains a bug but still runs. It can cause nasty and hard to\ndebug bugs (has happened to me several times before I wised\nup). Therefore, it's good practice to always wrap the main code in a\n<code>main</code>, even for small scripts. Like this:</p>\n\n<pre><code>def main():\n ...\nif __name__ == '__main__':\n main()\n</code></pre>\n\n<h3>Follow PEP 8</h3>\n\n<p>Follow <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP 8</a> - Python's\nstyle guide. So use snake-case instead of camel-case for variable\nnames. E.g <code>list_of_files</code> instead of <code>listOfFiles</code>.</p>\n\n<h3>Naming</h3>\n\n<p>Ensure that names are accurate, understandable and follows PEP 8. E.g</p>\n\n<pre><code>choosen_dir = get_filenames()\nos.chdir(choosen_dir)\n</code></pre>\n\n<p>The function gets a <em>directory</em> not filenames, so it should be called\n<code>get_dir</code>.</p>\n\n<p>The name <code>file</code> should be avoided because it clashes with a\nPython builtin. I'd replace it with <code>fname</code>.</p>\n\n<p>Also names such as <code>W1R43</code>, <code>L_W1R43</code> and <code>ListL</code> are very cryptic. I\nhave looked at the code for a while but I still have no idea what they\nare about.</p>\n\n<h3>Intermediate lists</h3>\n\n<p>You have code like</p>\n\n<pre><code>listOfFiles = []\n...\nfor file in glob.glob(\"*.csv\"):\n listOfFiles.append(file)\nfor file in listOfFiles:\n ...\n</code></pre>\n\n<p>Instead you can just write</p>\n\n<pre><code>for file in glob.glob(\"*.csv\")\n</code></pre>\n\n<p>without creating the <code>listOfFiles</code> list.</p>\n\n<h3>ToDate</h3>\n\n<p>I don't understand the purpose of this class. I think you can just write:</p>\n\n<pre><code>df_l['LDUR'] = pd.to_datetime(df_l['LDUR'])\ndf_l['LDOP'] = pd.to_datetime(df_l['LDOP'])\ndf_m['LDUR'] = pd.to_datetime(df_m['LDUR'])\ndf_m['LDOP'] = pd.to_datetime(df_m['LDOP'])\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-08T07:45:05.417",
"Id": "235276",
"ParentId": "235216",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "235276",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-07T11:51:38.853",
"Id": "235216",
"Score": "4",
"Tags": [
"python",
"numpy",
"database",
"pandas"
],
"Title": "First program in Python for data analysis"
}
|
235216
|
<p>I have made this BST using templates</p>
<p>Node.h</p>
<pre><code>#ifndef NODE_H_INCLUDED
#define NODE_H_INCLUDED
template<typename T>
class Node
{
public:
Node<T> *pLeft;
Node<T> *pRight;
T val;
Node<T>(T val)
{
this->val = val;
pLeft = pRight = nullptr;
}
// Node<T>(const Node<T>& src); -> to be implemented
// Node& operator=(const Node&); -> to be implemented
};
#endif // NODE_H_INCLUDED
</code></pre>
<p>Tree.h</p>
<pre><code>#ifndef TREE_H_INCLUDED
#define TREE_H_INCLUDED
#include <iostream>
#include "Node.h"
template<typename T>
class Tree
{
Node<T>* root;
Node<T>* insert_at_sub(T i, Node<T>*);
Node<T>* delete_at_sub(T i, Node<T>*);
int countNodes(Node<T> *p);
void print_sub(Node<T> *p);
Node<T>* minValue(Node<T>*);
Node<T>* maxValue(Node<T>*);
Node<T>* get_last(Node<T>*);
Node<T>* get_first(Node<T>*);
int t_size = 0;
public:
Tree ()
{
root = nullptr;
}
~Tree()
{
delete root;
}
void add(T i)
{
++t_size;
root = insert_at_sub(i, root);
}
void print()
{
print_sub(root);
};
bool contain(T i)
{
return contain_sub(i, root);
}
bool contain_sub(T i, Node<T> *p);
void destroy(T i)
{
if(contain(i))
root = delete_at_sub(i, root);
else
return;
}
void showFirst();
void showLast();
int get_size()
{
return t_size;
}
int getNumberLeftNodes()
{
return countNodes(root->pLeft);
}
int getNumberRightNodes()
{
return countNodes(root->pRight);
}
};
template<typename T>
int Tree<T>::countNodes(Node<T> *p)
{
static int nodes;
if(!p)
return 0;
if (p->pLeft)
{
++nodes;
countNodes(p->pLeft);
}
if (p->pRight)
{
++nodes;
countNodes(p->pRight);
}
return nodes + 1;
}
template<typename T>
Node<T>* Tree<T>::insert_at_sub(T i, Node<T> *p)
{
if( ! p )
return new Node<T>(i);
else if (i <= p->val)
p->pLeft = insert_at_sub(i, p->pLeft);
else if (i > p->val)
p->pRight = insert_at_sub(i, p->pRight);
return p;
}
template<typename T>
void Tree<T>::print_sub(Node<T> *p)
{
if(p)
{
print_sub(p->pLeft);
std::cout << p->val << std::endl;
print_sub(p->pRight);
}
}
template<typename T>
bool Tree<T>::contain_sub(T i, Node<T> *p)
{
if (!p)
return false;
else if(i == p->val)
return true;
else if (i <= p->val)
contain_sub(i, p->pLeft);
else
contain_sub(i, p->pRight);
}
template<typename T>
Node<T> *Tree<T>::minValue(Node<T> *p)
{
Node<T> *current = p;
while(current && current->pLeft)
current = current->pLeft;
return current;
}
template<typename T>
Node<T> *Tree<T>::maxValue(Node<T> *p)
{
Node<T> *current = p;
while(current && current->pRight)
current = current->pRight;
return current;
}
template<typename T>
void Tree<T>::showLast()
{
Node<T> *last = maxValue(root);
if(last)
std::cout << last->val;
else
std::cout << "";
}
template<typename T>
void Tree<T>::showFirst()
{
Node<T> *first = minValue(root);
if(first)
std::cout << first->val;
else
std::cout << "";
}
template<typename T>
Node<T>* Tree<T>::delete_at_sub(T i, Node<T>* p)
{
if (i < p->val)
p->pLeft = delete_at_sub(i, p->pLeft);
else if (i > p->val)
p->pRight = delete_at_sub(i, p->pRight);
else if(i == p->val)
{
if ( ! p->pLeft)
{
Node<T> *temp = p->pRight;
delete p;
return temp;
}
else if ( ! p->pRight)
{
Node<T> *temp = p->pLeft;
delete p;
return temp;
}
Node<T> *temp = minValue(p->pRight);
p->val = temp->val;
p->pRight = delete_at_sub(p->val, p->pRight);
}
return p;
}
#endif // TREE_H_INCLUDED
</code></pre>
<p>main.cpp </p>
<pre><code>#include <iostream>
#include "Tree.h"
using namespace std;
class Test
{
string name;
public:
Test () {}
Test(string name_) : name(name_) {}
friend ostream& operator<<(ostream& os, Test& t)
{
os << t.name;
return os;
}
bool operator<(Test t);
bool operator<=(Test t);
bool operator>(Test t);
};
bool Test::operator<(Test t)
{
return (name < t.name);
}
bool Test::operator<=(Test t)
{
return (name <= t.name);
}
bool Test::operator>(Test t)
{
return (name > t.name);
}
int main()
{
Tree<int> tr;
/*
4
/ \
1 6
/ \ / \
0 2 5 9
\
89
/ \
12 222
\
32
/
22
*/
tr.add(4);
tr.add(6);
tr.add(1);
tr.add(9);
tr.add(2);
tr.add(0);
tr.add(89);
tr.add(12);
tr.add(32);
tr.add(5);
tr.add(22);
tr.add(222);
// tr.test();
tr.showFirst();
cout << endl;
tr.showLast();
cout << endl;
Tree<string> bst;
bst.add("Zanildo");
bst.add("Helder");
bst.add("Wilson");
bst.add("Ady");
bst.add("Adilson");
bst.add("Patrick");
bst.showFirst();
cout << endl;
bst.showLast();
cout << endl;
Tree<Test> test;
test.add({"Jhonny"});
test.add({"Bruno"});
test.add({"Garry"});
test.add({"Henry"});
test.add({"Amber"});
test.add({"Brandy"});
test.add({"Danny"});
test.add({"Cameron"});
test.add({"Edla"});
test.add({"Zenalda"});
test.showFirst();
cout << endl;
test.showLast();
cout << endl;
//test.print();
return 0;
}
</code></pre>
<p>I put all the <code>Tree</code> class functions implementation inside the header file because didn't want to put'em in a cpp file and having to add the explicit instantiation at the end of the file like this for example:</p>
<pre><code>template class Tree<int>; // explicit instantiation
</code></pre>
<p>I also know I have to provide a <code>copy constructor</code> and an <code>assignment operator</code> for the <code>Node</code> class but I am still studying how to implement them correctly as this is my first time having the need to provide either of them. I have studied them before but while googling around came across the <code>copy-swap idiom</code> which is said to be the best approach so I have a few tabs open to study it and try to implement it. If anyone wish to give me a head start would be more than welcome.</p>
<p>An iterative BST is better for performance when the tree gets quite large but I have made the main functions for this BST <code>recursively</code> on purpose. I know how to implement those functions <code>iteratively</code> but not all of them yet.
After I want to create this BST entirely <code>iterative</code>.</p>
<p>Besides all this, what can be said about my BST with <code>template</code>?</p>
|
[] |
[
{
"body": "<h1>Make it explicit that it is a <em>binary</em> tree</h1>\n\n<p>Your class name is <code>Tree</code>, but there are many different types of trees. Make it clear that this is a binary tree, and name it <code>BinaryTree</code>.</p>\n\n<h1>Move <code>class Node</code> inside <code>class Tree</code></h1>\n\n<p>Move the declaration of <code>class Node</code> inside that of <code>class Tree</code>, in the <code>public</code> section. This makes it clear that this <code>Node</code> is specific to the tree you are implementing, and avoids a potention conflict with other classes that might have nodes.</p>\n\n<p>Consider for example that you might also have an implementation of a linked list, which also consists of nodes named <code>Node</code>. If you would want to use both your binary tree and your linked list in the same program, you would get a conflict.</p>\n\n<h1>Try to make your <code>Tree</code> look like other <code>STL</code> container classes</h1>\n\n<p>Have a look at what member functions STL containers define. The closest <code>STL</code> container to your binary tree is <a href=\"https://en.cppreference.com/w/cpp/container/set\" rel=\"nofollow noreferrer\"><code>std::set</code></a>. You don't have to add all the functionality of an STL container right away, just first consider renaming some of your member functions to match that of the STL. For example, instead of <code>add()</code> and <code>destroy()</code>, use <code>insert()</code> and <code>erase()</code>. Instead of <code>get_size()</code>, use <code>size()</code>.</p>\n\n<p>There are several benefits to this. First, for someone who is already familiar with other STL containers, it makes working with your <code>Tree</code> more intuitive. But that's not all: if you make it look enough like an STL container, then some of the <a href=\"https://en.cppreference.com/w/cpp/algorithm\" rel=\"nofollow noreferrer\">STL algorithms</a> might actually start to work on your <code>Tree</code> as well!</p>\n\n<h1>Move printing out of <code>class Tree</code></h1>\n\n<p>Instead of having a <code>print_sub()</code> function that only prints to <code>std::cout</code>, consider writing instead a function that walks the tree and takes a function as one of its argument, so that it allows the caller to decide what to do with each visited node. For example:</p>\n\n<pre><code>template<typename T>\nvoid Tree<T>::visit_subtree(const Node<T> *p, std::function<void(const T&)> func)\n{\n if (p)\n {\n visit_subtree(p->pLeft, func);\n func(p->val);\n visit_subtree(p->pRight, func);\n }\n}\n\ntemplate<typename T>\nvoid Tree<T>::visit(std::function<void(const T&)> func)\n{\n return visit_subtree(root, func);\n}\n</code></pre>\n\n<p>Then you could call it like:</p>\n\n<pre><code>Tree<Test> test;\n...\ntest.visit([](Test &val){std::cout << val << '\\n';});\n</code></pre>\n\n<p>The advantage is that you can call it with any other function you like, so if you wanted to print it to <code>std::cerr</code> instead, or if you wanted to do something completely different with each element of the tree, you don't have to change your <code>Tree</code>'s <code>visit()</code> function.</p>\n\n<p>However, another approach is:</p>\n\n<h1>Implement iterators for your <code>Tree</code></h1>\n\n<p>Try to implement an iterator class for your <code>Tree</code>, and provide <code>begin()</code> and <code>end()</code> member functions that return the appropriate iterators, to allow someone to loop over all the elements of the tree with a simple <code>for</code>-statement, like:</p>\n\n<pre><code>Tree<Test> test;\n...\nfor (const auto &val: test)\n std::cout << val << '\\n';\n</code></pre>\n\n<p>Read <a href=\"https://stackoverflow.com/questions/8054273/how-to-implement-an-stl-style-iterator-and-avoid-common-pitfalls\">this question</a> for some good references on how to implement an iterator yourself. It is a bit of work, but it makes using your class much easier. Once you have it, you also get many things for free. For example, instead of having to write your own <code>minValue()</code> function, once you have iterators you can just use <a href=\"https://en.cppreference.com/w/cpp/algorithm/min_element\" rel=\"nofollow noreferrer\"><code>std::min_element</code></a> on an instance of a <code>Tree</code> class to get the smallest element.</p>\n\n<h1>Fix the memory leak in the destructor</h1>\n\n<p>Your destructor only deletes the <code>root</code> node, not any of its children.</p>\n\n<h1>Use <code>const</code> where appropriate</h1>\n\n<p>You should make arguments, variables, return values and whole member functions <code>const</code> whereever appropriate. For example, <code>countNodes()</code> does not modify the <code>Node<T></code> that you give a pointer to as an argument, and it also doesn't change anything in <code>class Tree</code> itself. Therefore, you should declare it as:</p>\n\n<pre><code>int countNodes(const Node<T> *p) const;\n</code></pre>\n\n<p>The same goes for many other functions. Apart from catching potential errors and helping the compiler produce better optimized code, doing this will also allow these member functions to be called on <code>const</code> instances of <code>class Tree</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-07T23:09:46.500",
"Id": "460327",
"Score": "0",
"body": "**Move class Node inside class Tree** -> How `Node` inside the class `Tree` avoids a potential conflict with other classes that might have nodes?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-07T23:18:47.313",
"Id": "460328",
"Score": "0",
"body": "**Move printing out of class Tree** Unfortunately I can't seem to understand this, how exactly does it work?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-07T23:37:22.890",
"Id": "460332",
"Score": "0",
"body": "**\"_if you make it look enough like an STL container, then some of the STL algorithms might actually start to work on your Tree as well!_\"** -> Could you please clarify this statement?"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-07T19:30:15.000",
"Id": "235244",
"ParentId": "235220",
"Score": "7"
}
},
{
"body": "<ul>\n<li>There's no way to access the tree's nodes, so <code>contain_sub</code> is useless to clients.</li>\n<li>Even if it works, <code>contain_sub</code> doesn't return anything in two of its branches and looks gnarly.</li>\n<li>Use smart pointers or have a good reason not to.</li>\n<li>Don't copy items unless you're copying the tree itself; you're doing this a lot.</li>\n<li>Regarding iterators: remember that there are multiple ways to traverse a binary tree (pre/post/in/level order, and reverse).</li>\n<li>use_consistentNamingConventions (<code>getNumberLeftNodes</code> vs <code>get_size</code>).</li>\n<li>When would <code>getNumberLeftNodes</code> ever be useful to a client?</li>\n<li>Test your interface if you're going to write test code. 100% coverage is completely reasonable for a data structure.</li>\n<li><code>insert_at_sub</code> could reduce to else returning the new node instead of having two returns</li>\n<li>\"destroy\" is semantically inaccurate for C++, it should be something like \"erase\".</li>\n<li><code>destroy</code> is pretty inefficient and needs revising. Don't repeatedly traverse trees if you don't have to.</li>\n</ul>\n\n<hr>\n\n<p>At a high level, why is this binary tree useful? Why not sort a vector or a list? Does this require fewer comparisons? Fewer pointer indirections? Fewer bytes allocated? It looks very slow at a cursory glance. If it's more optimal in some way than another data structure, write a test to demonstrate that.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-07T23:01:12.133",
"Id": "460325",
"Score": "0",
"body": "First of all, thanks for your review.I have a question, how would I write test code. What is that?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-07T23:02:58.157",
"Id": "460326",
"Score": "0",
"body": "_**At a high level, why is this binary tree useful? Why not sort a vector or a list? _** Didn't understand the question"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-07T23:24:16.173",
"Id": "460329",
"Score": "0",
"body": "**When would getNumberLeftNodes ever be useful to a client?** -> It was just an exercise"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-07T23:26:19.550",
"Id": "460330",
"Score": "0",
"body": "**Don't copy items unless you're copying the tree itself, you're doing this a lot** - > Could you please point to an example in the code and provide a fix?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-07T23:57:06.527",
"Id": "460334",
"Score": "0",
"body": "`contain_sub` is not meant for client and it is not supposed to return anything. It is just a helper function that takes the `root` node as a parameter."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-07T23:58:09.477",
"Id": "460335",
"Score": "0",
"body": "Consider `void add(T i)` \nIf T is a std::string, it's going to do a string copy every time insert_at_sub is called. So say you had a tree 1000 levels deep and a string 1000 characters long -- that will copy 1million bytes. Using std::move you could reduce this to 0 string copies. \n\nConsider making a test object that prints out in its copy constructor and copy assignment operator to test how often copies are happening. Or, make a non-copyable object and get it to compile."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-08T00:09:23.150",
"Id": "460336",
"Score": "0",
"body": "If contain_sub is not meant for client, it should be private.\n\nYour container should have some directive. For example, a binary tree should do O(logn) insertion. A vector does O(n) insertion. They both have O(logn) search times. So maybe its directive would be \"build a searchable database faster than inserting into a vector\". You can use this to help guide your designs. Otherwise maybe performance doesn't matter at all. In that case, there's no reason to optimize the amount of object copies the tree does."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-08T00:12:26.530",
"Id": "460337",
"Score": "0",
"body": "regarding printing, imagine you took all the print functions out of the tree. How would you proceed to print out the tree using the remaining interface?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-08T11:30:14.433",
"Id": "460390",
"Score": "0",
"body": "`contain_sub` is misplaced, hadn't noticed that."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-08T11:32:32.033",
"Id": "460392",
"Score": "0",
"body": "So I would use `std::move` in `void add(T i)` like this: `root = std::move(insert_at_sub(i, root));`??"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-09T00:14:56.730",
"Id": "460504",
"Score": "0",
"body": "No, that is incorrect. It is difficult to teach the concept of r-value references in the comments section. Try to get your code to work with a non-copyable object type as T to help understand why this is important."
}
],
"meta_data": {
"CommentCount": "11",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-07T21:48:25.863",
"Id": "235258",
"ParentId": "235220",
"Score": "3"
}
},
{
"body": "<p>A few extra points to the current answers:</p>\n\n<ul>\n<li>Tree will create a default copy constructor which will not behave as expected.\nAs root is a raw pointer it will just do a shallow copy, assuming T is copiable (i.e. create a new pointer to the same data.)\nThis will create unexpected behaviour if you copy the Tree and then modify one of the copies.\nAs they both point to the same data both will be modified.\nYou should either disable copying of Tree and Node, e.g. <code>Tree(const Tree&) = delete;</code>\nor write a custom copy that does a full deep copy of the data. The deep copy for Node would look something like this:</li>\n</ul>\n\n<pre><code>Node<T>(const Node<T>& src)\n: val(src.val)\n {\n if(src.pLeft)\n {\n pLeft=*src.pLeft;\n }\n if(src.pRight)\n {\n pLeft=*src.pRight;\n }\n }\n</code></pre>\n\n<p>and something similar for Tree. NB I haven't done the copy-assignment here, you can either do something very similar to the copy constructor or implement a swap function and use that, see <a href=\"https://stackoverflow.com/questions/3279543/what-is-the-copy-and-swap-idiom\">https://stackoverflow.com/questions/3279543/what-is-the-copy-and-swap-idiom</a>.</p>\n\n<ul>\n<li><p>I would strongly recommend using smart pointers. This would prevent the memory leak in Node,\nand would implicitly prevent copying if you use <code>unique_ptr</code>.</p></li>\n<li><p>Your Tree allows duplicate elements, I'm not sure if this is intentional, but it has some\nnot entirely obvious behaviour. <code>add</code> will perfectly happily add multiple of the same data,\nand <code>destroy</code> will only remove the first matching element. If this is intentional it should probably\nbe documented. In most cases it is probably not necessary for a search tree to have duplicate elements.</p></li>\n<li><p>Consider adding ways to add/remove multiple elements at once. This is probably quite a common \nthing to do. The standard way would be a templated function taking a start and end iterator,\nthat you can loop though.</p></li>\n<li><p>The performance of the tree is dependant on the order elements are added. This is not necessarily\na problem, but is something to be aware of. If your tree is very unbalanced (e.g. the left nodes go a lot deeper than the right)\nsome nodes will have to do many more checks to find than others. If you are interested in this\nyou might want to look at self-balancing trees such as a red-black tree.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-08T23:44:20.700",
"Id": "460503",
"Score": "0",
"body": "Having duplicates in the Tree was intentional, didn't know that it was not necessary to for a search tree to have duplicate elements. For the `destroy` though, that behavior was unintentional. while implementing/trying to implement the fixes mentioned in reviews above I tested the class more rigorously I saw that it has many problems, e.g. if you call the `get_size` function twice the size in the second call will return almost 2x bigger without adding any element to the tree in between the two functions calls."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-10T08:34:11.903",
"Id": "460727",
"Score": "0",
"body": "Using `std::unique_ptr` in the `Node` function would be like this: `std::unique_ptr<Node<T>> pRight; std::unique_ptr<Node<T>> pLeft`? I did so but it gave errors in the `Tree` class functions."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-10T12:27:25.593",
"Id": "460744",
"Score": "0",
"body": "Yes, you will need to refactor at least delete_at_sub as it copies Node* which you cannot do with unique_ptr."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-10T22:19:56.883",
"Id": "460814",
"Score": "0",
"body": "Refactoring always breaks stuffs along the way and as no with no surprise it broke a lot of stuff and it takes too much time to fix them as I have never worked with smart pointer, I will instead study smart pointers again (this time knowing I will be working with them immediately) and rebuild the BST. Thanks for review."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-08T15:07:11.823",
"Id": "235300",
"ParentId": "235220",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "235244",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-07T13:12:13.980",
"Id": "235220",
"Score": "4",
"Tags": [
"c++",
"recursion",
"tree",
"template",
"binary-search"
],
"Title": "Binary Search Tree Using Templates in C++"
}
|
235220
|
<p>I'm trying to solve a problem from Project Euler:
The prime factors of 13195 are 5, 7, 13 and 29. What is the largest prime factor of the number 600851475143 ?
and here is my attempt:</p>
<pre><code>def getPrimeNumbers(testNumber):
'''
For a given number it returns a list of all prime numbers from 2 to given number.
>>> getPrimeNumbers(15)
[2,3,5,7,11,13]
'''
primeNumbers = [2]
temp=0
for i in range(3,testNumber):
for eachElement in primeNumbers:
if i%eachElement==0:
break
else:
temp+=1
if temp == len(primeNumbers):
primeNumbers.append(i)
temp=0
return primeNumbers
def getMaxPrimeFactor(testNumber):
'''
For a given testNumber it returns a maximum prime factor of that number. Else it returns that number is already a prime!
>>> (1) getMaxPrimeFactor(15)
5
(2) getMaxPrimeFactor(13)
A number is already a prime!
'''
helpList = []
for eachElement in getPrimeNumbers(testNumber):
if testNumber%eachElement == 0:
helpList.append(eachElement)
if len(helpList) == 0:
print("A number is already a prime!")
else:
print(max(helpList), helpList)
</code></pre>
<p>For smaller numbers it works, but it takes too much time to solve for 600851475143!</p>
<ul>
<li>Can you suggest other solutions, and explain them?</li>
<li>Given my code, what would you suggest to improve in future?</li>
<li>Why doesn't return work in <code>getMaxPrimeFactor()</code> function, but instead I had to use <code>print(max(helpList), helpList)</code>?</li>
</ul>
<p>Thanks!</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-07T13:43:33.853",
"Id": "460269",
"Score": "2",
"body": "FYI \"Can you suggest other solutions, and explain them?\" is a code request, asking for code is off-topic here as it's a slippery slope. Some members of the site may provide an alternate solution, with code. But that's out of the kindness of their hearts, not because it's something we should actively be doing."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-07T13:46:37.490",
"Id": "460270",
"Score": "2",
"body": "Additionally \"Why doesn't return work in getMaxPrimeFactor() function, but instead I had to use print(max(helpList), helpList)?\" is off-topic as you're asking why your code works. This normally is a sign of users not writing the posted code. Additionally posts asking how code work aren't really that helpful except to you. As part of the Stack Exchange network, we aim to help possible future visitors too. Take people that have completed this Project Euler and search for alternate solutions to see what they could do better."
}
] |
[
{
"body": "<p>Normally I'd suggest printing out the current time three times: at the beginning, after calling <code>getPrimeNumbers</code>, and after calling <code>getMaxPrimeFactor</code>, to see which function is taking up so much time.\nBut in this case <em>both</em> functions are very inefficient.</p>\n<p>Put more effort into designing and analyzing your algorithms, <em>before</em> you try coding them in any specific language.</p>\n<h1>getPrimeNumbers():</h1>\n<p>To generate a list of prime numbers, it isn't necessary to test every individual value in the range.\n<a href=\"https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes\" rel=\"nofollow noreferrer\">Sieve of Eratosthenes - Wikipedia</a> describes a much more efficient method.</p>\n<p>And you can make the range much shorter by realizing that if it the given number itself isn't prime, the next largest candidate will be its square root.\nE.g. if the number is 1,000,000, its largest prime factor can't be larger than 1000.\nIf the number is 600851475143, no prime factor other than itself can be larger than 800,000.</p>\n<h1>getMaxPrimeFactor:</h1>\n<p>Building a list of prime factors, printing the maximum value in the list, then discarding them all is a waste of effort.</p>\n<p>Instead of a list, simply keep track of the last prime factor found.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-07T15:09:59.553",
"Id": "460278",
"Score": "1",
"body": "While this is a good answer, I can't vote it up because the question itself is off-topic. When you see comments that indicate the question is off-topic it is best not to answer it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-07T16:32:46.110",
"Id": "460293",
"Score": "0",
"body": "@pacmaninbw, I saw your original comment, but it mentioned \"code request\" as the reason, so I didn't provide any code. I treated it instead as a question about what is wrong with the algorithm. Is critiquing algorithms off-topic here? Is there a better site for it?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-08T15:35:23.237",
"Id": "460414",
"Score": "0",
"body": "@RayButterworth I'm a bit confused... So, let's say that the given number is 10. sqrt(10) is around 3,162. That means that all prime factors of 10 lie between [2, 3,162], which implies numbers 2 and 3 since they are prime and thus possible prime factors of 10. Since, 10mod3 is not equal to 0, that means that we discard 3 but are left with 2. 10mod2 equals 0. Since we are left with number 2 only, that means that largest prime factor for 10 is 2, which is not true since 2*5=10 and 5 is also a prime factor. Right?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-08T16:28:20.837",
"Id": "460423",
"Score": "0",
"body": "@Krushe, yes, I totally blew it. I was thinking of the test-for-prime algorithm. Thanks for pointing it out. FYI, [this](https://www.geeksforgeeks.org/find-largest-prime-factor-number/) contains some optimization speedups to the algorithm."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-07T14:52:25.033",
"Id": "235230",
"ParentId": "235223",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "235230",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-07T13:26:03.383",
"Id": "235223",
"Score": "-4",
"Tags": [
"python",
"programming-challenge",
"time-limit-exceeded"
],
"Title": "Geting maximum prime factor for a given number"
}
|
235223
|
<p>I am going to have multiple APIs in routes folder should I put them in in the same file API or separate them?</p>
<pre><code>├── app.js
├── src/
│ ├── contants/
│ ├── helpers/
│ ├── models/
│ ├── routes/
| | |___index.js
|___api.js
│ └── libs/
│ ├── backbone/
│ ├── underscore/
│ └── ...
</code></pre>
<pre><code>api.js file contains all the APIs
const jwt = require("jsonwebtoken")
const axios = require("axios")
require("express-async-errors")
const bodyParser = require("body-parser")
const fs = require("fs")
const LOLTrackingSystem = require("../methods/onlineGamesTracking/LOLTracking")
const getUserData = require("../methods/leagueOfLegends/getUserData")
const isAuthenticated = require("../helpers/authenticated")
const apiRoute = (api) => {
api.use(bodyParser.json())
api.use(bodyParser.urlencoded({
extended: false
}));
api.post("/api/auth", (req, res) => {
//API Functions
})
api.post("/api/gizmo/memberProfile", isAuthenticated, (req, res) => {
//API Functions
})
api.post("/api/gizmo/memberState/:userId/:host/:state", async (req, res) => {
//API Functions
})
}
module.exports = apiRoute
</code></pre>
<p>Is what I am doing is right? </p>
<p>If it's wrong what is the right way to do it?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-12T09:56:02.027",
"Id": "464889",
"Score": "1",
"body": "Please edit your question so that the title describes the *purpose* of the code, rather than its *mechanism*. We really need to understand the motivational context to give good reviews. Thanks!"
}
] |
[
{
"body": "<p>there is no right in wrong in this situation it's a question of what's best for your particular situation if you are going to build many Rest API endpoints it's best to separate them in separate files under routes like this so your code can be more maintainable :</p>\n\n<pre><code>│ ├── routes/\n| | |___index.js\n |___auth.js\n |___gizmo.js\n - \n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-07T21:31:15.700",
"Id": "235254",
"ParentId": "235224",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "235254",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-07T13:39:20.870",
"Id": "235224",
"Score": "2",
"Tags": [
"javascript",
"node.js"
],
"Title": "NodeJS APIs folder structure"
}
|
235224
|
<p>I've wrote a calculator in Java with a GUI using swing.
Here are the classes:</p>
<p><strong>Control.java:</strong></p>
<pre class="lang-java prettyprint-override"><code>public class Control {
public static void main(String[] args) {
Calculator calculator = new Calculator();
Gui gui = new Gui(calculator);
gui.setVisible(true);
boolean exit = false;
while(!exit) {
}
}
}
</code></pre>
<p><strong>Gui.java:</strong></p>
<pre class="lang-java prettyprint-override"><code>import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Gui extends JFrame {
Calculator calculator;
public Gui(Calculator calculator) {
this.calculator = calculator;
//The frame
setSize(400, 400);
setDefaultCloseOperation(EXIT_ON_CLOSE);
//Panel for Text-output
JPanel textPanel = new JPanel();
textPanel.setPreferredSize(new Dimension(400,70));
JTextField textfield = new JTextField("");
textfield.setPreferredSize(new Dimension(380,70));
textfield.setHorizontalAlignment(JTextField.RIGHT);
textPanel.add(textfield);
add(textPanel, BorderLayout.NORTH);
//Panel for buttons
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new java.awt.GridLayout(4, 5));
buttonPanel.setPreferredSize(new Dimension(380, 280));
//Buttons
String[] buttonText = {
"7", "8", "9", "+", "<-", "4", "5", "6", "-", "(", "1", "2", "3",
"*", ")", "0", ",", "C", "/", "="
};
JButton button[] = new JButton[20];
for(int i = 0; i < 20; i++) {
button[i] = new JButton(buttonText[i]);
button[i].addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent event) {
for(int i = 0; i < 20; i++) {
if(event.getSource() == button[i]) {
//Delete last character button
if(i == 4) {
String text = textfield.getText().toString();
text = text.substring(0, text.length()-1);
textfield.setText(text);
}
//Delete all button
else if(i == 17) {
textfield.setText("");
}
//"="-button
else if(i == 19) {
String text = textfield.getText().toString();
String output = "";
try {
output = calculator.calculate(text);
}
catch (Exception ex) {
}
textfield.setText(output);
}
//other buttons
else {
String text = button[i].getText().toString();
String fieldText = textfield.getText().toString();
textfield.setText(fieldText + text);
}
}
}
}
});
buttonPanel.add(button[i]);
}
add(buttonPanel, BorderLayout.SOUTH);
}
}
</code></pre>
<p><strong>Calculator.java:</strong></p>
<pre class="lang-java prettyprint-override"><code>import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
public class Calculator {
public String calculate(String text) throws Exception {
ScriptEngineManager scriptEngineManager = new ScriptEngineManager();
ScriptEngine scriptEngine = scriptEngineManager.getEngineByName("JavaScript");
Object sol = scriptEngine.eval(text);
String solution = sol + "";
return solution;
}
}
</code></pre>
<p>What do you think about it? Do you have any suggestions on improving the code? </p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-08T13:10:10.863",
"Id": "460400",
"Score": "0",
"body": "Sorry for the delay, I have updated my answer with the model and controller parts; https://codereview.stackexchange.com/a/235277/115154"
}
] |
[
{
"body": "<h2>Control.java</h2>\n\n<p>I don't like this name as it's not specific. I'd suggest 'CalculatorApp' instead.</p>\n\n<p>You don't need the inifinite loop. The application will already continue until the user closes the program.</p>\n\n<pre><code>// you can remove all of this:\nboolean exit = false;\nwhile(!exit) {\n}\n</code></pre>\n\n<h2>Calculator.java</h2>\n\n<p>If you didn't write the program, would you know what <code>Calculator.calculate(String)</code> does? The naming is very ambiguous and the code itself looks very complicated (thankfully the heavy complicated, heavy lifting is done by an external library). You should add a javadoc to both the class & method at the very least.</p>\n\n<p>You could have done this entire assignment without JavaScript. You may have gotten more learning out of it if you didn't use ScriptEngine. To me it seems hacky. I do give you bonus points for cleverness, though.</p>\n\n<h2>Gui.java</h2>\n\n<p>You have 2 unused imports (Level & Logger)</p>\n\n<p>Avoid using wildcards (<code>.*</code>) in your imports. It clutters the local namespace and It makes it harder to tell which libraries are doing what. It will also cause a compiler error when there are two classes with the same name.</p>\n\n<pre><code>import javax.swing.*;\nimport java.awt.*;\nimport java.awt.event.*;\n</code></pre>\n\n<p>If you're using an IDE you should see a warning about your class not having a <code>serialversionUID</code>. You can allow your IDE to auto-generate one for you:</p>\n\n<pre><code>private static final long serialVersionUID = 1L;\n</code></pre>\n\n<p><strong>Avoid magic numbers & magic strings</strong> Your class would be easier to maintain & read if you used static variables declared at the top. E.G:</p>\n\n<pre><code>private static final int WIDTH = 400;\nprivate static final int HEIGHT = 400;\n...\n//The frame\nsetSize(WIDTH, HEIGHT);\n</code></pre>\n\n<p>No need to count the number of values in an array yourself, instead use <code>array.length</code>. This will make maintenance easier as you don't have to re-count the values every time:</p>\n\n<pre><code>JButton button[] = new JButton[buttonText.length];\nfor(int i = 0; i < buttonText.length; i++) {\n</code></pre>\n\n<p>Alternatively use a 'for-each' loop since you don't need the index.</p>\n\n<p>'17' should definitely be a variable here, as it's currently unreadable. Same goes for your other magic strings/variables:</p>\n\n<pre><code>else if(i == 17) {\n</code></pre>\n\n<p>This is probably one of, if not the worst thing you can possibly do. You may not think it matters now but trust me, this is a really bad habit and the best way to use good practices is to never learn the bad ones. Please use a throws declaration if you don't want to handle errors:</p>\n\n<pre><code>catch (Exception ex) {\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-07T20:12:09.017",
"Id": "460319",
"Score": "2",
"body": "In addition to this good review, Swing is not thread safe. The method body inside `Control` should all be done on the Event Dispatch Thread. (I.e., inside a call to `SwingUtils.invokeLater()`)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-07T19:00:35.847",
"Id": "235243",
"ParentId": "235227",
"Score": "3"
}
},
{
"body": "<p>First of all, you should read a bit on how to start a Swing application. You must take care of the <em>Event Dispatcher Thread</em> when starting your application. And, because of the way AWT manage threads, you don't need this infinite loop that will just take resources for nothing. The main thread will stay active until your frame is closed[1].</p>\n\n<h2>View</h2>\n\n<p>For the GUI, it is always a good idea to extract your components. You can create other classes, inner classes or <em>factory methods</em> to distinct your <code>TextPanel</code>, <code>ButtonsPanel</code> and the frame itself. Keep in mind the <em>single responsibility principle</em>.</p>\n\n<pre><code>Gui(Calculator calculator) {\n this.calculator = calculator;\n setSize(400, 400);\n setDefaultCloseOperation(EXIT_ON_CLOSE);\n\n add(text = new TextPanel(), BorderLayout.NORTH);\n add(buttons = new ButtonsPanel(text), BorderLayout.SOUTH);\n}\n</code></pre>\n\n<p>The <code>ButtonsPanel</code> is the most complex part of your view. The buttons loop and the event handling should be improved. Let's start with the deepest <code>for</code>. Did you know that you can set one <code>actionCommand</code> on a <code>JButton</code> this will be useful to assign one value to one button and drop the loop inside the event handling.</p>\n\n<p>But there is better, you can create your own action or button to clearly expose this aspect. To improve your code readability you can also introduce some constants for the special buttons. By doing that you remove the comparison on array indexes and have a code that start to be <em>auto documented</em> </p>\n\n<pre><code>ButtonsPanel(final TextPanel screen, final Calculator calculator) {\n super(new java.awt.GridLayout(4, 5));\n setPreferredSize(new Dimension(380, 280));\n\n for (int i = 0; i < buttonText.length; i++) {\n add(new ActionButton(buttonText[i]));\n }\n}\n\nprivate void onButtonPressed(String symbol) {\n if (ERASE.equals(symbol)) {\n String text = screen.getText();\n text = text.substring(0, text.length() - 1);\n screen.setText(text);\n } else if (CLEAR.equals(symbol)) {\n screen.setText(\"\");\n } else if (EQUAL.equals(symbol)) {\n String text = screen.getText();\n String output = \"\";\n try {\n output = calculator.calculate(text);\n } catch (Exception ex) {\n }\n screen.setText(output);\n } else {\n String fieldText = screen.getText();\n screen.setText(fieldText + symbol);\n }\n}\n</code></pre>\n\n<p>At this time you can notice that most of your logic is into this <code>ButtonsPanel</code>. This is not a good thing because testing it is not easy and this class mixes presentation and logic.</p>\n\n<p>The de-facto pattern for Swing is MVC, you have already noticed that all existing components are using <em>listeners</em>. And you can do the same. Create one listener that will be used by your <code>Gui</code> to be notified when one button is pressed. In the meantime, if you are using Java 9 or bigger, you can use a <code>switch</code> expression to replace your ifs.</p>\n\n<pre><code>public Gui(final Calculator calculator) {\n this.calculator = calculator;\n setSize(400, 400);\n setDefaultCloseOperation(EXIT_ON_CLOSE);\n add(display = new TextPanel(), BorderLayout.NORTH);\n add(buttons = new ButtonsPanel(display, calculator), BorderLayout.SOUTH);\n buttons.addListener(symbol -> {\n StringBuilder equation = new StringBuilder(display.getText());\n switch (symbol) {\n case ButtonsPanel.ERASE:\n equation.deleteCharAt(equation.length()-1);\n break;\n case ButtonsPanel.CLEAR:\n equation.delete(0, equation.length());\n break;\n case ButtonsPanel.EQUAL:\n String output = \"\";\n try {\n output = calculator.calculate(equation.toString());\n } catch (Exception ex) {\n // FIXME\n }\n equation.replace(0, equation.length(), output);\n break;\n default:\n equation.append(symbol);\n }\n display.setText(equation.toString());\n });\n}\n</code></pre>\n\n<p>While this is still better, in my opinion, you are still exposing too much details onf your <code>ButtonsPanel</code> (what if you want to use icons instead of String). The <code>ButtonsListener</code> should have dedicated method for the special symbols.</p>\n\n<pre><code>interface ButtonsPanelListener extends EventListener {\n void onInput(String text);\n\n void onClearScreen();\n\n void onEraseOne();\n\n void onEqual();\n}\n</code></pre>\n\n<p>By doing that you will move the interpretation of the symbols back to the <code>ButtonsPanel</code>. Another improvement that you can do is create a class for all your buttons with a callback to trigger the correct method on the listener. By doing that the behavior is attached to the button and the reader will not have to scroll into the sources to find how each button behave. </p>\n\n<pre><code>interface Key {\n String getText();\n void onPressed(ButtonsPanelListener listener);\n}\n</code></pre>\n\n<p>This will clean the \"view\" part. But, as already said, Swing is an MVC framework. So you are still missing the <em>\"m</em>\" and <em>\"c\"</em> parts... </p>\n\n<h2>Model</h2>\n\n<p>The model must be where your \"state\" is stored. Ideally this is the only class where you set and get the text. Let's create an <code>Equation</code> class for it and add all the required method on it (append, clear, dropLast, ..)</p>\n\n<p>So the <code>Gui</code> change this model when he receive an event from his <code>ButtonsPanel</code>. And you ends-up a line that is duplicate for each kind of event:</p>\n\n<pre><code>display.setText(equation.getText());\n</code></pre>\n\n<p>In Swing, the model is usually observable, so you can also add some listeners to react when he change. With this observable model your <code>Gui</code> will receive events form the buttons and update the model. When updated, the model will notify the text (via the event listener) and the text will change. </p>\n\n<pre><code> +---------------+ +-----+ +-----------+ +-----------+ \n | ButtonsPanel | | Gui | | Equation | | TextPanel | \n +---------------+ +-----+ +-----------+ +-----------+ \n | | | | \n | onInput | | | \n |------------>| | | \n | | | | \n | | append | | \n | |------------->| | \n | | | | \n | | | onChange | \n | | |--------------->| \n | | | | \n | | | | setText \n | | | |-------- \n | | | | | \n | | | |<------- \n | | | | \n</code></pre>\n\n<p>You can notice that from one side, there is ane actor between the event and the model (the <code>Gui</code> between <code>ButtonsPanel</code> and <code>Equation</code>), while on the other side there is no actor between the model and one view (<code>Equation</code> to <code>TextPanel</code>). This incoherence lead us to a little architectural discussion.</p>\n\n<p>It is up to you to decide who will listen and react to an event. But, in my case, I rely on the <em>smart and dumb containers</em> pattern. Where I have one smart component, the <code>Gui</code> and the two dumbs, <code>ButtonsPanel</code> and <code>TextPanel</code>. So that the Gui is a kind of mediator between the model and the views. </p>\n\n<pre><code> +-----------+ +-----+ +---------------+ +-----------+\n | Equation | | Gui | | ButtonsPanel | | TextPanel |\n +-----------+ +-----+ +---------------+ +-----------+\n | | | |\n | | onInput | |\n | |<-----------------| |\n | | | |\n | append | | |\n |<------------| | |\n | | | |\n | onChange | | |\n |------------>| | |\n | | | |\n | | setText | |\n | |--------------------------------->|\n | | | |\n</code></pre>\n\n<p>In fact the <code>Gui</code> has too much responsibility, because it play both the role of a view (a smart container) and the role of a controller.</p>\n\n<h2>Controller</h2>\n\n<p>Let's segregate the roles of the <code>Gui</code> is role will be to deal with the presentation and redirect events to a controller. On the other side the controller will update the model according to the received actions. </p>\n\n<p>In some systems the controller implements all the required listeners. This is sometime not the best one for code reuse because the controller depends on Swing. Also it require to expose the listeners of all of your components or create adapters between the listeners for the dumb components and those of the smart components. But it is useful to reduce the number of delegation or decoration methods. The biggest advantage is that it force you to create one model that represent the state of your application (or part of it) so that any change can be observed by the view.</p>\n\n<h2>Finally</h2>\n\n<p>A this time you should have a clean MVC. The advantages of this pattern is that you can easily test the model and the controller who are usually the most critical parts in an MVC. You can also extract your core business (representation and execution of an equation) to reusable and testable classes and build your model (and sometimes controller) over them by applying the <em>decorator</em> and <em>adapter</em> patterns.</p>\n\n<p>Please note that there are other popular pattern to build one application, <em>Model View Presenter</em> is one of them.</p>\n\n<pre><code> +-------+ +-------+ +---------------+ +-----------+ +-------------+\n | Model | | View | | ButtonsPanel | | TextPanel | | Controller |\n +-------+ +-------+ +---------------+ +-----------+ +-------------+\n | | | | |\n | | onButtonPressed | | |\n | |<-------------------------| | |\n | | | | |\n | | // call method for the pressed button | |\n | |-------------------------------------------------------->|\n | | | | |\n | | | // call mutation method |\n |<------------------------------------------------------------------------|\n | | | | |\n | onChange | | | |\n |-------------->| | | |\n | | | | |\n | | setText | | |\n | |----------------------------------------->| |\n | | | | |\n</code></pre>\n\nModel\n\n<pre><code>class Model {\n\n private final EventListenerList listeners = new EventListenerList();\n private final StringBuilder content;\n\n public Model() {\n this.content = new StringBuilder();\n }\n\n public void setResult(String result) {\n fireOnResult(result);\n }\n\n public void append(String part) {\n content.append(part);\n fireOnChange();\n }\n\n public void clear() {\n content.delete(0, content.length());\n fireOnChange();\n }\n\n public void dropLast() {\n content.deleteCharAt(content.length());\n fireOnChange();\n }\n\n public String getText() {\n return content.toString();\n }\n\n public void addListener(ModelListener listener) {\n listeners.add(ModelListener.class, listener);\n }\n\n public void removeListener(ModelListener listener) {\n listeners.remove(ModelListener.class, listener);\n }\n\n private void fireOnChange() {\n ModelListener[] lstnrs = listeners.getListeners(ModelListener.class);\n for (int i=lstnrs.length-1; i > -1; i--) {\n lstnrs[i].onEquationChange(content.toString());\n }\n }\n\n private void fireOnResult(String result) {\n ModelListener[] lstnrs = listeners.getListeners(ModelListener.class);\n for (int i=lstnrs.length-1; i > -1; i--) {\n lstnrs[i].onResult(result);\n }\n }\n\n}\n</code></pre>\n\nView\n\n<pre><code>class View extends JFrame {\n private final Controller controller;\n private final ButtonsPanel buttons;\n private final TextPanel display;\n\n public View(final Controller controller) {\n this.controller = controller;\n setSize(400, 400);\n setDefaultCloseOperation(EXIT_ON_CLOSE);\n\n add(display = new TextPanel(), BorderLayout.NORTH);\n add(buttons = new ButtonsPanel(), BorderLayout.SOUTH);\n\n buttons.addListener(new ButtonsListener());\n controller.addModelListener(new TextUpdater());\n }\n\n private final class TextUpdater implements ModelListener {\n private void updateText(String newText) {\n SwingUtilities.invokeLater(() -> display.setText(newText));\n }\n\n @Override\n public void onEquationChange(String equation) {\n updateText(equation);\n }\n\n @Override\n public void onResult(String result) {\n updateText(result);\n }\n }\n\n private final class ButtonsListener implements ButtonsPanel.ButtonsPanelListener {\n @Override\n public void onButtonPressed(String text) {\n new SwingWorker<Void, Void>(){\n @Override\n protected Void doInBackground() throws Exception {\n switch (text) {\n case ButtonsPanel.CLEAR:\n controller.clear();\n break;\n case ButtonsPanel.ERASE:\n controller.eraseOne();\n break;\n case ButtonsPanel.EQUAL:\n controller.compute();\n break;\n default:\n controller.onInput(text);\n }\n return null;\n }\n }.execute();\n }\n }\n\n}\n</code></pre>\n\nController\n\n<pre><code>class Controller {\n\n private final Engine engine;\n private final Model model;\n\n public Controller(Engine engine) {\n this.engine = engine;\n this.model = new Model();\n }\n\n public void compute() throws Exception {\n String result = engine.compute(model.getText());\n model.setResult(result);\n }\n\n public void onInput(String text) {\n model.append(text);\n }\n\n\n public void clear() {\n model.clear();\n }\n\n\n public void eraseOne() {\n model.dropLast();\n }\n\n\n public void addModelListener(ModelListener listener) {\n model.addListener(listener);\n }\n\n public void removeModelListener(ModelListener listener) {\n model.removeListener(listener);\n }\n\n} \n</code></pre>\n\n<hr>\n\n<p>[1] : <a href=\"https://docs.oracle.com/javase/7/docs/api/java/awt/doc-files/AWTThreadIssues.html\" rel=\"nofollow noreferrer\">https://docs.oracle.com/javase/7/docs/api/java/awt/doc-files/AWTThreadIssues.html</a></p>\n\n<p>The sequence diagrams were made with <em>TextArt.io</em> : <a href=\"https://textart.io/sequence\" rel=\"nofollow noreferrer\">https://textart.io/sequence</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-08T07:45:06.803",
"Id": "235277",
"ParentId": "235227",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "235277",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-07T13:52:33.237",
"Id": "235227",
"Score": "1",
"Tags": [
"java",
"calculator",
"swing"
],
"Title": "Java Calculator with GUI"
}
|
235227
|
<p>I have a VSTO Excel Add-In which is used to retrieve data from another application and insert it into an Excel worksheet. Due to the potential for lots of pieces of data to be inserted into a spreadsheet, performance is a concern. Potentially thousands of rows could be inserted. </p>
<p>Here is the method which inserts data into an Excel spreadsheet.</p>
<p>Note: Using <code>Microsoft.Office.Interop.Excel</code></p>
<pre><code>private Worksheet Worksheet { get { return Globals.ThisAddIn.Application.ActiveSheet; } }
private Range Cells { get { return Globals.ThisAddIn.Application.ActiveSheet.Cells; } }
private void PopulateCurrentWorksheet(ReportData data, int columnIndex, int rowIndex)
{
if (data == null)
throw new ArgumentNullException("No valid ReportData available");
// NOTE: Excel uses indexing that starts at 1
if (columnIndex == 0)
columnIndex = 1;
if (rowIndex == 0)
rowIndex = 1;
int startingRowIndex = rowIndex;
foreach (ReportColumn column in data.Columns)
{
Cells[columnIndex][rowIndex].Value = column.ColumnName;
Cells[columnIndex][rowIndex].Font.Bold = true; // put the header in bold
for (int i = 0; i < column.ColumnData.Length; i++)
{
rowIndex++; // move down a cell to the next row
Cells[columnIndex][rowIndex] = column.ColumnData.ElementAt(i);
}
rowIndex = startingRowIndex;
columnIndex++; // move right a cell to the next column
}
Worksheet.Columns.AutoFit();
}
</code></pre>
<p>Below is the <code>ReportData</code> class (and associated <code>ReportColumn</code> class) which holds data retrieved from an external application to be inserted into a worksheet</p>
<pre><code>public class ReportData
{
public ReportData(IEnumerable<ReportColumn> columns)
{
Columns = columns ?? throw new ArgumentNullException("No valid columns available");
}
public IEnumerable<ReportColumn> Columns { get; set; }
}
public class ReportColumn
{
public ReportColumn(string columnName, object[] columnData)
{
ColumnName = columnName;
ColumnData = columnData;
}
public string ColumnName { get; set; }
public object[] ColumnData { get; set; }
}
</code></pre>
<p>When trying to insert data into a worksheet which results in over 100k rows, there is a significant performance hit. Is there anyway I could improve the code to make it faster? Any other advice is welcomed too. </p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-07T16:13:49.920",
"Id": "460287",
"Score": "2",
"body": "Try assigning Range.Value of the top-left target cell on the target sheet, to a 2D array that contains your values. That's 1 worksheet write operation instead of 100K x NumberOfColumns. Basically `ReportData` wants a `ToArray()` method."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-07T16:21:11.247",
"Id": "460289",
"Score": "1",
"body": "Also, how exactly are `Cells` and `Worksheet` defined? Seeing the rest of the code would be beneficial, too: why is the method working off whatever sheet happens to be active rather than from a specific worksheet?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-08T09:00:46.357",
"Id": "460381",
"Score": "0",
"body": "@MathieuGuindon Have included how Cells and Worksheets are defined. The method is working off the active sheet because there is no use case for the Add-In where we would want a non-active worksheet to be written to."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-08T11:00:46.910",
"Id": "460388",
"Score": "1",
"body": "@MathieuGuindon I have just tried your suggestion of only doing one worksheet write operation, and it is drastically improved. Thanks!"
}
] |
[
{
"body": "<blockquote>\n<pre><code>public class ReportData\n{\n public ReportData(IEnumerable<ReportColumn> columns)\n {\n Columns = columns ?? throw new ArgumentNullException(\"No valid columns available\");\n }\n\n public IEnumerable<ReportColumn> Columns { get; set; }\n}\n</code></pre>\n</blockquote>\n\n<p>The <code>Columns</code> property should be <code>get</code>-only.</p>\n\n<blockquote>\n<pre><code>public string ColumnName { get; set; } \npublic object[] ColumnData { get; set; }\n</code></pre>\n</blockquote>\n\n<p>Same with these two: it makes no sense to set them in the constructor, even throw an exception if it's <code>null</code>, if you can legally construct the object and then merrily do this:</p>\n\n<pre><code>var data = new ReportData(Enumerable.Empty<ReportColumn>()) { Columns = null };\n</code></pre>\n\n<p>Note that <code>IEnumerable<T></code> things should indeed never be <code>null</code>, but any <code>IEnumerable<T></code> can still be empty without being <code>null</code>. As such, the guard clause is insufficient, since it appears to be there to protect against creating a <code>new ReportData</code> that wouldn't have any columns - <code>Enumerable.Empty<T>()</code> is a perfectly valid input that should be guarded against.</p>\n\n<pre><code>public class ReportData\n{\n public reportData(IEnumerable<ReportColumn> columns)\n {\n var reportColumns = columns ?? throw new ArgumentNullException(...);\n if (!reportColumns.Any())\n {\n throw new ArgumentException(...);\n }\n\n Columns = reportColumns;\n }\n\n public IEnumerable<ReportColumns> Columns { get; }\n}\n</code></pre>\n\n<p>Now there's no way a <code>ReportData</code> object can have 0 columns, be it during or after construction.</p>\n\n<p>These two could be expression-bodied auto-properties:</p>\n\n<blockquote>\n<pre><code>private Worksheet Worksheet { get { return Globals.ThisAddIn.Application.ActiveSheet; } }\nprivate Range Cells { get { return Globals.ThisAddIn.Application.ActiveSheet.Cells; } }\n</code></pre>\n</blockquote>\n\n<p>Like this:</p>\n\n<pre><code>private Worksheet Worksheet => Globals.ThisAddIn.Application.ActiveSheet;\nprivate Range Cells => Globals.ThisAddIn.Application.ActiveSheet.Cells;\n</code></pre>\n\n<p>This is a serious problem:</p>\n\n<blockquote>\n<pre><code>// NOTE: Excel uses indexing that starts at 1\nif (columnIndex == 0)\n columnIndex = 1;\n\nif (rowIndex == 0)\n rowIndex = 1;\n</code></pre>\n</blockquote>\n\n<p>Consider consistently using <code>{ }</code> braces to avoid such implicit scopes.</p>\n\n<p>If the <code>columnIndex</code> or <code>rowIndex</code> supplied was <code>0</code>, then the calling code is off-by-one and this silent one-upping is literally <em>hiding</em> that bug, and there's a very very very high chance that the next call is going to pass a <code>1</code> that you're not going to offset, which will produce <em>a</em> result, but very unlikely the <em>expected</em> result.</p>\n\n<p>Consider:</p>\n\n<ul>\n<li>Throwing an <code>ArgumentOutOfRangeException</code> given <code>0</code> for column or row index.</li>\n<li>Adding XML docs to document that the index parameters are 1-based - OR document them as 0-based, and abstract away the fact that Excel's object model is 1-based by offsetting every provided value, not just <code>0</code>. In any case, you need XML docs to say this.</li>\n</ul>\n\n<hr>\n\n<p>My experience with VSTO is that if you don't properly release <strong><em>all</em></strong> the COM objects you ever access, then when your program exits you'll be left with a ghost EXCEL.EXE process in Task Manager, because .NET will be holding on to RCW objects wrapping COM/unmanaged objects that won't be garbage-collected like managed objects would be.</p>\n\n<p>Hence, avoid double-dots like this:</p>\n\n<pre><code>Globals.ThisAddIn.Application.ActiveSheet\n</code></pre>\n\n<p>That's essentially leaking <code>ThisAddIn</code>, <code>Application</code>, and <code>ActiveSheet</code> objects.</p>\n\n<p>Every single access to <code>Cells</code> is re-dereferencing the same <code>ActiveSheet</code> over and over and over, every time. That makes a lot of redundant member access.</p>\n\n<pre><code>var addin = Globals.ThisAddIn;\nvar application = addin.Application;\nvar activeSheet = application.ActiveSheet;\n\nvar allCells = activeSheet.Cells;\nvar cell = allCells[columnIndex][rowIndex];\ncell.Value = column.ColumnName;\n\nvar cellFont = cell.Font;\ncellFont.Bold = true;\n</code></pre>\n\n<p>...and then each of these objects need to be released... in the reverse order they were accessed:</p>\n\n<pre><code>Marshal.ReleaseCOMObject(cellFont);\nMarshal.ReleaseCOMObject(cell);\nMarshal.ReleaseCOMObject(allCells);\n...\n</code></pre>\n\n<p>Miss one single COM object, and the EXCEL.EXE process won't be able to shut down correctly.</p>\n\n<p>That makes it a pretty good reason to avoid writing to individual cells, ...regardless of the performance hit ;-)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-13T00:22:26.920",
"Id": "235534",
"ParentId": "235233",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-07T15:25:13.457",
"Id": "235233",
"Score": "2",
"Tags": [
"c#",
"excel"
],
"Title": "Inserting large amounts data into Excel spreadsheet"
}
|
235233
|
<p>I am an absolute newcomer in R. For my bachelor thesis I worked with spatial data. I did many plots with the normal "points"-function. I already have my results, but would like to improve my code. </p>
<p>This is the first example: (leg and colours were defined previously. <code>WLPoi</code> is a <code>SpatialPointsDataFrame</code>, <code>german_reich_polyline_new</code> is a <code>SpatialLinesDataFrame</code> and <code>GEPolnew</code> is a <code>SpatialPolygonDataFrame</code>. All of them have the same projection.)</p>
<pre><code>SelNegativbelege <- (WLPoi$lfp_bra < 1) & (WLPoi$lfp_ack_se < 1) & (WLPoi$lfp_ack_na < 1) & (WLPoi$lfp_bau < 1) & (WLPoi$lfp_fel < 1) & (WLPoi$lfp_pfl_zu < 1) & (WLPoi$lfp_zu_na < 1) & (WLPoi$lfp_grab < 1) & (WLPoi$lfp_hack < 1) & (WLPoi$lfp_pfl_na < 1) & (WLPoi$lfp_pfl < 1)
SelHack <- (WLPoi$lfp_hack > 0)
SelGrab <- (WLPoi$lfp_grab > 0)
...
plot(GEPolnew, fill= NA)
points(WLPoi[SelNegativbelege,], col=colormint, cex=.3, pch=16)
points(WLPoi[SelHack,], col=colorolive, pch=16, cex=1)
points(WLPoi[SelGrab,], col=colorgold, pch=16, cex=1) …
lines(german_reich_polyline_new, lwd=2) legend("bottomright", leg, cex=0.55, bty="n",pch=19, col=c(colormint,colormaroon, colorolive, colorgold, colorred, c7, colortomato))
</code></pre>
<p>Maybe someone has also an advice how I can shorten:</p>
<pre><code>EUnew_merge$lfp_bra100 <- ((EUnew_merge$lfp_bra)*100)
EUnew_merge$lfp_ack_se100 <- ((EUnew_merge$lfp_ack_se)*100)
EUnew_merge$lfp_ack_na100 <- ((EUnew_merge$lfp_ack_na)*100)
EUnew_merge$lfp_bau100 <- ((EUnew_merge$lfp_bau)*100)
EUnew_merge$lfp_fel100 <- ((EUnew_merge$lfp_fel)*100)
EUnew_merge$lfp_pfl_zu100 <- ((EUnew_merge$lfp_pfl_zu)*100)
EUnew_merge$lfp_zu_na100 <- ((EUnew_merge$lfp_zu_na)*100)
EUnew_merge$lfp_grab100 <- ((EUnew_merge$lfp_grab)*100)
EUnew_merge$lfp_hack100 <- ((EUnew_merge$lfp_hack)*100)
EUnew_merge$lfp_pfl_na100 <- ((EUnew_merge$lfp_pfl_na)*100)
EUnew_merge$lfp_pfl100 <- ((EUnew_merge$lfp_pfl)*100)
EUnew_merge$Pflug100 <- ((EUnew_merge$Pflug)*100)
</code></pre>
<p>Or</p>
<pre><code>selac0 <- (GEPolnew_merge$PFLUGNF4AC == 0)
selac1 <- (GEPolnew_merge$PFLUGNF4AC > 0)
selac2 <- (GEPolnew_merge$PFLUGNF4AC > 0.02)
selac3 <- (GEPolnew_merge$PFLUGNF4AC > 0.05)
selac4 <- (GEPolnew_merge$PFLUGNF4AC > 0.1)
selac5 <- (GEPolnew_merge$PFLUGNF4AC > 0.2)
selac6 <- (GEPolnew_merge$PFLUGNF4AC > 0.5)
selac7 <- (GEPolnew_merge$PFLUGNF4AC > 0.8)
selac8 <- (GEPolnew_merge$PFLUGNF4AC == 1)
</code></pre>
<p>or</p>
<pre><code>plot(GEPolnew_merge, fill=NA) plot(GEPolnew_merge[selac0,], col=c1, add= TRUE) plot(GEPolnew_merge[selac1,], col=c2, add= TRUE)
plot(GEPolnew_merge[selac2,], col=c3, add= TRUE)
plot(GEPolnew_merge[selac3,], col=c4, add= TRUE)
plot(GEPolnew_merge[selac4,], col=c5, add= TRUE)
plot(GEPolnew_merge[selac5,], col=c6, add= TRUE)
plot(GEPolnew_merge[selac6,], col=c7, add= TRUE)
plot(GEPolnew_merge[selac7,], col=c8, add= TRUE)
plot(GEPolnew_merge[selac8,], col=c9, add= TRUE)
lines(german_reich_polyline_new, lwd=3)
legend("bottomright", legc3, cex=1.15, bty="n",pch=c(1,19,19,19,19,19,19,19,19,19), col=c(rgb(0,0,0),c1,c2,c3,c4,c5,c6,c7,c8,c9))
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-08T13:37:02.740",
"Id": "460401",
"Score": "0",
"body": "Cross-posted: https://codereview.stackexchange.com/q/235264"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-07T16:14:57.913",
"Id": "235236",
"Score": "1",
"Tags": [
"r",
"data-visualization",
"geospatial"
],
"Title": "code plots - spatial data"
}
|
235236
|
<p>I have created a visualisation of sorting algorithms using tkinter and matplotlib. Please let me know what you think and if you have any suggestions or find errors.
The aim of this code is to create a GUI in which the user can enter a length for a random array of number, then select a sorting algorithm from a button, which brings up an animated plot of the sorting algorithm being used on the random array. The plot uses bar heights to represent the numbers in the array.
The project can be found with the algorithms separated for ease of reading at:
<a href="https://github.com/MGedney1/Sorting_Algorithm_Visualisation" rel="nofollow noreferrer">https://github.com/MGedney1/Sorting_Algorithm_Visualisation</a></p>
<p>Code:</p>
<pre class="lang-py prettyprint-override"><code>
import random
import time
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from matplotlib.figure import Figure
from matplotlib import style
style.use('ggplot')
from tkinter import Tk,Label,Entry,Button
def bubble_sort(lst): #Bubble Sort
index = len(lst) - 1
while index >= 0:
test_index = index
while test_index >= 0:
if lst[index] < lst[test_index]:
temp = lst[index]
lst[index] = lst[test_index]
lst[test_index] = temp
test_index -= 1
yield lst
index -= 1
def merge_sort(lst, start, end): #Merge sort
if end <= start:
return
mid = start + ((end - start + 1) // 2) - 1 #Finding mid point for split
yield from merge_sort(lst, start, mid) #Further splitting first half
yield from merge_sort(lst, mid + 1, end) #Further splitting second half
yield from merge(lst, start, mid, end) #Merging
yield lst
def merge(lst, start, mid, end):
result = []
leftIdx = start
rightIdx = mid + 1
while leftIdx <= mid and rightIdx <= end: #checking if next index of first or second list is larger and appending to the result list
if lst[leftIdx] < lst[rightIdx]:
result.append(lst[leftIdx])
leftIdx += 1
else:
result.append(lst[rightIdx])
rightIdx += 1
while leftIdx <= mid: #If only first list filled then appending that to result
result.append(lst[leftIdx])
leftIdx += 1
while rightIdx <= end: #Vice versa for the second list
result.append(lst[rightIdx])
rightIdx += 1
for i, sorted_val in enumerate(result): #Copying values and order to the origional array
lst[start + i] = sorted_val
yield lst
def insertion_sort(lst):
for i in range(1,len(lst)):
j = i-1 #Starting comparison to just the first element of the list
next_element = lst[i] #Iterating through the test values from start (indexed 1 intially) to insert
while (lst[j] > next_element) and (j >= 0): #iterating through each element already ordered to find position of test value
lst[j+1] = lst[j]
j -= 1
lst[j+1] = next_element
yield lst
def shell_sort(lst):
split_point = len(lst) // 2 #Initially splitting the list in half
while split_point > 0:
for i in range(split_point, len(lst)):
temp = lst[i]
j = i
while j >= split_point and lst[j - split_point] > temp: #Sorting the subsection of the list
lst[j] = lst[j - split_point]
j = j - split_point
lst[j] = temp
split_point = split_point // 2 #splitting the unordered part of the list in half
yield lst
def create_array(n):
unordered = [i + 1 for i in range(n)] #Creating a list of subsequent values
random.seed(time.time())
random.shuffle(unordered) #Shuffling the list
return unordered
def update_fig(unordered, rects, iteration,text): #Update fig function
for rect, val in zip(rects, unordered): #Setting height of the rectangles
rect.set_height(val)
iteration[0] += 1
text.set_text("# of operations: {}".format(iteration[0]))
def create_animation(generator,unordered,n):
title = 'Sorting Animation'
fig, ax = plt.subplots() #Creating axis and figure
ax.set_title(title) #Adding a title
bar_rects = ax.bar(range(len(unordered)), unordered, align="edge") #Creating the rectangular bars
ax.set_xlim(0, n) #Axis limits
ax.set_ylim(0, int(1.07 * n))
text = ax.text(0.02, 0.95, "", transform=ax.transAxes) #Number of operations counter
iteration = [0]
if generator != merge_sort:
anim = animation.FuncAnimation(fig, func=update_fig, #Creating the animation
fargs=(bar_rects, iteration,text), frames=generator(unordered), interval=1,
repeat=False)
else:
anim = animation.FuncAnimation(fig, func=update_fig, #Creating the animation for merge sort
fargs=(bar_rects, iteration,text), frames=generator(unordered,0,n-1), interval=1,
repeat=False)
plt.show() #Showing the plot
class GUI:
def __init__(self,master):
self.master = master
master.title('Sorting Algorithm Visualisation')
self.instruct = Label(master, text="Please enter a length for the array to sort: ")
self.instruct.grid(row = 1, column = 1,columnspan=2,ipadx=50)
self.length = Entry(master)
self.length.grid(row=1,column=3,padx=5,pady=5,columnspan=2,ipadx=50)
self.close_button = Button(master, text="Close", command=master.quit)
self.close_button.grid(row=1,column=6,padx=5,pady=5)
self.bubble_sort = Button(master, text="Bubble Sort",command=self.bubble_s)
self.bubble_sort.grid(row=2,column=1,padx=5,pady=5)
self.merge_sort = Button(master, text="Merge Sort",command=self.merge_s)
self.merge_sort.grid(row=2,column=2,padx=5,pady=5)
self.insertion_sort = Button(master, text="Insertion Sort",command=self.insertion_s)
self.insertion_sort.grid(row=2,column=3,padx=5,pady=5)
self.shell_sort = Button(master, text="Shell Sort",command=self.shell_s)
self.shell_sort.grid(row=2,column=4,padx=5,pady=5)
def get_length(self):
self.n = int(self.length.get())
def bubble_s(self):
self.animate(bubble_sort)
def merge_s(self):
self.animate(merge_sort)
def insertion_s(self):
self.animate(insertion_sort)
def shell_s(self):
self.animate(shell_sort)
def animate(self,generator):
self.get_length()
unordered = create_array(self.n)
create_animation(generator,unordered,self.n)
if __name__ == '__main__':
root = Tk()
gui = GUI(root)
root.mainloop()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-07T20:03:24.190",
"Id": "460318",
"Score": "1",
"body": "Add some information what that code is actually intended to do please."
}
] |
[
{
"body": "<p>I'll just review <code>bubble_sort</code> as an example. My quick notes:</p>\n\n<ol>\n<li>Add a useful docstring and/or types (I had to read the entire function to realize that it was a generator)</li>\n<li>When iterating over a range, use <code>for in range</code> rather than <code>while</code>. I also prefer using brief, generic variable names like <code>i</code> and <code>j</code> in lieu of names like <code>index</code> and <code>test_index</code> that are longer without being any more descriptive.</li>\n<li>You can swap two elements with a tuple assignment.</li>\n</ol>\n\n<pre><code>from typing import Generator, List, TypeVar\n\n_Elem = TypeVar('_Elem')\n\ndef bubble_sort(elems: List[_Elem]) -> Generator[List[_Elem]]:\n \"\"\"Bubble-sort a list, yielding the list at each swap.\"\"\"\n for i in list(reversed(range(len(elems)))):\n for j in list(reversed(range(i))):\n if elems[i] < elems[j]:\n elems[i], elems[j] = elems[j], elems[i]\n yield elems\n</code></pre>\n\n<p>Note that if you iterate forward instead of backward, you can just use <code>for i in range(len(elems))</code> -- simply making the code easier to read might be a good enough reason to rearrange this. :)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-07T20:04:02.373",
"Id": "235247",
"ParentId": "235245",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-07T19:40:48.690",
"Id": "235245",
"Score": "6",
"Tags": [
"python",
"algorithm",
"sorting",
"tkinter",
"matplotlib"
],
"Title": "Animation of sorting algorithms"
}
|
235245
|
<p>Please see the file <a href="https://github.com/VijayS1/windows-dev-box-setup-scripts/blob/master/scripts/MouseCursorSettings.ps1" rel="nofollow noreferrer">here</a>, reproduced below in separate sections.
My question is basically</p>
<ol>
<li>Which way is better? </li>
<li>Which is easier to understand? </li>
<li>Which is easier to modify? </li>
<li>What should be the priority? Modification or Understanding? </li>
</ol>
<p>NEW WAY, using variables & loops, trying to deduplicate as much as possible. Ideally should have one array to change only. </p>
<pre><code>$regpath = "HKCU:\Control Panel\Cursors"
$cursorpath = "%LocalAppData%\Microsoft\Windows\Cursors\"
$suffix = "_eoa.cur"
$settings = @(@{Path="."; Force=$true; PropertyType="String"; Name="(Default)"; Value="Windows Inverted"}
@{Path="."; Force=$true; PropertyType="DWord"; Name="CursorBaseSize"; Value=64}
@{Path="."; Force=$true; PropertyType="DWord"; Name="Scheme Source"; Value=2}
@{Path="."; Force=$true; PropertyType="ExpandString"; Name="Appstarting"; Value=$cursorpath + "busy" +$suffix}
@{Path="."; Force=$true; PropertyType="ExpandString"; Name="Arrow"; Value=$cursorpath + "arrow" +$suffix}
@{Path="."; Force=$true; PropertyType="ExpandString"; Name="Crosshair"; Value=$cursorpath + "cross" +$suffix}
@{Path="."; Force=$true; PropertyType="ExpandString"; Name="Hand"; Value=$cursorpath + "link" +$suffix}
@{Path="."; Force=$true; PropertyType="ExpandString"; Name="Help"; Value=$cursorpath + "helpsel"+$suffix}
@{Path="."; Force=$true; PropertyType="ExpandString"; Name="IBeam"; Value=$cursorpath + "ibeam" +$suffix}
@{Path="."; Force=$true; PropertyType="ExpandString"; Name="No"; Value=$cursorpath + "no" +$suffix}
@{Path="."; Force=$true; PropertyType="ExpandString"; Name="NWPen"; Value=$cursorpath + "pen" +$suffix}
@{Path="."; Force=$true; PropertyType="ExpandString"; Name="Person"; Value=$cursorpath + "person" +$suffix}
@{Path="."; Force=$true; PropertyType="ExpandString"; Name="Pin"; Value=$cursorpath + "pin" +$suffix}
@{Path="."; Force=$true; PropertyType="ExpandString"; Name="SizeAll"; Value=$cursorpath + "move" +$suffix}
@{Path="."; Force=$true; PropertyType="ExpandString"; Name="SizeNESW"; Value=$cursorpath + "nesw" +$suffix}
@{Path="."; Force=$true; PropertyType="ExpandString"; Name="SizeNS"; Value=$cursorpath + "ns" +$suffix}
@{Path="."; Force=$true; PropertyType="ExpandString"; Name="SizeNWSE"; Value=$cursorpath + "nwse" +$suffix}
@{Path="."; Force=$true; PropertyType="ExpandString"; Name="SizeWE"; Value=$cursorpath + "ew" +$suffix}
@{Path="."; Force=$true; PropertyType="ExpandString"; Name="UpArrow"; Value=$cursorpath + "up" +$suffix}
@{Path="."; Force=$true; PropertyType="ExpandString"; Name="Wait"; Value=$cursorpath + "wait" +$suffix}
)
Set-Location $regpath #set location to registry folder where we will make all changes
#$DebugPreference = "Continue"
foreach ($regkey in $settings) {
New-ItemProperty @regkey #create all the registry keys
Write-Debug ($regkey | Out-String)
}
#$settings.ForEach(New-ItemProperty @_) #alternative method testing
</code></pre>
<p>OLD WAY. Using only 1 variable.</p>
<pre><code>#Set Mouse Pointer Scheme to Windows Inverted, large size
$cursorpath = "%LocalAppData%\Microsoft\Windows\Cursors\" #this references the environment variable directly
##$cursorpath = "%SystemRoot%\cursors\" #this references the environment variable directly
New-ItemProperty -Path "HKCU:\Control Panel\Cursors" -Name "(Default)" -Value "Windows Inverted" -PropertyType String -Force
New-ItemProperty -Path "HKCU:\Control Panel\Cursors" -Name CursorBaseSize -Value 64 -PropertyType DWord -Force
New-ItemProperty -Path "HKCU:\Control Panel\Cursors" -Name "Scheme Source" -Value 2 -PropertyType DWord -Force
New-ItemProperty -Path "HKCU:\Control Panel\Cursors" -Name AppStarting -Value ($cursorpath + "busy" + "_eoa.cur") -PropertyType ExpandString -Force
New-ItemProperty -Path "HKCU:\Control Panel\Cursors" -Name Arrow -Value ($cursorpath + "arrow" + "_eoa.cur") -PropertyType ExpandString -Force #same
New-ItemProperty -Path "HKCU:\Control Panel\Cursors" -Name Crosshair -Value ($cursorpath + "cross" + "_eoa.cur") -PropertyType ExpandString -Force
New-ItemProperty -Path "HKCU:\Control Panel\Cursors" -Name Hand -Value ($cursorpath + "link" + "_eoa.cur") -PropertyType ExpandString -Force
New-ItemProperty -Path "HKCU:\Control Panel\Cursors" -Name Help -Value ($cursorpath + "helpsel"+ "_eoa.cur") -PropertyType ExpandString -Force
New-ItemProperty -Path "HKCU:\Control Panel\Cursors" -Name IBeam -Value ($cursorpath + "ibeam" + "_eoa.cur") -PropertyType ExpandString -Force #same
New-ItemProperty -Path "HKCU:\Control Panel\Cursors" -Name No -Value ($cursorpath + "no" + "_eoa.cur") -PropertyType ExpandString -Force #same
New-ItemProperty -Path "HKCU:\Control Panel\Cursors" -Name NWPen -Value ($cursorpath + "pen" + "_eoa.cur") -PropertyType ExpandString -Force
New-ItemProperty -Path "HKCU:\Control Panel\Cursors" -Name Person -Value ($cursorpath + "person" + "_eoa.cur") -PropertyType ExpandString -Force #same
New-ItemProperty -Path "HKCU:\Control Panel\Cursors" -Name Pin -Value ($cursorpath + "pin" + "_eoa.cur") -PropertyType ExpandString -Force #same
New-ItemProperty -Path "HKCU:\Control Panel\Cursors" -Name SizeAll -Value ($cursorpath + "move" + "_eoa.cur") -PropertyType ExpandString -Force
New-ItemProperty -Path "HKCU:\Control Panel\Cursors" -Name SizeNESW -Value ($cursorpath + "nesw" + "_eoa.cur") -PropertyType ExpandString -Force
New-ItemProperty -Path "HKCU:\Control Panel\Cursors" -Name SizeNS -Value ($cursorpath + "ns" + "_eoa.cur") -PropertyType ExpandString -Force
New-ItemProperty -Path "HKCU:\Control Panel\Cursors" -Name SizeNWSE -Value ($cursorpath + "nwse" + "_eoa.cur") -PropertyType ExpandString -Force
New-ItemProperty -Path "HKCU:\Control Panel\Cursors" -Name SizeWE -Value ($cursorpath + "ew" + "_eoa.cur") -PropertyType ExpandString -Force
New-ItemProperty -Path "HKCU:\Control Panel\Cursors" -Name UpArrow -Value ($cursorpath + "up" + "_eoa.cur") -PropertyType ExpandString -Force
New-ItemProperty -Path "HKCU:\Control Panel\Cursors" -Name Wait -Value ($cursorpath + "wait" + "_eoa.cur") -PropertyType ExpandString -Force #same
# It's so annoying that only 6/17 names are the same. I guess it'd due to changes in modern thinking about naming conventions and how they thought
#previously. This raises the question about how to do it right in OSes? That's why APIs are hard I guess.
</code></pre>
|
[] |
[
{
"body": "<p>If path is always . and force is always true, why are you always setting them? It inhibits readability. </p>\n\n<p>The priority should always be understanding, because well understood code can be made more modular by anyone (e.g. you in the future), but it's far harder to update code that you don't understand. </p>\n\n<p>It's pretty easy to tell what you're doing already though. If you wanted to be minimalist, you functionally have key/value pairs of strings, and could just store them in an array or hashtable to send to New-ItemProperty.</p>\n\n<p>I would personally lay it out like:</p>\n\n<ol>\n<li>declare a lambda that adds non-cursor entries</li>\n<li>declare a lambda that adds cursor entries</li>\n<li>Pipe a table of Key:Value pairs into lambda from step 1</li>\n<li>Pipe a table of cursor names to cursor paths into lambda from step 2</li>\n</ol>\n\n<p>The reasoning is that:</p>\n\n<ul>\n<li>Pretty close to the minimal amount of code</li>\n<li>Configuration is at the top of the file: the registry paths, cursor paths, and the mapping of friendly cursor names to paths is in the first two lines</li>\n<li>Hashtables are hard to get typos in, and any errors like misspellings should be readily apparent</li>\n<li>The hashtables are storing high-level data that can be further mutated later if desired</li>\n<li>Non-cursors and cursors appear to be separate classes of data -- cursors always have the same property type, so that should be extrinsic from cursor entries.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-13T10:57:46.507",
"Id": "461098",
"Score": "0",
"body": "The path entry is required, the function won't work otherwise. Since priority is understanding, doesn't the OLD way win out over any other minimalist code or also your suggested method, as the person reading has to conceptually then understand the things you said, i.e. lambdas ...etc."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-13T18:23:11.783",
"Id": "461139",
"Score": "1",
"body": "@Vijay Maximum verbosity does not necessarily mean maximum understanding or readability. In fact, more verbosity can be much less readable and much more bug prone. For example, imagine you're reading this and can only see half the lines on your display. Do you know for sure every path is the same? If they're always being specified, maybe if you scroll down you'll see one that is different -- you don't know for sure. If you specify the path a single time at the top of the file, the reader can reasonably assume it's relevant for all entries."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-13T18:33:26.160",
"Id": "461143",
"Score": "0",
"body": "Why is it necessary to use a powershell script and not a registry script? https://support.microsoft.com/en-us/help/310516/how-to-add-modify-or-delete-registry-subkeys-and-values-by-using-a-reg"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-07T23:49:17.420",
"Id": "235263",
"ParentId": "235249",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-07T20:14:52.503",
"Id": "235249",
"Score": "4",
"Tags": [
"powershell"
],
"Title": "Duplicated lines easier to read vs DRY"
}
|
235249
|
<p>I have a userform with around 20 controls in that can be inputted. Some are textboxes some are comboboxes etc. </p>
<p>The user fills in these controls and then hits save. When save is pressed, the code finds the relevant row number (based on the task number generated in userform e.g. 1.04 will find 1.03 and add row below.)</p>
<p>However, it can take around 10 seconds or more to fill the newly inserted/copied row, which is impractical for something that will be used frequently. </p>
<p>Is there any efficiencies or alternatives i could use? Sorry I am a newbie to this sort of thing!</p>
<p>I have also included a screen shot which shows the user form, as well as the column where the value is searched before adding a row. The screenshot also shows example of the columns included in the spreadsheet.</p>
<p><img src="https://i.stack.imgur.com/fRZaa.png" alt="image 1"></p>
<p><img src="https://i.stack.imgur.com/OKlZ9.png" alt="image 2"></p>
<p><img src="https://i.stack.imgur.com/jSHiu.png" alt="userform image"></p>
<pre><code>
Private Sub CommandButtonSave_Click()
Application.ScreenUpdating = False
Application.Calculation = xlManual
'Declare variables
Dim subtaskws As Worksheet: Set subtaskws = ThisWorkbook.Sheets("Sub Tasks")
Dim ActivityWs As Worksheet: Set ActivityWs = ThisWorkbook.Sheets("Activity Overview")
Dim lastrow As Long, lastrowAO As Long, cellinput As Variant, newrow As Long, lastcollet As String, lastcol As Long, findtasknum As Range, lastrowST As Long, cell As Range, found As Variant, activitynum As Long
'Find column Letters
Call ColumnLetterFinder(subtaskws, 2, "Actual Workload", AWCol)
Call ColumnLetterFinder(subtaskws, 2, "W.", WCol)
Call ColumnLetterFinder(subtaskws, 2, "I.", ICol)
Call ColumnLetterFinder(subtaskws, 2, "E.", ECol)
Call ColumnLetterFinder(subtaskws, 2, "P", PCol)
Call ColumnLetterFinder(subtaskws, 2, "Level", LevelCol)
'find lastrows, columns and cells
lastrow = (subtaskws.Range("A" & Rows.Count).End(xlUp).row) + 1
lastcol = subtaskws.Cells(2, 1).End(xlToRight).Column
lastcollet = lastcol
lastcollet = Split(Cells(1, lastcol).Address, "$")(1)
lastrowST = subtaskws.Range("A" & Rows.Count).End(xlUp).row
activitynum = AddTask.TextBoxid.Value + 1
Dim Ctrl As Variant, range1 As Range, userformorder As Variant, col As Long, IDrange() As Variant
userformorder = Array("SubTaskID", "TextBoxsubtask", "ComboBoxDeliverableFormat", "TextBoxcheckedcomplete", "TextBoxformat", "TextBoxacceptancecriteria", "BudgetWorkloadTextBox", "AWLTextBox", "ComboBoxOwner", "TextBoxTDSNumber", "TextBoxMilestone", "TextBoxTargetDeliveryDate", "ComboBoxW", "ComboBoxI", "ComboBoxe", "TextBoxP", "TextBoxLevel", "TextBoxInputQuality", "TextBoxNewInput", "TextBoxDelay", "TextBoxInternalVV", "TextBoxReviewer", "TextBoxDelivered", "ComboBoxNumIterations", "ComboBoxAcceptance", "ComboBoxProgress", "ComboBoxStatus", "ComboBoxFlowChart", "TextBoxActivitySheet", "TextBoxEvidenceofDelivery", "TextBoxComments") 'etc
'Find row before subtaskId number
Set found = subtaskws.Range("A3:A" & lastrowST).Find(What:=(activitynum), LookAt:=xlWhole)
If found Is Nothing Then
newrow = lastrow
subtaskws.Range("A4:A" & lastcollet).EntireRow.Copy
subtaskws.Range("A" & newrow).EntireRow.PasteSpecial xlPasteFormulasAndNumberFormats
subtaskws.Range("A" & newrow).EntireRow.PasteSpecial xlPasteValidation
subtaskws.Range("A" & newrow).EntireRow.PasteSpecial xlPasteAllMergingConditionalFormats
subtaskws.Range("A" & newrow & ":AE" & newrow & "").ClearContents
subtaskws.Columns("A:BB").Calculate
For Each Ctrl In userformorder
If col = 8 Then
Else
If AddTask.Controls(Ctrl).Value <> "" Then
subtaskws.Range("A" & newrow).Offset(, col).Value = AddTask.Controls(Ctrl).Value
End If
col = col + 1
End If
Next Ctrl
subtaskws.Cells(newrow, AWCol).Value = "=SUM(AF" & newrow & ":" & lastcollet & newrow & ")"
subtaskws.Cells(newrow, PCol).Value = "=(" & WCol & newrow & "*" & ICol & newrow & "*" & ECol & newrow & ")"
subtaskws.Cells(newrow, LevelCol).Value = "=IF(" & PCol & newrow & " >11,1,IF(" & PCol & newrow & ">3,2,""N/A""))"
Else
subtaskws.Range("A" & (found.row)).EntireRow.Insert
newrow = found.row - 1
subtaskws.Range("A4:A" & lastcollet & "").EntireRow.Copy
subtaskws.Range("A" & newrow).EntireRow.PasteSpecial xlPasteFormulasAndNumberFormats
subtaskws.Range("A" & newrow).EntireRow.PasteSpecial xlPasteValidation
subtaskws.Range("A" & newrow).EntireRow.PasteSpecial xlPasteAllMergingConditionalFormats
subtaskws.Range("A" & newrow & ":AE" & newrow & "").ClearContents
For Each Ctrl In userformorder
If AddTask.Controls(Ctrl).Value <> "" Then
subtaskws.Range("A" & newrow).Offset(, col).Value = AddTask.Controls(Ctrl).Value
End If
col = col + 1
Next Ctrl
subtaskws.Cells(newrow, AWCol).Value = "=SUM(AF" & newrow & ":" & lastcollet & newrow & ")"
subtaskws.Cells(newrow, PCol).Value = "=(" & WCol & newrow & "*" & ICol & newrow & "*" & ECol & newrow & ")"
subtaskws.Cells(newrow, LevelCol).Value = "=IF(" & PCol & newrow & " >11,1,IF(" & PCol & newrow & ">3,2,""N/A""))"
End If
TextBoxsubtask.Value = vbNullString
ComboBoxDeliverableFormat.Value = vbNullString
TextBoxformat.Value = vbNullString
ComboBoxOwner.Value = vbNullString
TextBoxTargetDeliveryDate.Value = vbNullString
ComboBoxW.Value = vbNullString
ComboBoxI.Value = vbNullString
ComboBoxe.Value = vbNullString
TextBoxP.Value = vbNullString
TextBoxLevel.Value = vbNullString
TextBoxComments.Value = Null
TextBoxEvidenceofDelivery.Value = Null
TextBoxActivitySheet.Value = Null
ComboBoxFlowChart.Value = Null
ComboBoxStatus.Value = Null
ComboBoxProgress.Value = Null
ComboBoxAcceptance.Value = Null
ComboBoxNumIterations.Value = Null
TextBoxDelivered.Value = Null
TextBoxReviewer.Value = Null
TextBoxInternalVV.Value = Null
TextBoxDelay.Value = Null
TextBoxNewInput.Value = Null
TextBoxInputQuality.Value = Null
TextBoxMilestone.Value = Null
TextBoxTDSNumber.Value = Null
TextBoxacceptancecriteria.Value = Null
TextBoxcheckedcomplete.Value = Null
SubTaskID.Value = SubTaskID.Value + 0.01
Application.ScreenUpdating = True
Application.Calculation = xlAutomatic
End Sub
Public Function ColumnLetterFinder(ws, row, Value, x)
Dim rFind As range
With ws.Rows(row)
Set rFind = .Find(What:=Value, LookAt:=xlWhole, MatchCase:=False, SearchFormat:=False)
If Not rFind Is Nothing Then
x = Split(rFind.Address, "$")(1)
End If
End With
End Function
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-08T04:49:52.597",
"Id": "460350",
"Score": "0",
"body": "You should include `ColumnLetterFinder` and some screenshots of thedata and formats. I download link with mock data would also help."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-08T10:16:42.467",
"Id": "460384",
"Score": "0",
"body": "Sorry these have been added now!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-10T05:21:03.850",
"Id": "460715",
"Score": "1",
"body": "Sorry about the slow response. Is `ColumnLetterFinder()` really necessary? Will the users be reordering the columns? Or are you using it to make your code more dynamic, in case you plan on changing the column order yourself?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-10T08:28:29.923",
"Id": "460725",
"Score": "0",
"body": "Yes unfortunately as the extra columns may be added in depending on the project. The columns included now and the vital ones"
}
] |
[
{
"body": "<p>I don't see anything wrong so just a few shots in the dark:</p>\n\n<p>Are there any \"hidden\" data-driven automations like worksheet_change or whatever?</p>\n\n<p>You may disable event handling and a few more time comsuming services for the course of processing. Take a look at this: <a href=\"https://codereview.stackexchange.com/questions/234904/changing-the-formatting-of-sheets/235074?noredirect=1#comment459911_235074\">Speed up App</a></p>\n\n<p>I would not apply copying validations and formats and whatever on all the 16K cells in the entire row. It's OK to manage a dynamically changing number of columns but I'd rather maximize the number of columns with calculating the exact number of used columns (more hassle) or simply setting it to say 100 if you'd never have more than 80 (quick and dirty). </p>\n\n<p>Checking a string for zero length it is somewhat faster to use</p>\n\n<pre><code>If LenB(AddTask.Controls(Ctrl).Value) <> 0 ...\n</code></pre>\n\n<p>instead of </p>\n\n<pre><code>If AddTask.Controls(Ctrl).Value <> \"\" ...\n</code></pre>\n\n<p>for it does not invoke string comparision function but checks a single byte in the string header. </p>\n\n<p>+1: For manipulating formulas run-time I prefer using <code>.Cells</code> this way</p>\n\n<pre><code>subtaskws.FormulaLocal=\"=sum(\" & Range(CElls(newrow, \"AF\"), Cells(newrow, lastcollet)).Address & \")\"\n</code></pre>\n\n<p>for it is more handy than bothering with string concatenations to make cell references. \nSee also <code>.FormulaLocal</code> and <code>.Address(False, False)</code></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-10T09:34:52.350",
"Id": "460730",
"Score": "0",
"body": "Thanks for the feedback! i never knew about forumla local so that could be really handy! thanks"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-10T09:24:13.897",
"Id": "235407",
"ParentId": "235257",
"Score": "3"
}
},
{
"body": "<p>I am going to address some style issues.</p>\n\n<p><strong>Do not compress lines</strong></p>\n\n<p>Yes, the syntax allows you to write code like:</p>\n\n<pre><code>Dim subtaskws As Worksheet: Set subtaskws = ThisWorkbook.Sheets(\"Sub Tasks\")\n</code></pre>\n\n<p>But it is harder to read and the assignment versus declaration is harder to see. This makes code harder to follow and maintain. Instead, be clear and explicit:</p>\n\n<pre><code>Dim subtaskws As Worksheet \nSet subtaskws = ThisWorkbook.Sheets(\"Sub Tasks\")\n</code></pre>\n\n<p>The use of the ':' is useful in command line basic (or when doing some things in the immediate window). It is not good in modules.</p>\n\n<p><strong>Use code names (named sheets)</strong></p>\n\n<p>In the VBA Editor, you can rename the 'Sheet1' name of the sheets to something meaningful. Let us say, for example, that you change the <code>(Name)</code> of the sheets to 'SubTasks'. The following image is an example I have - different names but you should get the idea.</p>\n\n<p><a href=\"https://i.stack.imgur.com/sfd74.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/sfd74.png\" alt=\"enter image description here\"></a></p>\n\n<p>Now the code </p>\n\n<pre><code>Dim subtaskws As Worksheet \nSet subtaskws = ThisWorkbook.Sheets(\"Sub Tasks\")\n</code></pre>\n\n<p>is no longer necessary, and you can jump straight into </p>\n\n<pre><code>lastcol = SubTasks.Cells(2, 1).End(xlToRight).Column\n</code></pre>\n\n<p><strong>Do not use <code>Call</code></strong></p>\n\n<p>This is debated - <code>Call</code> is an obsolete word for backwards compatibility, but if anyone needs backwards compatibility to when Call was necessary, they have much bigger issues!</p>\n\n<p>But you have really exemplified why using the obsolete and unnecessary token is not good. You have completely misused a function call (see next comment)!</p>\n\n<p>At this point I am going to say:</p>\n\n<pre><code>Call ColumnLetterFinder(subtaskws, 2, \"Actual Workload\", AWCol)\n</code></pre>\n\n<p>should be idiomatic VBA:</p>\n\n<pre><code>ColumnLetterFinder subtaskws, 2, \"Actual Workload\", AWCol\n</code></pre>\n\n<p><strong>Functions should return things</strong></p>\n\n<p>Your function, written as a <code>Function</code> does not return anything. From your description it is intended to return a string representing the name of a column. There are other ways of doing this, or achieving the result you want. But, for the purposes of this answer I am going to focus on the Function.</p>\n\n<pre><code>Public Function ColumnLetterFinder(ws, row, Value, x)\n</code></pre>\n\n<p>does not declare a return type, does not strongly type the inputs, nor does it exercise discipline in mutating values (by value, rather than by the implicit reference).</p>\n\n<pre><code>Public Function ColumnLetterFinder(ByVal ws As Worksheet, ByVal row As Long, ByVal Value As String, ByRef x As String) As String\n</code></pre>\n\n<p>Note: I made the last one explicitly <code>ByRef</code> because your current code changes that value.</p>\n\n<p>Of course, what you are implicitly doing, is returning the answer through <code>x</code>. So, we can tidy this up a bit:</p>\n\n<pre><code>Public Function ColumnLetterFinder(ByVal ws As Worksheet, ByVal row As Long, ByVal Value As String) As String\nDim rFind As range\n With ws.Rows(row)\n Set rFind = .Find(What:=Value, LookAt:=xlWhole, MatchCase:=False, SearchFormat:=False)\n If Not rFind Is Nothing Then\n ColumnLetterFinder = Split(rFind.Address, \"$\")(1) '<--- set the return value here\n End If\n End With\nEnd Function ' Default value for string is \"\" if rFind is nothing\n</code></pre>\n\n<p>Now your main code can definitely get rid of that annoying <code>Call</code>:</p>\n\n<pre><code>AWCol = ColumnLetterFinder(subtaskws, 2, \"Actual Workload\")\n</code></pre>\n\n<p>… or if you have names the sheet as suggested before:</p>\n\n<pre><code>AWCol = ColumnLetterFinder(SubTasks, 2, \"Actual Workload\")\n</code></pre>\n\n<p>Now the code pretty much comments itself!</p>\n\n<p><strong>Standard comments</strong></p>\n\n<p>Use <code>Option Explict</code> at the top of modules. Always. <strong><em>Always</em></strong>.</p>\n\n<p>Properly indent your code. This makes it easier to read and easier to spot where logic should be. An out of place <code>If</code> or loop becomes easier to spot.</p>\n\n<p>Use meaningful variable names every time. Yes, it is sometimes hard to figure out a good name, but you will thank yourself in the months to come. After all, what did 'x' mean?</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-12T04:13:10.370",
"Id": "235492",
"ParentId": "235257",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "235407",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-07T21:47:26.710",
"Id": "235257",
"Score": "2",
"Tags": [
"vba",
"excel"
],
"Title": "Why does it take so long to print values from userform to sheet?"
}
|
235257
|
<p>In some (perhaps not well-designed) competitive programming problems,
the runtime and score is dependent on how fast your program can
process input. Therefore I've written a small C99 library with optimized
functions for reading from stdin and writing to stdout:</p>
<p><code>fastio.h</code>:</p>
<pre><code>#ifndef FASTIO_H
#define FASTIO_H
#include <stdio.h>
#include <stdlib.h>
#ifdef _WIN32
#define putchar_unlocked putchar
#else
#include <unistd.h>
#include <sys/mman.h>
#include <sys/stat.h>
#endif
// Fast IO routines accessing stdin and stdout. The purpose of them is
// to reduce IO overhead in competitive programming. Therefore, no
// error checking anywhere.
// On Linux and OS X, this is a pointer to stdin's next character. On
// Windows, standard getchar() is used and the pointer
// is NULL.
extern char *
FAST_IO_STDIN;
void
fast_io_init();
// Reading
inline char
fast_io_read_char() {
#ifdef _WIN32
return getchar();
#else
return *FAST_IO_STDIN++;
#endif
}
inline unsigned int
fast_io_read_unsigned_int() {
int val = 0;
#ifdef _WIN32
while (true) {
char c = getchar();
if (c < '0') {
ungetc(c, stdin);
break;
}
val = val * 10 + c - '0';
}
#else
do {
val = val*10 + *FAST_IO_STDIN++ - '0';
} while(*FAST_IO_STDIN >= '0');
#endif
return val;
}
inline int
fast_io_read_int() {
int val = 0;
int sgn = 1;
#ifdef _WIN32
char c = getchar();
if (c == '-') {
sgn = -1;
} else {
ungetc(c, stdin);
}
while (true) {
char c = getchar();
if (c < '0') {
ungetc(c, stdin);
break;
}
val = 10 * val + c - '0';
}
#else
if (*FAST_IO_STDIN == '-') {
sgn = -1;
FAST_IO_STDIN++;
}
do {
val = val*10 + *FAST_IO_STDIN++ - '0';
} while(*FAST_IO_STDIN >= '0');
#endif
return val * sgn;
}
// Writing
inline void
fast_io_write_char(char ch) {
putchar_unlocked(ch);
}
inline void
fast_io_write_long(long n) {
if (n < 0) {
putchar_unlocked('-');
n *= -1;
} else if (n == 0) {
putchar_unlocked('0');
return;
}
long N = n;
long rev = N;
int count = 0;
rev = N;
while ((rev % 10) == 0) {
count++; rev /= 10;
}
rev = 0;
while (N != 0) {
rev = (rev<<3) + (rev<<1) + N % 10; N /= 10;
}
while (rev != 0) {
putchar_unlocked(rev % 10 + '0');
rev /= 10;
}
while (count--) {
putchar_unlocked('0');
}
}
#endif
</code></pre>
<p><code>fastio.c</code></p>
<pre><code>#include "fastio.h"
char *
FAST_IO_STDIN = NULL;
void
fast_io_init() {
#ifdef _WIN32
// Nothing to do on Windows because we use standard getchar().
#else
int flags = MAP_SHARED;
#ifdef __linux__
// Prefills the buffer.
flags |= MAP_POPULATE;
#endif
struct stat sb;
(void)fstat(STDIN_FILENO, &sb);
FAST_IO_STDIN = (char*)mmap(0, sb.st_size,
PROT_READ, flags, STDIN_FILENO, 0);
#endif
}
extern inline char fast_io_read_char();
extern inline unsigned int fast_io_read_unsigned_int();
extern inline int fast_io_read_int();
extern inline void fast_io_write_char(char ch);
extern inline void fast_io_write_long(long n);
</code></pre>
<p>I want the library to work on Windows, Linux and OS X, but
performance only matters on Linux because bots for competitive
programming only run on Linux. As the goal is to shave off
milliseconds to win contests, there is absolutely no error
checking.</p>
<p>Does anyone have any ideas how to make it even faster?</p>
|
[] |
[
{
"body": "<p>On Windows, you'd rather use the <a href=\"https://docs.microsoft.com/en-us/windows/console/console-functions\" rel=\"nofollow noreferrer\">console API</a> directly instead of stdio.h. This should increase performance somewhat, since these functions are what <code>getchar</code> etc will end up calling anyhow.</p>\n\n<p>Other issues:</p>\n\n<ul>\n<li>All functions should be declared to take <code>void</code> as parameters, rather than to accept any parameter. If they are properly inlined this should hopefully not have any impact on the program, but in some cases it might mess up the calling convention.</li>\n<li><p>Rather than making a mess with compiler switch <code>#ifdef</code> all over the place, you could in the header file do something like:</p>\n\n<pre><code>#ifdef _WIN32\n #define fast_io_read_char fast_io_read_char_windows\n#else\n #define fast_io_read_char fast_io_read_char_linux\n#endif\n</code></pre>\n\n<p>And so on. Then separate the implementation of each function, so that you have one file <code>fastio_windows.c</code> and one <code>fastio_linux.c</code>. You can add both files to linking both no matter, the <code>#ifdef</code> in the header will determine which functions that actually get linked to the binary.</p></li>\n<li>Left shifting the signed type <code>long rev</code> is questionable code - you have to ensure that <code>n</code> is never negative or too large.</li>\n<li>Missing <code>#include <stdbool.h></code> so the code won't compile.</li>\n<li><code>getchar</code> calls incorrectly use <code>char</code> instead of <code>int</code> so the code cannot handle <code>EOF</code>. If you don't intend to handle <code>EOF</code>, then you should still cast the result of <code>getchar()</code> to <code>char</code> - to silence compiler warnings and write self-documenting code that shows that you have considered this.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-08T16:21:33.570",
"Id": "460422",
"Score": "0",
"body": "Thank you. I think inline functions in libraries need to be declared in that way. See [this](https://stackoverflow.com/questions/5229343/how-to-declare-an-inline-function-in-c99-multi-file-project) SO answer. But maybe there's a better way."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-09T07:38:25.073",
"Id": "460533",
"Score": "0",
"body": "@BjörnLindqvist Ah right, that remark isn't correct, I just found it odd to find them in the .c file. But technically they can be anywhere in the translation unit. I did however notice a few other issues just now. Post updated."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-08T09:23:28.763",
"Id": "235281",
"ParentId": "235260",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-07T22:11:25.970",
"Id": "235260",
"Score": "4",
"Tags": [
"performance",
"c",
"programming-challenge",
"io",
"c99"
],
"Title": "C functions for fast IO for competitive programming"
}
|
235260
|
<p>I have a library with a lot of duplicate code to accommodate different collection types, and its starting to get a bit tedious, is there a better way to do this to reduce the amount of duplication going on ? Its only going to get worse the more functions i add...</p>
<p>This is my current library script:</p>
<pre><code>using System.Collections.Generic;
using UnityEngine;
namespace Math {
public static class Geometry
{
public static float Area(List<Vector2> points)
{
float a = 0;
for (int i = 0; i < points.Count; i++)
{
var p1 = points[i];
var p2 = points[(i + 1) % points.Count];
a += p1.x * p2.y - p2.x * p1.y;
}
return a * 0.5f;
}
public static float Area(List<Vector3> points)
{
float a = 0;
for (int i = 0; i < points.Count; i++)
{
var p1 = points[i];
var p2 = points[(i + 1) % points.Count];
a += p1.x * p2.z - p2.x * p1.z;
}
return a * 0.5f;
}
public static float Area(Vector3[] points)
{
float a = 0;
for (int i = 0; i < points.Length; i++)
{
var p1 = points[i];
var p2 = points[(i + 1) % points.Length];
a += p1.x * p2.z - p2.x * p1.z;
}
return a * 0.5f;
}
public static float Area(Vector2[] points)
{
float a = 0;
for (int i = 0; i < points.Length; i++)
{
var p1 = points[i];
var p2 = points[(i + 1) % points.Length];
a += p1.x * p2.y - p2.x * p1.y;
}
return a * 0.5f;
}
public static bool IsClockwise(List<Vector3> points)
{
float sum = 0;
for (int i = 0; i < points.Count - 1; i++)
{
var point1 = points[i];
var point2 = points[i + 1];
sum += (point2.x - point1.x) * (point2.z + point1.z);
}
return sum > 0;
}
public static bool IsClockwise(Vector3[] points)
{
float sum = 0;
for (int i = 0; i < points.Length - 1; i++)
{
var point1 = points[i];
var point2 = points[i + 1];
sum += (point2.x - point1.x) * (point2.z + point1.z);
}
return sum > 0;
}
public static bool IsClockwise(List<Vector2> points)
{
float sum = 0;
for (int i = 0; i < points.Count - 1; i++)
{
var point1 = points[i];
var point2 = points[i + 1];
sum += (point2.x - point1.x) * (point2.y + point1.y);
}
return sum > 0;
}
public static bool IsClockwise(Vector2[] points)
{
float sum = 0;
for (int i = 0; i < points.Length - 1; i++)
{
var point1 = points[i];
var point2 = points[i + 1];
sum += (point2.x - point1.x) * (point2.y + point1.y);
}
return sum > 0;
}
}
}
</code></pre>
|
[] |
[
{
"body": "<p>You could avoid a lot of duplicated code if you call one overloaded method from the other overloaded one.</p>\n\n<p>An <code>IList<T></code> can be easily changed to a <code>[T]</code> array by just calling the <code>ToArray()</code> method of that <code>List</code>. This would result in e.g <code>public static float Area(List<Vector3> points)</code> looking like so </p>\n\n<pre><code>public static float Area(IList<Vector3> points)\n{\n return Area(points.ToArray());\n}\n\npublic static float Area(Vector3[] points)\n{\n float a = 0;\n for (int i = 0; i < points.Length; i++)\n {\n var p1 = points[i];\n var p2 = points[(i + 1) % points.Length];\n\n a += p1.x * p2.z - p2.x * p1.z;\n }\n return a * 0.5f;\n} \n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-08T06:15:19.350",
"Id": "460356",
"Score": "0",
"body": "How about just having one method for IEnumerable<T>? That covers both List And Array And many more."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-08T06:17:13.520",
"Id": "460357",
"Score": "0",
"body": "@slepic and later on you will return it into an array again or what? The items are accessed by index hence a `IEnumerable<T>` won't fit."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-08T07:37:37.790",
"Id": "460364",
"Score": "0",
"body": "@Heslacher `IList<T>` then."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-08T08:12:48.310",
"Id": "460373",
"Score": "0",
"body": "@Heslacher Indeed they are. But is it necessary? Compute for first versus last. Set first as previous. Then loop from second to end comparing current to previous. Set current as previous on end of each iteration."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-08T17:54:14.337",
"Id": "460442",
"Score": "0",
"body": "Why do you need `Area(Vector3[] points)` when the first method with the `IList<Vector3>` argument can be called with an array of `Vector3`? An array implements IList<T>"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-08T05:42:26.837",
"Id": "235268",
"ParentId": "235267",
"Score": "1"
}
},
{
"body": "<p>Depending on how many points you'll be dealing with, you could go one step further. Since you're only using 2 points from the <code>Vector3</code>, it's fairly simple to cast the <code>Vector3</code>'s into <code>Vector2</code>'s.</p>\n\n<pre><code>public static float Area(List<Vector2> points)\n{\n float a = 0;\n for (int i = 0; i < points.Count; i++)\n {\n var p1 = points[i];\n var p2 = points[(i + 1) % points.Count];\n\n a += p1.x * p2.y - p2.x * p1.y;\n }\n\n return a * 0.5f;\n}\n\npublic static float Area(List<Vector3> points)\n{\n\n return Area(points.Select(x => new Vector2(x.x,x.z)).ToList());\n}\n\npublic static float Area(Vector3[] points)\n{\n return Area(points.ToList());\n}\n\npublic static float Area(Vector2[] points)\n{\n return Area(points.ToList());\n}\n</code></pre>\n\n<p>Upon further reflection the code reduction can be taken a step further by using <code>IEnumerable<T></code>. Now it becomes:</p>\n\n<pre><code>public static float Area(IEnumerable<Vector2> points)\n{\n float a = 0;\n var first = points.First();\n var prev = first;\n foreach (var curr in points.Skip(1))\n {\n a += prev.x * curr.y - curr.x * prev.y;\n prev = curr;\n\n }\n a += prev.x * first.y - first.x * prev.y;\n return a * 0.5;\n}\n\npublic static float Area(IEnumerable<Vector3> points)\n{\n\n return Area(points.Select(x => new Vector2(x.x,x.z)));\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-09T06:30:34.390",
"Id": "460521",
"Score": "0",
"body": "That's gonna be quite inefficient."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-09T11:54:20.910",
"Id": "460572",
"Score": "0",
"body": "Specifically, the call to `Last()` is `O(a*n)` which turns the `O(b*n)` algorithm to `O((a+b)*n)`. Check my answer to see how to avoid this both with and without linq and also squeeze a bit more flexibility out of all this."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-10T01:57:33.217",
"Id": "460705",
"Score": "0",
"body": "@slepic - The inefficiency is corrected."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-08T06:14:35.963",
"Id": "235269",
"ParentId": "235267",
"Score": "4"
}
},
{
"body": "<p>your non-common code is the line with the formula, so this is what you have to move to the outside,\nand pass as a parameter.</p>\n\n<pre><code> public static float Area<T>(IReadOnlyCollection<T> points, Func<T, T, float> func)\n {\n float a = 0;\n for (int i = 0; i < points.Count; i++)\n {\n var p1 = points[i];\n var p2 = points[(i + 1) % points.Count];\n a += func(p1, p2);\n }\n\n return a * 0.5f;\n }\n</code></pre>\n\n<p>And this you can call with</p>\n\n<pre><code> Area(yourpointVector2list, (p1, p2) => p1.x * p2.y - p2.x * p1.y) \n Area(yourpointVector3list, (p1, p2) => p1.x * p2.z - p2.x * p1.z)\n</code></pre>\n\n<p>And since I changed it to ICollection, you can use it with lists and arrays, witout having the code twice.<br>\nUsing the readonly version documents, the method is not changing the collection. (Works with .NET 4.5 and above)</p>\n\n<p>For your \"IsClockwise\" you can apply this pattern yourself.</p>\n\n<p>It will perform a little slower, the delegate call is a little costly,\ndepending on how often you use it, you will not notice it.</p>\n\n<p>I give you the performance back, at another place</p>\n\n<pre><code> public static float Area<T>(IReadOnlyCollection<T> points, Func<T, T, float> func)\n {\n float a = 0;\n for (int i = 1; i < points.Count; i++)\n {\n a += func(points[i-1], points[i]);\n }\n a += func(points[points.Count-1], points[0]);\n\n return a * 0.5f;\n }\n</code></pre>\n\n<p>This save the 'mod' operation in each iteration.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-08T17:52:20.143",
"Id": "460441",
"Score": "0",
"body": "OK, I make a hint in the answer. After one has made copy&paste, it's always hard to find for others, if something really is a copy, or not."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-09T06:33:57.317",
"Id": "460522",
"Score": "1",
"body": "When you move the computation out as parameter you probably dont want it to be called `Area` anymore. Because you have to provide a specific callback in order for it to provide the area of polygon."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-09T06:36:07.533",
"Id": "460523",
"Score": "0",
"body": "Anyway i would instead make it return enumerable of pairs of points instead of having to pass callback acceptin such pair. That's gonna be yet more flexible because you can do more then sums."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-09T06:38:51.783",
"Id": "460524",
"Score": "0",
"body": "It would basically turn the polygon representation as list of points into a list of consecutive line segments which might be easier to work with."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-08T15:50:30.327",
"Id": "235302",
"ParentId": "235267",
"Score": "2"
}
},
{
"body": "<h1>Extension methods</h1>\n\n<p>Notice that I add <code>this</code> to the first arguments of all the functions to allow calling them like <code>points.Area()</code> instead of <code>Area(points)</code>.</p>\n\n<h1>Polygon Vertices vs. Edges</h1>\n\n<p>The biggest problem I see is that you represent the polygon as a list/array (generaly an enumerable) of points. Well that's not bad on it's own. But the fact that all your functions need to treat the polygon as a list of edges rather than vertices makes you repeat the complexity of \"converting the representations\" in every function again. </p>\n\n<p>And so the first thing I would do, would be to generalize to IEnumerable and create a function that converts the vertices representation into an edges representation. And use yielding to avoid triplication of memory.</p>\n\n<p>Maybe you could do this with linq but it is not necessary. There is a low level interface called IEnumerator. Thats how every IEnumerable achieve the \"foreachability\", they simply provide an enumerator through the <code>GetEnumerator()</code> method. It is useful whenever you need different code for some items and different for other items. Only when all items are processed the same you fall back to standard foreach (which uses the enumerator for you). The enumerator is probably used directly by linq as well. But true is, sometimes, if you use it directly yourself, you can get the best fit for your case.</p>\n\n<p>And because such function no longer depends on the \"point type\" it can be made generic.</p>\n\n<pre><code>public static IEnumerable<Tuple<T, T>> GetCircularPairs<T>(this IEnumerable<T> items)\n{\n var enumerator = items.GetEnumerator();\n if (enumerator.MoveNext())\n {\n T first = enumerator.Current;\n if (enumerator.MoveNext())\n {\n T previous = first;\n do\n {\n T current = enumerator.Current;\n yield return new Tuple<T, T>(previous, current);\n previous = current;\n } while (enumerator.MoveNext());\n yield return new Tuple<T, T>(previous, first);\n }\n }\n}\n</code></pre>\n\n<p>All your functions could then rely on the edges representation simplifying them a lot. And because we generalized to IEnumerable, you dont need any overloads for lists, arrays, etc...</p>\n\n<pre><code>public static float Area(this IEnumerable<Vector2> points)\n{\n float area = 0.0;\n foreach (var (p1, p2) in points.GetCircularPairs()) {\n area += p1.x * p2.y - p2.x * p1.y;\n }\n return area;\n}\n\npublic static bool IsClockwise(this IEnumerable<Vector2> points)\n{\n float sum = 0.0;\n foreach (var (p1, p2) in points.GetCircularPairs()) {\n sum += (p2.x - p1.x) * (p2.y + p1.y);\n }\n return sum > 0;\n}\n</code></pre>\n\n<p>The same in linq:</p>\n\n<pre><code>public static float Area(this IEnumerable<Vector2> points)\n{\n return points.GetCircularPairs().Aggregate(0.0, (a, x) => a + x.Item1.x * x.Item2.y - x.Item2.x * x.Item1.y);\n}\n\npublic static bool IsClockwise(this IEnumerable<Vector2> points)\n{\n return 0 < points.GetCircularPairs().Aggregate(0.0, (a, x) => a +(x.Item2.x - x.Item1.x) * (x.Item2.y + x.Item1.y));\n}\n</code></pre>\n\n<h1>3D Wrappers may not be necessary</h1>\n\n<p>Similarly to @tinstaafl linq solution for Vector3, but extract the select to separate function because that also repeats:</p>\n\n<pre><code>public static IEnumerable<Vector2> OmitY(this IEnumerable<Vector3> points)\n{\n return points.Select(p => new Vector2(p.x,p.z));\n}\n\npublic static float Area(this IEnumerable<Vector3> points)\n{\n return points.OmitY().Area();\n}\n\npublic static bool IsClockwise(this IEnumerable<Vector3> points)\n{\n return points.OmitY().IsClockwise();\n}\n</code></pre>\n\n<p>you can solve without linq this way:</p>\n\n<pre><code>public static IEnumerable<Vector2> OmitY(this IEnumerable<Vector3> points)\n{\n foreach (var p in points) {\n yield return new Vector2(p.x,p.z);\n }\n}\n</code></pre>\n\n<p>You see that maybe you will want to also define <code>OmitX</code> and <code>OmitZ</code>, and then maybe the 3D wrappers would need variants for that too (ie <code>AreaXOmitted</code>, etc.), so it becomes disuptable whether they are needed at all or rather let the consumer choose which axis to omit by calling <code>OmitX|Y|Z</code> himself before calling <code>Area</code> and/or <code>IsClockwise</code> on it. But by all means, if you feel that omitting y is the best fit for most cases, go for it and add this y-omitting overload :)</p>\n\n<h1>Linq or No Linq?</h1>\n\n<p>As you can see with Linq the code gets a bit shorter in height and longer in width :). Also depends on you if you wanna make it dependent on Linq. I wouldn't see any problem with it as Linq is commonly used anyway. On other hand, in the code you needed Select and Aggregate functions from linq. And these actually encapsulate a very trivial using such wrappers may cause some performance drop. To show how trivial they are here is a possible implementation:</p>\n\n<pre><code>public static IEnumerable<R> Select<R,T>(this IEnumerable<T> items, Func<T,R> f)\n{\n foreach (var item in items)\n {\n yield return f(item);\n }\n}\n\npublic static R Aggregate<R,T>(this IEnumerable<T> items, R acc, Func<R,T,R> f)\n{\n foreach (var item in items)\n {\n acc = f(acc, item);\n }\n return acc;\n}\n</code></pre>\n\n<h1>Some More Abstraction?</h1>\n\n<p>If the expression <code>p1.x * p2.y - p2.x * p1.y</code> make any \"Sense\" separately you can also create a function for it (depends how far you wanna go :)):</p>\n\n<pre><code>public static float AreaSense(this Tuple<Vector2, Vector2> edge)\n{\n return edge.Item1.x * edge.Item2.y - edge.Item2.x * edge.Item1.y\n}\n\npublic static float ClockwiseSense(this Tuple<Vector2, Vector2> edge)\n{\n return (edge.Item2.x - edge.Item1.x) * (edge.Item2.y + edge.Item1.y);\n}\n\npublic static float Area(this IEnumerable<Vector2> points)\n{\n return points.GetCircularPairs().Select(p => p.AreaSense()).Sum();\n // supposing Sum() is the obvious Aggregate(0.0, (a,x) => a+x)\n}\n\n// or aggregate directly\npublic static float IsClockwise(this IEnumerable<Vector2> points)\n{\n return points.GetCircularPairs().Aggregate(0.0, (a,p) => a + p.ClockwiseSense());\n}\n</code></pre>\n\n<h1>Increased performance without linq</h1>\n\n<p>You can increase performance by bypassing linq and merging everything possible together, and you get something similar to what @Holger suggests in his answer, but it is generalized for anything enumerable, not just read only collections.</p>\n\n<pre><code>public static float SumCircluarPairs<T>(this IEnumerable<T> points, Func<T, T, float> f)\n{\n float sum = 0.0;\n var enumerator = items.GetEnumerator();\n if (enumerator.MoveNext())\n {\n T first = enumerator.Current;\n if (enumerator.MoveNext())\n {\n T previous = first;\n do\n {\n T current = enumerator.Current;\n sum += f(previous, current);\n previous = current;\n } while (enumerator.MoveNext());\n sum += f(previous, first);\n }\n }\n return sum;\n} \n\npublic static float Area(this IEnumerable<Vector2> points)\n{\n return points.SumCircularPairs((p1, p2) => p1.x * p2.y - p2.x * p1.y);\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-09T18:09:35.783",
"Id": "460629",
"Score": "0",
"body": "Maybe you get the price for creativity and elegance, but for sure not for performance. So many function calls, Creation of enumerators, 3-level-member access, delegates and tons of object creations. If you run it once in a while it's nice, but not if you need to rotate some 10.000 vector grid-model with 25 frames/second. No use of Linq is only the weakest condition, extend it with no foreach(no enumerators), no object creation, stack limited to 10 items ;-)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-09T18:21:52.257",
"Id": "460632",
"Score": "0",
"body": "@Holger You can also merge the approach from `GetCircularPairs` with the expression `AreaSense`/`ClockwiseSense`, inlining the expression instead of the yields and making the aggregation inside that function. That way you avoid extra enumeration wrappers from `Select` and `Aggregate` while keeping it work for any enumerable, althoutgh you will have to repeat the `GetCircularPairs` logic in both `Area()` and `IsClockwise()`, unless you expose the expression logic as a callback argument like you did in your answer. But with the callback you still get many function calls against which you object."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-09T18:36:34.773",
"Id": "460638",
"Score": "0",
"body": "@Holger I have added a new section on the end showing the implementation as I descibed in previous comment using the callback..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-09T21:36:59.703",
"Id": "460670",
"Score": "0",
"body": "I just wanted to direct attention on all the GetEnumerator, MoveNext and Current, calls. This can all be avoided if you don' turn it down to IEnumerable and not use foreach. But I'm just combining the best of our ideas, we just demonstrate different techniques. for case T is a huge struct, you move quiet a lot of bytes. (btw: it's points.getenumerator, not items.getenumerator)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-09T21:39:46.233",
"Id": "460671",
"Score": "0",
"body": "if we do the sum over 3 points, like `(p1, p2, p3) => (p1.x-p3.x)*p2.y - (p3.y-p1.y)*p2.x` we have only 6 member accesses instead of 8, and 5 math operations instead of 7, and half the number of loops and delegate calls ;-)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-10T02:52:16.227",
"Id": "460710",
"Score": "0",
"body": "If you want some buck wild single line circular nonsense that's not performant, try \n`enumerable.Skip(1).Concat(enumerable.Take(1)).Zip(enumerable,Tuple.Create);` This will yield tuples of (item[1], item[0]), (item[2], item[1]), ..."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-09T08:14:30.360",
"Id": "235342",
"ParentId": "235267",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-08T04:57:01.940",
"Id": "235267",
"Score": "7",
"Tags": [
"c#"
],
"Title": "Reducing code duplication for my C# math class"
}
|
235267
|
<p>I have written a program in Java 8 using BlueJ. There is just one function of type byte that accepts two String values and return 1 if the first word comes before the second in alphabetical order, and return -1 if the first word comes after the second in alphabetical order, and 0 if both are equivalent strings. I would welcome any suggestions on how to make my code faster and more readable.</p>
<pre class="lang-java prettyprint-override"><code>public class Test
{
public static byte spaceshipAlphabetical (String str1, String str2)
{
int str1Length = str1.length();
int str2Length = str2.length();
int strLength;
if
(str1Length < str2Length)
{
str2 = str2.substring(0, str1Length);
strLength = str1.length();
}
else
{
str1 = str1.substring(0, str2Length);
strLength = str2.length();
}
str1 = str1.toUpperCase();
str2 = str2.toUpperCase();
char charStr1;
char charStr2;
int intChar1 = 0;
int intChar2 = 0;
for
(int i = 0; i < strLength; i++)
{
charStr1 = str1.charAt(i);
charStr2 = str2.charAt(i);
intChar1 = (int) charStr1;
intChar2 = (int) charStr2;
if
((intChar1 < intChar2) || (intChar2 < intChar1) || ((intChar2 == intChar1) && (i == (strLength - 1))))
{
break;
}
}
if
((intChar1 < intChar2) || ((intChar2 == intChar1) && (str1Length < str2Length)))
{
return 1;
}
else if
((intChar2 < intChar1) || ((intChar2 == intChar1) && (str2Length < str1Length)))
{
return -1;
}
else
{
return 0;
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-08T06:50:45.853",
"Id": "460360",
"Score": "1",
"body": "Is there a reason, `return str1.compare(str2);`, won't work? If so include the cases where it won't."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-08T06:56:14.960",
"Id": "460361",
"Score": "0",
"body": "Uhh.. no. I just coded for practice. It is an assignment from school. The question goes: Write a program to lexicographically compare two string objects without using the java.lang.String.compareTo(String) function."
}
] |
[
{
"body": "<p>[1] By Java convention curly brackets belong in the same line as the preceding statement/expression.</p>\n\n<p>Instead of this:</p>\n\n<pre><code>if\n()\n{}\nelse\n{}\n\nfor\n()\n{}\n</code></pre>\n\n<p>do this:</p>\n\n<pre><code>if () {\n ...\n} else {\n ...\n}\n\nfor () {\n ...\n}\n</code></pre>\n\n<p>I suggest you read the Google Java style guide for more tips: <a href=\"https://google.github.io/styleguide/javaguide.html\" rel=\"nofollow noreferrer\">https://google.github.io/styleguide/javaguide.html</a></p>\n\n<p>[2] You don't have to introduce an intermediate variable for holding chars, you can directly assign the result of charAt() method to an int variable: <code>intChar1 = (int) str1.charAt(i);</code></p>\n\n<p>[3] You don't have to do all those substring operations to make the strings the same length. Rewrite the main for loop to do as many iterations as there are characters in the shorter string. Written more succinctly: <code>min(length(A), length(B)</code> iterations</p>\n\n<p>[4] To lexicographically compare two strings, you have to find the first different character in both strings and handle the remaining edge cases after the main for loop. Some pseudocode:</p>\n\n<pre><code>for i = 0; i < (min(length(A), length(B)); i++\n if A[i] != B[i]\n if A[i] < B[i] return -1\n else return 1\n\n// If you didn't return from the method at this point, there are only three options left\nString A is shorter than string B - return -1\nString B is shorter than string A - return 1\nString A and string B are equal - return 0\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-08T07:48:22.970",
"Id": "460367",
"Score": "0",
"body": "Thanks a lot for the help. By the way, I just feel comfortable skipping lines for curly braces."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-08T07:52:41.310",
"Id": "460368",
"Score": "0",
"body": "That/s ok for now, but I would strongly urge to format your code according to the standard conventions, because it will make it easier for other programmers to read and understand your code. This is true no matter which programming language you'll end up writing."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-08T08:11:31.823",
"Id": "460372",
"Score": "1",
"body": "*google.com's Style Guide*: Calling those *Java conventions* is bold."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-08T08:17:42.883",
"Id": "460375",
"Score": "0",
"body": "I didn't mean to imply that Google style guide is an official convention, just as an additional resource to read."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-08T07:37:13.553",
"Id": "235275",
"ParentId": "235270",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "235275",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-08T06:26:29.990",
"Id": "235270",
"Score": "0",
"Tags": [
"java",
"beginner",
"homework"
],
"Title": "Spaceship Operation in for Lexicographic Comparison"
}
|
235270
|
<p>I've recently been trying to learn more rust and I have just finished <a href="https://doc.rust-lang.org/book/ch03-05-control-flow.html#summary" rel="nofollow noreferrer">chapter 3 of the Rust book</a>, which has a list of projects to do to practice.</p>
<p>I have tried to write a program that prints the 12 Days of Christmas and I would like to know if it is idiomatic or if any major improvementsc could be made.</p>
<p>Thanks in advance.</p>
<pre><code>const LYRICS: [&str; 12] = [
"Twelve drummers drumming",
"Eleven pipers piping",
"Ten lords a-leaping",
"Nine ladies dancing",
"Eight maids a-milking",
"Seven swans a-swimming",
"Six geese a-laying",
"Five golden rings",
"Four calling birds",
"Three french hens",
"Two turtle doves, and",
"A partridge in a pear tree",
];
fn gen_lyrics(day: i32) -> String {
let ordinal = match day {
1 => "1st".to_string(),
2 => "2nd".to_string(),
3 => "3rd".to_string(),
_ => day.to_string() + "th",
};
let mut start = format!(
"On the {} day of Christmas, my true love gave to me:\n",
ordinal
);
for i in (0..day).rev() {
start.push_str(&LYRICS[11 - (i as usize)]);
if i != 0 {
start.push_str("\n");
}
}
start
}
fn main() {
for i in 1..13 {
println!("{}\n", gen_lyrics(i))
}
}
</code></pre>
|
[] |
[
{
"body": "<p>This looks pretty good! I'm still fairly new to Rust myself, so I'm not sure how familiar I am with the idioms beyond those outlined in the book. That said, there's a few improvements I can suggest.</p>\n\n<h2>Unsigned integer for <code>day</code></h2>\n\n<p>Since <code>day</code> is never negative, you can use an <a href=\"https://doc.rust-lang.org/book/ch03-02-data-types.html#integer-types\" rel=\"noreferrer\">unsigned integer</a> instead of an <code>i32</code> here:</p>\n\n<pre><code>fn gen_lyrics(day: usize) -> String\n</code></pre>\n\n<p>If you use <code>usize</code> specifically, you also avoid the cast to <code>usize</code> here:</p>\n\n<pre><code>start.push_str(&LYRICS[11 - (i as usize)]);\n</code></pre>\n\n<p>That would then just be:</p>\n\n<pre><code>start.push_str(&LYRICS[11 - i]);\n</code></pre>\n\n<h2>Ordinal suffix <code>match</code> expression</h2>\n\n<p>You can avoid some <code>.to_string()</code> calls and repetition of numbers by making the match expression return just the suffix of the ordinal. You can then append that suffix to the number itself in the <code>format!()</code> call:</p>\n\n<pre><code>let ordinal_suffix = match day {\n 1 => \"st\",\n 2 => \"nd\",\n 3 => \"rd\",\n _ => \"th\",\n};\n\nlet mut start = format!(\n \"On the {}{} day of Christmas, my true love gave to me:\\n\",\n day,\n ordinal_suffix\n);\n</code></pre>\n\n<h2>Inclusive range</h2>\n\n<p>You can use <code>..=</code> instead of <code>..</code> to create an <a href=\"https://doc.rust-lang.org/edition-guide/rust-2018/data-types/inclusive-ranges.html\" rel=\"noreferrer\">inclusive range</a>:</p>\n\n<pre><code>fn main() {\n for i in 1..=12 {\n println!(\"{}\\n\", gen_lyrics(i))\n }\n}\n</code></pre>\n\n<h2>Iterators and the skip method</h2>\n\n<p>You can iterate directly over the <code>LYRICS</code> array, <a href=\"https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.skip\" rel=\"noreferrer\">skipping</a> over the number of lines you don't want to include:</p>\n\n<pre><code>for line in (&LYRICS).iter().skip(12 - day) {\n start.push_str(line);\n start.push_str(\"\\n\");\n}\n</code></pre>\n\n<p>The problem with this is that there's no longer an <code>i</code> variable to check whether an iteration is the last line or not, so it can't conditionally insert a newline. The code above will always insert a newline.</p>\n\n<p>But we can cheat a little </p>\n\n<p>If you remove the newline from the end of the <code>start</code> variable:</p>\n\n<pre><code>\"On the {} day of Christmas, my true love gave to me:\"\n</code></pre>\n\n<p>You can push the newline first, that way you no longer need a conditional in the loop:</p>\n\n<pre><code>for line in (&LYRICS).iter().skip(12 - day) {\n start.push_str(\"\\n\");\n start.push_str(line);\n}\n</code></pre>\n\n<hr>\n\n<h2>Bringing it all together</h2>\n\n<p>This is the code with all the changes applied:</p>\n\n<pre><code>const LYRICS: [&str; 12] = [\n \"Twelve drummers drumming\",\n \"Eleven pipers piping\",\n \"Ten lords a-leaping\",\n \"Nine ladies dancing\",\n \"Eight maids a-milking\",\n \"Seven swans a-swimming\",\n \"Six geese a-laying\",\n \"Five golden rings\",\n \"Four calling birds\",\n \"Three french hens\",\n \"Two turtle doves, and\",\n \"A partridge in a pear tree\",\n];\n\nfn gen_lyrics(day: usize) -> String {\n let ordinal_suffix = match day {\n 1 => \"st\",\n 2 => \"nd\",\n 3 => \"rd\",\n _ => \"th\",\n };\n\n let mut start = format!(\n \"On the {}{} day of Christmas, my true love gave to me:\",\n day,\n ordinal_suffix\n );\n\n for line in (&LYRICS).iter().skip(12 - day) {\n start.push_str(\"\\n\");\n start.push_str(line);\n }\n\n start\n}\n\nfn main() {\n for i in 1..=12 {\n println!(\"{}\\n\", gen_lyrics(i))\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-08T09:30:40.730",
"Id": "460382",
"Score": "1",
"body": "Thanks for this great answer - I hope to see more from you in future!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-08T14:57:16.923",
"Id": "460408",
"Score": "0",
"body": "I think you can just `start.push_str((&LYRICS).iter().skip(12 - day).join(\"\\n\"))`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-08T17:47:39.693",
"Id": "460438",
"Score": "0",
"body": "@Alexander-ReinstateMonica I think you can only `join` on a slice, not from an iterator, so you'd have to do `start.push_str(&LYRICS[12 - day..].join(\"\\n\"))`. Note that this will allocate to make the `String` of the lyrics joined together, then copy that into `start`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-08T19:32:50.690",
"Id": "460466",
"Score": "1",
"body": "[What's an idiomatic way to print an iterator separated by spaces in Rust?](https://stackoverflow.com/q/36941851/155423)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-08T19:33:45.033",
"Id": "460467",
"Score": "1",
"body": "*no longer an `i` variable to check* — [`Iterator::enumerate`](https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.enumerate)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-08T19:35:06.060",
"Id": "460468",
"Score": "1",
"body": "`(&LYRICS).iter()` can just be `LYRICS.iter()`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-10T17:54:51.773",
"Id": "460790",
"Score": "0",
"body": "Thanks for the great answer -- this has been invaluable and has taught me a lot, definitely motivated me to keep learning!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-11T11:00:22.247",
"Id": "460899",
"Score": "0",
"body": "Thanks for the comments everyone! I also learned some new things here :D\n\n@OllyBritton I'm glad to have helped! If my answer helped sufficiently, could you mark it as [accepted](https://meta.stackexchange.com/a/5235)? Thanks!"
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-08T09:18:53.540",
"Id": "235280",
"ParentId": "235271",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-08T06:38:32.443",
"Id": "235271",
"Score": "4",
"Tags": [
"rust"
],
"Title": "12 Days of Christmas in Rust"
}
|
235271
|
<p>This is part of <a href="https://codereview.stackexchange.com/questions/235086/data-analysis-program-for-job-interview">this topic</a>.<br>
Problem:<br>
I need to read a file with BigIntegers and make some analysis "on-the-fly" with each read number (get prime numbers count, get armstrong numbers count). Right now I have this code, but it works very slow:</p>
<pre><code>package ee.raintree.test.numbers;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.math.BigInteger;
import ee.raintree.test.numbers.utils.MathUtils;
public class FileAnalyzer {
private static final char SEPARATOR = ' ';
private File file;
private int armstrongNumbersCount;
private int primeNumbersCount;
public FileAnalyzer(File file) {
this.file = file;
}
public void analyze() throws FileNotFoundException, IOException {
countNumbers();
}
public int getArmstrongNumbersCount() {
return armstrongNumbersCount;
}
public int getPrimeNumbersCount() {
return primeNumbersCount;
}
private void countNumbers() throws FileNotFoundException, IOException {
StringBuilder numberSb = new StringBuilder();
try (FileInputStream fis = new FileInputStream(file)) {
char currentChar;
while (fis.available() > 0) {
currentChar = (char) fis.read();
if (currentChar == SEPARATOR) {
analyzeNumber(new BigInteger(numberSb.toString()));
numberSb = new StringBuilder();
continue;
}
numberSb.append(currentChar);
}
if (numberSb.length() > 0) {
analyzeNumber(new BigInteger(numberSb.toString()));
}
}
}
private void analyzeNumber(BigInteger number) {
if(MathUtils.isArmstrongNumber(number)) {
armstrongNumbersCount++;
}
if(MathUtils.isPrime(number)) {
primeNumbersCount++;
}
}
}
</code></pre>
<p>How can I speed up this process? As I was informed - it is lack of buffering.</p>
|
[] |
[
{
"body": "<p>Replace</p>\n\n<pre><code>try (FileInputStream fis = new FileInputStream(file)) {\n</code></pre>\n\n<p>with</p>\n\n<pre><code>try (InputStream fis = new BufferedInputStream(new FileInputStream(file))) {\n</code></pre>\n\n<p>See also <a href=\"https://stackoverflow.com/questions/18600331/why-is-using-bufferedinputstream-to-read-a-file-byte-by-byte-faster-than-using-f\">Why is using BufferedInputStream to read a file byte by byte faster than using FileInputStream?</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-08T16:35:45.943",
"Id": "460424",
"Score": "0",
"body": "In the second try with resources shouldn't the FileInputStream also created before buffered stream, so both can be closed?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-08T07:17:07.653",
"Id": "235273",
"ParentId": "235272",
"Score": "3"
}
},
{
"body": "<p>Apart from the performce issue, you should not call <code>available</code> at all, as it makes your code unnecessarily complicated. Instead, <code>read</code> into an <code>int</code> variable until the value gets <code>-1</code>, just like everyone else is doing this. You then need to add a <code>(char)</code> type cast to the <code>append</code> call.</p>\n\n<p>It's not necessary to create a new <code>StringBuilder</code> each time, you can just call <code>sbNumber.setLength(0)</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-08T07:35:27.963",
"Id": "235274",
"ParentId": "235272",
"Score": "3"
}
},
{
"body": "<p>Some more general things to consider. Your class is called <code>FileAnalyzer</code>, but it advertises public properties like <code>getPrimeNumbersCount</code>, which I'd consider to be part of the analysis result (rather than the analyser itself). Do they really belong there?</p>\n\n<p>There's a similar issue around the way that you're storing the file to be analysed in a field of the analyser. If a field isn't needed by at least two public member functions, I'd consider if it really needs to be a field or not. </p>\n\n<p><code>FileNotFoundException</code> extends <code>IOException</code>, so you don't really need to declare that a method throws both of them.</p>\n\n<p>Does the analyzer really need to be tied to an input file, or could it actually take in an <code>InputStream</code> as the source to analyse? This approach makes the analyser more flexible (it could be used to process numbers from an API call, or could simply process numbers from a <code>String</code> for testing purposes), and pushes the decision about what type of stream to construct up to the caller, where there may be more context about the information's source.</p>\n\n<p>Given those points, I'd expect the analyze function to have a signature more like:</p>\n\n<pre><code>NumericAnalysis analyze(InputStream streamToAnalyse) throws IOException\n</code></pre>\n\n<p>As it stands, your public <code>analyze</code> method immediately delegates out to a private <code>countNumbers</code>. You don't perform any signature adaption or anything else as part of this, so there doesn't really seem to be a reason for creating this extra layer of complexity. Why not just put the code straight into the <code>analyze</code> method?</p>\n\n<p>There's no validity checking when constructing a <code>BigInteger</code> when a <code>SEPERATOR</code> is encountered. This might be OK in your scenario because you're confident about the source of the data, however it's good to consider what you would expect the behaviour to be if for example there were two spaces between a pair of numbers / if a file started with a space before the first number.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-14T14:18:26.517",
"Id": "235612",
"ParentId": "235272",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "235273",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-08T07:12:26.123",
"Id": "235272",
"Score": "2",
"Tags": [
"java",
"performance",
"multithreading",
"file"
],
"Title": "Java file analyzer byte-by-byte"
}
|
235272
|
<p>let's say I want to create a 'utils' package with several functions
working on files and folders. I want to do it once properly so I can use
them in all my personal projects without feeling to re invent the wheel
each time.
I also want to learn 2 items by the way:</p>
<ul>
<li>exception handling, already read a lot about EAFP vs LBYL, I think the following function suits well to EAFP. </li>
<li>unit tests with pytest tool, it seems simple enough to start with.</li>
</ul>
<p>My function is:</p>
<pre class="lang-py prettyprint-override"><code>def removeanything(src):
"""
remove files or folders
"""
try:
os.remove(src)
print('File is removed')
except IsADirectoryError:
shutil.rmtree(src)
print('Folder is removed')
except FileNotFoundError:
print('File/folder is not existing')
except PermissionError:
print('Not allowed to suppress this file')
</code></pre>
<p>Do you have any comment to do regarding my exception handling? Did I forget one or more exceptions?</p>
<p>To go ahead, I have written this test function for pytest:</p>
<pre class="lang-py prettyprint-override"><code>from pathlib import Path
import utils
#import pytest
def test_removeanything(tmp_path):
d = tmp_path / '.tmp_dir'
d.mkdir()
f = d / '.tmp_file'
f.touch()
# Test permission
d.chmod(mode=0o555)
utils.removeanything(f)
assert Path.exists(f)
# Test file deletion
d.chmod(mode=0o777)
utils.removeanything(f)
assert not Path.exists(f)
# Test folder deletion
utils.removeanything(d)
assert not Path.exists(d)
</code></pre>
<p>As I am pretty newbie at testing, I would like to know if I include all reasonable things to assert for my function? Are there other way to do it more properly?
Is there a way to assert if expected error has been indeed raised by my function?</p>
<p>Thanks!</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-08T08:53:59.027",
"Id": "460378",
"Score": "0",
"body": "Just a general comment: I wouldn't make a function to remove files or directories, it may be dangerous. You can separate your function in two (or pass a flag) and make sure you will remove a file or a directory separately. I'm telling you this because I already had this problem. I removed an entire directory with results that took days to complete just because I passed the wrong path to a function like this one. Of course this is up to you, others may disagree."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-09T08:56:15.020",
"Id": "460544",
"Score": "0",
"body": "you can check the [tempfile](https://docs.python.org/3/library/tempfile.html#tempfile.TemporaryDirectory) module to make a temporary directory"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-09T09:23:54.970",
"Id": "460552",
"Score": "1",
"body": "I have rolled back your latest edit. 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><strong>Doc comments:</strong></p>\n\n<p>You can be more clear in the doc comment about what the function does:</p>\n\n<ul>\n<li>What is the input? (string, path)</li>\n<li>Does it return anything? (no)</li>\n<li>Does it throw exceptions? (yes, because <code>os.remove</code> and <code>shutil.rmtree</code> may throw)</li>\n<li>What is the state after calling the function? (file/folder has been removed, except if there was a permission error or another error)</li>\n</ul>\n\n<p><strong>Exceptions:</strong></p>\n\n<p>Someone who calls <code>removeanything(\"myfile\")</code> may expect that <code>myfile</code> does not exist anymore after the function call. However, in case of a permission error, it still does exist. I think this is an exceptional situation, so I recommend that you do not catch the <code>PermissionError</code> and instead propagate it to the caller.</p>\n\n<p><strong>Output:</strong></p>\n\n<p>Currently, the function communicates via print statements. This means that callers of the function have no way of finding out what actually happened. You could add a return value that indicates whether a file, a directory, or nothing was removed. Then you may think about removing the print statement, or enabling/disabling it via function argument, because users may want to remove files silently.</p>\n\n<p><strong>Tests:</strong></p>\n\n<p>It may be useful to separate the single test <code>test_removeanything</code> into multiple tests <code>test_removeanything_deletes_file</code>, <code>test_removeanything_deletes_directory</code>, <code>test_removeanything_handles_permission_error</code>. This way, if a test fails, the test name gives you some more information about what went wrong.</p>\n\n<p>Often, functions that remove directories require them to be non-empty. Therefore, it makes sense to test the removal of both empty and non-empty directories.</p>\n\n<p>If you change <code>removeanything</code> so that the <code>PermissionError</code> propagates to the user, you can use <code>pytest.raises</code> to test whether the exception was raised correctly.</p>\n\n<p><strong>Misc:</strong></p>\n\n<p>I think the name <code>removeanything</code> can be more specific. After all, the function does not remove a CD from my CD drive ;)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-08T12:44:47.660",
"Id": "460397",
"Score": "0",
"body": "Very detailed answer! Thanks, I will update my code this way, it sounds relevant."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-08T12:37:11.850",
"Id": "235288",
"ParentId": "235278",
"Score": "4"
}
},
{
"body": "<p>I have updated my code this way, using pytest.fixtures with temp file/folders provided by pytest.</p>\n\n<pre><code>from pathlib import Path\nimport os\nimport utils\nimport pytest\n\n@pytest.fixture\ndef fd(tmp_path):\n d = tmp_path / '.tmp_dir'\n d.mkdir()\n f = d / '.tmp_file'\n f.touch()\n return f,d\n\n# Test permission\ndef test_permissions(fd):\n with pytest.raises(PermissionError):\n f,d = fd\n d.chmod(mode=0o555)\n utils.removeanything(f)\n\n# Test file deletion\ndef test_delete_file(fd):\n f,d = fd\n utils.removeanything(f)\n assert not Path.exists(f)\n\n# Test non empty folder deletion\ndef test_delete_folder_nonempty(fd):\n f,d = fd\n utils.removeanything(d)\n assert not Path.exists(d)\n\n# Test empty folder deletion\ndef test_delete_folder_empty(fd):\n f,d = fd\n f.unlink()\n utils.removeanything(d)\n assert not Path.exists(d)\n</code></pre>\n\n<p>I have added other tests taking into account possiblke empty directory. Regarding test_permissions, a context manager tracks if error is well raised.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-09T09:33:53.620",
"Id": "235347",
"ParentId": "235278",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "235288",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-08T07:49:45.747",
"Id": "235278",
"Score": "5",
"Tags": [
"python",
"unit-testing"
],
"Title": "Test on remove function"
}
|
235278
|
<p>It's been about a day since I've started writing some Rust, and I'm looking for some code review on a simple spell checker I've written up</p>
<pre><code>use generator::{Gn, Generator, Scope, done};
use std::collections::{HashMap, HashSet};
use std::ops::Add;
use std::io::{BufRead, BufReader};
use std::fs::File;
#[derive(Debug)]
struct EditWord {
word: String,
editDistance: usize,
}
impl EditWord {
fn new(w: String, editDistance: usize) -> EditWord {
return EditWord { word: w, editDistance };
}
}
static ASCII_LOWER: [char; 26] = [
'a', 'b', 'c', 'd', 'e',
'f', 'g', 'h', 'i', 'j',
'k', 'l', 'm', 'n', 'o',
'p', 'q', 'r', 's', 't',
'u', 'v', 'w', 'x', 'y',
'z',
];
type Stream<'s, T> = Generator<'s, (), T>;
#[derive(Debug)]
pub struct WordDataSet {
counter: HashMap<String, usize>
}
impl<'a> From<Vec<&'a str>> for WordDataSet {
fn from(vec: Vec<&'a str>) -> Self {
let mut counter = HashMap::new();
for w in vec {
*counter.entry(w.to_string()).or_default() += 1;
}
return WordDataSet { counter };
}
}
impl WordDataSet {
pub fn prob(&self, word: &str) -> f64 {
if !self.counter.contains_key(word) {
return 0.0;
}
return *self.counter.get(word).unwrap() as f64 / self.counter.values().sum::<usize>() as f64;
}
fn exists(&self, word: &str) -> bool {
return self.counter.contains_key(word);
}
}
fn splits(w: &str) -> Vec<(&str, &str)> {
(0..=w.len()).map(|i| w.split_at(i)).collect()
}
pub struct SimpleCorrector {
data_set: WordDataSet
}
impl SimpleCorrector {
pub fn correct(&self, word: &str) -> Option<String> {
if self.data_set.exists(word) {
return Some(word.to_string());
}
edits(1, word)
.filter(|e| self.data_set.exists(&e.word))
.map(|e| ((1 / e.editDistance) as f64 * self.data_set.prob(&e.word), e.word))
.max_by(|(p1, w1), (p2, w2)| p1.partial_cmp(p2).expect("Tried to compare NAN"))
.map(|(p, w)| w)
}
}
fn edit1(w: &str) -> Stream<String> {
let pairs = splits(w);
let g = Gn::new_scoped(move |mut s| {
//deletes
for (a, b) in pairs.iter() {
let delete = format!("{}{}", a, b.get(1..).unwrap_or_default());
s.yield_(delete);
}
for (a, b) in pairs.iter() {
for c in ASCII_LOWER.iter() {
//replace
let replace = format!("{}{}{}", a, c, b.get(1..).unwrap_or_default());
s.yield_(replace);
//insert
let insert = format!("{}{}{}", a, c, b);
s.yield_(insert);
}
}
done!();
});
return g;
}
fn edits(n: usize, word: &str) -> Stream<EditWord> {
let g = Gn::new_scoped(move |mut s| {
let mut v = vec![word.to_string()];
let mut seen = HashSet::new();
seen.insert(word.to_string());
for i in 0..n {
let mut next_list = vec![];
for word in v {
for w in edit1(&word) {
if !seen.contains(&w) {
next_list.push(w.to_string());
seen.insert(w.to_string());
let editWord = EditWord::new(w.to_string(), i + 1);
s.yield_(editWord);
}
}
}
v = next_list;
}
done!();
});
return g;
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_word_prob() {
let data_set = WordDataSet::from(vec!["A", "B"]);
assert_eq!(data_set.prob("B"), 0.5)
}
#[test]
fn test_word_split() {
let word = "abc";
let word_splits = splits(word);
assert_eq!(word_splits, vec![("", "abc"),
("a", "bc"),
("ab", "c"),
("abc", "")])
}
#[test]
fn test_corrector_on_valid_word() {
let word = "ab";
let word_list = vec!["ab", "cd"];
let word_dataset = WordDataSet::from(word_list);
let s = SimpleCorrector { data_set: word_dataset };
let res = s.correct("ab");
dbg!(res);
}
#[test]
fn test_corrector_on_invalid_word() {
let test_word = "aa";
let word_list = vec!["ab", "cd"];
let word_dataset = WordDataSet::from(word_list);
let s = SimpleCorrector { data_set: word_dataset };
let res = s.correct(test_word);
assert_eq!(res.unwrap(), "ab");
}
}
</code></pre>
<p>Deps:</p>
<pre><code>
[dependencies]
generator = "0.6.19"
</code></pre>
<p>I've got to add more tests to test the logic again, but so far I think it's alright. I'm mainly looking for pointers on how I can exploit the type system better, and how to write shorter, ergonomic code. </p>
<p>I'm quite sure the <code>.to_string()</code> calls in the <code>edits</code> function can be reduced, but not sure how. </p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-08T14:47:28.973",
"Id": "460406",
"Score": "0",
"body": "@Shepmaster, done, thanks!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-08T15:48:23.333",
"Id": "460417",
"Score": "0",
"body": "@Shepmaster, whoops that was just an extraneous artifiact from before -- removed it"
}
] |
[
{
"body": "<h3>First thoughts</h3>\n\n<ol>\n<li><p><strong>Read and act on</strong> the warnings provided by the compiler. That's one of the biggest points of a compiled language. Do not ignore the <strong>10+</strong> warnings. You have a ton of unused imports, unused variables, and non-idiomatic variable names.</p></li>\n<li><p>Run <a href=\"https://github.com/rust-lang-nursery/rustfmt\" rel=\"nofollow noreferrer\">Rustfmt</a>, a tool for automatically formatting Rust code to the community-accepted style.</p></li>\n<li><p>Run <a href=\"https://github.com/rust-lang-nursery/rust-clippy\" rel=\"nofollow noreferrer\">Clippy</a>, a tool for finding common mistakes that may not be compilation errors but are unlikely to be what the programmer intended. This points out that almost all of your uses of <code>return</code> are non-idiomatic.</p></li>\n</ol>\n\n<h3><code>impl EditWord</code></h3>\n\n<ol>\n<li>Don't abbreviate the argument <code>w</code>; call it <code>word</code> and use the struct shorthand syntax.</li>\n</ol>\n\n<h3><code>impl<'a> From<Vec<&'a str>> for WordDataSet</code></h3>\n\n<ol>\n<li><p>There's no obvious reason to require a <code>Vec</code>. This could equally be <code>FromIterator</code>.</p></li>\n<li><p>The required conversion to <code>String</code> is unfortunate. <a href=\"https://stackoverflow.com/q/51542024/155423\">How do I use the Entry API with an expensive key that is only constructed if the Entry is Vacant?</a> talks about a future solution. Also, you could avoid allocation completely here by storing the string slices instead. </p></li>\n</ol>\n\n<h3><code>impl WordDataSet</code></h3>\n\n<ol>\n<li><p>Don't look up in a map twice. Instead, use <code>get</code> once and work with the <code>Option</code>.</p></li>\n<li><p>Using <code>as</code> is dubious for integer <-> floating point conversions. It's better to use <code>TryFrom</code> and panic instead. See <a href=\"https://stackoverflow.com/q/28273169/155423\">How do I convert between numeric types safely and idiomatically?</a> for more details.</p></li>\n</ol>\n\n<h3><code>fn splits</code></h3>\n\n<ol>\n<li>This doesn't need to return a <code>Vec</code> as you only iterate over it. You can return an iterator instead. In this case, you also need to make it <code>Clone</code> so that you can use it twice in <code>edit1</code>, but you could probably iterate just once or call <code>splits</code> twice, as it's cheap. See <a href=\"https://stackoverflow.com/q/27535289/155423\">What is the correct way to return an Iterator (or any other trait)?</a>.</li>\n</ol>\n\n<h3><code>impl SimpleCorrector</code></h3>\n\n<ol>\n<li>Instead of always returning a <code>String</code>, you could return a <code>Cow<str></code>. This would avoid allocation when the word is correctly spelled.</li>\n</ol>\n\n<h3><code>fn edit1</code></h3>\n\n<ol>\n<li>It's more common to use <code>&collection</code> than <code>collection.iter()</code>.</li>\n</ol>\n\n<h3><code>fn test_corrector_on_valid_word</code></h3>\n\n<ol>\n<li>This has no assertions.</li>\n</ol>\n\n<h3><code>fn test_corrector_on_invalid_word</code></h3>\n\n<ol>\n<li>I avoid using <code>unwrap</code> whenever possible. It's fine in tests, but I still try.</li>\n</ol>\n\n<h3>General</h3>\n\n<ol>\n<li><p>From an outside API, it's not clear what benefit there is to exposing both <code>WordDataSet</code> and <code>SimpleCorrector</code>. Perhaps the API should be restricted to one.</p></li>\n<li><p>I'm not excited about the <code>generator</code> crate. This may just be ignorance on my part, but I'd probably strive to use standard iterator techniques until Rust gains stable first-class support for generators</p></li>\n</ol>\n\n<pre class=\"lang-rust prettyprint-override\"><code>use generator::{done, Generator, Gn};\nuse std::{\n collections::{HashMap, HashSet},\n iter::FromIterator,\n};\n\n#[derive(Debug)]\nstruct EditWord {\n word: String,\n edit_distance: usize,\n}\n\nimpl EditWord {\n fn new(word: String, edit_distance: usize) -> EditWord {\n EditWord {\n word,\n edit_distance,\n }\n }\n}\n\nstatic ASCII_LOWER: [char; 26] = [\n 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's',\n 't', 'u', 'v', 'w', 'x', 'y', 'z',\n];\n\ntype Stream<'s, T> = Generator<'s, (), T>;\n\n#[derive(Debug)]\npub struct WordDataSet {\n counter: HashMap<String, usize>,\n}\n\nimpl<'a> FromIterator<&'a str> for WordDataSet {\n fn from_iter<I>(words: I) -> Self\n where\n I: IntoIterator<Item = &'a str>,\n {\n let mut counter = HashMap::new();\n for w in words {\n *counter.entry(w.to_string()).or_default() += 1;\n }\n WordDataSet { counter }\n }\n}\n\nimpl WordDataSet {\n pub fn prob(&self, word: &str) -> f64 {\n self.counter.get(word).map_or(0.0, |&c| {\n let sum: usize = self.counter.values().sum();\n c as f64 / sum as f64\n })\n }\n\n fn exists(&self, word: &str) -> bool {\n self.counter.contains_key(word)\n }\n}\n\nfn splits(w: &str) -> impl Iterator<Item = (&str, &str)> + Clone {\n (0..=w.len()).map(move |i| w.split_at(i))\n}\n\npub struct SimpleCorrector {\n data_set: WordDataSet,\n}\n\nimpl SimpleCorrector {\n pub fn correct(&self, word: &str) -> Option<String> {\n if self.data_set.exists(word) {\n return Some(word.to_string());\n }\n\n edits(1, word)\n .filter(|e| self.data_set.exists(&e.word))\n .map(|e| {\n (\n (1 / e.edit_distance) as f64 * self.data_set.prob(&e.word),\n e.word,\n )\n })\n .max_by(|(p1, _w1), (p2, _w2)| p1.partial_cmp(p2).expect(\"Tried to compare NAN\"))\n .map(|(_p, w)| w)\n }\n}\n\nfn edit1(w: &str) -> Stream<String> {\n let pairs = splits(w);\n Gn::new_scoped(move |mut s| {\n //deletes\n for (a, b) in pairs.clone() {\n let delete = format!(\"{}{}\", a, b.get(1..).unwrap_or_default());\n s.yield_(delete);\n }\n\n for (a, b) in pairs {\n for c in &ASCII_LOWER {\n //replace\n let replace = format!(\"{}{}{}\", a, c, b.get(1..).unwrap_or_default());\n s.yield_(replace);\n\n //insert\n let insert = format!(\"{}{}{}\", a, c, b);\n s.yield_(insert);\n }\n }\n\n done!();\n })\n}\n\nfn edits(n: usize, word: &str) -> Stream<EditWord> {\n Gn::new_scoped(move |mut s| {\n let mut v = vec![word.to_string()];\n let mut seen = HashSet::new();\n seen.insert(word.to_string());\n for i in 0..n {\n let mut next_list = vec![];\n for word in v {\n for w in edit1(&word) {\n if !seen.contains(&w) {\n next_list.push(w.to_string());\n seen.insert(w.to_string());\n let edit_word = EditWord::new(w.to_string(), i + 1);\n s.yield_(edit_word);\n }\n }\n }\n v = next_list;\n }\n done!();\n })\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n\n #[test]\n fn test_word_prob() {\n let data_set = WordDataSet::from_iter(vec![\"A\", \"B\"]);\n assert_eq!(data_set.prob(\"B\"), 0.5)\n }\n\n #[test]\n fn test_word_split() {\n let word = \"abc\";\n let word_splits = splits(word).collect::<Vec<_>>();\n assert_eq!(\n word_splits,\n vec![(\"\", \"abc\"), (\"a\", \"bc\"), (\"ab\", \"c\"), (\"abc\", \"\")]\n )\n }\n\n #[test]\n fn test_corrector_on_valid_word() {\n let word_list = vec![\"ab\", \"cd\"];\n let data_set = WordDataSet::from_iter(word_list);\n let s = SimpleCorrector { data_set };\n let res = s.correct(\"ab\");\n dbg!(res);\n }\n\n #[test]\n fn test_corrector_on_invalid_word() {\n let test_word = \"aa\";\n let word_list = vec![\"ab\", \"cd\"];\n let data_set = WordDataSet::from_iter(word_list);\n let s = SimpleCorrector { data_set };\n let res = s.correct(test_word);\n assert_eq!(res.as_deref(), Some(\"ab\"));\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-10T18:09:25.337",
"Id": "460794",
"Score": "0",
"body": "super helpful, thank you!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-08T17:13:56.687",
"Id": "235308",
"ParentId": "235279",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "235308",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-08T08:53:49.223",
"Id": "235279",
"Score": "4",
"Tags": [
"algorithm",
"rust"
],
"Title": "Rust Spelling corrector"
}
|
235279
|
<p>I have a Web API application in .NET Core 3.1. In a controller I have a GET action that must return a JSON object with a name and a description. In order to retrieve the correct description I need to call an external API (not implemented by myself and outside of my control). This is the code in the controller:</p>
<pre><code>public async Task<ActionResult<Models.Result>> Get(string name)
{
try
{
var objectWrapper = await _clientService.GetObjectAsync(name.ToLowerInvariant());
//Other logic here....
return Ok(new Models.Result { Name = name, Description = objectWrapper.Description} );
}
catch (Exception ex)
{
_logger.LogError($"Failed to get object {name}: {ex}");
if (ex is ApiCallFailedException apiCallEx)
return StatusCode((int)apiCallEx.HttpStatusCode);
return BadRequest($"Failed to get object {name}");
}
}
</code></pre>
<p>The <code>_clientService</code> is the service responsible for the call to the external API:</p>
<pre><code>public async Task<ObjectDto> GetObjectAsync(string name)
{
var objectWrapper = new ObjectDto();
var request = new HttpRequestMessage(HttpMethod.Get, $"object/{name}/");
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
using (var response = await _client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead))
{
if (response.IsSuccessStatusCode)
{
objectWrapper = await response.Content.ReadAsAsync<ObjectDto>();
}
else
{
throw new ApiCallFailedException(response.StatusCode);
}
}
return objectWrapper;
}
</code></pre>
<p>Therefore, I created a custom exception class <code>ApiCallFailedException</code> to handle not successful status codes returned by the external API in order to be able to catch it in my controller action.
In the controller action, in caso of not successful status codes from the external API, I decided to return the same status code. </p>
<p>My question is: <strong>is this approach correct to handle external API call failure?</strong></p>
<p>Thank you!</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-08T10:49:37.660",
"Id": "460386",
"Score": "0",
"body": "Welcome to Code Review! The current question title, which states your concerns about the code, is too general to be useful here. Please [edit] to the site standard, which is for the title to simply state **the task accomplished by the code**. Please see [How to get the best value out of Code Review: Asking Questions](//codereview.meta.stackexchange.com/q/2436) for guidance on writing good question titles."
}
] |
[
{
"body": "<p>I have only 2 things to note.</p>\n\n<ol>\n<li><p>Returning the same status code as the remote server could lead to confused clients of your API due to incorrect status codes. What if the remote server has returns a 5xx status code? Your server didn't have an internal server error, the remote did, but then why is your server returning a 5xx status code?</p>\n\n<p>Instead, I recommend replacing it with returning a fixed status code (or something depending on the status code the remote API returned). The method name is <code>Get</code>, so I'd go with a <code>404 Not Found</code>.</p></li>\n<li><p>Use attributes. In ASP.NET and ASP.NET Core the runtime can figure out which method to call by the http method and the name of it (call <code>Get</code> when an http get request comes, <code>Post</code> when a post comes etc), but it would be a lot more obvious not only for the runtime but also for developers if you named your methods a good name (e.g <code>GetName</code>) and decorate it with attributes specifying the route and the http request method to respond to.</p>\n\n<p>Plus, you could also do yourself and any future developer a favor by specifying where the parameter to the method comes from. Right now it's part of the URI string (also called query parameters), but other methods might accept JSON to deserialize, you can do this by adding an attribute to the parameter. More about it <a href=\"https://docs.microsoft.com/en-us/aspnet/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api\" rel=\"nofollow noreferrer\">here</a>.</p></li>\n</ol>\n\n<p>Putting number 2 into code:</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>[Route(\"Result/GetName\")]\n[HttpGet]\npublic async Task<ActionResult<Models.Result>> GetName([FromUri] string name) \n{\n // ...\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-08T12:50:21.647",
"Id": "460398",
"Score": "0",
"body": "Thank you for the tips! In particular, I can consider point 1 as an answer to my doubts and return 404 if something went worng in calling the external API."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-08T12:23:01.437",
"Id": "235286",
"ParentId": "235283",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "235286",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-08T10:36:26.783",
"Id": "235283",
"Score": "2",
"Tags": [
"c#",
"asp.net-web-api",
"asp.net-core"
],
"Title": "Handling external API calls status code in my application"
}
|
235283
|
<p>I repost my question here because it has been closed on stack overflow</p>
<p>This question could sound stupid but I am new to the logging, displaying and handling exceptions.
Because before I was just doing a big try catch (Exception ex) to get exceptions (test softwares)</p>
<p>But now I am doing a "real" software, which will have a public release.
And I am asking what is the right way of doing those things.</p>
<p>I am using WPF with the .NET Framework 4.7.2, and i'm also using NLog</p>
<p>For now, I did a little code, and I am just asking like a review / advices.
I put that code at startup, so in the app.xaml.cs with a protected override OnStartup()</p>
<pre class="lang-cs prettyprint-override"><code>using System;
using System.IO;
using System.Windows;
using WPFTemplate.Classes;
using WPFTemplate.Classes.Core;
namespace WPFTemplate {
public partial class App : Application {
/// <summary>
/// Logger
/// </summary>
private static readonly NLog.Logger Log = NLog.LogManager.GetCurrentClassLogger();
/// <summary>
/// Application starting point
/// </summary>
protected override void OnStartup(StartupEventArgs e) {
// ---- Application
// -- Directory
try {
// Create application main directory
Directory.CreateDirectory(Reference.AppPath);
} catch (Exception ex) {
// Log
Log.Error(ex);
// The path isn't valid/found (ex: with network name)
if (ex is DirectoryNotFoundException || ex is IOException || ex is NotSupportedException) {
MessageBox.Show(string.Format("The application path '{0}' isn't valid..\nPlease check if the path is valid", Reference.AppPath), Reference.AppName, MessageBoxButton.OK, MessageBoxImage.Error);
}
// The user hasn't the permission to write (then need to run the application as administrator)
else if (ex is UnauthorizedAccessException) {
MessageBox.Show(string.Format("The application hasn't the right to write data in the application path '{0}'..\nPlease start the application as administrator", Reference.AppPath), Reference.AppName, MessageBoxButton.OK, MessageBoxImage.Error);
}
// Path is too long (max: 256 chars)
else if (ex is PathTooLongException) {
MessageBox.Show(string.Format("The application path '{0}' is too long..\nPlease install the application in another place", Reference.AppPath), Reference.AppName, MessageBoxButton.OK, MessageBoxImage.Error);
}
// Shutdown
Application.Current.Shutdown();
}
}
protected override void OnExit(ExitEventArgs e) {
// -- Logs
Log.Info("Stopping the application");
NLog.LogManager.Shutdown();
}
}
}
</code></pre>
<p>I did a custom message for every exceptions, and it's a little bit long</p>
<p>So i'm waiting for your reviews/advices and thanks a lot i'm still a beginner in that x)</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-08T17:58:41.013",
"Id": "460444",
"Score": "0",
"body": "In C# a Try/Catch block will be withing a function, and the function will be within a class. To get any review you need to provide the entire function, and to get a good review you should provide the entire class. This question is currently off-topic because there is not enough code presented."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-08T18:15:10.977",
"Id": "460448",
"Score": "1",
"body": "I edited the code"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-09T11:25:36.973",
"Id": "460568",
"Score": "0",
"body": "If you want to catch all Exceptions, you should take a look here\nhttps://stackoverflow.com/a/1472562/4961688\nor here\nhttps://stackoverflow.com/a/46804709/4961688"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-10T14:23:36.863",
"Id": "460756",
"Score": "0",
"body": "Avoid coding in the code-behind and instead implement MVVM when working with WPF. Here you've written 30/40 lines merely to configure the location of the log files; imagine how complicated things will become when you need to implement actual business logic in your app."
}
] |
[
{
"body": "<p>Remove logs from Starup.cs and add the logging into every method.</p>\n\n<p>You can override the onException method, where you can write your own customized message and exception</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-10T12:02:38.970",
"Id": "235411",
"ParentId": "235285",
"Score": "0"
}
},
{
"body": "<p>The main reason for exceptions (from a developer point of view) is to detect malfunctioning code. Because once this malfunctioning code is executed, the result of an operation and therefore the state of an application can be considered as undefined, since unexpected/unpredictable side effects will transition the application to an unpredictable state. </p>\n\n<p>Data might be in an unpredictable state i.e. data integrity is not guaranteed any more. Unmanaged resources might be initialized or reserved but not released, which may even affect other applications. So most of the time you want the application to stop execution to avoid unpredictable behavior. </p>\n\n<p>Exceptions are designed to hold a program. They are controlled on OS level so that Operating System can stop the application and also provide a snapshot from the stack memory, that was occupied by the faulting application.</p>\n\n<p>We can say that there are expected errors e.g., not enough disk space to save a file or wrong user credentials and there are unexpected errors e.g. a null reference exception.\nSo if the application could recover/rollback from an error, this error will be an expected error. You know in advance what can fail and you know how to handle this situation to keep the application operating reliably. You preferably would want to handle such errors \"silently\", without throwing exceptions, as exceptions have impact on application performance and therefore user experience.<br>\nYou also don't want the exception to propagate through your complete application, which is expensive in terms of performance. Therefore you would like to handle it directly where the exception occurred. This implies that you better don't handle exceptions in a big catch block around your application. You always catch exceptions where they occur. This is a best practice for the reasons explained. </p>\n\n<p>It's also best practice to use multiple catch blocks and catch specific exceptions only. This way your code becomes more readable. Specific exceptions are those and only those you can handle. And <em>logging</em> is not considered <em>handling</em> (if this exception is not relevant you should have avoided it in the first place). Every other exception must be thrown as they are unexpected or have heavy impact on the stability (predictability) of the application.</p>\n\n<p>This means catching <code>Exception</code>, like it is happening in your code, is a very bad idea:</p>\n\n<pre><code>try \n{\n // Create application main directory\n Directory.CreateDirectory(Reference.AppPath);\n} \ncatch (Exception ex) // Bad: this will swallow every exception although unhandled by this catch block\n{\n Log.Error(ex);\n\n if (ex is DirectoryNotFoundException || ex is IOException || ex is NotSupportedException) \n {\n MessageBox.Show(\"Error\");\n }\n}\n</code></pre>\n\n<p><em>Bad exception handling as all exceptions are swallowed. Logging an exception is not handling an exception.</em></p>\n\n<p>What is happening here, is that <em>all</em> exceptions are swallowed. Especially those that are critical to the application. By catching <code>Exception</code> you basically handle <em>every</em> exception. Catching <code>Exception</code> at application level makes it even worse: a <code>NullReferenceException</code> will <em>never</em> see the light. A <code>IndexOutOfRangeException</code> will <em>never</em> get attention too, as you didn't even re-throw anything (re-throwing an exception is also generally considered as bad practice). A <code>NullReferenceException</code> must crash your application and requires the developer's full attention. If <code>Reference.AppPath</code> throws a <code>NullReferenceException</code> because <code>Reference</code> or <code>AppPath</code> is <code>null</code> we will never notice it without consulting any log file. </p>\n\n<p>In real life, nobody is reading log files. Every developer avoids it. And for sure, nobody reads them daily to check if any of the hundreds of customers experienced a critical runtime error. Indeed, it's an uncomfortable situation when a customer experiences an application crash, but at least it will draw everybody's attention to look for an immediate fix. An application error reporter can be a very powerful enhancement to provide quick and proper bug support.<br>\nNevertheless log files can be a very valuable support to reproduce and find bugs. </p>\n\n<p>Also, exceptions of the same type might get thrown at different code segments in a totally different context. A global exception handler will have a hard time to get the context of the exception to find out if <code>NotSupportedException</code> was thrown in context of a invalid user input (recoverable error) or a wrong call to an API method (non-recoverable). </p>\n\n<p>To solve the issue of swallowing exceptions, you have to get rid of the smelly <code>switch</code> statement, which already indicates that you are doing something \"wrong\". Type checking in a <code>switch</code> statement (or ugly and unreadable if-else constructs) is a classic code smell. </p>\n\n<p>The goal is to handle exceptions that are non-critical i.e. the application can recover from and leave every other exception unhandled:</p>\n\n<pre><code>try \n{\n // Create application main directory\n Directory.CreateDirectory(Reference.AppPath);\n} \ncatch (DirectoryNotFoundException ex) \n{\n // Log\n Log.Error(ex);\n\n MessageBox.Show(\"Error\");\n}\ncatch (UnauthorizedAccessException ex) \n{\n // Log\n Log.Error(ex);\n\n MessageBox.Show(\"Error\");\n}\n</code></pre>\n\n<p>Now, any developer that comes across this code knows immediately what is going on here. The code has become more readable and the ugly and smelly <code>switch</code> was successfully eliminated. But more important, every unhandled exception will still crash the app, to indicate a critical bug. If <code>Reference.AppPath</code> throws a <code>NullReferenceException</code> we will now notice it first hand this time, without the need of consulting any log file. </p>\n\n<p><em>Don't catch what you can't handle.</em></p>\n\n<p>If you wish to log unhandled exceptions, instead subscribe to the <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.windows.application.dispatcherunhandledexception?view=netframework-4.8\" rel=\"nofollow noreferrer\"><code>Application.DispatcherUnhandled</code></a> event:</p>\n\n<pre><code>public partial class App : Application\n{\n public App()\n {\n this.DispatcherUnhandledException += (sender, args) => this.logger.Error(args.Exception.Message);\n }\n}\n</code></pre>\n\n<hr>\n\n<h2>Free Resources</h2>\n\n<p>As a note: it's best practice to take care of managed/unmanaged resources and use finalizers i.e. <code>finally</code> or <code>using</code> blocks, to make sure that these resources are released i.e. disposed properly under any circumstances before letting the application crash.</p>\n\n<p>In case the following code throws an exception, the <code>using</code> statement will execute a finalizer <em>before</em> the forced exit:</p>\n\n<pre><code>using (var sqlConnection = new SqlConnection(args))\n{\n sqlConnection.ExecuteQuery(queryArgs);\n}\n</code></pre>\n\n<p>This is equal to:</p>\n\n<pre><code>try\n{\n var sqlConnection = new SqlConnection(args);\n sqlConnection.ExecuteQuery(queryArgs);\n}\nfinally\n{\n sqlConnection.Dispose();\n}\n</code></pre>\n\n<p>Both implementations won't handle the critical exception, but will release unmanaged resources before the method is put on hold and the exception routing is executed by the OS.</p>\n\n<h2>Re-throwing Exceptions</h2>\n\n<p>Although re-throwing exceptions is considered bad practice, it makes sense if you need to add data to the exception or like to throw a more specialized maybe custom exception type. But make sure to keep the stack trace intact.</p>\n\n<p>Bad re-throw as it will break the stack trace:</p>\n\n<pre><code>try \n{\n // Create application main directory\n Directory.CreateDirectory(Reference.AppPath);\n} \ncatch (DirectoryNotFoundException directoryNotFoundException) \n{\n Log.Error(directoryNotFoundException);\n\n // The previous stack trace of 'directoryNotFoundException' will be lost\n throw new UnknownUserInputException(\"Custom Message\");\n}\n</code></pre>\n\n<p>Good re-throw as it will preserve the full stack trace by setting<br>\nthe original exception as inner exception of the wrapping exception type:</p>\n\n<pre><code>try \n{\n // Create application main directory\n Directory.CreateDirectory(Reference.AppPath);\n} \ncatch (DirectoryNotFoundException directoryNotFoundException) \n{\n Log.Error(directoryNotFoundException);\n\n // Use constructor to set inner exception\n throw new UnknownUserInputException(\"Custom Message\", directoryNotFoundException);\n}\n</code></pre>\n\n<h2>Avoiding Exceptions in the First Place</h2>\n\n<p>Microsoft best practices <a href=\"https://docs.microsoft.com/en-us/dotnet/standard/exceptions/best-practices-for-exceptions?view=netframework-4.8#design-classes-so-that-exceptions-can-be-avoided\" rel=\"nofollow noreferrer\">recommends</a> to <em>\"Design classes so that exceptions can be avoided\"</em>.<br>\nThis is especially true for user input, since this are always errors we can recover from. In general, data input whether the source is a user or a client application, can be validated <em>before</em> it enters the application. The goal is to have the application to deal with valid data only. The logic should not process invalid data and throw an exception. The data persistence layers should never persist invalid data. </p>\n\n<p>To prevent invalid data from being processed, you would typically use a form of data validation. In case of a WPF application, which is what you are implementing, I highly recommend to apply the <em>MVVM</em> pattern and implement the <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.componentmodel.inotifydataerrorinfo?view=netframework-4.8\" rel=\"nofollow noreferrer\"><code>INotifyDataErrorInfo</code></a> interface (<a href=\"https://stackoverflow.com/a/56608064/3141792\">example</a>) which is part of the WPF framework and enables error propagation to the UI to provide a visual feedback. If the user enters an invalid file path you can easily make the UI draw e.g. a red border around the concerning input field, with messages or hints, forcing the user to correct the input. </p>\n\n<p>In this special scenario of picking a file or folder, the best way is to use a file or folder picker dialog. This way, invalid filesystem path inputs are almost impossible.</p>\n\n<p>Another example is file saving. Before saving a file, you can check whether the operation can be executed by checking the available disk space to avoid I/O exceptions.</p>\n\n<p>Almost all expected exceptions can be avoided by checking the preconditions before executing a critical operation.</p>\n\n<hr>\n\n<p><strong>The bottom line is</strong>, that you should never catch <code>Exception</code>. Swallowing exceptions is dangerous as it will conceal serious bugs. To log an exception is <em>not</em> handling an exception. Logging an exception and done is equal to swallowing it, as you can't be sure somebody will ever read the log data or search it for random errors.<br>\nIf you wish to log all unhandled exceptions by default, subscribe to the <code>Application.DispatcherUnhandledException</code> event, but <em>never</em> use a global catch block at application level.<br>\nEspecially in your case where the errors or exceptions are triggered by invalid user input, you are advised to use data validation. This makes exception handling obsolete and is the preferred way. User input validation e.g., by implementing <code>INotifyDataErrorInfo</code>, includes a convenient way to give the user feedback and prompt him to correct the input.<br>\nIn case the exception is not critical, in a away that it requires the application to halt, consider to roll it back to a defined state before continuing execution in order to prevent dirty data or undefined states.<br>\nDon't forget to free resources using a <code>finally</code> or <code>using</code> block to properly close/dispose those objects.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-07T17:09:51.357",
"Id": "464272",
"Score": "0",
"body": "Thank you for your response! It really helps me a lot! I will follow your advice ;) Thanks again and have a nice evening!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-02T10:09:38.783",
"Id": "236525",
"ParentId": "235285",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "236525",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-08T11:51:45.817",
"Id": "235285",
"Score": "2",
"Tags": [
"c#",
"error-handling",
"wpf"
],
"Title": "Right way to handle, log and display exceptions"
}
|
235285
|
<p>I have this function </p>
<pre><code> const rank = (totalPoints, pointsRank) => {
if (totalPoints <= pointsRank[0]) {
return ({
rank: 1,
pointsLeftForNextRank: (pointsRank[1] - totalPoints)
})
} else if (totalPoints >= pointsRank[1] && totalPoints < pointsRank[2]) {
return ({
rank: 2,
pointsLeftForNextRank: (pointsRank[2] - totalPoints)
})
} else if (totalPoints >= pointsRank[2] && totalPoints < pointsRank[3]) {
return ({
rank: 3,
pointsLeftForNextRank: (pointsRank[3] - totalPoints)
})
} else if (totalPoints >= pointsRank[3] && totalPoints < pointsRank[4]) {
return ({
rank: 4,
pointsLeftForNextRank: (pointsRank[4] - totalPoints)
})
} else if (totalPoints >= pointsRank[4] && totalPoints < pointsRank[5]) {
return ({
rank: 5,
pointsLeftForNextRank: (pointsRank[5] - totalPoints)
})
} else if (totalPoints >= pointsRank[5] && totalPoints < pointsRank[6]) {
return ({
rank: 6,
pointsLeftForNextRank: (pointsRank[6] - totalPoints)
})
} else if (totalPoints >= pointsRank[6]) {
return ({
rank: 7,
pointsLeftForNextRank: 0
})
}
}
module.exports = rank
</code></pre>
<p>and I call it like this</p>
<pre><code> let pointsRank = [150, 500, 1000, 2000, 3500, 5000, 5500]
let totalPoints = 1200
rank(totalPoints, pointsRank)
</code></pre>
<p>output</p>
<pre><code>{ rank: 3, pointsLeftForNextRank: 600 }
</code></pre>
<p>how can I improve this function? I feel like that I wrote a lot of code which can be refactored into something smaller<br>
like a small amount of code that does the same functionality
also, I need to know if am violating any of the SOLID principles </p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-08T13:06:49.390",
"Id": "460399",
"Score": "0",
"body": "You can use `loop (for/while)` with `break` to achieve the same"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-08T16:44:23.537",
"Id": "460427",
"Score": "1",
"body": "This question lacks any indication of what the code is intended to achieve. To help reviewers give you better answers, please add sufficient context to your question, including a title that summarises the *purpose* of the code. We want to know **why** much more than **how**. The more you tell us about [what your code is for](//meta.codereview.stackexchange.com/q/1226), the easier it will be for reviewers to help you. The title needs an [edit] to simply [**state the task**](//meta.codereview.stackexchange.com/q/2436)."
}
] |
[
{
"body": "<p>Basically we search for the most close number from array where our number belongs. After we find the min value, we take the index of it and add 1, because the rank starts from 1</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>//rank 1 : 150 - 500\n//rank 2 : 500 - 1000\n//rank 3 : 1000 - 2000\n//rank 4 : 2000 - 3500\n//rank 5 : 3500 - 5000\n//rank 6 : 5000 - 5500\n\nlet pointsRank = [150, 500, 1000, 2000, 3500, 5000, 5500]\n\nfunction rank(pointsRank, score) {\n var closest = pointsRank.reduce(function(prev, curr) {\n return (Math.abs(curr - score) < Math.abs(prev - score) ? curr : prev);\n });\n var rank = pointsRank.indexOf(closest) + 1; // cuz starts from 0 and we don't have rank 0\n console.log(\"min range: \" + closest +\n \" | our score: \" + score +\n \" | max range: \" + pointsRank[rank])\n\n return {\n rank: rank,\n pointsLeftForNextRank: (pointsRank[rank] - score)\n }\n\n}\n\nconst test1 = rank(pointsRank, 1200);\nconst test2 = rank(pointsRank, 2000);\nconst test3 = rank(pointsRank, 3700);\n\nconsole.log(test1);\nconsole.log(test2);\nconsole.log(test3);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-08T16:43:54.413",
"Id": "460426",
"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": "2020-01-08T15:20:02.133",
"Id": "235301",
"ParentId": "235287",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "235301",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-08T12:32:11.147",
"Id": "235287",
"Score": "0",
"Tags": [
"javascript"
],
"Title": "Javascript refactor if condition function"
}
|
235287
|
<pre><code>mails = []
mails.concat(@note.cc_emails) unless @note.cc_emails.nil?
mails.concat(@note.to_emails) unless @note.to_emails.nil?
</code></pre>
<p>Everything what I'm doing here is checking is @note.cc_emails is not nil then concatenating it in mails array.
How can I write it in more efficient way & also reduce the number of lines in the code (if possible)?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-08T16:46:26.470",
"Id": "460428",
"Score": "0",
"body": "Welcome to Code Review! Please edit your question so that the title describes the *purpose* of the code, rather than its *mechanism*. We really need to understand the motivational context to give good reviews. Thanks!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-09T14:14:09.980",
"Id": "460591",
"Score": "1",
"body": "Welcome to Code Review! this is a small set of code, and there isn't much to what is being done here. if you give us more to work with, like the purpose of this piece of code and how it relates to other code in your application (posting that code as well) we will likely be able to give you a better review. Once your question has been edited we will evaluate it to be reopened. right now there isn't enough here to review."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-10T11:12:27.783",
"Id": "460736",
"Score": "0",
"body": "If you don't mind creating a new array you can use the splat operator `*`. If you splat a `nil` value it simply disappears `[*nil] #=> []`. With this in mind you could do `mails = [*@note.cc_emails, *@note.to_emails]`. Another option is making sure `cc_emails` and `to_emails` are always set and are at least an empty array."
}
] |
[
{
"body": "<p>These things are very much a matter of preference but I would go for something like:</p>\n\n<pre><code>mails = [ @note.cc_emails,\n @note.to_emails ].compact.join('')\n</code></pre>\n\n<p>which tends to remain usable as you add more clauses</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-10T09:27:56.710",
"Id": "460728",
"Score": "0",
"body": "should add `.flatten()` before `compact()`. It looks like `cc_emails` and `to_emails` are arrays"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-09T01:15:47.343",
"Id": "235330",
"ParentId": "235291",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-08T14:08:18.750",
"Id": "235291",
"Score": "1",
"Tags": [
"ruby"
],
"Title": "Concatenate unless note"
}
|
235291
|
<p>I am making a quiz game and every time you complete a stage, the next stage will be unlocked. </p>
<p><strong>The Problem:</strong>
When I am at Stage 3 and finish it, Stage 4 is unlocked. But when I feel like I want to play stage 1 again and finish it, the unlocked stage reverts to only Stage 2.</p>
<p><strong>The Code:</strong></p>
<pre class="lang-java prettyprint-override"><code>
protected void stageCompleted(){
//If the stage is completed unlock the next stage
if(10-correctAnswers<=mistakesAllowed){
SharedPreferences sharedPref = mContext.getSharedPreferences("saves",Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt("completeStages", stageNumber+1);
editor.commit();
}
</code></pre>
<p><strong>And here is my Stages List.java file:</strong></p>
<pre class="lang-java prettyprint-override"><code>public class StagesActivity extends AppCompatActivity {
List<Stage> stageList=new ArrayList<Stage>();
Button backBtn;
SharedPreferences.OnSharedPreferenceChangeListener onPrefsChangeListener;
private ListView stagesListView;
SharedPreferences sharedPref ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_stages);
sharedPref = StagesActivity.this.getSharedPreferences("saves",Context.MODE_PRIVATE);
stagesListView=findViewById(R.id.stages_list_view);
backBtn=findViewById(R.id.back_btn);
backBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
finish();
}
});
initListView();
onPrefsChangeListener=new SharedPreferences.OnSharedPreferenceChangeListener() {
@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String s) {
initListView();
}
};
sharedPref.registerOnSharedPreferenceChangeListener(onPrefsChangeListener);
}
public void initListView(){
JSONTools.readFileWithStages(StagesActivity.this,stageList);
int completeStages=sharedPref.getInt("completeStages",0);
Log.d("COMPLETED","COM:"+completeStages);
for(int i=0;i<stageList.size();i++){
if(completeStages>=i)
stageList.get(i).setEnabled(true);
}
StagesListAdapter adapter = new StagesListAdapter(StagesActivity.this,stageList);
stagesListView.setAdapter(adapter);
}
@Override
protected void onDestroy() {
super.onDestroy();
sharedPref.unregisterOnSharedPreferenceChangeListener(onPrefsChangeListener);
}
}
</code></pre>
<p><strong>Stages List after Completing Stage 1 again:</strong>
<a href="https://i.stack.imgur.com/2og4q.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/2og4q.png" alt="Stage List After Completing Stage 1 Again"></a></p>
<p><strong>Even if I completed Stage 3 and unlocked Stage 4:</strong>
<a href="https://i.stack.imgur.com/Uj8aW.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Uj8aW.png" alt="enter image description here"></a></p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-08T17:48:39.620",
"Id": "460439",
"Score": "0",
"body": "Welcome to the code review website where we review code that is working as expected and provide suggestions on how that code might be improved. Code that is not working as expected is considered off-topic for this website. Unfortunately we can't help debug the program, you might get help from the stackoverflow.com website, but please look at their guidelines at https://stackoverflow.com/help first to see if the question meets the requirements. You can also search their previous questions to see if the question has already been answered."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-08T14:17:01.677",
"Id": "235292",
"Score": "1",
"Tags": [
"java",
"beginner",
"android"
],
"Title": "Game Level Unlocking Logic Java"
}
|
235292
|
<p>I'm working on my own generic-type dynamic array in C99 and I would like to hear your input, suggestions, ideas, anything! </p>
<p><strong>What I most care about is:</strong> 1) correctness and 2) performance.</p>
<p>So far, I've tested both with standard <code>malloc</code> and <a href="https://github.com/microsoft/mimalloc" rel="noreferrer">mimalloc</a>, although with the standard implementation it seems to be running 50% faster. </p>
<p>I've also ran <strong>benchmarks</strong> against <a href="https://github.com/faragon/libsrt" rel="noreferrer">libsrt</a>, <a href="https://github.com/rxi/vec/blob/master/src/vec.c" rel="noreferrer">vec</a> and Nim's implementation of dynamic sequences and my code seems to be beating them all.</p>
<p>Also, of major importance is to note that this code is not meant to be used as a library, but as part of a bytecode VM/intepreter that I've been working on - which means I am the one who is going to use it.</p>
<p><strong>Here's the source:</strong></p>
<pre><code>#ifndef __VARRAY_H__
#define __VARRAY_H__
/**************************************
Type definitions
**************************************/
#define Array(TYPE) \
struct { \
size_t size; \
size_t cap; \
size_t typeSize; \
TYPE *data; \
}
/**************************************
Macros
**************************************/
#define aInit(DEST,TYPE,CAP) { \
int k=0; \
while (powerOfTwo[++k]<CAP); \
\
DEST = malloc(sizeof(Array(TYPE))); \
DEST->size = 0; \
DEST->typeSize = sizeof(TYPE); \
DEST->cap = powerOfTwo[k]; \
DEST->data = calloc(DEST->cap, DEST->typeSize); \
}
#define aNew(NAME,TYPE,CAP) \
Array(TYPE)* NAME; \
aInit(NAME,TYPE,CAP);
#define aResize(DEST) { \
DEST->cap *= 2; \
DEST->data = realloc(DEST->data, DEST->cap * DEST->typeSize); \
}
#define aAdd(DEST,X) \
if (++(DEST->size) >= DEST->cap) aResize(DEST); \
DEST->data[DEST->size-1] = X
#define aAppend(DEST,X) \
DEST->cap += X->cap; \
DEST->data = realloc(DEST->data, DEST->cap * DEST->typeSize); \
memcpy(DEST->data + DEST->size, X->data, X->size * X->typeSize); \
DEST->size += X->size
#define aEach(DEST,INDEX) \
for (int INDEX=0; INDEX<DEST->size; INDEX++)
#define aFree(DEST) \
free(DEST->data); \
free(DEST)
#endif
</code></pre>
<p>The <code>powerOfTwo</code> lookup constant:</p>
<pre><code>/**************************************
Constants
**************************************/
static size_t powerOfTwo[] = {
0,
1, 2, 4, 8, 16, 32, 64, 128,
256, 512, 1024, 2048, 4096, 8192, 16384, 32768,
65536, 131072, 262144, 524288, 1048576, 2097152, 4194304, 8388608,
16777216, 33554432, 67108864, 134217728, 268435456, 536870912, 1073741824, 2147483648,
4294967296, 8589934592, 17179869184, 34359738368, 68719476736, 137438953472, 274877906944, 549755813888
};
</code></pre>
<p><strong>And a little usage example:</strong></p>
<pre><code>Array(int)* arr;
aInit(arr,int,0);
aAdd(arr,0);
aAdd(arr,1);
aEach(fastArr,i) {
printf("item @ %d = %d\n",i,arr->data[i]);
}
aFree(arr);
</code></pre>
|
[] |
[
{
"body": "<p>See\n<a href=\"https://stackoverflow.com/questions/1100311/what-is-the-ideal-growth-rate-for-a-dynamically-allocated-array\">this Stackoverflow answer</a> for\na discussion on the optimal growth factor for dynamic\narrays. The gist of it is that it depends, but growth\nfactors around the golden ratio are easier for the memory allocator to\nhandle. I'd recommend using 1.5 because it is easy to implement:</p>\n\n<pre><code>DEST->cap += DEST->cap / 2\n</code></pre>\n\n<p>It likely fares worse on artifical benchmarks but better on real\nworkloads. This requires that the minimum capacity of the dynamic\narray is 2 which is reasonable. But a more realistic minimum size\nlikely should be 8 or 16 since\nthe <a href=\"https://prog21.dadgum.com/179.html\" rel=\"noreferrer\">minimum malloc size</a> is 32\nbytes.</p>\n\n<p>In <code>aAppend</code> you are always realloc:ing which will cause performance\nto suffer if many small dynamic arrays are collected into one big one\nin a loop. Instead, you want something like:</p>\n\n<pre><code>size_t req = DEST->size + X->size;\nif (req > DEST->cap) {\n aResize(DEST);\n}\nmemcpy(DEST->data + DEST->size, X->data, X->size * X->typeSize);\nDEST->size = req;\n</code></pre>\n\n<p>The last thing I'd change is the alignment of the capacity to a power\nof two in <code>aInit</code>. On realistic workloads, a good chunk of all\nvariable arrays never grow so the alignment just wastes space. But\nif you insist on alignment, this function is better than the loop:</p>\n\n<pre><code>static inline int\nnext_pow2(int v) {\n v--;\n v |= v >> 1;\n v |= v >> 2;\n v |= v >> 4;\n v |= v >> 8;\n v |= v >> 16;\n v++;\n return v;\n}\n</code></pre>\n\n<p>I also wonder why you are using macros when C99 has inline functions?\nThey have many advantages in comparison to code macros.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-08T17:34:19.190",
"Id": "460435",
"Score": "3",
"body": "`DEST->cap += DEST->cap / 2` won't change anything of the current value of `DEST->cap` is 1 (or 0, but 0 would be a problem in the original code as well)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-08T18:15:11.273",
"Id": "460449",
"Score": "2",
"body": "The minimum malloc size is platform dependent. It might be 32 in your environment, but is likely different for others. The point is good though: allocating very small sizes will hurt performance; but choosing a good minimum size isn't necessarily trivial, especially given that we're measuring in units of `TYPE` but multiplying up to talk to `malloc()` in units of `char`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-08T18:39:26.313",
"Id": "460453",
"Score": "1",
"body": "Yep! 32 bytes is just an \"educated guess\" that has been true for some 64-bit systems but might very well change in the future. It all depends on the VM OP is building."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-09T18:35:48.473",
"Id": "460637",
"Score": "0",
"body": "The expansion by 1.5 was used by standard libraries for a while. But in modern ones they gave up on 1.5 and started using 2. They did not see the theoretical gains in real life enough to make it worth it. But I tried a maths prrof on why 1.5 is better :-) https://lokiastari.com/blog/2016/03/25/resizemaths/index.html"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-09T19:02:08.127",
"Id": "460643",
"Score": "0",
"body": "Cool! Can you link to their discussion?"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-08T17:08:51.217",
"Id": "235306",
"ParentId": "235294",
"Score": "10"
}
},
{
"body": "<p>We're missing an include of <code><stddef.h></code> to define <code>size_t</code> (or any of the other headers which define it).</p>\n\n<p>We're missing an include of <code><stdlib.h></code>, needed for <code>malloc()</code> and friends (and this would define <code>size_t</code> for us, too).</p>\n\n<p>With those fixed, and sufficient minor changes to the test program, I managed to compile with only a few warnings.</p>\n\n<blockquote>\n<pre><code>DEST = malloc(sizeof(Array(TYPE))); \\\nDEST->size = 0; \\\n</code></pre>\n</blockquote>\n\n<p>Oops! If <code>malloc()</code> returns a null pointer, we have undefined behaviour. Replace with </p>\n\n<pre><code>DEST = malloc(sizeof(Array(TYPE))); \\\nif (DEST) { \\\n DEST->size = 0; \\\n</code></pre>\n\n<p>Similarly, when we delete, let's accept a null pointer:</p>\n\n<pre><code>#define aFree(DEST) \\\n if (DEST) { \\\n free(DEST->data); \\\n } \\\n free(DEST)\n</code></pre>\n\n<p>We have a dangerous <code>realloc()</code>:</p>\n\n<blockquote>\n<pre><code>#define aResize(DEST) { \\\n DEST->cap *= 2; \\\n DEST->data = realloc(DEST->data, DEST->cap * DEST->typeSize); \\\n}\n</code></pre>\n</blockquote>\n\n<p>If the <code>realloc()</code> fails, then we have a null pointer in <code>data</code> and <strong>no way to access the old contents</strong>. The standard idiom is to check the return value <em>before</em> assigning it to <code>data</code>. We're going to need some way to report failure, too.</p>\n\n<p>In <code>aAppend()</code>, we should be using the <code>aResize()</code> we've defined instead of resizing to fit - as it is, we're going to reallocate on every single call.</p>\n\n<hr>\n\n<p>Overall, I think that writing everything as macros is a poor choice. It's probably better to use macro expansion (or equivalent technique, such is multiple includes with varying definitions) to create a set of (small, inlinable) functions for a given type. </p>\n\n<p>The macros we have here look like functions, but can't be used like functions (in particular, <code>aNew</code> expands to a declaration and a statement, and <code>aAdd</code> and <code>aFree</code> both expand to multiple statements, making them dangerous and confusing near conditionals.</p>\n\n<p>It's frustrating that the array control block must be allocated from dynamic memory - C++ programmers expect to be able to create <code>std::vector</code> objects on the stack, with only the object storage itself on the heap.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-08T18:29:12.910",
"Id": "460452",
"Score": "1",
"body": "See [Malloc Never Fails](https://scvalex.net/posts/6/). Imo, it's not practical to check mallocs return value. Even if @Dr.Kameleon adds `NULL` checks to his mallocs, clients of his library also need to check every invocation of the `aAdd` macro to ensure that it didn't cause memory to run out."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-08T18:40:00.947",
"Id": "460455",
"Score": "1",
"body": "Ouch, that's a scary attitude. Personally, I find that allowing overcommit does more harm than good, so it's turned off on my non-embedded systems (and certain problem processes get a specific `ulimit` value). And yes, I did say that we need functions that report errors properly; that's another reason to eschew the macros."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-08T18:41:16.597",
"Id": "460456",
"Score": "1",
"body": "Oh, having read further, I see, \"To clarify, the surprising behaviour `malloc` has does _not_ mean we should ignore its return value\". I feel better now."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-08T19:20:02.263",
"Id": "460461",
"Score": "0",
"body": "It's perfectly reasonable. There's [lots](https://stackoverflow.com/questions/10157778/why-some-people-dont-check-for-null-after-calling-malloc) [of](https://stackoverflow.com/questions/1941323/always-check-malloced-memory) [discussion](https://news.ycombinator.com/item?id=17734830) on whether to check the return value of malloc. I usually don't because it's impractical or impossible to test all oom errors, even if you check them, you can't handle them gracefully and false sense of security. For really robust software, I'd eschew dynamic memory entirely."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-09T11:08:26.657",
"Id": "460563",
"Score": "3",
"body": "@BjörnLindqvist It's reasonable under some conditions, ***IF*** you're aware of what those conditions are, and ***IF*** you've explicitly acknowledged the tradeoffs. In your specific applications, you believe it will take too long to make your software fail gracefully, for a situation that rarely happens, and it's fine that you make that call. I don't think it's good practise to generalise that to a blanket statement of \"it's not practical\" though. I see far too many cases of newbies ignoring return values; their code works fine on a sunny day, but it dies horribly when anything goes wrong."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-08T17:40:42.320",
"Id": "235309",
"ParentId": "235294",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": "235306",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-08T14:37:16.113",
"Id": "235294",
"Score": "5",
"Tags": [
"c",
"array"
],
"Title": "Generic dynamic array implementation in C"
}
|
235294
|
<p>This is a problem from CodeWar.</p>
<blockquote>
<p>Write a function that will return the count of distinct
case-insensitive alphabetic characters and numeric digits that occur
more than once in the input string. The input string can be assumed to
contain only alphabets (both uppercase and lowercase) and numeric
digits. </p>
<p>EX: "abba" -> 2, "aabBcde" -> 2.</p>
</blockquote>
<p>Here is my solution in Java: </p>
<pre><code>public class CountingDuplicates {
public static int duplicateCount(String text) {
String textLower = text.toLowerCase();
char[] charArray = textLower.toCharArray();
String uniqueRepeats = ""; //Will keep track of unique repeats.
int count = 0;
for(int i = 0; i < charArray.length - 1; i ++) {
String restOfString = textLower.substring(i + 1);
//Convert single char to String to be used in method.
String character = Character.toString(charArray[i]);
//If not in uniqueRepeats, check if it is a repeat.
if(!uniqueRepeats.contains(character)) {
if(restOfString.indexOf(character) != -1) {
//If it is a repeat, increase count and concat it to uniqueRepeats
count++;
uniqueRepeats += character;
}
}
}
return count;
}
}
</code></pre>
<p>Some improvements that I can think of is using a HashMap to store the repeats so that I do not have to create a new string object for every repeat
If you guys have any suggestions on code readability, code structure, or better implementation for this problem, please leave me a comment. Thank you!
EDIT - Here is the link to the problem: <a href="https://www.codewars.com/kata/counting-duplicates/train/java" rel="nofollow noreferrer">https://www.codewars.com/kata/counting-duplicates/train/java</a></p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-08T15:26:17.227",
"Id": "460411",
"Score": "0",
"body": "The code doesn't work because you used end of line comments and had a formatter add newlines to them."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-08T15:31:05.457",
"Id": "460412",
"Score": "0",
"body": "Before we go into fixing the code, tell us are you restricted to ASCII or are you expected to be able to deal with the full Unicode character set?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-08T17:17:17.927",
"Id": "460432",
"Score": "0",
"body": "@TorbenPutkonen My apologies for the incorrect formatting. I have edited the code. I believe that the problem is restricted to ASCII, not Unicode. I have included a link to the problem also."
}
] |
[
{
"body": "<p><strong>Let's see what is the Big O of your code.</strong></p>\n\n<ol>\n<li>In new versions of Java <code>substring</code> creates a new String and performs in <span class=\"math-container\">\\$O(n)\\$</span> (In older versions this is <span class=\"math-container\">\\$O(1)\\$</span>)</li>\n<li><code>uniqueRepeats.contains(character)</code> results in <span class=\"math-container\">\\$O(m)\\$</span> where <span class=\"math-container\">\\$m\\$</span> is count of unique characters.</li>\n<li><code>restOfString.indexOf(character) != -1</code> - this is again <span class=\"math-container\">\\$O(n)\\$</span></li>\n<li><code>uniqueRepeats += character</code> Depending on the JVM this might end up creating set of <code>StringBuilder</code> objects or set of <code>String</code> objects that are discarded. So this is probably <span class=\"math-container\">\\$O(m^2)\\$</span></li>\n<li>You are doing this for <span class=\"math-container\">\\$n\\$</span> characters.</li>\n</ol>\n\n<p>So time complexity is - <span class=\"math-container\">\\$O(n *(n + m + m^2))\\$</span> in some situations <span class=\"math-container\">\\$m\\$</span> can be as large as <span class=\"math-container\">\\$n\\$</span>. So if we simplyfy things we get <span class=\"math-container\">\\$O(n^3)\\$</span>.</p>\n\n<p><strong>Ideas:</strong></p>\n\n<ul>\n<li>This is where your <code>HashMap</code> idea would've been better. We can simply store <code>Char</code> and an <code>Integer</code> count. Then iterate over your map to count all elements that has more than <span class=\"math-container\">\\$1\\$</span> element. <code>LinkedHashMap</code> is very useful for a situation like this.</li>\n<li>Why is <code>LinkedHashMap</code> better? Because it has an internal linked list that allows faster iteration.</li>\n<li>We can also use an array if this is ASCII only. (But it is easier with a <code>Map</code>).</li>\n<li>This will result in armotized <span class=\"math-container\">\\$O(n)\\$</span>. Which is lot better.</li>\n<li>Either way all these are theoretical and it is always better to profile things.</li>\n</ul>\n\n<hr>\n\n<p><strong>Code</strong></p>\n\n<blockquote>\n<pre><code>//Will keep track of unique repeats.\n//Convert single char to String to be used in method.\n//If not in uniqueRepeats, check if it is a repeat. \n//If it is a repeat, increase count and concat it to uniqueRepeats\n</code></pre>\n</blockquote>\n\n<ul>\n<li>You have mentioned <strong>what</strong> you are doing in comments. We can also understand that from code itself. So it is better to include <strong>why</strong> comments.</li>\n<li>I recommend that you use an IDE to indent code. Code is clearly not indented accurately.</li>\n</ul>\n\n<blockquote>\n<pre><code>if(!uniqueRepeats.contains(character)) {\n if(restOfString.indexOf(character) != -1) {\n</code></pre>\n</blockquote>\n\n<ul>\n<li>Be consistent. We can use <code>contains</code> to both above statements.</li>\n</ul>\n\n<p><sub>\n<strong>References</strong></p>\n\n<ul>\n<li><a href=\"https://stackoverflow.com/a/1532483/1355145\">https://stackoverflow.com/a/1532483/1355145</a></li>\n<li><a href=\"http://java-performance.info/changes-to-string-java-1-7-0_06/\" rel=\"nofollow noreferrer\">http://java-performance.info/changes-to-string-java-1-7-0_06/</a></li>\n<li><a href=\"https://stackoverflow.com/questions/26311776/why-iteration-through-buckets-in-linkedhashmap-is-faster-than-hashmap\">https://stackoverflow.com/questions/26311776/why-iteration-through-buckets-in-linkedhashmap-is-faster-than-hashmap</a></li>\n</ul>\n\n<p></sub></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-08T17:58:50.850",
"Id": "460445",
"Score": "0",
"body": "Let me know if you think something is wrong in the answer. "
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-08T19:11:03.053",
"Id": "460458",
"Score": "0",
"body": "Thank you for the detailed comment. I will try to re-implement the solution using HashMap. I have yet to learn the Map and Collection API. Solving these problems with Java makes me appreciate the simple syntax of Python."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-08T19:14:49.783",
"Id": "460460",
"Score": "0",
"body": "@bhathiya-perea, I do have one question. What would the time complexity be for the solution using HashMap? Would it be O(n) ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-08T19:22:02.383",
"Id": "460462",
"Score": "1",
"body": "@David ah yes it would be armotized O(n)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-09T19:33:33.633",
"Id": "460654",
"Score": "0",
"body": "Unfortunately the Codewars tasks aren't very well specified. There was no limitation on the input so we must assume it covers all alphabet sets in the Unicode. So the array solution is out of the question."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-10T11:53:39.563",
"Id": "460740",
"Score": "1",
"body": "@TorbenPutkonen IMHO this is ASCII only as it is a programming challenge, these tests usually checks if user can build a fast algorithm for the given scenario. But in real world pretty much everything is Unicode. If someone asked this as an interview question then the I would ask is this for ASCII only? And they would most probably say \"Yes\"."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-08T17:49:42.373",
"Id": "235311",
"ParentId": "235296",
"Score": "5"
}
},
{
"body": "<p>Like bhathiya-perera and yourself suggested this can be better implemented using a <code>HashMap</code> and simply count the characters.</p>\n\n<p>However in my opinion your attempt isn't that bad. The problem is you are using the wrong methods and data structures and you are coping/creating strings too much.</p>\n\n<p>First you don't need to create <code>charArray</code> which is an unnecessary copy of the string. You are only using for the length (with is identical to the length of the original string) and to get the character, which can be done with the <code>.charAt()</code> method of <code>String</code>.</p>\n\n<p><code>String</code> is the wrong data structure for <code>uniqueRepeats</code>. The only thing you do with that is check if it contains a specific character. The optimized data structure for that would be a <code>HashSet<Character></code>:</p>\n\n<pre><code>Set<Character> uniqueRepeats = new HashSet<>();\n</code></pre>\n\n<p>Counting the duplicates yourself with <code>count</code> is also not necessary. You can just take the <code>size()</code> of <code>uniqueRepeats</code> at the end.</p>\n\n<p>Creating <code>restOfString</code> is also not necessary, since <code>String</code> has a variant of <code>indexOf</code> that searches from a given index instead of from the start.</p>\n\n<pre><code>textLower.indexOf(character, i + 1) != -1\n</code></pre>\n\n<p>When getting the character from the string, you don't need to convert it into a <code>String</code>. Generally anything that can be done with a <code>String</code>, usually can be done with a character:</p>\n\n<pre><code>char character = textLower.charAt(i); \n</code></pre>\n\n<p>Finally the two nested <code>if</code>s can be combined into one using <code>&&</code>. </p>\n\n<p>Final code:</p>\n\n<pre><code>public static int duplicateCount(String text) {\n String textLower = text.toLowerCase(); \n Set<Character> uniqueRepeats = new HashSet<>();\n\n for (int i = 0; i < textLower.length - 1; i ++) { \n char character = textLower.charAt(i);\n\n if (!uniqueRepeats.contains(character) && textLower.indexOf(character, i + 1) != -1) { \n uniqueRepeats.add(character);\n }\n }\n\n return uniqueRepeats.size(); \n} \n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-13T15:51:40.060",
"Id": "461124",
"Score": "0",
"body": "Thank you for your input. I am still learning the ins and outs of Java and it's data structures."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-12T20:09:30.047",
"Id": "235523",
"ParentId": "235296",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "235311",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-08T14:45:25.420",
"Id": "235296",
"Score": "4",
"Tags": [
"java",
"programming-challenge"
],
"Title": "Counting Duplicates - Code War"
}
|
235296
|
<p>I want to clean my code up. I'm using a for I loop and using alot of if statements. What is the best way to clean this code up? </p>
<pre><code> for (let i = 0; i < 100 ; i++) {
if (file_1h[i] == null) {
console.log("Null detected and deleted");
delete file_1h[i];
}
if (file_20h[i] == null) {
console.log("Null detected and deleted");
delete file_20h[i];
}
if (file_20d[i] == null) {
console.log("Null detected and deleted");
delete file_20d[i];
}
if (file_40y[i] == null) {
console.log("Null detected and deleted");
delete file_40y[i];
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-08T15:45:40.867",
"Id": "460416",
"Score": "4",
"body": "Please include enough code that reviewers can run it. The additional context (e.g. what is `file_1h[i]`) will also help reviewers recommend how to improve your code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-08T16:03:13.257",
"Id": "460418",
"Score": "2",
"body": "Welcome to Code Review! This question lacks any indication of what the code is intended to achieve. To help reviewers give you better answers, please add sufficient context to your question, including a title that summarises the *purpose* of the code. We want to know **why** much more than **how**. The more you tell us about [what your code is for](//meta.codereview.stackexchange.com/q/1226), the easier it will be for reviewers to help you. The title needs an [edit] to simply [**state the task**](//meta.codereview.stackexchange.com/q/2436)."
}
] |
[
{
"body": "<p>Based on your code, you can reuse the console.log and delete by putting them in a function. I don't have all the data in order to run the code, but this is one approach of refactor.</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>for (let i = 0; i < 100; i++) {\n\n deleteIfNull(file_1h[i]);\n deleteIfNull(file_20h[i]);\n deleteIfNull(file_20d[i]);\n deleteIfNull(file_40y[i]);\n}\n\nfunction deleteIfNull(element) {\n if (element == null) {\n console.log(\"Null detected and deleted\");\n delete element;\n }\n}</code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-08T17:02:17.267",
"Id": "460431",
"Score": "0",
"body": "Please note: questions containing small snippets of code (and with little description of what the code does or how it is used) are off-topic on this site. If the OP edits their post to address the problem and make their post on-topic, they make your answer moot. [It is advised not to answer such questions](https://codereview.meta.stackexchange.com/a/6389/120114). Protip: There are tons of on-topic questions to answer; you'll make more reputation faster if you review code in questions that will get higher view counts for being on-topic."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-08T16:08:22.490",
"Id": "235303",
"ParentId": "235297",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-08T14:46:21.663",
"Id": "235297",
"Score": "-2",
"Tags": [
"javascript"
],
"Title": "Clean coding best practise for i loop with if statements"
}
|
235297
|
<p>This code (~30lines) detects independence between variables in a dataset, by using a bootstrap of a statistic. This is fully-broadcasted, but it's still long. </p>
<p>Reading it, or making it run, do you see some possibilities for more optimisation? </p>
<p>Right here is a MWE with a sample of data with 100 points. Feel free to comment </p>
<pre><code>import numpy as np
########### Data and prerequisites
# Sample of data with strong dependence structure :
data = np.array([[5.61293390e-01, 9.97100450e-01, 4.23530180e-01, 6.08808896e-01],
[1.22563280e-01, 1.72015130e-01, 8.71145720e-01, 5.40745844e-01],
[8.51194500e-02, 1.18289130e-01, 8.90346540e-01, 7.22859351e-01],
[9.83241310e-01, 9.57282690e-01, 7.22347100e-02, 5.43527399e-02],
[5.49211550e-01, 3.97858250e-01, 6.86380990e-01, 7.91494336e-01],
[9.94878920e-01, 6.39160920e-01, 2.01045170e-01, 9.86840712e-01],
[5.04337540e-01, 5.69995040e-01, 3.99087430e-01, 4.32140476e-01],
[9.28230540e-01, 9.32143440e-01, 1.02748280e-01, 9.92666867e-01],
[1.77513660e-01, 1.83466350e-01, 7.99027540e-01, 6.30800256e-01],
[5.14663640e-01, 6.34361690e-01, 5.33889110e-01, 7.90899958e-01],
[2.58006640e-01, 2.88319290e-01, 7.09604700e-01, 9.02145588e-01],
[2.04811730e-01, 1.58717810e-01, 8.41421970e-01, 8.84068574e-01],
[3.11875950e-01, 2.46353420e-01, 7.58289460e-01, 9.65660849e-01],
[9.36622730e-01, 8.01263020e-01, 9.83931900e-02, 5.44281251e-01],
[3.45077880e-01, 2.88884330e-01, 6.99352220e-01, 9.71301027e-01],
[8.18323020e-01, 8.42968360e-01, 2.68607890e-01, 1.52418342e-01],
[9.07517590e-01, 7.41841580e-01, 3.94466860e-01, 3.33215046e-01],
[3.84328210e-01, 2.85716010e-01, 7.73390420e-01, 4.79702183e-01],
[4.74390660e-01, 7.16142340e-01, 4.52819790e-01, 7.98200958e-01],
[1.91063150e-01, 3.11021770e-01, 8.17990970e-01, 3.65566296e-02],
[3.84454330e-01, 5.31087070e-01, 6.46125720e-01, 4.26028784e-01],
[7.76256310e-01, 9.82152950e-01, 2.24877600e-01, 9.03596071e-01],
[5.21782070e-01, 6.09994810e-01, 5.49719820e-01, 3.77052128e-01],
[2.44654800e-01, 2.22705930e-01, 6.92217350e-01, 8.04524950e-01],
[6.26568380e-01, 6.85160450e-01, 5.05651420e-01, 1.06857236e-01],
[4.57300600e-02, 3.19478800e-02, 9.56385030e-01, 5.62236853e-01],
[9.85249100e-02, 9.00401200e-02, 9.15879990e-01, 9.37933793e-01],
[1.13619610e-01, 1.08790380e-01, 8.86476490e-01, 9.07453097e-01],
[8.61160760e-01, 9.26073490e-01, 1.51885700e-02, 5.61689264e-01],
[4.72355650e-01, 8.90940390e-01, 4.79858960e-01, 1.31270153e-01],
[3.29944340e-01, 3.87579980e-01, 5.10804930e-01, 5.19551698e-01],
[5.29880000e-03, 7.01797000e-03, 9.93625440e-01, 1.85747216e-01],
[6.23029300e-01, 4.84573370e-01, 2.68151590e-01, 5.60921564e-03],
[8.03967200e-01, 7.84008540e-01, 2.37276020e-01, 9.47798098e-01],
[4.58525700e-01, 6.45049070e-01, 5.76664620e-01, 5.75709041e-01],
[8.65658770e-01, 8.99023760e-01, 2.40967370e-01, 5.56589158e-01],
[9.67638170e-01, 8.83972000e-01, 3.44920000e-04, 9.17016810e-01],
[7.24319710e-01, 8.63911350e-01, 2.64988220e-01, 2.13078474e-01],
[9.91532810e-01, 9.85368470e-01, 6.58391400e-02, 4.58927178e-04],
[1.17465420e-01, 1.14261700e-01, 9.05365980e-01, 1.80863318e-01],
[8.63220080e-01, 7.91506140e-01, 5.18878970e-01, 5.49666344e-01],
[3.12470000e-02, 3.19607200e-02, 9.72981330e-01, 8.60758375e-01],
[4.41205810e-01, 4.87292710e-01, 5.39217100e-01, 5.65980037e-01],
[1.39334500e-02, 1.40076300e-02, 9.84327060e-01, 9.38894626e-01],
[2.43659030e-01, 2.09662260e-01, 7.81243000e-01, 1.14951150e-01],
[9.45841720e-01, 9.45075580e-01, 1.37627400e-02, 5.39213927e-01],
[7.92013050e-01, 6.55037130e-01, 2.08627580e-01, 1.50823215e-01],
[6.04095200e-02, 4.57398400e-02, 9.53590740e-01, 6.32755639e-01],
[5.67334500e-01, 2.75674320e-01, 6.47657510e-01, 4.68491101e-01],
[1.58600060e-01, 1.22128390e-01, 8.47935330e-01, 4.94281577e-01],
[8.26576000e-03, 4.07989000e-03, 9.95207870e-01, 8.02447365e-02],
[7.25499790e-01, 7.05574910e-01, 3.94566850e-01, 8.90077195e-01],
[8.30398180e-01, 7.65006390e-01, 1.04508490e-01, 9.44908637e-01],
[6.84425700e-01, 8.13177160e-01, 2.55194010e-01, 1.71608600e-01],
[3.69045830e-01, 4.10810940e-01, 6.39276590e-01, 9.22700243e-01],
[1.42119190e-01, 1.45086850e-01, 8.87464990e-01, 2.35533293e-01],
[8.51399930e-01, 8.63513030e-01, 4.28106000e-02, 7.49796027e-01],
[7.26388760e-01, 9.23435870e-01, 3.21152410e-01, 5.59389176e-01],
[2.68165680e-01, 2.21699530e-01, 7.13336850e-01, 8.28847266e-01],
[4.67212100e-02, 6.18397600e-02, 9.08459550e-01, 1.73109978e-01],
[8.12353540e-01, 6.14787930e-01, 2.36200930e-01, 6.70979632e-01],
[3.56200600e-01, 2.86300900e-01, 6.87996620e-01, 7.68872468e-01],
[4.27617260e-01, 4.08906890e-01, 4.65987670e-01, 1.67199623e-01],
[6.63373240e-01, 9.66214910e-01, 1.39582640e-01, 9.85382902e-01],
[5.51993350e-01, 4.93202560e-01, 5.63663960e-01, 1.69990831e-01],
[8.04742160e-01, 7.23388830e-01, 1.97937550e-01, 5.06756753e-01],
[1.07240370e-01, 1.15115720e-01, 9.07925810e-01, 3.46134208e-01],
[3.61709450e-01, 2.16649010e-01, 7.91721970e-01, 5.22621049e-01],
[9.83195600e-01, 9.35189250e-01, 1.09384140e-01, 4.87989100e-01],
[1.07405620e-01, 1.05033440e-01, 8.76795260e-01, 2.44237928e-01],
[6.75897130e-01, 6.50329960e-01, 3.04297580e-01, 3.60810270e-01],
[7.02020600e-02, 4.96392100e-02, 9.33498520e-01, 7.17513612e-01],
[4.84155500e-01, 6.88098980e-01, 3.46669530e-01, 2.16784063e-01],
[6.04164790e-01, 7.48494480e-01, 9.49017500e-02, 2.69127829e-03],
[5.92501140e-01, 7.18188940e-01, 4.79787090e-01, 4.72203718e-01],
[6.47244640e-01, 9.12962170e-01, 3.94908800e-02, 1.89967176e-02],
[7.52063710e-01, 8.36582980e-01, 2.56381510e-01, 1.82552057e-01],
[7.33809600e-01, 5.88942430e-01, 3.17564930e-01, 4.83186793e-02],
[6.37782580e-01, 7.91589180e-01, 3.08634220e-01, 1.83951279e-01],
[7.32009020e-01, 9.14051250e-01, 1.80915920e-01, 2.45163585e-01],
[1.53493780e-01, 1.90967590e-01, 8.19005590e-01, 7.55056039e-01],
[5.36161820e-01, 5.13641150e-01, 5.01637010e-01, 3.47079632e-01],
[6.06637230e-01, 6.67565790e-01, 3.33999130e-01, 2.51786198e-01],
[7.25650010e-01, 8.41152620e-01, 2.36374270e-01, 2.61322095e-01],
[6.52008490e-01, 8.66015010e-01, 1.90032370e-01, 5.14531432e-01],
[2.59336300e-02, 3.60464100e-02, 9.42735970e-01, 8.76251330e-01],
[3.91414850e-01, 3.16164320e-01, 6.36344310e-01, 2.11938819e-01],
[6.43722130e-01, 5.38235890e-01, 1.13523690e-01, 3.54529909e-01],
[7.90799970e-01, 7.44277280e-01, 3.24458070e-01, 1.60302427e-01],
[7.10510700e-02, 8.50407900e-02, 9.08863250e-01, 9.18056054e-02],
[8.27656880e-01, 7.68024600e-01, 6.35402600e-02, 1.39203186e-01],
[4.22585470e-01, 4.66851210e-01, 5.36839920e-01, 9.51087042e-02],
[8.74929100e-02, 9.12235300e-02, 8.91159090e-01, 3.88725280e-02],
[9.36443830e-01, 8.16299420e-01, 2.90021130e-01, 2.89175878e-01],
[9.26354550e-01, 9.51074570e-01, 8.49412000e-03, 1.76092602e-01],
[5.72510800e-02, 3.56584500e-02, 9.67113730e-01, 7.74680782e-01],
[1.10646890e-01, 1.10709490e-01, 8.85004310e-01, 8.08970193e-01],
[9.30983140e-01, 9.85525760e-01, 6.47764700e-02, 3.51535913e-01],
[9.16176650e-01, 8.13787300e-01, 2.80715970e-01, 7.69428516e-01],
[9.34773620e-01, 8.73895270e-01, 1.23538120e-01, 5.72796569e-01]])
# Remove the dependence of the last dimension :
data[:,3] = np.random.uniform(size=100)
# use this specific breakpoint :
breakpoint = np.array([0.57425735, 0.52599749, 0.43842457, 0.66851334])
# Dimensions
d = data.shape[1] # Number of variables
M = 2 ** d
n = data.shape[0] # Number of observationsa
N = 999 # Number of bootstrap resamples
# compute prerequisites : Thoose prerequistes dont need optimisation.
binary_repr = np.arange(2 ** d)[:, None] >> np.arange(d)[::-1] & 1 # this is already optimized
min = breakpoint * binary_repr # (M,d)
max = breakpoint ** (1 - binary_repr) # (M,d)
lambda_l = np.prod(max - min, axis=1) # (M,)
########### Algorithm
# small function : the 3 imputs needs to be broadcastable to each other,
# and it returns something that is shaped as the broadcast of the 3 inputs
def is_in(data,min,max): return np.logical_and(data >= min, data < max)
def compute_statistic(A, B, C): return np.sum(B ** 2 / C - 2 * A * B,axis=0)
# Now we get to the algorithm itself.
are_in = is_in(data[None,], min[:, None, ], max[:, None, ]) # (M,n,d)
f_l = np.mean(np.all(are_in, axis=2), axis=1) # (M,)
# Draw random numbers :
random_numbers = np.random.uniform(size=(N, n, d)) # (N,n,d)
# build indices selectors :
masks = (np.identity(d) == 0).reshape(d * d) # (d*d)
rev_masks = np.logical_not(masks)
# simplify broadcasting by repeating a little the data : # <<<<<<<<<<<< Here problems might start !
maxes = np.repeat(max, d, axis=1) # (M,d*d)
mines = np.repeat(min, d, axis=1) # (M,d*d)
zes = np.repeat(data, d, axis=1) # (n,d*d)
random_numbers = np.repeat(random_numbers, d, axis=2)
are_in_rep = np.repeat(are_in, d, axis=2) # (M,n,d*d)
# Compute a piece of the result :
f_k = np.mean(np.all(are_in_rep[..., masks].reshape(M, n, d - 1, d), axis=2), axis=1) # (M,d)
lambda_k = np.prod((maxes - mines)[:, masks].reshape((M, d - 1, d)), axis=1) # (M,d)
rez_k = np.flip(f_k / lambda_k,axis=1)
# The observed values of the statistic can now be computed :
value = compute_statistic(rez_k, f_l[:,None], lambda_l[:, None]) # (d,)
# Now compute the same statistic value, but bootstrapped :
z_reps = np.repeat(zes[None, :, :], N, axis=0) # (N,n,d*d)
z_reps[:, :, rev_masks] = random_numbers[:, :, rev_masks] # (N,n,d*d)
are_in_boot = is_in(z_reps[None,], mines[:, None, None, ], maxes[:, None, None, ]).reshape(M, N, n, d, d)
f_ls = np.mean(np.all(are_in_boot, axis=3), axis=2) # (M,N,d)
values = compute_statistic(rez_k[:,None],f_ls,lambda_l[:, None, None]) # (N,d)
# return the result :
result = np.mean(value < values, axis=0)
print(result)
</code></pre>
<p><strong>Edit</strong>: I tried to split the code into smaller functions, and run <code>cProfiler</code> on it. The code is below. The problem seems to come from the <code>compute_f_l</code> function which is eating more than half the runtime. But this function is soo trivial that i dont know what to do... The <code>is_in</code> function eats 1/4 of the time, same issue for me.</p>
<p>Here is the profiled and splitted up code : </p>
<pre><code>import numpy as np
import cProfile
cp = cProfile.Profile()
cp.enable()
########### Data and prerequisites
# Sample of data with strong dependence structure :
data = np.array([[5.61293390e-01, 9.97100450e-01, 4.23530180e-01, 6.08808896e-01],
[1.22563280e-01, 1.72015130e-01, 8.71145720e-01, 5.40745844e-01],
[8.51194500e-02, 1.18289130e-01, 8.90346540e-01, 7.22859351e-01],
[9.83241310e-01, 9.57282690e-01, 7.22347100e-02, 5.43527399e-02],
[5.49211550e-01, 3.97858250e-01, 6.86380990e-01, 7.91494336e-01],
[9.94878920e-01, 6.39160920e-01, 2.01045170e-01, 9.86840712e-01],
[5.04337540e-01, 5.69995040e-01, 3.99087430e-01, 4.32140476e-01],
[9.28230540e-01, 9.32143440e-01, 1.02748280e-01, 9.92666867e-01],
[1.77513660e-01, 1.83466350e-01, 7.99027540e-01, 6.30800256e-01],
[5.14663640e-01, 6.34361690e-01, 5.33889110e-01, 7.90899958e-01],
[2.58006640e-01, 2.88319290e-01, 7.09604700e-01, 9.02145588e-01],
[2.04811730e-01, 1.58717810e-01, 8.41421970e-01, 8.84068574e-01],
[3.11875950e-01, 2.46353420e-01, 7.58289460e-01, 9.65660849e-01],
[9.36622730e-01, 8.01263020e-01, 9.83931900e-02, 5.44281251e-01],
[3.45077880e-01, 2.88884330e-01, 6.99352220e-01, 9.71301027e-01],
[8.18323020e-01, 8.42968360e-01, 2.68607890e-01, 1.52418342e-01],
[9.07517590e-01, 7.41841580e-01, 3.94466860e-01, 3.33215046e-01],
[3.84328210e-01, 2.85716010e-01, 7.73390420e-01, 4.79702183e-01],
[4.74390660e-01, 7.16142340e-01, 4.52819790e-01, 7.98200958e-01],
[1.91063150e-01, 3.11021770e-01, 8.17990970e-01, 3.65566296e-02],
[3.84454330e-01, 5.31087070e-01, 6.46125720e-01, 4.26028784e-01],
[7.76256310e-01, 9.82152950e-01, 2.24877600e-01, 9.03596071e-01],
[5.21782070e-01, 6.09994810e-01, 5.49719820e-01, 3.77052128e-01],
[2.44654800e-01, 2.22705930e-01, 6.92217350e-01, 8.04524950e-01],
[6.26568380e-01, 6.85160450e-01, 5.05651420e-01, 1.06857236e-01],
[4.57300600e-02, 3.19478800e-02, 9.56385030e-01, 5.62236853e-01],
[9.85249100e-02, 9.00401200e-02, 9.15879990e-01, 9.37933793e-01],
[1.13619610e-01, 1.08790380e-01, 8.86476490e-01, 9.07453097e-01],
[8.61160760e-01, 9.26073490e-01, 1.51885700e-02, 5.61689264e-01],
[4.72355650e-01, 8.90940390e-01, 4.79858960e-01, 1.31270153e-01],
[3.29944340e-01, 3.87579980e-01, 5.10804930e-01, 5.19551698e-01],
[5.29880000e-03, 7.01797000e-03, 9.93625440e-01, 1.85747216e-01],
[6.23029300e-01, 4.84573370e-01, 2.68151590e-01, 5.60921564e-03],
[8.03967200e-01, 7.84008540e-01, 2.37276020e-01, 9.47798098e-01],
[4.58525700e-01, 6.45049070e-01, 5.76664620e-01, 5.75709041e-01],
[8.65658770e-01, 8.99023760e-01, 2.40967370e-01, 5.56589158e-01],
[9.67638170e-01, 8.83972000e-01, 3.44920000e-04, 9.17016810e-01],
[7.24319710e-01, 8.63911350e-01, 2.64988220e-01, 2.13078474e-01],
[9.91532810e-01, 9.85368470e-01, 6.58391400e-02, 4.58927178e-04],
[1.17465420e-01, 1.14261700e-01, 9.05365980e-01, 1.80863318e-01],
[8.63220080e-01, 7.91506140e-01, 5.18878970e-01, 5.49666344e-01],
[3.12470000e-02, 3.19607200e-02, 9.72981330e-01, 8.60758375e-01],
[4.41205810e-01, 4.87292710e-01, 5.39217100e-01, 5.65980037e-01],
[1.39334500e-02, 1.40076300e-02, 9.84327060e-01, 9.38894626e-01],
[2.43659030e-01, 2.09662260e-01, 7.81243000e-01, 1.14951150e-01],
[9.45841720e-01, 9.45075580e-01, 1.37627400e-02, 5.39213927e-01],
[7.92013050e-01, 6.55037130e-01, 2.08627580e-01, 1.50823215e-01],
[6.04095200e-02, 4.57398400e-02, 9.53590740e-01, 6.32755639e-01],
[5.67334500e-01, 2.75674320e-01, 6.47657510e-01, 4.68491101e-01],
[1.58600060e-01, 1.22128390e-01, 8.47935330e-01, 4.94281577e-01],
[8.26576000e-03, 4.07989000e-03, 9.95207870e-01, 8.02447365e-02],
[7.25499790e-01, 7.05574910e-01, 3.94566850e-01, 8.90077195e-01],
[8.30398180e-01, 7.65006390e-01, 1.04508490e-01, 9.44908637e-01],
[6.84425700e-01, 8.13177160e-01, 2.55194010e-01, 1.71608600e-01],
[3.69045830e-01, 4.10810940e-01, 6.39276590e-01, 9.22700243e-01],
[1.42119190e-01, 1.45086850e-01, 8.87464990e-01, 2.35533293e-01],
[8.51399930e-01, 8.63513030e-01, 4.28106000e-02, 7.49796027e-01],
[7.26388760e-01, 9.23435870e-01, 3.21152410e-01, 5.59389176e-01],
[2.68165680e-01, 2.21699530e-01, 7.13336850e-01, 8.28847266e-01],
[4.67212100e-02, 6.18397600e-02, 9.08459550e-01, 1.73109978e-01],
[8.12353540e-01, 6.14787930e-01, 2.36200930e-01, 6.70979632e-01],
[3.56200600e-01, 2.86300900e-01, 6.87996620e-01, 7.68872468e-01],
[4.27617260e-01, 4.08906890e-01, 4.65987670e-01, 1.67199623e-01],
[6.63373240e-01, 9.66214910e-01, 1.39582640e-01, 9.85382902e-01],
[5.51993350e-01, 4.93202560e-01, 5.63663960e-01, 1.69990831e-01],
[8.04742160e-01, 7.23388830e-01, 1.97937550e-01, 5.06756753e-01],
[1.07240370e-01, 1.15115720e-01, 9.07925810e-01, 3.46134208e-01],
[3.61709450e-01, 2.16649010e-01, 7.91721970e-01, 5.22621049e-01],
[9.83195600e-01, 9.35189250e-01, 1.09384140e-01, 4.87989100e-01],
[1.07405620e-01, 1.05033440e-01, 8.76795260e-01, 2.44237928e-01],
[6.75897130e-01, 6.50329960e-01, 3.04297580e-01, 3.60810270e-01],
[7.02020600e-02, 4.96392100e-02, 9.33498520e-01, 7.17513612e-01],
[4.84155500e-01, 6.88098980e-01, 3.46669530e-01, 2.16784063e-01],
[6.04164790e-01, 7.48494480e-01, 9.49017500e-02, 2.69127829e-03],
[5.92501140e-01, 7.18188940e-01, 4.79787090e-01, 4.72203718e-01],
[6.47244640e-01, 9.12962170e-01, 3.94908800e-02, 1.89967176e-02],
[7.52063710e-01, 8.36582980e-01, 2.56381510e-01, 1.82552057e-01],
[7.33809600e-01, 5.88942430e-01, 3.17564930e-01, 4.83186793e-02],
[6.37782580e-01, 7.91589180e-01, 3.08634220e-01, 1.83951279e-01],
[7.32009020e-01, 9.14051250e-01, 1.80915920e-01, 2.45163585e-01],
[1.53493780e-01, 1.90967590e-01, 8.19005590e-01, 7.55056039e-01],
[5.36161820e-01, 5.13641150e-01, 5.01637010e-01, 3.47079632e-01],
[6.06637230e-01, 6.67565790e-01, 3.33999130e-01, 2.51786198e-01],
[7.25650010e-01, 8.41152620e-01, 2.36374270e-01, 2.61322095e-01],
[6.52008490e-01, 8.66015010e-01, 1.90032370e-01, 5.14531432e-01],
[2.59336300e-02, 3.60464100e-02, 9.42735970e-01, 8.76251330e-01],
[3.91414850e-01, 3.16164320e-01, 6.36344310e-01, 2.11938819e-01],
[6.43722130e-01, 5.38235890e-01, 1.13523690e-01, 3.54529909e-01],
[7.90799970e-01, 7.44277280e-01, 3.24458070e-01, 1.60302427e-01],
[7.10510700e-02, 8.50407900e-02, 9.08863250e-01, 9.18056054e-02],
[8.27656880e-01, 7.68024600e-01, 6.35402600e-02, 1.39203186e-01],
[4.22585470e-01, 4.66851210e-01, 5.36839920e-01, 9.51087042e-02],
[8.74929100e-02, 9.12235300e-02, 8.91159090e-01, 3.88725280e-02],
[9.36443830e-01, 8.16299420e-01, 2.90021130e-01, 2.89175878e-01],
[9.26354550e-01, 9.51074570e-01, 8.49412000e-03, 1.76092602e-01],
[5.72510800e-02, 3.56584500e-02, 9.67113730e-01, 7.74680782e-01],
[1.10646890e-01, 1.10709490e-01, 8.85004310e-01, 8.08970193e-01],
[9.30983140e-01, 9.85525760e-01, 6.47764700e-02, 3.51535913e-01],
[9.16176650e-01, 8.13787300e-01, 2.80715970e-01, 7.69428516e-01],
[9.34773620e-01, 8.73895270e-01, 1.23538120e-01, 5.72796569e-01]])
# Remove the dependence of the last dimension :
data[:,3] = np.random.uniform(size=100)
# use this specific breakpoint :
breakpoint = np.array([0.57425735, 0.52599749, 0.43842457, 0.66851334])
# Dimensions
d = data.shape[1] # Number of variables
M = 2 ** d
n = data.shape[0] # Number of observationsa
N = 999 # Number of bootstrap resamples
# compute prerequisites : Thoose prerequistes dont need optimisation.
binary_repr = np.arange(2 ** d)[:, None] >> np.arange(d)[::-1] & 1 # this is already optimized
min = breakpoint * binary_repr # (M,d)
max = breakpoint ** (1 - binary_repr) # (M,d)
lambda_l = np.prod(max - min, axis=1) # (M,)
########### Algorithm
# small function : the 3 imputs needs to be broadcastable to each other,
# and it returns something that is shaped as the broadcast of the 3 inputs
def compute_statistic(A, B, C): return np.sum(B ** 2 / C - 2 * A * B,axis=0)
def is_in(data,min,max): return np.logical_and(data >= min, data < max)
def compute_f_l(are_in,axes = (2,1)):
return np.mean(np.all(are_in, axis=axes[0]), axis=axes[1])
def compute_repeats(max,min,data,random_numbers,are_in):
maxes = np.repeat(max, d, axis=1) # (M,d*d)
mines = np.repeat(min, d, axis=1) # (M,d*d)
zes = np.repeat(data, d, axis=1) # (n,d*d)
random_numbers = np.repeat(random_numbers, d, axis=2)
are_in_rep = np.repeat(are_in, d, axis=2) # (M,n,d*d)
return maxes,mines,zes,random_numbers,are_in_rep
def compute_first_piece(are_in_rep,masks,maxes,mines):
f_k = np.mean(np.all(are_in_rep[..., masks].reshape(M, n, d - 1, d), axis=2), axis=1) # (M,d)
lambda_k = np.prod((maxes - mines)[:, masks].reshape((M, d - 1, d)), axis=1) # (M,d)
rez_k = np.flip(f_k / lambda_k, axis=1)
return rez_k
def compute_z_reps(zes,rev_masks,random_numbers):
z_reps = np.repeat(zes, N, axis=0) # (N,n,d*d)
z_reps[:, :, rev_masks] = random_numbers[:, :, rev_masks] # (N,n,d*d)
return z_reps
def compute_bootstrap(z_reps,mines,maxes,rez_k,lambda_l):
are_in_boot = is_in(z_reps, mines, maxes).reshape(M, N, n, d, d)
f_ls = compute_f_l(are_in_boot,axes=(3,2)) # (M,N,d)
values = compute_statistic(rez_k,f_ls,lambda_l) # (N,d)
return values
for i in np.arange(20): # just repeat 20 times to augment values of times.
# Now we get to the algorithm itself.
are_in = is_in(data[None,], min[:, None, ], max[:, None, ]) # (M,n,d)
f_l = compute_f_l(are_in) # (M,)
# Draw random numbers :
random_numbers = np.random.uniform(size=(N, n, d)) # (N,n,d)
# build indices selectors :
masks = (np.identity(d) == 0).reshape(d * d) # (d*d)
rev_masks = np.logical_not(masks)
# simplify broadcasting by repeating a little the data : # <<<<<<<<<<<< Here problems might start !
maxes,mines,zes,random_numbers,are_in_rep = compute_repeats(max,min,data,random_numbers,are_in)
# Compute a piece of the result :
rez_k = compute_first_piece(are_in_rep,masks,maxes,mines)
# The observed values of the statistic can now be computed :
value = compute_statistic(rez_k, f_l[:,None], lambda_l[:, None]) # (d,)
z_reps = compute_z_reps(zes[None, :, :],
rev_masks,
random_numbers)
# Now compute the same statistic value, but bootstrapped :
values = compute_bootstrap(z_reps[None,],
mines[:, None, None, ],
maxes[:, None, None, ],
rez_k[:,None],
lambda_l[:, None, None])
# return the result :
result = np.mean(value < values, axis=0)
print(result)
cp.disable()
cp.print_stats()
</code></pre>
<p><em>Edit : Was originally posted on <a href="https://stackoverflow.com/posts/59649929">SO</a> but after comments we thought it was better suited for code review.</em></p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-10T15:45:41.823",
"Id": "481654",
"Score": "0",
"body": "You can try \"Numba\" but it's rare it will do any good since everything seems to be vectorized here. There's although few places where \"Numba\" stands out since it optimizes your python code. Otherwise tensorflow and gpu. Not an answer since I don't know if that will work."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-08T16:38:23.830",
"Id": "235304",
"Score": "8",
"Tags": [
"python",
"numpy"
],
"Title": "Calculation of independence test statistic"
}
|
235304
|
<p>Im am currently wrapping all OpenGL ressources (which are simply a GLuint) into classes that own and manage the deletion of them, to make it possible to use OpenGL in an object oriented fassion. Since these classes manage a ressource that get's destroyed in their destructor i know the rule of five is something to think about. This is how my Shader classes look like:</p>
<p>Shader.h :</p>
<pre><code>#pragma once
#include <glad/glad.h>
#include <string>
class Shader
{
public:
Shader(GLuint type, const std::string& shaderPath);
virtual ~Shader();
Shader(const Shader& s) = delete;
Shader& operator = (const Shader& s) = delete;
Shader(Shader&&) = default;
Shader& operator = (Shader&&) = default;
private:
/*
The Shader objects are passed to the constructor
of ShaderProgram that compiles the glShaderProgram -> needs id
*/
friend class ShaderProgram; //
GLuint id = 0;
};
class FragmentShader : public Shader
{
public:
FragmentShader(const std::string& shaderPath) : Shader(GL_FRAGMENT_SHADER, shaderPath) {};
};
class VertexShader : public Shader
{
public:
VertexShader(const std::string& shaderPath) : Shader(GL_VERTEX_SHADER, shaderPath) {};
};
</code></pre>
<p>Shader.cpp :</p>
<pre><code>Shader::Shader(GLuint type, const std::string& shaderPath)
{
std::ifstream fstram;
std::stringstream sstream;
fstram.exceptions (std::ifstream::failbit | std::ifstream::badbit);
fstram.open(shaderPath);
sstream << fstram.rdbuf();
fstram.close();
id = glCreateShader(type);
auto data = sstream.str();
const char* dataPtr = data.c_str();
glShaderSource(id, 1, &dataPtr, NULL);
glCompileShader(id);
int result = 0;
glGetShaderiv(id, GL_COMPILE_STATUS, &result);
if(result == 0)
{
char infolog[1024];
glGetShaderInfoLog(id, 1024, NULL, infolog);
throw std::runtime_error(infolog);
}
}
Shader::~Shader()
{
glDeleteShader(id);
}
</code></pre>
<p>Use them like this:</p>
<pre><code>try
{
VertexShader vs("Path to file");
FragmentShader fs("Path to file");
}
catch(const std::exception& e)
{
std::cerr << e.what() << std::endl;
}
</code></pre>
<p>Because i am planning to implement classes for the ofther OpenGL ressources like buffers, textures, etc in a similar fassion i would like some feedback. Any insight on mistakes that i made or how to improve my code are very appreciated. And do i need to declare move assignment and move constructor in the derived shader classes too?</p>
|
[] |
[
{
"body": "<p>Is it really necessary to split vertex and fragment shaders into their own type? It causes the type to go from 4 bytes to 16 bytes on a typical 64 bit processor, just for it to store a vtable ptr for the destructor that's never going to do anything different. </p>\n\n<p>They could privately inherit and not have a virtual destructor, but I would rather they just be a single class and let incorrectly assigning shaders to a program be a runtime error. There's already a potential failure point when creating the shader program, and the gl error should alert the client to what went wrong, so it's not introducing a new point of failure.</p>\n\n<p>You can't use the default move functions because they won't zero-out the id, and <code>glDeleteShader</code> will be called twice on the same id.</p>\n\n<p>Consider using a factory function to create shaders from file instead of doing file IO in the constructor. It will make it easier to test, and it's also not obvious that this is a blocking function that shouldn't be called on UI threads. </p>\n\n<p>It also makes it more portable to possibly use in a context that doesn't want to use fstreams for doing file IO, for example if you had zipped shaders or hosted them on a cloud it would make more sense to pass in a byte array which is what <code>glShaderSource</code> will expect.</p>\n\n<p>If you're going to use a path constructor, consider std::filesystem::path.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-08T18:42:11.847",
"Id": "235315",
"ParentId": "235307",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "235315",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-08T17:13:55.003",
"Id": "235307",
"Score": "2",
"Tags": [
"c++",
"opengl"
],
"Title": "Shader class in OpenGL"
}
|
235307
|
<p>I have a situation where we need to be able to run multiple instances of a Spring app with dynamically assigned ports defined at runtime. I need to be able to get an available port at runtime, create some associated file structure for dedicated logs &c, and plug the port number into the command-line arguments passed to Java.</p>
<p>Below is an adaptation of some code I pulled off the Unix exchange and tweaked. It currently seems to do what I need - runs in single-digit milliseconds, accepts upper an lower bounds or provides reasonable defaults, won't spin off into an infinite loop if someone does something stupid like specifying the same upper and lower bound as a port that's already in use, doesn't actually send a newline into a port that's already in use, etc.</p>
<p>Anyone see a flaw, or a way to make it cleaner?</p>
<p>I know there's a possible race condition, and suggestions for that are welcome. I don't need non-bash portability. </p>
<pre><code>getPort() {
local -i lo=${1:-50000} hi=${2:-65000}
local -i range=$(( hi - lo + 1 )) candidate
for try in {1..999}
do candidate=$(( lo + ( $RANDOM$RANDOM % range ) ))
{ printf "" >/dev/tcp/127.0.0.1/$candidate ||
printf "" >/dev/tcp/-thisIP,redacted-/$candidate
} >/dev/null 2>&1 || { echo $candidate; return 0; }
done
return 1;
}
</code></pre>
<h3>ADDENDUM</h3>
<hr/>
<p>Since I am only interested in ports on the local machine, I should be ok if I test both localhost and every IP for this machine, which in my case will be only one. (IP redacted above.)</p>
<p>Yes?</p>
<p>Also, since someone could pass in 0 and 65000 as args, just using a 16bit <code>$RANDOM</code> alone doesn't cover all cases. I took the cheesy-easy route and used <code>$RNADOM$RANDOM</code>, which has some weirdness since about 2/3 of the time the 5th digit from the right will only be one of <code>[123]</code>, and the distribution curve will slope up from the low end, but these aren't problematic in my case. Still, I'd love to see examples of how to smooth it out.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-08T17:59:37.957",
"Id": "460446",
"Score": "0",
"body": "Is it possible to modify your server program to run on \"any\" port (i.e. pass `0` as port number) and output the one it was given? That would avoid both polling and the race condition."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-08T19:42:09.450",
"Id": "460471",
"Score": "1",
"body": "It's a dedicated server, so polling isn't really a problem. This runs on average in 2ms, returning the first port it tries, as almost all will be available. Even the race condition is unlikely to ever be an issue because nothing else will likely be grabbing ports. Spring boot already has a mechanism to dynamically assign by using port zero, but there is apparently some admin app code that gets confused by that, and the devs said it's sometimes buggy. This will let me bypass all their issues - but to answer your question, I have no control over their code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-10T11:25:53.210",
"Id": "460738",
"Score": "0",
"body": "Please don't change your code after receiving an answer. You now have two different answers, addressing different versions of the question. That's unhelpful and confusing. See [What should I do when someone answers my question?](/help/someone-answers)."
}
] |
[
{
"body": "<p>There's an obvious flaw if the candidate port is closed on <code>127.0.0.1</code> but open on a different interface that you want your service to bind to. That's particularly relevant if you want it to listen on all interfaces (<code>0.0.0.0</code>).</p>\n\n<p>If your service binds to the localhost address, then that's obviously not a concern.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-08T19:37:07.893",
"Id": "460470",
"Score": "0",
"body": "That's a good point. Have a suggested solution?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-08T20:45:08.863",
"Id": "460486",
"Score": "0",
"body": "Sorry, no suggested solution in a shell script (all I can think of is writing a C program to bind to the address/port combination). An alternative approach may be to use the output of `netstat -A inet -l`, or to discover where it gets the list of listening ports; I didn't pursue that far enough."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-08T21:37:01.090",
"Id": "460492",
"Score": "0",
"body": "Assuming no multi-IP NIC cards, shouldn't I be ok if I test both localhost and the machine's IP? I only care that the port be available on this machine... right?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-08T21:39:16.443",
"Id": "460493",
"Score": "1",
"body": "If you're in a position to make such assumptions about your target environments, then go ahead (but put a big fat comment in the code so that you know its limitations!)."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-08T17:57:15.120",
"Id": "235312",
"ParentId": "235310",
"Score": "5"
}
},
{
"body": "<h3>Use more functions</h3>\n\n<p>The expression that checks if a port is available is a bit complex.\nIt would be good to encapsulate it in a separate function.</p>\n\n<h3>Avoid hardcoded values</h3>\n\n<p>It seems you are using a hard-coded IP address buried in the middle of the code.\nIt would be better to extract such values and define them at the top of the script.\nThen you wouldn't even need to redact anything for code review purposes.</p>\n\n<h3>Validate input</h3>\n\n<p>The function accepts ranges that wouldn't make sense.\nIt would be good to add input validation to fail fast with a clear message.</p>\n\n<h3>Exploring a list of things in random order</h3>\n\n<p>In this example \"things\" is port numbers within a range.\nA simple technique to explore all of them in random order is to enumerate and shuffle.</p>\n\n<pre><code>ports \"$lo\" \"$hi\" | shuf | while read candidate; do\n if is_available \"$candidate\"; then\n echo \"$candidate\"\n return\n fi\ndone\nreturn 1\n</code></pre>\n\n<p>Where <code>ports</code> is a custom function that produces the candidate ports within the specified range, and <code>shuf</code> is the GNU shuffle tool or a custom function that implements <a href=\"https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle\" rel=\"nofollow noreferrer\">Fisher-Yates shuffle</a> using a Bash array.</p>\n\n<p>If in the typical use case you expect to find an available port easily in at most a few random trials, then I agree that this shuffling technique would be overkill, and your current method is just fine.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-10T11:23:15.673",
"Id": "460737",
"Score": "1",
"body": "Why not simply `seq \"$lo\" \"$hi\"` instead of writing a custom function `ports`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-10T11:48:27.723",
"Id": "460739",
"Score": "0",
"body": "@TobySpeight `seq` is not recommended, and it's not a standard tool, so not always available. If it was, then sure, that would be fine."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-10T12:07:18.463",
"Id": "460741",
"Score": "0",
"body": "Shame we can't use `printf '%d\\n {$lo..$hi}` (brace expansions are performed before parameter expansions, unfortunately)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-10T14:45:08.857",
"Id": "460764",
"Score": "0",
"body": "The \"hardcode\" is localhost. That IP never changes. I calc the local machine's IP dynamically for the second one. \n\nMore functions is good in a large, shared codebase, but there's a vanishing point where the benefits are outweighed. That way lies Java and other madness.\n\nValidation is a good point, thanks.\n\nPassing a list through `shuf` requires generating a whole list and running `shuf`, when on this system the odds are any random port will be ok on the first pass. On a busier system (like my laptop) it would be worth the extra overhead, but this saves notable deploy time over 40 svcs."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-11T13:58:18.497",
"Id": "460904",
"Score": "0",
"body": "@PaulHodges The hardcoded value I referred to is \"-thisIP,redacted-\", not localhost. \"More functions\" is a relative term. I recommend more than what you used (= the concrete example I gave), and certainly less than the vanishing point you described."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-13T14:16:11.947",
"Id": "461117",
"Score": "0",
"body": "Ah. That IP isn't hardcoded, but the code was not locally visible or relevant, and I didn't want to distract from the point. Apologies."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-10T07:04:04.303",
"Id": "235400",
"ParentId": "235310",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-08T17:47:56.980",
"Id": "235310",
"Score": "4",
"Tags": [
"bash"
],
"Title": "Get available port from specified range"
}
|
235310
|
<p><strong>EDIT2</strong>: There is a <a href="https://codereview.stackexchange.com/a/235445/212940">summary below</a> of the findings with new improved code and run time results achieved. </p>
<p><strong>Multi threaded follow up</strong> has been <a href="https://codereview.stackexchange.com/questions/235517/multi-threaded-high-performance-txt-file-parsing">posted here</a>. </p>
<hr>
<p>I find, in my daily programming, that text-file parsing (various CSV, and ad-hoc formats etc) is still very common. When data size gets to >1MB, performance becomes a critical aspect. Reading files, parsing for separators and converting contents (often to floats or ints) can be a very slow process. </p>
<p>The approach was to pull in existing tools, which can help, and make them convenient, rather than to reinvent the wheel. So I have curated and written helpers for some tools to help make this process convenient while achieving very high performance. </p>
<p>The <a href="https://www.reddit.com/r/dailyprogrammer/comments/dv0231/20191111_challenge_381_easy_yahtzee_upper_section/" rel="nofollow noreferrer">"Yahtzee" programming challenge</a> shall serve as an illustrative example. Clearly this is not a real world problem, but not much imagination is required to see how it translates. Follow that link for full details, but the task is basically:</p>
<ul>
<li>Read ~1MB file with about ~100,000 whitespace separated ints </li>
<li>Group them by hash map (most efficient?) </li>
<li>Find the group with the largest sum</li>
</ul>
<p>The code below achieves complete parse and compute in < 8ms on my machine (i7 2600 with SSD) for the provided <a href="https://gist.githubusercontent.com/cosmologicon/beadf49c9fe50a5c2a07ab8d68093bd0/raw/fb5af1a744faf79d64e2a3bb10973e642dc6f7b0/yahtzee-upper-1.txt" rel="nofollow noreferrer">1MB file on github</a>. Most of that is read & parse (~7ms). This represents about a 5x gain on the "naive" approach using <code><iostream></code> or <code>std::getline</code> parsing and converting. (For reference the output is "31415926535" as the sum of the largest group.)</p>
<p>Performance techniques / tricks used are:</p>
<ul>
<li>Use memory mapped file -- <code>mmap</code> . Wrapped in an RAII convenience class. </li>
<li>Use a piping mentality throughout. Never accumulate data.</li>
<li>Make no <code>std::string</code> and no copies. Use <code>std::string_view</code> throughout.</li>
<li>The <code>mmap</code> file gives a <code>const char*</code> buffer which we can parse over
and access using <code>std::string_view</code> .</li>
<li>Don't use <code>std::isnumeric</code> because it is locale dependent. Use an optimised replacement which assumes ASCII and has knowledge about the format. </li>
<li>Use <code><charchonv> from_chars</code> because it's very fast. (Only MSVC supports floats, but on gcc/clang we could use <a href="https://github.com/ulfjack/ryu" rel="nofollow noreferrer">Ryu</a>)</li>
<li>Use the awesome <code>ska::bytell_hash_map</code> <a href="https://github.com/skarupke/flat_hash_map" rel="nofollow noreferrer">from here</a></li>
<li>All the <code>os::</code>... utility wrappers are my own <a href="https://github.com/oschonrock/toolbelt" rel="nofollow noreferrer">from here</a>.</li>
<li>Compiled with <code>clang-9 -O3</code> for x64. Platform is Kubuntu 19.10.</li>
</ul>
<p>The <code>mmap</code> is key at this file size. It dropped time from ~38ms to 20ms immediately. (I realise that <code>mmap</code> is not optimal for smaller files, but those are "fast" anyway.)</p>
<p>skarupke's <code>ska::bytell_hash_map</code> is also a sigificant gain on the compute side. See here <a href="https://probablydance.com/2017/02/26/i-wrote-the-fastest-hashtable/" rel="nofollow noreferrer">for why</a>. </p>
<p>Clearly <code>mmap</code> is not very portable, but accepting that, does this represent about the best we can do?</p>
<p>Is there any other feedback about the approach or the code (including the code in <code>os::</code> namespace on github link)? </p>
<p><strong>EDIT</strong>: Based on some feedback, just a clarification. The 1MB is what I have found to be smallest size where this sort of approach makes sense. Of course 8ms is pretty quick. But the speedup from 40ms is still very relevant because the actual use case may involve either hundreds of such 1MB files or one much bigger file. We can make a large file with: <code>for i in {1..1000}; do cat yahtzee-upper-1.txt >> yahtzee-upper-big.txt ; done</code> which gives a ~1GB file. That runs in 5.8seconds on my machine. ie the whole process scales almost perfectly linearly. </p>
<p>The idea is not to optimise away every last cycle given the exact nature of this task/file. Because that tends to a) quickly have diminishing returns and b) remove any re-usability. Instead I am trying to get 80% of the possible speedup by using a few big tools (mmap, charconv, ska::bytell_hashmap, ...) and then make them conveniently usable for many many different kinds of parsing tasks with minimal or no code change.</p>
<pre><code>#include "flat_hash_map/bytell_hash_map.hpp"
#include "os/fs.hpp"
#include "os/str.hpp"
#include <cstdint>
#include <iostream>
#include <string>
#include <string_view>
// code extracts for from os/str.hpp for hot-path
// see github link above for complete code
namespace os::str {
namespace ascii {
inline constexpr bool isnumeric(char c) {
return (c >= '0' && c <= '9') || c == '+' || c == '-' || c == '.' || c == ',' || c == '^' ||
c == '*' || c == 'e' || c == 'E';
}
} // namespace ascii
/// ... skip
inline std::optional<std::string> trim_lower(std::string_view word) {
word = trim_if(word, ascii::isalpha);
if (!word.empty()) {
std::string output{word};
// tolower is redundant for this example, but not significant
std::transform(output.begin(), output.end(), output.begin(),
[](auto c) { return ascii::tolower(c); });
return std::optional<std::string>{output};
}
return std::nullopt;
}
template <typename ActionFunction, typename Predicate = decltype(ascii::isalpha)>
void proc_words(std::string_view buffer, const ActionFunction& action,
const Predicate& pred = ascii::isalpha) {
const char* begin = buffer.begin();
const char* curr = begin;
const char* const end = buffer.end();
while (curr != end) {
if (!pred(*curr)) {
auto maybe_word =
trim_lower(std::string_view{&*begin, static_cast<std::size_t>(curr - begin)});
if (maybe_word) action(*maybe_word);
begin = std::next(curr);
}
std::advance(curr, 1);
}
}
} // namespace os::str
// EOF os/str.hpp
// start main code
std::uint64_t yahtzee_upper(const std::string& filename) {
auto mfile = os::fs::MemoryMappedFile{filename};
auto max_total = std::uint64_t{0};
auto accum = ska::bytell_hash_map<std::uint64_t, std::uint64_t>{};
os::str::proc_words(
mfile.get_buffer(),
[&](std::string_view word) {
auto die = os::str::from_chars<std::uint64_t>(word);
auto total = accum[die] += die;
if (total > max_total) max_total = total;
},
os::str::ascii::isnumeric);
return max_total;
}
int main(int argc, char* argv[]) {
if (argc < 2) return 1;
std::cout << yahtzee_upper(argv[1]) << '\n';
return 0;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-08T19:28:28.733",
"Id": "460464",
"Score": "1",
"body": "Can you try to put the code in one file? It would be easier to review and benchmark that way."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-08T19:56:08.283",
"Id": "460477",
"Score": "2",
"body": "@BjörnLindqvist\nif you want something that \"just compiles and runs\" I have concatenated everything into one file here (3000+ lines!, because it includes the ska::hashmap): https://gist.github.com/oschonrock/6ee9ff225f0805d82e31351c6204c8d3"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-08T21:12:15.017",
"Id": "460487",
"Score": "2",
"body": "Thanks! As @butt said in the answer, it matters *a lot* if the file is cached or not. So when benchmarking, you need to run `sync; echo 3 > /proc/sys/vm/drop_caches` between runs to [clear caches](https://www.tecmint.com/clear-ram-memory-cache-buffer-and-swap-space-on-linux/), otherwise you'll be measuring the wrong thing."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-08T21:13:52.763",
"Id": "460488",
"Score": "2",
"body": "@BjörnLindqvist\nI agree it matters. But I think I want it cached. I don't want to measure disk performance. I want to measure file read, parse and compute performance. So I was actively looking for OS caching..?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-08T21:17:14.240",
"Id": "460490",
"Score": "0",
"body": "@BjörnLindqvist\nJust ran the big 1GB file with and without drop cache. No much difference. 5.8s vs 6.1s. \"real 0m5.810s sys 0m0.076s\" vs \"real 0m6.137s sys 0m0.216s\""
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-08T21:21:28.693",
"Id": "460491",
"Score": "0",
"body": "@BjörnLindqvist @butt is right, my SSD is about 500MB/s so the 1GB should read in about 2sec and the whole thing takes 5.8s. So the disk is not the bottleneck even without cache. The point with mmap is that the OS can load the required pages of the file in the background on a kernel thread while the C++ userspace code is busy parsing and hashtable'ing the `int`s."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-09T07:04:35.447",
"Id": "460525",
"Score": "3",
"body": "Yes, mmap is excellent, especially for files that are hot in the pagecache. (Even if not, faultaround / speculative prefault helps). Possible downsides include not using hugepages, which might make it worse for multiple passes over the input data. Things to try: `mmap(MAP_POPULATE)` if your file isn't huge and you expect it to be hot in pagecache. That should wire up the page tables, avoiding soft page faults as you read it. But if it's not in RAM at all, that prevents overlapping I/O with computation on the first part of the file :/"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-09T07:37:18.373",
"Id": "460532",
"Score": "0",
"body": "@PeterCordes That's interesting, I have not played with those options at all. Will take a look. Thanks"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-09T12:25:55.890",
"Id": "460577",
"Score": "0",
"body": "You should probably write a benchmark, which just reads the whole file and just counts how many bytes=='0' there are (as an example for a minimal operation, so the compiler cannot optimize it away) as a baseline. - So you can separate the reading from the parsing and the algorithm."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-09T14:14:56.110",
"Id": "460592",
"Score": "0",
"body": "@Falco Yes, I did that, not as a formal benchmark, but I would comment out sections of the code and look for difference on a periodic basis. That's how I found the `std::string` in `tolower` (which was there from previous usage of this routine) as mentioned in some of the other comments."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-09T15:07:27.693",
"Id": "460599",
"Score": "0",
"body": "@Oliver, what I was saying is that this will work perfectly well in non-ASCII environments, such as EBCDIC machines, since the compiler will translate those character constants to the correct `char` values for the platform. So it's not as restricted as you believed."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-09T15:10:43.880",
"Id": "460600",
"Score": "0",
"body": "@TobySpeight\nRight that makes sense. Thanks for the clarification. It will certainly not work with \"locales\" which expect other numeric separators (eg '.' instead of ',' for ints) -- not super relevant here, but you get the idea. Nor will it work with any kind of unicode etc. -- Just checked EBCDIC ... LOL ... 0-9 => 0xF0 - 0xF9 ... haha..never knew that!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-09T15:18:03.133",
"Id": "460603",
"Score": "0",
"body": "@TobySpeight EBCDIC: and 'A' > 'a' so that will break my static assert in `tolower` (not that I am using that anymore, given other comments)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-09T15:46:14.620",
"Id": "460604",
"Score": "0",
"body": "C and C++ both guarantee that digits `0`..`9` have consecutive code-points, so that test is safe. I see no `tolower` in the question, so I can't comment on that. And it should be fine with Unicode, providing your `char` type is up to the job (or use UTF-8, in which 7-bit characters are identical to ASCII)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-09T16:02:53.170",
"Id": "460607",
"Score": "0",
"body": "yup. the `tolower` (used inside `proc_words` in this example, eventhough it probably should'nt have been) is here: https://github.com/oschonrock/toolbelt/blob/master/os/str.hpp"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-09T16:30:19.830",
"Id": "460613",
"Score": "0",
"body": "Moderator sidenote: While the comments here are in the vast majority topical, comments are not the correct place for an extended discussion. For such purposes, please make use of [chat] :) In addition some of the points made here could be added as supplementary material to an answer (or possibly to the question). Thanks!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-09T17:36:29.813",
"Id": "460621",
"Score": "0",
"body": "Why would you not use (f)lex?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-09T17:45:37.530",
"Id": "460625",
"Score": "0",
"body": "Did You look at : https://stackoverflow.com/questions/1042110/using-scanf-in-c-programs-is-faster-than-using-cin/12762166?r=SearchResults#12762166"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-09T18:50:49.693",
"Id": "460640",
"Score": "0",
"body": "@jamesqf no reason. Just not familiar with it. This is a good point to start? https://ftp.gnu.org/pub/old-gnu/Manuals/flex-2.5.4/html_node/flex_19.html"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-09T18:51:38.153",
"Id": "460641",
"Score": "0",
"body": "@RobertAndrzejuk I didn't, but we are way faster than any of those techniques here."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-09T18:53:27.620",
"Id": "460642",
"Score": "0",
"body": "@OliverSchonrock are You comparing their times to your times or is this based on Your own benchmark using the technique specified?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-09T19:04:40.533",
"Id": "460644",
"Score": "0",
"body": "@RobertAndrzejuk\nI am not comparing benchmarks (which is slightly naughty) but I think I have spent enough time to to know that you can't get anywhere near fast with `cin >> intvar`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-09T19:21:05.033",
"Id": "460650",
"Score": "0",
"body": "@RobertAndrzejuk just for the record. I ran their num generator and then consumed it with my code doing just the parity xor => 0.7s. vs their fastest code (with the sync=false) takes 3.3s on my hardware. So almost 5x faster, which correlates well with my experience of this sort of approach."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-09T20:57:51.267",
"Id": "460662",
"Score": "0",
"body": "The newfangled hipsters in the first reddit link was a little sad to see when. `perl -nE '$x{$_}+=$_;END{say((sort {$b<=>$a} values %x)[0])}' yahtzee-upper-1.txt` did it in 25 ms already. :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-09T21:08:37.660",
"Id": "460664",
"Score": "0",
"body": "@pipe I don't see that...where?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-09T21:21:13.693",
"Id": "460666",
"Score": "0",
"body": "@OliverSchonrock I mean it's sad that there are 160 answers and not a single perl oneliner (which used to be the norm) even though it's shorter and faster than most of the answers there."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-09T21:29:54.187",
"Id": "460669",
"Score": "0",
"body": "@pipe Indeed! And yes, that is impressive for a 1 line script! (not that I can read it LOL!)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-09T22:57:00.520",
"Id": "460684",
"Score": "0",
"body": "Out of curiosity, as you're going for performance here, what is your control measurement that you're comparing against? mmap is great and all but I would be curious to see the comparison to dual buffering block reads and inline parsing."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-10T00:16:00.553",
"Id": "460692",
"Score": "0",
"body": "@EmilyL. My starting point was the \"simple (naive?) and idiomatic\" `cin >> intvar` or `std::getline` styles. These are the most common approaches, and they are convenient. But not fast. The techniques described here will produce a 4-10x gain over those depending on the circumstances. I also tried single buffer `std::fread` `std::scanf` and friends. These produce performance similar or slightly better than the 1st set. I have not tried double buffering. Do you have some example code?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-10T20:01:20.887",
"Id": "460805",
"Score": "0",
"body": "@Oliver Schonrock: It should do, though I'd recommend starting from the beginning of the manual if you're new to the idea of scanners. (I would also write the scanner and associated code in C, and call it as \"extern C\", but that's just personal taste :-)) Note that a flex scanner is pretty much equivalent to the perl regex, or grep/awk. They're just using regular expressions to define state machines, which can be much faster than straightforeward programming."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-10T20:23:44.897",
"Id": "460807",
"Score": "0",
"body": "@jamesqf Yeah I am familiar with the concept and thought that's what it was from my 2sec glance. But I reckon it might just be easier to `#include` this: https://www.youtube.com/watch?v=8dKWdJzPwHw ;-) for a \"textfile level challenge\" a little regexp (compiled as part of your 1 line c++ programme) is probably easier to write than a whole lex grammar which you to compile separately. She has done very well there BTW ;-) https://gcc.godbolt.org/z/x64CVp"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-11T19:42:46.380",
"Id": "460920",
"Score": "0",
"body": "@Oliver Schonrock: I can't comment on the regexp, since I learned long ago that anything presented as a video is not really comprehensible to me. (So I never waste my time trying.) As to what's easier, it depends on what you're used to. I'm used to lex, so writing something simple is not a challenge, and separate compilation is what makefiles are for."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-12T00:05:34.660",
"Id": "460945",
"Score": "0",
"body": "Double buffering is a common technique. In this case you would issue an asynchronous read to fill the \"back\" buffer simultaneously while you are processing the \"front\" buffer. When you're done processing the front buffer, you swap the pointers to the buffers and start processing what was previously the back buffer while you issue another asynchronous read for the new back buffer. This way you'll always have a buffer of data ready for processing."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-12T02:54:18.340",
"Id": "460947",
"Score": "0",
"body": "@EmilyL.\nYeah,I understand that. And I could write it, but it's not a priority. Unless you want to write some proposed answer. I don't think this is the bottleneck, see the summary here: https://codereview.stackexchange.com/a/235445/212940 140ms for the mmap to spin through the whole 1GB file. I have started writing a muilti threaded parsing version. With 4 threads I am just above 400ms, 8 threads is not much better, I am working on locality. So I am not highly motivated to write code for double buffereing which I don't believe will make it any faster."
}
] |
[
{
"body": "<blockquote>\n <p><strong>Update</strong></p>\n</blockquote>\n\n<p>I made a bare-bones yahtzee solver with no error checking in pure C++ (no mmap). The code is considerably more complex than mmapping, but is more portable, more generic, and seems to work just fine.</p>\n\n<p>With a single-producer-single-consumer pattern and 64k buffers(arbitrary) and got <strong>(0.97s)</strong>: </p>\n\n<pre><code>$ /usr/bin/time -f \"%e %U %S %M\" ./a ~/yahtzee-upper-big.txt \n31415926535000\n0.97 1.01 0.37 663528\n</code></pre>\n\n<p>I compared to an mmap implementation (without using the SPSC) <strong>(1.04s)</strong>:</p>\n\n<pre><code>/usr/bin/time -f \"%e %U %S %M\" ./a ~/yahtzee-upper-big.txt \n31415926535000\n1.04 0.98 0.05 884192\n</code></pre>\n\n<p>mmap has almost no system time while fstream does, presumably memcpying or buffering. C++/fstream has about the same latency and uses less memory, but uses much more processing time. I speculate that the lower peak memory usage is due to the system being able to page-out memory faster than mmap.</p>\n\n<p>Here's the test code. It's pretty sloppy and I wasn't thinking too hard about it. It is <strong><em>not</em></strong> meant to be a reference.</p>\n\n<pre><code>#include <condition_variable>\n#include <fstream>\n#include <iostream>\n#include <thread>\n#include <vector>\n\nauto constexpr kReadBlockSize = size_t{1ull << 15ull};\n\nint main(int argc, char** argv) {\n if (argc != 2) return -1;\n\n auto input_path_argument = argv[1];\n auto file_stream = std::ifstream{input_path_argument, std::ios::binary};\n if (file_stream.bad()) return -1;\n\n auto mutex = std::mutex{};\n auto condition_variable = std::condition_variable{};\n auto shared_is_finished_reading = false;\n auto shared_buffer_pool = std::vector<std::vector<uint8_t>>{};\n auto shared_buffers = std::vector<std::vector<uint8_t>>{};\n auto producer_thread = std::thread{[&]() {\n auto producer_buffer = std::vector<uint8_t>{};\n while (file_stream.good()) {\n producer_buffer.resize(kReadBlockSize);\n if (!file_stream.read(reinterpret_cast<char*>(producer_buffer.data()),\n producer_buffer.size())) {\n producer_buffer.resize(file_stream.gcount());\n }\n\n {\n auto lock = std::lock_guard<std::mutex>{mutex};\n shared_buffers.push_back(std::move(producer_buffer));\n\n if (!shared_buffer_pool.empty()) {\n producer_buffer = std::move(shared_buffer_pool.back());\n shared_buffer_pool.pop_back();\n } else {\n producer_buffer = std::vector<uint8_t>{};\n }\n }\n condition_variable.notify_all();\n }\n\n {\n auto lock = std::lock_guard<std::mutex>{mutex};\n shared_is_finished_reading = true;\n }\n condition_variable.notify_all();\n }};\n\n auto max_yahtzee_roll = 0ull;\n auto consumer_buffers = std::vector<std::vector<uint8_t>>{};\n auto is_finished_reading = false;\n auto current_parsed_value = 0;\n auto occurrance_counts = std::vector<uint32_t>();\n\n while (!is_finished_reading) {\n {\n auto lock = std::unique_lock<std::mutex>{mutex};\n condition_variable.wait(lock, [&]() {\n return !shared_buffers.empty() || shared_is_finished_reading;\n });\n\n is_finished_reading = shared_is_finished_reading;\n shared_buffer_pool.insert(\n shared_buffer_pool.end(),\n std::make_move_iterator(consumer_buffers.begin()),\n std::make_move_iterator(consumer_buffers.end()));\n std::swap(shared_buffers, consumer_buffers);\n }\n\n for (auto& buffer : consumer_buffers) {\n for (auto c : buffer) {\n if (auto digit_value = c - '0'; digit_value >= 0 && digit_value <= 9) {\n current_parsed_value *= 10u;\n current_parsed_value += digit_value;\n } else {\n if (occurrance_counts.capacity() <= current_parsed_value) {\n occurrance_counts.reserve(2ull * current_parsed_value + 1ull);\n }\n auto current_value_count = ++occurrance_counts[current_parsed_value];\n max_yahtzee_roll = std::max<uint64_t>(\n max_yahtzee_roll,\n (uint64_t)current_value_count * current_parsed_value);\n current_parsed_value = 0;\n }\n }\n }\n }\n\n std::cout << max_yahtzee_roll << std::endl;\n\n producer_thread.join();\n return 0;\n}\n\n</code></pre>\n\n<hr>\n\n<p>The internet tells me a typical SSD might read at 500MB/s, which is 0.5MB/ms or 1M in 2ms. 8ms is incredibly fast and also very close to the theoretical limit. In fact, just reading that file on a HDD is probably slower. </p>\n\n<p>The parsing code is doing a lot of unnecessary work if you're positive that the input will always be an int-per-line.</p>\n\n<p>You're accumulating the hash table by adding the value, but you actually only need to store the occurrence count since the total can be derived from the count and the key. You could store 4 byte ints instead of 8 bytes if there's only 100,000 values with a max value of 999,999,999, reducing the hash table size, though it's already so small this probably won't matter. </p>\n\n<p>You could reserve hash table space, though you might not want to reserve too much.</p>\n\n<p>You could try passing flags to the mmap to notify the os that it will be read sequentially and all the file will be read, or try to prefetch memory.</p>\n\n<p>You can skip updating the table if the current value cannot possibly be higher than the current max. For example, if a 1 is read in and the current max total is over 100,000 there's no possible way for 1s to be the highest number class so they don't need to hit the hash table. </p>\n\n<p>For small sets of data, an array might be faster than the hash map. </p>\n\n<p>You could maybe use multiple threads, but that could be challenging on small data sets to overcome the overhead of just creating them. </p>\n\n<p>At this point you could also hand optimize the parsing. Consider that the file, if well formed, will have a strict pattern of ([0-9]+\\n)+. So it could be a loop that reads a byte, multiplies the current value by 10 and adds the new value - '0', or consumes the current value if it's a \\n.</p>\n\n<p>Maybe play with compile flags too, in particular things that might make the code load faster, perhaps reducing the executable size so there's less to load. </p>\n\n<p>The hash map probably allocates heap memory, but if you made it use a giant chunk of 0-initialized global memory, that might be faster since it skips an allocation and should instead come free when the program launches.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-12T06:40:21.573",
"Id": "460967",
"Score": "0",
"body": "Comments are not for extended discussion; this conversation has been [moved to chat](https://chat.stackexchange.com/rooms/103204/discussion-on-answer-by-butt-high-performance-txt-file-parsing)."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-08T20:01:31.607",
"Id": "235317",
"ParentId": "235314",
"Score": "8"
}
},
{
"body": "<p>You say your file contains integers only. Yet your parsing code calls <code>trim_lower</code>, which doesn't make sense at all.</p>\n\n<p>At least I hope you implemented <code>tolower</code> other than in the C++ standard library, since the latter must not be called with <code>signed char</code> or <code>char</code> as argument.</p>\n\n<p>The <code>proc_words</code> function creates lots of <code>std::string</code> objects internally, which is unnecessary. No wonder your code takes so long. Since numbers are not words, you are using the completely wrong tool for this job. You should rather define <code>for_each_token</code> instead of <code>proc_words</code>.</p>\n\n<p>The <code>isnumeric</code> function is inappropriate as well. You need <code>isdigit</code> here.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-09T07:31:13.983",
"Id": "460529",
"Score": "1",
"body": "These are all valid points. Remember that these are a generic set of parsing tools and not 100% specialised for this file. `proc_words` was written for a different task originally. And yes you are right there are gains here. See my comment in @butt 's answer above. \n\nHowever \"no wonder your code is so slow\" is not reasonable. The change which eliminates the last `std::string` and the `toupper` makes a 2.8ms gain. We started at 40ms. So yes it's a good point, but it only became relevant to look at when the other 80% was done. \n\nWe want re-usable component, not \"last cycle optimisations\"."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-09T07:35:25.920",
"Id": "460531",
"Score": "1",
"body": "If you can suggest a generic architecture which supports a composable set of separator parsing, trimming and \"munging\" operators (eg tolower) which retains 80-90% of the performance of custom code, then that would be awesome. `proc_words` is a step in that direction, but I acknowledge it is far from complete. \n\nThe other changes (eg `mmap` and not using `<iostream>` / `getline`) are much bigger gains."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-09T07:41:19.780",
"Id": "460534",
"Score": "0",
"body": "is `numeric` and `tolower` and ascii aware function not from `std::` see the code and links to github above. the difference between `isnumeric` and `isdigit` from a performance POV would not be significant. There could be a \"correctness\" argument."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-09T07:43:27.760",
"Id": "460535",
"Score": "2",
"body": "BTW did you look at the implementation of `tolower` it is basically `return c | 0x20;`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-10T00:55:28.307",
"Id": "460697",
"Score": "0",
"body": "I saw the implementation of `tolower`, and I also noticed that `ascii:tolower('[') == '{'`. You're lucky that your \"words\" consist of digits and these, by coincidence already have the 0x20 bit set."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-10T01:08:36.810",
"Id": "460699",
"Score": "2",
"body": "I think you are missing the point. But I assure you. Luck has nothing to do with it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-10T22:41:26.753",
"Id": "460823",
"Score": "2",
"body": "You can write an efficient ASCII-only `tolower` that doesn't assume alphabetic to start with. It's only a couple extra operations. Using the name `tolower` for `c|0x20` is misleading: standard C `tolower` is supposed to leave non-alphabetic characters unmodified. `c|0x20` has its uses as a building block, e.g. for ASCII `isalpha` like `(c|0x20) - 'a' < (unsigned)('z'-'a')`. See [What is the idea behind ^= 32, that converts lowercase letters to upper and vice versa?](//stackoverflow.com/a/54585515) for that, and SIMD [Convert a String In C++ To Upper Case](//stackoverflow.com/a/37151084)"
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-09T04:14:12.337",
"Id": "235335",
"ParentId": "235314",
"Score": "11"
}
},
{
"body": "<p>Without sacrifying something, you can probably gain the most (wall time) by using a hint such as <code>posix_fadvise(POSIX_FADV_WILLNEED)</code>. Or, if portability is not paramount, something like <code>readahead</code> (Windows calls that function <code>PrefetchVirtualMemory</code>). Be sure to read the docs and watch for words like \"blocking\".</p>\n\n<p>The reason for wanting to prefetch is that while <code>mmap</code> is indeed awesome in its own way and totally superior to any I/O functions (let alone C++ iostream which is \"slow\" because it does a lot of stuff and is very general and flexible, it can do pretty much everything, including proper error reporting) in terms of performance, there is a huge misconception that people often fall for:</p>\n\n<p><code>mmap</code> is awesome, but it does <strong>not</strong> do magic.</p>\n\n<p>While <code>mmap</code> does prefetch, the algorithm is very non-ingenious, block sizes are small (usually something like 128k), and the sequence is very non-optimal (still, much better than other I/O). Also, linear scan hints do not really do \"magic\" either, they usually just double the prefetch size, which is still small.</p>\n\n<p>In theory, things look like this:</p>\n\n<pre><code>(OS) read + awesome magic\n(app) work, work, work, work\n</code></pre>\n\n<p>In practice, things look like this:</p>\n\n<pre><code>(OS) read ... queue, read ... queue, read\n(app) work, FAULT, ... work, FAULT, ...\n ^^^^^^ ^^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^^^\n nothing happens here! nothing happens here!\n</code></pre>\n\n<p>Even with hinting or explicit readahead, reading from disk (or SSD) is of course still much slower than your parsing so inevitably you <strong>will</strong> stall. There is no way to avoid that. In the end, we're trying to get this:</p>\n\n<pre><code>(OS) read, read, read, read, read, read, read\n(app) work, work, work, work, FAULT ... work\n ^^^^^^^^^^^^\n aww too bad, can't help this!\n</code></pre>\n\n<p>You can't prevent yourself from eventually outrunning the disk and blocking. However, you can reduce the number of stalls, push the time of the first stall back, and you can eliminate several round trip times between requests, maximizing throughput. Certainly, prefetching a couple of megabytes in one go is more efficient (even if broken down to smaller requests at driver level) than to do a lot of small requests ad-hoc as page faults are realized with sync-points in between, which are <em>necessarily</em> full stalls.</p>\n\n<p>Trying to tune the <em>actual</em> parsing is unlikely to give very substantial gains. Using a custom <code>isnumeric</code> as you've done is probably the single best thing to start with, but the gains beyond that won't likely be great.</p>\n\n<p>The reason is that you're trying to turn the wrong knob (for the same reason, the ideology-driven environmental craze that is so much <em>en vogue</em> is failing). Thing is, even if you reduce something that makes up 3% of the total to one half, or eliminate it altogether, the gains are not very substantial. The gains, however, <em>are substantial</em> if you reduce the other 97%. Which, unluckily, is hard to do because that's forementioned disk access, followed by memory bandwidth and memory latency.</p>\n\n<p>Parsing of very simple data (integers on a line), even badly implemented easily runs in the \"dozen gigabyte per second\" realm. Converting numbers is very fast and almost certainly hidden by memory latency.</p>\n\n<p>Your CPU cache is probably not much help, and prefetching most likely will not help much either. The reason being that fetching a cache line takes something around 300-400 or so cycles, and you hardly need that much to parse the data. You're still going to be memory bandwidth bound (in addition to being I/O bound).</p>\n\n<p>There's the TLB to consider, though (the CPU typically only caches ~50-60 entries). It may very much be worth it to code a \"TLB primer\" into the next couple of pages. That's a more or less no-op which somehow reads/accesses a memory location but doesn't use the result, and thus bears no dependency chain. The processor pipeline will thus (hopefully) make the latency invisible, but it will still do <em>something</em>. Very soon after, when you <strong>really</strong> access that location, it is guaranteed that no TLB miss happens and the to-be read cache line will, with some luck, already have been fetched already, too. TLB misses are painful. That's a few thousand or so cycles saved on every memory page.<br>\nYou'll have to try. Be wary of page faults blocking your thread though, it might be an advantage of having a dedicated prefetcher thread (depends on cost of spawning vs. page faults, surely only worth it for larger data sets).</p>\n\n<p>Doing away with the hashmap would help, but that only works if you do not actually <em>need</em> a map. It's a fair assumption that you do need it (or you wouldn't be using it!) so that's probably not an option. If you <em>need</em> something, well, then you <em>need</em> it. But I would really be interested in seeing what a profiler has to say about it. My uneducated guess would be 50-70% of your \"parse\" time being spent somewhere inside the hash map.</p>\n\n<p>Hash maps are, contrary to theory, utterly bad data structures performance-wise. Not as bad as <em>some</em> other structures, but still...</p>\n\n<p>That is also true for Robin Hood hashing (such as what's used in the implementation that you cite). While it is one of the better, and probably one of the best implementations, still it is adverse to performance.<br>\nIn theory, hash maps are O(1), in practice they're some calculations plus two guaranteed cache misses on every access, and usually more. Robin Hood hashing in theory has a guaranteed upper bound, blah blah. In practice, it <em>also</em> has guaranteed extra accesses as data is inserted. In theory, RH hashing shows low variance and thus clusters memory accesses together in a cache-friendly manner. In practice, when you parse megabytes of data, <em>there is no such thing as a cache</em>. You're reading gigabytes of data, and <em>that is what's in your cache</em>. None of the hash map is. Every access is (except for sheer random luck!) a guaranteed miss.</p>\n\n<p>There exist some very fast JSON and XML parsers which are so fast for the sole reason that they work in-place. They do zero allocations, and no jumping around in memory. Simple, sequential processing, front to back, overwriting stuff as they go. That's as good as it can get.</p>\n\n<p>Note that there are a couple of possible issues with that in your simple datafile. A single digit plus newline is two bytes, but an integer is four bytes (a <code>double</code> is 8). So, that probably doesn't work too well for the general case in your example (your life is much easier with XML since there's lots of extra <code><</code> and <code>></code>s around, and a lot of other noise, so you have no trouble storing your data in-place).</p>\n\n<p>Another issue is that you need a way of not modifying the mapped file. Private mapping works, of course, but that'll mark pages COW and may cause a fault with a memory copy on every modified page, depending on how intelligent the memory system is coded (private mappings actually only need to be copied when modified while there's more than one mapping). Which, if it happens, isn't precisely optimal. I wouldn't know if there is a way of somehow hinting the memory manager towards such a behavior either.<br>\nThere is <code>MADV_DONTNEED</code> which is destructive on some platforms, so one could use that on a normal mapping, but that being destructive is not standard, not portable, and doesn't work properly (i.e. reliably) either. It might very well do something to your original file (and partly, even!) that you don't want. So that's not a real option.</p>\n\n<p>In the end, you will probably either have to do a <code>memcpy</code> or read from a readonly mapping, and write to another linear buffer (which isn't quite in-place, but still orders of magnitude better in terms of access pattern and caching).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-09T20:33:16.753",
"Id": "460660",
"Score": "1",
"body": "This is very good. You've understood the issues very well. Plenty of hints for me to investigate. Thank you for your time."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-09T20:42:02.877",
"Id": "460661",
"Score": "1",
"body": "BTW, you are right about the hash map -- not for that particular file because it has very low cardinality (< 1000 unique ints). But in general, as soon as the cardinality goes up, the hash map blows it out of the water. I always comment it out when concentrating on the reading/parsing code/pipeline."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-10T13:33:22.323",
"Id": "460751",
"Score": "0",
"body": "\"The reason is that you're trying to turn the wrong knob\". Well turning IO knobs is generally not a bad idea I'd say. But then not using iostreams is basically the most essential performance improvement you can make here. iostreams despite the nice words is the worst io library I've yet to encounter. I've had situations where my parsing code was CPU limited for god's sake, which is simply insane."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-10T14:52:57.250",
"Id": "460765",
"Score": "2",
"body": "@Voo What you say is true. As someone else also pointed out `<iostream>` gets a lot better if you do `std::ios::sync_with_stdio(false);` https://stackoverflow.com/questions/1042110/using-scanf-in-c-programs-is-faster-than-using-cin/12762166#12762166 The approach outlined here is still ~4x faster though, but least we can outrun the disk if we turn off the sync!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-10T14:53:48.617",
"Id": "460766",
"Score": "0",
"body": "@Voo: That's right. Though, although I hate iostream with passion (for being slow, and for having obnoxious syntax) you have to admit that what it does is awesome. It can do input anything, output anything, and things \"just work\", plus it does 100% failsafe error handling (in a sense that if things go wrong you **will** know). The C input/output API doesn't provide that (nobody checks error codes anyway, so if something fails, that's _silent_ failure), and `mmap` doesn't even do that. You have a pointer, and your program either works, or it crashes and burns. Which, for me personally, is fine."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-10T14:54:58.983",
"Id": "460767",
"Score": "0",
"body": "One just needs to be fair insofar as the reason why iostream sucks performance-wise is really that it does things strictly correctly in a strictly no-silent-failure way. And it does it according to locale, and whatnot (with correct date and number formats, etc.etc.) Which, depending on your needs, may just be what you want, and which is a good default. Unluckily, that doesn't come for free."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-10T15:31:09.937",
"Id": "460772",
"Score": "2",
"body": "@Damon I can see your point, although I'd argue that people being able to do things like (`while (!file.eof())`) and you still needing to check return values means it's not that fool proof either. Personally I prefer say Go's approach to handling io, but they had a long time to learn from the mistakes of their predecessors. And the whole Java/.NET approach of needing several wrapper classes for optimal usage leaves a lot to be desired too."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-10T16:35:40.420",
"Id": "460782",
"Score": "2",
"body": "@OliverSchonrock: I just accidentially stumbled upon this: https://www.usenix.org/sites/default/files/conference/protected-files/hotstorage17_slides_choi.pdf -- interesting read, in particular pages 11-16. TL;DR: Demand paging is slow. Use `MAP_POPULATE`, or better yet use `MADV_SEQUENTIAL|MADV_WILLNEED` to pre-fault. Allegedly, the latter is running highly asynchronously and is up to 38% faster with fewer page faults. Not sure what kernel versions support aggressive prefaulting, but I guess the worst thing to happen if unsupported is that it's none faster."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-10T16:46:18.000",
"Id": "460783",
"Score": "0",
"body": "@Damon just tried it. No difference. I am not hitting disk I think. All cache. Just commented out the `<charconv>from_chars` call that dropped it from 2s down to 1s for a 1GB file. (I removed the hashmap long ago, just for tests). So that's close to 1GB / second which is double my disk speed. But unless I start manually coding `<charconv>` which I am not inclined to do, then ..this could be the wall already?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-10T17:46:18.803",
"Id": "460788",
"Score": "0",
"body": "`echo 1 > /proc/sys/vm/drop_caches` between runs might help with making the measurements \"fair\" (in a sense of actually hitting disk). Otherwise, you basically have prefaulted already after the first run, so of course doing it doesn't help any further. Normally, some haphazard random huge files are not already in cache, though, and must be read in from disk."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-10T19:04:44.377",
"Id": "460803",
"Score": "0",
"body": "C++ stream objects are poorly designed because they allow many ways to be used incorrectly. But I don't think they're useless or totally unusable. The slowness seems overblown and it provides a generic, platform independent way to read data from a streamable source -- that is, in a semantically distinct way from mmap. If you're doing domain specific optimizations, mmap is great, but you're making assumptions about how the code is going to be used. Consider a specialization spectrum of \"parser that turns bits into structured data\" to \"parser that reads uncached files from a HDD in a vacuum\"."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-10T22:53:15.950",
"Id": "460825",
"Score": "0",
"body": "@Damon: The OP *wants* to test the hot-in-pagecache case, e.g. for a file that some other program just wrote. Modern computers have lots of RAM, it's not rare for that to be the case. But yes, testing both cases to make sure you don't faceplant in the `drop_caches` case is a good idea. BTW, *\"dozen gigabyte per second\"* parsing is not easy to achieve. If you only look at 1 byte at a time (8-bit charset like ASCII), that's going to be *maybe* 1 byte per clock cycle, or 4GB/s at 4GHz. To saturate dual-channel DRAM bandwidth on a modern desktop you need to load about 8 bytes per clock cycle."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-10T23:03:44.557",
"Id": "460826",
"Score": "0",
"body": "@OliverSchonrock: To go faster than 1B/cycle you'd need SIMD. But parsing decimal strings into binary integers is hard. [How to implement atoi using SIMD?](//stackoverflow.com/q/35127060). Although that SSE4.2 atoi has a throughput of about 16 cycles per integer on Haswell so it might lose for short integers, if branch prediction doesn't kill performance for a `total = 10*total + digit` loop. Could be simplified by removing leading `+` and `-` handling. OoO exec can overlap execution of the `10*total + c-'0'` iterations across different lines..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-10T23:07:04.460",
"Id": "460828",
"Score": "0",
"body": "`memcpy` + in-place is almost never good; process on the fly so you can interleave computation with CPU hardware prefetch of data and TLB. Otherwise yes, agreed with your final points about in-place to avoid touching even more memory. x86 does have NT software prefetch which tries to reduce cache pollution (e.g. bypassing L2, and only using 1 way of the sets in L3), but tuning the prefetch distance is hard and system-dependent, so it's fairly brittle."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-10T23:08:21.813",
"Id": "460829",
"Score": "0",
"body": "@PeterCordes Yes that sounds right. See comment under other post. The single byte XOR got heavily SIMD's with clang -O3 (I checked the ASM) and that's how I got 14GB/s. I think parsing ints at this rate is a probably a bridge too far? it would never be reusable to anything else?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-10T23:14:33.410",
"Id": "460831",
"Score": "0",
"body": "@OliverSchonrock: From arbitrary decimal strings, yeah, no chance. SIMD xor will go 16 bytes at a time (or 32 with `-march=native` using AVX). If you know they're limited to 4 bytes or 8 bytes, or padded to fixed width, you could go faster. string->int parsing is not exactly rare, though, but SIMD optimizations are going to come from any specific assumptions you can make. Which of course makes it specific to one use-case. The link in my last comment is supposed to be usable for JSON after copying the chars to a `0`-terminated buffer, but by that point it becomes pretty expensive."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-10T23:25:55.337",
"Id": "460834",
"Score": "0",
"body": "@OliverSchonrock: to get anywhere near that kind of speed, you're going to need multiple parsing threads. You could for example start another thread half way through a large file, and have it find the end of a line. (This only works for file formats that are \"self synchronizing\", where you can find a whatever boundary where you can start parsing after seeking to the middle, uniquely. Or you'd need an index. And of course the thread(s) all have to agree on who starts where.) You might have multiple threads parse into arrays of `int` for another to hash, or merge hash tables at the end..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-10T23:27:15.743",
"Id": "460835",
"Score": "0",
"body": "@OliverSchonrock: Finding good ways to divide up work between threads is hard because inter-thread synchronization can be relatively expensive. A lockless hash table using atomics is possible but might be slower than merging after."
}
],
"meta_data": {
"CommentCount": "18",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-09T20:23:11.080",
"Id": "235379",
"ParentId": "235314",
"Score": "22"
}
},
{
"body": "<h1>Build a userland threaded prefetch</h1>\n\n<p>In addition of <a href=\"https://codereview.stackexchange.com/a/235379/115494\">Damon excellent</a> answer, I would like emphasize this: trying to add any optimization only to be limited by disk throughput is a <strong>waste of time.</strong></p>\n\n<p>It's something that's hard to see and even harder to believe. And so this answer.</p>\n\n<p>Your desktop machine probably has more than one CPU, and certainly any server your code may run will be by dozen of CPUs by now.</p>\n\n<p>So a portable solution the get 80% of that critical performance is to code a threaded file prefetcher. Say, a separate thread dedicated to read <code>N</code> sequencial pre-allocated buffers of <code>M</code> size, while the parsing occurs in another thread.</p>\n\n<p><code>N</code> and <code>M</code> are left for your experimentation because you <strong>most probably</strong> will discover the parsing thread will be starving most of time, even after tweaking these numbers. This is even more true in the world of SSD drivers, where scheduling disk reads in parallel does not have a dramatic effect anymore.</p>\n\n<p>You can add a alert into the prefetcher to warn about a full buffers situation, <strong>and only when</strong> worry about parser or processing optimization.</p>\n\n<h1>Then build a thread parser</h1>\n\n<p>Every ms spend in reading is a ms wasted in parsing. And other ms wasted in processing.</p>\n\n<p>Leave your specific code simple and readable, but a thread parser, with small data accumulation may be a significant improvement.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-10T16:31:26.640",
"Id": "460780",
"Score": "1",
"body": "Yes, this is true. And that is part of why `mmap` brings benefits, because (without having to code it ourselves), the kernel is working alongside the userland code (pre-)fetching the data. mmap scheduler won't be ideal hence Damon's and other's suggestions above trying to tune it -- I am yet to see a benefit from that. I am getting >400MB/s parsing now. Which is close to the disk speed, but I am not convinced that my SSD is the bottleneck. Because the 1GB file should be cached after the first run (16GB ram)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-10T17:33:01.443",
"Id": "460785",
"Score": "2",
"body": "You may be not convinced that disk is you bottleneck, but consider this: every ms spend in reading is a wasted ms of parsing plus a wasted ms of processing. If you a are close to the disk limit anyway, the best bang for you buck is simple: threads."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-10T17:40:39.780",
"Id": "460786",
"Score": "1",
"body": "Threads for what? Parsing? If I comment out the parsing (just a placebo XOR to prevent the code disappearing), I get >1GB/sec (0.8s for 900MB file -- down from 2s). That is at 2x disk speed, so this is not about that. A 2x gain is possible before hitting wall with mmap. But only by radically refactoring the parsing code or using threads for that (and that will introduce massive memory/cache contention)..... I would stop here TBH."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-10T17:54:23.740",
"Id": "460789",
"Score": "1",
"body": "Updated answer. Two (additional) threads. One for reading, other for parsing (with I believe is general in your case). Leave your specific code simple. The threaded parser produces a single linked list of parsed data to the processing code to pull and slab free."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-10T18:25:44.613",
"Id": "460796",
"Score": "0",
"body": "(Down-voters please comment.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-10T22:33:39.440",
"Id": "460818",
"Score": "0",
"body": "@OliverSchonrock: a prefetch thread to pre-fault an mmaped file might be worth considering, if you don't want to just use `mmap(MAP_POPULATE)` or `madvise(MADV_WILLNEED)`. That might get hard and soft page faults out of the way, leaving a single-threaded parser to only deal with TLB misses."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-10T22:36:00.270",
"Id": "460822",
"Score": "0",
"body": "`read` into shared buffers would also work, but needs synchronization between fetch and work threads. (It's no longer simply a *pre*-fetch, it is the actual fetch.) That can be fairly cheap if you have enough space to be pure producer-consumer, just publish a read-position via `atomic<size_t>` with `memory_order_release` / `acquire.. But if you want to recycle buffers that the consumer has finished with, then you need another var going the other way. I guess that could still be cheap for a big circular buffer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-10T23:05:46.800",
"Id": "460827",
"Score": "0",
"body": "@PeterCordes\nI think this is not where the next gain is coming from. I just did a stripped down test. I can mmap read and parse at 7GB/s (with the file cached). If I take a copy of the mmap and then parse it it's ~14GB/s. Might be overhead not twice speed. Anyway that shows me that the mmap is not the bottleneck (assuming disk cache). The bottleneck is parsing. The above \"test\" is single XOR parity check instead of parsing. If I change it to a 64bit checksum it slows down by half. These are the margins now! And we are supposed to parse ints from chars!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-10T23:20:03.643",
"Id": "460833",
"Score": "0",
"body": "@OliverSchonrock: well whatever your parsing is, you want the CPU running that thread to spend all its time actually parsing, *not* waiting for I/O or even for soft page faults (data in page-cache but not wired into the HW page tables). mmap of a file can't use transparent hugepages (on Linux), so reading into buffers might be an advantage there, allowing the parsing thread to have fewer TLB misses. But your XOR/checksum test is way too optimistic about how fast you can parse decimal strings so HW data and TLB prefetch should be able to do a good job of keeping up and avoiding stalls."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-10T23:32:54.370",
"Id": "460836",
"Score": "0",
"body": "Yeah: \"XOR/checksum test is way too optimistic about how fast you can parse decimal strings\" ... that!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-11T00:20:54.420",
"Id": "460844",
"Score": "0",
"body": "I updated my answer and I really believe mmapping is only mandatory once you've significantly narrowed down your problem set. fstream can solve the yahtzee puzzle with a 900MB file in 1 second on my computer. It seems perfectly usable if you don't know what platform or architecture you will be running your code on."
}
],
"meta_data": {
"CommentCount": "11",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-10T16:21:16.813",
"Id": "235426",
"ParentId": "235314",
"Score": "4"
}
},
{
"body": "<p>I am going to try to summarise and incorporate some findings from the very good and lively discussion in the comments above. I have put together a \"best case\". \"Best\" without going \"totally silly\", ie no custom SIMD ASM or anything. </p>\n\n<ul>\n<li>If the file is OS-cached in RAM the mmap can go very very fast. I have measured up to 7GB/s (140ms for 1GB file). Just with a pointer spinning over the whole file and taking an 8-bit XOR parity checksum. </li>\n<li>If I take a copy of the 1GB file into a string first and then spin over over it, I get about 14GB/s (70ms for 1GB file). That's about my RAM bandwidth since this is an old machine and only has DDR3-1600 memory.</li>\n<li>But is doing no work at all really. Getting to anywhere near that\nspeed in parsing ints is going to be very very hard. Only with SIMD\nand then totally custom. </li>\n<li>The code below is a tight loop which an exact file format, not negative ints, no illegal chars etc. It cuts out charchonv, my minimal isdigit/isnumeric etc. It's pretty much the tightest loop I can invisage without spending too much time on it. And totally not error tolerant obviously. </li>\n<li>It achieves 1GB/s. Which is 1/7th of what the mmap can give me with\nan OS cached file and a little over 2x disk speed (should the disk\nget involved).</li>\n<li>Obviously, at this point, the hashmap is gone so we are not even meeting the spec anymore. Putting it back and finding the group for biggest total as per spec, slows us down to 1.7s or ~530MB/s. (Note this is a very low cardinality file with < 1000 unique ints). </li>\n</ul>\n\n<p>We <strong>might</strong> be able to use multiple threads/cores to parse and process the ints, but the synchronisation on the hash_map and also the contention on the memory bus will likely affect us quite badly. </p>\n\n<p>So, task can be \"just about reasonably\" done at 530MB/s or 1.7s for the 1GB file or about 2ms (plus probably some overhead there) for the small 1MB file which they gave in the reddit post. </p>\n\n<p>Thanks everyone. I learnt a few more tricks. </p>\n\n<pre><code>#include \"flat_hash_map/bytell_hash_map.hpp\"\n#include \"os/fs.hpp\"\n#include <cmath>\n#include <cstdint>\n#include <iostream>\n\ntemplate <typename T>\nT yahtzee_upper(const std::string& filename) {\n auto mfile = os::fs::MemoryMappedFile{filename};\n auto buffer = mfile.get_buffer();\n const char* begin = buffer.begin();\n const char* curr = begin;\n const char* const end = buffer.end();\n\n auto dist = ska::bytell_hash_map<T, T>{};\n auto val = T{0};\n auto max_total = T{0};\n while (curr != end) {\n if (*curr == '\\n') {\n auto total = dist[val] += val;\n if (total > max_total) max_total = total;\n val = 0;\n } else {\n val = val * 10 + (*curr - '0');\n }\n ++curr;\n }\n return max_total;\n}\n\nint main(int argc, char* argv[]) {\n if (argc < 2) return 1;\n std::cout << yahtzee_upper<std::uint64_t>(argv[1]) << '\\n'; // NOLINT\n return 0;\n}\n\n</code></pre>\n\n<p><strong>EDIT</strong>: I worked on a threaded parser. Simple implementation below. I am far from a concurrency expert, so bear with me. No locks or atomics. Doesn't need it: <a href=\"https://en.wikipedia.org/wiki/Embarrassingly_parallel\" rel=\"nofollow noreferrer\">Embarrassingly parallel</a>? Memory locality / bus or L1/L2/L3 cache size for hashmap are the limits to scalability -- not sure.</p>\n\n<p>Output and simple performance stats below (baseline from above is 1.7s single threaded for the same work, and 140ms of \"overhead\" to spin through the mmap'd file with no work):</p>\n\n<p>4 threads:</p>\n\n<pre><code>spawn=0.218369ms\nwork=680.104ms\nfinalise=0.17976ms\n8605974989487699234\n</code></pre>\n\n<p>6 threads</p>\n\n<pre><code>spawn=0.451396ms\nwork=437.958ms\nfinalise=0.151554ms\n8605974989487699234\n\n</code></pre>\n\n<p>8 threads:</p>\n\n<pre><code>spawn=0.441865ms\nwork=390.369ms\nfinalise=0.202808ms\n8605974989487699234\n</code></pre>\n\n<p>Pretty happy with sub 400ms? Any feedback on the concurrent code warmly welcome. </p>\n\n<pre><code>#include \"flat_hash_map/bytell_hash_map.hpp\"\n#include \"os/bch.hpp\"\n#include \"os/fs.hpp\"\n#include <cstdint>\n#include <iostream>\n#include <string>\n#include <thread>\n#include <vector>\n\ntemplate <typename T>\nT yahtzee_upper(const std::string& filename) {\n auto mfile = os::fs::MemoryMappedFile{filename};\n auto max_total = std::int64_t{0};\n\n const unsigned n_threads = std::thread::hardware_concurrency();\n auto threads = std::vector<std::thread>{};\n auto maps = std::vector<ska::bytell_hash_map<T, T>>{n_threads, ska::bytell_hash_map<T, T>{}};\n std::cout << n_threads << \" threads\"\n << \"\\n\";\n {\n auto tim = os::bch::Timer(\"spawn\");\n auto chunk = std::ptrdiff_t{(mfile.end() - mfile.begin()) / n_threads};\n const char* end = mfile.begin();\n for (unsigned i = 0; end != mfile.end() && i < n_threads; ++i) {\n const char* begin = end;\n end = std::min(begin + chunk, mfile.end());\n\n while (end != mfile.end() && *end != '\\n') ++end; // ensure we have a whole line\n if (end != mfile.end()) ++end; // one past the end\n\n threads.push_back(std::thread(\n [](const char* begin, const char* const end, ska::bytell_hash_map<T, T>& map) {\n\n const char* curr = begin;\n auto val = std::int64_t{0};\n while (curr != end) {\n if (*curr == '\\n') {\n map[val] += val;\n val = 0;\n } else {\n val = val * 10 + (*curr - '0');\n }\n ++curr;\n }\n },\n begin, end, std::ref(maps[i])));\n }\n }\n {\n auto tim = os::bch::Timer(\"work\");\n for (auto&& t: threads) t.join();\n }\n {\n auto tim = os::bch::Timer(\"finalise\");\n auto final_map = ska::bytell_hash_map<T, T>{};\n\n for (auto&& m: maps) {\n for (auto p: m) {\n std::int64_t total = final_map[p.first] += p.second;\n if (total > max_total) max_total = total;\n }\n }\n }\n return max_total;\n}\n\nint main(int argc, char* argv[]) {\n if (argc < 2) return 1;\n std::cout << yahtzee_upper<std::uint64_t>(argv[1]) << '\\n'; // NOLINT\n return 0;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-12T06:40:53.513",
"Id": "460968",
"Score": "0",
"body": "Comments are not for extended discussion; this conversation has been [moved to chat](https://chat.stackexchange.com/rooms/103205/discussion-on-answer-by-oliver-schonrock-high-performance-txt-file-parsing)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-12T11:34:40.000",
"Id": "460982",
"Score": "0",
"body": "@Jamal Most of the value of this question and its answers is in the comments. If you can't see that, then either you need to modify your \"policy\" or we need to use a different platform to share and create value..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-13T05:40:55.130",
"Id": "461077",
"Score": "1",
"body": "That's a Stack Exchange wide policy, not mine specifically. Comments aren't meant for this exact purpose, hence the applicable tools for moving comments to chat. Implementation of this can be found [here](https://meta.stackexchange.com/questions/93444/provide-a-tool-for-moderators-to-migrate-comments-to-chat)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-13T07:09:19.150",
"Id": "461083",
"Score": "0",
"body": "@Jamal I understand that. It is about the interpretation (!) of the policy. IMO 80% of the value of this page is in the comments. Very few people wrote answers. Some of the best \"partial answers\" are in comments. The comments discuss the trade-offs, because there is no \"one answer\". Non trivial questions tend to work like this. By moving the comments to chat you have significantly reduced the value of the page for everyone involved, the whole community and stack exchange."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-11T00:18:45.453",
"Id": "235445",
"ParentId": "235314",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "235379",
"CommentCount": "34",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-08T18:24:57.233",
"Id": "235314",
"Score": "27",
"Tags": [
"c++",
"performance",
"parsing"
],
"Title": "High performance txt file parsing"
}
|
235314
|
<p>I feel like the main point of inefficiency is how I create "notches" and must loop through all of the created notches every time the value for the slider is changed. </p>
<pre><code>function sliderLoop() {
for (var i = slideNotchArray.length - 1; i >= 0; i--) {
if ($(".slider").val() >= slideNotchArray[i].value) {
console.log(slideNotchArray[i].slide);
teamSlider.goTo(slideNotchArray[i].slide);
break;
}
}
}
</code></pre>
<p>It's an exponential nightmare as each call can loop through every notch object, and there can be multiple calls a second. This is the only solution I could have thought of though, and I am more than welcome to someone else's suggestions. I attempted to mitigate the severity by including a break once the first notch has been found, as to not loop through the rest, but I feel as though it is still quite heavy.</p>
<p><a href="https://codesandbox.io/s/currying-bush-h3xyz" rel="nofollow noreferrer">https://codesandbox.io/s/currying-bush-h3xyz</a></p>
<p>My major concerns are in relation to </p>
<pre><code> function sliderLoop() {
for (var i = slideNotchArray.length - 1; i >= 0; i--) {
if ($(".slider").val() >= slideNotchArray[i].value) {
console.log(slideNotchArray[i].slide);
teamSlider.goTo(slideNotchArray[i].slide);
break;
}
}
}
// Fires slider loop every time the value changes, I had to use mousemove as .change() would only fire once the mouse click was relseased.
$(".slider").on("change mousemove", function() {
sliderLoop();
});
</code></pre>
<p>The "change mousemove" event listener, calls sliderLoop multiple times a second. sliderLoop() contains a for loop, which could potentially iterate through many (10+) array index's. Calling a for loop which iterates through so many index's multiple times a second makes me believe this is an inefficient method of going about a slider navigation, however, I am at a loss as to how to improve the code while maintaining the functionality. Would you believe this to be an issue worth worrying about? If so, how could I go about improving this?</p>
|
[] |
[
{
"body": "<p>A technique that would likely improve this situation is a <a href=\"https://davidwalsh.name/javascript-debounce-function\" rel=\"nofollow noreferrer\"><em>debounced</em> function</a>. That way the function to be run will only run at certain intervals instead of each time the events occur.</p>\n\n<p>From <a href=\"https://davidwalsh.name/\" rel=\"nofollow noreferrer\">the Blog of JavaScript consultant David Walsh</a>:</p>\n\n<blockquote>\n <p>For those of you who don't know what a debounce function does, it limits the rate at which a function can fire. A quick example: you have a resize listener on the window which does some element dimension calculations and (possibly) repositions a few elements. That isn't a heavy task in itself but being repeatedly fired after numerous resizes will really slow your site down. Why not limit the rate at which the function can fire?</p>\n \n <p>Here's the basic JavaScript debounce function (<a href=\"https://davidwalsh.name/function-debounce\" rel=\"nofollow noreferrer\">as taken from Underscore.js</a>):</p>\n\n<pre><code>// Returns a function, that, as long as it continues to be invoked, will not\n// be triggered. The function will be called after it stops being called for\n// N milliseconds. If `immediate` is passed, trigger the function on the\n// leading edge, instead of the trailing.\nfunction debounce(func, wait, immediate) {\n var timeout;\n return function() {\n var context = this, args = arguments;\n var later = function() {\n timeout = null;\n if (!immediate) func.apply(context, args);\n };\n var callNow = immediate && !timeout;\n clearTimeout(timeout);\n timeout = setTimeout(later, wait);\n if (callNow) func.apply(context, args);\n };\n};\n</code></pre>\n \n <p><sup><a href=\"https://davidwalsh.name/javascript-debounce-function\" rel=\"nofollow noreferrer\">1</a></sup></p>\n</blockquote>\n\n<p>That can be used to create a <em>debounced</em> function that only gets called at an interval - e.g. 250 milliseconds (feel free to adjust to your needs):</p>\n\n<pre><code>var debouncedFunc = debounce(sliderLoop, 250);\n</code></pre>\n\n<p>And use that function in the callback of the event handler:</p>\n\n<pre><code>// Fires slider loop every time the value changes, I had to use mousemove as .change() would only fire once the mouse click was relseased.\n$(\".slider\").on(\"change mousemove\", function() {\n debouncedFunc();\n});\n</code></pre>\n\n<p>That could also be simplified to the following, since the extra lambda function/closure is pointless:</p>\n\n<pre><code>// Fires slider loop every time the value changes, I had to use mousemove as .change() would only fire once the mouse click was relseased.\n$(\".slider\").on(\"change mousemove\", debouncedFunc);\n</code></pre>\n\n<p><sup>1</sup><sub><a href=\"https://davidwalsh.name/javascript-debounce-function\" rel=\"nofollow noreferrer\">https://davidwalsh.name/javascript-debounce-function</a></sub></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-22T17:14:39.730",
"Id": "236030",
"ParentId": "235316",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-08T19:27:28.877",
"Id": "235316",
"Score": "3",
"Tags": [
"javascript",
"jquery",
"event-handling",
"user-interface"
],
"Title": "Javascript Slider that controls TinySlider - feels inefficient"
}
|
235316
|
<p>My Solution for Question 13 on <a href="https://www.w3resource.com/csharp-exercises/string/index.php" rel="nofollow noreferrer">https://www.w3resource.com/csharp-exercises/string/index.php</a></p>
<pre><code> Console.Write("Please enter your word : ");
string word = Console.ReadLine();
Console.Write("Starting position : ");
int start = Convert.ToInt32(Console.ReadLine());
Console.Write("Number of letters : ");
int numberOfLetters = Convert.ToInt32(Console.ReadLine());
int x = word.Length - numberOfLetters;
int end = word.Length - x;
for (int counter = start; counter <= end; counter++)
{
Console.Write(word[counter]);
}
Console.ReadLine();
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-08T21:14:58.617",
"Id": "460489",
"Score": "4",
"body": "Please summarise the problem statement (in your own words, of course). The link may be helpful while it lasts, but questions are expected to be complete without needing external resources. Thanks!"
}
] |
[
{
"body": "<p>You are not really extracting a substring, you are only printing a substring.</p>\n\n<p>A string consists of single characters of type <code>char</code>. Create an array of chars and then convert it to string</p>\n\n<pre><code>var characters = new char[numberOfLetters];\nfor (int i = 0; i < numberOfLetters; i++) {\n characters[i] = word[i + start];\n}\nstring output = new String(characters);\n</code></pre>\n\n<hr>\n\n<p>You are doing a strange calculation</p>\n\n<pre><code>int x = word.Length - numberOfLetters;\nint end = word.Length - x;\n</code></pre>\n\n<p>If you insert the first expression for <code>x</code> into the second, you get:</p>\n\n<pre><code>int end = word.Length - (word.Length - numberOfLetters);\n</code></pre>\n\n<p>which is equivalent to</p>\n\n<pre><code>int end = word.Length - word.Length + numberOfLetters;\n</code></pre>\n\n<p>or</p>\n\n<pre><code>int end = numberOfLetters;\n</code></pre>\n\n<p>which is not correct. Simply add <code>start</code> and <code>numberOfLetters</code> to get the exclusive upper bound. If printing the substring is a solution, then you can write:</p>\n\n<pre><code>int max = start + numberOfLetters;\nfor (int i = start; i < max; i++) {\n Console.Write(word[i]);\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-08T21:03:56.673",
"Id": "235320",
"ParentId": "235319",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-08T20:45:58.583",
"Id": "235319",
"Score": "-1",
"Tags": [
"c#"
],
"Title": "Extract a substring from a string without using the library function.[C# Console Application]"
}
|
235319
|
<p>I am trying to optimize this code. The only optimization I can think of is to ?¿? a <code>return</code> or <code>break</code> statement after <code>applyOfferChanges(…)</code> inside the second <code>if</code> condition which does not work either because there could be multiple matches. I cannot either use a map for <code>favoriteMerchantsList</code> because <code>getFavoriteMerchantsList()</code> return type is a list (of favorited merchants). Any ideas?</p>
<pre><code>void applyFavoriteChangesToMerchantStore(){
List<Merchant> favoriteMerchantsList = FavoriteMerchantStore.getInstance().getFavoriteMerchantsList();
if(favoriteMerchantsList != null && !favoriteMerchantsList.isEmpty()) {
List<Merchant> storeMerchantList = MerchantStore.getInstance().getMerchantList();
for (Merchant storeMerchant : storeMerchantList) {
for (Merchant favoriteMerchant: favoriteMerchantsList){
if(TextUtils.equals(storeMerchant.getId(), favoriteMerchant.getId())){
//merchant match found
//set merchant favorite status
storeMerchant.setFavoriteMerchant(favoriteMerchant.getFavoriteMerchant());
//set offer favorite status
applyOfferChanges(favoriteMerchant.getOffferList(),
storeMerchant.getOffferList());
}
}
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-08T23:09:54.213",
"Id": "460501",
"Score": "1",
"body": "Welcome to [codereview.se]! Please provide additional code which forms a complete program so that reviewers can run and test your code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-09T03:32:35.393",
"Id": "460512",
"Score": "0",
"body": "Please edit the question title to say _what your code achieves_ instead of _what you want to be done to your code_."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-09T03:34:14.497",
"Id": "460513",
"Score": "0",
"body": "Please add some details about how many favorite and store merchants there are usually. And what ahould happen if there are multiple matches."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-09T11:17:06.290",
"Id": "460566",
"Score": "0",
"body": "Interesting information would be also: What is a \"Merchant\" and what is the relationship between a \"store merchant\" and a \"favorite merchant\"? Why do they use the same class, but need to matched like that?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-09T15:55:59.070",
"Id": "460606",
"Score": "0",
"body": "Furthermore, please define \"optimize\". In terms of runtime? (Is there a concrete problem?) In terms of readability? In terms of less lines of code?"
}
] |
[
{
"body": "<p>You are implementing an inner join as a nested loop join. There are several other ways to implement joins, such as hash-based or sort-merge sort. Which one is better depends on the length of the lists.</p>\n\n<p>I will sketch a hash join as that usually works most of the time.</p>\n\n<pre><code>void applyFavoriteChangesToMerchantStore(){\n\n List<Merchant> favoriteMerchantsList = FavoriteMerchantStore.getInstance().getFavoriteMerchantsList();\n if(favoriteMerchantsList != null && !favoriteMerchantsList.isEmpty()) {\n // build the hash table\n Map<String, Merchant> favoriteMerchantById = favoriteMerchantsList.stream().collect(Collectors.toMap(Merchant::getId, Function.identity()));\n List<Merchant> storeMerchantList = MerchantStore.getInstance().getMerchantList();\n for (Merchant storeMerchant : storeMerchantList) {\n // probe the hash table\n Merchant favoriteMerchant = favoriteMerchantById.get(storeMerchant.getId())\n if(favoriteMerchant != null){\n //merchant match found\n //set merchant favorite status\n\n storeMerchant.setFavoriteMerchant(favoriteMerchant.getFavoriteMerchant());\n //set offer favorite status\n applyOfferChanges(favoriteMerchant.getOffferList(),\n storeMerchant.getOffferList());\n }\n }\n }\n}\n</code></pre>\n\n<p>I assumed that <code>TextUtils.equals</code> is equal to <code>String.equals</code>. If it's more lenient (e.g., case-insensitive), you need to normalize the lookup key (e.g., <code>String.toLowerCase()</code>).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-09T14:47:06.097",
"Id": "235365",
"ParentId": "235324",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-08T22:54:57.267",
"Id": "235324",
"Score": "0",
"Tags": [
"java",
"performance"
],
"Title": "optimize nested for loops within nested if statements"
}
|
235324
|
<p>I have build a C# Windows Forms app that used Entity Framework(DB first model). For the data I am using a .mdf database file. </p>
<p><strong>The data view of dbo.students:</strong>
<a href="https://i.stack.imgur.com/ST0oK.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ST0oK.png" alt="enter image description here"></a></p>
<p><strong>GUI:</strong>
<a href="https://i.stack.imgur.com/Q18Y9.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Q18Y9.png" alt="GUI"></a></p>
<p><strong>The Form1 class:</strong></p>
<pre><code>public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
StudentsEntities db = new StudentsEntities();
private void Form1_Load(object sender, EventArgs e)
{
bsStudents.DataSource = db.students.ToList();
dgvStudents.DataSource = bsStudents;
lstResults.DisplayMember = "FullName";
DisplayStudent();
}
// Displaying student info(name & credits) in lables, & refreshes DataGridView
private void DisplayStudent()
{
if (bsStudents.Current != null)
{
lblName.Text = ((student)bsStudents.Current).FullName;
lblCurrent.Text = ((student)bsStudents.Current).CurrentCredits.ToString();
lblTotal.Text = ((student)bsStudents.Current).TotalCredits.ToString();
dgvStudents.Refresh();
}
}
private void bsStudents_CurrentChanged(object sender, EventArgs e)
{
DisplayStudent();
}
// add 1 credit to selected student's current credits
private void btnAdd1_Click(object sender, EventArgs e)
{
((student)bsStudents.Current).AddToCurrentCredits(1);
DisplayStudent();
lblForm1UserPrompt.Text = "1 credit has been added to the current credits of " + ((student)bsStudents.Current).FullName;
}
// add 3 credits to selected student's current credits
private void btnAdd3_Click(object sender, EventArgs e)
{
((student)bsStudents.Current).AddToCurrentCredits(3);
DisplayStudent();
lblForm1UserPrompt.Text = "3 credits has been added to the current credits of " + ((student)bsStudents.Current).FullName;
}
// place current credits into total credits of selected student
private void btnAddCurrentToTotal_Click(object sender, EventArgs e)
{
((student)bsStudents.Current).AddCurrentToTotal();
DisplayStudent();
lblForm1UserPrompt.Text = ((student)bsStudents.Current).FullName + "'s" + " current credits were added to their total credits.";
}
// change current credits of selected student to user input
private void btnUpdateCurrentCredits_Click(object sender, EventArgs e)
{
string currentCredits = txtUpdateCurrentCredits.Text;
int currentCreditsNumeric = 0;
// validate user input
if (int.TryParse(currentCredits, out currentCreditsNumeric))
{
((student)bsStudents.Current).UpdateCurrentCredits(currentCreditsNumeric);
DisplayStudent();
lblForm1UserPrompt.Text = ((student)bsStudents.Current).FullName + "'s" + " current crdits have been set to " + currentCredits;
txtUpdateCurrentCredits.Clear();
}
else
{
lblForm1UserPrompt.Text = "Please enter numeric data for current credits.";
txtUpdateCurrentCredits.Clear();
}
}
// change total credits of selected student to user input
private void btnUpdateTotalCredits_Click(object sender, EventArgs e)
{
string totalCredits = txtUpdateTotalCredits.Text;
int totalCreditsNumeric = 0;
// validate user input
if (int.TryParse(totalCredits, out totalCreditsNumeric))
{
((student)bsStudents.Current).UpdateTotalCredits(totalCreditsNumeric);
DisplayStudent();
lblForm1UserPrompt.Text = ((student)bsStudents.Current).FullName + "'s" + " total crdits have been set to " + totalCredits;
txtUpdateTotalCredits.Clear();
}
else
{
lblForm1UserPrompt.Text = "Please enter numeric data for total credits.";
txtUpdateCurrentCredits.Clear();
}
}
// add 1 credit to all student's current credits
private void btnAdd1All_Click(object sender, EventArgs e)
{
foreach (student s in bsStudents)
{
s.AddToCurrentCredits(1);
}
DisplayStudent();
lblForm1UserPrompt.Text = "1 credit has been added to the current credits of all students";
}
// add 3 credits to all student's current credits
private void btnAdd3All_Click(object sender, EventArgs e)
{
foreach (student s in bsStudents)
{
s.AddToCurrentCredits(3);
}
DisplayStudent();
lblForm1UserPrompt.Text = "3 credits have been added to the current credits of all students";
}
// place current credits into total credits of all students
private void btnAddCurrentToTotalAll_Click(object sender, EventArgs e)
{
foreach (student s in bsStudents)
{
s.AddCurrentToTotal();
}
DisplayStudent();
lblForm1UserPrompt.Text = "The current credits of all students have been added to their total credits.";
}
// set current credits to 0 for all students
private void btnSetCurrent0All_Click(object sender, EventArgs e)
{
foreach (student s in bsStudents)
{
s.CurrentCredits = 0;
}
DisplayStudent();
lblForm1UserPrompt.Text = "The current credits of all students have been set to 0.";
}
// set total credits to 0 for all students
private void btnSetTotal0All_Click(object sender, EventArgs e)
{
foreach (student s in bsStudents)
{
s.TotalCredits = 0;
}
DisplayStudent();
lblForm1UserPrompt.Text = "The total credits of all students have been set to 0.";
}
// navigate to first element
private void btnFirst_Click(object sender, EventArgs e)
{
bsStudents.MoveFirst();
DisplayStudent();
}
// navigate to preceding element
private void btnPrevious_Click(object sender, EventArgs e)
{
bsStudents.MovePrevious();
DisplayStudent();
}
// navigate to succeeding element
private void btnNext_Click(object sender, EventArgs e)
{
bsStudents.MoveNext();
DisplayStudent();
}
// navigate to last element
private void btnLast_Click(object sender, EventArgs e)
{
bsStudents.MoveLast();
DisplayStudent();
}
// TODO: Maybe improve search
private void txtSearchLastName_TextChanged(object sender, EventArgs e)
{
}
// searches BindingSource for names that start with user input
private void btnSearch_Click(object sender, EventArgs e)
{
List<student> students = new List<student>();
foreach (student s in bsStudents)
{
if (s.StudentLastName.ToLower().StartsWith(txtSearchLastName.Text.ToLower()))
{
students.Add(s);
}
}
if (students.Any())
{
bsStudents.Position = bsStudents.IndexOf(students.First());
lstResults.DataSource = students;
DisplayStudent();
}
else
{
MessageBox.Show("Not found");
}
}
// navigate to name selected in ListBox
private void lstResults_SelectedIndexChanged(object sender, EventArgs e)
{
List<student> students = new List<student>();
foreach (student s in bsStudents)
{
if (s.FullName == lstResults.Text)
{
students.Add(s);
}
}
if (students.Any())
{
bsStudents.Position = bsStudents.IndexOf(students.First());
}
else
{
MessageBox.Show("Not found");
}
}
// create new student & add student to BindingSource
private void btnAddStudent_Click(object sender, EventArgs e)
{
Form2 frmNew = new Form2();
frmNew.ShowDialog();
if (frmNew.stu != null)
{
bsStudents.Insert(0, frmNew.stu);
}
}
// remove student from binding source
private void btnRemove_Click(object sender, EventArgs e)
{
string fullName = ((student)bsStudents.Current).FullName;
bsStudents.RemoveCurrent();
lblForm1UserPrompt.Text = fullName + " has been removed.";
}
// save BindingSource to DB
private void btnSaveToDB_Click(object sender, EventArgs e)
{
db.SaveChanges();
}
// exit app
private void btnExitForm1_Click(object sender, EventArgs e)
{
this.Close();
}
}
</code></pre>
<p><strong>The Form2 class:</strong></p>
<pre><code>public partial class Form2 : Form
{
public student stu;
public Form2()
{
InitializeComponent();
lblForm2UserPrompt.Text = "Please enter a first name, last name, current and total credits.";
}
private void btnSave_Click(object sender, EventArgs e)
{
string firstName = txtFirst.Text;
string lastName = txtLast.Text;
string currentCredits = txtCurrentCredits.Text;
int currentCreditsNumeric = 0;
string totalCredits = txtTotalCredits.Text;
int totalCreditsNumeric = 0;
//validate user input
if (!string.IsNullOrEmpty(firstName) && !string.IsNullOrEmpty(lastName) && int.TryParse(currentCredits, out currentCreditsNumeric) && int.TryParse(totalCredits, out totalCreditsNumeric))
{
// instantiate & initialize student
stu = new student();
stu.StudentFirstName = char.ToUpper(firstName[0]) + firstName.Substring(1);
stu.StudentLastName = char.ToUpper(lastName[0]) + lastName.Substring(1);
stu.CurrentCredits = currentCreditsNumeric;
stu.TotalCredits = totalCreditsNumeric;
lblForm2UserPrompt.Text = "Student has been saved.";
}
else
{
//if user did not entered first or last name
if (string.IsNullOrEmpty(firstName) || string.IsNullOrEmpty(lastName))
{
lblForm2UserPrompt.Text = "Please enter a first and last name.";
}
//if user did not entered a number for current credit
else if (!int.TryParse(currentCredits, out currentCreditsNumeric))
{
lblForm2UserPrompt.Text = "Please enter numeric data for current credits.";
txtCurrentCredits.Clear();
}
//if user did not entered a number for total credit
else
{
lblForm2UserPrompt.Text = "Please enter numeric data for total credits.";
txtTotalCredits.Clear();
}
}
}
private void btnExit_Click(object sender, EventArgs e)
{
this.Close();
}
}
</code></pre>
<p><strong>The student class:</strong></p>
<pre><code> public partial class student
{
public int Id { get; set; }
public string StudentLastName { get; set; }
public string StudentFirstName { get; set; }
public int CurrentCredits { get; set; }
public int TotalCredits { get; set; }
public string FullName
{
get
{
return $"{StudentFirstName} {StudentLastName}";
//return StudentFirstName + " " + StudentLastName;
}
}
public void AddToCurrentCredits(int newCurrentCredits)
{
CurrentCredits += newCurrentCredits;
}
public void AddCurrentToTotal()
{
TotalCredits += CurrentCredits;
CurrentCredits = 0;
}
public void UpdateCurrentCredits(int newCurrentCredits)
{
CurrentCredits = newCurrentCredits;
}
public void UpdateTotalCredits(int newTotalCredits)
{
TotalCredits = newTotalCredits;
}
}
</code></pre>
<p><strong>The StudentsEntities class:</strong></p>
<pre><code>public partial class StudentsEntities : DbContext
{
public StudentsEntities()
: base("name=StudentsEntities")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
throw new UnintentionalCodeFirstException();
}
public virtual DbSet<student> students { get; set; }
}
</code></pre>
<p>The app runs but not as expected... </p>
<p><strong>These are the bits I am having trouble with:</strong></p>
<ol>
<li>I seem to be able to create a new student, & to be able to add them to the BindingSource. I know this because the show up in the DataGridView. But, their id value is always 0. And, I need for the id value to be unique.</li>
<li>When I save the changes made in the BindingSource to the underlying db file the new students are not saved. If I edit the credits of a student, these edits will save. But, the newly created students will not.</li>
</ol>
<p><strong>The btnAddStudent_Click method:</strong></p>
<pre><code> private void btnAddStudent_Click(object sender, EventArgs e)
{
Form2 frmNew = new Form2();
frmNew.ShowDialog();
if (frmNew.stu != null)
{
bsStudents.Insert(0, frmNew.stu);
}
}
</code></pre>
<p>The student object is then created & provided with values in Form2.</p>
<p><strong>After having added 2 new students & set all current credits to 0 in the BindingSource:</strong>
<a href="https://i.stack.imgur.com/Krow2.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Krow2.png" alt="I have set all current credits to 0 in the BindingSource"></a></p>
<p><strong>The data view of dbo.students after saving the changes made to the BindingSource:</strong>
<a href="https://i.stack.imgur.com/ZGssn.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ZGssn.png" alt="data view of dbo.students after saving"></a></p>
<p>As you can see the changes made to the students credits changed. But, the number of students did not.</p>
<p><strong>What I am looking for:</strong></p>
<ol>
<li>I want for the new student objects to save to the BindingSource with unique ids.</li>
<li>When I save the changes made to the BindingSource I would like to see new students(if created) in the data view of the dbo.</li>
</ol>
<p>What do you think? </p>
<p>Thanks in advance for the input. </p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-09T21:45:45.267",
"Id": "460673",
"Score": "0",
"body": "Welcome to Code Review! Please see [_What to do when someone answers_](https://codereview.stackexchange.com/help/someone-answers). I have rolled back Rev 4 → 3"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-10T14:26:10.563",
"Id": "460757",
"Score": "0",
"body": "We require that the code be working correctly, to the best of the author's knowledge, before proceeding with a review. Please [**follow the tour**](https://CodeReview.StackExchange.com/tour), and read [**\"What topics can I ask about here?\"**](https://CodeReview.StackExchange.com/help/on-topic), [**\"How do I ask a good question?\"**](https://CodeReview.StackExchange.com/help/how-to-ask) and [**\"What types of questions should I avoid asking?\"**](https://CodeReview.StackExchange.com/help/dont-ask)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-10T15:05:03.400",
"Id": "460768",
"Score": "2",
"body": "Sounds good, folks. Sorry for any misuse on my part. First time poster. Thank you for the information. Will checkout these links."
}
] |
[
{
"body": "<blockquote>\n<ol>\n<li><p>I seem to be able to create a new student, & to be able to add them to\nthe BindingSource. I know this because the show up in the\nDataGridView. But, their id value is always 0. And, I need for the id\nvalue to be unique.</p>\n</li>\n<li><p>When I save the changes made in the BindingSource\nto the underlying db file the new students are not saved. If I edit\nthe credits of a student, these edits will save. But, the newly\ncreated students will not.</p>\n</li>\n</ol>\n</blockquote>\n<p>Both concerns are related to the table schema. Your students columns don't allowed nulls, and in your current work, you're passing null <code>id</code>, which is not allowed. Those, the changes were not committed. To solve it, you need to pass a valid <code>Id</code> when creating a new student. you can do this :</p>\n<pre><code>public static int NewId()\n{\n using (var entity = new StudentsEntities())\n {\n return entity.students.Max(x => x.Id) + 1;\n }\n}\n</code></pre>\n<p>and then do this :</p>\n<pre><code>// instantiate & initialize student\nstu = new student\n{\n Id = student.NewId(),\n StudentFirstName = char.ToUpper(firstName[0]) + firstName.Substring(1),\n StudentLastName = char.ToUpper(lastName[0]) + lastName.Substring(1),\n CurrentCredits = currentCreditsNumeric,\n TotalCredits = totalCreditsNumeric\n};\n</code></pre>\n<p><strong>Update</strong></p>\n<blockquote>\n<p>These are the results:</p>\n<p>There were originally 5 students. IDs 1-5. I added 2 new students. The first one received an ID of 6. But, the second one did too.These students were did save to the dbo after a save was executed.</p>\n</blockquote>\n<p>in short, you've executed <code>NewId()</code> twice before any updates. So, there were 5 records, and you've added 2 new rows (on the datagrid not the database). Those two records have not been committed to the database yet, so executing the <code>NewId()</code> would get the max current id from the database (which is 6). No matter how many times you execute it, as long as you've not commit any new changes, it'll always return the same value. So, either commit one row each time, and get the next max id from the database, or get the max id, then do your own counting, and commit the changes once.</p>\n<p>For instance, your current work should store students in a collection, and whenever the user clicks <code>save changes to the database</code>, the application will insert the new records from that collection.</p>\n<pre><code>// this would be global \nprivate List<student> studentList = new List<student>();\n\npublic void AddStudent(int id, string firstName, string lastName, int currentCredits, int totalCredits)\n{\n var _student = new student \n {\n Id = id,\n StudentFirstName = char.ToUpper(firstName[0]) + firstName.Substring(1),\n StudentLastName = char.ToUpper(lastName[0]) + lastName.Substring(1),\n CurrentCredits = currentCredits,\n TotalCredits = totalCredits\n };\n \n studentList.Add(_student);\n}\n\n\npublic void CommitNewStudents()\n{\n // get the new students that have not been committed yet.\n var numberOfnewStudents = studentList.Count;\n \n if(numberOfnewStudents > 0)\n {\n //get the current max Id from the database.\n var maxDbId = student.NewId();\n \n for(int x =0; x < numberOfnewStudents; x++)\n { \n // since the id is max + 1, then we can get the count of the new students, and add 1 to the maxId. \n studentList[x].Id = maxDbId + x;\n }\n \n //now, add them to the entity and save the the changes. \n db.students.AddRange(studentList);\n \n db.SaveChanges(); \n }\n}\n</code></pre>\n<p>this should cover adding new students, however, you'll need to cover the update and delete logic in your app.</p>\n<p><strong>Another Update</strong></p>\n<p>I've checked some of your code (from the uploded source), and I noticed that you are treating all actions as <code>INSERT</code>. For instance, when you add new student, this is an insert action, but when you change a value of current student, this is an update action. You didn't specify anything that separates these actions.</p>\n<p>Since you are using Entity Framework, you could use <code>AddOrUpdate()</code> extension which will update current records, and add new ones.</p>\n<p>you could do this in your code :</p>\n<pre><code>// save BindingSource to DB\nprivate void btnSaveToDB_Click(object sender, EventArgs e)\n{\n if (bsStudents.Count != 0)\n {\n // Do UPSERT (UPDATE existing records & add new records)\n\n using (var context = new StudentsEntities())\n {\n var list = (IList<student>) bsStudents.DataSource;\n\n var studentsList = new student[list.Count];\n\n for (int x = 0; x < list.Count; x++)\n {\n var id = list[x].Id;\n\n\n var stud = new student\n {\n Id = id < 1 ? x + 1 : id, //assuming that the datasource has loaded all records from DB.\n StudentLastName = list[x].StudentLastName,\n StudentFirstName = list[x].StudentFirstName,\n CurrentCredits = list[x].CurrentCredits,\n TotalCredits = list[x].TotalCredits\n };\n\n studentsList[x] = stud;\n }\n\n context.students.AddOrUpdate(studentsList);\n\n context.SaveChanges();\n\n //Rebind data\n dgvStudents.DataSource = null;\n\n bsStudents.DataSource = context.students.ToList();\n dgvStudents.DataSource = bsStudents;\n }\n\n\n\n }\n\n}\n</code></pre>\n<p>Another thought that I saw, you are using BindingSource, it's not required in your case, you can load the <code>db.students.ToList()</code> directly to the datagridview datasource, and continue your work.</p>\n<p>Another note, you modified the Entity Framework auto-generated student model class. It's okay, but keep in mind, this class will be regenarted whenever you update the Entity Framework Entities (say, you added new entities using the designer). So, I would suggest you move all modified work from the this class, to another file (you can create another partial class and move your work to it). Just try to avoid modifying on EF auto-generated classes, if you don't want to lose your work ;) ..</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-09T20:06:17.107",
"Id": "460658",
"Score": "0",
"body": "Thank you very much for this feedback. I have implemented it. Please see the update at the bottom of my original for continued information."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-09T21:05:28.873",
"Id": "460663",
"Score": "0",
"body": "@ReedWilliams8404 check update"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-09T22:10:13.283",
"Id": "460677",
"Score": "0",
"body": "Thanks for the update. Correct me if I am wrong, but as written now, isn't the new student being added to the BindingSource(bsStudnets)? Could we use this BS to get a count of the current elements in it? And, then use this number to inform the next student ID value?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-09T23:10:24.017",
"Id": "460686",
"Score": "0",
"body": "I have also noticed that when I create just one new student, now students with IDs 1-6. When I save the state of the app this student is still not saving to the dbo. So, I feel like we have 2 separate questions on our hands 1) is the question adding students to the BS with correct IDs 2) Saving the new students in the BS to the dbo on save."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-10T01:06:06.690",
"Id": "460698",
"Score": "0",
"body": "I feel like this is on the right track: https://docs.microsoft.com/en-us/dotnet/framework/winforms/controls/how-to-customize-item-addition-with-the-windows-forms-bindingsource?view=netframework-4.8"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-10T01:53:33.193",
"Id": "460702",
"Score": "1",
"body": "@ReedWilliams8404 you are correct on using BindingSource, my code is just an example to help demonstrate the answer, and intent to add more options to your thoughts !"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-10T14:23:33.453",
"Id": "460755",
"Score": "0",
"body": "@ReedWilliams8404 check the new update"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-10T20:40:59.383",
"Id": "460809",
"Score": "0",
"body": "Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/103159/discussion-between-reedwilliams8404-and-isr5)."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-09T08:04:00.537",
"Id": "235341",
"ParentId": "235326",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "235341",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-08T23:42:10.863",
"Id": "235326",
"Score": "4",
"Tags": [
"c#",
"entity-framework",
"winforms",
"databinding"
],
"Title": "C# Windows Forms App: Adding An Element To The BindingSource And Save These Changes To The DB"
}
|
235326
|
<p>Looking for feedback on a question I solved in C++. It is a <a href="https://leetcode.com/problems/maximum-subarray/" rel="nofollow noreferrer">leetcode problem</a> and I used divide and conquer to solve the problem. </p>
<blockquote>
<h3>53. Maximum Subarray</h3>
<p>Given an integer array <code>nums</code>, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.</p>
<p><strong>Example:</strong></p>
<pre><code>Input: [-2,1,-3,4,-1,2,1,-5,4],
Output: 6
Explanation: [4,-1,2,1] has the largest sum = 6.
</code></pre>
<p><strong>Follow up:</strong></p>
<p>If you have figured out the <span class="math-container">\$\mathcal{O}(n)\$</span> solution, try coding another solution using the divide and conquer approach, which is more subtle.</p>
</blockquote>
<p>I am looking for feedback in terms of logic and also the implementation. If I search for a C++ solution online, I only see problem solved using arrays and I have used vector to solve to the problem while utilizing iterators. </p>
<p>Any feedback would be great.</p>
<p>Thanks!</p>
<pre class="lang-cpp prettyprint-override"><code>
int FindMaximumSubarray(const vector<int> &vec) {
if (vec.size() == 1) {
return vec.at(0);
}
int midIndex = vec.size() / 2;
vector<int> leftArray(vec.begin(), vec.begin() + midIndex);
vector<int> rightArray(vec.begin() + midIndex, vec.end());
int maximumSumLeftSubarray = FindMaximumSubarray(leftArray);
int maximumSumRightSubarray = FindMaximumSubarray(rightArray);
int maximumSumCrossingSubarray = FindMaximumSubarrayCrossing(vec);
return FindMaximumNumber(maximumSumLeftSubarray,
maximumSumRightSubarray,
maximumSumCrossingSubarray);
}
int FindMaximumSubarrayCrossing(const vector<int> &vec) {
int midIndex = vec.size() / 2, leftSum = INT_MIN, rightSum = INT_MIN, sum = 0;
for (auto itr = vec.rbegin() + midIndex; itr != vec.rend(); ++itr) {
sum += *itr;
if (sum > leftSum) leftSum = sum;
}
sum = 0;
for (auto itr = vec.begin() + midIndex + 1; itr != vec.end(); ++itr) {
sum += *itr;
if (sum > rightSum) rightSum = sum;
}
if (leftSum == INT_MIN || rightSum == INT_MIN) {
return (leftSum == INT_MIN) ? rightSum : leftSum;
}
return (leftSum + rightSum);
}
int FindMaximumNumber(const int &a, const int &b, const int &c) {
if (a >= b && a >= c) return a;
if (b >= a && b >= c) return b;
if (c >= a && c >= b) return c;
}
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-09T00:46:28.887",
"Id": "460506",
"Score": "1",
"body": "It would be nice to see a more complete description of the problem as well as a link to the actual problem description."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-09T09:34:23.133",
"Id": "460557",
"Score": "0",
"body": "For future reviews, remember that it helps reviewers to have a self-contained review, rather than having to infer the missing `#include <vector>` and `using std::vector;` that you've not shown. An example `main()` is always helpful, too."
}
] |
[
{
"body": "<p>You're creating a bunch of unnecessary vector copies. Try passing iterators into <code>FindMaximumSubarray</code> instead of a vector.</p>\n\n<p>You can find the max of an initializer list of numbers using <code>std::max</code>.</p>\n\n<p>You don't need to pass ints as const refs.</p>\n\n<p>Are you sure this is more performant than a linear solution? What is your reasoning? Can we see your linear version?</p>\n\n<p>Your code looks like it might have potential overflow errors. Maybe that's not important.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-09T15:16:18.670",
"Id": "460602",
"Score": "0",
"body": "I understand that I am creating several unnecessary vector copies but if I pass iterators how can I calculate the `midIndex`? Or is there a workaround for that?\n\nI have added `std::max` with an initializer. Why should I not pass ints as const refs? I am practising divide and conquer methodology hence I did not implement a linear solution but the above solution."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-09T19:13:10.600",
"Id": "460646",
"Score": "0",
"body": "You can use std::distance or just the - operator since they're vector iterators to get a integral distance between iterators. \n\nInts generally shouldn't be const ref parameters because there's no advantage to it. A reference type is possibly bigger than an int, and it may confuse the compiler."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-09T03:28:46.647",
"Id": "235333",
"ParentId": "235327",
"Score": "1"
}
},
{
"body": "<h1>Consider the edge cases</h1>\n<p>The first thing I tried to do was:</p>\n<pre><code>#include <iostream>\nint main()\n{\n std::cout << FindMaximumSubarray({});\n}\n</code></pre>\n<p>This resulted in a stack overflow, since we check for a unitary vector but not for an empty one.</p>\n<p>Consider using a larger type for the accumulator, as the sum is liable to overflow if the inputs are large. Ideally, you'd want to use a type that can represent <code>SIZE_MAX</code> times the range of <code>int</code>.</p>\n<h1>Make good use of <code><algorithm></code></h1>\n<p>Instead of <code>FindMaximumNumber()</code>, we can simply use <code>std::max()</code>:</p>\n<pre><code> return std::max({FindMaximumSubarray({vec.begin(), vec.begin() + midIndex}),\n FindMaximumSubarray({vec.begin() + midIndex, vec.end()}),\n FindMaximumSubarrayCrossing(vec)});\n</code></pre>\n<p>We can use <code>std::find_if()</code> to find the first and last positive values, immediately trimming off parts of the input which will never contribute.</p>\n<h1>Other observations</h1>\n<p>Internal functions ought to have internal (<code>static</code>) linkage.</p>\n<p>Use the correct type for <code>midIndex</code> - it should be a <code>std::size_t</code>. Simply using <code>auto</code> would avoid that mistake.</p>\n<p><code>FindMaximumSubarrayCrossing</code> contains two code blocks that are almost identical - it may be worth refactoring to reduce duplication.</p>\n<p>When we test <code>sum > leftSum</code>, that's exactly equivalent (in the absence of overflow) to <code>*itr > 0</code>. That observation may help in identifying a more efficient algorithm.</p>\n<p>Using <code>INT_MIN</code> as a marker is risky, given that that's a valid input value.</p>\n<p>We could just use <code>std::find_if()</code> to locate zero-crossings and <code>std::accumulate()</code> to total each positive and each negative run. Then see which runs combine usefully.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-09T14:57:33.023",
"Id": "460597",
"Score": "0",
"body": "Thanks for the advice. I have fixed moved from my custom function to `std::max()`.\n\nIt also makes sense to change `midIndex` from int to size_t.\n\nI did not understand your point about sum > leftSum.\n\nWhat would you recommend using if not `INT_MIN`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-09T15:13:27.067",
"Id": "460601",
"Score": "0",
"body": "The observation that we only update `leftSum` when we're looking at a positive value is just an observation (not a criticism). It may help in understanding what we're looking for. You might be able to use `LONG_MIN` as a marker if `long` is big enough for any sum, but I think it could be clearer to maintain a separate boolean flag. Or use a `std::optional` - that's the kind of thing it's for, after all."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-09T10:11:11.383",
"Id": "235349",
"ParentId": "235327",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "235333",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-09T00:27:35.733",
"Id": "235327",
"Score": "2",
"Tags": [
"c++"
],
"Title": "Finding maximum subarry sum"
}
|
235327
|
<p>I'm trying to connect the create of a comment to the <code>current_user</code>. I have a model <code>comment</code> which is a polymorphic association.</p>
<pre><code>class CreateComments < ActiveRecord::Migration[6.0]
def change
create_table :comments do |t|
t.string :content
t.references :commentable, polymorphic: true
t.timestamps
end
end
end
</code></pre>
<p>In the controller I'm trying to connect the <code>@comment.user = current_user</code>.
controllers/comments_controller.rb</p>
<pre><code> def create
@comment = @commentable.comments.new comment_params
@comment.user = current_user
@comment.save
redirect_to @commentable, notice: 'Comment Was Created'
end
</code></pre>
<p>But I get the following error:</p>
<blockquote>
<p>NoMethodError: undefined method `user=' for #
Did you mean? user_id=</p>
</blockquote>
<p>I would rather set up a relationship from which I can get to a user (The creator of comment) from the comment itself. For example <code>@comment.user</code> instead of just having the id.</p>
<p>I have the following models:</p>
<pre><code>class Question < ApplicationRecord
belongs_to :user
has_many :comments, as: :commentable
has_rich_text :content
end
class User < ApplicationRecord
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :validatable
has_many :posts
has_many :questions
has_one_attached :avatar
before_create :set_defaults
def set_defaults
self.avatar = 'assets/images/astronaut.svg' if self.new_record?
end
end
class Comment < ApplicationRecord
belongs_to :commentable, polymorphic: true
end
</code></pre>
<p>Since <code>comment</code> is a polymorphic association, I'm not sure if it should be connected to user via a <code>belongs_to</code> to <code>user</code>.</p>
<pre><code>[5] pry(#<Questions::CommentsController>)> @comment
=> #<Comment:0x00007fb3e6df72e8
id: nil,
content: "some test content",
commentable_type: "Question",
commentable_id: 1,
created_at: nil,
updated_at: nil,
user_id: nil>
[6] pry(#<Questions::CommentsController>)>
</code></pre>
<p>Does this mean, I should create a foreign_key in the <code>comments</code> migration to a user? How can I go about getting the creator of the comment from the comment itself? Something like <code>@comment.creator</code> or <code>@comment.user</code>?</p>
|
[] |
[
{
"body": "<p>Don't think your question belongs to this code review section. You would have gotten help much faster if had posted in stackoverflow instead. Anyway there are couple points you need to check.</p>\n\n<ol>\n<li><p>The <strong>CreateComments</strong> migration must have been updated (or at least there was another migration that changed the table) because the migration does not say anything about <code>user_id</code> column but the your model has that.</p></li>\n<li><p><strong><em>Since comment is a polymorphic association, I'm not sure if it should be connected to user via a belongs_to to user</em></strong>. You are confused between the polymorphic association relation and the user's relation of a comment. They are different, a comment belongs to a Question (or Post, Thread... that why you have polymorphic here) and also belongs to a user who created the comment. Even better, you can have another polymorphic association for commenter (I will skip it to avoid adding noise to your question)</p></li>\n<li><p><strong><em>Does this mean, I should create a foreign_key in the comments migration to a user?</em></strong> NO</p></li>\n<li><strong><em>How can I go about getting the creator of the comment from the comment itself? Something like @comment.creator or @comment.user?</em></strong> They are just methods rails generated for you after you setup the association, so yeah you can have whatever you want</li>\n</ol>\n\n<p>Here is what I would do to get <code>comment.commenter</code> and <code>comment.commenter=</code> to work:</p>\n\n<pre><code>class Comment < ApplicationRecord\n belongs_to :commentable, polymorphic: true\n belongs_to :commenter, class_name: 'User', foreign_key: 'user_id'\nend\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-10T10:31:55.070",
"Id": "235408",
"ParentId": "235331",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "235408",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-09T01:55:46.313",
"Id": "235331",
"Score": "1",
"Tags": [
"ruby",
"ruby-on-rails",
"active-record"
],
"Title": "Rails: create a relationship between comment and user"
}
|
235331
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.