body
stringlengths 25
86.7k
| comments
list | answers
list | meta_data
dict | question_id
stringlengths 1
6
|
|---|---|---|---|---|
<p>I'm writing a program that creates curling sequences -- in short this means that we start with a given sequences, consisting of 2's and 3's (i.e. a mix of 22 of them), and look for repetition at the end of the sequence. The curling number, i.e. <em>highest frequency of a period at the end of the sequence</em> is then appended to the sequence and we redo the calculation and append and so on...</p>
<p>Quick example: the curling number (curl) of the sequence <strong>seq = 223223</strong>, <strong>curl(seq) = 2</strong>, because <em>223</em> is repeated twice. Then, <strong>seq = 2232232</strong>, and <strong>curl(seq) = 2</strong>, because <em>232</em> is repeated twice.</p>
<p>Now, we continue this calculation until we find <strong>curl(seq) = 1</strong>. That's the idea of the program, but then I want to do this for a bazillion amount of sequences (just kidding, more like 2^50).</p>
<p>Thanks to a fellow Stackoverflow user, I switched over to Intel Intrinsics (AVX/AVX2 and SSE) instructions, where we represent a sequence of 2's and 3's with bits in a 256-bit register.</p>
<p>Here's the script -- I tried my best to comment enough, but if there are any questions, be sure to ask them.</p>
<pre><code>
// the curl of a sequence is defined as : the highest frequency of any period at the end of a sequence
// some examples:
// the curl of 11232323 is 3, because 23 is the most-repeated element at the end of the sequence
// the curl of 2222 is 4, because 2 is the most-repeated element at the end of the sequence
// the curl of 1234 is 1, because every period at the end of the sequence is repeated only once
#include <iostream>
#include <immintrin.h>
// Vlad - ShiftRight is my adaptation from http://notabs.org/lfsr/software/
//----------------------------------------------------------------------------
// bit shift right a 256-bit value using ymm registers
// __m256i *data - data to shift
// int count - number of bits to shift
static void bitShiftRight256ymm(__m256i* data, int count)
{
__m256i innerCarry = _mm256_slli_epi64(*data, 64 - count); // carry outs in bit 0 of each qword
__m256i rotate = _mm256_permute4x64_epi64(innerCarry, 0x39); // rotate ymm left 64 bits
innerCarry = _mm256_blend_epi32(_mm256_setzero_si256(), rotate, 0x3F); // clear lower qword
*data = _mm256_srli_epi64(*data, count); // shift all qwords right
*data = _mm256_or_si256(*data, innerCarry); // propagate carrys from low qwords
}
// bit shift left by one a 256-bit value using ymm registers
// __m256i *data - data to shift
static void bitShiftLeftByOne256ymm(__m256i* data)
{
__m256i innerCarry = _mm256_srli_epi64(*data, 63); // carry outs in bit 0 of each qword
__m256i rotate = _mm256_permute4x64_epi64(innerCarry, 0x93); // rotate ymm left 64 bits
innerCarry = _mm256_blend_epi32(_mm256_setzero_si256(), rotate, 0xFC); // clear lower qword
*data = _mm256_slli_epi64(*data, 1); // shift all qwords left
*data = _mm256_or_si256(*data, innerCarry); // propagate carrys from low qwords
}
// mask of 64 to select smaller parts of the sequence
static const uint64_t mask64[65] = { 0,
0x1, 0x3, 0x7, 0xF, 0x1F, 0x3F, 0x7F, 0xFF,
0x1FF, 0x3FF, 0x7FF, 0xFFF, 0x1FFF, 0x3FFF, 0x7FFF, 0xFFFF,
0x1FFFF, 0x3FFFF, 0x7FFFF, 0xFFFFF, 0x1FFFFF, 0x3FFFFF, 0x7FFFFF, 0xFFFFFF,
0x1FFFFFF, 0x3FFFFFF, 0x7FFFFFF, 0xFFFFFFF, 0x1FFFFFFF, 0x3FFFFFFF, 0x7FFFFFFF, 0xFFFFFFFF,
0x1FFFFFFFF, 0x3FFFFFFFF, 0x7FFFFFFFF, 0xFFFFFFFFF, 0x1FFFFFFFFF, 0x3FFFFFFFFF, 0x7FFFFFFFFF, 0xFFFFFFFFFF,
0x1FFFFFFFFFF, 0x3FFFFFFFFFF, 0x7FFFFFFFFFF, 0xFFFFFFFFFFF, 0x1FFFFFFFFFFF, 0x3FFFFFFFFFFF, 0x7FFFFFFFFFFF, 0xFFFFFFFFFFFF,
0x1FFFFFFFFFFFF, 0x3FFFFFFFFFFFF, 0x7FFFFFFFFFFFF, 0xFFFFFFFFFFFFF, 0x1FFFFFFFFFFFFF, 0x3FFFFFFFFFFFFF, 0x7FFFFFFFFFFFFF, 0xFFFFFFFFFFFFFF,
0x1FFFFFFFFFFFFFF, 0x3FFFFFFFFFFFFFF, 0x7FFFFFFFFFFFFFF, 0xFFFFFFFFFFFFFFF, 0x1FFFFFFFFFFFFFFF, 0x3FFFFFFFFFFFFFFF, 0x7FFFFFFFFFFFFFFF, 0xFFFFFFFFFFFFFFFF,
};
// mask of 128 to select larger parts of the sequence, built at start
static __m128i mask128[129] = {};
void build_mask()
{
for (int i = 0; i < 128; ++i)
mask128[i] = i < 64 ?
_mm_set_epi64x(0, mask64[i % 64]) :
_mm_set_epi64x(mask64[(i - 64) % 64], mask64[64]);
mask128[128] = _mm_set_epi64x(mask64[64], mask64[64]);
}
// mask a part of the sequence
// __m256i *m - data to mask
// int length - length to mask
__m128i masked128(const __m128i* m, int length) {
return _mm_and_si128(*m, mask128[length]);
}
// check if 2 parts of the sequence are equal
// __m256i *m - last part of the sequence to compare
// int length - length to compare
// __m256i *target - shifted part of the sequence to compare
bool masked128eq(const __m128i* m, int length, const __m128i* target) {
__m128i masked = _mm_and_si128(*m, mask128[length]);
__m128i neq = _mm_xor_si128(masked, *target);
return (_mm_test_all_zeros(neq, neq)); //v0 == v1
}
// find the curling number (curl) of a sequence
// uint8_t i - current length of the sequence
// uint8_t last_curl - previous curl in the sequence
// const __m256i& seq - current sequence
int krul(uint8_t i, uint8_t last_curl, const __m256i& seq) {
int curl = 1;
__m128i seq128 = _mm256_castsi256_si128(seq); // cast the second halve of 256-bit sequence to 128-bit for faster functions
unsigned char upper_limit = i / (curl + 1);
for (int j = 1; j <= upper_limit; ++j) { // since the curl can be 4, we need to start from a fourth of the cached length, up to halve the total length (else curl = 1)
int freq = 1; // default curl of any length is 1
__m128i target = masked128(&seq128, j); // last j bits of sequence
__m256i temp = seq; // copy sequence
int cond = 2 * j; // cond = freq + 1
while (cond <= i) { // while we are within range of the sequence length..
bitShiftRight256ymm(&temp, j); // shift the copy of sequence by j bits
__m128i t128 = _mm256_castsi256_si128(temp);// cast it to length of 128 bits for faster functions
if (!masked128eq(&t128, j, &target)) // check if the two parts are equal; break if negative, continue if positive
break;
if (++freq > curl) { // increase freq by one and update curl if the frequency is larger
curl = freq;
upper_limit = i / (curl + 1);
if (curl > last_curl) {
return curl; // mathematical break: the curl can't be larger than 'last_curl + 1'
}
}
cond += j; // try to find repetition once more
}
} return curl; // return curl (if we didn't break yet)
}
int main() {
build_mask();
__m256i seq = _mm256_set_epi64x(0, 0, 0, 1200457); // fill sequence initial sequence
uint8_t last_curl = 3; // if the curl would be > 3, we can break, thus we set the last curl to 3 in advance
for (int i = 22; i <= 256; ++i) { // while within range of the register (256 bits)
int curl = krul(i, last_curl, seq); // find curl of the current sequence
if (curl == 1) {
std::cout << i; // return the current length of the sequence if we encounter 1
break;
}
if (curl > 3) {
std::cout << i + 1; // return the current length of the sequence + 1 if we encounter curl > 3, because the next curl will be 1
break;
}
bitShiftLeftByOne256ymm(&seq); // shift the sequence left one bit
static const __m256i mask1 = _mm256_set_epi64x(0, 0, 0, 1);
if (curl - 2)
seq = _mm256_or_si256(seq, mask1); // and add 1 if the curl is 3 (binary twin)
last_curl = curl; // save the curl
}
}
</code></pre>
<p>Very quick overview: in main, we start with a specific sequence of length 22 (the binary twin of the 2-3 sequence, represented as an integer). We calculate the curling number by making a copy of the sequence, and shifting it by <em>j</em> bits, where <em>j</em> represents the length of the period we are testing. we mask these last <em>j</em> bits of both sequences, and if they match, this means a frequency of 2 is found, and we repeat this until the shifted sequence and original sequence don't match. We return the highest found frequency after going through all possible options (with a simple mathematical break included). Then, we shift the sequence left by one bit, add the curling number (in its binary twin), and repeat the process, until we find curl(seq) = 1, or curl(seq) > 3, which would result in the next curling number being 1.</p>
<p>The script generates the requested output, i.e. the length of the sequence when the curl = 1 is found. Which, in this case, is 142.</p>
<p>I want to squeeze out more performance, so I wish someone could help me. We would appreciate if someone with knowledge of Assembly could help us, because we would like to know if there are any useless / unnecessary copies from memory to registers. But any other implementation that can be improved by anyone, is welcome anyway!</p>
<p>Thanks in advance!</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-18T15:42:56.360",
"Id": "253625",
"Score": "1",
"Tags": [
"c++",
"performance",
"assembly",
"sse"
],
"Title": "C++ calculation of curling number in sequences (Assembly?)"
}
|
253625
|
<p>This is the follow up question of <a href="https://codereview.stackexchange.com/q/253498/100620">How can we optimizing Java BigInteger operations?</a></p>
<h1>Problem</h1>
<p>Reduce the number to 1 in a minimal number of steps, following the rules:</p>
<pre><code>If the number is even, divide it by 2.
Otherwise, increment or decrement it by 1.
</code></pre>
<p>Limit: s can be up to 309 digits long.</p>
<h1>Solution</h1>
<p>The solution I have come up with is below:</p>
<pre><code>import java.math.BigInteger;
public class Solution {
public static int solution(String s) {
BigInteger n = new BigInteger(s);
if ( isPrimitive(n) ) {
return longOps(0, n.longValue());
}
return bigIntOps(n);
}
public static int bigIntOps(BigInteger n) {
BigInteger one = BigInteger.ONE;
BigInteger two = BigInteger.TWO;
BigInteger four = new BigInteger("4");
int count = 0;
while (n.compareTo(one) == 1) {
count++;
if( n.and(one).byteValue() == 0 ){
n = n.shiftRight(1);
if ( isPrimitive(n) )
return longOps(count, n.longValue());
} else if ( n.byteValue() == 3 || n.mod(four).byteValue() == 1)
n = n.subtract(one);
else
n = n.add(one);
}
return count;
}
public static int longOps(int count, long n) {
while (n > 1) {
count++;
// If number is divisible by 2
if ( (n & 1) == 0 ) {
// Check if the number is power of two
if ((n&(n-1)) == 0)
return (int)Math.ceil(Math.log(n)/Math.log(2)) + count - 1;
else
n = n >> 1;// Binary Division
} else if ( n == 3 || n%4 == 1 )
n--;
else
n++;
}
return count;
}
public static boolean isPrimitive(BigInteger n) {
return n.compareTo(new BigInteger(String.valueOf(Long.MAX_VALUE))) < 0;
}
}
</code></pre>
<p>Just some note from the source I collect:</p>
<p>"From the research, <code>BigInteger</code> operations are memory intensive and hence slow. Hence, the processing was divided into <code>BigInteger</code> processing and <code>long</code> processing.</p>
<p>A check was made at first to see if the number is <code>long</code>, and the processing was divided based on the number.
Check was also made in the <code>BigInteger</code> processing to check if the remainder was a <code>long</code>, and if true, further processing was done for <code>long</code> processing.</p>
<p>I found a sweet math solution to find the 2 power of number:
<code>Math.ceil(Math.log(x)/Math.log(2))</code></p>
<p>This solution provided a single statement to find the number of steps.</p>
<p>Unfortunately <code>BigInteger</code> does not provide <code>Math.log()</code> functionality so this could not be implemented which could have been a great solution."</p>
<ul>
<li><a href="https://github.com/JavaCheatsheet/codechallenge/blob/master/src/google/Level3/Part3/README.md" rel="nofollow noreferrer">https://github.com/JavaCheatsheet/codechallenge/blob/master/src/google/Level3/Part3/README.md</a></li>
</ul>
|
[] |
[
{
"body": "<h1>Log2(n)</h1>\n<p><code>Math.ceil(Math.log(x)/Math.log(2))</code> is not the fastest way of determining <span class=\"math-container\">\\$\\lceil\\log_2{n}\\rceil\\$</span>, of an integer n. That requires converting the integer to a double, calculating the transcendental function, dividing by a constant, and then converting back to an integer, while rounding up.</p>\n<p>Much faster is to count the number of bits in the value. <span class=\"math-container\">\\$\\lceil\\log_2{255}\\rceil\\$</span> is 8, and <span class=\"math-container\">\\$255 = 11111111_2\\$</span> which has 8 bits. Exact powers of two are represented by a 1 followed by <span class=\"math-container\">\\$\\log_2\\$</span> zeros; we can fix this with a tiny amount of preprocessing: subtracting 1.</p>\n<p>Java doesn't directly provide the number of bits in an <code>int</code>, but it does give us <code>Integer.numberOfLeadingZeros()</code>, which will we can use to get the answer:</p>\n<pre><code>int ceil_log_2(int n) {\n if (n < 1)\n return Integer.MIN_VALUE;\n return 32 - Integer.numberOfLeadingZeros(n - 1);\n}\n</code></pre>\n<p>Java's <code>BigInteger</code> does give us the <code>BigInteger.bitLength()</code> which does directly give the number of bits required to represent the number, so will give us the answer more directly:</p>\n<pre><code>int ceil_log_2(BigInteger n) {\n if (n.compareTo(BigInteger.ONE) < 0)\n return Integer.MIN_VALUE;\n return n.subtract(BigInteger.ONE).bitLength();\n}\n</code></pre>\n<hr />\n<h1>bigIntOps</h1>\n<h2>Even/Odd</h2>\n<p>In <code>bigIntOps()</code>, you are now dividing by 2 using a <code>shiftRight(1)</code> operation. Good; that faster than actual division.</p>\n<p>But you are testing if the value is even by and'ing the <code>BigInteger</code> value with <code>BigInteger.ONE</code>, which likely allocates a new <code>BigInteger</code> value, which after being used must be garbage collected. Then, you discard all of the upper bits of the value keeping only the lower 8 with <code>.byteValue()</code>, and finally test if that is zero.</p>\n<p>You could simply discard the upper bits, then and with 1, and test:</p>\n<pre><code>if (n.byteValue() & 1 == 0)\n</code></pre>\n<p>Now no additional <code>BigInteger</code> temporary object is being created, which is a win. But that is still doing unnecessary work. Java directly provides a way of testing individual bits of a <code>BigInteger</code>, with <code>.testBit()</code>:</p>\n<pre><code>if (n.testBit(0) == false)\n</code></pre>\n<h2>Looping</h2>\n<p>While the result is even, you are dividing by 2. You are doing this by shifting by 1 bit, which is faster than division, but still creates a new <code>BigInteger</code> object each step.</p>\n<p>You notice this with your power-of-two test in <code>longOps</code>, and handle a power-of-two final value in one operation, instead of doing it in multiple steps.</p>\n<p>Why not do that in <code>bigIntOps</code> as well?</p>\n<p><code>BigInteger.getLowestSetBit()</code> will tell you the number of trailing zero bits in the number, which is the number of times it can be divided evenly by 2. And this works not only for exact power-of-twos</p>\n<pre><code>int zeros = n.getLowestSetBit();\nn = n.shiftRight(zeros)\ncount += zeros;\n</code></pre>\n<p>Note that this works for integers as well:</p>\n<pre><code>int zeros = Integer.numberOfTrailingZeros(n);\nn >>= zeros;\ncount += zeros;\n</code></pre>\n<p>So instead of doing a bunch of divisions one at a time, you can do them in bulk. And not just for power of twos.</p>\n<p>With the value <span class=\"math-container\">\\$3*2^{1024}\\$</span>, you'd do 1024 divisions by 2 in one step, leaving 3, which you'd then subtract 1, and then divide by 2, for 1026 steps, done in 3 calculations.</p>\n<h2>mod-4</h2>\n<p>Like the <code>n.and(one)</code> early, <code>n.mod(four).byteValue() == 1</code> takes a possibly 1000-bit number, and does expensive modulo-4 division, and creates a new <code>BigInteger</code> value to store the result in, which must be allocated, and then garbage collected later. You then discard all of the upper bits, and compare the result with 1.</p>\n<p>Again, since your doing modulo-4 math, you can do modulo-256 math first, without changing the result. <code>n.byteValue() % 4 == 1</code>. This means no temporary <code>BigInteger</code> object needs to be created.</p>\n<p>But because you know that <code>n</code> is odd (or you would be doing division-by-2), the results must be 1 or 3. This means you are effectively just testing whether or not bit 1 is set. <code>n.testBit(1) == false</code>. Which is a lot clearer and more direct:</p>\n<h1>isPrimitive</h1>\n<p>Every time, <code>isPrimitive</code> is called, this statement is executed:</p>\n<pre><code> return n.compareTo(new BigInteger(String.valueOf(Long.MAX_VALUE))) < 0;\n</code></pre>\n<p>You are converting <code>Long.MAX_VALUE</code> to a string, and then converting that back to binary form in <code>BigInteger</code>.</p>\n<p>EVERY TIME!</p>\n<p>If ever there was time to declare a constant, that was it, so it was done once, and not every call.</p>\n<p>It could also be made more efficient by getting rid of the string intermediate step, and simple use <code>BigInteger.valueOf(Long.MAX_VALUE)</code>.</p>\n<hr />\n<h1>Improved Code</h1>\n<pre class=\"lang-java prettyprint-override\"><code>import java.math.BigInteger;\n\npublic class Solution {\n\n private final static BigInteger MAX_LONG = BigInteger.valueOf(Long.MAX_VALUE);\n\n public static int solution(String s) {\n BigInteger n = new BigInteger(s);\n int count = 0;\n\n while (n.compareTo(MAX_LONG) > 0) {\n int zeros = n.getLowestSetBit();\n\n if (zeros > 0) { // Even!\n n = n.shiftRight(zeros);\n count += zeros;\n } else { // Odd\n if (n.testBit(1)) // At least 2 least significant one bits\n n = n.add(BigInteger.ONE);\n else // Only 1 least significant one bit\n n = n.subtract(BigInteger.ONE);\n count++;\n }\n }\n\n // Value now fits with a primitive long\n long lv = n.longValue();\n\n while (lv > 3) {\n int zeros = Long.numberOfTrailingZeros(lv);\n if (zeros > 0) { // Even!\n lv >>= zeros;\n count += zeros;\n } else { // Odd\n if (lv % 4 == 1) // Only 1 least significant one bit\n lv--; \n else\n lv++; // At least 2 least significant one bits\n count++;\n }\n }\n\n if (lv == 3)\n count += 2;\n if (lv == 2)\n count += 1;\n\n return count;\n }\n}\n</code></pre>\n<p>Notice:</p>\n<ul>\n<li>The <code>BigInteger</code> loop condition loops while the value is greater than <code>Long.MAX_VALUE</code>, instead of while greater than 1. This naturally breaks out of the loop when the value is small enough. No need for a separate test.</li>\n<li>The <code>n.byteValue() == 3</code> special case is not even present in <code>BigInteger</code> case, since it does not change the number of steps, and adding the test will slow execution down.</li>\n<li>The <code>lv == 3</code> special case can been removed from the primitive loop as well, by only looping while <code>lv > 3</code>!</li>\n</ul>\n<hr />\n<h1>Improved Algorithm</h1>\n<p>Consider:</p>\n<pre class=\"lang-none prettyprint-override\"><code>11111000000111111100000000111111100000000111011100000111100000111 +1\n11111000000111111100000000111111100000000111011100000111100001000 / 2^3\n11111000000111111100000000111111100000000111011100000111100001 -1\n11111000000111111100000000111111100000000111011100000111100000 / 2^5\n111110000001111111000000001111111000000001110111000001111 +1\n111110000001111111000000001111111000000001110111000010000 / 2^4\n11111000000111111100000000111111100000000111011100001 -1\n11111000000111111100000000111111100000000111011100000 / 2^5\n111110000001111111000000001111111000000001110111 +1\n111110000001111111000000001111111000000001111000 / 2^3\n111110000001111111000000001111111000000001111 +1\n111110000001111111000000001111111000000010000 / 2^4\n11111000000111111100000000111111100000001 -1\n11111000000111111100000000111111100000000 / 2^8\n111110000001111111000000001111111 +1\n111110000001111111000000010000000 / 2^7\n11111000000111111100000001 -1\n11111000000111111100000000 / 2^8\n111110000001111111 +1\n111110000010000000 / 2^7\n11111000001 -1\n11111000000 / 2^6\n11111 +1\n100000 / 2^5\n</code></pre>\n<p>How many bits were there originally? How many divide by 2's?</p>\n<p>How many groups of 1 bits were there? How many extra operations did a single 1 bit require? How many operations did a group of more than a single 1 bit require?</p>\n<p>Can you just count groups of 1's, single 1's, and total number of bits? Are there any special cases you need to consider, like ending with 3, or a single 0 bit?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-20T06:29:36.237",
"Id": "500259",
"Score": "0",
"body": "That is a perfect example of how code review should be done! Hats off Sir.\n\nI just read your feedback and ran the code against the test codes but unfortunately it fails for BigInteger. Could you please verify by yourself as well? :)\n\nThe recommendations are really great so I am making adjustments based on them and will get back to you soon. \n\nThank you so much. I just enjoyed the experience."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-20T06:48:06.610",
"Id": "500260",
"Score": "1",
"body": "Hats off? No! This is the Winter Bash! We’re supposed to be putting hats on. Re: BigIntegers not working, looks like I forgot `n = ` at the start of the `n.shiftRight(zeros)` line. Performed the shift, but didn’t store the result. Sigh."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-20T06:55:11.783",
"Id": "500262",
"Score": "0",
"body": "LOL.. \n\nThank you @AJNeufeld! Solution works. \n\nYou definitely pointed out what I was looking for.\n\nI hope you have a great time ahead. Take care."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-20T01:48:36.697",
"Id": "253686",
"ParentId": "253626",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "253686",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-18T15:53:41.110",
"Id": "253626",
"Score": "1",
"Tags": [
"java",
"performance",
"programming-challenge",
"memory-optimization",
"bigint"
],
"Title": "Follow-up: How can we optimizing Java BigInteger operations?"
}
|
253626
|
<p>This is a snippet of code written in Python 3.9 to implement the concept of "enum unions": an enum made up of several sub-enums whose set of members is the union of the sub-enums' members. This aims to be fully compatible with the standard library <code>enum</code>. Up-to-date code with some documentation can be found <a href="https://gist.github.com/plammens/ab1a2f236b5c6d748f193eb12eefa6dd" rel="nofollow noreferrer">here</a>.</p>
<p>Usage and desired behaviour:</p>
<pre class="lang-py prettyprint-override"><code>import enum
class EnumA(enum.Enum):
A = 1
class EnumB(enum.Enum):
B = 2
ALIAS = 1
class EnumC(enum.Enum):
C = 3
</code></pre>
<pre><code>>>> UnionAB = enum_union(EnumA, EnumB)
>>> UnionAB.__members__
mappingproxy({'A': <EnumA.A: 1>, 'B': <EnumB.B: 2>, 'ALIAS': <EnumA.A: 1>})
>>> list(UnionAB)
[<EnumA.A: 1>, <EnumB.B: 2>]
>>> EnumA.A in UnionAB
True
>>> EnumB.ALIAS in UnionAB
True
>>> isinstance(EnumB.B, UnionAB)
True
>>> issubclass(UnionAB, enum.Enum)
True
>>> UnionABC = enum_union(UnionAB, EnumC)
>>> UnionABC.__members__
mappingproxy({'A': <EnumA.A: 1>, 'B': <EnumB.B: 2>, 'ALIAS': <EnumA.A: 1>, 'C': <EnumC.C: 3>})
>>> set(UnionAB).issubset(UnionABC)
True
</code></pre>
<p>The code is below. I'm mainly concerned with design, maintainability, compatibility with <code>enum</code> and intuitive (unsurprising) behaviour for the user. The implementation uses the internals of <code>enum.EnumMeta</code>; I'm aware this might be brittle or might not be reliable in the long run but it's the only way of reusing most of <code>enum.EnumMeta</code>'s code without rewriting the whole thing.</p>
<pre class="lang-py prettyprint-override"><code>import enum
import itertools as itt
from functools import reduce
import operator
from typing import Literal, Union
import more_itertools as mitt
AUTO = object()
class UnionEnumMeta(enum.EnumMeta):
"""
The metaclass for enums which are the union of several sub-enums.
Union enums have the _subenums_ attribute which is a tuple of the enums forming the
union.
"""
@classmethod
def make_union(
mcs, *subenums: enum.EnumMeta, name: Union[str, Literal[AUTO], None] = AUTO
) -> enum.EnumMeta:
"""
Create an enum whose set of members is the union of members of several enums.
Order matters: where two members in the union have the same value, they will
be considered as aliases of each other, and the one appearing in the first
enum in the sequence will be used as the canonical members (the aliases will
be associated to this enum member).
:param subenums: Sequence of sub-enums to make a union of.
:param name: Name to use for the enum class. AUTO will result in a combination
of the names of all subenums, None will result in "UnionEnum".
:return: An enum class which is the union of the given subenums.
"""
subenums = mcs._normalize_subenums(subenums)
class UnionEnum(enum.Enum, metaclass=mcs):
pass
union_enum = UnionEnum
union_enum._subenums_ = subenums
if duplicate_names := reduce(
set.intersection, (set(subenum.__members__) for subenum in subenums)
):
raise ValueError(
f"Found duplicate member names in enum union: {duplicate_names}"
)
# If aliases are defined, the canonical member will be the one that appears
# first in the sequence of subenums.
# dict union keeps last key so we have to do it in reverse:
union_enum._value2member_map_ = value2member_map = reduce(
operator.or_, (subenum._value2member_map_ for subenum in reversed(subenums))
)
# union of the _member_map_'s but using the canonical member always:
union_enum._member_map_ = member_map = {
name: value2member_map[member.value]
for name, member in itt.chain.from_iterable(
subenum._member_map_.items() for subenum in subenums
)
}
# only include canonical aliases in _member_names_
union_enum._member_names_ = list(
mitt.unique_everseen(
itt.chain.from_iterable(subenum._member_names_ for subenum in subenums),
key=member_map.__getitem__,
)
)
if name is AUTO:
name = (
"".join(subenum.__name__.removesuffix("Enum") for subenum in subenums)
+ "UnionEnum"
)
UnionEnum.__name__ = name
elif name is not None:
UnionEnum.__name__ = name
return union_enum
def __repr__(cls):
return f"<union of {', '.join(map(str, cls._subenums_))}>"
def __instancecheck__(cls, instance):
return any(isinstance(instance, subenum) for subenum in cls._subenums_)
@classmethod
def _normalize_subenums(mcs, subenums):
"""Remove duplicate subenums and flatten nested unions"""
# we will need to collapse at most one level of nesting, with the inductive
# hypothesis that any previous unions are already flat
subenums = mitt.collapse(
(e._subenums_ if isinstance(e, mcs) else e for e in subenums),
base_type=enum.EnumMeta,
)
subenums = mitt.unique_everseen(subenums)
return tuple(subenums)
def enum_union(*enums, **kwargs):
return UnionEnumMeta.make_union(*enums, **kwargs)
</code></pre>
|
[] |
[
{
"body": "<p>For the benefit of anyone else that, like me, does not read Typing nor Black, here is the code reformatted. Comments are interspersed.</p>\n<pre><code>AUTO = object()\n\nclass UnionEnumMeta(enum.EnumMeta):\n """\n The metaclass for enums which are the union of several sub-enums.\n\n Union enums have the _subenums_ attribute which is a tuple of the enums\n forming the union.\n """\n\n @classmethod\n def make_union(mcs, *subenums, name=AUTO):\n """\n Create an enum whose set of members is the union of members of\n several enums.\n\n Order matters: where two members in the union have the same value,\n they will be considered as aliases of each other, and the one appearing\n in the first enum in the sequence will be used as the canonical members\n (the aliases will be associated to this enum member).\n\n :param subenums: Sequence of sub-enums to make a union of.\n :param name: Name to use for the enum class. AUTO will result in a\n combination of the names of all subenums, None will result\n in "UnionEnum".\n :return: An enum class which is the union of the given subenums.\n """\n subenums = mcs._normalize_subenums(subenums)\n\n class UnionEnum(enum.Enum, metaclass=mcs):\n pass\n\n union_enum = UnionEnum\n</code></pre>\n<p>Did you mean to instantiate <code>UnionEnum</code> here? Looks like you forgot the parenthesis.</p>\n<pre><code> union_enum._subenums_ = subenums\n\n if duplicate_names := reduce(\n set.intersection,\n (set(subenum.__members__) for subenum in subenums),\n ):\n raise ValueError(\n f"Found duplicate member names in enum union: {duplicate_names}"\n )\n\n # If aliases are defined, the canonical member will be the one that\n # appears first in the sequence of subenums.\n # dict union keeps last key so we have to do it in reverse:\n union_enum._value2member_map_ = value2member_map = reduce(\n operator.or_,\n (subenum._value2member_map_ for subenum in reversed(subenums)),\n )\n # union of the _member_map_'s but using the canonical member always:\n union_enum._member_map_ = member_map = {\n name: value2member_map[member.value]\n for name, member in itt.chain.from_iterable(\n subenum._member_map_.items() for subenum in subenums\n )}\n # only include canonical aliases in _member_names_\n union_enum._member_names_ = list(\n mitt.unique_everseen(\n itt.chain.from_iterable(\n subenum._member_names_ for subenum in subenums\n ),\n key=member_map.__getitem__,\n ))\n\n if name is AUTO:\n name = (\n "".join(\n subenum.__name__.removesuffix("Enum")\n for subenum in subenums\n )\n + "UnionEnum"\n )\n UnionEnum.__name__ = name\n elif name is not None:\n UnionEnum.__name__ = name\n</code></pre>\n<p>What happens if <code>name</code> is <code>None</code>?</p>\n<pre><code> return union_enum\n\n def __repr__(cls):\n return f"<union of {', '.join(map(str, cls._subenums_))}>"\n\n def __instancecheck__(cls, instance):\n return any(\n isinstance(instance, subenum)\n for subenum in cls._subenums_\n )\n\n @classmethod\n def _normalize_subenums(mcs, subenums):\n """Remove duplicate subenums and flatten nested unions"""\n # we will need to collapse at most one level of nesting, with the\n # inductive hypothesis that any previous unions are already flat\n subenums = mitt.collapse(\n (e._subenums_ if isinstance(e, mcs) else e for e in subenums),\n base_type=enum.EnumMeta,\n )\n subenums = mitt.unique_everseen(subenums)\n return tuple(subenums)\n\n\ndef enum_union(*enums, **kwargs):\n return UnionEnumMeta.make_union(*enums, **kwargs)\n</code></pre>\n<p>All in all, this looks very interesting. While the pieces you are referencing from <code>EnumMeta</code> are implementation details, they are unlikely to change. I am curious how <code>UnionEnum</code> would be used to solve the <a href=\"https://stackoverflow.com/q/65321592/208880\">original Stackoverflow question</a>?</p>\n<hr />\n<p>Disclosure: I am the author of the <a href=\"https://docs.python.org/3/library/enum.html\" rel=\"noreferrer\">Python stdlib <code>Enum</code></a>, the <a href=\"https://pypi.python.org/pypi/enum34\" rel=\"noreferrer\"><code>enum34</code> backport</a>, and the <a href=\"https://pypi.python.org/pypi/aenum\" rel=\"noreferrer\">Advanced Enumeration (<code>aenum</code>)</a> library.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-19T08:16:24.133",
"Id": "500202",
"Score": "0",
"body": "Thanks for the review! \"Did you mean to instantiate UnionEnum here?\" Not really; enums are classes, so what I want to return is the class itself (which is dynamically created every time that method is run); one can think of the `UnionEnum` class definition as the instantiation of `UnionEnumMeta` (or perhaps \"meta-instantiation\"). Then again, you could ask me why make the `union_enum` alias, and the answer would just be \"It felt weird setting attributes of a dynamically created class and so I used a lowercase alias to mentally hide that\" :) [continued]"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-19T08:20:10.513",
"Id": "500203",
"Score": "0",
"body": "[continuation] Regarding the `name=None` case, that just leaves the default `UnionEnum` name. Finally, you are right that I didn't really specify how this can be used in the original SO question; I've added an edit there. The idea is computing the union of the \"base\" enum and the \"extension\" enum to achieve exactly the desired behaviour (and more, since unions support additional non-alias members too)."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-18T19:53:56.613",
"Id": "253638",
"ParentId": "253628",
"Score": "5"
}
},
{
"body": "<p>I have made some observations and improvements myself, and I thought it could be useful to add them here as well.</p>\n<ul>\n<li><p>What happens with the empty union? Currently, the <code>reduce</code> calls will raise because they will receive an empty iterator.</p>\n<p>This can be fixed by simply adding the appropriate identity element to each <code>reduce</code> operation (as the <code>initial</code> argument), which will serve as the default value if the iterable is empty.</p>\n<p>Also, a minor aesthetic detail, an empty union would have a <code>repr</code> of <code><union of ></code>.</p>\n</li>\n<li><p>The check for duplicates is implemented as checking that the intersection of all names is empty:</p>\n<pre class=\"lang-py prettyprint-override\"><code>if duplicate_names := reduce(\n set.intersection, (set(subenum.__members__) for subenum in subenums)\n ):\n raise ValueError(...)\n</code></pre>\n<p>But this is not quite what we want to check: we don't want to check whether some names appear in <em>all</em> subenums; if a name appears in <em>more than one</em> subenum it's enough to mark it as a duplicate. This is most easily solved with a good old-fashioned for loop:</p>\n<pre class=\"lang-py prettyprint-override\"><code>names, duplicates = set(), set()\nfor subenum in subenums:\n for name in subenum.__members__:\n (duplicates if name in names else names).add(name)\nif duplicates:\n raise ValueError(f"Found duplicate member names: {duplicates}")\n</code></pre>\n<p>I guess I was too eager to make this look "mathematical" with <code>reduce</code> and set intersection.</p>\n</li>\n<li><p>The merging of the <code>_value2member_map_</code>s is done via <a href=\"https://www.python.org/dev/peps/pep-0584/\" rel=\"nofollow noreferrer\">PEP 584 dict union</a>:</p>\n<pre class=\"lang-py prettyprint-override\"><code> union_enum._value2member_map_ = value2member_map = reduce(\n operator.or_, (subenum._value2member_map_ for subenum in reversed(subenums))\n )\n</code></pre>\n<p>Something to keep in mind is that this makes a copy for every intermediate operand, and so this will be inefficient for moderate to large numbers of subenums. If, however, this is intended for just a small size of subenums that are specified manually in the varargs list, it should be fine. An advantage of using the union operator is that it is a pure function and hence there's no risk of accidentally modifying one of the subenums.</p>\n</li>\n<li><p>Since union enums are not really a type in themselves (semantically speaking), they just aggregate a bunch of other enums, it might make sense to implement equality in terms of subenums:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def __eq__(cls, other):\n """Equality based on the tuple of subenums (order-sensitive)."""\n if not isinstance(other, UnionEnumMeta):\n return NotImplemented\n return cls._subenums_ == other._subenums_\n</code></pre>\n<p>Using the example above, this would result in</p>\n<pre><code>>>> enum_union(UnionAB, EnumC) == enum_union(EnumA, EnumB, EnumC)\nTrue\n</code></pre>\n<p>which makes sense intuitively.</p>\n</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-20T12:08:15.503",
"Id": "500274",
"Score": "1",
"body": "You can also declare the function as an alias: `enum_union = UnionEnumMeta.make_union` without need to push another function call in the stack"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-20T12:05:42.427",
"Id": "253700",
"ParentId": "253628",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "253638",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-18T17:34:19.653",
"Id": "253628",
"Score": "6",
"Tags": [
"python",
"object-oriented",
"enum"
],
"Title": "Enum union in Python"
}
|
253628
|
<p>I wrote this mini thread pool in JavaScript that takes a maximum number of concurrently running tasks and runs them in the order it was given. I appreciate any feedback or review. Thank you.</p>
<pre><code>class TaskPool {
constructor(poolSize) {
this.poolSize = poolSize;
this.queue = [];
this.runningTasks = 0;
this.scheduled = null;
this.id = 0;
}
backgroundRunner() {
if (this.queue.length) {
if (this.runningTasks < this.poolSize) {
const index = 0;
const [[task, id]] = this.queue.splice(index, 1);
this.runningTasks++;
task(id).finally(() => {
this.runningTasks--;
this.backgroundRunner();
});
} else {
console.log('queue is full');
if (!this.scheduled) {
console.log('scheduled for later');
this.scheduled = setTimeout(() => {
this.backgroundRunner();
this.scheduled = false;
}, 1000);
}
}
}
}
run(task) {
this.queue.push([task, ++this.id]);
this.backgroundRunner();
}
}
</code></pre>
<p>Tests:</p>
<pre><code>function task(id) {
//create an ID
return new Promise((resolve, _) => {
console.log('running task #', id);
setTimeout(() => {
console.log('done running task #', id);
resolve();
}, 400);
});
}
const pool = new TaskPool(3);
for (let i = 0; i < 10; i++) {
pool.run(task);
}
</code></pre>
<p><a href="https://jsfiddle.net/ud3vxh8s/" rel="nofollow noreferrer">jsfiddle</a></p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-18T22:59:17.420",
"Id": "500191",
"Score": "0",
"body": "Maybe this steps from some confusion with promises? javascript is single threaded. promises are just a fancy alternative to using callback, and all callbacks execute on the same thread - one callback after another. Look up \"Javascript event loop\" to learn more about how this works. If you really want to do threading, you can use \"web workers\" to do the job. But a \"promise pool\" is just overhead that'll slow things down, not speed them up."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-19T00:44:49.857",
"Id": "500193",
"Score": "0",
"body": "@ScottyJamison This was an interview question. I wanted to get feedback for my code"
}
] |
[
{
"body": "<p>Some suggestions:</p>\n<ul>\n<li><p>It's not entirely clear until getting to the bottom of the class what the <code>queue</code> array holds. Maybe call it something more precise like <code>unstartedTasks</code> or <code>unstartedTasksQueue</code>.</p>\n</li>\n<li><p>You can return early to avoid nested indentation - cutting down on unnecessary indentation can make it clearer exactly which block a <code>}</code> at the end corresponds to. For example, <code>backgroundRunner</code> could be made to be:</p>\n<pre><code>backgroundRunner() {\n if (!this.queue.length) {\n return;\n }\n // lots of code\n</code></pre>\n</li>\n<li><p>The <code>scheduled for later</code> section looks superfluous since unstarted tasks will be run immediately upon the completion of a task, due to the</p>\n<pre><code>task(id).finally(() => {\n this.runningTasks--;\n this.backgroundRunner();\n});\n</code></pre>\n</li>\n<li><p>When you want to remove the first element from an array and use it, use <code>shift</code>, not <code>splice</code>. This:</p>\n<pre><code>const [[task, id]] = this.queue.splice(index, 1);\n</code></pre>\n<p>can be</p>\n<pre><code>const [task, id] = this.queue.shift();\n</code></pre>\n</li>\n<li><p>Unless the insertion index of the task <em>needs</em> to be saved, you could simplify the queue by incrementing and using the <code>id</code> not when the task is pushed, but when the task gets executed. This way the queue only needs to be an array of functions, not an array of <code>[task, id]</code>s.</p>\n</li>\n</ul>\n<p>See below for the version I'd prefer, if a class-based implementation is required. I use <code>#</code> to clearly distinguish what's exclusively private methods and properties from a public method:</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>class TaskPool {\n #unstartedTasksQueue = [];\n #runningTaskCount = 0;\n #id = 0;\n #runningTaskLimit;\n constructor(runningTaskLimit) {\n this.#runningTaskLimit = runningTaskLimit;\n }\n insertTask(fn) {\n if (this.#runningTaskCount === this.#runningTaskLimit) {\n this.#unstartedTasksQueue.push(task);\n } else {\n this.#startTask(fn);\n }\n }\n #startTask(fn) {\n this.#runningTaskCount++;\n fn(this.#id++).finally(() => {\n if (this.#unstartedTasksQueue.length) {\n this.#startTask(this.#unstartedTasksQueue.shift());\n } else {\n this.#runningTaskCount--;\n }\n });\n }\n}\n\nfunction task(id) {\n //create an ID\n return new Promise((resolve) => {\n console.log('running task #', id);\n setTimeout(() => {\n console.log('done running task #', id);\n resolve();\n }, 4000);\n });\n}\n\nconst pool = new TaskPool(3);\nfor (let i = 0; i < 5; i++) {\n pool.insertTask(task);\n}</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>But all the private methods and properties, despite making the code's <em>intent</em> a bit clearer, can look a bit ugly. Since the external user of the class is only interfacing with 2 things (the constructor, and the <code>run</code> method), I'd prefer to make a <em>function</em> instead of a class, which returns the <code>run</code> (or, as I've named it, <code>insertTask</code>) method, so as to rely on the closure instead of on <code>#</code>s:</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const makeTaskPool = (runningTaskLimit) => {\n const unstartedTasksQueue = [];\n let runningTaskCount = 0;\n let id = 0;\n const startTask = (fn) => {\n runningTaskCount++;\n fn(id++).finally(() => {\n if (unstartedTasksQueue.length) {\n startTask(unstartedTasksQueue.shift());\n } else {\n runningTaskCount--;\n }\n });\n };\n return (fn) => {\n if (runningTaskCount === runningTaskLimit) {\n unstartedTasksQueue.push(task);\n } else {\n startTask(fn);\n }\n };\n};\n\nfunction task(id) {\n //create an ID\n return new Promise((resolve) => {\n console.log('running task #', id);\n setTimeout(() => {\n console.log('done running task #', id);\n resolve();\n }, 4000);\n });\n}\n\nconst insertTask = makeTaskPool(3);\nfor (let i = 0; i < 5; i++) {\n insertTask(task);\n}</code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-19T01:29:34.527",
"Id": "253646",
"ParentId": "253630",
"Score": "3"
}
},
{
"body": "<h1>Poor jargon leads to bugs</h1>\n<p>An important part of coding is correctly describing and/or interpreting from natural language what the code does or should do.</p>\n<p>As natural language can be very ambiguous, descriptions use a lot of jargon that have very specific meaning within the context of programming, often completely different from the colloquial meaning.</p>\n<p>If you are unsure about the correct use of programming jargon you should look it up.</p>\n<h3>Concurrent</h3>\n<p><sub>From google</sub></p>\n<blockquote>\n<p><em>"Concurrent tasks are multiple tasks that progress at the same time but they are not executed simultaneously"</em></p>\n</blockquote>\n<h3>Thread</h3>\n<p><sub>From google</sub></p>\n<blockquote>\n<p><em>"A thread is a unit of execution. Multithreading is a technique which allows a CPU to execute many tasks of one process at the same time. "</em></p>\n</blockquote>\n<ul>\n<li><p><em>"Multithreading"</em> and <em>"Thread"</em> are interchangeable in JavaScript (and most languages) as JavaScript does not provide a mechanism to distinguish the two.</p>\n</li>\n<li><p>In JavaScript a <em>"Thread"</em> has a specific property of being <em>"Non blocking"</em></p>\n</li>\n<li><p>In JavaScript a <em>"Thread"</em> is AKA a <em>"worker"</em>.</p>\n</li>\n</ul>\n<h2>Bug #1</h2>\n<p>The question's title and question</p>\n<blockquote>\n<p><em>"Mini JavaScript thread pool with maximum number of concurrently running tasks"</em></p>\n</blockquote>\n<blockquote>\n<p><em>"I wrote this mini thread pool in JavaScript that takes a maximum number of concurrently running tasks..."</em></p>\n</blockquote>\n<p>Threads run in parallel or concurrently via web workers. If I create a task I would expect your code to do as advertised.</p>\n<pre><code>function task(id) {\n return new Promise(completed => {\n while (Math.random() > 0.00001) {}\n completed();\n });\n}\n\nconst pool = new TaskPool(3);\npool.run(task); // Blocks for indeterminate time\npool.run(task); // this line is not executed until previous task is complete\n</code></pre>\n<p>However as your code is not threaded and the tasks do not run concurrently, the first task blocking all execution until it resolves its promise.</p>\n<h2>Bug #2</h2>\n<p>Your code assumes that the task returns a promise. As you do not vet the argument <code>task</code> in <code>run(task) {</code> to make sure it is a function, and when you attempt to execute it, if it does not throw <em>"task Is not a function"</em> it will throw <em>".finally is not a function"</em> if <code>task</code> does not return a <code>promise</code>.</p>\n<p>Because the task count <code>this.runningTasks++;</code> is incremented before the error each time there is this error the pool size is permanently reduced by one.</p>\n<h2>Redundant code.</h2>\n<p>The polling of <code>TaskPool.backgroundRunner</code></p>\n<pre><code> else {\n console.log('queue is full');\n if (!this.scheduled) {\n console.log('scheduled for later');\n this.scheduled = setTimeout(() => {\n this.backgroundRunner();\n this.scheduled = false;\n }, 1000);\n }\n }\n</code></pre>\n<p>And property</p>\n<pre><code> this.scheduled = false;\n</code></pre>\n<p>can be completely removed from the code without changing its behavior at all.</p>\n<p>There is no need to poll <code>backgroundRunner</code> as the <code>task.finally</code> has a 1 to 1 match with completed tasks.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-19T18:15:53.127",
"Id": "253670",
"ParentId": "253630",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "253646",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-18T18:24:02.267",
"Id": "253630",
"Score": "2",
"Tags": [
"javascript",
"promise"
],
"Title": "Mini JavaScript thread pool with maximum number of concurrently running tasks"
}
|
253630
|
<p>I built an allsky camera with a temperature sensor and a heater. The heater is supposed to turn when the sensor (<code>measure_temp()</code>) return a temperature below 8, which is checked every 15 minutes. However, about every 4th measurement fails and so I included an error handler that returns 7, so that the heater turns on if the sensor returns an error, but it seems like a bad solution. Is there a better way to handle the error like run the function until no error occurs?</p>
<pre><code>import RPi.GPIO as GPIO
import time
import datetime
import time
import board
import adafruit_dht
def measure_temp():
dhtDevice = adafruit_dht.DHT22(board.D18)
try:
temperature = dhtDevice.temperature
error_test = ""
except RuntimeError as error:
temperature = 7
except:
temperature = 7
return temperature
if __name__ == '__main__':
while True:
if measure_temp() < 8:
GPIO.setmode(GPIO.BCM)
RELAIS_1_GPIO = 17
GPIO.setup(RELAIS_1_GPIO, GPIO.OUT)
GPIO.output(RELAIS_1_GPIO, GPIO.HIGH)
print('{:%d.%m.%Y %H:%M:%S}'.format(datetime.datetime.now()))
print('Heating on')
print()
time.sleep(900)
GPIO.cleanup()
else:
GPIO.setmode(GPIO.BCM)
RELAIS_1_GPIO = 17
GPIO.setup(RELAIS_1_GPIO, GPIO.OUT)
GPIO.output(RELAIS_1_GPIO, GPIO.LOW)
print('{:%d.%m.%Y %H:%M:%S}'.format(datetime.datetime.now()))
print('Heating off')
time.sleep(900)
GPIO.cleanup()
</code></pre>
|
[] |
[
{
"body": "<p>Every 4th measurement fails is a pretty high error rate. The preferred course of action would be to root cause the error and fix it. Meanwhile, since the error seems to be transient, you may want to read the sensor again, and again, until it reads cleanly. Another strategy is to read more often, and maintain the running average (discarding the failures).</p>\n<p>For a proper review, <strong>DRY</strong>. The GPIO setup shall be lifted out of the <code>if/else</code>:</p>\n<pre><code>while True:\n GPIO.setmode(GPIO.BCM)\n RELAIS_1_GPIO = 17\n GPIO.setup(RELAIS_1_GPIO, GPIO.OUT)\n if measure_temp() < 8:\n GPIO.output(RELAIS_1_GPIO, GPIO.HIGH)\n print('{:%d.%m.%Y %H:%M:%S}'.format(datetime.datetime.now()))\n print('Heating on')\n print()\n else:\n GPIO.output(RELAIS_1_GPIO, GPIO.LOW)\n print('{:%d.%m.%Y %H:%M:%S}'.format(datetime.datetime.now()))\n print('Heating off')\n time.sleep(900)\n GPIO.cleanup()\n</code></pre>\n<p>I also recommend to factor the printing out to the function, e.g.</p>\n<pre><code>def log_heating_status(status):\n print('{:%d.%m.%Y %H:%M:%S}'.format(datetime.datetime.now()))\n print('Heating {%s}'.format(status))\n</code></pre>\n<p>to be called as <code>log_heating_status('on')</code> and <code>log_heating_status('off')</code>.</p>\n<p>It is also very unclear why do you setup/cleanup GPIO on every iteration. I'd expect it to be done once, outside the loop.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-20T08:28:30.437",
"Id": "500265",
"Score": "0",
"body": "thanks for you feedback @vnp!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-19T20:52:51.917",
"Id": "253678",
"ParentId": "253632",
"Score": "4"
}
},
{
"body": "<h3>Constants should be defined at module level</h3>\n<p><code>RELAIS_1_GPIO = 17</code> doesn't seem to change. Define it right after the import statements.</p>\n<h3>Keep implementation details out of your main loop</h3>\n<p>You currently know what <code>GPIO.output(RELAIS_1_GPIO, GPIO.HIGH)</code> does, but will you know in a couple of months? In addition to what @vnp recommended, better extract that into a function <code>turn_heater_on()</code>, the same goes for turning the heater off.</p>\n<pre class=\"lang-py prettyprint-override\"><code>if measure_temp() < 8:\n turn_heater_on()\nelse:\n turn_heater_off()\n</code></pre>\n<h3>Don't use bare <code>except</code></h3>\n<p>See e.g. <a href=\"https://stackoverflow.com/questions/54948548/what-is-wrong-with-using-a-bare-except\">this Q&A</a> for reasons why.</p>\n<h3>Handle exceptions where you can handle them</h3>\n<p>If I understood you correctly, your logic is:</p>\n<ul>\n<li>Read temperature</li>\n<li>If temperature is below threshold, turn heater on</li>\n<li>If temperature is above threshold, turn heater off</li>\n<li>If there was an error reading the temperature, turn heater on</li>\n</ul>\n<p>But that's not what your main loop's logic does because part of the decision is hidden in <code>measure_temp</code>. This may become a problem if your script grows bigger and in a couple of months you decide that 6 °C are actually acceptable, changing</p>\n<pre class=\"lang-py prettyprint-override\"><code>if measure_temp() < 8:\n</code></pre>\n<p>to</p>\n<pre class=\"lang-py prettyprint-override\"><code>if measure_temp() < 6:\n</code></pre>\n<p>...and all of a sudden your heater erroneously turns <em>off</em> once every hour (i.e. every fourth measurement) despite -10°C, only because you forgot to change the return value of <code>measure_temp</code> in case of an error.</p>\n<p>While using an unrealistically small value like <code>-99999</code> would prevent that, there are two conceptual problems with this approach:</p>\n<ul>\n<li>You are using a return value to indicate an error. The proper way to signal an exception to the caller is, well, raising an exception.</li>\n<li>The <code>measure_temp</code> function implicitly decides what action to take in case of an error.</li>\n</ul>\n<p>By the way, <strong>documenting your functions</strong> is a good way to find problems like this. Even if the function is trivial, it can help if you at least imagine what the docstring for <code>measure_temp</code> would look like:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def measure_temp():\n """Returns the temperature of sensor XYZ in °C, or 7 if reading the sensor fails.\n """\n</code></pre>\n<p>That's no function you'd want to work with.</p>\n<p><code>measure_temp</code> should raise an exception if the measurement fails, so you can decide what to do in your main loop instead. If you don't know which exceptions the adafruit library may raise (which unfortunately is very common in python), and if the only information you're interested in is whether the measurement failed, it is acceptable to catch all <code>Exception</code>s. In order to meaningfully indicate a failed measurement to the caller, you can define a custom exception class:</p>\n<pre class=\"lang-py prettyprint-override\"><code>class MeasurementError(Exception):\n pass\n\ndef measure_temp():\n try:\n return adafruit_dht.DHT22(board.D18).temperature\n except Exception as error:\n # raising your custom exception "from" the original one helps when debugging because you can also see where it originated from\n raise MeasurementError("Error reading sensor XYZ") from error\n</code></pre>\n<h3>Now your main loop can be written like this:</h3>\n<pre class=\"lang-py prettyprint-override\"><code>while True:\n try:\n if measure_temp() < 8:\n turn_heater_on()\n else:\n turn_heater_off()\n time.sleep(900)\n except MeasurementError:\n print("Error reading temperature sensor. Retrying measurement.")\n</code></pre>\n<p>In fact, in small scripts like this I usually write the logic (i.e. the snippet above) first using functions that don't yet exist, and implement those functions later.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-23T18:45:21.480",
"Id": "253836",
"ParentId": "253632",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "253678",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-18T19:00:02.010",
"Id": "253632",
"Score": "1",
"Tags": [
"python",
"python-3.x",
"raspberry-pi"
],
"Title": "Error handling on temperature sensor"
}
|
253632
|
<p>I built a solver for <a href="https://www.chiark.greenend.org.uk/%7Esgtatham/puzzles/js/tents.html" rel="nofollow noreferrer">Tents puzzles</a> using the <a href="https://github.com/arminbiere/cadical" rel="nofollow noreferrer">CaDiCaL</a> SAT solver. The code works and runs quickly, it takes less than <code>0.1</code> seconds for a <code>60x60</code> tents puzzle on a 2,6 GHz Dual-Core Intel Core i5 2013 Macbook Pro. Note that the tents website can't handle puzzles greater than <code>25x25</code>, the <code>60x60</code> board was created by a custom script.</p>
<p>My questions are:</p>
<ol>
<li>Is the code any good? I'm not yet very familiar with C++14 and more modern features, so there might be easy ways to simplify the code.</li>
<li>How can I improve the performance? I thought about using <code>int16_t</code> instead of <code>int</code> to get more tent variables into the cache. <code>int16_t</code> should be enough for boards smaller than <code>180x180</code>.</li>
<li>How can I improve the code style? I'm torn between using the 80 character limit or not.</li>
</ol>
<p><code>main.cpp</code></p>
<pre><code>#include <fstream>
#include <iostream>
#include <stdexcept>
#include <string>
#include "tents.hpp"
int main(int argc, char ** argv) {
if (argc < 2) {
std::cout << "Usage: " << argv[0] << " <tents file>\n";
return 0;
}
std::ifstream file(argv[1]);
if (file.fail()) {
std::cout << "Invalid file.\n";
}
std::string line;
std::string board;
while (std::getline(file, line))
board += line + '\n';
file.close();
try {
Tents * tents = new Tents(board);
std::cout << *tents << '\n';
if (tents->solve())
std::cout << *tents << '\n';
else
std::cout << "Could not solve file.\n";
} catch (const std::invalid_argument & e) {
std::cout << e.what() << '\n';
}
}
</code></pre>
<p><code>tents.hpp</code></p>
<pre><code>#include <chrono>
#include <ostream>
#include <vector>
#define ROWMAX 200
#define COLMAX 200
using sysClock = std::chrono::system_clock;
using durSec = std::chrono::duration<double>;
// States each cell of the tents board can be in.
enum class CellState {
EMPTY,
TREE,
TENT
};
// Each variable denotes a possible tent that can be placed. 'row' and 'col'
// denote the position of the tent on the board, 'number' is the variable number
// used in the SAT solver and 'tree' is the number of the adjacent tree.
struct Variable {
int row;
int col;
int number;
int tree;
Variable(int row, int col, int number, int tree) : row(row), col(col),
number(number), tree(tree) {}
};
class Tents {
private:
int rows;
int cols;
// Number of trees.
int trees;
durSec durationBuild;
durSec durationSolve;
// Board of size rows * cols. Maximum is ROWMAX * COLMAX.
std::vector<CellState> board;
std::vector<int> rowRestrictions;
std::vector<int> colRestrictions;
// Variables to build clauses from.
std::vector<Variable> variables;
// Variable assignments.
std::vector<bool> assignments;
// Clauses for the SAT solver.
std::vector<int> clauses;
// Can a tent be placed on the cell denoted by parameters 'row' and 'col'?
bool tentPlacable(int, int) const;
// Find all tents that are orthogonally adjacent to the tree denoted by
// parameters 'row' and 'col'.
void findTents(int, int, std::vector<std::pair<int, int> > &) const;
// Check if variables 'v1' and 'v2' are adjacent in any of the following
// directions: same position, east, south east, south, south west.
bool adjacent(const Variable &, const Variable &) const;
// Using the variables 'vars', it builds the clauses for the tree restrictions:
// every tree must have exactly one adjacent tent.
void buildClausesTree(const std::vector<std::vector<Variable> > &);
// Using the variables 'vars', it builds the adjacent tents restrictions:
// There must be no two adjacent tents.
void buildClausesAdjacent(const std::vector<std::vector<Variable> > &);
// Using the variables 'vars', it builds a 'k'-cardinality constraint by
// building a sequential counter. The sequential counter needs to create new
// variables starting at variable number 'number'. For more information, see
// (1) at the bottom of this file.
void buildSequentialCounter(const std::vector<Variable> &, int, int &);
// Based on the tents board configuration, it builds clauses in CNF format
// for the SAT solver.
void buildClauses();
public:
// The constructor takes a tents board as string 'str'.
Tents(const std::string &);
// Solves the tents puzzle by building clauses and invoking a SAT solver.
bool solve();
// Print the tents board.
friend std::ostream & operator<<(std::ostream & out, const Tents & tents);
};
</code></pre>
<p><code>tents.cpp</code></p>
<pre><code>#include <chrono>
#include <ostream>
#include <sstream>
#include <stdexcept>
#include <string>
#include <utility>
#include <vector>
#include "cadical.hpp"
#include "tents.hpp"
using sysClock = std::chrono::system_clock;
using durSec = std::chrono::duration<double>;
// Can a tent be placed on the cell denoted by parameters 'row' and 'col'?
bool Tents::tentPlacable(int row, int col) const {
if (row < 0 || col < 0 || row >= this->rows || col >= this->cols)
return false;
if (this->rowRestrictions[row] > 0
&& this->colRestrictions[col] > 0
&& this->board[row * this->cols + col] == CellState::EMPTY)
return true;
return false;
}
// Find all tents that are orthogonally adjacent to the tree denoted by
// parameters 'row' and 'col'.
void Tents::findTents(int row, int col, std::vector<std::pair<int, int> > & tents) const {
// Check north.
if (tentPlacable(row - 1, col))
tents.emplace_back(row - 1, col);
// Check east.
if (tentPlacable(row, col + 1))
tents.emplace_back(row, col + 1);
// Check south.
if (tentPlacable(row + 1, col))
tents.emplace_back(row + 1, col);
// Check west.
if (tentPlacable(row, col - 1))
tents.emplace_back(row, col - 1);
}
// Check if variables 'v1' and 'v2' are adjacent in any of the following
// directions: same position, east, south east, south, south west.
bool Tents::adjacent(const Variable & v1, const Variable & v2) const {
// Do both tents belong to the same tree?
if (v1.tree == v2.tree)
return false;
// Two tents on the same cell?
if (v1.row == v2.row && v1.col == v2.col)
return true;
// Check east.
if (v1.row == v2.row && v1.col + 1 == v2.col)
return true;
// Check south east.
if (v1.row + 1 == v2.row && v1.col + 1 == v2.col)
return true;
// Check south.
if (v1.row + 1 == v2.row && v1.col == v2.col)
return true;
// Check south west.
if (v1.row + 1 == v2.row && v1.col - 1 == v2.col)
return true;
return false;
}
// Using the variables 'vars', it builds the clauses for the tree restrictions:
// every tree must have exactly one adjacent tent.
void Tents::buildClausesTree(const std::vector<std::vector<Variable> > & vars) {
for (const auto & tree : vars) {
// Build a clause of the form a v ... v d.
for (const auto & var : tree)
this->clauses.push_back(var.number);
this->clauses.push_back(0);
// Build clauses of the form a v ... v d.
if (tree.size() == 2) {
// One clause of the form -a v -b.
this->clauses.insert(this->clauses.end(), {-tree[0].number, -tree[1].number, 0});
} else if (tree.size() == 3) {
// Three clauses of the form -a v -b.
this->clauses.insert(this->clauses.end(), {-tree[0].number, -tree[1].number, 0});
this->clauses.insert(this->clauses.end(), {-tree[0].number, -tree[2].number, 0});
this->clauses.insert(this->clauses.end(), {-tree[1].number, -tree[2].number, 0});
} else if (tree.size() == 4) {
// Four clauses of the form -a v -b v -c.
this->clauses.insert(this->clauses.end(), {-tree[0].number, -tree[1].number, -tree[2].number, 0});
this->clauses.insert(this->clauses.end(), {-tree[0].number, -tree[1].number, -tree[3].number, 0});
this->clauses.insert(this->clauses.end(), {-tree[0].number, -tree[2].number, -tree[3].number, 0});
this->clauses.insert(this->clauses.end(), {-tree[1].number, -tree[2].number, -tree[3].number, 0});
}
}
}
// Using the variables 'vars', it builds the adjacent tents restrictions:
// There must be no two adjacent tents.
void Tents::buildClausesAdjacent(const std::vector<std::vector<Variable> > & vars) {
std::vector<Variable>::size_type i;
std::vector<Variable>::size_type j;
for (int row = 0; row < this->rows - 1; ++row) {
for (i = 0; i < vars[row].size(); ++i) {
const auto & v1 = vars[row][i];
// Are there any adjacent variables in the same row?
for (j = i + 1; j < vars[row].size(); ++j) {
const auto & v2 = vars[row][j];
if (adjacent(v1, v2))
this->clauses.insert(this->clauses.end(), {-v1.number, -v2.number, 0});
}
// Are there any adjacent variables in the next row?
for (j = 0; j < vars[row + 1].size(); ++j) {
const auto & v2 = vars[row + 1][j];
if (adjacent(v1, v2))
this->clauses.insert(this->clauses.end(), {-v1.number, -v2.number, 0});
}
}
}
}
// Using the variables 'vars', it builds a 'k'-cardinality constraint by
// building a sequential counter. The sequential counter needs to create new
// variables starting at variable number 'number'. For more information, see
// (1) at the bottom of this file.
void Tents::buildSequentialCounter(const std::vector<Variable> & vars, int k, int & number) {
if (k == 0)
return;
const int n = vars.size();
if (n == 1) {
this->clauses.insert(this->clauses.end(), {vars[0].number, 0});
return;
}
// Initialize the partial sums. Every inner vector is a partial sum of k
// bits. Every bit has its own variable number.
std::vector<std::vector<int> > sums(n, std::vector<int>(k, 0));
for (auto & sum : sums) {
for (auto & bit : sum)
bit = number++;
}
this->clauses.insert(this->clauses.end(), {-vars[0].number, sums[0][0], 0});
for (int j = 2; j <= k; ++j)
this->clauses.insert(this->clauses.end(), {-sums[0][j-1], 0});
for (int i = 2; i < n; ++i) {
this->clauses.insert(this->clauses.end(), {-vars[i-1].number, sums[i-1][0], 0,
-sums[i-2][0], sums[i-1][0], 0});
for (int j = 2; j <= k; ++j) {
this->clauses.insert(this->clauses.end(), {-vars[i-1].number, -sums[i-2][j-2],
sums[i-1][j-1], 0, -sums[i-2][j-1], sums[i-1][j-1], 0});
}
this->clauses.insert(this->clauses.end(), {-vars[i-1].number, -sums[i-2][k-1], 0});
}
this->clauses.insert(this->clauses.end(), {-vars[n-1].number, -sums[n-2][k-1], 0});
}
// Based on the tents board configuration, it builds clauses in CNF format
// for the SAT solver.
void Tents::buildClauses() {
// Tents that are orthogonally adjacent to a tree.
std::vector<std::pair<int, int> > tents;
tents.reserve(4);
// Reserve space for the variables. Every row has at most # columns * 2 variables,
// every column at most # rows * 2 and every tree has at most 4.
// ---------------------
// | T | 3 | T | 3 | T |
// | 3 | T | 4 | T | 3 | <- This row has the maximum amount of variables.
// | T | 3 | T | 3 | T |
// ---------------------
// ^ This column has the maximum amount of variables.
std::vector<std::vector<Variable> > rowVars(this->rows, std::vector<Variable>());
for (int row = 0; row < this->rows; ++row)
rowVars[row].reserve(this->cols * 2);
std::vector<std::vector<Variable> > colVars(this->cols, std::vector<Variable>());
for (int col = 0; col < this->cols; ++col)
colVars[col].reserve(this->rows * 2);
std::vector<std::vector<Variable> > treeVars(this->trees, std::vector<Variable>());
for (int tree = 0; tree < this->trees; ++tree)
treeVars[tree].reserve(4);
// The board has at most # trees * 4 variables.
this->variables.reserve(this->trees * 4);
// Which also means at most # trees * 4 assignments.
this->assignments.reserve(this->trees * 4);
// Estimate the number of clauses. 2 ^ 17 clauses should suffice for
// boards smaller than 70x70.
this->clauses.reserve(1 << 17);
// Increasing variable number.
int number = 1;
int tree = 0;
for (int row = 0; row < this->rows; ++row) {
for (int col = 0; col < this->cols; ++col) {
if (this->board[row * this->cols + col] == CellState::TREE) {
// Find all orthogonally adjecent tents.
findTents(row, col, tents);
if (tents.size() == 0)
continue;
// Construct all variables for each tree.
for (const auto & tent : tents) {
this->variables.emplace_back(tent.first, tent.second, number, tree);
rowVars[tent.first].emplace_back(tent.first, tent.second, number, tree);
colVars[tent.second].emplace_back(tent.first, tent.second, number, tree);
treeVars[tree].emplace_back(tent.first, tent.second, number++, tree);
}
tents.clear();
++tree;
}
}
}
// Build the clauses for the SAT solver.
buildClausesTree(treeVars);
buildClausesAdjacent(rowVars);
// Build a sequential counter for each row and column.
for (int row = 0; row < this->rows; ++row)
buildSequentialCounter(rowVars[row], this->rowRestrictions[row], number);
for (int col = 0; col < this->cols; ++col)
buildSequentialCounter(colVars[col], this->colRestrictions[col], number);
}
// The constructor takes a tents board as string 'str'.
Tents::Tents(const std::string &str) : trees(0) {
std::stringstream stream(str);
stream >> std::skipws;
// Read board size.
if (!(stream >> this->rows))
throw std::invalid_argument("Invalid string.");
if (!(stream >> this->cols))
throw std::invalid_argument("Invalid string.");
if (this->rows <= 0 || this->cols <= 0)
throw std::invalid_argument("Invalid board dimensions.");
if (this->rows > ROWMAX || this->cols > COLMAX)
throw std::invalid_argument("Invalid board dimensions.");
// Initialize the board.
this->board.assign(this->rows * this->cols, CellState::EMPTY);
this->rowRestrictions.reserve(this->rows);
this->colRestrictions.reserve(this->cols);
// Read board.
char c;
for (int row = 0; row < this->rows; ++row) {
// Read row.
for (int col = 0; col < this->cols; ++col) {
if (!(stream >> c))
throw std::invalid_argument("Invalid string.");
if (c == 'T') {
this->board[row * this->cols + col] = CellState::TREE;
++this->trees;
}
}
// Read row restriction.
if (!(stream >> this->rowRestrictions[row]))
throw std::invalid_argument("Invalid string.");
}
// Read column restrictions.
for (int col = 0; col < this->cols; ++col) {
if (!(stream >> this->colRestrictions[col]))
throw std::invalid_argument("Invalid string.");
}
}
// Solves the tents puzzle by building clauses and invoking a SAT solver.
bool Tents::solve() {
CaDiCaL::Solver * solver = new CaDiCaL::Solver;
const auto beforeBuild = sysClock::now();
buildClauses();
this->durationBuild = sysClock::now() - beforeBuild;
// Feed clauses to cadical.
for (auto var : this->clauses)
solver->add(var);
const auto beforeSolve = sysClock::now();
const int res = solver->solve();
this->durationSolve = sysClock::now() - beforeSolve;
// Is the board unsatisfiable?
if (res != 10)
return false;
// It is satisfiable. Set assignments and palce tents.
std::vector<Variable>::size_type i;
for (i = 0; i < this->variables.size(); ++i) {
const bool assignment = (solver->val(this->variables[i].number) > 0);
this->assignments[i] = assignment;
if (assignment)
this->board[this->variables[i].row * this->cols + this->variables[i].col] = CellState::TENT;
}
return true;
}
// Print the tents board.
std::ostream & operator<<(std::ostream & out, const Tents & tents) {
// Print board and row restrictions.
for (int row = 0; row < tents.rows; ++row) {
for (int col = 0; col < tents.cols; ++col) {
const CellState state = tents.board[row * tents.cols + col];
if (state == CellState::EMPTY)
out << '.';
else if (state == CellState::TREE)
out << 'T';
else
out << 'A';
}
out << ' ' << tents.rowRestrictions[row] << '\n';
}
// Print column restrictions.
for (int col = 0; col < tents.cols; ++col)
out << tents.colRestrictions[col] << ' ';
out << "\nBuilding the clauses took " << tents.durationBuild.count() << "s.\n";
out << "Solving the clauses took " << tents.durationSolve.count() << "s.\n";
return out;
}
</code></pre>
<p>Tent puzzle of size <code>15x15</code></p>
<pre><code>15 15
.........T.T..T 4
T...TT..TT..... 3
......T.....T.. 3
T..T....T..T... 4
....T........T. 2
..TT........... 3
........T.T...T 3
.T.T..T........ 2
......T.......T 4
..T.T.TT..T...T 1
.......T.T.T... 6
T...T.......T.. 1
T........T.T.T. 6
.T..T.T........ 2
............... 1
4 3 3 1 5 1 5 1 4 2 4 3 3 2 4
</code></pre>
<p>Tent puzzle of size <code>20x20</code></p>
<pre><code>20 20
.T..........T...T..T 4
....TT..T..........T 4
T.T.......TT........ 4
.....T....T..TT..T.T 3
.......T.T......T... 6
.TT.T............... 2
....TT.......T.T.... 2
.T..........T.....T. 8
.T.T.....T.......T.. 1
.....TT.....T..T.T.T 7
T.......TT......T... 1
...............T.... 6
...T.....T..TT..T.T. 2
.TT.T..T............ 7
...........T.....T.. 1
....TT....T........T 7
T....T.....T.TT.T... 1
T.......T.T...T...TT 8
T.TTT.......T....... 2
.......T............ 4
7 3 3 6 3 5 5 3 2 5 2 5 2 5 4 3 6 2 3 6
</code></pre>
<p>Tent puzzle of size <code>25x25</code></p>
<pre><code>25 25
..............T.T.T.TTT.. 7
...T..T..T.........T..... 4
.T..T...T.....T...T...... 4
.....T..T..T...T......T.. 3
.T..T........T........... 7
T..............TT..T.TTT. 3
.......T.....T.......T... 7
..T.....T.TT.....T....... 3
....T.T......TT...T.T..T. 8
.T.......T.T.......T..... 3
..T..TT...T.....T.T.T...T 9
...T........T...T...TT..T 1
..T..................T... 10
.....T.T.T.TT..T...TT..T. 2
......TT...T.T........... 8
TTT...............T....T. 2
.....T.T....T...T...T.... 9
....T.........T...TT..... 2
..T...TT.T...TT.....T.... 8
.T..................T..T. 3
.T.T......T...T..T..T.T.. 8
T.T..T..T...T.......T.... 3
.....T..........TT..T.... 9
.......T.T.T............T 2
.............T...T....... 0
5 5 5 3 6 4 4 4 7 4 4 7 0 12 0 10 2 10 1 9 3 7 2 7 4
</code></pre>
<p>Compile with <code>g++ -std=c++14 -O3 -o tents.out main.cpp tents.cpp -L. -lcadical</code>. You can find the library and the <code>hpp</code> file in the <a href="https://github.com/arminbiere/cadical" rel="nofollow noreferrer">CaDiCaL Github repository</a>.</p>
<p>Run with <code>./tents.out <tents puzzle txt file></code>.</p>
|
[] |
[
{
"body": "<h1>Answers to your questions</h1>\n<blockquote>\n<p>Is the code any good? I'm not yet very familiar with C++14 and more modern features, so there might be easy ways to simplify the code.</p>\n</blockquote>\n<p>From a first glance, it looks very decent. You are already using lots of modern features, and using good C++ programming practices like range-<code>for</code>, <code>enum class</code>es and so on.</p>\n<p>I did notice you use <code>this-></code> a lot, it is almost never necessary to use that, so remove it where possible. It will also shorten your lines.</p>\n<blockquote>\n<p>How can I improve the performance? I thought about using int16_t instead of int to get more tent variables into the cache. int16_t should be enough for boards smaller than 180x180.</p>\n</blockquote>\n<p>Which cache are you talking about? Forget about the L1d cache, it typically is 32 kB on contemporary CPUs, although maybe there are a few with 64 kB, but that still is probably too little to hold a 180x180 array of <code>int16_t</code>s and all the other data necessary to run the algorithm. The L2 cache is typically much larger. Of course, reducing the bandwidth, even to a cache, might still improve performance. On the other hand the CPU might need to do more work unpacking <code>uint16_t</code>s. So you can try to use <code>int16_t</code>, but you have to measure it to know for sure what version will be faster.</p>\n<blockquote>\n<p>How can I improve the code style? I'm torn between using the 80 character limit or not.</p>\n</blockquote>\n<p>Personally, I would do away with any character limit. If a line is so long you have to split it, it is going to be ugly anyway, and I would rather let my editor split the line visually for me depending on the editor's window size than impose a hardcoded limit that only works well for a specific screen size.</p>\n<p>Code style is very much a matter of taste, with the exception that once you pick a certain style, you should apply it consistently. I recommend you pick a code formatter like <a href=\"http://astyle.sourceforge.net/\" rel=\"nofollow noreferrer\">Artistic Style</a> or <a href=\"https://clang.llvm.org/docs/ClangFormat.html\" rel=\"nofollow noreferrer\">ClangFormat</a>, configure it the way you like (I recommend picking one of the built-in standard styles that most closely resembles the one you are already using), and then format your code with the code formatter. Then you don't have to worry too much about the style anymore, and if you want to collaborate with others, they can use the same formatter with the same settings.</p>\n<p>Apart from that, your use of <code>this-></code> has made some lines much longer than necessary, for example:</p>\n<pre><code>this->clauses.insert(this->clauses.end(), {-tree[0].number, -tree[1].number, 0});\n</code></pre>\n<p>Can be shortened by 12 characters to:</p>\n<pre><code>clauses.insert(clauses.end(), {-tree[0].number, -tree[1].number, 0});\n</code></pre>\n<h1>Useless <code>try</code>-<code>catch</code> in <code>main()</code></h1>\n<p>You have the following in <code>main()</code>:</p>\n<pre><code>try {\n ...\n} catch (const std::invalid_argument &e) {\n std::cout << e.what() << '\\n';\n}\n</code></pre>\n<p>This is bad for two reasons: first, if you wouldn't catch the exception, the default behaviour is that <code>e.what()</code> is printed anyway. Second, by catching the error and just letting <code>main()</code> exit normally, the program will now exit with a return code of zero. This is bad if you want to use your tent solving program in a script, as that script can now no longer distinguish between your program having run successfully or unsuccesfuly easily.</p>\n<p>In short, only handle exceptions if you can deal with them in a meaningful way. If you can't, that's fine, just don't catch the exception and let the program terminate with an error.</p>\n<h1>Print error messages to <code>std::cerr</code></h1>\n<p>You should print error messages to <code>std::cerr</code>. This allows them to be distinguished from the regular output of your program. This is especially important if ever want to redirect the output of your program to a file. Consider:</p>\n<pre><code>./tents-solver input_file > output_file\n</code></pre>\n<p>If you print errors to <code>std::cout</code>, no error message will appear on screen, it will just go to <code>output_file. If you print them to </code>std::cerr`, they will appear on screen.</p>\n<h1>Exit with a non-zero exit code on errors</h1>\n<p>If you encountered an error in your program you cannot recover from, make sure you return with a non-zero exit code. So:</p>\n<pre><code>if (argc < 2) {\n std::cerr << "Usage: " << argv[0] << " <tents file>\\n";\n return 1;\n}\n...\nif (file.fail)) {\n std::cerr << "Invalid file.\\n";\n return 1;\n}\n</code></pre>\n<h1>Check for all possible I/O errors</h1>\n<p>You only check whether you could open the input file, but you didn't check whether you could read the file correctly. After reading the board, check that there wasn't some error:</p>\n<pre><code>while (std::getline(file, line))\n board += line + '\\n';\n\nif (file.bad()) {\n std::cerr << "Error reading file.\\n";\n return 1;\n}\n</code></pre>\n<p>Also, there might be a problem writing the output, especially if the output is redirected to a file, or piped into another program. So you should also check for <code>cout.bad()</code> at the end of <code>main()</code>.</p>\n<h1>Use <code>static constexpr</code> where possible for constants</h1>\n<p>Instead of using <code>#define</code>, declare constants as <code>static constexpr</code> variables, like so:</p>\n<pre><code>static constexpr int ROWMAX = 200;\nstatic constexpr int COLMAX = 200;\n</code></pre>\n<p>Also, since these constants are only used internally in <code>tents.cpp</code>, you should move them into <code>tents.cpp</code>.</p>\n<h1>Move other types into <code>class Tents</code></h1>\n<p>You define several types in <code>tents.hpp</code> outside of <code>class Tents</code>, but since they are only relevant to <code>class Tents</code> itself, you should move their definitions inside that of <code>class Tents</code> to avoid polluting the global namespace. Furthermore, since these types are only used internally, you can make them <code>private</code>. For example:</p>\n<pre><code>class Tents {\nprivate:\n using sysClock = std::chrono::system_clock;\n using durSec = std::chrono::duration<double>;\n\n enum class CellState {\n ...\n }:\n\n struct Variable {\n ...\n };\n\n ...\n};\n</code></pre>\n<h1>Prefer using <code>size_t</code> for sizes and counters</h1>\n<p>An <code>int</code> can be negative, and might not be large enough to represent all possible sizes of data structures. Prefer using <code>size_t</code> for variables holding sizes and counters, like <code>rows</code>, <code>cols</code>, and <code>trees</code>.</p>\n<h1>Prefer <code>return</code>ing variables where possible</h1>\n<p>It's perfectly fine in C++ to return "large" objects by value thanks to <a href=\"https://en.cppreference.com/w/cpp/language/copy_elision\" rel=\"nofollow noreferrer\">copy elision</a>. For example, you can make <code>findTents()</code> return the vector of coordinates by value:</p>\n<pre><code>std::vector<std::pair<int, int>> Tents::findTents(int, int) const {\n std::vector<std::pair<int, int>> tents;\n tents.reserve(4);\n ...\n return tents;\n}\n</code></pre>\n<p>And then use it like so:</p>\n<pre><code>for (int row = 0; row < this->rows; ++row) {\n for (int col = 0; col < this->cols; ++col) {\n if (this->board[row * this->cols + col] == CellState::TREE) {\n auto tents = findTents(row, col);\n ...\n // no need for tents.clear()\n }\n }\n}\n</code></pre>\n<p>But even better:</p>\n<h1>Avoid unnecessary temporaries</h1>\n<p>Instead of building a vector of elements, then doing a single loop through them and discarding the vector, consider changing the flow of the code so you don't need the temporary vector. For example, you could change <code>findTents</code> to apply a function to each of the empty spots it finds:</p>\n<pre><code>void Tents::findTents(int, int, std::function<void(int, int)> func) const {\n if (tentPlacable(row - 1, col))\n func(row - 1, col);\n\n if (tentPlacable(row, col + 1))\n func(row, col + 1);\n\n ...\n}\n</code></pre>\n<p>And use it like so:</p>\n<pre><code>for (int row = 0; row < this->rows; ++row) {\n for (int col = 0; col < this->cols; ++col) {\n if (this->board[row * this->cols + col] == CellState::TREE) {\n bool foundSpot = false;\n \n findTents(row, col, [&](int trow, int tcol) {\n foundSpot = true;\n variables.emplace_back(trow, tcol, number, tree);\n rowVars[row].emplace_back(trow, tcol, number, tree);\n colVars[col].emplace_back(trow, tcol, number, tree);\n treeVars[tree].emplace_back(trow, tcol, number++, tree);\n });\n\n trees += foundSpot;\n }\n }\n}\n</code></pre>\n<p>Similarly, you are building a list of clauses in a vector, just to call <code>solver->add()</code> on all of them. This is quite the waste of memory, especially given that you call <code>clauses.reserve(1 << 17)</code>. You could just pass a reference to <code>solver</code> to <code>buildClauses()</code>, and have that one in turn pass it on to the other <code>build*()</code> functions.</p>\n<h1>Have the constructor take a <code>std::istream</code> instead of a <code>std::string</code></h1>\n<p>Instead of having the constructor take a reference to a <code>std::string</code> as input, consider having it take a <code>std::istream</code> reference. Apart from having a better symmetry with how you print the result, this avoids having to create a <code>std::stringstream</code> from the string, and even allows directly passing <code>file</code> from main to the constructor:</p>\n<pre><code>Tents::Tents(std::istream &stream) : trees(0) {\n ...\n}\n\n...\n\nint main(int argc, char **argv) {\n if (argc < 2) {\n ...\n }\n\n Tents tents(std::ifstream(argv[1]));\n\n if (tents.solve()) {\n std::cout << tents << '\\n';\n } else {\n std::cerr << "Could not solve.\\n";\n return 1;\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-20T09:34:58.903",
"Id": "500266",
"Score": "0",
"body": "Thank you, your review was really helpful. I don't know why I didn't pass the solver directly, it seems obvious now. One more question. What does `[&]` in `buildClauses()` do? It seems to allow `func` access to variables of the local scope."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-20T09:47:31.343",
"Id": "500267",
"Score": "1",
"body": "Correct, the things between brackets are the variables the [lambda captures](https://en.cppreference.com/w/cpp/language/lambda#Lambda_capture), and `&` is short for \"everything by reference\"."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-19T12:10:01.980",
"Id": "253656",
"ParentId": "253633",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "253656",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-18T19:00:40.433",
"Id": "253633",
"Score": "3",
"Tags": [
"c++",
"performance",
"c++14"
],
"Title": "Solving Tents puzzles using a SAT solver"
}
|
253633
|
<p>I developed this feature that I think can be improved quite a bit. The result is the desired one, but it took me many lines of code. Any idea to optimize it?</p>
<pre><code>import json
import urllib.request
dni = 71179047
def get_cuit(dni):
request = urllib.request.Request('https://www.cuitonline.com/search.php?q=' + str(dni))
response = urllib.request.urlopen(request)
data_content = response.read()
html = data_content.decode('ISO-8859-1')
cuit = re.findall(r"\(?\b[0-9]{2}\)?-?[0-9]{7,8}-[0-9]{1}\b", html)[0]
result = re.sub('[^0-9]','', cuit)
return result
get_cuit(dni)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-18T19:52:15.577",
"Id": "500181",
"Score": "9",
"body": "It's cliché, but: Do not parse HTML with regexes. Do not parse HTML with regexes. [Do not parse HTML with regexes.](https://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/)"
}
] |
[
{
"body": "<ul>\n<li>Use Requests for HTTP and let it deal with the encoding</li>\n<li>Do not bake the query into the URL string</li>\n<li>Use BeautifulSoup for HTML parsing</li>\n<li>Use typehints</li>\n</ul>\n<p>Nice and simple:</p>\n<pre><code>from requests import get\nfrom bs4 import BeautifulSoup\n\n\ndef get_cuit(dni: int) -> str:\n with get(\n 'https://www.cuitonline.com/search.php',\n params={'q': dni},\n ) as resp:\n resp.raise_for_status()\n doc = BeautifulSoup(resp.text, 'html.parser')\n\n span = doc.find('span', class_='cuit')\n return span.text\n\n\nprint(get_cuit(71_179_047))\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-19T01:52:18.343",
"Id": "500195",
"Score": "0",
"body": "As you said, 'nice and simple'. Thanks! ;)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-20T18:00:37.750",
"Id": "500286",
"Score": "0",
"body": "@Raymont BeautifulSoup really helps too. If you aren't familiar with it, I highly recommend checking it out to see what it can do."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-20T19:58:27.833",
"Id": "500292",
"Score": "0",
"body": "from-importing `get` would be confusing in larger programs, its better to just use the full name"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-20T21:00:56.950",
"Id": "500296",
"Score": "0",
"body": "@Reinderien Why do you use `context manager` when making a `GET` request?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-21T00:02:32.507",
"Id": "500306",
"Score": "0",
"body": "@KonstantinKostanzhoglo It ensures that the response stream is closed. This is more important when manipulating a raw stream directly, but it's better to get in the habit of closing it anyway."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-21T01:08:53.817",
"Id": "500308",
"Score": "1",
"body": "Why do Python devs tend to prefer `from requests import get`/`get(foo)` over `import requests`/`requests.get(foo)`? It just seems very short-sighted to me. Surely, reading `requests.get(foo)` is more informative/self-explanatory than just reading `get(foo)`? In the latter case, I'd have no idea where this `get` came from unless I scrolled all the way up to check all the import statements. Why not just keep namespaces separate? Ease of reading is vastly more important than ease of writing."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-21T04:36:20.697",
"Id": "500312",
"Score": "1",
"body": "@Will This is a 12-line program. The provenance of `get` is somewhat painfully obvious. In a much longer file, it would be worth considering the other `import` style."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-21T08:29:01.207",
"Id": "500327",
"Score": "1",
"body": "Reading your answer just happened to remind me that I don't see the merit of the `from X import Y` import style in any case, generally speaking. That said, I admit that it isn't a big deal per se in your specific example code (even if `get` seems overly generic to me), and that this wasn't the ideal place to express that notion."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-18T22:55:34.703",
"Id": "253645",
"ParentId": "253637",
"Score": "15"
}
},
{
"body": "<p>If you <em>did</em> have to use a regular expression for this task (which you shouldn't in this case - see the other answer), you could improve it by:</p>\n<ul>\n<li><code>[0-9]</code> is equivalent to <code>\\d</code>, a digit character</li>\n<li>A number inside brackets indicates the number of times the previous token should be repeated. In the case of <code>{1}</code>, it's superfluous - you can leave out the brackets entirely and the token will be matched exactly once anyway.</li>\n</ul>\n<pre><code>\\(?\\b\\d{2}\\)?-?\\d{7,8}-\\d\\b\n</code></pre>\n<ul>\n<li>Since you don't want <em>all</em> matches, but just the <em>first</em> match, <code>.search</code> could be a bit more appropriate than using <code>.findall</code> to find all matches followed by extracting the <code>[0]</code>th match.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-19T01:52:25.590",
"Id": "253647",
"ParentId": "253637",
"Score": "4"
}
},
{
"body": "<p>Couple additional points to what @Reinderien mentioned:</p>\n<ul>\n<li>if you would need to execute this function often, consider initializing a <a href=\"https://requests.readthedocs.io/en/master/user/advanced/#session-objects\" rel=\"noreferrer\"><code>requests.Session()</code></a> and re-using it for subsequent requests</li>\n<li>you could improve the speed of HTML parsing here as well:\n<ul>\n<li><p>use <code>lxml</code> instead of <code>html.parser</code> (<code>lxml</code> needs to be installed):</p>\n<pre><code>doc = BeautifulSoup(resp.text, 'lxml')\n</code></pre>\n</li>\n<li><p>since you are looking for a single element, <a href=\"https://www.crummy.com/software/BeautifulSoup/bs4/doc/#parsing-only-part-of-a-document\" rel=\"noreferrer\"><code>SoupStrainer</code></a> would really help out to allow your parser not waste time and resources parsing other parts of HTML:</p>\n<pre><code>from bs4 import BeautifulSoup, SoupStrainer\n\nparse_only = SoupStrainer('span', class_='cuit')\ndoc = BeautifulSoup(resp.text, 'lxml', parse_only=parse_only)\n</code></pre>\n</li>\n</ul>\n</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-19T02:47:08.650",
"Id": "253649",
"ParentId": "253637",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "253645",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-18T19:33:06.963",
"Id": "253637",
"Score": "8",
"Tags": [
"python",
"performance",
"regex",
"web-scraping"
],
"Title": "Function in Python to extract web Data"
}
|
253637
|
<p>I wrote a connect four game for two players, where each player uses the same keyboard. I programmed this solely in hopes of improving my skills.</p>
<p>I'm open to and looking for any sort of feedback. Do the comments contain sufficient detail to understand the code? Are the functions separated into their individual mechanisms/purposes properly? Is it, overall, a decently written algorithm?</p>
<p>I'm especially skeptical of the check_winner function. I feel like it could be optimized, just not sure how.</p>
<pre><code>import math
def board_setup():
"""Setup game board dimension size; returns game board as list"""
board_size = -1
while board_size < 4 or board_size > 9:
try:
board_size = int(input("Enter board size dimension (minimum=4, maximum=9): "))
except ValueError:
print("Error: Enter an integer")
return [" "]*board_size**2
def player_setup():
"""Setup two players and their corresponding symbol/piece to represent them on the game board; returns list of player symbols/pieces"""
players = ["too many"]*2
for i in range(2):
while len(players[i]) > 1:
players[i] = input("Player " + str(i+1) + ": Enter your symbol/piece (1 character in length): ")
if players[0] == players[1] or players[i].isspace() or players[i] == "":
print("Error: Duplicate or unsupported player symbol provided")
players[i] = "too many"
return players
def line_break(lines):
"""Prints specified number of blank lines
lines: number of lines"""
print("\n"*lines)
def print_board_pieces(board):
"""Prints board's vertical and horizontal barrier and player symbols/pieces set in board
board: board array"""
board_width = int(math.sqrt(len(board)))
barrier_symbol = "▋"
#print player pieces or blank space and vertical barriers
for s in range(0, len(board), board_width):
print(barrier_symbol, *board[s:s+board_width], barrier_symbol, sep="|")
if s < len(board)-board_width:
print(barrier_symbol, "+", "-+"*board_width, barrier_symbol, sep="")
#horizontal floor of board
print(barrier_symbol, barrier_symbol*board_width*2, barrier_symbol*2, sep="")
def print_board(board, numbered):
"""Print game board to screen
board: board array
numbered: number top of columns?; bool"""
line_break(3) #padding
#number rows
if numbered:
print(" ", end="")
for i in range(int(math.sqrt(len(board)))):
print(" ", str(i+1), sep="", end="")
print(" ")
else:
print()
#barrier and player pieces
print_board_pieces(board)
line_break(3) #padding
def player_move(board, player):
"""Prompt and apply player input to board; returns index of player's movement in the board array as int
board: board array to modify
player: player symbol/piece to apply"""
board_width = int(math.sqrt(len(board)))
board_size = len(board)
print("It is " + player + "'s turn!")
move = -1
succeeded = False
while not succeeded:
while move < 0 or move >= board_width:
try:
move = int(input("Where would you like to drop your symbol/piece (enter the integer representing the column)?: "))-1
except ValueError:
print("Error: Enter an integer")
move = board_size - (board_width - move) #move symbol/piece to bottommost row of board
#move player piece up vertically on board until spot is free
while 0 <= move < board_size and board[move] != " ":
move -= board_width
#if piece is in free and valid spot on board, end root loop
if 0 <= move < board_size:
succeeded = True
else:
print("Error: No space left in column")
board[move] = player #apply player piece/symbol to board
return move
def switch_player_turn(player):
"""Switches current player turn; returns other player index in array as int
player: player index in players list as int"""
return 0 if player == 1 else 1
def check_winner(board, player, index):
"""Check if player has won vertically, diagonally, horizontally, if it's a tie, or if the game should continue
board: board array
player: player symbol/piece as string
index: newly placecd player piece's/symbol's index in board array to check from"""
board_width = board_height = int(math.sqrt(len(board)))
board_size = len(board)
#horizontal check
row_start = board_width * math.floor(moved/board_width)
if board[row_start:row_start+board_width].count(player) >= 4:
connected = 1
l, r = moved-1, moved+1
while connected < 4 and r < row_start+board_width and board[r] == player:
connected += 1
r += 1
while connected < 4 and l >= row_start and board[l] == player:
connected += 1
l -= 1
if connected == 4:
return player
#vertical check
column_start = moved
while column_start >= board_height:
column_start -= board_height
if board[column_start:board_size:board_height].count(player) >= 4:
connected = 1
l, r = moved-board_height, moved+board_height
while connected < 4 and r < board_size and board[r] == player:
connected += 1
r += board_height
while connected < 4 and l >= 0 and board[l] == player:
connected += 1
l -= board_height
if connected == 4:
return player
#diagonal check
_dir = -1
while _dir <= 1:
diag_start = diag_end = moved
while diag_start % board_height != 0 if _dir == 1 else (diag_start+1) % board_height != 0 and diag_start >= board_width:
diag_start -= board_height+_dir #move diag_start as far top as possible until wall collision
while diag_end % board_height != 0 if _dir == -1 else (diag_end+1) % board_height != 0 and diag_end < (board_size-board_width):
diag_end += board_height+_dir #move diag_end as far bottom as possible until wall collision
if board[diag_start:diag_end+1:board_height+_dir].count(player) >= 4:
connected = 1
l, r = moved-(board_height+_dir), moved+(board_height+_dir)
while connected < 4 and r <= diag_end and board[r] == player:
connected += 1
r += board_height+_dir
while connected < 4 and l >= diag_start and board[l] == player:
connected += 1
l -= board_height+_dir
if connected == 4:
return player
_dir += 2
#draw/tie check
if " " not in board:
return "No one"
else:
return None #no winner or draw yet
#board setup
board_arr = board_setup()
#player setup
players = player_setup()
current_player = 0
#main loop
winner = None
while winner == None:
print_board(board_arr, numbered=True)
moved = player_move(board_arr, players[current_player])
winner = check_winner(board_arr, players[current_player], moved)
if winner:
break
else:
current_player = switch_player_turn(current_player)
#winner
print("\n"*100)
print_board(board_arr, numbered=False)
if winner in players:
print(winner, "won!")
else:
print("The board is full, it's a draw!")
</code></pre>
|
[] |
[
{
"body": "<p>The code is not hard to follow, I'd just recommend overall to use a matrix since it will ease all operations to check who has won</p>\n<p>I added a suggestion for checking vertical/horizontal winning condition with your current plain list implementation</p>\n<pre><code>for i in range(board_width):\n # horizontal check\n row = board[i*board_width:i*board_width+board_width]\n if player*4 in ''.join(row):\n return player\n\n # vertical check\n column = [board[j*board_width+i] for j in range(board_width)]\n print(column)\n if player*4 in ''.join(column):\n return player\n</code></pre>\n<p>That's the biggest function that I will aim to reduce, diagonals are a bit trickier, but they get easier if you use a matrix.</p>\n<p>I'd also check the function to move player, since it will get out of hand easily</p>\n<p>Happy coding!</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-19T12:04:54.660",
"Id": "253655",
"ParentId": "253639",
"Score": "1"
}
},
{
"body": "<p>Overall not bad at all,</p>\n<ol>\n<li>You are correct with respect to the correct_winner function. Robert Martin, in his book "<a href=\"https://www.goodreads.com/quotes/7630396-the-first-rule-of-functions-is-that-they-should-be\" rel=\"nofollow noreferrer\">Clean Code</a>" expresses in humerous terms just how small a function should be (hint, really small). When I see code that is broken up by comments (eg. #horiztontal check, it immediately suggests to me that it should be its own function. I believe this is true in your case.</li>\n</ol>\n<ol start=\"2\">\n<li><p>Use Python type hints, it will make the world a better place.</p>\n</li>\n<li><p>Some of your function names are not meaningful enough. "print_board_pieces" is a good name because it gives me an idea of what you are doing, "player_move" not so much. Are you handling player move? Printing player move? It is unclear to me by the name.</p>\n</li>\n<li><p>Make one mental thought per line. When you write "while connected < 4 and r < row_start+board_width and board[r] == player", that is two thoughts per line, the while statement and the logic. But I have no idea what the logic is. The following is much more readable.</p>\n<p>is_connected = while connected < 4 and r < row_start+board_width and board[r] == player<br />\nwhile is_connected:<br />\n....do something</p>\n</li>\n</ol>\n<p>It is worth piking up Martin's book on clean code. It is an easy read and will be of great benefit to you -- it completely changed (for the better I hope) the way I write code some 15 or so years ago. Another good book is CodeCommit.</p>\n<p>Cheers,</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-20T03:55:16.403",
"Id": "253688",
"ParentId": "253639",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "253655",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-18T20:41:09.847",
"Id": "253639",
"Score": "0",
"Tags": [
"python",
"python-3.x",
"connect-four"
],
"Title": "Connect Four Shared Keyboard Game"
}
|
253639
|
<p>Please review my strstr implementation in terms of time/space efficiency and overall readability. I am preparing for a coding assessment coming up as I am looking to pivot my career from Physics to Computer Science. This is an exercise from the <a href="https://app.codesignal.com/interview-practice/topics/strings" rel="nofollow noreferrer">interview practice questions on CodeSignal</a>. My implementation successfully passes all 14 tests but I get the following error when I submit my answer:</p>
<blockquote>
<p>Tests passed: 21/27. Execution time limit exceeded on test 22: Program
exceeded the execution time limit. Make sure that it completes
execution in a few seconds for any possible input.</p>
</blockquote>
<pre><code>"""strstr().
Given two strings, text and pattern, return an integer indicating the index
in the text of the first occurrence of the pattern.
"""
def strstr(text, pattern):
"""Needle in haystack O(|text|) time? and O(?) space.
Return an integer indicating the first occurrence of pattern in the text,
or -1 if the pattern is not part of the text.
"""
lookup = set([pattern])
len_text = len(text)
len_pattern = len(pattern)
for index in range(len_text-len_pattern+1):
if text[index:index+len_pattern] in lookup:
return index
return -1
def tests():
"""Sample Tests."""
samples = [("CodesignalIsAwesome", "IA", -1),
("CodesignalIsAwesome", "IsA", 10),
("a", "a", 0),
("a", "A", -1),
("sst", "st", 1),
("lrnkbldxguzgcseccinlizyogwqzlifxcthdgmanjztlt", "an", 38)]
for text, pattern, answer in samples:
if strstr(text, pattern) != answer:
print(f"text: {text}, pattern: {pattern}, aswer: {answer}")
if __name__ == "__main__":
tests()
</code></pre>
<p><strong>Edit:</strong> <em>Avoid using built-in functions to solve this challenge. Implement them yourself, since this is what you would be asked to do during a real interview.</em></p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-19T06:25:51.440",
"Id": "500197",
"Score": "1",
"body": "Can't you use `text.find(pattern)`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-20T00:01:19.610",
"Id": "500253",
"Score": "0",
"body": "@Marc I am not familiar with that method but the goal is to come up with our own efficient implementation: `Avoid using built-in functions to solve this challenge. Implement them yourself, since this is what you would be asked to do during a real interview.`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-20T03:41:56.763",
"Id": "500257",
"Score": "0",
"body": "Got it, FYI [str.find](https://docs.python.org/3/library/stdtypes.html#str.find)."
}
] |
[
{
"body": "<p>As someone trying to pivot from physics to Computer Science, I think this solution is good, many CS graduates might not come up with a better solution first up.</p>\n<p>Let's get some optimizations unrelated to cyclomatic complexity out of the way.</p>\n<p>You added the <code>pattern</code> to a <code>set</code>. The lookup is constant <code>O(1)</code>, I don't see a need to do that and you can save on a high constant.</p>\n<p>Let's take a closer look at</p>\n<pre class=\"lang-py prettyprint-override\"><code> for index in range(len_text-len_pattern+1):\n if text[index:index+len_pattern] in lookup:\n</code></pre>\n<p>specifically <code>text[index:index+len_pattern]</code>, this creates a <strong>copy</strong> of the string for the range <code>index:len_pattern</code>. This is an implementation detail of Python, one can just as easily imagine an optimization that does not create a copy.</p>\n<p><a href=\"https://stackoverflow.com/questions/13710329/substrings-in-python-copies-in-memory\">This question and its response might help explain this better.</a></p>\n<p>You might be able to optimize away the object creation, again this unrelated to cyclomatic complexity.</p>\n<p><em>premature optimization is evil</em> - the intent above is more of a code review. Addressing you question below.</p>\n<hr />\n<p>The runtime complexity of the loop is the equivalent of creating a copy of the <code>pattern</code> times the len of <code>text</code></p>\n<p>if <code>m</code> is <code>len(text)</code> and <code>n</code> is <code>len(pattern)</code> the for loop is <code>O(n*m)</code> in every iteration.</p>\n<p>Typically in questions like these, there is an insight that is not always obvious that drives the solution resulting in a lower cyclomatic complexity. In this instance it is that the algorithm can be implemented in a single pass <code>O(n)</code> by keeping track of indexes across both the <code>text</code> and the <code>pattern</code></p>\n<pre class=\"lang-py prettyprint-override\"><code>def strstr(text, pattern):\n \n t = 0\n len_text = len(text)\n len_pattern = len(pattern)\n i = 0\n for i in range(len_text + 1):\n if (t == len_pattern or i == len_text):\n break\n if (text[i] == pattern[t]):\n t += 1\n elif (text[i] == pattern[0]):\n t = 1\n else:\n t = 0\n\n if (t < len_pattern):\n return -1\n else:\n return i - t\n \ndef tests():\n """Sample Tests."""\n samples = [("CodesignalIsAwesome", "IA", -1),\n ("CodesignalIsAwesome", "IsA", 10),\n ("a", "a", 0),\n ("a", "A", -1),\n ("sst", "st", 1),\n ("lrnkbldxguzgcseccinlizyogwqzlifxcthdgmanjztlt", "an", 38),\n ("abcd" * 300000 + "abcde", "abcde", 1200000),]\n for text, pattern, answer in samples:\n actual = strstr(text, pattern)\n if actual != answer:\n print(f"FAILED : pattern: {pattern}, actual: {actual}, expected: {answer}")\n else:\n print(f"SUCCESS: pattern: {pattern}, actual: {actual} matched expected")\n</code></pre>\n<p>I added an additional text case to demonstrate the runtime, testing this with <code>time</code> module in python, the clock time of the implementation is a few milli seconds compared to the clock time of the <code>O(n*m)</code> algorithm which on my machine is aboue 21 seconds.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-19T20:34:32.513",
"Id": "500232",
"Score": "0",
"body": "Yours fails for example `strstr('aaab', 'aab')`, returns `-1`. Also, are you saying that yours has lower cyclomatic complexity? And \"O(n*m) in every iteration\" is misleading."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-19T21:18:48.403",
"Id": "500240",
"Score": "0",
"body": "I think expanding on a solution that linearly keeps track of substring match should be feasible, I'll be open to you expanding on the solution"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-19T20:13:20.287",
"Id": "253676",
"ParentId": "253640",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-18T20:51:43.337",
"Id": "253640",
"Score": "3",
"Tags": [
"performance",
"strings",
"interview-questions",
"complexity",
"pattern-matching"
],
"Title": "strstr implementation with python and sets"
}
|
253640
|
<p><strong>Background</strong></p>
<p>In one of our repositories we have a folder called <code>player_test</code> where we store all <code>player_test</code> related <code>.py</code> files. We realized that there are certain static <code>csv</code> files we use to do some processing. So we decided to create a folder called <code>player_test_input</code> inside the player_test folder. The <code>player_test_input</code> should store all the <code>csv</code> files.</p>
<p><strong>CODE</strong></p>
<pre><code>def get_player_call_logic_df() -> pd.DataFrame:
df = pd.read_csv(
"../dev/player-assignment/src/player_test/player_test_input/player_call_logic.csv"
)
return df
</code></pre>
<p><strong>Issue</strong></p>
<p>In the above function <code>get_player_call_logic_df</code> I read the <code>csv</code> using relative path.</p>
<p>However I am not sure if there is a more pythonic way to do this?</p>
<p>We use pathlib quite a bit in our codebase and avoid using relative path but was not sure how that would apply in this case. I am always trying to figure out how i can use the modern python features and best practices more.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-18T23:17:42.187",
"Id": "500192",
"Score": "0",
"body": "Do you have any more information about the directory other than its position relative to the current one? For instance, is it assumed to be in the home directory, or some other well-known path?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-19T01:30:01.723",
"Id": "500194",
"Score": "0",
"body": "Yes it is assumed to be in a well known path. The way we use our code base is we use aws where we launch ec2 instances and our source code is in a known directory"
}
] |
[
{
"body": "<p>It seems to me that: 1) the path should be a function argument 2) but the function as it stands is very short and does only one thing - you actually don't need a function for this because there is nothing particular that can be reused.</p>\n<p>Since the file is going to reside in a specific path, use a constant, it can be defined inside a config file. Quite likely, you may have other options or hardcoded stuff, so it's good to use a config file to keep it all in the same place.</p>\n<p>eg:\nconfig.py</p>\n<pre><code>PLAYER_FILES_DIR = "/dev/player-assignment/src/player_test/player_test_input/"\n</code></pre>\n<p>And then in your code you import the config file and you can refer to the location path as config.PLAYER_FILES_DIR:</p>\n<pre><code>import config\n\ndf = pd.read_csv(config.PLAYER_FILES_DIR...)\n# do something\n</code></pre>\n<p>pathlib can still possibly be used if you intend to read multiple files from the directory.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-19T17:11:08.747",
"Id": "500217",
"Score": "0",
"body": "The problem is i can not use absolute path because while the absoloute path will work for times when this code is run on a ec2 instance but when folks run it locally it won't work so i would have to use a relative path. So would it be fine if i stored relative path as a constant?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-19T12:18:53.477",
"Id": "253657",
"ParentId": "253643",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "253657",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-18T22:14:21.790",
"Id": "253643",
"Score": "1",
"Tags": [
"python",
"python-3.x"
],
"Title": "Pythonic way to read csv files from a folder in repository"
}
|
253643
|
<p>I'm trying to develop an OOP way of thinking. I was hoping someone would be kind enough to spare some of their valuable time to review my Grade Calculator OOP program. As always, I'd like to know what I've done well, what I should improve upon, and any suggestions on how I could perhaps improve what I have? By the way, I have a class called Class. I probably should prefix it with "cls" so as not to confuse. Treat this program as is supposed to be entered, I haven't error checked it. The point of this program is to develop in OOP.</p>
<pre><code> // Task 1.cpp : This file contains the 'main' function. Program execution begins and ends there.
#include <iostream>
#include <vector>
#include <algorithm>
#include <functional>
#include <numeric>
#include <string>
class TestPaper
{
public:
int m_scoreOutOf;
bool checkBoundary(int value, int boundary) {
if (value < 0 || value > boundary) {
std::cout << "Score must be between " << " 0 and " << boundary << ". Please try again.\n";
return false;
}
return true;
}
};
class Student {
private:
std::string m_name;
int m_scoreGot;
public:
Student(std::string name, int scoreGot)
:m_name(name), m_scoreGot(scoreGot){}
std::string getName() const { return m_name; }
int getScoreGot() const { return m_scoreGot; }
};
class Class {
private:
std::vector<Student>students;
public:
void AddStudent(TestPaper& testPaper) {
std::string name = "";
int scoreGot = 0;
std::cout << "Enter student name: ";
std::getline(std::cin >> std::ws, name);
do
{
std::cout << "\nWhat did " << name << " score?\nEnter a score between 0 and "
<< testPaper.m_scoreOutOf << ": ";
std::cin >> scoreGot;
} while (testPaper.checkBoundary(scoreGot, testPaper.m_scoreOutOf) == false);
students.push_back({ name, scoreGot });
}
std::vector<Student>& accessStudents() { return students; }
};
class GradeCalculator {
TestPaper m_testPaper;
Class m_ClassOfStudents;
public:
GradeCalculator(TestPaper testPaper, Class classOfStudents) :m_testPaper(testPaper), m_ClassOfStudents(classOfStudents) {}
void DisplayMenu() {
std::cout << "\n1. Add student and their grade\n";
std::cout << "2. Calculate class score\n";
std::cout << "3. Modify testpaper (haven't implemented this yet)\n";
}
double averageGrade() {
auto sum = std::transform_reduce(m_ClassOfStudents.accessStudents().begin(), m_ClassOfStudents.accessStudents().end(), 0.0, std::plus<>(),
[&](auto& student) { return calculateGradePercentage(student); });
return sum / m_ClassOfStudents.accessStudents().size();
}
double calculateGradePercentage(Student &student)
{
return static_cast<double>(student.getScoreGot()) / static_cast<double>(m_testPaper.m_scoreOutOf) * 100;
}
void DisplayResult() {
for (auto& student : m_ClassOfStudents.accessStudents()) {
std::cout << "Percentage scores are: \n";
std::cout << student.getName() << ": " << calculateGradePercentage(student) << "%\n";
}
std::cout << "Average grade perecentage: " << averageGrade() << "%\n";
}
void runProgram() {
int menuChoice = 0;
while (true)
{
DisplayMenu();
std::cout << "\nEnter a choice from the menu: ";
std::cin >> menuChoice;
switch (menuChoice)
{
case 1:
m_ClassOfStudents.AddStudent(m_testPaper);
break;
case 2:
DisplayResult();
break;
default:
std::cout << "Invalid choice!\n";
}
}
}
};
int main()
{
TestPaper testPaper({ 20 });
Class classOfStudents;
GradeCalculator calculator(testPaper, classOfStudents);
calculator.runProgram();
}
</code></pre>
|
[] |
[
{
"body": "<p>Here are some things to help you improve your program.</p>\n<h2>Don't mix I/O with data operations</h2>\n<p>Generally speaking having a <code>std::getline</code> and <code>std::cout</code> within a data class such as <code>Class</code> is not a good idea. It makes it harder to reuse the class. Better practice is to keep the data (<code>Student</code>, <code>Class</code>, etc.) separate from getting input from users. The <a href=\"http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller\" rel=\"noreferrer\">Model-View-Controller</a> design pattern is often useful for programs like this. Consider using something like a <code>ConsoleMenu</code> class as in <a href=\"https://codereview.stackexchange.com/a/176644/39848\">this answer</a>.</p>\n<h2>Use move semantics where practical</h2>\n<p>In the <code>AddStudent</code> function, we have this line:</p>\n<pre><code>students.push_back({ name, scoreGot });\n</code></pre>\n<p>Better would be to use <a href=\"https://en.cppreference.com/w/cpp/container/vector/emplace_back\" rel=\"noreferrer\"><code>emplace_back</code></a> which tells the compiler that it doesn't need to construct and copy, but that it's safe to construct the object in place.</p>\n<h2>Rethink the class interface</h2>\n<p>The <code>Class</code> class has this member function:</p>\n<pre><code>std::vector<Student>& accessStudents() { return students; }\n</code></pre>\n<p>This is a bad idea. It returns a reference to an internal class member. Think what happens if the <code>Class</code> instance is deleted but some external entity is still holding a reference to data that no longer exists. The only place it's used is within <code>GradeCalculator::averageGrade()</code> and <code>GradeCalculator::DislayResult()</code> so that's a strong indicator that something is not right in the class interface. I'd suggest making the <code>averageGrade()</code> function a <code>Class</code> member function.</p>\n<h2>Use defaults when sensible</h2>\n<p>The <code>Student</code> constructor is essentially the same as that which would have been generated by the compiler. To reduce the chance of error, it can be simply eliminated.</p>\n<h2>Think about the user</h2>\n<p>There is no obvious way to gracefully exit the program. I'd suggest adding a menu item for that. Also, chances are that anyone actually using the program would want to enter the entire class of students and then calculate the scores for the whole class. Having to repeatedly select "1. Add student..." is a bit tedious. Better might be to have the program gather input until an empty name or maybe "quit" was entered, and then automatically show the scores. Better still would be to allow input from a text file.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-19T07:46:07.420",
"Id": "500199",
"Score": "0",
"body": "Thank you for your instructive feedback! I am going to reflect on everything you have said. I may have questions later on!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-19T02:35:49.590",
"Id": "253648",
"ParentId": "253644",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "253648",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-18T22:52:02.753",
"Id": "253644",
"Score": "3",
"Tags": [
"c++",
"c++11"
],
"Title": "Grade Calculator (New OOP Version from one previous)"
}
|
253644
|
<p>I've come up with some simple implementation for algorithms in <code>C</code> and more specifically for <code>std::accumulate</code> alternate since I need something like it recently. Can you provide some review on the approach?</p>
<pre><code>#include <stdio.h>
#include <string.h>
#define ARRSIZE(X) (sizeof(X) / sizeof(X[0]))
#define ACCUMULATE(RET, FIRST, LAST, INIT, SUM_CB) \
do { \
RET = INIT; \
while (FIRST != LAST){ \
RET = SUM_CB(RET, *FIRST); \
FIRST++; \
} \
} while(0);
/**
* example usage
* sum integers and sum strings by some delimiter
*/
struct str_t
{
char data[512];
};
struct str_t sumStr(struct str_t a, struct str_t b)
{
struct str_t ret = {0};
strcat(ret.data, a.data);
strcat(ret.data, "--");
strcat(ret.data, b.data);
return ret;
}
struct A { int a, b, c; };
struct A sumA(struct A a, struct A b) {
struct A ret ;
ret.a = a.a + b.a;
ret.b = a.b + b.b;
ret.c = a.c + b.c;
return ret;
}
int main()
{
unsigned long i;
struct A sumvec[10];
struct str_t sumstr[10];
memset(sumstr, 0, sizeof(sumstr));
for(i=0; i < ARRSIZE(sumvec); i++) {
sumvec[i].a = i;
sumvec[i].b = i+1;
sumvec[i].c = i+2;
snprintf(sumstr[i].data, sizeof(sumstr[i].data), "%d", i);
}
for(i=0; i < ARRSIZE(sumvec); i++) {
printf("[%d][%d][%d]\r\n", sumvec[i].a ,sumvec[i].b,sumvec[i].c);
}
struct A ret = {sumvec[0].a, sumvec[0].b, sumvec[0].c};
struct A* pBegin = &sumvec[1];
struct A* pEnd = &sumvec[ARRSIZE(sumvec)];
ACCUMULATE(ret, pBegin, pEnd, ret, sumA)
printf("SUM: [%d][%d][%d]\r\n", ret.a, ret.b, ret.c);
struct str_t retstr;
strcat(retstr.data, sumstr[0].data);
struct str_t *pBegs = &sumstr[1];
struct str_t *pEnds = &sumstr[ARRSIZE(sumstr)];
ACCUMULATE(retstr, pBegs, pEnds, retstr, sumStr);
printf("SUM STR: [%s]\r\n", retstr.data);
return 0;
}
</code></pre>
|
[] |
[
{
"body": "<p>When using the <code>do { ... } while (0)</code> idiom for macros, we don't generally include the terminating semicolon in the definition. That's so we can use it like a function call:</p>\n<pre><code>if (condition)\n ACCUMULATE(result, a, b, 0, add);\nelse\n ACCUMULATE(result, a, c, 10, add);\n</code></pre>\n<p>There's a typo in the <code>ARRSIZE()</code> macro: where we protect X from misbinding - should be <code>(X)[0]</code>, not <code>(X[0])</code>:</p>\n<pre><code>#define ARRSIZE(X) (sizeof (X) / sizeof (X)[0])\n</code></pre>\n<p>Also, be careful with this macro when its argument isn't a whole, completely defined array. In particular, it will be wrong when the argument is a variable-length (dynamically-allocated) array, or when the argument is a pointer (perhaps the array decayed to pointer - that can easily catch you out!).</p>\n<p>In the sample usage:</p>\n<ul>\n<li>Identifiers ending in <code>_t</code> are reserved for future use by the standard library, so <code>str_t</code> should be renamed.</li>\n<li>It's a shame, after being so careful to use <code>snprintf()</code> avoid overflow, that we we then use unchecked <code>strcat();strcat();strcat();</code> in <code>sumStr()</code> - why not <code>snprintf()</code> there, too?</li>\n<li>A lot of needless parens around the arguments to <code>sizeof</code>. Just write <code>sizeof sumstr</code> instead of <code>sizeof(sumstr)</code>, for example.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-19T21:26:48.840",
"Id": "500241",
"Score": "1",
"body": "You may also want to mention that the `ARRSIZE` macro often [confuses people](https://stackoverflow.com/questions/1975128/why-isnt-the-size-of-an-array-parameter-the-same-as-within-main) when it decays to a pointer and that it doesn't work with dynamically sized arrays."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-21T15:53:04.097",
"Id": "500349",
"Score": "0",
"body": "Thanks @Edward - edited."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-19T20:34:35.823",
"Id": "253677",
"ParentId": "253653",
"Score": "3"
}
},
{
"body": "<p>In addition to <a href=\"https://codereview.stackexchange.com/a/253677/29485\">@Toby Speight</a> fine answer.</p>\n<blockquote>\n<p>Can you provide some review on the approach?</p>\n</blockquote>\n<p>I found the macro <code>ACCUMULATE()</code>, at best, slightly useful. I did not see it adding clarity. Perhaps it would be a useful benefit in a larger code usage.</p>\n<p>A particular issue with <code>ACCUMULATE(a, b,c, d, e)</code> is the 9 usages of the 5 arguments - potentially incurring re-use problems.</p>\n<p>At a minimum <code>ACCUMULATE()</code>, deserve some comments detailing its usage, simpler sample usage and limitations. Do not assume C users are familiar with <code>std::accumulate</code> from another language.</p>\n<hr />\n<p>I realize this is demonstrative code. Yet ...</p>\n<p><strong>Bug</strong></p>\n<p>Attempting to concatenate to an uninitialized string. Use <code>strcpy()</code>.</p>\n<pre><code>struct str_t retstr;\n// strcat(retstr.data, sumstr[0].data);\nstrcpy(retstr.data, sumstr[0].data);\n</code></pre>\n<p><strong>Walk a string once, not 3 times</strong></p>\n<p>As <code>strlen(ret.data)</code> increases, <code>strcat(ret.data, ...</code> becomes increasingly expensive.</p>\n<pre><code>//strcat(ret.data, a.data);\n//strcat(ret.data, "--");\n//strcat(ret.data, b.data);\nsprintf(ret.data, "%s--%s", a.data, b.data);\n</code></pre>\n<p>Robust would consider using <code>snprintf()</code>.</p>\n<p><strong>Simplify initialization</strong></p>\n<pre><code>// struct str_t sumstr[10];\n// memset(sumstr, 0, sizeof(sumstr));\nstruct str_t sumstr[10] = { 0 };\n\n// struct A ret = {sumvec[0].a, sumvec[0].b, sumvec[0].c};\nstruct A ret = sumvec[0];\n</code></pre>\n<p><strong><code>\\r\\n</code> vs. <code>\\n</code>"</strong></p>\n<p><code>stdout</code> is normally in text mode and will translates <code>'\\n'</code> into the end-of-line- encoding best for that system. Recommend <code>'\\n'</code>.</p>\n<pre><code>// printf("[%d][%d][%d]\\r\\n", sumvec[i].a ,sumvec[i].b,sumvec[i].c);\nprintf("[%d][%d][%d]\\n", sumvec[i].a ,sumvec[i].b,sumvec[i].c);\n</code></pre>\n<p><strong>Minor: Unclear mixed use of types <code>unsigned long</code> and <code>int</code></strong></p>\n<pre><code>struct A { int a, b, c; };\n\n unsigned long i;\n sumvec[i].a = i;\n sumvec[i].b = i+1;\n sumvec[i].c = i+2;\n</code></pre>\n<p>Why is <code>i</code> <code>unsigned long</code> and not <code>int</code> to match the s<code>struct</code> members or <code>size_t</code> to match the range for indexing?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-20T10:11:45.763",
"Id": "500268",
"Score": "0",
"body": "Thanks. Good point but I didn’t focus on example usage just a demo of the macro, but will fix it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-21T15:55:15.097",
"Id": "500350",
"Score": "0",
"body": "Agh! I had the `\\r` in my mind, then forgot it again whilst writing my answer! It always helps to have more than one of us reviewing..."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-20T00:49:19.883",
"Id": "253683",
"ParentId": "253653",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-19T09:43:03.407",
"Id": "253653",
"Score": "3",
"Tags": [
"c",
"macros"
],
"Title": "std::accumulate alternative for the C programming language"
}
|
253653
|
<p>A legacy project was upgraded from legacy code that used either SystemV FIFO device (or similar queue on Windows platform) which was deeply ingrained into every thread's implementation. Following implementation of locking queue with a wait was meant to emulate original FIFO use:</p>
<pre><code>#include <queue>
// target platform doesn't have std::mutex or support >C++14
#include <QWaitCondition>
#include <QMutex>
template < typename _Msg, typename _Alloc = std::allocator<_Msg> >
class WaitQue
{
public:
typedef _Alloc Allocator;
typedef _Msg DataType;
// a thread calls this to place a copy of msg
void post(const DataType& msg)
{
QMutexLocker lock_(&mx);
que.push(msg);
cv.wakeOne();
}
// a thread calls this to to wait for a message
void wait(DataType& msg)
{
/// wait if que empty
QMutexLocker cvlock_(&mx);
while(que.empty()) // spurious exit from wait()
cv.wait(&mx);
msg = que.front();
que.pop();
}
unsigned long size()
{
QMutexLocker lock_(&mx);
return que.size();
}
private:
typedef std::deque<DataType, Allocator> Container;
std::queue<DataType, Container> que;
QWaitCondition cv;
QMutex mx;
};
</code></pre>
<p>A simplest use of such queue without any fluff:</p>
<pre><code>#include <QCoreApplication>
#include <QtConcurrent>
#include <QFuture>
struct Message {
int value;
};
using Queue = WaitQue<Message>;
Queue east; // messages for east-side events
Queue west; // messages for west-side events
void westSide()
{
Message msg = {};
for(int i = 5; i-->0; )
{
qDebug() << "West side is working." << endl;
east.post(Message{i}); //
west.wait(msg); //
}
}
void eastSide()
{
Message msg = {};
do
{
east.wait(msg);
qDebug() << "East side received " << msg.value << endl;
west.post(msg);
}while(msg.value);
}
int main(int argc, char *argv[])
{
QCoreApplication a(argc,argv);
QFuture<void> future1 = QtConcurrent::run(westSide);
QFuture<void> future2 = QtConcurrent::run(eastSide);
future1.waitForFinished();
future2.waitForFinished();
return 0;
}
</code></pre>
<p>In reality most of workers are infinite state-machine loops operating only after receiving messages or generating such messages for other workers while some are actually doing ping-pong exchange as above.</p>
<p>Target platform got partial C++11 support and Qt < 5.4 support. <code>std::queue</code> was used instead of Qt container for sake of custom allocator support and condition variable <code>QWaitCondition</code> is used to lock queue. Custom allocator allows to avoid heap allocation. Is this correct implementation and if its not, what flaws are there? Is there a Qt analog for this maybe?</p>
<p>PS. Indefinite wait was a known problem that was solved by design of any scenario was ending with posting "stop thread" messages to all queues in past implementation of project.</p>
|
[] |
[
{
"body": "<blockquote>\n<pre><code>template < typename _Msg, typename _Alloc = std::allocator<_Msg> >\n</code></pre>\n</blockquote>\n<p>Those names are dangerous - underscore followed by capital is reserved to the implementation <em>for any purpose</em>. That means they could be macros, which would give you some tricky parse errors to diagnose! Stick to names you're allowed to use (in this case, I'd just drop the underscores).</p>\n<h2><code>post()</code></h2>\n<blockquote>\n<pre><code>{\n QMutexLocker lock_(&mx);\n que.push(msg);\n cv.wakeOne();\n}\n</code></pre>\n</blockquote>\n<p>There's an inefficiency here, because waking another thread while we still hold the mutex will cause that thread to immediately block. Better to release the mutex before waking:</p>\n<pre><code>{\n {\n QMutexLocker lock_(&mx);\n que.push(msg);\n }\n cv.wakeOne();\n}\n</code></pre>\n<p>A design choice here: should a queue be allowed to expand until it throws <code>std::bad_alloc</code>? Or do we want a maximum capacity at which the write end blocks?</p>\n<p>If you have enough C++11 support, prefer to accept the argument by value, then <code>std::move()</code> it to the container. That avoids copying rvalue arguments.</p>\n<h2><code>wait()</code></h2>\n<blockquote>\n<pre><code>void wait(DataType& msg)\n</code></pre>\n</blockquote>\n<p>That's a clunky interface. Prefer to just return the <code>DataType</code>.</p>\n<p>I'm not a fan of the truncated "Que" name, and seem to stutter on it every time I read it. What's wrong with the full word?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-18T07:36:00.613",
"Id": "505632",
"Score": "0",
"body": "Are you sure about `post()`? all examples of use show opposite (usually with direct `lock()` for Qt examples). It is possible that two threads would wake one thread once while posting two items in queue because one would slip in-between `.unlock()` and `.wakeOne()`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-18T08:04:41.963",
"Id": "505633",
"Score": "1",
"body": "That's the advice I've seen for the Standard Library condition variables; it's hard to see why it wouldn't also be good advice for the Qt types too. I can't quite see a path where `wait()` could find the queue empty and miss being woken (if we enter the mutex on the reader side between unlock and wake, then the queue is not empty, because releasing the mutex on the writer side is a barrier). OTOH, it is possible that two readers arrive, one takes the item and the other gets woken with an empty queue, but that's already handled well."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-18T08:40:51.513",
"Id": "505637",
"Score": "0",
"body": "I was afraid f getting problem with that part - `std::queue::empty()` isn't said to be thread-safe or atomic."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-18T11:45:29.797",
"Id": "505650",
"Score": "0",
"body": "We hold the mutex when calling `empty()` so I'm satisfied about that. I wonder if the differing advice to wake whilst holding the lock comes from Java programmers. I vaguely remember that's a thing to do with Java CVs."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-17T17:25:07.380",
"Id": "256153",
"ParentId": "253658",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "256153",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-19T13:28:31.667",
"Id": "253658",
"Score": "2",
"Tags": [
"c++",
"queue"
],
"Title": "A thread-safe blocking FIFO queue"
}
|
253658
|
<p>I have implemented a message queue for inter thread communication just like POSIX message queue. I want to know whether there is any scope for performance improvement and also any bugs which need to be corrected. This is my code:</p>
<pre><code>#include <iostream>
#include <cstring>
#include <list>
#include <vector>
#include <thread>
#include <mutex>
#include <condition_variable>
std::mutex mu;
std::condition_variable cv;
std::list<std::vector<char>> msg_queue;
void recv() {
char buff[2048];
while(true) {
std::unique_lock<std::mutex> ul { mu };
while(msg_queue.empty())
cv.wait(ul);
std::vector<char>& queue_msg = msg_queue.front();
if(queue_msg.size() < sizeof(buff)) {
std::memcpy(buff, queue_msg.data(), queue_msg.size());
buff[queue_msg.size()] = '\0';
}
msg_queue.pop_front();
ul.unlock();
std::cout << buff << std::endl;
}
}
int32_t main() {
const char *data = "Hello world!";
std::thread th(recv);
while(true) {
mu.lock();
msg_queue.emplace_back(std::vector<char>(data, data + strlen(data)));
cv.notify_one();
mu.unlock();
std::this_thread::sleep_for(std::chrono::seconds(1));
}
th.join();
return EXIT_SUCCESS;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-19T17:23:09.437",
"Id": "500218",
"Score": "2",
"body": "Welcome to Code Review! It would help reviewers if you could provide an example of how this code is intended to be used."
}
] |
[
{
"body": "<p>Since you’re primarily interested in efficiency, that’s what I’m going to focus on in my review.</p>\n<p>However, first I do need to point out that <code>int32_t main()</code> is not legal C++. I’m mildly surprised it even compiles. There are only two legal forms of <code>main()</code>:</p>\n<ul>\n<li><code>int main()</code>; and</li>\n<li><code>int main(int, char*[])</code>.</li>\n</ul>\n<p>I should also mention that a message queue is probably better done as a class, with the mutex and other implementation details as private data members, rather than as global variables, and details like notifying the condition variable handled automatically. But that isn’t a performance issue, just a design one.</p>\n<pre><code>std::list<std::vector<char>> msg_queue;\n</code></pre>\n<p>Using a <code>std::list</code> for the actual queue is an odd choice. It’s not <em>wrong</em>; it’ll work perfectly fine. And <code>std::list</code> is not the most performant container, but its inefficiencies will be absolutely <em>dwarfed</em> by all the thread context switching and locking/unlocking.</p>\n<p>Normally for a message queue like this you’d use a <code>std::vector</code>, or maybe a <code>std::deque</code>. Or sometimes you’d actually use a <code>std::array</code> (or a <code>std::vector</code> with a fixed size), and either treat it like a ring buffer—so if there are too many unhandled messages, older messages get lost—or block any new messages until some older messages are handled.</p>\n<p>As I said, <code>std::list</code> isn’t <em>wrong</em>. It’ll work. I just don’t see any <em>benefits</em> to using it, because at least in the example code, you don’t really benefit from iterator stability (which is the primary reason to prefer a <code>std::list</code>), and you’ll pay a lot more for allocations and cache misses.</p>\n<pre><code>char buff[2048];\n</code></pre>\n<p>Is there a reason you use a fixed-size buffer? I don’t see any performance gains from it, and you’ll just lose any messages longer than 2k.</p>\n<p>I’ll offer alternative suggestions later.</p>\n<pre><code>while(true) {\n</code></pre>\n<p><del>You have a bug in your program in that the loops are infinite. Infinite loops are UB.</del> (Correction: Infinite loops are UB if and only if they have no observable side effects. These loops have side effects (like printing to standard out, and locking mutexes). However, there is no portable way to end the program, and—more importantly (because it’s the subject of the review)—the message queue. If you tried to put this message queue as-is in an existing program, like the example one, it will never end; it will deadlock while waiting for the thread to join, while the thread loops and waits on the condition variable.)</p>\n<p>What you really need is a way for the <code>recv()</code> function to realize the program’s ending. For example, you could use a message "done" as a signal to wind things up:</p>\n<pre><code>// in recv()\nwhile (true)\n{\n // ... [snip] ...\n\n if (buf == "done")\n break;\n}\n\n// in main()\nfor (auto n = 0; n < 10000; ++n) // instead of while (true)\n{\n // ... [snip] ...\n}\n\n// artificial scope\n{\n auto lock = std::scoped_lock(mu);\n msg_queue.emplace_back({'d', 'o', 'n', 'e'});\n}\n\ncv.notify_one();\n\nth.join();\n</code></pre>\n<p>It doesn’t need to be a special message to signal the end, but if you use something else, like a flag, then you might need to be sure you finish handling all the messages before ending the <code>recv()</code> loop, and you need to consider what happens if the flag is set while the queue is empty (and the condition variable is waiting on it to <em>not</em> be empty).</p>\n<pre><code>while(msg_queue.empty())\n cv.wait(ul);\n</code></pre>\n<p>Rather than a manual loop like this, it’s cleaner and less likely to cause problems if you use the other form of <code>wait()</code> that takes a lambda:</p>\n<pre><code>cv.wait(ul, [] { return not msg_queue.empty(); });\n</code></pre>\n<p>This removes the temptation for some later code monkey to fool with the loop in some way. Raw loops are a code smell, because you should generally prefer algorithms. They’re fine in the use cases here, but you never know what some future coder might think to do. Also, this reads much clearer, even to someone who doesn’t understand condition variables (who might ask, “why a loop <em>and</em> a call to a wait function?”).</p>\n<pre><code>std::vector<char>& queue_msg = msg_queue.front();\nif(queue_msg.size() < sizeof(buff)) {\n std::memcpy(buff, queue_msg.data(), queue_msg.size());\n buff[queue_msg.size()] = '\\0';\n}\n\nmsg_queue.pop_front();\n</code></pre>\n<p>Okay, here’s where the biggest inefficiencies lie. I don’t see a reason—at least in this code—why you copy the message from the message queue into a buffer, then delete the message from the queue. Why not just <em>take</em> the message right from the queue and use it?</p>\n<p>In other words, why not do this:</p>\n<pre><code>void recv()\n{\n while (true)\n {\n std::unique_lock<std::mutex> ul { mu };\n cv.wait(ul, [] { return not msg_queue.empty(); });\n\n // *TAKE* the message from the queue. This will be *LIGHTNING* quick;\n // possibly *thousands* of times faster than copying the message into a\n // buffer.\n auto queue_msg = std::move(msg_queue.front());\n\n // Remove it from the list.\n msg_queue.pop_front();\n\n // No need to hold the lock anymore.\n ul.unlock();\n\n // Now you have the message as queue_msg, and you can do whatever you want\n // with it. For example, print it:\n std::cout.write(queue_msg.data(), queue_msg.size());\n std::cout << '\\n';\n }\n}\n</code></pre>\n<p>But that’s just the tip of the performance iceberg. It’s very wasteful to do all that locking and so on for <em>ONE</em> message at a time. What if there are several messages in the queue? Why not handle them all at once?</p>\n<p>For example:</p>\n<pre><code>void recv()\n{\n while (true)\n {\n std::unique_lock<std::mutex> ul { mu };\n cv.wait(ul, [] { return not msg_queue.empty(); });\n\n // Take the ENTIRE QUEUE. Even if there are multiple messages, this could\n // still be thousands of times faster than copying a SINGLE message into a\n // buffer, and that's not even taking into account the gains you get from\n // avoiding multiple locking and unlocking and waiting cycles.\n auto messages = std::vector<std::vector<char>>{};\n messages.resize(msg_queue.size()); // make space for the messages\n std::move(msg_queue.begin(), msg_queue.end(), messages.begin()); // move them all out of the queue\n msg_queue.clear(); // clear the queue of the (now empty, moved-from) messages\n\n // No need for the lock anymore.\n ul.unlock();\n\n // Now we can handle all the messages at our leisure.\n std::for_each(messages.begin(), messages.end(),\n [](auto&& message)\n {\n std::cout.write(message.data(), message.size());\n std::cout << '\\n';\n });\n }\n}\n</code></pre>\n<p>As an optimization, you could also move <code>messages</code> out of the loop, and call <code>messages.clear()</code> at the end of the loop. The advantage of this is that it will mean that <code>messages.resize()</code> will almost never need to allocate because you can reuse the memory. That means that that entire block of code in the middle of the function above will amount to a few measly pointer copies… which will be <em>FAST</em>… far faster than copying entire strings, even with <code>std::memcpy()</code>. And that in turn means much less time spent with the mutex locked, which means you should be able to get a <em>MUCH</em> higher throughput for your messages.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-19T20:20:32.210",
"Id": "500229",
"Score": "2",
"body": "\"*only two legal forms of `main()`*\" is not quite true. Compilers are permitted to accept other signatures for the main function - a common extension is `int main(int argc, char **argv, char **envp)` for example. What is true is that the code presented is needlessly *non-portable*."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-19T21:12:53.490",
"Id": "500239",
"Score": "3",
"body": "An infinite loop is not UB. An infinite loop _without a side effect_ is."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-20T11:06:01.920",
"Id": "500270",
"Score": "0",
"body": "-1 because of the incorrect statements about `main()` and infinite loops, will +1 once that's fixed :) I would keep the bit about `std::list` short, just say that `std::vector` or `std::deque` might be fast because it avoids a lot of allocations and keeps things together in memory. As for copying the contents of the queue so you can process multiple messages in one go: why not just [`messages.swap(msg_queue)`](https://en.cppreference.com/w/cpp/container/vector/swap)?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-21T21:05:22.300",
"Id": "500394",
"Score": "0",
"body": "1) Extensions are not standard, and it would be misleading, if not incorrect, to call extensions “legal C++” just because the standard acknowledges the possibility of their existence. You can call it “legal C++-with-GCC-extensions” or “legal MSVC/Windows-flavour-C++” if you like, I suppose, but I wouldn’t do that kind of waffling when teaching, because it just sows confusion. 2) Yes, that’s true; my mistake. There are side effects here, so these infinite loops are not UB. Though, there’s still no way to portably end the program—that `th.join()` will (probably) never get executed."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-21T21:05:37.957",
"Id": "500396",
"Score": "1",
"body": "3) Thing is, because there are no comments, I’m not sure there *isn’t* a valid reason to use `std::list`. I’ve made concurrent message queues using (singly) linked lists before (so they can be lock-free). Maybe `std::list` is perfect for whatever the ultimate intended application here is. I don’t like to presume cluelessness wantonly, so I try to explain the *usual* reasons why `std::list` isn’t right, so the reader can at least balance them with whatever reasons for using it they have in their head."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-21T21:07:29.880",
"Id": "500397",
"Score": "0",
"body": "4) Because they’re different types (`list` and `vector`). But even if they weren’t I might still do it that way, because if you swap the message queue with a new, empty one, then you’ll lose all the memory the queue already has. In other words, if you swap/move the queue itself, the next message will always trigger a new allocation; if you just swap/move the messages then clear, the queue still has its memory, and should only need to do a new allocation if the queue fills up with more messages than it had. (If you do the optimization, then this won’t really matter, and swapping would work.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-22T00:13:25.237",
"Id": "500423",
"Score": "0",
"body": "Thanks for the edit. But still: the implementation defined form of `main()` *is* legal C++. The version @TobySpeight mentioned is also not a compiler extension, it is a platform-specific version. Don't confuse \"implementation defined\" with \"illegal\"."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-22T00:21:42.407",
"Id": "500424",
"Score": "1",
"body": "As for 4), good point about the allocated memory. If both the queue itself and the temporary are a `vector`, then you could do something like `std::vector<...> messages; messages.reserve(msg_queue.capacity); messages.swap(msg_queue)`. If you also declare `messages` outside the loop, you need to call `msg_queue.clear()` somewhere in the loop, but you avoid unnecessary memory (re)allocations. If a `std::list` is used for both the queue and temporary, you can also [`swap()`](https://en.cppreference.com/w/cpp/container/list/swap)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-22T22:59:47.513",
"Id": "500485",
"Score": "0",
"body": "Don’t confuse implementation-defined *behaviour* with implementation-defined *extensions*. The former is legal C++ (valid everywhere) whose behaviour differs with the implementation. The latter is “anything goes”, and is not legal C++ almost by definition. The only reason the standard mentions non-standard forms of `main()` at all is because it has to: it clarifies that if you don’t use a standard form, you’re not allowed to use just anything as the entry point (like a label); it is constrained to *some* flavour of `main()`. The `**env` flavour is just a popular extension; it’s not even POSIX."
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-19T18:41:25.977",
"Id": "253672",
"ParentId": "253664",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "253672",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-19T15:15:30.430",
"Id": "253664",
"Score": "2",
"Tags": [
"c++"
],
"Title": "implementation of Message queue"
}
|
253664
|
<p>This is a follow-up question for <a href="https://codereview.stackexchange.com/q/253556/231235">A recursive_transform Template Function Implementation with <code>std::invocable</code> concept in C++</a> and <a href="https://codereview.stackexchange.com/q/251823/231235">A recursive_transform Template Function with Execution Policy</a>. Based on the previous questions, I am trying to consider <a href="https://en.cppreference.com/w/cpp/algorithm/execution_policy_tag_t" rel="nofollow noreferrer">execution policy parameter</a> for <code>recursive_transform</code> function here.</p>
<p><strong>The experimental implementation</strong></p>
<pre><code>// recursive_transform implementation (with execution policy)
template<class ExPo, class T, class F>
requires (std::is_execution_policy_v<std::remove_cvref_t<ExPo>>)
constexpr auto recursive_transform(ExPo execution_policy, const T& input, const F& f)
{
return f(input);
}
// specific case for std::array
template<class ExPo, class T, std::size_t S, class F>
requires (std::is_execution_policy_v<std::remove_cvref_t<ExPo>>)
constexpr auto recursive_transform(ExPo execution_policy, const std::array<T, S>& input, const F& f)
{
using TransformedValueType = decltype(recursive_transform(execution_policy, *input.cbegin(), f));
std::array<TransformedValueType, S> output;
std::transform(input.cbegin(), input.cend(), output.begin(),
[execution_policy, &f](auto&& element)
{
return recursive_transform(execution_policy, element, f);
}
);
return output;
}
template<class ExPo, template<class...> class Container, class Function, class... Ts>
requires (std::is_execution_policy_v<std::remove_cvref_t<ExPo>>) && (is_inserterable<Container<Ts...>> && !std::invocable<Function, Container<Ts...>>)
constexpr auto recursive_transform(ExPo execution_policy, const Container<Ts...>& input, const Function& f)
{
using TransformedValueType = decltype(recursive_transform(execution_policy, *input.cbegin(), f));
Container<TransformedValueType> output(input.size());
std::mutex mutex;
std::for_each(execution_policy, input.cbegin(), input.cend(),
[&](auto&& element)
{
auto result = recursive_transform(execution_policy, element, f);
std::lock_guard lock(mutex);
output.emplace_back(std::move(result));
}
);
return output;
}
#ifdef USE_BOOST_MULTIDIMENSIONAL_ARRAY
template<class ExPo, is_multi_array T, class F>
requires (std::is_execution_policy_v<std::remove_cvref_t<ExPo>>) && (!std::invocable<F, T>)
constexpr auto recursive_transform(ExPo execution_policy, const T& input, const F& f)
{
boost::multi_array output(input);
for (decltype(+input.shape()[0]) i = 0; i < input.shape()[0]; i++)
{
output[i] = recursive_transform(execution_policy, input[i], f);
}
return output;
}
#endif
</code></pre>
<p><strong>Test cases</strong></p>
<pre><code>// std::vector<int> -> std::vector<std::string>
std::vector<int> test_vector = {
1, 2, 3
};
std::cout << "string: " + recursive_transform(std::execution::par, test_vector, [](int x)->std::string { return std::to_string(x); }).at(0) << std::endl;
// std::vector<std::vector<int>> -> std::vector<std::vector<std::string>>
std::vector<decltype(test_vector)> test_vector2 = {
test_vector, test_vector, test_vector
};
std::cout << "string: " + recursive_transform(std::execution::par, test_vector2, [](int x)->std::string { return std::to_string(x); }).at(0).at(0) << std::endl;
//std::vector<std::vector<int>> -> std::vector<std::size_t>
std::cout << "recursive_count_if: " + recursive_transform(std::execution::par, test_vector2, [](std::vector<int> x) {
return std::to_string(recursive_count_if(x, [](int number) { return number == 3; }));
}).at(0) << std::endl;
</code></pre>
<p>The full testing code:</p>
<pre><code>#include <algorithm>
#include <array>
#include <cassert>
#include <chrono>
#include <complex>
#include <concepts>
#include <deque>
#include <exception>
#include <execution>
#include <functional>
#include <iostream>
#include <iterator>
#include <list>
#include <map>
#include <numeric>
#include <optional>
#include <ranges>
#include <stdexcept>
#include <string>
#include <type_traits>
#include <utility>
#include <variant>
#include <vector>
template<typename T>
concept is_inserterable = requires(T x)
{
std::inserter(x, std::ranges::end(x));
};
#ifdef USE_BOOST_MULTIDIMENSIONAL_ARRAY
template<typename T>
concept is_multi_array = requires(T x)
{
x.num_dimensions();
x.shape();
boost::multi_array(x);
};
#endif
// recursive_count implementation
template<std::ranges::input_range Range, typename T>
constexpr auto recursive_count(const Range& input, const T& target)
{
return std::count(input.cbegin(), input.cend(), target);
}
// transform_reduce version
template<std::ranges::input_range Range, typename T>
requires std::ranges::input_range<std::ranges::range_value_t<Range>>
constexpr auto recursive_count(const Range& input, const T& target)
{
return std::transform_reduce(std::cbegin(input), std::cend(input), std::size_t{}, std::plus<std::size_t>(), [target](auto&& element) {
return recursive_count(element, target);
});
}
// recursive_count implementation (with execution policy)
template<class ExPo, std::ranges::input_range Range, typename T>
requires (std::is_execution_policy_v<std::remove_cvref_t<ExPo>>)
constexpr auto recursive_count(ExPo execution_policy, const Range& input, const T& target)
{
return std::count(execution_policy, input.cbegin(), input.cend(), target);
}
template<class ExPo, std::ranges::input_range Range, typename T>
requires (std::is_execution_policy_v<std::remove_cvref_t<ExPo>>) && (std::ranges::input_range<std::ranges::range_value_t<Range>>)
constexpr auto recursive_count(ExPo execution_policy, const Range& input, const T& target)
{
return std::transform_reduce(execution_policy, std::cbegin(input), std::cend(input), std::size_t{}, std::plus<std::size_t>(), [execution_policy, target](auto&& element) {
return recursive_count(execution_policy, element, target);
});
}
// recursive_count_if implementation
template<class T, std::invocable<T> Pred>
constexpr std::size_t recursive_count_if(const T& input, const Pred& predicate)
{
return predicate(input) ? 1 : 0;
}
template<std::ranges::input_range Range, class Pred>
requires (!std::invocable<Pred, Range>)
constexpr auto recursive_count_if(const Range& input, const Pred& predicate)
{
return std::transform_reduce(std::cbegin(input), std::cend(input), std::size_t{}, std::plus<std::size_t>(), [predicate](auto&& element) {
return recursive_count_if(element, predicate);
});
}
// recursive_count_if implementation (with execution policy)
template<class ExPo, class T, std::invocable<T> Pred>
requires (std::is_execution_policy_v<std::remove_cvref_t<ExPo>>)
constexpr std::size_t recursive_count_if(ExPo execution_policy, const T& input, const Pred& predicate)
{
return predicate(input) ? 1 : 0;
}
template<class ExPo, std::ranges::input_range Range, class Pred>
requires ((std::is_execution_policy_v<std::remove_cvref_t<ExPo>>) && (!std::invocable<Pred, Range>))
constexpr auto recursive_count_if(ExPo execution_policy, const Range& input, const Pred& predicate)
{
return std::transform_reduce(execution_policy, std::cbegin(input), std::cend(input), std::size_t{}, std::plus<std::size_t>(), [predicate](auto&& element) {
return recursive_count_if(element, predicate);
});
}
// recursive_transform implementation
template<class T, std::invocable<T> F>
constexpr auto recursive_transform(const T& input, const F& f)
{
return f(input);
}
// specific case for std::array
template<class T, std::size_t S, class F>
constexpr auto recursive_transform(const std::array<T, S>& input, const F& f)
{
using TransformedValueType = decltype(recursive_transform(*input.cbegin(), f));
std::array<TransformedValueType, S> output;
std::transform(input.cbegin(), input.cend(), output.begin(),
[&f](auto&& element)
{
return recursive_transform(element, f);
}
);
return output;
}
template<template<class...> class Container, class Function, class... Ts>
requires (is_inserterable<Container<Ts...>> && !std::invocable<Function, Container<Ts...>>)
constexpr auto recursive_transform(const Container<Ts...>& input, const Function& f)
{
using TransformedValueType = decltype(recursive_transform(*input.cbegin(), f));
Container<TransformedValueType> output;
std::transform(input.cbegin(), input.cend(), std::inserter(output, std::ranges::end(output)),
[&](auto&& element)
{
return recursive_transform(element, f);
}
);
return output;
}
#ifdef USE_BOOST_MULTIDIMENSIONAL_ARRAY
template<is_multi_array T, class F>
requires(!std::invocable<F, T>)
constexpr auto recursive_transform(const T& input, const F& f)
{
boost::multi_array output(input);
for (decltype(+input.shape()[0]) i = 0; i < input.shape()[0]; i++)
{
output[i] = recursive_transform(input[i], f);
}
return output;
}
#endif
// recursive_transform implementation (with execution policy)
template<class ExPo, class T, class F>
requires (std::is_execution_policy_v<std::remove_cvref_t<ExPo>>)
constexpr auto recursive_transform(ExPo execution_policy, const T& input, const F& f)
{
return f(input);
}
// specific case for std::array
template<class ExPo, class T, std::size_t S, class F>
requires (std::is_execution_policy_v<std::remove_cvref_t<ExPo>>)
constexpr auto recursive_transform(ExPo execution_policy, const std::array<T, S>& input, const F& f)
{
using TransformedValueType = decltype(recursive_transform(execution_policy, *input.cbegin(), f));
std::array<TransformedValueType, S> output;
std::transform(input.cbegin(), input.cend(), output.begin(),
[execution_policy, &f](auto&& element)
{
return recursive_transform(execution_policy, element, f);
}
);
return output;
}
template<class ExPo, template<class...> class Container, class Function, class... Ts>
requires (std::is_execution_policy_v<std::remove_cvref_t<ExPo>>) && (is_inserterable<Container<Ts...>> && !std::invocable<Function, Container<Ts...>>)
constexpr auto recursive_transform(ExPo execution_policy, const Container<Ts...>& input, const Function& f)
{
using TransformedValueType = decltype(recursive_transform(execution_policy, *input.cbegin(), f));
Container<TransformedValueType> output(input.size());
std::mutex mutex;
std::for_each(execution_policy, input.cbegin(), input.cend(),
[&](auto&& element)
{
auto result = recursive_transform(execution_policy, element, f);
std::lock_guard lock(mutex);
output.emplace_back(std::move(result));
}
);
return output;
}
#ifdef USE_BOOST_MULTIDIMENSIONAL_ARRAY
template<class ExPo, is_multi_array T, class F>
requires (std::is_execution_policy_v<std::remove_cvref_t<ExPo>>) && (!std::invocable<F, T>)
constexpr auto recursive_transform(ExPo execution_policy, const T& input, const F& f)
{
boost::multi_array output(input);
for (decltype(+input.shape()[0]) i = 0; i < input.shape()[0]; i++)
{
output[i] = recursive_transform(execution_policy, input[i], f);
}
return output;
}
#endif
template<std::size_t dim, class T>
constexpr auto n_dim_vector_generator(T input, std::size_t times)
{
if constexpr (dim == 0)
{
return input;
}
else
{
auto element = n_dim_vector_generator<dim - 1>(input, times);
std::vector<decltype(element)> output(times, element);
return output;
}
}
template<std::size_t dim, std::size_t times, class T>
constexpr auto n_dim_array_generator(T input)
{
if constexpr (dim == 0)
{
return input;
}
else
{
auto element = n_dim_array_generator<dim - 1, times>(input);
std::array<decltype(element), times> output;
std::fill(std::begin(output), std::end(output), element);
return output;
}
}
template<std::size_t dim, class T>
constexpr auto n_dim_deque_generator(T input, std::size_t times)
{
if constexpr (dim == 0)
{
return input;
}
else
{
auto element = n_dim_deque_generator<dim - 1>(input, times);
std::deque<decltype(element)> output(times, element);
return output;
}
}
template<std::size_t dim, class T>
constexpr auto n_dim_list_generator(T input, std::size_t times)
{
if constexpr (dim == 0)
{
return input;
}
else
{
auto element = n_dim_list_generator<dim - 1>(input, times);
std::list<decltype(element)> output(times, element);
return output;
}
}
template<std::size_t dim, template<class...> class Container = std::vector, class T>
constexpr auto n_dim_container_generator(T input, std::size_t times)
{
if constexpr (dim == 0)
{
return input;
}
else
{
return Container(times, n_dim_container_generator<dim - 1, Container, T>(input, times));
}
}
int main()
{
// std::vector<int> -> std::vector<std::string>
std::vector<int> test_vector = {
1, 2, 3
};
std::cout << "string: " + recursive_transform(std::execution::par, test_vector, [](int x)->std::string { return std::to_string(x); }).at(0) << std::endl;
// std::vector<std::vector<int>> -> std::vector<std::vector<std::string>>
std::vector<decltype(test_vector)> test_vector2 = {
test_vector, test_vector, test_vector
};
std::cout << "string: " + recursive_transform(std::execution::par, test_vector2, [](int x)->std::string { return std::to_string(x); }).at(0).at(0) << std::endl;
//std::vector<std::vector<int>> -> std::vector<std::size_t>
std::cout << "recursive_count_if: " + recursive_transform(std::execution::par, test_vector2, [](std::vector<int> x) {
return std::to_string(recursive_count_if(x, [](int number) { return number == 3; }));
}).at(0) << std::endl;
// std::deque<int> -> std::deque<std::string>
std::deque<int> test_deque;
test_deque.push_back(1);
test_deque.push_back(1);
test_deque.push_back(1);
auto recursive_transform_result3 = recursive_transform(
std::execution::par,
test_deque,
[](int x)->std::string { return std::to_string(x); }); // For testing
std::cout << "string: " + recursive_transform_result3.at(0) << std::endl;
// std::deque<std::deque<int>> -> std::deque<std::deque<std::string>>
std::deque<decltype(test_deque)> test_deque2;
test_deque2.push_back(test_deque);
test_deque2.push_back(test_deque);
test_deque2.push_back(test_deque);
auto recursive_transform_result4 = recursive_transform(
std::execution::par,
test_deque2,
[](int x)->std::string { return std::to_string(x); }); // For testing
std::cout << "string: " + recursive_transform_result4.at(0).at(0) << std::endl;
// std::array<int, 10> -> std::array<std::string, 10>
std::array<int, 10> test_array;
for (int i = 0; i < 10; i++)
{
test_array[i] = 1;
}
auto recursive_transform_result5 = recursive_transform(
std::execution::par,
test_array,
[](int x)->std::string { return std::to_string(x); }); // For testing
std::cout << "string: " + recursive_transform_result5.at(0) << std::endl;
// std::array<std::array<int, 10>, 10> -> std::array<std::array<std::string, 10>, 10>
std::array<std::array<int, 10>, 10> test_array2;
for (int i = 0; i < 10; i++)
{
test_array2[i] = test_array;
}
auto recursive_transform_result6 = recursive_transform(
std::execution::par,
test_array2,
[](int x)->std::string { return std::to_string(x); }); // For testing
std::cout << "string: " + recursive_transform_result6.at(0).at(0) << std::endl;
// std::list<int> -> std::list<std::string>
std::list<int> test_list = { 1, 2, 3, 4 };
auto recursive_transform_result7 = recursive_transform(
std::execution::par,
test_list,
[](int x)->std::string { return std::to_string(x); }); // For testing
std::cout << "string: " + recursive_transform_result7.front() << std::endl;
// std::list<std::list<int>> -> std::list<std::list<std::string>>
std::list<std::list<int>> test_list2 = { test_list, test_list, test_list, test_list };
auto recursive_transform_result8 = recursive_transform(
std::execution::par,
test_list2,
[](int x)->std::string { return std::to_string(x); }); // For testing
std::cout << "string: " + recursive_transform_result8.front().front() << std::endl;
return 0;
}
</code></pre>
<p><a href="https://godbolt.org/z/9h5M53" rel="nofollow noreferrer">A Godbolt link is here.</a></p>
<p>All suggestions are welcome.</p>
<p>The summary information:</p>
<ul>
<li><p>Which question it is a follow-up to?</p>
<p><a href="https://codereview.stackexchange.com/q/253556/231235">A recursive_transform Template Function Implementation with <code>std::invocable</code> concept in C++</a> and</p>
<p><a href="https://codereview.stackexchange.com/q/251823/231235">A recursive_transform Template Function with Execution Policy</a></p>
</li>
<li><p>What changes has been made in the code since last question?</p>
<p>Considering <a href="https://en.cppreference.com/w/cpp/algorithm/execution_policy_tag_t" rel="nofollow noreferrer">execution policy parameter</a> for <code>recursive_transform</code> function.</p>
</li>
<li><p>Why a new review is being asked for?</p>
<p>I tried to add <code>execution_policy</code> parameter based on the previous experimental implementation first. If there is any possible improvement about the part of execution policy, please let me know.</p>
</li>
</ul>
|
[] |
[
{
"body": "<p>I hope someone else can have a look at the use of the mutex. Just some small things I'll note here:</p>\n<h1>Prefer using <code>{}</code> over <code>0</code> when you don't know the type</h1>\n<p>If you don't know the type of something, don't assume that <code>0</code> is implicitly convertible to an element of that type. Prefer default-constructing it in that case. So instead of:</p>\n<pre><code>for (decltype(+input.shape()[0]) i = 0; i < input.shape()[0]; i++)\n</code></pre>\n<p>Write:</p>\n<pre><code>for (decltype(+input.shape()[0]) i{}; i != input.shape()[0]; ++i)\n</code></pre>\n<p>Also note that I used <code>!=</code> instead of <code><</code> here, as well as the pre-increment operator. If you already assume it's an integer, then I'd not use <code>decltype</code> here but just write <code>std::size_t i = 0</code>, to make this clear.</p>\n<h1>Missing test cases</h1>\n<p>I don't see <code>std::vector<std::string></code> being used as the input in any of the test cases. This is a very important case to test.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-23T22:12:19.137",
"Id": "253853",
"ParentId": "253665",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "253853",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-19T15:24:10.073",
"Id": "253665",
"Score": "2",
"Tags": [
"c++",
"performance",
"recursion",
"lambda",
"c++20"
],
"Title": "A recursive_transform Template Function Implementation with std::invocable Concept and Execution Policy in C++"
}
|
253665
|
<p>Some time ago, I wrote <a href="https://codereview.stackexchange.com/a/176644/39848">this answer</a> to a question about creating a command line menu. I referred to it <a href="https://codereview.stackexchange.com/questions/253644/grade-calculator-new-oop-version-from-one-previous/253648#253648">recently</a> and noticed a few things that I wanted to improve.</p>
<h2>Purpose</h2>
<p>As with the original version, the purpose is to have a class which simplifies the construction and use of a command line (console) menu.</p>
<p>The improvements I made are:</p>
<ol>
<li>allow either <code>std::string</code> or <code>std::wstring</code> prompts and answers</li>
<li>allow the user to separate selectors from descriptions</li>
<li>move everything into a header-only module</li>
<li>allow creation of <code>const</code> menus</li>
<li>sort by selectors</li>
</ol>
<h2>Questions</h2>
<p>Some things I had questions about are:</p>
<ol>
<li>template parameter names - could they be improved?</li>
<li>use of <code>default_in</code> and <code>default_out</code> - would it be better to infer defaults from the string type?</li>
<li>choice of <code>std::function<void()></code> as the operation for each choice</li>
<li>use of <code>std::pair</code> vs. custom object</li>
<li>should I wrap all of this in a namespace?</li>
<li>is any functionality missing?</li>
<li>is there a way to make a <code>constexpr</code> version?</li>
</ol>
<h2>menu.h</h2>
<pre><code>#ifndef MENU_H
#define MENU_H
#include <functional>
#include <iostream>
#include <map>
#include <string>
#include <utility>
template <typename T> struct default_in;
template<> struct default_in<std::istream> {
static std::istream& value() { return std::cin; }
};
template<> struct default_in<std::wistream> {
static std::wistream& value() { return std::wcin; }
};
template <typename T> struct default_out;
template<> struct default_out<std::ostream> {
static std::ostream& value() { return std::cout; }
};
template<> struct default_out<std::wostream> {
static std::wostream& value() { return std::wcout; }
};
template <class str, class intype, class outtype>
class ConsoleMenu {
public:
ConsoleMenu(const str& message,
const str& invalidChoiceMessage,
const str& prompt,
const str& delimiter,
const std::map<str, std::pair<str, std::function<void()>>>& commandsByChoice,
intype &in = default_in<intype>::value(),
outtype &out = default_out<outtype>::value());
void operator()() const;
private:
outtype& showPrompt() const;
str message;
str invalidChoiceMessage_;
str prompt;
str delimiter;
std::map<str, std::pair<str, std::function<void()>>> commandsByChoice_;
intype &in;
outtype &out;
};
template <class str, class intype, class outtype>
ConsoleMenu<str, intype, outtype>::ConsoleMenu(const str& message,
const str& invalidChoiceMessage,
const str& prompt,
const str& delimiter,
const std::map<str, std::pair<str, std::function<void()>>>& commandsByChoice,
intype &in, outtype& out) :
message{message},
invalidChoiceMessage_{invalidChoiceMessage},
prompt{prompt},
delimiter{delimiter},
commandsByChoice_{commandsByChoice},
in{in},
out{out}
{}
template <class str, class intype, class outtype>
outtype& ConsoleMenu<str, intype, outtype>::showPrompt() const {
out << message;
for (const auto &commandByChoice : commandsByChoice_) {
out << commandByChoice.first
<< delimiter
<< commandByChoice.second.first
<< '\n';
}
return out << prompt;
}
template <class str, class intype, class outtype>
void ConsoleMenu<str, intype, outtype>::operator()() const {
str userChoice;
const auto bad{commandsByChoice_.cend()};
auto result{bad};
out << '\n';
while (showPrompt() && (!(std::getline(in, userChoice)) ||
((result = commandsByChoice_.find(userChoice)) == bad))) {
out << '\n' << invalidChoiceMessage_;
}
result->second.second();
}
#endif // MENU_H
</code></pre>
<h2>main.cpp</h2>
<pre><code>#include "menu.h"
#include <iostream>
#include <functional>
template <class str, class outtype>
class Silly {
public:
void say(str msg) {
default_out<outtype>::value() << msg << "!\n";
}
};
using MySilly = Silly<std::string, std::ostream>;
int main() {
bool running{true};
MySilly thing;
auto blabble{std::bind(&MySilly::say, thing, "BLABBLE")};
const ConsoleMenu<std::string, std::istream, std::ostream> menu{
"What should the program do?\n",
"That is not a valid choice.\n",
"> ",
". ",
{
{ "1", {"bleep", []{ std::cout << "BLEEP!\n"; }}},
{ "2", {"blip", [&thing]{ thing.say("BLIP"); }}},
{ "3", {"blorp", std::bind(&MySilly::say, thing, "BLORP")}},
{ "4", {"blabble", blabble }},
{ "5", {"speak Chinese", []{std::cout << "对不起,我不能那样做\n"; }}},
{ "0", {"quit", [&running]{ running = false; }}},
}
};
while (running) {
menu();
}
}
</code></pre>
<p>This shows the use of the program and several different ways of creating menu functions. Depending on your console and compiler settings, the Chinese sentence may or may not be displayed properly. Next is a wide string version.</p>
<h2>wide.cpp</h2>
<pre><code>#include "menu.h"
#include <iostream>
#include <functional>
#include <locale>
template <class str, class outtype>
class Silly {
public:
void say(str msg) {
default_out<outtype>::value() << msg << "!\n";
}
};
using MySilly = Silly<std::wstring, std::wostream>;
int main() {
bool running{true};
MySilly thing;
auto blabble{std::bind(&MySilly::say, thing, L"BLABBLE")};
ConsoleMenu<std::wstring, std::wistream, std::wostream> menu{
L"What should the program do?\n",
L"That is not a valid choice.\n",
L"> ",
L". ",
{
{ L"1", {L"bleep", []{ std::wcout << L"BLEEP!\n"; }}},
{ L"2", {L"blip", [&thing]{ thing.say(L"BLIP"); }}},
{ L"3", {L"blorp", std::bind(&MySilly::say, thing, L"BLORP")}},
{ L"4", {L"blabble", blabble }},
{ L"5", {L"说中文", []{std::wcout << L"对不起,我不能那样做\n"; }}},
{ L"0", {L"quit", [&running]{ running = false; }}},
}
};
std::locale::global(std::locale{"en_US.UTF-8"});
while (running) {
menu();
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-19T18:03:32.617",
"Id": "500219",
"Score": "0",
"body": "Perhaps more event driven and model-view-controller like architecture would be better? Usually there is some shared state that needs to change and there is usually only one screen to render into. Perhaps I’m being biased towards OpenGL though."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-19T18:09:04.190",
"Id": "500220",
"Score": "0",
"body": "It could have been separated, but there's so little of the view and controller pieces that it didn't seem worthwhile to do that. Also keep in mind that one could easily wrap this inside another `class` to maintain whatever shared state might be needed. The `running` variable was intended to illustrate that kind of use."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-19T18:24:59.227",
"Id": "500221",
"Score": "0",
"body": "The use cases I had in mind were multi-menu situations and submenu cases. There are also conditions when menu needs to be rebuilt or some parts of it disabled. For example not letting the user exit without explicitly either saving or discarding current state."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-19T18:31:21.133",
"Id": "500222",
"Score": "0",
"body": "Oh, I see what you mean. I had in mind a simple single-level menu that was small and simple enough to be useable on an embedded system. An answer pointing out the use case you mention and what is lacking in the current code to support it would be welcome!"
}
] |
[
{
"body": "<h1>Answers to your questions</h1>\n<blockquote>\n<p>template parameter names - could they be improved?</p>\n</blockquote>\n<p>Mostly it's that they are inconsistent. Start type names with a capital, and either suffix them all with <code>Type</code> or don't. I suggest:</p>\n<ul>\n<li><code>str</code> -> <code>Str</code></li>\n<li><code>intype</code> -> <code>IStream</code> (just to be clear the we do expect something like <code>std::istream</code> here)</li>\n<li><code>outtype</code> -> <code>OStream</code></li>\n</ul>\n<blockquote>\n<p>use of default_in and default_out - would it be better to infer defaults from the string type?</p>\n</blockquote>\n<p>Yes, see below.</p>\n<blockquote>\n<p>choice of <code>std::function<void()></code> as the operation for each choice</p>\n</blockquote>\n<p>You need <code>std::function<></code> here to store the functions for each choice in the map. The only question is if <code>void()</code> is the right type for the function. If you wanted <code>operator()()</code> to take parameters and/or return a value, then you would have to change the type of the function as well.</p>\n<blockquote>\n<p>use of std::pair vs. custom object</p>\n</blockquote>\n<p>I personally think it's fine with <code>std::pair</code>.</p>\n<blockquote>\n<p>should I wrap all of this in a namespace?</p>\n</blockquote>\n<p>If it is just <code>class ConsoleMenu</code>, I don't think it would be any improvement to put it in a namespace. However, I would put <code>default_in</code> and <code>default_out</code> in a namespace, as those names are quite generic, and you don't want them to pollute the global namespace.</p>\n<blockquote>\n<p>is any functionality missing?</p>\n</blockquote>\n<p>I don't know, if this is all you need then it's complete. If you need something else from it, it's not.</p>\n<blockquote>\n<p>is there a way to make a constexpr version?</p>\n</blockquote>\n<p>Yes, by making sure it satisfies the requirements of <a href=\"https://en.cppreference.com/w/cpp/named_req/LiteralType\" rel=\"nofollow noreferrer\">LiteralType</a>. This also means that all member variables must be valid LiteralTypes, and that prevents using <code>std::string</code> or <code>std::map</code>. You can use <code>const char *</code> and <code>std::array</code> instead.</p>\n<h1>Pass the input and output stream by value</h1>\n<p>The construction you have where you pass a stream type as a template parameter, and then have it deduce a concrete stream from that is very weird, inflexible, and requires more typing than necessary. Just add the input and output stream as parameters to the constructor:</p>\n<pre><code>template <class str, class intype, class outtype>\nclass ConsoleMenu {\npublic:\n ConsoleMenu(const str& message,\n ...,\n intype &in,\n outtype &out);\n</code></pre>\n<p>Compare:</p>\n<pre><code>ConsoleMenu<std::wstring, std::wistream, std::wostream> menu{...}\n</code></pre>\n<p>Versus:</p>\n<pre><code>ConsoleMenu<std::wstring> menu{..., std::wcin, std::wcout}\n</code></pre>\n<p>If you want the standard input and output to be a default parameter, then I would deduce it from the string type:</p>\n<pre><code>template <typename T> struct default_in;\n\ntemplate<> struct default_in<std::string> { \n static std::istream& value() { return std::cin; }\n};\n\ntemplate<> struct default_in<std::wstring> { \n static std::wistream& value() { return std::wcin; }\n};\n\n...\n\ntemplate <class str, class intype, class outtype>\nclass ConsoleMenu {\npublic:\n ConsoleMenu(const str& message,\n ...,\n intype &in = default_in<str>::value(),\n outtype &out = default_out<str>::value());\n</code></pre>\n<p>Because then you can just write:</p>\n<pre><code>ConsoleMenu menu{L"Wide menu", L"invalid", L"> ", L". ", {/* choices */}};\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-20T14:51:33.857",
"Id": "500279",
"Score": "0",
"body": "I also noticed another flaw with my version. If I try to use `std::string_view`, the code won't compile because it tries to read one from `std::cin`. I think I'll have to key the type off of the string type such that `wstring_view` becomes `wstring`. Still pondering how best to do that."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-20T16:34:25.387",
"Id": "500282",
"Score": "1",
"body": "You could use `str::value_type` perhaps? And then use `intype = std::basic_istream<str::value_type>` as the default parameter value."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-20T12:16:07.743",
"Id": "253702",
"ParentId": "253667",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "253702",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-19T16:48:24.880",
"Id": "253667",
"Score": "5",
"Tags": [
"c++",
"console",
"c++17"
],
"Title": "Header-only generic console menu maker"
}
|
253667
|
<p>I am using Retrofit to get data from API. I am doing it in view model like the following:</p>
<pre><code>class RegisterShopViewModel : ViewModel() {
private val client by lazy { WebServicesApi.getClient }
private var isShopRegisterSuccessful = MutableLiveData<Pair<Boolean, List<String>>>()
fun registerShop(shopModel: ShopModel): LiveData<Pair<Boolean, List<String>>> {
client.registerShop(shopModel)
.enqueue(object : Callback<RegisterResponseModel> {
override fun onFailure(call: Call<RegisterResponseModel>, t: Throwable) {
TODO("Not yet implemented")
}
override fun onResponse(
call: Call<RegisterResponseModel>,
response: Response<RegisterResponseModel>
) {
response.body()?.let {
isShopRegisterSuccessful.value =
Pair(it.isSuccess, it.errorsList)
}
}
})
return isShopRegisterSuccessful
}
</code></pre>
<p>and in my view(Activity/Fragment), I am listening for changes like so</p>
<pre><code> val email = txtShopEmail.text.toString()
val password = txtShopPassword.text.toString()
val confirmPassword = txtShopConfirmPassword.text.toString()
val name = txtShopName.text.toString()
val shopModel = ShopModel(email, password, confirmPassword, name)
registerShopViewModel.registerShop(shopModel).observe(this, Observer {
registerShop(it)
})
}
private fun registerShop(result: Pair<Boolean, List<String>>) {
if (result.first)
Toast.makeText(this, "Registered Successfully", Toast.LENGTH_SHORT).show()
else
Toast.makeText(this, "error ${result.second}", Toast.LENGTH_SHORT).show()
}
}
</code></pre>
<p>my questions are:</p>
<p>1 - is it best practice to send the data in <code>ViewModel</code>'s function?</p>
<p>2 - in cases of register/ login in which I send a request with data and wait for a response. Is <code>LiveData</code> useful?</p>
<p>if you have any suggestion to improve this code please share it</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-19T17:40:47.837",
"Id": "253669",
"Score": "0",
"Tags": [
"android",
"kotlin"
],
"Title": "Android: should I get network calls in viewmodel"
}
|
253669
|
<p>My code takes the input submitted by <code>$ _POST</code>, via a checkbox array. I process the array and check the sent data if there is a particular string in it, which is set as my default. If I have a string, which is my default, I just go through implode and add ",", if my default string is missing in the data. I add and sort the array anew, with the first string being the default. I want to shorten the code because I can't make it shorter.</p>
<pre><code><?php
if(isset($_POST['submit'])) {
//for update
$site_id['locale'] = 'tr';
//new
$exampleArray = isset($_POST['lala']) ? $_POST['lala'] : '';
$example = null;
if(($key = array_search($site_id['locale'], $exampleArray, true)) !== false) {
unset($exampleArray[$key]);
$FirstString = array($site_id['locale']);
$exampleArray = array_diff($exampleArray, $FirstString);
usort($exampleArray);
$exampleArray = array_merge($FirstString, $exampleArray);
//print_r($exampleArray);
$myArray = array();
foreach ( $exampleArray as $key => $value ) {
$myArray[] = $value;
}
echo implode( ', ', $myArray );
} else {
$FirstString = array($site_id['locale']);
$exampleArray = array_diff($exampleArray, $FirstString);
usort($exampleArray);
$exampleArray = array_merge($FirstString, $exampleArray);
//print_r($exampleArray);
$myArray = array();
foreach ( $exampleArray as $key => $value ) {
$myArray[] = $value;
}
echo implode( ', ', $myArray );
}
}
?>
<form method="POST" action="">
<input type="checkbox" name="lala[]" value="bg" />
<input type="checkbox" name="lala[]" value="us" />
<input type="checkbox" name="lala[]" value="gr" />
<input type="submit" name="submit" />
</form>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-19T23:18:11.637",
"Id": "500249",
"Score": "0",
"body": "**Warning: usort() expects exactly 2 parameters, 1 given**"
}
] |
[
{
"body": "<p>Addressing two issues here:</p>\n<h3>Setting a default value</h3>\n<p>PHP now has a null coalesce operator (<code>??</code>).\nThis allows you to easily set a default value if the variable is null.</p>\n<pre><code>$exampleArray = $_POST['lala'] ?? [];\n</code></pre>\n<p>(Here, I am setting the default value to an empty array)</p>\n<h3>Refactoring code</h3>\n<p>Any time you catch yourself copy/pasting a chunk of code, that’s a signal to start refactoring. So the code you provided had almost everything in the if and else block repeated. Just pull the repeated stuff out. In this case, you don’t even need the else.</p>\n<pre><code>\nif(isset($_POST['submit'])) {\n //for update\n $site_id['locale'] = 'tr';\n \n //new\n $exampleArray = $_POST['lala']) ?? [];\n \n $example = null;\n if(($key = array_search($site_id['locale'], $exampleArray, true)) !== false) {\n unset($exampleArray[$key]);\n }\n \n $FirstString = array($site_id['locale']);\n $exampleArray = array_diff($exampleArray, $FirstString);\n usort($exampleArray);\n $exampleArray = array_merge($FirstString, $exampleArray); \n //print_r($exampleArray);\n $myArray = array();\n foreach ( $exampleArray as $key => $value ) {\n $myArray[] = $value;\n }\n echo implode( ', ', $myArray );\n\n // Note, should always redirect after a post. \n // Post means change data, so after you have \n // stored the changes, redirect to the next (or \n // back to same) page. Cannot be any output \n // before this (print, echo, blank lines, html)\n \n}\n<span class=\"math-container\">```</span>\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-19T22:43:50.777",
"Id": "253681",
"ParentId": "253671",
"Score": "4"
}
},
{
"body": "<p>To be honest, I am struggling to follow the intended logic in your snippet.</p>\n<p>To my understanding, you are merely wanting to check if the default value exists in the submitted array -- if not, add the default value as the first element. This can be far simpler, more direct.</p>\n<p>Code: (<a href=\"https://3v4l.org/O4ctO\" rel=\"nofollow noreferrer\">Demo</a>)</p>\n<pre><code>$site_id['locale'] = 'tr';\n$exampleArray = ['us', 'gr'];\n\nif (!in_array($site_id['locale'], $exampleArray)) {\n array_unshift($exampleArray, $site_id['locale']);\n}\n\necho implode(', ', $exampleArray);\n</code></pre>\n<p>Output:</p>\n<pre><code>tr, us, gr\n</code></pre>\n<p>As for the code in general, I endorse Tim's insights regarding the null coalescing operator and using an array versus an empty string when null. A string will make <code>array_search()</code> choke.</p>\n<p>I do not know your intended sorting logic with <code>usort()</code>. This is a broken part of your code and must be changed or removed.</p>\n<p>If your code intends to validate/sanitize the submitted values, I can't find that logic. It does make sense to compare the submitted values against a lookup array.</p>\n<p>Also, about <code>$_POST</code>, I don't know what actions are occurring in this script execution, but if you are only <em>reading</em> data from the server (versus writing to the server), then you should be using <code>$_GET</code>. <code>$_POST</code> is primarily used when you are changing the file system or the database (there are some exceptions to this general rule).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-19T23:35:22.687",
"Id": "500251",
"Score": "0",
"body": "Thanks. @mickmackusa That seems to be exactly what I was looking for. Thanks. Question: Before processing an array with in_array, isn't it more correct to check with is_array whether the data is an array? Just a joker, if you can?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-20T00:37:22.883",
"Id": "500254",
"Score": "1",
"body": "The submitted element _will_ be an array unless the user manually fools with the form or submission data structure. To ensure that you are always using an array in this case, you can cast the variable as array-type. `$selectedLanguages = (array)($_POST['lala'] ?? []);` then any scalar values will become the lone element of the newly formed array."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-21T04:40:34.983",
"Id": "500313",
"Score": "1",
"body": "@Vladimirov it makes perfect sense to check that it is an array in the first place. Just casting to array means that you are generous but ignorant. You graciously guess the intent of the one who tampered your front-end form and desperately try to satisfy him. You better disregard such tamperer. Better yet log that event as it means someone is playing tricks with your back-end."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-21T04:42:05.880",
"Id": "500314",
"Score": "1",
"body": "Rule #7: \"Don't let people play with your back-end -- unless you give them express permission to do so\" ;)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-28T22:25:55.403",
"Id": "500965",
"Score": "0",
"body": "I'm frankly surprised that my answer wasn't accepted (not that it matters) because I demonstrated how 27 lines of convoluted code can be simplified to form 6 lines of readable code."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-19T23:30:34.950",
"Id": "253682",
"ParentId": "253671",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "253681",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-19T18:18:20.433",
"Id": "253671",
"Score": "3",
"Tags": [
"php",
"array",
"mergesort"
],
"Title": "Process POSTed data and add default string if missing"
}
|
253671
|
<p>I recently bumped into <a href="https://github.com/dry-python/returns" rel="nofollow noreferrer">dry-python/returns</a>, which seems like a very useful project. In the project description, the authors describe a snippet which can be written with their <code>Maybe</code> container in a better way (according to the authors):</p>
<p>The original code is:</p>
<pre><code>if user is not None:
balance = user.get_balance()
if balance is not None:
credit = balance.credit_amount()
if credit is not None and credit > 0:
discount_program = choose_discount(credit)
</code></pre>
<p>And the improved version is:</p>
<pre><code>discount_program: Maybe['DiscountProgram'] = Maybe.from_optional(
user,
).bind_optional(
lambda real_user: real_user.get_balance(),
).bind_optional(
lambda balance: balance.credit_amount(),
).bind_optional(
lambda credit: choose_discount(credit) if credit > 0 else None,
)
</code></pre>
<p>This is a legitimate solution. However, I would write the first code as:</p>
<pre><code>if user:
balance = user.get_balance()
if balance:
credit = balance.credit_amount()
if credit > 0:
discount_program = choose_discount(credit)
</code></pre>
<p>Being a long time pylint user that the style that is recommended.
Honestly, I've never given it much thought, and now that I saw the first
code, I started asking myself if I should give it some thought.</p>
<p>The most dangerous place IMHO, in my version is:</p>
<pre><code>if credit > 0:
</code></pre>
<p>Since <code>None</code> will raise here a <code>TypeError</code>. However, the original line can be written as:</p>
<pre><code>if credit and credit > 0:
discount_program = choose_discount(credit)
</code></pre>
<p>My favorite style for re-writing this block would be very LISPy. I use <code>getattr</code> with a default value which is callable (a lambda which returns None). This very similar to what the example in return does, but without a 3rd party library:</p>
<pre><code>choose_discount(
getattr(
getattr(user, 'get_balance', lambda: None)(),
'credit_amount', lambda: 0)())
</code></pre>
<p>Which I think would not be like by many because it's very unusual. Also, for this to work properly, I would write <code>choose_discount</code> as:</p>
<pre><code>def choose_discount(credit):
if credit:
return "Your discount choosing ..."
else:
return "No discount"
</code></pre>
<p>If allowed to use a newer version of Python, I would probably use the walrus operator here:</p>
<pre><code>if (credit := getattr(getattr(user, 'get_balance', lambda: None)(), 'credit_amount', lambda: 0)()) > 0:
discount_program = choose_discount(credit)
</code></pre>
<p>This style strongly assume that <code>credit_amount</code> always returns a type which can be numerically compared ... Hence, the caveat I mentioned earlier, with credit being a None is implicitly handled.</p>
<p>I have a few questions regarding this.</p>
<ul>
<li>Can you point out possible caveats in my style?</li>
<li>Could I be missing out something terrible, and I should look for <code>is not None</code>
explicitly?</li>
<li>Is the functional style legitimate here or should I absolutely avoid it?</li>
</ul>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-23T10:10:51.083",
"Id": "500511",
"Score": "1",
"body": "Unfortunately this question has been closed just before I could submit my answer. Don't do `if variable` unless `variable` is of type `bool`. It's easy to accidentally discard valid values this way, e.g. if `variable` is `0`. There is no other way to test if `variable` is not `None` than `if variable is not None`. However, the example given is not good python anyway because a) they return `None` where an exception should have been raised instead and b) it is \"LBYL\" style whereas in python the \"EAFP\" style is usually preferred."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-25T19:40:24.480",
"Id": "500723",
"Score": "0",
"body": "Thanks for the answer. I felt like the problem solved was not a problem at all because of EAFP. Seemed weired for me that so many functions should return `None`... As for `if variable` should be a boolean, that is a good thing to take from this discussion."
}
] |
[
{
"body": "<p>I thought the readme on <a href=\"https://github.com/dry-python/returns\" rel=\"nofollow noreferrer\">dry-python/return</a> did a good job of explaining the usage of the <code>Maybe</code> type.</p>\n<p>The key to understanding <code>Maybe</code> is that it <em>represents computations which might "go wrong" by not returning a value.</em></p>\n<p>The <code>bind</code> method (<code>bind_optional</code>) in this library allows you to write code without having to worry about the result of the computation at any intermediate step, it handles the case where one of the computations returns None.</p>\n<p>In the code you use to demonstrate the conditionals, you still have to handle the cases of <code>None</code> via an <code>if</code> statement, the use of <code>if not None</code> vs <code>if Some</code> isn't relevant. As a hypothetical consider a computation with many level of <code>optional</code> results from computation, you'd still have to implement the same level of nesting.</p>\n<p>In the example from the documentation</p>\n<pre class=\"lang-py prettyprint-override\"><code>user: Optional[User]\n\n# Type hint here is optional, it only helps the reader here:\ndiscount_program: Maybe['DiscountProgram'] = Maybe.from_optional(\n user,\n).bind_optional( # This won't be called if `user is None`\n lambda real_user: real_user.get_balance(),\n).bind_optional( # This won't be called if `real_user.get_balance()` is None\n lambda balance: balance.credit_amount(),\n).bind_optional( # And so on!\n lambda credit: choose_discount(credit) if credit > 0 else None,\n)\n</code></pre>\n<p>the comments in the code say the same. You can imagine a library using a symbolic function name <code>>>=</code> with <code>infix</code> operators allowing the above code to be rewritten as</p>\n<pre class=\"lang-py prettyprint-override\"><code>\ncredit = user >>= (lambda real_user: real_user.get_balance())\n >>= (lambda balance: balance.credit_amount()) \n >>= (lambda credit: choose_discount(credit) if credit > 0 else None)\n\n</code></pre>\n<p>IMO, you approach to utilizing <code>getattr</code> is more akin to programming in a "<a href=\"https://en.wikipedia.org/wiki/Duck_typing\" rel=\"nofollow noreferrer\">duck typing</a>" style than functional.</p>\n<p>I used the haskell wiki's description of the <a href=\"https://en.wikibooks.org/wiki/Haskell/Understanding_monads/Maybe\" rel=\"nofollow noreferrer\"><code>Maybe</code> monad</a> if you want to dig in further.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-20T21:06:55.597",
"Id": "253720",
"ParentId": "253673",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-19T19:42:28.670",
"Id": "253673",
"Score": "2",
"Tags": [
"python-3.x",
"functional-programming"
],
"Title": "Alternatives for checking if something is not None in Python"
}
|
253673
|
<p>This is an exercise in the Automate The Boring Stuff book. I am supposed to create a function that takes a dictionary argument that represents a chess board (ex: {'1h': 'bking', '6c': 'wqueen', '2g': 'bbishop', etc.}) and returns True or False depending on if the board is valid.</p>
<p>A valid board will have (A) exactly one black king and exactly one white king. (B) Each player can only have at most 16 pieces, (C) at most 8 pawns, and (D) all pieces must be on a valid space from '1a' to '8h'; that is, a piece can’t be on space '9z'. (E) The piece names begin with either a 'w' or 'b' to represent white or black, followed by 'pawn', 'knight', 'bishop', 'rook', 'queen', or 'king'. This function should detect when a bug has resulted in an improper chess board.</p>
<pre><code>#Example dictionary of coordinates (keys) and pieces (values)
#my_board = {"1a":"wking", "2a":"bking", "8b":"wpawn", "3a":"wpawn"}
def isValidChessBoard(board):
#Creating a dictionary of pieces (keys) and the number of pieces (values)
num_pieces = {}
list_pieces = ["bpawn", "bking", "bqueen", "brook", "bbishop", "bknight", "wpawn", "wking", "wqueen", "wrook", "wbishop", "wknight"]
for v in board.values():
num_pieces.setdefault(v, 0)
num_pieces[v] = num_pieces[v] + 1
for i in list_pieces:
if i not in num_pieces:
num_pieces.setdefault(i, 0)
#Making sure there is exactly one king on each side
if (num_pieces["wking"] != 1) or (num_pieces["bking"] != 1):
return False
#Making sure there are no more than 8 pawns on each side
if ("bpawn" or "wpawn" in num_pieces) and (num_pieces["bpawn"] or num_pieces["wpawn"]) > 8:
return False
#Making sure every piece is apprpriately named (b/w + king/queen/rook/pawn/knight/bishop)
for j in num_pieces:
if j not in list_pieces:
return False
#Making sure there are no more than 16 pieces on each side
if num_pieces["bpawn"] + num_pieces["bking"] + num_pieces["bqueen"] + num_pieces["brook"] + num_pieces["bbishop"] + num_pieces["bknight"] > 16:
return False
if num_pieces["wpawn"] + num_pieces["wking"] + num_pieces["wqueen"] + num_pieces["wrook"] + num_pieces["wbishop"] + num_pieces["wknight"] > 16:
return False
#Making sure that the board coordinates are all between (a-h, and 1-8)
in_range = 0
possible_coordinates = []
for i in range(1, 9):
for j in ["a", "b", "c", "d", "e", "f", "g", "h"]:
possible_coordinates.append(str(i)+str(j))
for k in board.keys():
if k in possible_coordinates:
in_range = in_range + 1
if len(board) != in_range:
return False
return True
if isValidChessBoard(my_board) == True:
print("Valid Board")
else:
print("Invalid Board")
</code></pre>
<p>I know that the code works, but I was wondering if there were any faux-pas that I am implementing, or if there is anything I could obviously do to make it cleaner. Thanks!</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-19T20:58:31.147",
"Id": "500235",
"Score": "5",
"body": "There are much more restrictions. For example, if all 8 pawns are intact, the side cannot have more than 2 Knights, or more than 2 Rooks, etc."
}
] |
[
{
"body": "<p>As you said the code works - there might be additional conditions for a valid board, that you are not checking for which you will be able to expand on using the same structure. I looked up the <a href=\"https://automatetheboringstuff.com/2e/chapter5/\" rel=\"nofollow noreferrer\">chapter</a> from the book you mention and your implementation meets the requirements outlined there.</p>\n<p>Since this is Python, there are more than one way to implement the requirements, at a minimum I'd recommend refactoring the code to be self documenting instead of relying on comments. This will require only minor refactoring of your code.</p>\n<p>Then building on that may be consider taking a functional approach and utilizing python builtins. YMMV - here is my implementation, it is not perfect, but that is not the intent here.</p>\n<pre class=\"lang-py prettyprint-override\"><code>def checkCriteria(pieces, fn, cnt):\n if len(list(filter(fn, pieces))) > cnt:\n return False\n \n return True\n\ndef checkValidPositions(input_pos):\n positions = set()\n for col in ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']:\n for row in range(1, 9):\n positions.add(str(row) + col)\n\n return all(pos in positions for pos in input_pos)\n\ndef checkMaxPiecesByColor(pieces):\n return all(checkCriteria(pieces, lambda piece: len(piece) > 0 and piece[0] == ch, 16) for ch in ['w', 'b'])\n\ndef checkKingCount(pieces):\n return all(checkCriteria(pieces, lambda piece: piece == king, 1) for king in ['bking', 'wking'])\n\ndef checkPawnCount(pieces):\n return all(checkCriteria(pieces, lambda piece: piece == pawn, 8) for pawn in ['bpawn', 'wpawn'])\n\ndef checkValidPieces(pieces):\n valid_pieces = set()\n for color in ['w', 'b']:\n for piece in ['pawn', 'knight', 'bishop', 'rook', 'queen', 'king']:\n valid_pieces.add(color + piece)\n\n return len(pieces - valid_pieces) == 0\n\ndef isValidChessBoard(board):\n pieces = board.values()\n positions = board.keys()\n\n if not checkValidPositions(positions):\n return False\n \n if not checkMaxPiecesByColor(pieces):\n return False\n \n if not checkKingCount(pieces):\n return False\n \n if not checkPawnCount(pieces):\n return False\n \n if not checkValidPieces(set(pieces) - set([''])):\n return False\n \n return True\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-20T17:14:25.150",
"Id": "253709",
"ParentId": "253674",
"Score": "4"
}
},
{
"body": "<p>This code is not correct</p>\n<pre><code>#Making sure there are no more than 8 pawns on each side\nif ("bpawn" or "wpawn" in num_pieces) and (num_pieces["bpawn"] or num_pieces["wpawn"]) > 8:\n return False\n</code></pre>\n<p>For example, it fails if <code>num_pieces = {"bpawn":2, "wpawn":11}</code>.</p>\n<p><code>("bpawn" or "wpawn" in num_pieces)</code> evaluates to <code>"bpawn"</code>.</p>\n<p><code>(num_pieces["bpawn"] or num_pieces["wpawn"])</code> evaluates to <code>2</code>.</p>\n<p><code>"bpawn" and 2 > 8</code> evaluates to <code>False</code>, so the test passes even though <code>num_pieces["wpawn"]</code> is <code>11</code>.</p>\n<p>It should be something like:</p>\n<pre><code>if num_pieces.get("bpawn", 0) > 8 or num_pieces.get("wpawn", 0) > 8:\n return False\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-22T01:10:21.733",
"Id": "253766",
"ParentId": "253674",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-19T19:46:10.083",
"Id": "253674",
"Score": "5",
"Tags": [
"python"
],
"Title": "Chess Dictionary Validator (Python) (Automate The Boring Stuff)"
}
|
253674
|
<p>I have classes that have some data, and whenever this data changes, it should notify observers of that data change. There also should be a method to add new observers.</p>
<p>My first approach was to use a property with a custom setter. This means that whenever the <code>=</code> operator was used on the data it would call the custom setter, which would notify the observers.</p>
<p>Like so:</p>
<pre><code># (1)
from typing import Callable
class Foo:
def __init__(self):
self.__bar = 0
self.__bar_observers = []
@property
def bar(self):
return self.__bar
@bar.setter
def bar(self, value):
self.__bar = value
#notify observers
for obs in self.__bar_observers:
obs(value)
def add_bar_observer(self, observer : Callable[[int], None]):
self.__bar_observers.append(observer)
f = Foo()
f.add_bar_observer(lambda newval : print(f'new bar val {newval}'))
f.bar = 8
</code></pre>
<p>But this is a lot of boilerplate and is many lines of code just for one property. If <code>Foo</code> had 10 observable properties instead of just one, this class would be quite large.</p>
<p>It would be good if this pattern could be created automatically with a decorator.</p>
<p>Here is my attempt at that:</p>
<pre><code># (2)
def observable_property(initial_value):
class _observable_property:
def __init__(self, fget):
pass
# We don't know if __set__, __get__, or add_observer will be called first, so we need to call this at the start of all 3.
def __init(self, obj):
#On first time called, create the data
if not hasattr(obj, f'__{self.name}'):
setattr(obj, f'__{self.name}', initial_value)
if not hasattr(obj, f'__{self.name}_observers'):
setattr(obj, f'__{self.name}_observers', [])
def __get__(self, obj, objtype=None):
self.__init(obj)
return getattr(obj, f'__{self.name}')
def __set__(self, obj, value):
self.__init(obj)
setattr(obj, f'__{self.name}', value)
#Notify all of the observers
for obs in getattr(obj, f'__{self.name}_observers'):
obs(value)
def __set_name__(self, owner: type, name : str):
self.name = name
#Add a function to the owner to add new observers
def add_observer(obj, observer):
self.__init(obj)
getattr(obj, f'__{name}_observers').append(observer)
setattr(owner, f'add_{name}_observer', add_observer)
return _observable_property
</code></pre>
<p>And then a test:</p>
<pre><code># (3)
Meters = NewType('Meters', float)
Kelvin = NewType('Kelvin', float)
class Axis:
@observable_property(initial_value=Meters(0.0))
def position(self):
pass
@observable_property(initial_value=Kelvin(0.0))
def temperature(self):
pass
a = Axis()
a.add_position_observer(lambda newval : print(f'New position for a: {newval}'))
a.add_temperature_observer(lambda newval : print(f'New temperature for a: {newval}'))
a.position = Meters(5.0)
a.temperature = Kelvin(300.0)
</code></pre>
<p>This works, but two downsides I can see are that the <code>add_{}_observer</code> functions do not appear in an IDE IntelliSense autocomplete, and it also loses its type hints.</p>
<p>What do you think? Would you use this in production code?</p>
<p>I would also prefer it if the <code>initial_value</code> was set in the constructor of the class, instead of as a decorator parameter, and then the function to be decorated returns that, as is the case with the standard <code>@property</code> decorator.</p>
<p>i.e</p>
<pre><code># (4)
class Axis:
def __init__(self):
self.__position=Meters(0.0)
@observable_property
def position(self):
return self.__position
</code></pre>
<p>But I cannot do this as I can't mutate the <code>self.__position</code> from the <code>__set__</code> descriptor. Is there any way to get the style of <code># (4)</code>, with the functionality of <code># (3)</code>?</p>
<p>Thanks.</p>
|
[] |
[
{
"body": "<h1>Private name mangling</h1>\n<p>The reason why you "<em>can't mutate the <code>self.__position</code> from the <code>__set__</code> descriptor</em>" is the leading double underscore. From <a href=\"https://docs.python.org/3/reference/expressions.html#atom-identifiers\" rel=\"nofollow noreferrer\">6.2.1. Identifiers (Names)</a>:</p>\n<blockquote>\n<p><strong>Private name mangling:</strong> When an identifier that textually occurs in a class definition begins with two or more underscore characters and does not end in two or more underscores, it is considered a private name of that class. Private names are transformed to a longer form before code is generated for them. The transformation inserts the class name, with leading underscores removed and a single underscore inserted, in front of the name. For example, the identifier __spam occurring in a class named Ham will be transformed to _Ham__spam. This transformation is independent of the syntactical context in which the identifier is used. If the transformed name is extremely long (longer than 255 characters), implementation defined truncation may happen. If the class name consists only of underscores, no transformation is done.</p>\n</blockquote>\n<p>In the constructor, <code>self.__position = 0.0</code> is rewritten to be <code>self._Axis__position = 0.0</code>. When you are in the descriptor's <code>__set__</code> method, <code>getattr(obj, '__position')</code> does not exists, because the name is wrong.</p>\n<p>If you used a single leading underscore, instead of a double leading underscore, no name mangling will take place, and attribute can be referenced with the same name in both the main class and the descriptors. This means you can set the initial values in the constructor, as desired.</p>\n<h1>Boilerplate</h1>\n<pre class=\"lang-py prettyprint-override\"><code> @observable_property(initial_value=Meters(0.0))\n def position(self):\n pass\n</code></pre>\n<p>The <code>def</code>, <code>(self):</code> and <code>pass</code> parts of this are also boilerplate. If you tried to use actual code, instead of the <code>pass</code> statement, the code would never be executed, because the descriptor's <code>__get__</code> method is used instead.</p>\n<p>The above code is approximately:</p>\n<pre class=\"lang-py prettyprint-override\"><code> position = observable_property(initial_value=Meters(0.0))(lambda self: pass)\n</code></pre>\n<p>If you removed the unused <code>fget</code> argument from the constructor, or removed the <code>_observable_property</code> constructor entirely, this could be reduced to:</p>\n<pre class=\"lang-py prettyprint-override\"><code> position = observable_property(initial_value=Meters(0.0))()\n</code></pre>\n<p>Since you don't need (or want) the initial value in the observable property descriptor, you want it in the class constructor, and the previous section showed why it wasn't working and how to fix it, we can remove the <code>initial_value</code> argument entirely, and with it the <code>def observable_property</code> wrapper around the <code>class _observable_property</code>.</p>\n<h1>Reworked code:</h1>\n<pre class=\"lang-py prettyprint-override\"><code>from typing import NewType\n\nclass ObservableProperty:\n \n def __set_name__(self, owner: type, name: str) -> None:\n def add_observer(obj, observer):\n if not hasattr(obj, self.observers_name):\n setattr(obj, self.observers_name, [])\n getattr(obj, self.observers_name).append(observer)\n \n self.private_name = f'_{name}'\n self.observers_name = f'_{name}_observers'\n setattr(owner, f'add_{name}_observer', add_observer)\n \n def __get__(self, obj, objtype=None):\n if obj is None:\n return self\n return getattr(obj, self.private_name)\n\n def __set__(self, obj, value):\n setattr(obj, self.private_name, value)\n for observer in getattr(obj, self.observers_name, []):\n observer(value)\n\n\nMeters = NewType('Meters', float)\nKelvin = NewType('Kelvin', float)\n\nclass Axis:\n\n def __init__(self):\n self._position = Meters(0.0)\n self._temperature = Kelvin(273.0)\n\n position = ObservableProperty()\n temperature = ObservableProperty()\n\na = Axis()\nprint(a.position) # Initial values from the constructor\nprint(a.temperature)\na.add_position_observer(lambda newval : print(f'New position for a: {newval}'))\na.add_temperature_observer(lambda newval : print(f'New temperature for a: {newval}'))\na.position = Meters(5.0)\na.temperature = Kelvin(300.0)\n</code></pre>\n<h1>Composition</h1>\n<p>The <code>ObservableProperty</code> descriptor takes away all control of the attribute from the class. The attribute cannot be calculated. For instance, an observable attribute <code>celsius</code> could not read <code>self.kelvin + 273</code>, or write <code>self.kelvin = value - 273</code> because it has no control over the get/set functionality.</p>\n<p>What if you made an <code>@observable</code> decorator, which just added the observer capability, which could be used like:</p>\n<pre class=\"lang-py prettyprint-override\"><code>class Axis:\n\n def __init__(self):\n self._position = 0.0\n\n @property\n def position(self) -> Meters:\n return self._position\n\n @observable\n @position.setter\n def position(self, value: Meters) -> None:\n self._position = value\n</code></pre>\n<p>Then, you could have validation in the setter (such as position can't be negative).</p>\n<p>And if you wanted, you could create a <code>SimpleProperty</code>, which had the trivial getter & setter, and compose that into <code>ObservableSimpleProperty</code> and so on.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-21T15:29:46.273",
"Id": "500347",
"Score": "0",
"body": "Thanks for your answer. I agree with your points and have ended up going with something like your final code snippet (@observable @position.setter). But the reason I couldn't mutate `self.__position`, wasn't just because it was private, it was also because it was a float. even if was called `self.position`, if I did `obj.position = value` inside `__set__` it wouldn't change the orginal `position` because floats are imutable."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-21T18:11:18.547",
"Id": "500356",
"Score": "1",
"body": "You are confusing immutability of objects and immutability of attributes. Yes `4.0` is an immutable `float`, and `position = 4.0` will store that immutable object in `position`, but you can still write `position += 2.5`, which changes the value stored in the attribute, but does not change an immutable object. `obj.position = value` inside `__set__` doesn’t work, because it would cause infinite recursion."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-20T18:40:41.597",
"Id": "253714",
"ParentId": "253675",
"Score": "2"
}
},
{
"body": "<p>How about an mixin Observable class.</p>\n<pre><code>from collections import defaultdict\n\nclass Observable:\n def __init__(self):\n self.observed = defaultdict(list)\n \n def __setattr__(self, name, value):\n super().__setattr__(name, value)\n \n for observer in self.observed.get(name, []):\n observer(value) \n \n def add_observer(self, name, observer):\n self.observed[name].append(observer)\n</code></pre>\n<p>To be used like so:</p>\n<pre><code>class Foo(Observable):\n def __init__(self):\n super().__init__()\n self.aaa = 42\n\nf = Foo()\nf.add_observer('aaa', lambda value:print(f"a.aaa changed to {value}"))\nf.add_observer('aaa', lambda value:print(f"a.aaa is now {value}"))\n</code></pre>\n<p>Output:</p>\n<pre><code>f.aaa = 21\na.aaa changed to 21\na.aaa is now 21\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-23T06:45:41.843",
"Id": "500504",
"Score": "1",
"body": "That allows every attribute of the object to be observable, instead of marked properties. The OP also wanted `.add_{name}_observer(...)` methods which IDE's could offer autocomplete suggestions for; your method doesn't provide autocomplete hints for attribute names. Finally, as used here, `Observable` is technically a base class, not a mix-in."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-23T05:21:24.543",
"Id": "253811",
"ParentId": "253675",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-19T19:59:54.980",
"Id": "253675",
"Score": "3",
"Tags": [
"python-3.x",
"design-patterns",
"observer-pattern"
],
"Title": "A Python decorator for an \"observable property\", that notifies observers when the data is changed"
}
|
253675
|
<p>I'm trying to learn some basic x86 assembly and so I've begun solving Project Euler problems. I was hoping for some critique of my code that, hopefully, includes either the efficiency of the operations or the readability / style of the code itself. I will provide the Makefile for Linux 64 bit.</p>
<p>The purpose of the code is to sum all numbers from [0, 1000) that are divisible by 3 or 5.</p>
<p>The code can be run using <code>make RUN=euler_1</code>.</p>
<p>NB:</p>
<p>I am aware that most compilers replace modulos of known numbers with some combination of <code>mov</code> and <code>shr</code> to avoid the integer division. For example, see <a href="https://stackoverflow.com/questions/8021772/assembly-language-how-to-do-modulo">this thread</a>.</p>
<p><strong>Makefile</strong></p>
<pre><code>.PHONY: clean
all: $(RUN).elf
./$^
%.elf: %.o
ld $^ -o $@ -lc -e main -dynamic-linker /lib64/ld-linux-x86-64.so.2
%.o: %.asm
nasm -f elf64 $^
clean:
rm -f *.o *.elf
</code></pre>
<p><strong>euler_1.asm</strong></p>
<pre><code>extern printf
global main
section .data
fmt: db "%d", 0x0a, 0
section .text
;; main - Calculate the sum of all numbers between [0, 1000) that are divisible
;; by 3 or 5.
;; sum : R8
main:
; sum = 0
mov r8, 0
; for i in [0, 1000) {
mov rcx, 0
for0:
; if i % 3 == 0 or i % 5 == 0 {
; i % 3 == 0
mov rax, rcx
mov rdx, 0
mov r9, 3
div r9
test rdx, rdx
jne if01
; sum = sum + i
add r8, rcx
jmp if0
if01:
; i % 5 == 0
mov rax, rcx
mov rdx, 0
mov r9, 5
div r9
test rdx, rdx
jne if0
; sum = sum + i
add r8, rcx
jmp if0
; }
if0:
inc rcx
cmp rcx, 1000
jl for0
; }
; printf("%d", sum)
lea rdi, [rel fmt]
mov rsi, r8
mov rax, 0
call printf
; sys_exit(0)
mov rdi, 0
mov rax, 60
syscall
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-19T22:43:26.367",
"Id": "500245",
"Score": "2",
"body": "Looks like an interesting question! Could you please update the text of the question to describe exactly what the program does? Right now it's somewhat hidden in a comment in the code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-19T22:44:30.067",
"Id": "500246",
"Score": "1",
"body": "Oops, added! Thanks @Edward"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-20T16:21:55.897",
"Id": "500281",
"Score": "3",
"body": "Hi, if your goal is to study assembly, you can also try disassembling a compiled C program. e.g. gcc test.c -g && gdb ./a.out ; and disas /m main ; or even try out https://godbolt.org/"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-21T21:17:08.577",
"Id": "500398",
"Score": "2",
"body": "I also asked about Project Euler 1 in x86_64 (but AT&T rather than Intel syntax) recently, maybe some of those comments will help you: https://codereview.stackexchange.com/q/245990/195637"
}
] |
[
{
"body": "<ul>\n<li><p><code>if01</code> and <code>if0</code> are not the greatest names.</p>\n</li>\n<li><p>Instead of reloading <code>r9</code>, use two registers. Let <code>r9</code> always contain 3, and <code>r10</code> always contain 5.</p>\n</li>\n<li><p>Increment <code>r8</code> in one place.</p>\n</li>\n<li><p>Running the loop downwards (1000 to 0), rather than upwards, spares an instruction (<code>cmp</code>).</p>\n</li>\n<li><p><code>mov rdx, 0</code> is encoded in 7 bytes. <code>xor rdx, rdx</code> is way shorter.</p>\n</li>\n</ul>\n<p>All that said, consider</p>\n<pre><code>main:\n mov r8, 0 \n mov r9, 3\n mov r10, 5\n\n ; for i in (1000, 0] \n mov rcx, 999\n\nfor0: \n mov rax, rcx\n xor rdx, rdx\n div r9\n test rdx, rdx\n jeq accumulate\n\n mov rax, rcx\n xor rdx, rdx\n div r10\n test rdx, rdx\n jne next\n\naccumulate:\n add r8, rcx\nnext:\n dec rcx\n jne for0\n</code></pre>\n<p>PS: I hope you know that this problem has a very straightforward arithmetical solution.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-20T02:18:40.590",
"Id": "500256",
"Score": "4",
"body": "+1 for the final comment especially."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-20T12:54:15.647",
"Id": "500277",
"Score": "4",
"body": "What assembler uses the mnemonic `jeq`? Or is that just a typo? Also, you do not need to use the full 64-bit registers when clearing or loading small immediates. The upper 32 bits are automatically cleared, so you can just do, e.g., `xor edx, edx`. And there's never a reason to do `mov reg, 0`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-20T16:47:52.150",
"Id": "500283",
"Score": "0",
"body": "@CodyGray if you wanted to align the next instruction, I suppose `mov reg32,0` could be (if it has a suitable size) a better choice than `xor reg32,reg32\\nnop dword [rax]`. Am I wrong?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-20T17:13:12.463",
"Id": "500284",
"Score": "0",
"body": "Yes, there are times you might intentionally want to use a larger-size instruction for alignment reasons. But the only time you would worry about that sort of alignment is before a branch target, when that branch was expected to be taken a large number of times. And honestly, whether the MOV vs the XOR+NOP is better, I couldn't tell you. You'd have to benchmark it. Most of the benchmarks I've run tell me that alignment is not obsessing over. The assembler should automatically align functions. @Ruslan"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-20T19:22:34.990",
"Id": "500288",
"Score": "1",
"body": "@CodyGray: Compilers automatically align functions. In hand-written assembly, you should use `align 16` before labels if you want to match that behaviour. If I wanted a longer zeroing instruction, I might use some dummy segment-override prefixes and a REX.W=0 before a 32-bit xor-zeroing instruction. Segment prefixes (unlike REP) can apply to some forms of XOR, so it's highly unlikely that future CPUs will use that prefix+opcode combo as some other instruction."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-20T19:24:38.170",
"Id": "500289",
"Score": "1",
"body": "If I didn't want to use extra prefixes on xor-zeroing, `mov reg, 0` is really not bad unless you need to avoid partial-register penalties on P6-family (e.g. before setcc); I think I mentioned that in my canonical answer on [What is the best way to set a register to zero in x86 assembly: xor, mov or and?](https://stackoverflow.com/q/33666617). Modern CPUs have enough back-end ports vs. their front-end width that having xor-zeroing eliminated is usually not significant for throughput. And only Intel actually eliminates it in the front-end; AMD Zen only eliminates `mov reg,reg`. (@Ruslan)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-21T06:53:00.903",
"Id": "500325",
"Score": "1",
"body": "Besides xor-zeroing, we know the remainder of anything divided by 3 or 5 will fit in a 32-bit register, so we can similarly save a REX prefix with `test edx, edx`. (And with `mov r9d, 3`, although [NASM will do that optimization for you](https://stackoverflow.com/questions/48596247/why-nasm-on-linux-changes-registers-in-x86-64-assembly) because it's exactly equivalent. Other assemblers won't, and understanding x86-64's implicit zero-extending is important for understanding some compiler-generated code because they always optimize mov-immediate; unfortunately not always other insns.)"
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-20T01:14:53.523",
"Id": "253685",
"ParentId": "253680",
"Score": "16"
}
},
{
"body": "<p>Here are some things that may help you improve your code. The other review made some good points, but here are some not covered there.</p>\n<h2>Decide whether you're using stdlib or not</h2>\n<p>The <code>Makefile</code> and call to <code>printf</code> both indicate that you're using the standard C library, which is fine, but then the program terminates using a <code>syscall</code> which is not. The reason is that the standard C startup sets things up before <code>main</code> is called and then also tears them down again after <code>main</code> returns. This code is skipping the teardown by instead using the <code>syscall</code> to end the program, which is not good practice. There are two alternatives: either don't use the C library at all (that is, write your own <a href=\"https://stackoverflow.com/questions/27594297/how-to-print-a-string-to-the-terminal-in-x86-64-assembly-nasm-without-syscall\">printing routine</a>) or let the teardown actually happen:</p>\n<pre><code>xor eax, eax ; set exit code to 0 to indicate success\nret ; return to _libc_start_main which called our main\n</code></pre>\n<p>For further reading on how the startup and teardown works in Linux <a href=\"http://dbp-consulting.com/tutorials/debugging/linuxProgramStartup.html\" rel=\"noreferrer\">read this</a>.</p>\n<h2>Manage registers carefully</h2>\n<p>One of the things that expert assembly language programmers (and good compilers) do is managing register usage. In this case, the ultimate use of the sum is to print it, and to print it we need the value in the <code>rsi</code> register. So why not use <code>rsi</code> instead of <code>r8</code> as the running sum?</p>\n<h2>Know how to efficiently zero a register</h2>\n<p>Obviously, if we write <code>mov r8, 0</code> it has the desired effect of loading the value 0 into the <code>r8</code> register, and as the other review notes, there are better ways to do that, but let's look more deeply. The code currently does this:</p>\n<pre><code>; sum = 0\nmov r8, 0 \n; for i in [0, 1000) {\nmov rcx, 0\n</code></pre>\n<p>That works, but let's look at the listing file to see what NASM has turned that into:</p>\n<pre><code>13 ; sum = 0\n14 00000000 41B800000000 mov r8, 0 \n15 ; for i in [0, 1000) {\n16 00000006 B900000000 mov rcx, 0\n</code></pre>\n<p>The first column is just the line number of the listing file, the second is the address and the third is the encoded instruction. So we see that the two instructions use 11 bytes. We can do better! The other review correctly mentioned the <code>xor</code> instruction, so let's try it:</p>\n<pre><code>19 00000000 4D31C0 xor r8, r8\n20 00000003 4831C9 xor rcx, rcx\n</code></pre>\n<p>Better, only six bytes. We can do better still. As one of the comments correctly noted, on a 64-bit x86 machine, if you <code>xor</code> the lower half of a <code>rXX</code> register, it also clears the upper half. So let's do that:</p>\n<pre><code>19 00000000 4D31C0 xor r8, r8\n20 00000003 31C9 xor ecx, ecx\n</code></pre>\n<p>That saved one byte, but there is no <code>e8</code> register. Can we do better by clearing <code>ecx</code> and then copying that value into <code>r8</code>?</p>\n<pre><code>14 00000000 31C9 xor ecx, ecx\n20 00000002 4989C8 mov r8, rcx\n</code></pre>\n<p>No, we can't, unless we also follow the advice above and use <code>rsi</code> instead of <code>r8</code>:</p>\n<pre><code>19 00000000 31C9 xor ecx, ecx\n20 00000002 31F6 xor esi, esi\n</code></pre>\n<p>Now we're down to four bytes, and we no longer need the <code>mov rsi, r8</code> instruction which saves us another 3 bytes, for a net savings of 10 bytes with just those two things.</p>\n<h2>Avoid <code>div</code> if practical</h2>\n<p>The <code>div</code> instruction is one of the slowest instructions on the x86_64 architecture and can also cause an exception if we try to divide by zero. For both of those reasons, it's often better to avoid the instruction if we can. In this case, one way to avoid it is to note that it looks a lot like <a href=\"https://codereview.stackexchange.com/a/56896/39848\"><code>fizzbuzz</code></a> and keep two counters: one that counts down from 5 and the other that counts down from 3.</p>\n<h2>Use local labels where practical</h2>\n<p>It's clear that <code>main</code> needs to be a file global symbol, but <code>for0</code> and <code>if01</code> (both poor names, as has already been noted) do not need to be. In NASM, we can designate <a href=\"https://nasm.us/doc/nasmdoc3.html#section-3.9\" rel=\"noreferrer\">local labels</a> by prefixing those labels with a single period so instead of <code>for0</code> we could use <code>.for0</code>. The advantage to doing this is that we can reuse a label in another function without having to worry about collision.</p>\n<h2>Avoid unconditional jumps where practical</h2>\n<p>The x86 processor does its best to figure out which instruction will be executed next. It has all kinds of things to make that happen, including multi-level cacheing and branch prediction. It does that to try to make software run faster. You can help it by avoiding branching at all where practical, and especially by avoiding unconditional jumps. Thinking carefully about it, we can often do this by restructuring the code. Here's the original code:</p>\n<pre><code> test rdx, rdx\n jne if01\n ; sum = sum + i\n add rsi, rcx\n jmp if0\n\nif01:\n ; i % 5 == 0\n mov rax, rcx\n mov rdx, 0\n mov r9, 5\n div r9\n test rdx, rdx\n jne if0\n ; sum = sum + i\n add rsi, rcx\n jmp if0\n ; }\nif0:\n inc rcx\n cmp rcx, 1000\n jl for0\n</code></pre>\n<p>We can rewrite this like this:</p>\n<pre><code> test rdx, rdx\n je .accumulate\n ; i % 5 == 0\n mov rax, rcx\n mov rdx, 0\n mov r9, 5\n div r9\n test rdx, rdx\n jne .next\n.accumulate:\n ; sum = sum + i\n add rsi, rcx\n ; }\n.next:\n inc rcx\n cmp rcx, 1000\n jl .for0\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-20T17:17:24.860",
"Id": "500285",
"Score": "6",
"body": "Unconditional jumps aren't necessarily bad. In fact, they're more likely to be predicted properly than conditional jumps. But in this case, you are exactly right, the code should be restructured to simply fall through. In general, a good rule of thumb is that the expected case should be the fall-through case, and the unexpected case should be the one that takes a branch. When writing large swaths of assembly code, readability and performance concerns dovetail nicely: avoid as many branches as reasonably possible."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-21T19:14:29.630",
"Id": "500362",
"Score": "2",
"body": "I wonder if it might be worthwhile to use `cmov` instructions to avoid having a branch at all in that part of the code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-21T19:16:27.397",
"Id": "500364",
"Score": "1",
"body": "@DanielSchepler: That is a very good suggestion."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-21T21:05:29.033",
"Id": "500395",
"Score": "1",
"body": "Regarding \"there is no `e8` register\": I thought that was what `r8d` would be. (However, in my test with GNU asm, `xor %r8, %r8` and `xor %r8d, %r8d` ended up having the same length.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-21T23:16:33.413",
"Id": "500416",
"Score": "0",
"body": "The Q&A you linked about the `write` syscall only covers strings. To also / instead cover formatting integers into strings of decimal digits, [How do I print an integer in Assembly Level Programming without printf from the c library?](https://stackoverflow.com/a/46301894) is NASM for x86-64 Linux."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-21T23:18:45.667",
"Id": "500417",
"Score": "1",
"body": "@DanielSchepler: You're correct, the 32-bit version of `r8` is `r8d`. It doesn't make xor-zeroing smaller because it still needs a REX prefix for the register number. But you should still use `xor r8d, r8d` because Silvermont doesn't recognize `xor r8,r8` as a \"zeroing idiom\" independent of the old value, but 32-bit operand-size xor (which all compilers always use) is optimal on every CPU that treats any kind of zeroing idiom specially. See [What is the best way to set a register to zero in x86 assembly: xor, mov or and?](https://stackoverflow.com/q/33666617)"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-20T17:07:30.043",
"Id": "253707",
"ParentId": "253680",
"Score": "13"
}
},
{
"body": "<p>A few quick notes on your implementation choices, and how I'd approach it:</p>\n<p>You don't need 64-bit operand-size for <code>div</code> when your numbers only go up to 1000, that's significantly slower than <code>div r32</code> on Intel before Ice Lake: I explained the details in another Code Review: <a href=\"https://codereview.stackexchange.com/questions/204902/checking-if-a-number-is-prime-in-nasm-win64-assembly/204965#204965\">Checking if a number is prime in NASM Win64 Assembly</a>.</p>\n<p>(And in general for other instructions, <code>test edx, edx</code> would save code size there. Even with 64-bit numbers and 64-bit <code>div</code>, <code>i % 5</code> will always fit in 32 bits so it's safe to ignore the high 32. See\n<a href=\"https://stackoverflow.com/questions/38303333/the-advantages-of-using-32bit-registers-instructions-in-x86-64\">The advantages of using 32bit registers/instructions in x86-64</a> - it's the default operand-size for x86-64, not needing any machine-code prefixes. For efficiency, use it unless you actually need 64-bit operand-size for that specific instruction, and implicit zero-extension to 64-bit won't do what you need.\nDon't spend extra instructions, though; 64-bit operand-size is often needed, e.g. for pointer increments.)</p>\n<p>Of course, for division by compile-time constants, <code>div</code> is a slow option that compilers avoid entirely, instead using a fixed-point multiplicative inverse. Like in <a href=\"https://stackoverflow.com/questions/41183935/why-does-gcc-use-multiplication-by-a-strange-number-in-implementing-integer-divi\">Why does GCC use multiplication by a strange number in implementing integer division?</a> on SO, or <a href=\"https://codereview.stackexchange.com/questions/142842/integer-to-ascii-algorithm-x86-assembly\">this code review</a>.</p>\n<hr />\n<p>Also, you don't need to divide at all if you use down-counters that you reset to 3 or 5 when they hit 0 (and/or unrolling) to handle the 3, 5 pattern, like FizzBuzz - see <a href=\"https://stackoverflow.com/questions/28334034/fizzbuzz-in-assembly-segmentation-fault/37494090#37494090\">this Stack Overflow answer</a> where I wrote a large tutorial about such techniques, which I won't repeat here. Unlike FizzBuzz, you only want to count a number once even if it's a multiple of both 3 and 5.</p>\n<p>You could just unroll by 15 (so the pattern fully repeats) and hard-code something like</p>\n<pre><code>.unroll15_loop:\n ; lets say ECX=60 for example\n add eax, ecx ; += 60\n lea eax, [rax + rcx + 3] ; += 63\n lea eax, [rax + rcx + 5] ; += 65\n lea eax, [rax + rcx + 6] ; += 66\n ...\n add ecx, 15\n cmp ecx, 1000-15\n jbe .unroll15_loop\n ; handle the last not full group of 15 numbers\n</code></pre>\n<p>Or apply some math and instead of actually looking at every number, use a closed-form formula for the sum of the multiples of 3 and 5 in a 15-number range, offset by <code>i * nmuls</code> where <code>i</code> is the start of your range, and <code>nmuls</code> is the number of multiples.</p>\n<p>e.g. in the <code>[60, 75)</code> range, we have 60, 63, 65, 66, 69, 70, 72. So that's 8 of the 15 numbers. So it's like <code>[0, 15)</code> but <code>+ 8*60</code>. Either do the 0..14 part by hand, or with a loop and remember the result. (Project Euler is about math as much as programming; it's up to you how much math you want to do vs. how much brute force you want your program to do.)</p>\n<p>Conveniently, 8 happens to be one of the scale-factors that x86 addressing modes support, so we can even do</p>\n<pre><code>lea eax, [rax + rcx*8 + 0 + 3 + 5 + 6 + 9 + 10 + 12]\n</code></pre>\n<p>(3+5+6+... is a constant expression so the assembler can do it for you at assemble time, producing a <code>[reg + reg*scale + disp8]</code> addressing mode. Unfortunately that 3-component LEA has 3-cycle latency on Intel CPUs, and that loop-carried dependency will be the bottleneck for the loop. So it would actually be more efficient to use a separate <code>add</code> instruction.)</p>\n<p>And of course we've reduced this to basically a sum of a linearly increasing series, and could apply Gauss's formula (<code>n * (n+1) / 2</code>) for a closed form over the whole-interval range, just having to handle the cleanup of <code>n%15</code> for the numbers approaching <code>n</code>. BTW, clang knows how to turn a simple for loop doing <code>sum += i;</code> into the closed form, arranging it to avoid overflow of the temporary before dividing by 2. (right shift). Matt Godbolt's CppCon2017 talk <a href=\"https://youtu.be/bSkpMdDe4g4\" rel=\"noreferrer\">“What Has My Compiler Done for Me Lately? Unbolting the Compiler's Lid”</a> uses that as an example. See also <a href=\"https://stackoverflow.com/questions/38552116/how-to-remove-noise-from-gcc-clang-assembly-output\">https://stackoverflow.com/questions/38552116/how-to-remove-noise-from-gcc-clang-assembly-output</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-21T22:32:36.193",
"Id": "500410",
"Score": "0",
"body": "The remainder part could be implemented based on a simple table lookup. Especially if you're doing a count down to 0; but even if you're doing a count up to the limit, you could have the table with entries for the number of multiples of the base and the constant term to use."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-21T22:47:29.713",
"Id": "500411",
"Score": "0",
"body": "@DanielSchepler: Oh, the 0..14 elements of cleanup? Yeah, might as well just look up the answer instead of a jump table into a series of `lea` and NOP instructions or something. Although if you make every LEA the same length, you can do a computed jump (like `end_of_block - remaining * 4` instead of loading from a table of pointers, so no static data involved. That might be fun, but yeah the efficient option would be a table."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-20T19:18:05.153",
"Id": "253716",
"ParentId": "253680",
"Score": "11"
}
},
{
"body": "<h1>Use conditional move instructions where appropriate</h1>\n<p>To extend the discussion in <a href=\"https://codereview.stackexchange.com/a/253707/232026\">the answer by @Edward</a>: if you can use conditional move instructions, that will further reduce the amount of branching and thus help the processor.</p>\n<p>If you combine with the suggestion to maintain modulo 3 and modulo 5 counters instead of doing division, then an outline of the main loop body could look like this (untested, though):</p>\n<pre><code>%define mod3_reg r8\n%define mod5_reg r9\n%define zero_reg r10\n%define count_reg rcx\n%define accum_reg rsi\n%define addend_reg rdi\n%define limit 1000\n\n ...\nmainloop:\n xor addend_reg, addend_reg\n inc mod3_reg\n cmp mod3_reg, 3\n cmove addend_reg, count_reg\n cmove mod3_reg, zero_reg\n inc mod5_reg\n cmp mod5_reg, 5\n cmove addend_reg, count_reg\n cmove mod5_reg, zero_reg\n add accum_reg, addend_reg\n\n inc count_reg\n cmp count_reg, limit\n jl mainloop\n</code></pre>\n<p>(Note that in order to match an initial value of 0 for the counter, you would need to initialize <code>mod3_reg</code> to 2 and <code>mod5_reg</code> to 4. If you adjust to start with 1, on the other hand, you could initialize both to 0 which would be a bit simpler.)</p>\n<hr />\n<p>Do also note that according to some comments by @PeterCordes, there may be issues with <code>cmov</code> creating enough extra dependencies in the loop that it might not actually turn out to be worth it. This would be a case where, if you cared a lot about performance, running a benchmark on your target machine would be important.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-21T20:23:56.427",
"Id": "500380",
"Score": "1",
"body": "Instead of `inc`, `cmp` it would be simpler and shorter to preload with 3 and 5 and count down with `dec`. You could then directly use `cmove` to reload."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-21T20:41:56.050",
"Id": "500382",
"Score": "0",
"body": "Sure, that's definitely a possibility. Then, you could take advantage of the fact that `dec` preloads flags for you and avoid the `test` or `cmp`. In the end, I ended up doing it this way for a slight improvement in readability - with the count down, it's a bit more complex to describe what the registers represent."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-21T22:58:36.153",
"Id": "500413",
"Score": "0",
"body": "If you're going for simplicity not performance, you can increment your mod3 and mod5 regs *after* their cmp/cmov (next to count_reg), so everything can start at zero. Or with down-counters, they'd just start at 3 and 5 for counter=0, same as their reset values."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-21T23:04:59.293",
"Id": "500414",
"Score": "1",
"body": "However, this branchless strategy is probably only good for *very* low limits; Most modern branch predictors will learn the pattern quickly. But you're always paying a high cost every time through the loop for front-end throughput (12 uops assuming single-uop CMOVE (Intel Broadwell and later, or AMD since forever) and macro-fusion of cmp/jl, so on a 4-wide pipeline like Intel before Ice Lake, that takes 3 cycles per iteration to issue. With down-counters, that could get down to 10 uops, which Zen can issue in 2 cycles."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-21T23:10:00.340",
"Id": "500415",
"Score": "0",
"body": "Then you're up against the 2-cycle loop-carried dependency chain you've created with inc/cmov on the mod3 and 5 counters. (Or worse, 3-cycle on older Intel with 2-uop cmov). Out-of-order exec can hide some of that if the loop trip count is low and the code after doesn't all depend on the result. But otherwise (for 1k iters) some branch misses early will pay for themselves overall. At least the dep chain through the accum_reg itself is only 1 cycle. (GCC [sometimes pessimizes branchless C](//stackoverflow.com/q/28875325) to make cmov part of longer dep chains, like prepare 2 possible vals.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-21T23:22:46.247",
"Id": "500418",
"Score": "0",
"body": "And BTW, you don't need to use 64-bit operand-size for the counters; edx and edi would be fine for the mod counters, allowing those insns to avoid REX prefixes, even if you did want to run this for a limit too large to fit in ECX. The mod regs could even be 8-bit so you can increment or decrement them both at once, except then you can't use 8-bit cmov and partial regs suck. (Chris Jester-Young suggested that in [16-bit FizzBuzz in x86 NASM assembly](https://codereview.stackexchange.com/a/56896) where it's specifically useful to know when both counters become zero at once)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-21T23:32:29.770",
"Id": "500420",
"Score": "0",
"body": "@PeterCordes OK, I've added a section at the tail acknowledging that benchmarking would be important if you want to see whether the change to `cmov` actually helps or hurts overall performance."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-21T19:58:52.093",
"Id": "253753",
"ParentId": "253680",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "253707",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-19T22:41:18.777",
"Id": "253680",
"Score": "25",
"Tags": [
"programming-challenge",
"assembly",
"x86"
],
"Title": "x86-64 Assembly - Sum of multiples of 3 or 5"
}
|
253680
|
<p>Extreme script newbie here, so please go easy on me!</p>
<p>I wrote a script to install zsh on a number of different Linux distributions. But since I'm so new at this, I'm piecing a lot of different things together and I doubt it's as efficient and tight as possible. Any suggestions are welcome. Thank you!</p>
<pre><code>#!/bin/bash
export ZSHUSER=$USER
if [ -f /etc/os-release ]; then
. /etc/os-release
OS=$NAME
VER=$VERSION_ID
elif type lsb_release >/dev/null 2>&1; then
OS=$(lsb_release -si)
VER=$(lsb_release -sr)
fi
echo "Creating fonts directory"
cd /tmp && mkdir fonts && cd $_
echo "Downloading fonts"
wget https://github.com/romkatv/powerlevel10k-media/raw/master/MesloLGS%20NF%20Regular.ttf
wget https://github.com/romkatv/powerlevel10k-media/raw/master/MesloLGS%20NF%20Bold.ttf
wget https://github.com/romkatv/powerlevel10k-media/raw/master/MesloLGS%20NF%20Italic.ttf
wget https://github.com/romkatv/powerlevel10k-media/raw/master/MesloLGS%20NF%20Bold%20Italic.ttf
echo "Entering sudo mode to copy fonts"
if [[ $NAME = "Fedora" ]]; then
sudo su - <<EOF
dnf install -y git zsh zsh-autosuggestions zsh-syntax-highlighting
cd /usr/share/fonts/ && mkdir MesloMGS
cp /tmp/fonts/*.ttf /usr/share/fonts/MesloMGS
fc-cache
rm -r /tmp/fonts
scp -v /mnt/E/Linux/zsh/$NAME/aliasrc $HOME
chown $USER:$USER $HOME/aliasrc
su $USER
EOF
elif [[ $NAME = "void" ]]; then
sudo su - <<EOF
xbps-install -y git zsh zsh-autosuggestions zsh-syntax-highlighting
cp /tmp/fonts/*.ttf /usr/share/fonts/TTF
fc-cache
rm -r /tmp/fonts
scp -v /mnt/E/Linux/zsh/$NAME/aliasrc $HOME
chown $USER:$USER $HOME/aliasrc
su $USER
EOF
elif [[ $NAME = "Debian" ]] || [[ $NAME = "Ubuntu" ]] || [[ $NAME = "Linux Mint" ]]; then
sudo su - <<EOF
apt install -y git zsh zsh-autosuggestions zsh-syntax-highlighting
cd /usr/share/fonts/truetype && mkdir MesloMGS
cp /tmp/fonts/*.ttf /usr/share/fonts/truetype/MesloMGS
fc-cache
rm -r /tmp/fonts
scp -v /mnt/E/Linux/zsh/Debian/aliasrc $HOME
chown $USER:$USER $HOME/aliasrc
su $USER
EOF
elif [[ $NAME = "CentOS Linux" ]]; then
sudo su - <<EOF
yum install -y git zsh zsh-syntax-highlighting
cd /usr/share/fonts/ && mkdir MesloMGS
cp /tmp/fonts/*.ttf /usr/share/fonts/MesloMGS
fc-cache
rm -r /tmp/fonts
scp -v /mnt/E/Linux/zsh/CentOS/aliasrc $HOME
chown $USER:$USER $HOME/aliasrc
git clone https://github.com/zsh-users/zsh-autosuggestions /usr/share/zsh-autosuggestions/zsh-autosuggestions.zsh
su $USER
EOF
else
echo "Operating system not identified"
pause
fi
mkdir ~/powerlevel10k && cd ~/powerlevel10k
git clone --depth=1 https://github.com/romkatv/powerlevel10k.git ~/powerlevel10k
echo 'source ~/powerlevel10k/powerlevel10k.zsh-theme' >> ~/.zshrc
echo "opening terminal to configure zsh"
if [[ $NAME = "Ubuntu" ]] || [[ $NAME = "CentOS Linux" ]] || [[ $NAME = "Linux Mint" ]]; then
gnome-terminal -q -- zsh
read -p "press enter to resume"
elif [[ $NAME = "Fedora" ]]; then
mate-terminal -e zsh
elif [[ $NAME = void ]]; then
qterminal -e zsh
elif [[ $NAME = Debian ]]; then
xfce4-terminal -e zsh
fi
sudo su - <<EOF
echo "copying .zshrc file"
scp -v /mnt/E/Linux/zsh/.zshrc $HOME
chown $USER:$USER $HOME/.zshrc
su $USER
EOF
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-20T08:07:35.850",
"Id": "500264",
"Score": "0",
"body": "In a professional environment, we much prefer stock bash rather than zsh, because we can just about guarantee that everyone can use it and that it is installed on the majority of systems by default. Zsh just brings unnecessary complications that we could really do without. e.g. the majority of shell programs run in bash and running them in zsh could break them in unexpected ways due to the differences in command output in zsh. I'm not arguing whether zsh or bash is better, just that bash is much more common and that zsh should be left for toys like macbooks rather than pro-tools like linux."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-20T19:47:05.293",
"Id": "500291",
"Score": "0",
"body": "I appreciate that point of view. However, I'm just a college student looking for reasons to write scripts just to practice and get some practical application from it. Thanks."
}
] |
[
{
"body": "<blockquote>\n<pre><code>if [[ $NAME = "Fedora" ]]; then\nelif [[ $NAME = "void" ]]; then\nelif [[ $NAME = "Debian" ]] || [[ $NAME = "Ubuntu" ]] || [[ $NAME = "Linux Mint" ]]; then\n</code></pre>\n</blockquote>\n<p>That looks like a candidate for <code>case "$NAME" in</code>. However, instead of changing that, let's look at what we're doing:</p>\n<blockquote>\n<pre><code>if [[ $NAME = "Fedora" ]]\nthen\n dnf install -y git zsh zsh-autosuggestions zsh-syntax-highlighting\n</code></pre>\n</blockquote>\n<p>Ah, so we're using that to determine which package manager is in use. It might be better to just test that directly:</p>\n<blockquote>\n<pre><code>if [ -x /usr/bin/dnf ]\nthen\n dnf install\n</code></pre>\n</blockquote>\n<p>That has the added benefit that it's plain POSIX shell, not requiring Bash.</p>\n<hr />\n<p>Hang on, where did that <code>$NAME</code> come from? Let's look:</p>\n<blockquote>\n<pre><code>if [ -f /etc/os-release ]; then\n . /etc/os-release\n OS=$NAME\n VER=$VERSION_ID\nelif type lsb_release >/dev/null 2>&1; then\n OS=$(lsb_release -si)\n VER=$(lsb_release -sr)\nfi\n</code></pre>\n</blockquote>\n<p>Oh dear, it looks like <code>NAME</code> is assigned in only one of those two paths, and we actually wanted to be using <code>OS</code> (or assigning to <code>NAME</code> and <code>VERSION_ID</code> in the <code>elif</code> branch, and getting rid of <code>OS</code> and <code>VER</code>).</p>\n<p>This is why it's a good idea to <code>set -u</code>, so that you get an error when expanding an undefined variable.</p>\n<hr />\n<blockquote>\n<pre><code>echo "Operating system not identified"\npause\n</code></pre>\n</blockquote>\n<p>That should be <code>echo >&2</code>, since it's an error message. What's <code>pause</code>? It's certainly not a common tool, and you probably just want to <code>exit 1</code> at that point anyway.</p>\n<hr />\n<p>Not a big fan of copying those font files into <code>/usr/share</code> (that should be only for files under control of the package manager). That's what <code>/usr/local</code> is for.</p>\n<hr />\n<p>Why are we using <code>scp</code> for a local copy? Just use plain <code>cp</code> and reduce the dependencies.</p>\n<hr />\n<p>Many platforms have a configurable preferred terminal emulator, so use that first if it exists. For example <code>/usr/bin/x-terminal-emulator</code> on Debian.</p>\n<hr />\n<p>On the use of <code>sudo</code> and <code>su</code> (not sure why you feel the need to double up like that!), I'd recommend turning this the other way around, and having a script that you must be root to run, but which drops privileges for the parts where that's possible. That's certainly better than being repeatedly asked for passwords (in many <code>sudo</code> configurations), which isn't something you want to be training users to do.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-02T15:47:04.430",
"Id": "255511",
"ParentId": "253684",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-20T00:59:13.980",
"Id": "253684",
"Score": "3",
"Tags": [
"bash",
"linux"
],
"Title": "Bash script to install zsh on different distributions"
}
|
253684
|
<p>I'm a long-time Java programmer, but recently I decided to give Kotlin a try. So far, I'm loving the language features, it feels much more expressive than what I'm used to. As practice, I wrote this function that produces a repeatable sequence of prime numbers (i.e. the sequence can be iterated multiple times, and will make use of results from past iterations to speed up future iterations). It feels pretty solid to me, but I'm wondering how it would look to a Kotlin veteran - are there language features that I'm not taking full advantage of, or conventions that I should be following?</p>
<p>One question I have in particular is regarding top-level function vs. subclass; here I chose to implement a top-level function <code>primeSequence(): Sequence<Long></code> that returns an <code>object</code>, but I could have just about as easily implemented a class <code>PrimeSequence : Sequence<Long></code>. Is there a good rule of thumb for when to use one or the other?</p>
<pre class="lang-kotlin prettyprint-override"><code>fun primeSequence(): Sequence<Long> = object: Sequence<Long> {
private val knownPrimes: MutableList<Long> = arrayListOf(2L, 3L)
private fun Long.isMultipleOf(n: Long) = (this%n == 0L)
private fun Long.isPrime() = knownPrimes
.takeWhile { it*it <= this }
.none { this.isMultipleOf(it) }
override fun iterator(): Iterator<Long> = object: Iterator<Long> {
private var lastPrime: Long? = null
override fun hasNext() = true
override fun next(): Long {
val nextPrime = when(val lastPrime = this.lastPrime) {
null -> 2L
2L -> 3L
else -> {
if (knownPrimes.last() > lastPrime ) {
knownPrimes[knownPrimes.binarySearch(lastPrime) + 1]
} else {
val np = generateSequence(lastPrime+2) { it+2 }
.first { it.isPrime() }
knownPrimes.add(np)
np
}
}
}
this.lastPrime = nextPrime
return nextPrime
}
}
}
</code></pre>
|
[] |
[
{
"body": "<p>I don't like the idea of returning an inline object that inherits <code>Sequence<Long></code> like this. Kotlin has several features to help you build stuff, including one for sequences.</p>\n<p>Using the fantastic power of the <code>sequence</code> builder in Kotlin, which underneath the surface is using a <a href=\"https://kotlinlang.org/docs/reference/coroutines/basics.html\" rel=\"nofollow noreferrer\">suspendable function</a> internally, we can <code>yield</code> numbers one by one instead of implementing an <code>Iterator</code>.</p>\n<p>We can rewrite your code to use an outer <code>object</code> to keep the global state in, and then use a function to generate the sequence.</p>\n<pre><code>object Primes {\n private val knownPrimes: MutableList<Long> = mutableListOf(2L, 3L)\n private fun Long.isMultipleOf(n: Long) = (this % n == 0L)\n\n private fun Long.isPrime() = knownPrimes\n .takeWhile { it * it <= this }\n .none { this.isMultipleOf(it) }\n\n fun sequence(): Sequence<Long> {\n var lastPrime: Long? = null\n return sequence {\n while (true) {\n val nextPrime = when(val actualLastPrime = lastPrime) {\n null -> 2L\n 2L -> 3L\n else -> {\n if (knownPrimes.last() > actualLastPrime) {\n knownPrimes[knownPrimes.binarySearch(actualLastPrime) + 1]\n } else {\n val np = generateSequence(actualLastPrime + 2) { it+2 }\n .first { it.isPrime() }\n knownPrimes.add(np)\n np\n }\n }\n }\n lastPrime = nextPrime\n yield(nextPrime)\n }\n }\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-27T04:35:52.173",
"Id": "500815",
"Score": "0",
"body": "Nice, thanks for the tip! I haven't played around much with coroutines yet. Are they pretty widely used in Kotlin or is it more of a niche thing?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-27T13:07:37.163",
"Id": "500827",
"Score": "0",
"body": "@KevinK That very much depends on the application, and how well the developer knows about them. However, you don't really need to know much about coroutines in order to use the `sequence` builder."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-20T20:09:34.733",
"Id": "253718",
"ParentId": "253690",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "253718",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-20T04:26:05.093",
"Id": "253690",
"Score": "3",
"Tags": [
"beginner",
"primes",
"kotlin"
],
"Title": "Prime number sequence supporting repeated iteration"
}
|
253690
|
<p>Banknotes are given specifically 100, 50, 20, 10, 5, 2, 1. Required to check and find out: What is the maximum possibility to keep these individually into the given integer value.
For example:</p>
<pre><code>input: 576
output: 576
5 nota(s) de R$ 100,00
1 nota(s) de R$ 50,00
1 nota(s) de R$ 20,00
0 nota(s) de R$ 10,00
1 nota(s) de R$ 5,00
0 nota(s) de R$ 2,00
1 nota(s) de R$ 1,00
</code></pre>
<p>I have solved this problem by following this strategy-></p>
<pre><code>#include <stdio.h>
int main(){
int number, count = 0, occupied = 0, number_update, i;
int a = 100;
scanf("%d",&number);
number_update = number;
printf("%d\n",number);
//Getting the number that can be stored maximum in the given integer.
for (i = 0; i < 7; i++){
count = 0;
while (a <= number_update){
count++;
occupied = occupied + a;
number_update = number_update - a;
}
printf("%d nota(s) de R$ %d,00\n",count,a);
number_update = number - occupied;
if (i == 0){
a = a-50;
}
else if (i == 1){
a = a-30;
}
else if (i == 2){
a = a-10;
}
else if (i == 3){
a = a-5;
}
else if (i == 4){
a = a-3;
}
else {
a = a-1;
}
}
return 0;
}
</code></pre>
<p>I am here for:
Would you propose any simplification from my existing solution?
Will I face any problem with some conditions?
The way I followed to solve this problem. Is it ok or not?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-20T15:49:21.873",
"Id": "500280",
"Score": "0",
"body": "Sorry sir. I made a little mistake. 30 is not in that list. lists are 100, 50, 20, 10, 5, 2, 1"
}
] |
[
{
"body": "<h1>Don't use the <code>for</code>-<code>case</code> antipattern</h1>\n<p>You are using the <a href=\"https://en.wikipedia.org/wiki/Loop-switch_sequence\" rel=\"nofollow noreferrer\"><code>for</code>-<code>case</code> antipattern</a>, which you should almost always avoid. Instead, find some way to simplify your code. For example, instead of hardcoding the denominations in the <code>if</code>-statements, put them in an array:</p>\n<pre><code>static const int denominations[] = {100, 50, 20, 10, 5, 2, 1};\nstatic const int n_denominations = sizeof denominations / sizeof *denominations;\n</code></pre>\n<p>Then use it like so:</p>\n<pre><code>for (int i = 0; i < n_denominations; i++) {\n count = 0;\n\n while (number >= denominations[i]) {\n count++;\n number -= denominations[i];\n }\n\n printf("%d nota(s) de R$ %d,00\\n", count, denominations[i]);\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-21T04:28:41.633",
"Id": "500311",
"Score": "0",
"body": "Ok, sir, I am trying to follow this strategy from my next challenges. Thank you a ton for your worthy suggestions. Keep up the good works."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-20T16:47:12.323",
"Id": "253706",
"ParentId": "253691",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "253706",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-20T04:55:09.160",
"Id": "253691",
"Score": "3",
"Tags": [
"c"
],
"Title": "Maximum possibility of banknotes to keep into the given integer value"
}
|
253691
|
<p>Very new to spring and spring boot here... What would be the best practice for calling two async functions one after another? If I have three functions like this :</p>
<pre><code>@Async
public CompletableFuture<String> function1(String input){
return CompletableFuture.completedFuture("result1");
}
@Async
public CompletableFuture<String> function2(String input){
return CompletableFuture.completedFuture("result2");
}
@Async
public CompletableFuture<String> function3(String input){
return CompletableFuture.completedFuture("result3");
}
</code></pre>
<p>All of them do pretty heavy and slow tasks, so, I'd like them to be running on a separate thread. I also read that it's a bad practice in spring boot to run your own completable futures. ( read on this article <a href="https://stackoverflow.com/questions/533783/why-is-spawning-threads-in-java-ee-container-discouraged">https://stackoverflow.com/questions/533783/why-is-spawning-threads-in-java-ee-container-discouraged</a> ). So, this is what I came up with:</p>
<pre><code>CompletableFuture
.supplyAsync(() -> function1(initInput))
.thenSupplyAsync( output1 -> function2(output1.get()))
.thenSupplyAsync( output2 -> function3(output2.get()))
.exceptionally((output, ex ) -> handleException)
</code></pre>
<p>Is this a good coding practice? Or is there a better more recommended way to get it done?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-23T09:39:34.000",
"Id": "500509",
"Score": "0",
"body": "Regarding your reference to SO: Spring Boot is *not* a JavaEE container. Maybe similar rules apply to Spring as well (don't know, I don't use it) but statements about JEE containers do not refer to Spring."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-24T05:20:53.620",
"Id": "500592",
"Score": "0",
"body": "oh okay, but still spring does manages thread on it's own, they have their own `@Async` annotations, so, is the way I wrote code correct, or, should I write it some other way?"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-20T10:51:15.933",
"Id": "253696",
"Score": "1",
"Tags": [
"java",
"asynchronous",
"spring"
],
"Title": "What is the best way to call two async functions, one after another in spring?"
}
|
253696
|
<p>I wrote my own Discord Bot which is taking screenshot of a specific website. This scrip is very simple and thought it should work fast, but it isn't. I read a lot, and I think I'm not able to improve it. Today my driver.get(URL) not working fast- i think the website is a little broken. But yesterday I get a result of 10 seconds waiting to get one screenshot. Is there possibility to make it faster?</p>
<pre><code>
def taking_screenshot_clearoutsite(new_folder_path, folder, city_coordinates, driver, day=None):
(latitude, longitude), city_name = city_coordinates
url = f'https://clearoutside.com/forecast/{latitude}/{longitude}'
driver.get(url)
# driver.set_window_position(0, 0)
# driver.set_window_size(1500, 2000)
day_now = datetime.datetime.now().date().strftime("%d/%m/%Y")
day_now_obj = datetime.datetime.strptime(day_now, '%d/%m/%Y')
"""testing window size"""
# size = driver.get_window_size()
# print("Window size: width = {}px, height = {}px".format(size["width"], size["height"]))
try:
driver.find_element_by_xpath("//*[@aria-label='dismiss cookie message']").click()
# time.sleep(2)
except WebDriverException:
pass
if day:
if isinstance(day, int) and int(day) == datetime.datetime.now().day:
pass
elif isinstance(day, int) and int(day) != datetime.datetime.now().day:
searching_day_index = int(day) - day_now_obj.day
try:
driver.find_element_by_xpath \
(f"//div[@id='day_{searching_day_index}']//div[@class='fc_day_date'][contains(text(),"
f"'{day}')]").click()
except WebDriverException:
driver.find_element_by_xpath(f"// div[contains(text(),'{day}')]").click()
"""pause 1 second to let page loads"""
time.sleep(1)
"""save screenshot and return name of it to crop"""
screen_file_name = screenshot(driver, folder)
file = Image.open(screen_file_name)
top_add = searching_day_index * 100
bottom_add = searching_day_index * 100
final_photo = cropping_file(file, new_folder_path, CLEAROUTSITE_CROP_PARAM,
city_day=(city_name, int(day)), top_add=top_add, bottom_add=bottom_add)
os.remove(screen_file_name)
return final_photo
else:
try:
driver.find_element_by_xpath(f"//div[@id='day_{0}']//div[@class='fc_day_date'][contains(text(),"
f"'{datetime.datetime.now().day}')]").click()
except WebDriverException:
pass
"""pause 1 second to let page loads"""
time.sleep(1)
"""save screenshot and return name of it to crop"""
screen_file_name = screenshot(driver, folder)
file = Image.open(screen_file_name)
final_photo = cropping_file(file, new_folder_path, CLEAROUTSITE_CROP_PARAM, city_day=(city_name, day))
os.remove(screen_file_name)
return final_photo
driver = start_driver()
(city_coordinates), country = find_city_coordinates('elblag')
taking_screen_shot_clearoutsite('Z:\Python\Rozne_programy\Discord\saving_to_disc_task\clear\elblag',
'Z:\Python\Rozne_programy\Discord\saving_to_disc_task',
city_coordinates, driver, 21)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-20T12:03:26.037",
"Id": "500273",
"Score": "2",
"body": "`driver.get(url)` depends on the speed of your internet connection and the status of the server, so, it's really out of your hand..."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-20T11:48:20.127",
"Id": "253699",
"Score": "2",
"Tags": [
"python",
"python-3.x",
"web-scraping",
"selenium"
],
"Title": "Discord Bot Python. Selenium screenshots"
}
|
253699
|
<pre class="lang-hs prettyprint-override"><code>checkIfMultiple x [] = False
checkIfMultiple x (n:ns) = x `mod` n == 0 || checkIfMultiple x ns
findMultiples limit ns = [x | x <- [0..limit], checkIfMultiple x ns]
sumMultiples limit ns = sum (findMultiples limit ns)
</code></pre>
<p><code>sumMultiples 999 [3, 5]</code></p>
<p>Things I am curious about:</p>
<ol>
<li><p>Passing down <code>limit</code> and <code>ns</code> from <code>sumMultiples</code> to <code>findMultiples</code> might be redundant. I was wondering, if I could somehow use composition here or some other shortcut.</p>
</li>
<li><p>What is the convention regarding writing out the type in Haskell? Is it always recommended?</p>
</li>
</ol>
<p>Any other suggestion is appreciated, thank you.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-21T09:26:28.297",
"Id": "500331",
"Score": "1",
"body": "Is the O(1) solution intentionally avoided?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-21T09:35:14.607",
"Id": "500333",
"Score": "1",
"body": "BTW it would be best to include the specification of the project Euler problem 1 in your question if you implemented the problem solution as stated in project euler. Since you have a generalized solution, you should provide your generalized specification of the problem. In other words, what is it that is generalized compared to the original problem?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-21T09:38:24.133",
"Id": "500334",
"Score": "0",
"body": "Oh it's more generalized then I thought. Well then my first comment should have been why O(len(ns)) solution is avoided and instead O(limit * len(ns)) is used?"
}
] |
[
{
"body": "<p>If a helper function like <code>findMultiples</code> is not itself particularly interesting, then a standard way of passing down arguments is to move them into a <code>where</code> clause which will have available any bindings created by the pattern match:</p>\n<pre><code>sumMultiples limit ns = sum findMultiples\n where findMultiples = [x | x <- [0..limit], checkIfMultiple x ns]\n</code></pre>\n<p>Alternatively, when a single argument is involved, composition works pretty well, and in your example, you can use composition to pass along the last argument (<code>ns</code>):</p>\n<pre><code>sumMultiples limit = sum . findMultiples limit\nfindMultiples limit ns = [x | x <- [0..limit], checkIfMultiple x ns]\n</code></pre>\n<p>However, extending this to two arguments starts to get confusing. The following works, but it's pretty hard to read:</p>\n<pre><code>sumMultiples = (.) sum . findMultiples\nfindMultiples limit ns = [x | x <- [0..limit], checkIfMultiple x ns]\n</code></pre>\n<p>The usual convention for types in Haskell is to annotate all top-level bindings with their type signatures. (Generally, bindings in <code>where</code> and <code>let</code> clauses aren't annotated, unless the types are very complicated and/or the compiler needs some help.)</p>\n<p>There are several reasons for this. First, type signatures provide succinct documentation of how a function is meant be used. To the extent that top-level bindings provide the "interface" for your code, the type signatures document that interface. Second, type signatures assist the typechecker in producing sensible error messages and better localizing type errors. If all types are inferred, the compiler can construct extremely complicated and unexpected types which can result in error messages that don't make any sense or appear in the "wrong place", far away from the actual error in the code. For example, in your code, if you mix up the argument order for <code>findMultiples</code> in <code>sumMultiples</code>:</p>\n<pre><code>sumMultiples limit ns = sum (findMultiples ns limit)\n</code></pre>\n<p>then the program type checks fine, and when you try to calculate the answer:</p>\n<pre><code>> sumMultiples 999 [3,5]\n</code></pre>\n<p>you get the error <code>Non type-variable argument in the constraint: Integral [a] (Use FlexibleContexts to permit this)</code>. With proper type signatures:</p>\n<pre><code>checkIfMultiple :: Int -> [Int] -> Bool\ncheckIfMultiple x [] = False\ncheckIfMultiple x (n:ns) = x `mod` n == 0 || checkIfMultiple x ns\n\nfindMultiples :: Int -> [Int] -> [Int]\nfindMultiples limit ns = [x | x <- [0..limit], checkIfMultiple x ns]\n\nsumMultiples :: Int -> [Int] -> Int\nsumMultiples limit ns = sum (findMultiples ns limit)\n ^^ ^^^^^\n</code></pre>\n<p>the error is immediately localized to the bug with sensible error messages that say <code>ns</code> was <code>[Int]</code> when it should have been <code>Int</code>, and <code>limit</code> was <code>Int</code> when it should have been <code>[Int]</code>.</p>\n<p>Annotating just the top-level bindings usually provides enough information for type inference that you get decent, localized error messages, and it's a happy medium between annotating nothing and annotating all bindings. Finally, another reason bindings in <code>where</code> clauses are left unannotated is that it can sometimes be hard to assign them a type signature when polymoprhic functions are involved. For example, in the following function, uncommenting the type signature for <code>go</code> causes a type error, and there's no type signature that will work, unless you enable a GHC extension:</p>\n<pre><code>countValue :: (Eq a) => a -> [a] -> Int\ncountValue target = go\n where -- go :: [a] -> Int\n go (x:xs) | x == target = 1 + go xs\n | otherwise = go xs\n go [] = 0\n</code></pre>\n<p>Here are some other suggestions. There are two pairs of functions (<code>and</code>/<code>all</code> and <code>or</code>/<code>any</code>) that are useful for checking a boolean condition across a list. In this case, <code>checkIfMultiple</code> can be rewritten as:</p>\n<pre><code>checkIfMultiple x ns = any (\\n -> x `mod` n == 0) ns\n</code></pre>\n<p>or:</p>\n<pre><code>checkIfMultiple x = any (\\n -> x `mod` n == 0)\n</code></pre>\n<p>or even:</p>\n<pre><code>checkIfMultiple x = any ((== 0) . mod x)\n</code></pre>\n<p>Personally, I'm not sure that <code>checkIfMultiple</code> and <code>findMultiples</code> deserve their own names. I'd give an evocative name to the following helper:</p>\n<pre><code>d `divides` x = x `mod` d == 0\n</code></pre>\n<p>and write:</p>\n<pre><code>sumMultiples :: [Int] -> Int -> Int\nsumMultiples ds limit = sum [x | x <- [0..limit], any (`divides` x) ds]\n where d `divides` x = x `mod` d == 0\n</code></pre>\n<p>which, to me, can almost be read aloud to describe what it's doing.</p>\n<p>I think @slepic is pointing out that you can sum the multiples of <code>d</code> less than <code>stop</code> using a well known formula for the sum of an "arithmetic sequence". The formula is the average of the first and the last number times the count of numbers, so literally:</p>\n<pre><code>-- sum multiples of d that are less than stop\nmultiples :: Int -> Int -> Int\nmultiples d stop = count * (first + last) `div` 2\n where first = d\n count = (stop-1) `div` d\n last = first + d*(count - 1)\n</code></pre>\n<p>If you write <code>multiples 3 1000 + multiples 5 1000</code> to get the sum of all multiples of 3s and 5s, that overcounts, because multiples of 15 get counted twice, so you need to write:</p>\n<pre><code>euler1 = multiples 3 1000 + multiples 5 1000 - multiples 15 1000\n</code></pre>\n<p>which gives the same answer as <code>sumMultiples 999 [3,5]</code>.</p>\n<p>Of course, as far as I can see, the only way to be sure you didn't screw the clever answer up is to check it with the unclever answer, which kind of defeats the point.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-22T23:29:58.257",
"Id": "253807",
"ParentId": "253703",
"Score": "0"
}
},
{
"body": "<p>I decided to do euler1 before looking at your solution and this is what I came up with:</p>\n<pre><code>euler1 :: [Int] -> Int -> Int\neuler1 ns limit =\n sum .\n filter (\\x -> any (\\n -> x `mod` n == 0) ns) .\n take limit $\n [0..]\n</code></pre>\n<p>So my answers to your questions are:</p>\n<ul>\n<li>Yes, composition helps cut down on the things you have to name, and thus on the things you have to pass along to intermediate functions.</li>\n<li>Haskell loves lists, and [0..] is often a nice starting point for a composition chain.</li>\n<li>Your checkIfMultiple recursion is good, but you will often find a very short synonym for this type of thing (common operations on a list) in base (eg <code>all</code>).</li>\n<li>Types are awesome.</li>\n<li>List comprehensions are amazing but they can sometimes interrupt a good compositional chain, compared with the equivalent filters and/or fmaps.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-10T04:36:43.120",
"Id": "254514",
"ParentId": "253703",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-20T13:20:18.250",
"Id": "253703",
"Score": "2",
"Tags": [
"haskell"
],
"Title": "Generalized solution for project euler #1 in haskell with recursion"
}
|
253703
|
<p>I have been trying to improve my Discord sending webhooks functions where I have multiple dictionaries, as you will see in the code below:</p>
<pre><code>#!/usr/bin/python3
# -*- coding: utf-8 -*-
import time
from threading import Thread
from discord_webhook import DiscordEmbed, DiscordWebhook
DISCORD_POSITIVE = {
"hello": {
"US": "https://discordapp.com/api/webhooks/53235795325234093583/fwewefwefewfw",
"EU": "https://discordapp.com/api/webhooks/53235723523554285313/eafkuhafkjahfkje"
},
"world": {
"US": "https://discordapp.com/api/webhooks/3245252525/dsflgshglksgjdrlskg",
"EU": "https://discordapp.com/api/webhooks/2352352525253/2AW0ufHvn3werwerliweurlk"
},
"test": {
"US": "https://discordapp.com/api/webhooks/45764747457457/1125151aefaefafa",
"EU": "https://discordapp.com/api/webhooks/63456346346346/eliaulökeajealkgjealkjgea"
}
}
DISCORD_NEGATIVE = {
"hello": {
"SE": "https://discordapp.com/api/webhooks/5323534634633583/fasdfasasf",
"EU": "https://discordapp.com/api/webhooks/53235346346354285313/sefseafasfsafe"
},
"world": {
"US": "https://discordapp.com/api/webhooks/3243463464365/ergergegrergearg",
"EU": "https://discordapp.com/api/webhooks/23567896786725253/awdfawdawda"
},
"test": {
"US": "https://discordapp.com/api/webhooks/474645745457457/ergegrgesrgs",
"EU": "https://discordapp.com/api/webhooks/634561241242146346/asgasgasrgsd"
}
}
def main(data):
"""
data["name"] = Hello
data["link"] = https://google.com
data["status"] = Welcome!
data["image"] = https://p.bigstockphoto.com/GeFvQkBbSLaMdpKXF1Zv_bigstock-Aerial-View-Of-Blue-Lakes-And--227291596.jpg
data["keyword"] = Will be either True or False, If True = DISCORD_POSITIVE else DISCORD_NEGATIVE
data['webhook'] = Either hello, world or test
"""
embed = DiscordEmbed(title=data["name"], url=data["link"], description=data["status"], color=10881109)
embed.set_thumbnail(url=data["image"])
if data['keyword']:
for region, discord_webhooks in DISCORD_POSITIVE[data['webhook']].items():
webhook = DiscordWebhook(
url=discord_webhooks,
)
webhook.add_embed(embed)
Thread(
target=threding_test,
args=(
data,
region,
webhook
)
).start()
else:
for region, discord_webhooks in DISCORD_NEGATIVE[data['webhook']].items():
webhook = DiscordWebhook(
url=discord_webhooks,
)
webhook.add_embed(embed)
Thread(
target=threding_test,
args=(
data,
region,
webhook
)
).start()
return
def threding_test(data, region, webhook):
response = webhook.execute()
if response.ok:
print(f"Succesfully sent to Discord [{region}]")
return
else:
raise ValueError(
f"Request to slack returned an error {response.status_code}, the response is \n{response.text}")
</code></pre>
<p>My biggest goal here was to run the multiple dicts etc:</p>
<pre><code>"test": {
"US": "https://discordapp.com/api/webhooks/474645745457457/ergegrgesrgs",
"EU": "https://discordapp.com/api/webhooks/634561241242146346/asgasgasrgsd"
}
</code></pre>
<p>simultaneously so that US sends the requests for itself and EU for itself instead of waiting for each other to do one by one to gain speed improvements. My idea was then to do a for loop through the <code>DISCORD_POSITIVE/NEGATIVE</code> and loop through given <code>data['webhook']</code> and for each loop -> I will create a thread to send requests and then "kill" the thread after it has been sent. And this is the whole purpose pretty much, to gain fast time requests instead of being dependent on each other :)</p>
<p>Please let me know if there is anything that I might have missed.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-21T10:10:30.720",
"Id": "500335",
"Score": "1",
"body": "So, does your code work? I.e. does it actually run in parallel? If not, it would be off-topic here."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-21T10:11:44.277",
"Id": "500336",
"Score": "1",
"body": "@Graipher The code does work :) I do not see any problems when running it either. besides that you need real webhooks from Discord which I cannot provide here since someone can spam my discord. However the code does work! :D"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-20T13:32:25.337",
"Id": "253704",
"Score": "4",
"Tags": [
"python",
"python-3.x",
"multithreading"
],
"Title": "Sending simultaneous requests using threading"
}
|
253704
|
<p>I've recently started journey with ReactJS and to begin with I wanted to try something a bit more complex - paginated list of elements with back functionality enabled.
Below are two main components that I'd like to get feedback about. Especially <code>PagedListings</code>.</p>
<pre><code>import './App.css';
import PagedListings from './components/PagedListings';
import ScrollToTop from './components/ScrollToTop';
import React from "react";
import { Route } from 'react-router';
import { BrowserRouter as Router } from 'react-router-dom';
function App() {
return (
<Router>
<ScrollToTop>
<Route path={["/", "/:page"]} component={PagedListings}/>
</ScrollToTop>
</Router>
);
}
export default App;
</code></pre>
<p>And the actual component executing planned task</p>
<pre><code>import React, { useMemo } from "react";
import ListingsContainer from "./ListingsContainer";
import Pagination from "@material-ui/lab/Pagination";
import { useHistory, useLocation } from "react-router-dom";
const LISTINGS = ["Rec1", "Rec2", "Rec3",
"Rec4", "Rec5", "Rec6", "Rec7", "Rec8",
"Rec9", "Rec10",];
const DEFAULT_PAGE = 1;
const MAX_PAGE_COUNT = 10;
function PagedListings(props) {
const history = useHistory();
const location = useLocation();
const urlParams = useMemo(() => {
return new URLSearchParams(location.search);
}, [location.search]);
const handleChange = (
event: React.MouseEvent<HTMLButtonElement> | null,
newPage: number
) => {
let oneBasedNewPage = newPage;
urlParams.set("page", oneBasedNewPage.toString());
updateURL();
};
const updateURL = () => {
history.push({
pathname: location.pathname,
search: `?${urlParams}`,
});
};
function getPageNumber() {
let newPage = parseInt(urlParams.get("page")) || DEFAULT_PAGE;
return newPage <= MAX_PAGE_COUNT ? newPage : MAX_PAGE_COUNT;
}
return (
<>
<ListingsContainer listings={LISTINGS.slice(0, getPageNumber())} />
<Pagination
count={MAX_PAGE_COUNT}
defaultPage={DEFAULT_PAGE}
page={getPageNumber()}
onChange={handleChange}
/>
</>
);
}
export default PagedListings;
</code></pre>
|
[] |
[
{
"body": "<p>Your code looks quite reasonable. There are only a few small things I notice:</p>\n<ul>\n<li><p>Indent the JSX in <code>App</code> a bit more: <code>ScrollToTop</code> is a child of <code>Router</code>, so it should be indented further, not on the same level as <code>Router</code>. (It doesn't really make a difference here, but it's good to be consistent, and could be an improvement if that section ever got more complicated)</p>\n</li>\n<li><p><a href=\"https://softwareengineering.stackexchange.com/questions/278652/how-much-should-i-be-using-let-vs-const-in-es6\">Avoid <code>let</code>, prefer <code>const</code></a> - ESLint rule <a href=\"https://eslint.org/docs/rules/prefer-const\" rel=\"nofollow noreferrer\">here</a>.</p>\n</li>\n<li><p>Or, in the case of <code>oneBasedNewPage</code>, consider defining the <em>argument</em> with that name instead of creating a new variable - and maybe call it <code>oneIndexed</code>, not <code>oneBased</code>:</p>\n<pre><code>const handleChange = (\n event: React.MouseEvent<HTMLButtonElement> | null,\n oneIndexedNewPage: number\n) => {\n</code></pre>\n</li>\n<li><p><code>URLSearchParams</code> does not differentiate between numbers and strings.</p>\n<pre><code>urlParams.set("page", oneBasedNewPage.toString());\n</code></pre>\n<p>can be</p>\n<pre><code>urlParams.set("page", oneIndexedNewPage);\n</code></pre>\n<p>if you wish.</p>\n</li>\n<li><p>Consider if using <code>Math.min</code> might be clearer than the conditional operator:</p>\n<pre><code>function getPageNumber() {\n const newPage = parseInt(urlParams.get("page")) || DEFAULT_PAGE;\n return Math.min(newPage, MAX_PAGE_COUNT);\n}\n</code></pre>\n</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-22T09:41:03.917",
"Id": "500446",
"Score": "0",
"body": "Thank you for your review and all of the suggestions. I haven't been aware of the fact to use const instead of let in place you suggested."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-21T01:57:42.647",
"Id": "253729",
"ParentId": "253708",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "253729",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-20T17:12:56.803",
"Id": "253708",
"Score": "2",
"Tags": [
"javascript",
"react.js"
],
"Title": "ReactJS paginated component with React Router"
}
|
253708
|
<p>I am writing <a href="https://en.wikipedia.org/wiki/Color_model" rel="nofollow noreferrer">color model</a> logic in C++. I ask review in <em>defining limits for the color model</em>, by saying <strong>Limits</strong> I mean this.
Consider a <code>struct</code> which represents <code>RGB</code> color model.</p>
<pre><code>template<typename T>
struct RGB {
T r,g,b;
};
</code></pre>
<p>So I declared a type <code>RGB<T></code> where <code>T</code> can be any <code>arithmetic type</code> (the assertion is done, don't worry). So now I can create types <code>using RGB_Float = RGB<flaot></code> or <code>using RGB_888 = RGB<unsigned char></code> and so on.
As you already guessed I am doing <a href="https://en.wikipedia.org/wiki/Digital_image_processing" rel="nofollow noreferrer">image processing</a> and sometimes there comes a time where I want a type <code>RGB<float></code> where each component limits are <code>[0-1]</code> and sometimes I want same <code>RGB<float></code> with the limits <code>[10-20]</code> (An example) . Also I need each type to know its limits, at compile time. Syntax is like <code>RGB_Float::Limits::max() \\Returns max RGB_Float</code> and <code>RGB_Float::Limits::min() \\ Returns min RGB_Float</code>. So I need to change my struct <code>RGB<T></code> this way.</p>
<pre><code>template<typename T, typename LIMITS>
struct RGB {
using Limits = LIMITS;
T r,g,b;
}
</code></pre>
<p>And before declaring any <code>RGB<T,LIMITS></code> type I need to create a struct like</p>
<pre><code>RGB_FloatLimits {
static RGB<float,RGB_FloatLimits> max( return {1.0f,1.0f,1.0f};
... // min implementation too.
}
</code></pre>
<p>And then <code>using RGB_Float = RGB<float,RGB_FloatLimits>;</code></p>
<p>I know that this is a bad solution but I think it's the only if you use <code>C++17</code>. I spent a week trying to pass the limits as a template argument to a color model. Please review this solution and I am 90% sure that there is a better way to do this. Thx in advance.</p>
<p><strong>Note</strong> In any implementation of the <em>limits</em> <code>sizeof</code> the color model must remain the same.(So we must store the max and min statically)</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-20T19:31:00.183",
"Id": "500290",
"Score": "1",
"body": "There is not enough code in the question to provide a good review. The question borders on hypothetical code."
}
] |
[
{
"body": "<h1>C++11</h1>\n<p>Pre C++20 you have to use the type traits based approach, which is essentially what you have done. I dont think this is a bad solution, but probably the way to go if you need to.</p>\n<h1>C++20 solution (if integral min and max are ok also for C++11 )</h1>\n<p>In C++ 20 this all becomes easier as it finally allows for class and float non-type template arguments.</p>\n<pre><code>template<typename T, T min, T max>\nstruct RGB {\n T r,g,b; \n}\n</code></pre>\n<p>works for <code>T = int, T = char, T = float</code> and so on.</p>\n<p>This is the most straightforward solution I could think of that does not need any helper classes. If you only need <code>min</code> and <code>max</code> this is probably good.</p>\n<p>If you could live with integer <code>min</code> and <code>max</code> then this also works pre C++20. Simply use int for the min and max template arguments.</p>\n<p>The drawback is that in every function that accepts an RGB you need three template parameters (<code>T</code>, <code>min</code> and <code>max</code>), which could create a lot of noise in the code and make it less readable.</p>\n<h3>In case you need more than two config parameters</h3>\n<p>In case <code>min</code> and <code>max</code> is not a sufficient description of the number range, you could add addtional template parameters. However I would not advise this but make the parameters now a class.</p>\n<p>In C++20 this is very straightforward again, as you can also use class values as template parameters. This is a bit more clear than the previous type based traits approach (which is also the one you are using).</p>\n<pre><code>template <class T>\nstruct RGBconfig<T> {\n T min, max;\n}\n\ntemplate<typename T, RGBconfig<T> config>\nstruct RGB {\n T r,g,b; \n}\n</code></pre>\n<p>use as</p>\n<pre><code>constexpr RGBconfig<float> float1020 = {10, 20} \n\nusing RGBfloat1020 = RGB<float, float1020> \n</code></pre>\n<p>alternatively one could do</p>\n<pre><code>using RGBfloat1020 = RGB<float, RGBconfig<float> {10,20} > \n</code></pre>\n<h3>Reduce to one template parameter => include type in RGBconfig</h3>\n<p>Perhaps it is even possible to reduce it down to one template argument</p>\n<pre><code>template <class T>\nstruct RGBconfig<T> {\n using type = T;\n T min, max;\n}\n\ntemplate<auto config>\nstruct RGB {\n typename decltype(config)::type r,g,b; \n}\n</code></pre>\n<p>then use as</p>\n<pre><code>constexpr RGBconfig<float> float1020 = {10, 20};\nusing RGBfloat1020 = RGB<float1020>;\n</code></pre>\n<p>or</p>\n<pre><code>using RGBfloat1020 = RGB<RGBconfig<float> {10,20} >;\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-20T17:50:56.323",
"Id": "253712",
"ParentId": "253710",
"Score": "-1"
}
},
{
"body": "<p>I would simply use a traits configuration but use a default (so it can be overridden).</p>\n<pre><code>namespace Color\n{\n template<typename T>\n struct RGB_Traits; // No definition by default\n\n template<typename T, typename ColourTraits = RGB_Traits<T>>\n struct RGB {\n using Traits = ColourTraits;\n T r,g,b;\n };\n\n\n template<>\n struct RGB_Traits<float>\n {\n static RGB<float> max() {return {1.0, 1.0, 1.0};}\n static RGB<float> min() {return {0.0, 0.0, 0.0};}\n };\n template<>\n struct RGB_Traits<unsigned char>\n {\n static RGB<unsigned char> max() {return {255, 255, 255};}\n static RGB<unsigned char> min() {return {0, 0, 0};}\n };\n\n using RGB_Float = RGB<float>;\n using RGB_888 = RGB<unsigned char>;\n}\n\n#include <iostream>\nint main()\n{\n Color::RGB_888 data;\n std::cout << static_cast<int>(decltype(data)::Traits::max().r) << "\\n";\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-20T18:42:15.377",
"Id": "253715",
"ParentId": "253710",
"Score": "-1"
}
}
] |
{
"AcceptedAnswerId": "253712",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-20T17:14:48.713",
"Id": "253710",
"Score": "0",
"Tags": [
"c++",
"object-oriented",
"template",
"template-meta-programming"
],
"Title": "struct,template arguments, C++"
}
|
253710
|
<p>Recently I appeared for an job challenge organised on HackerEarth.</p>
<p>Question:</p>
<p>There are two teams T1 and T2. Power of each player is represented in array. The rules of game are as follow.</p>
<p>There are only N fights.</p>
<ul>
<li>No player from any team can fight twice.</li>
<li>At any instance, only one fight can occur.</li>
<li>For each fight score is calculated as (P1+P2)%N where P1, P2 is the power of player from T1 and T2 respectively and % is modulo operator.</li>
</ul>
<p>Task in Hand is to arrange T2 players in such a way so that score is minimum. We have to print the score of the match after every fight. T2 is aware of the sequence of T1 players.</p>
<p>Input format is first line contains T denoting the number of test cases. It also denotes the number of times we have to run our function.</p>
<p>Second line contains N i.e. the number of fights</p>
<p>Third line contains the power of players from Team T1. The sequence in which T1 player power is shown is the sequence in which T1 players would fight.</p>
<p>Fourth line contains the power of players from Team T2.</p>
<p>Constraints:</p>
<blockquote>
<p>1<=T<=10^5<br />
1<=N<=10^5<br />
0<=T1[i],T2[i]<= N for all i's.</p>
</blockquote>
<p>I wrote the following code:</p>
<pre><code>def solve (N, T1, T2):
# Write your code here
final_list=''
for each in T1:
temp_list=[]
flag=True
for i in range(0,len(T2)):
if (each + T2[i])%N==0:
T2.pop(i)
final_list+='0'
flag=False
break
else:
temp_list.append((each + T2[i])%N)
if flag:
j=temp_list.index(min(temp_list))
final_list+=str(min(temp_list))
T2.pop(j)
return final_list
T = int(input())
for _ in range(T):
N = int(input())
T1 = list(map(int, input().split()))
T2 = list(map(int, input().split()))
out_ = solve(N, T1, T2)
print (' '.join(map(str, out_)))
</code></pre>
<p>It took 0.1 seconds for few test cases and more than 10.2 seconds for few test cases(so basically the test case failed for taking too much time).</p>
<p><em><strong>Looking for optimal code</strong></em></p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-21T06:21:25.463",
"Id": "500321",
"Score": "0",
"body": "if possible, can you share the link to original question on the source platform (unless its visibility is private)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-21T06:37:09.197",
"Id": "500322",
"Score": "0",
"body": "It is one of the job challenges on hackerearth for jobs in India. Test time is over so can't really share it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-21T16:00:24.383",
"Id": "500352",
"Score": "3",
"body": "I don't see why this is down-voted. There's working code, and the OP posted what constraints he could provide."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-04T15:10:37.087",
"Id": "501524",
"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 [ask] for examples, and revise the title accordingly."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-04T15:37:51.970",
"Id": "501527",
"Score": "0",
"body": "If all that's wrong with it is the title, then just fix the title."
}
] |
[
{
"body": "<h3>Style:</h3>\n<p>This is the exact same algorithm, with the code-format, variable-names, and the use of strings cleaned up. I'm not actually sure this is the <em>exact</em> same function as yours, because the way you were using strings was probably wrong (because of the <code>' '.join(...)</code> in the surrounding use-code).</p>\n<pre class=\"lang-py prettyprint-override\"><code>def original_solve(N, T1, T2):\n final_list = []\n for item_1 in T1:\n temp_list = []\n already_appended = False\n for i in range(0, len(T2)):\n if (item_1 + T2[i]) % N == 0:\n T2.pop(i)\n final_list.append(0)\n already_appended = True\n break\n else:\n temp_list.append((item_1 + T2[i]) % N)\n if not already_appended:\n best_index = temp_list.index(min(temp_list))\n final_list.append(min(temp_list))\n T2.pop(best_index)\n \n return final_list\n</code></pre>\n<h3>Benchmarking:</h3>\n<p>We should have a quick way to test out any improvements we make.</p>\n<pre class=\"lang-py prettyprint-override\"><code>from random import randint # insecure RNG is fine for this task.\nfrom time import time\n\ndef make_test(N, t_len):\n return (N,\n [randint(0, N) for _ in range(t_len)],\n [randint(0, N) for _ in range(t_len)],\n None)\n\ndef time_function(f, *args):\n start = time()\n retval = f(*args)\n end = time()\n return retval, end - start\n\ndef main():\n candidates = {\n "Original": original_solve\n }\n tests = [\n (3, [1, 2, 3], [1, 2, 3], [0, 0, 0]),\n (4, [1, 2, 3], [1, 2, 3], [0, 0, 0]),\n (3, [1, 1, 3], [1, 2, 3], [0, 1, 1]),\n make_test(100, 100),\n make_test(100, 100),\n make_test(100, 100),\n make_test(10000, 10000),\n make_test(10000, 10000),\n make_test(10000, 10000),\n ]\n print(' T ' + ''.join(f'{k:>10} (s)' for k in candidates.keys()) + ' Answer')\n for N, T1, T2, known in tests:\n results = [time_function(f, N, list(T1), list(T2)) # Copy these lists, since these algorithms modify T2. \n for f in candidates.values()]\n\n assert 1 == len(set(\n tuple(answer)\n for answer in [known, *(r[0] for r in results)]\n if answer is not None\n ))\n print(f'{len(T1):^7}'\n + ''.join(f'{r[1]:>14.9f}' for r in results)\n + f' {results[0][0][:4]}')\n\nif __name__ == '__main__':\n main()\n</code></pre>\n<h3>Improvements to the existing algorithm:</h3>\n<p>Your current code is O(n^2). I suspect we can do better than that, but first lets consider some <em>simplifications</em>.</p>\n<ul>\n<li>Checking separately for <code>(item_1 + T2[i]) % N == 0</code> and short-circuiting is unlikely to save us much time, and it clutters up the function. Let's get rid of all of that.</li>\n<li>Finding the min of <code>temp_list</code>, and then searching again to get its index, is stinky. One option would be to build <code>temp_list</code> as a list of <code>t2_index, computed_value</code> tuples, but I think re-doing <em>one</em> of the modulo-sum computations is cheap enough to not worry about. So we can just ask for the minimum index using a key-function.</li>\n</ul>\n<h3>Improving the algorithm:</h3>\n<p>The modulo operator in the scoring function is what makes this problem non-trivial, but it doesn't really change the fact that numbers are easy to sort, and sorting is usually O(n log(n)). If our list (<code>T2</code>) were already sorted, could we do the rest of the problem in better-than O(n^2) complexity?</p>\n<ul>\n<li>Sort <code>T2</code>, and give it a structure to keep track of what's already been used. This is <code>bank</code> in the bellow code. Using ints/flags to track what's already been used is (probably) better than just dropping elements from the structure, because <a href=\"https://wiki.python.org/moin/TimeComplexity\" rel=\"nofollow noreferrer\">python's list's pop-intermediate is O(n)</a>.</li>\n<li>For each item in <code>T1</code>:\n<ul>\n<li>Calculate the ideal paring: <code>N - item</code> (mod N)</li>\n<li>Use a binary search (O(log(n)) to find where that value is or should be in the bank-structure.</li>\n<li>Search <em>upward</em> from there for a value that hasn't been used yet. In the worst-case this is O(n), but for randomly generated data the rate of collisions will be "low" (I haven't looked up the formula)</li>\n</ul>\n</li>\n</ul>\n<p>So yes, we can write a sub-quadratic algorithm, in fact it's O(n log(n)), which is pretty good for most purposes. Further refinement may be possibly, but I suspect there's not an algorithm better than log-linear.</p>\n<h3>Results:</h3>\n<pre class=\"lang-py prettyprint-override\"><code>from itertools import count, groupby\nfrom random import randint # insecure RNG is fine for this task.\nfrom time import time\n\ndef original_solve(N, T1, T2):\n final_list = []\n for item_1 in T1:\n temp_list = []\n already_appended = False\n for i in range(0, len(T2)):\n if (item_1 + T2[i]) % N == 0:\n T2.pop(i)\n final_list.append(0)\n already_appended = True\n break\n else:\n temp_list.append((item_1 + T2[i]) % N)\n if not already_appended:\n best_index = temp_list.index(min(temp_list))\n final_list.append(min(temp_list))\n T2.pop(best_index)\n \n return final_list\n\ndef clean_solve(N, T1, T2):\n final_list = []\n for item_1 in T1:\n def key_function(index):\n return (item_1 + T2[index]) % N\n best_index = min(range(len(T2)), key=key_function)\n final_list.append(key_function(best_index))\n T2.pop(best_index)\n \n return final_list\n\ndef sub_quadratic_solve(N, T1, T2):\n # Cases of `% length` are wrapping indexes back to the start of the list.\n # Cases of `% N` are wrapping any exact N values back to 0.\n bank = tuple([t2_item, len(list(copies))] # using list as an easily-mutable object.\n for t2_item, copies\n in groupby(sorted(t % N for t in T2)))\n length = len(bank)\n\n def binary_search_index(value): # https://www.codementor.io/@info658/the-binary-search-algorithm-in-python-19jvyrt5ly\n lower_bound = 0\n upper_bound = length - 1\n while lower_bound < upper_bound:\n midpoint = (lower_bound + upper_bound) // 2\n if bank[midpoint][0] == value:\n return midpoint\n elif bank[midpoint][0] < value:\n lower_bound = midpoint + 1\n else:\n upper_bound = midpoint - 1\n return lower_bound if bank[lower_bound][0] >= value else lower_bound + 1\n\n def find_best(value):\n ideal_index = binary_search_index(value % N)\n useable_index = next(i % length\n for i in count(ideal_index)\n if bank[i % length][1])\n bank[useable_index][1] -= 1\n return bank[useable_index][0]\n\n return [(t1_item + find_best(N - t1_item)) % N\n for t1_item in T1]\n\n\ndef make_test(N, t_len):\n return (N,\n [randint(0, N) for _ in range(t_len)],\n [randint(0, N) for _ in range(t_len)],\n None)\n\ndef time_function(f, *args):\n start = time()\n retval = f(*args)\n end = time()\n return retval, end - start\n\ndef main():\n candidates = {\n "Original": original_solve,\n "Cleaned": clean_solve,\n "Sub-Quad": sub_quadratic_solve,\n }\n tests = [\n (3, [1, 2, 3], [1, 2, 3], [0, 0, 0]),\n (4, [1, 2, 3], [1, 2, 3], [0, 0, 0]),\n (3, [1, 1, 3], [1, 2, 3], [0, 1, 1]),\n make_test(100, 100),\n make_test(100, 100),\n make_test(100, 100),\n make_test(10000, 10000),\n make_test(10000, 10000),\n make_test(10000, 10000),\n ]\n print(' T ' + ''.join(f'{k:>10} (s)' for k in candidates.keys()) + ' Answer')\n for N, T1, T2, known in tests:\n results = [time_function(f, N, list(T1), list(T2)) # Copy these lists, since these algorithms modify T2. \n for f in candidates.values()]\n assert 1 == len(set(\n tuple(answer)\n for answer in [known, *(r[0] for r in results)]\n if answer is not None\n ))\n print(f'{len(T1):^7}'\n + ''.join(f'{r[1]:>14.9f}' for r in results)\n + f' {results[0][0][:4]}')\n\nif __name__ == '__main__':\n main()\n</code></pre>\nPrints:\n<pre><code> T Original (s) Cleaned (s) Sub-Quad (s) Answer\n 3 0.000027657 0.000033140 0.000041246 [0, 0, 0]\n 3 0.000026226 0.000004768 0.000029802 [0, 0, 0]\n 3 0.000004292 0.000024319 0.000008106 [0, 1, 1]\n 100 0.000726700 0.000534534 0.000247002 [0, 2, 0, 0]\n 100 0.000698566 0.000530243 0.000190973 [0, 0, 4, 0]\n 100 0.000658035 0.000528812 0.000208855 [0, 5, 0, 2]\n 10000 7.761836529 5.691253662 0.064605951 [0, 0, 1, 0]\n 10000 7.386102200 5.667595863 0.067104578 [0, 1, 0, 2]\n 10000 7.601329803 5.666092873 0.056614161 [0, 0, 0, 0]\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-04T20:21:14.567",
"Id": "254327",
"ParentId": "253719",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-20T21:02:43.017",
"Id": "253719",
"Score": "2",
"Tags": [
"python",
"algorithm",
"python-3.x",
"time-limit-exceeded",
"interview-questions"
],
"Title": "Find minimal modulo-sum of pairs from two lists"
}
|
253719
|
<p>In working on another problem, one component I needed was to calculate the centroid of a collection of complex objects. The well-known way to calculate this is to simply average the real and imaginary parts. To accommodate either <code>std::complex<double></code> or <code>std::complex<float></code>, I have created the following code as a template. Everything works as expected.</p>
<h2>centroid.cpp</h2>
<pre><code>#include <iostream>
#include <complex>
#include <vector>
#include <numeric>
template<class ComplexIterator>
typename ComplexIterator::value_type centroid(ComplexIterator a, ComplexIterator b) {
return std::accumulate(a, b, typename ComplexIterator::value_type{0})
/ typename ComplexIterator::value_type{b-a};
}
int main() {
std::vector<std::complex<float>> points{ {4,5}, {30,6}, {20,25} };
std::cout << centroid(points.begin(), points.end()) << "\n";
}
</code></pre>
<p>Sample output:</p>
<blockquote>
<p>(18, 12)</p>
</blockquote>
<h2>My questions</h2>
<ol>
<li>The compiler rightly warns that in the calculation of the denominator in the template, there is a narrowing conversion. I can't think of a way to elegantly handle that. Should I just ignore it?</li>
<li>If given an empty set, the code returns a value of <code>(-nan, -nan)</code> which works for me, but for general use, should I throw an exception instead?</li>
<li>Should I use <code>std::enable_if</code> or C++20 <code>requires</code> to constrain the function to require only floating point numbers?</li>
<li>I thought about calling it <code>average</code> because technically, it would happily compute the average of, say, a <code>std::vector<float></code> but for my purposes, <code>centroid</code> seemed apt. What do you think of that choice?</li>
</ol>
<p>Any other ways to improve this would be good as well.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-21T16:14:18.313",
"Id": "500353",
"Score": "0",
"body": "This algorithm is handled quite well in a number of geography& mapping code bundles, since 'complex number' can just as easily represent points on a 2D surface. Might be worth looking up some of the source code in such software bundles/packages."
}
] |
[
{
"body": "<p>I'm fine with <code>(-nan. -nan)</code> and calling it <code>centroid</code>, but I'm not strongly tied to those opinions. I don't have enough experience with c++20 to weigh in on <code>std:enable_if</code>.</p>\n<p>Other improvements:</p>\n<ul>\n<li>the template should be <code>constexpr</code>.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-20T22:13:50.047",
"Id": "253724",
"ParentId": "253721",
"Score": "3"
}
},
{
"body": "<p>There's too little to review...</p>\n<p>It's not really a good practice to write function that accepts two iterators. Many STL functions work this way but it isn't convenient. It should accept a range instead. That's why ranges proposal was added to C++20.</p>\n<p><code>centroid</code> isn't a good name as even people well familiar with geometry might not remember this term. And it gets even more confusing as you use it with complex numbers because in programming complex numbers are usually used to represent 2d rotations rather than points in 2d space. You should use word <code>mean</code> or <code>average</code> instead - as a similar routine can just as easily compute arithmetic mean for whatever.</p>\n<p>I'd put an assert to deal with division by zero. Let caller figure out what to do with no element case. And you definitely don't want to deal with <code>nans</code>.</p>\n<blockquote>\n<p>Should I use std::enable_if or C++20 requires to constrain the function to require only floating point numbers?</p>\n</blockquote>\n<p>Don't bother. And there is no full C++20 implementation - or even one remotely close fully functioning.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-20T23:02:32.343",
"Id": "500297",
"Score": "0",
"body": "I don't know how to write a template that accepts a range. Any pointers?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-20T23:52:47.693",
"Id": "500304",
"Score": "0",
"body": "@Edward simply assume it has functions `begin()`, `end()`, and `size()` returning sensible data. Writing a type traits that verifies it is complex and unnecessary."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-20T22:14:25.883",
"Id": "253725",
"ParentId": "253721",
"Score": "3"
}
},
{
"body": "<p>Taking all of the suggestions from the other reviews, I think it's quite improved so I wanted to thank the reviewers and show the final version:</p>\n<pre><code>#include <iostream>\n#include <complex>\n#include <vector>\n#include <numeric>\n#include <concepts>\n#include <ranges>\n#include <array>\n#include <iterator>\n\ntemplate<typename T> \nconcept ComplexOrFloat = std::floating_point<T>\n || std::floating_point<typename T::value_type>;\n\ntemplate<typename R> \nrequires std::ranges::range<R> \n && ComplexOrFloat<std::ranges::range_value_t<R>>\nconstexpr std::ranges::range_value_t<R> average(R range) {\n if (std::ranges::size(range) == 0) \n throw std::domain_error("Cannot take average of zero-length range");\n using T = std::ranges::range_value_t<R>;\n return std::accumulate(std::ranges::begin(range), std::ranges::end(range), T{0}) \n / (T)(std::ranges::size(range));\n}\n\nint main() {\n using namespace std::complex_literals;\n constexpr std::array<std::complex<double>,3> points{{ {4,5}, {30,6}, {20,25} }};\n std::cout << average(std::views::all(points)) << "\\n";\n\n constexpr std::array<std::complex<double>,3> points2{\n { 24.0 + 7.0i, 22.0 + 9.0i, 8.0 + 20.0i }\n };\n std::cout << average(std::views::all(points2)) << "\\n";\n\n constexpr double numbers[]{1, -2, 3, 7, -8};\n std::cout << average(std::views::all(numbers)) << "\\n";\n\n const std::vector<float> numbers2{-7, -2, 3, 7, -8};\n std::cout << average(std::views::all(numbers2)) << "\\n";\n\n const std::vector<float> mt{};\n try {\n std::cout << average(std::views::all(mt)) << "\\n";\n } catch (std::domain_error& err) {\n std::cerr << "ERROR: " << err.what() << "\\n";\n }\n\n#if 0\n int intnumbers[]{1, -2, 3, 7, -8};\n // won't compile because an `int` is not floating point or complex floating point\n std::cout << average(std::views::all(intnumbers)) << "\\n";\n#endif\n}\n</code></pre>\n<p>I'm using C++20 concepts to avoid trying to take an average of a range of <code>int</code>s and returning an <code>int</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-21T00:55:16.020",
"Id": "253727",
"ParentId": "253721",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "253725",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-20T21:16:33.387",
"Id": "253721",
"Score": "4",
"Tags": [
"c++",
"mathematics",
"template-meta-programming",
"c++20"
],
"Title": "Calculate the centroid of a collection of complex numbers"
}
|
253721
|
<p>I have implemented a dictionary with an AVL tree, and here is the code and I need help improving it.</p>
<pre><code>#include <cstdlib>
#include <iostream>
#include <ctime>
#include <string>
#include <vector>
#include <list>
using namespace std;
class NoSuchKeyExeption {};
template<typename k, typename t>
class dictionary
{
private:
struct element
{
k key;
t data;
unsigned height;
unsigned level;
element* left;
element* right;
};
element* root;
unsigned size;
bool pinsert(element* ptr, const k &key, const t &data,element* parent);
bool pinsert_pseudo(element* ptr, element* toadd, element* parent);
element* pcopy(const element* ptr);
void pinsert_rec(const element* ptr);
void clear(element* ptr);
bool pexists(element* ptr, const k& key)const;
ostream & printos(ostream & os,element* ptr)const;
ostream & printosdes(ostream & os,element* ptr)const;
unsigned pheight(const element* ptr)const;
void calclvls(element* ptr, unsigned lvl, vector<element*> &storage, unsigned & maxlvl)const;
element* find(const k &key, element* ptr, element*& parent)const;
void find(element* ptr, vector<k> &keys)const;
void find(const t &data, element* ptr, vector<k> &keys)const;
void find(element* ptr, list<k> &keys)const;
void find(const t &data, element* ptr, list<k> &keys)const;
element* findrep(element* ptr, bool dir, element*& parent)const;
element* balance(element* ptr);
void premove(const element* ptr);
bool premove(const k &key, element* ptr, element* parent);
bool comparator(const element* ptr)const;
inline void newheight(element* ptr);
public:
dictionary();
dictionary(const dictionary<k,t> & copy);
~dictionary();
dictionary<k,t> & operator=(const dictionary<k,t> & copy);
template<typename u, typename i>
friend dictionary<u,i> operator+(const dictionary<u,i> & add1, const dictionary<u,i> & add2);
template<typename u, typename i>
friend dictionary<u,i> operator-(const dictionary<u,i> & subtract1, const dictionary<u,i> & subtract2);
dictionary<k,t> & operator+=(const dictionary<k,t> & add)
{
*this=*this+add;
return *this;
};
dictionary<k,t> & operator-=(const dictionary<k,t> & subtract)
{
*this=*this-subtract;
return *this;
};
void clear();
t& getData(const k& key)const;
vector<k> vgetKeys()const;
vector<k> vgetKeys(const t& data)const;
list<k> lgetKeys()const;
list<k> lgetKeys(const t& data)const;
unsigned int getSize()
{
return size;
};
bool empty()const
{
if(!root)
return true;
else
return false;
};
bool insert(const k &key, const t &data);
bool remove(const k &key);
inline bool exists(const k &key)const;
bool changeKey(const k &keyfrom,const k &keyto);
void printTree()const;
template<typename u, typename i>
friend bool operator==(const dictionary<u,i> & check1,const dictionary<u,i> & check2);
template<typename u, typename i>
friend bool operator!=(const dictionary<u,i> & check1,const dictionary<u,i> & check2);
template<typename u, typename i>
friend ostream & operator<< (ostream & os, const dictionary<u,i> & toprint);
void printDescend(ostream & os)const;
};
//MAI JEWELRY
template<typename k, typename t>
bool dictionary<k,t>::pinsert(element* ptr, const k &key, const t &data,element* parent)
{
if(root==nullptr)
{
element* temp = new element;
temp->key=key;
temp->data=data;
temp->height=1;
temp->left=nullptr;
temp->right=nullptr;
root=temp;
size=1;
return true;
}
if(ptr->key<key)
{
if(ptr->right==nullptr)
{
element * temp=new element;
temp->key=key;
temp->data=data;
temp->height=1;
temp->left=nullptr;
temp->right=nullptr;
ptr->right=temp;
size++;
newheight(ptr);
return true;
}
if(pinsert(ptr->right,key,data,ptr))
{
newheight(ptr);
if(parent)
{
if(parent->right==ptr)
parent->right=balance(ptr);
else
parent->left=balance(ptr);
}
else
root=balance(ptr);
return true;
}
else
return false;
}
else if(key<ptr->key)
{
if(ptr->left==nullptr)
{
element * temp=new element;
temp->key=key;
temp->data=data;
temp->height=1;
temp->left=nullptr;
temp->right=nullptr;
ptr->left=temp;
size++;
newheight(ptr);
return true;
}
if(pinsert(ptr->left,key,data,ptr))
{
newheight(ptr);
if(parent)
{
if(parent->right==ptr)
parent->right=balance(ptr);
else
parent->left=balance(ptr);
}
else
root=balance(ptr);
return true;
}
else
return false;
}
return false;
}
template<typename k, typename t>
bool dictionary<k,t>::pinsert_pseudo(element* ptr, element* toadd, element* parent)
{
if(root==nullptr)
{
toadd->left=nullptr;
toadd->right=nullptr;
toadd->height=1;
root=toadd;
size++;
return true;
}
if(ptr->key<toadd->key)
{
if(ptr->right==nullptr)
{
toadd->height=1;
toadd->left=nullptr;
toadd->right=nullptr;
ptr->right=toadd;
size++;
newheight(ptr);
//balance(root);
return true;
}
if(pinsert_pseudo(ptr->right,toadd,ptr))
{
newheight(ptr);
if(parent)
if(parent->right==ptr)
parent->right=balance(ptr);
else
parent->left=balance(ptr);
else
root=balance(ptr);
return true;
}
else
return false;
}
else if(toadd->key<ptr->key)
{
if(ptr->left==nullptr)
{
toadd->height=1;
toadd->left=nullptr;
toadd->right=nullptr;
ptr->left=toadd;
size++;
newheight(ptr);
//balance(root);
return true;
}
if(pinsert_pseudo(ptr->left,toadd,ptr))
{
newheight(ptr);
if(parent)
if(parent->right==ptr)
parent->right=balance(ptr);
else
parent->left=balance(ptr);
else
root=balance(ptr);
return true;
}
else
return false;
}
}
template<typename k, typename t>
typename dictionary<k,t>::element* dictionary<k,t>::pcopy(const element* ptr)
{
if(ptr==nullptr)
return nullptr;
element * temp=new element;
temp->key=ptr->key;
temp->data=ptr->data;
temp->height=ptr->height;
temp->left=pcopy(ptr->left);
temp->right=pcopy(ptr->right);
size++;
return temp;
}
template<typename k, typename t>
void dictionary<k,t>::pinsert_rec(const element* ptr)
{
if(ptr==nullptr)
return;
if(!pexists(root,ptr->key))
pinsert(root,ptr->key,ptr->data,nullptr);
pinsert_rec(ptr->left);
pinsert_rec(ptr->right);
}
template<typename k, typename t>
void dictionary<k,t>::clear(element* ptr)
{
if(ptr==nullptr)
return;
clear(ptr->left);
clear(ptr->right);
delete ptr;
ptr=nullptr;
}
template<typename k, typename t>
bool dictionary<k,t>::pexists(element* ptr, const k& key)const
{
if(ptr==nullptr)
return false;
if(ptr->key==key)
return true;
if(pexists(ptr->left,key)||pexists(ptr->right,key))
return true;
return false;
}
template<typename k, typename t>
ostream & dictionary<k,t>::printos(ostream & os,element* ptr)const
{
if(ptr==nullptr)
return os;
printos(os,ptr->left);
os<<"Key:"<<endl<<ptr->key<<endl<<"Data:"<<endl<<ptr->data<<endl;
printos(os,ptr->right);
return os;
}
template<typename k, typename t>
ostream & dictionary<k,t>::printosdes(ostream & os,element* ptr)const
{
if(ptr==nullptr)
return os;
printosdes(os,ptr->right);
os<<"Key:"<<endl<<ptr->key<<endl<<"Data:"<<endl<<ptr->data<<endl;
printosdes(os,ptr->left);
return os;
}
template<typename k, typename t>
unsigned dictionary<k,t>::pheight(const element* ptr)const
{
if(ptr==nullptr)
return 0;
unsigned l=pheight(ptr->left);
unsigned r=pheight(ptr->right);
if(l>r)
return l+1;
else
return r+1;
}
template<typename k, typename t>
void dictionary<k,t>::calclvls(element* ptr, unsigned lvl, vector<element*> &storage, unsigned & maxlvl)const
{
if(ptr==nullptr)
return;
ptr->level=++lvl;
storage.push_back(ptr);
if(maxlvl<lvl)
maxlvl=lvl;
calclvls(ptr->left,lvl,storage,maxlvl);
calclvls(ptr->right,lvl,storage,maxlvl);
}
template<typename k, typename t>
typename dictionary<k,t>::element* dictionary<k,t>::find(const k &key,element* ptr,element*& parent)const
{
if(ptr==nullptr)
return nullptr;
if(ptr->key==key)
return ptr;
parent=ptr;
element* lrptr=find(key,ptr->left,parent);
if(lrptr==nullptr)
{
parent=ptr;
lrptr=find(key,ptr->right,parent);
}
return lrptr;
}
template<typename k, typename t>
void dictionary<k,t>::find(element* ptr, vector<k> &keys)const
{
if(ptr==nullptr)
return;
keys.push_back(ptr->key);
find(ptr->left,keys);
find(ptr->right,keys);
}
template<typename k, typename t>
void dictionary<k,t>::find(const t &data, element* ptr, vector<k> &keys)const
{
if(ptr==nullptr)
return;
if(ptr->data==data)
keys.push_back(ptr->key);
find(data,ptr->left,keys);
find(data,ptr->right,keys);
}
template<typename k, typename t>
void dictionary<k,t>::find(element* ptr, list<k> &keys)const
{
if(ptr==nullptr)
return;
keys.push_back(ptr->key);
find(ptr->left,keys);
find(ptr->right,keys);
}
template<typename k, typename t>
void dictionary<k,t>::find(const t &data, element* ptr, list<k> &keys)const
{
if(ptr==nullptr)
return;
if(ptr->data==data)
keys.push_back(ptr->key);
find(data,ptr->left,keys);
find(data,ptr->right,keys);
}
template<typename k, typename t>
typename dictionary<k,t>::element* dictionary<k,t>::findrep(element* ptr,bool dir,element*& parent)const
{
if(dir)
{
if(ptr->right==nullptr)
return ptr;
else
{
parent=ptr;
return findrep(ptr->right,true,parent);
}
}
else
{
if(ptr->left==nullptr)
return ptr;
else
{
parent=ptr;
return findrep(ptr->left,false,parent);
}
}
}
template<typename k, typename t>
typename dictionary<k,t>::element* dictionary<k,t>::balance(element* ptr)
{
if(ptr==nullptr)
return nullptr;
int l=0;
int r=0;
if(ptr->left)
l=ptr->left->height;
if(ptr->right)
r=ptr->right->height;
int balfac=l-r;
if(balfac<=1&&balfac>=-1)
return ptr;
element* swapper;
if(balfac>1)
{
swapper=ptr->left;
if(ptr->left->right)
{
ptr->left=swapper->right;
swapper->right=swapper->right->left;
ptr->left->left=swapper;
newheight(swapper);
newheight(ptr->left);
newheight(ptr);
swapper=ptr->left;
}
ptr->left=swapper->right;
swapper->right=ptr;
newheight(ptr);
newheight(swapper);
if(root==ptr)
root=swapper;
return swapper;
}
else
{
swapper=ptr->right;
if(ptr->right->left)
{
ptr->right=swapper->left;
swapper->left=swapper->left->right;
ptr->right->right=swapper;
newheight(swapper);
newheight(ptr->right);
newheight(ptr);
swapper=ptr->right;
}
ptr->right=swapper->left;
swapper->left=ptr;
newheight(ptr);
newheight(swapper);
if(root==ptr)
root=swapper;
return swapper;
}
}
template<typename k, typename t>
void dictionary<k,t>::premove(const element* ptr)
{
if(ptr==nullptr)
return;
remove(ptr->key);
premove(ptr->right);
premove(ptr->left);
}
template<typename k, typename t>
bool dictionary<k,t>::premove(const k &key, element* remptr, element* parent)
{
if(remptr==nullptr)
return false;
if(remptr->key!=key)
{
if(key<remptr->key)
{
if(premove(key,remptr->left,remptr))
{
newheight(remptr);
if(parent)
if(parent->right==remptr)
parent->right=balance(remptr);
else
parent->left=balance(remptr);
else
balance(remptr);
return true;
}
return false;
}
else
{
if(premove(key,remptr->right,remptr))
{
newheight(remptr);
if(parent)
if(parent->right==remptr)
parent->right=balance(remptr);
else
parent->left=balance(remptr);
else
balance(remptr);
return true;
}
return false;
}
}
if(remptr->right==nullptr&&remptr->left==nullptr)
{
if(parent)
{
if(parent->right==remptr)
parent->right=nullptr;
else
parent->left=nullptr;
}
else
root=nullptr;
delete remptr;
size--;
return true;
}
if(remptr->right==nullptr||remptr->left==nullptr)
{
if(parent)
{
if(parent->right==remptr)
{
if(remptr->right==nullptr)
parent->right=remptr->left;
else
parent->right=remptr->right;
}
else
{
if(remptr->right==nullptr)
parent->left=remptr->left;
else
parent->left=remptr->right;
}
}
else
{
if(remptr->right==nullptr)
root=remptr->left;
else
root=remptr->right;
}
delete remptr;
size--;
return true;
}
element* repparent=nullptr;
element* repptr=findrep(remptr->right,false,repparent);
if(parent)
{
if(parent->right==remptr)
parent->right=repptr;
else
parent->left=repptr;
}
else
root=repptr;
repptr->left=remptr->left;
if(remptr->right!=repptr)
{
repparent->left=repptr->right;
repptr->right=remptr->right;
}
delete remptr;
size--;
return true;
}
template<typename k, typename t>
bool dictionary<k,t>::comparator(const element* ptr)const
{
if(ptr==nullptr&&root==nullptr)
return true;
if(ptr==nullptr)
return true;
if(!pexists(root,ptr->key))
return false;
if(comparator(ptr->left)&&comparator(ptr->right))
return true;
return false;
}
template<typename k, typename t>
void dictionary<k,t>::newheight(element* ptr)
{
if(ptr->right||ptr->left)
{
if(ptr->right&&ptr->left)
ptr->height=ptr->right->height>ptr->left->height?ptr->right->height+1:ptr->left->height+1;
else if(ptr->right)
ptr->height=ptr->right->height+1;
else
ptr->height=ptr->left->height+1;
}
else
ptr->height=1;
}
//MAI PUBLICS
template<typename k, typename t>
dictionary<k,t>::dictionary()
{
root=nullptr;
size=0;
}
template<typename k, typename t>
dictionary<k,t>::dictionary(const dictionary<k,t> & copy)
{
size=0;
root=pcopy(copy.root);
}
template<typename k, typename t>
dictionary<k,t>::~dictionary()
{
clear(root);
size=0;
}
template<typename k, typename t>
dictionary<k,t> & dictionary<k,t>::operator=(const dictionary<k,t> & copy)
{
if(this==&copy)
return *this;
clear(root);
size=0;
root=pcopy(copy.root);
}
template<typename k, typename t>
dictionary<k,t> operator+(const dictionary<k,t> & add1, const dictionary<k,t> & add2)
{
dictionary<k,t> temp;
temp.root = temp.pcopy(add1.root);
temp.pinsert_rec(add2.root);
return temp;
}
template<typename k, typename t>
dictionary<k,t> operator-(const dictionary<k,t> & subtract1, const dictionary<k,t> & subtract2)
{
dictionary<k,t> temp;
temp.root = temp.pcopy(subtract1.root);
temp.premove(subtract2.root);
return temp;
}
template<typename k, typename t>
void dictionary<k,t>::clear()
{
clear(root);
size=0;
root=nullptr;
}
template<typename k, typename t>
t& dictionary<k,t>::getData(const k& key)const
{
element *ptr,*parent;
ptr=find(key,root,parent);
if(ptr==nullptr)
throw NoSuchKeyExeption();
return ptr->data;
}
template<typename k, typename t>
vector<k> dictionary<k,t>::vgetKeys()const
{
vector<k> keys;
find(root,keys);
return keys;
}
template<typename k, typename t>
vector<k> dictionary<k,t>::vgetKeys(const t& data)const
{
vector<k> keys;
find(data,root,keys);
return keys;
}
template<typename k, typename t>
list<k> dictionary<k,t>::lgetKeys()const
{
list<k> keys;
find(root,keys);
return keys;
}
template<typename k, typename t>
list<k> dictionary<k,t>::lgetKeys(const t& data)const
{
list<k> keys;
find(data,root,keys);
return keys;
}
template<typename k, typename t>
bool dictionary<k,t>::insert(const k &key, const t &data)
{
if(pexists(root,key))
return false;
return pinsert(root,key,data,nullptr);
}
template<typename k, typename t>
bool dictionary<k,t>::remove(const k &key)
{
return premove(key,root,nullptr);
}
template<typename k, typename t>
bool dictionary<k,t>::exists(const k &key)const
{
return pexists(root,key);
}
template<typename k, typename t>
bool dictionary<k,t>::changeKey(const k &keyfrom,const k &keyto)
{
if(pexists(root,keyto))
return false;
element* remptr;
element* parent=nullptr;
remptr = find(keyfrom,root,parent);
//copypasta from remove method
{
if(remptr==nullptr)
return false;
else if(remptr->right==nullptr&&remptr->left==nullptr)
{
if(parent)
{
if(parent->right==remptr)
parent->right=nullptr;
else
parent->left=nullptr;
}
else
root=nullptr;
size--;
balance(root);
}
else if(remptr->right==nullptr||remptr->left==nullptr)
{
if(parent)
{
if(parent->right==remptr)
{
if(remptr->right==nullptr)
parent->right=remptr->left;
else
parent->right=remptr->right;
}
else
{
if(remptr->right==nullptr)
parent->left=remptr->left;
else
parent->left=remptr->right;
}
}
else
{
if(remptr->right==nullptr)
root=remptr->left;
else
root=remptr->right;
}
size--;
balance(root);
}
else
{
element* repparent=nullptr;
element* repptr=findrep(remptr->right,false,repparent);
if(parent)
{
if(parent->right==remptr)
parent->right=repptr;
else
parent->left=repptr;
}
else
root=repptr;
repptr->left=remptr->left;
if(remptr->right!=repptr)
{
repparent->left=repptr->right;
repptr->right=remptr->right;
}
size--;
balance(root);
}
}
remptr->key=keyto;
pinsert_pseudo(root,remptr,nullptr);
}
template<typename k, typename t>
void dictionary<k,t>::printTree()const
{
vector<element*> storage;
unsigned maxlvl=0;
calclvls(root,0,storage,maxlvl);
cout<<"size: "<<storage.size()<<endl;
cout<<"maxlvl: "<<maxlvl<<endl;
for(int i=1; i<=maxlvl; i++)
{
for(int j=0; j<storage.size(); j++)
{
if(storage[j]->level==i)
{
cout<<storage[j]->key<<" "<<storage[j]->height;
cout<<"(";
if(storage[j]->right)
cout<<storage[j]->right->key;
cout<<",";
if(storage[j]->left)
cout<<storage[j]->left->key;
cout<<")"<<" | ";
}
}
cout<<endl;
}
}
template<typename u, typename i>
bool operator==(const dictionary<u,i> & check1,const dictionary<u,i> & check2)
{
return check1.comparator(check2.root);
}
template<typename u, typename i>
bool operator!=(const dictionary<u,i> & check1,const dictionary<u,i> & check2)
{
return !check1.comparator(check2.root);
}
template<typename u, typename i>
ostream & operator<< (ostream & os, const dictionary<u,i> & toprint)
{
toprint.printos(os,toprint.root);
return os;
}
template<typename k, typename t>
void dictionary<k,t>::printDescend(ostream & os)const
{
printosdes(os,root);
}
int main()
{
dictionary<int,string> lol;
lol.insert(5,"dont care");
lol.insert(8,"dont care");
lol.insert(3,"dont care");
lol.insert(1,"dont care");
lol.insert(4,"dont care");
lol.insert(10,"dont care");
lol.insert(6,"dont care");
lol.insert(12,"dont care");
lol.insert(11,"dont care");
lol.insert(7,"dont care");
lol.insert(13,"dont care");
lol.insert(2,"dont care");
lol.printTree();
lol.remove(8);
lol.printTree();
lol.getData(11)="well what do you know it works";
dictionary<int,string> lol2;
lol2+=lol;
cout<<(lol2==lol)<<endl;
cout<<lol<<endl;
lol.printDescend(cout);
lol2.insert(-10,"hi im new here");
lol2.insert(23,"hi im new here");
lol2.insert(7,"hi im new here");
lol2.insert(-1,"hi im new here");
cout<<(lol2==lol)<<endl;
lol2.changeKey(7,1000);
cout<<"Start keys found in order"<<endl;
for(int i=0; i<lol2.vgetKeys().size(); i++)
cout<<lol2.vgetKeys()[i]<<endl;
cout<<"End keys found in order"<<endl;
cout<<"Start keys found in order"<<endl;
for(int i=0; i<lol2.vgetKeys("dont care").size(); i++)
cout<<lol2.vgetKeys("dont care")[i]<<endl;
cout<<"End keys found in order"<<endl;
lol2.changeKey(lol2.vgetKeys("dont care")[0],666);
dictionary<int,string> lol3 = lol2+lol;
cout<<"we got here"<<endl;
(lol2-lol).printTree();
cout<<endl;
cout<<(lol2-lol).getSize();
cout<<endl;
lol.printTree();
cout<<endl;
lol2.printTree();
cout<<lol2.getData(11)<<endl;
cout<<lol2.vgetKeys("hiim new here").size()<<endl;
cout<<lol2.lgetKeys("dont care").size()<<endl;
cout<<endl<<endl<<endl<<"------------End Normal Testing------------------"<<endl;
srand(time(nullptr));
lol3.clear();
int loops = 10000;
cout<<"the loop length is: "<<loops<<endl;
for(int i=0; i<loops; i++)
lol3.insert(rand(),"does it matter");
for(int i=0; i<loops; i++)
lol3.remove(rand());
// lol3.printTree();
//cout<<lol3<<endl;
cout<<"the size is: "<<lol3.getSize()<<endl;
}
</code></pre>
<p>Could you please help me improve it</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-21T00:25:31.897",
"Id": "500307",
"Score": "0",
"body": "What is wrong with it and what do you think needs to be improved?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-21T19:00:51.660",
"Id": "500360",
"Score": "0",
"body": "if I knew I wouldn't have asked"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-20T22:04:05.443",
"Id": "253723",
"Score": "2",
"Tags": [
"c++",
"object-oriented"
],
"Title": "AVL dictionary implementation"
}
|
253723
|
<p>As described in his <a href="https://www.semanticscholar.org/paper/Depth-First-Search-and-Linear-Graph-Algorithms-Tarjan/385742fffcf113656f0d3cf6c06ef95cb8439dc6" rel="nofollow noreferrer">paper</a>, Tarjan's algorithm reports only the nodes of the strongly connected components. For my use, I would also like to also have the edge list of the components (so that I can run Karp's minimum mean cycle algorithm on it)</p>
<blockquote>
<p>As a side note, it is rather curious why he did it for the biconnected component case but not the strongly connected component case in the same paper.</p>
</blockquote>
<p>For my purpose, I rolled my own modification. In addition to the stack of nodes, I also have a stack of edges. The edges are filtered before entering the stack and are also filtered when leaving the stack to make sure they are really staying within the same strongly connected components.</p>
<p>This code will eventually be converted into C or C++ for efficient implementation. Therefore, my primary goal with this code review is for correctness and performance. I am less concerned with how pythonic the code is, but I wouldn't mind comments along that line.</p>
<p>In particular, I would like to have a confirmation on the correctness of the algorithm as well as the fact that it still runs in linear time, that is, <code>O(|V| + |E|)</code>. The argument about the time bounds can be explained by the additional work to maintain the <code>instack</code> numbers takes an extra <code>O(|V|)</code> time, and the extra work to manage the edge stack takes an extra at most <code>O(|E|)</code> as an edge can enter the stack only once.</p>
<p>Without further ado, here is the code, thanks in advance for the reviewing.</p>
<pre><code>class edge:
def __init__(self, src, dst):
self.src = src
self.dst = dst
def __repr__(self):
return "%s --> %s" % (self.src, self.dst)
class strongly_connected_components_state:
def __init__(self, number_of_nodes):
self.time = 0
# This represents the time when the node is reached
self.start_time = [None] * number_of_nodes
# This represents whether a node is in the stack
# 0 implies it is never pushed on the stack
# 1 implies it is currently on the stack
# 2 implies it is currently being popped from the stack but we have not reported the strongly connected component yet
# 3 implies it left the stack
self.instack = [0] * number_of_nodes
# This represents, among all the nodes that are not currently declared as a strongly connected component
# The one with the smallest start time that can be reached through its subtree only.
self.low = [None] * number_of_nodes
self.node_stack = []
self.edge_stack = []
def strongly_connected_components(number_of_nodes, edges):
adjacency_list = [[] for _ in range(0, number_of_nodes)]
for edge in edges:
adjacency_list[edge.src].append(edge)
states = strongly_connected_components_state(number_of_nodes)
for node in range(0, number_of_nodes):
if states.start_time[node] is None:
strongly_connected_components_helper(node, adjacency_list, states)
def strongly_connected_components_helper(node, adjacency_list, states):
states.start_time[node] = states.time
states.time = states.time + 1
states.low[node] = states.start_time[node]
states.node_stack.append(node)
states.instack[node] = 1
for edge in adjacency_list[node]:
if states.start_time[edge.dst] is None:
# All the tree edges enters the edge stack
states.edge_stack.append(edge)
strongly_connected_components_helper(edge.dst, adjacency_list, states)
if states.low[edge.src] > states.low[edge.dst]:
states.low[edge.src] = states.low[edge.dst]
elif states.instack[edge.dst] == 1:
# So are all the edges that may end up in the strongly connected component
# We might encounter a back edge in this branch, and back edges always end up in a
# strongly connected component.
# But we might also encounter a cross edge or a forward edge in this branch, in that case
# the edge might cross two strongly connected components, and there is no good way
# to tell at this point.
states.edge_stack.append(edge)
if states.low[edge.src] > states.start_time[edge.dst]:
states.low[edge.src] = states.start_time[edge.dst]
else:
# Otherwise the edge is known to point to some other strongly connected component
# This is an edge we can safely skip from entering the edge stack
if not states.instack[edge.dst] == 3:
raise ValueError()
if states.start_time[node] == states.low[node]:
connected_component_nodes = []
connected_component_edges = []
while True:
stack_node = states.node_stack.pop()
# The node is marked as "being popped", not quite done with popping
states.instack[stack_node] = 2
connected_component_nodes.append(stack_node)
if node == stack_node:
break
while True:
# I claim that all edges within the strongly connected component must be currently at the
# top of the stack
edge = states.edge_stack.pop()
# I claim that states.instack[edge.src] == 2
if not states.instack[edge.src] == 2:
raise ValueError()
# The edge could be forward edge or cross edge to other strongly connected component
# Therefore we check if the destination of the edge is within the current strongly connected component
if states.instack[edge.dst] == 2:
connected_component_edges.append(edge)
# The popping should stop after we have emptied the stack (in case the node is the root of the depth first search)
# or after the tree edge to node is found. We are just leaving the depth first search for node, so it is
# impossible for us to have a forward edge to node, therefore the time condition confirms it is the tree edge
if len(states.edge_stack) == 0 or (edge.dst == node and states.start_time[edge.src] < states.start_time[edge.dst]):
break
print("connected component nodes: %s" % connected_component_nodes)
print("connected component edges: %s" % connected_component_edges)
for connected_component_node in connected_component_nodes:
states.instack[connected_component_node] = 3
def main():
edges = [
edge(1, 0),
edge(2, 1),
edge(3, 2),
edge(2, 3),
edge(0, 4),
edge(4, 1),
edge(5, 4),
edge(6, 5),
edge(5, 6),
edge(6, 2),
edge(7, 6),
edge(7, 7),
]
strongly_connected_components(8, edges)
return 0
if __name__ == "__main__":
main()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-21T09:26:38.053",
"Id": "500332",
"Score": "0",
"body": "Your creation of class serves no real purpose here."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-21T18:44:00.923",
"Id": "500359",
"Score": "0",
"body": "Thanks for your attention! Now I learn about namedtuple."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-21T20:23:20.770",
"Id": "500379",
"Score": "0",
"body": "I have found a bug and fixed it, when I pop from the edge stack, it is possible that the edge stack is empty. That could happen if I have a graph with just a single node."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-21T21:20:43.633",
"Id": "500399",
"Score": "0",
"body": "The fixed version can be found here: https://github.com/cshung/MiscLab/blob/master/MinCostFlowPrototype/strongly_connected_component.py"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-22T20:12:05.837",
"Id": "500470",
"Score": "0",
"body": "I need to reorder the assertion that the edge popping from the stack must be coming from the current strongly connected component after determining it is not a tree edge. In hindsight, obviously, the tree edge leading to 'node' cannot come from the same connected component."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-21T01:04:08.983",
"Id": "253728",
"Score": "3",
"Tags": [
"python",
"algorithm",
"graph"
],
"Title": "Modified Tarjan's algorithm for reporting the edges within the strongly connected component"
}
|
253728
|
<p>I want to ask if there is a better way to arrange this. Main concern is whether the store is set up in a good way and if passing Pointer to ProductRepository is a good idea or there are better ways but criticism towards all of it is welcome. I'm relatively new to Go. I have this folder structure</p>
<pre><code>.
├── Makefile
├── apiserver
├── cmd
│ └── apiserver
│ └── main.go
├── configs
│ └── apiserver.toml
├── go.mod
├── go.sum
└── internal
└── app
├── apiserver
│ ├── apiserver.go
│ ├── config.go
│ └── server.go
├── handlers
│ ├── getAll.go
│ └── getOne.go
├── model
│ └── product.go
└── store
├── product_repository.go
└── store.go
</code></pre>
<p>My <code>server.go</code> file looks like</p>
<pre class="lang-golang prettyprint-override"><code>package apiserver
import (
"net/http"
"github.com/gorilla/mux"
"github.com/sirupsen/logrus"
"github.com/vSterlin/sw-store/internal/app/handlers"
"github.com/vSterlin/sw-store/internal/app/store"
)
type server struct {
router *mux.Router
logger *logrus.Logger
store *store.Store
}
func newServer(store *store.Store) *server {
s := &server{
router: mux.NewRouter(),
logger: logrus.New(),
store: store,
}
s.configureRouter()
return s
}
func (s *server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
s.router.ServeHTTP(w, r)
}
func (s *server) configureRouter() {
pr := s.store.Product()
s.router.HandleFunc("/products", handlers.GetAllHandler(pr)).Methods("GET")
s.router.HandleFunc("/products/{id}", handlers.GetOneHandler(pr)).Methods("GET")
}
</code></pre>
<p><code>apiserver.go</code> which starts up</p>
<pre class="lang-golang prettyprint-override"><code>package apiserver
import (
"database/sql"
"net/http"
// Postgres driver
_ "github.com/lib/pq"
"github.com/vSterlin/sw-store/internal/app/store"
)
// Start starts up the server
func Start(config *Config) error {
db, err := newDB(config.DatabaseURL)
if err != nil {
return nil
}
defer db.Close()
store := store.New(db)
srv := newServer(store)
return http.ListenAndServe(config.BindAddr, srv)
}
func newDB(databaseURL string) (*sql.DB, error) {
db, err := sql.Open("postgres", databaseURL)
if err != nil {
return nil, err
}
if err := db.Ping(); err != nil {
return nil, err
}
return db, nil
}
</code></pre>
<p><code>product_repository.go</code></p>
<pre class="lang-golang prettyprint-override"><code>package store
import (
"github.com/vSterlin/sw-store/internal/app/model"
)
type ProductRepository struct {
store *Store
}
func (pr *ProductRepository) FindAll() ([]*model.Product, error) {
rows, err := pr.store.db.Query("SELECT * FROM products;")
if err != nil {
return nil, err
}
pmArr := []*model.Product{}
for rows.Next() {
pm := &model.Product{}
rows.Scan(&pm.ID, &pm.Name, &pm.Price, &pm.Description, &pm.CreatedAt, &pm.UpdatedAt)
pmArr = append(pmArr, pm)
}
return pmArr, nil
}
func (pr *ProductRepository) FindById(id int) (*model.Product, error) {
row := pr.store.db.QueryRow("SELECT * FROM products WHERE id=$1;", id)
pm := &model.Product{}
err := row.Scan(&pm.ID, &pm.Name, &pm.Price, &pm.Description, &pm.CreatedAt, &pm.UpdatedAt)
if err != nil {
return nil, err
}
return pm, nil
}
</code></pre>
<p>and <code>store.go</code> is</p>
<pre class="lang-golang prettyprint-override"><code>package store
import (
"database/sql"
)
type Store struct {
db *sql.DB
productRepository *ProductRepository
}
func New(db *sql.DB) *Store {
return &Store{
db: db,
}
}
func (s *Store) Product() *ProductRepository {
if s.productRepository != nil {
return s.productRepository
}
s.productRepository = &ProductRepository{
store: s,
}
return s.productRepository
}
</code></pre>
|
[] |
[
{
"body": "<p>The first thing I noticed about your folder structure is that all of your internal packages are contained within this <code>app</code> directory. There is no point to this. An internal package, by definition, cannot be imported outside of your project, so any package under <code>internal</code> by definition is part of the application you're building. It's less effort to type <code>import "github.com/vSterlin/sw-store/internal/model"</code>, and to me, it's arguably more communicative: From project <code>sw-store</code>, I'm importing the <em>"internal model"</em> package. That says all it needs to say.</p>\n<p>That being said, you may want to have a read through the <a href=\"https://github.com/golang/go/wiki/CodeReviewComments\" rel=\"nofollow noreferrer\">code review comments</a> on the official golang repo. It does link to some other resources about package names, for example. There's a recommendation to avoid package names that don't communicate much of anything. I understand that a <code>model</code>, especially if you've worked in an MVC style framework, has a meaning. I'm not entirely sold on the name, but that's a matter of personal preference, I suppose.</p>\n<hr />\n<h2>Bigger issues</h2>\n<p>My real concern in the code you posted is the <code>apiserver.go</code> file. Why is the package <code>apiserver</code> aware of what underlying storage solution we're using? Why is it even connecting to the database directly? How are you going to test your code, if an unexported function is always there trying to connect to a DB? You're passing around the raw types. The server expects a <code>*store.Store</code> argument. How can you unit test that? This type expects a DB connection, which it receives from the <code>apiserver</code> package. That's a bit of a mess.</p>\n<p>I noticed you have a <code>config.go</code> file. Consider creating a separate <code>config</code> package, where you can neatly organise your config values on a per-package basis:</p>\n<pre><code>package config\n\ntype Config struct {\n Server\n Store\n}\n\ntype Server struct {\n Port string // etc...\n}\n\ntype Store struct {\n Driver string // e.g. "postgres"\n DSN string // etc...\n}\n\nfunc New() (*Config, error) {\n // parse config from file/env vars/wherever\n return &Config{}, nil\n}\n\nfunc Defaults() *Config {\n return &Config{\n Server: Server{\n Port: ":8081",\n },\n Store: Store{\n Driver: "postgres",\n DSN: "foo@localhost:5432/dbname",\n },\n }\n}\n</code></pre>\n<p>Now each package can have a constructor function that takes in a specific config type, and that package is responsible for interpreting that config, and make sense of it. That way, if you ever need to change the storage you're using from PG to MSSQL or whatever, you don't need to change the <code>apiserver</code> package. That package should be completely unaffected by such a change.</p>\n<pre><code>package store\n\nimport (\n "database/sql"\n\n "github.com/vSterlin/sw-store/internal/config"\n\n _ "github.com/lib/pq"\n)\n\nfunc New(c config.Store) (*Store, error) {\n db, err := sql.Open(c.Driver, c.DSN)\n if err != nil {\n return nil, err\n }\n return &Store{db: db}, nil\n}\n</code></pre>\n<p>Now any code responsible for connecting to a DB is contained within a single package.</p>\n<p>As for your repositories, you're basically allowing them to access the raw connection directly on an unexported field of your <code>Store</code> type. That, too, seems off. Once again: how are you going to unit-test any of this? What if you're having to support different types of storage (PG, MSSQL, etc...?). What you're essentially looking for is something that has the functions <code>Query</code> and <code>QueryRow</code> (probably a couple of other things, but I'm just looking at the code you provided).</p>\n<p>As such, I'd define an interface alongside each repository. For clarity, I'm going to assume the repositories are defined in a separate package, too. This is to emphasise that the interface is to be defined <em>along side the repository</em>, the type that uses the dependency, not the type that implements the interface:</p>\n<pre><code>package repository\n\n//go:generate go run github.com/golang/mock/mockgen -destination mocks/store_mock.go -package mocks github.com/vSterlin/sw-store/internal/repository ProductStore\ntype ProductStore interface {\n Query(q string) (*sql.Rows, error)\n QueryRow(q string, args ...interface{}) *sql.Row\n}\n\ntype PRepo struct {\n s ProductStore\n}\n\nfunc NewProduct(s ProductStore) *PRepo {\n return &PRepo{\n s: s,\n }\n}\n</code></pre>\n<p>So now, in your <code>store</code> package, you would create the repositories like so:</p>\n<pre><code>func (s *Store) Product() *PRepo {\n if s.prepo != nil {\n return s.prepo\n }\n s.prepo = repository.NewProduct(s.db) // implements interface\n return s.prepo\n}\n</code></pre>\n<p>You may have noticed the <code>go:generate</code> comment on the interface. This allows you to run a simple <code>go generate ./internal/repository/...</code> command and it will generate a type for you that perfectly implements the interface your repo depends on. This makes the code in that file <em>unit-testable</em>.</p>\n<hr />\n<h2>Closing connections</h2>\n<p>The one thing you may be wondering is where the <code>db.Close()</code> call should go now. It was deferred in your start function originally. Well, that's quite simple: you just add it to the <code>store.Store</code> type (a stuttering name, BTW, you ought to fix that). Just defer your <code>Close</code> call there.</p>\n<hr />\n<p>There's a lot more stuff we could cover here, like using <code>context</code>, the pro's and con's of using the package structure you're doing, what type of testing we really want/need to write, etc...</p>\n<p>I think, based on the code you've posted here, this review should be enough to get you started, though.</p>\n<p>Have fun.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-21T20:02:45.063",
"Id": "500375",
"Score": "0",
"body": "I'm not quite sure how I would defer a connection Close() there? I have it inside ```apiserver.go``` file in Start function. Not sure where else I would put it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-21T21:57:00.857",
"Id": "500407",
"Score": "0",
"body": "Could you please tell me how to write a test for a handler? Here’s the link to the GetAll handler. Also what other tests are useful?[GetAll handler](https://github.com/vSterlin/Go-Rest-API-Template/blob/master/internal/handlers/getAll.go)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-21T22:20:05.423",
"Id": "500409",
"Score": "0",
"body": "Also not exactly sure why is it better to create interface for ProductStore alongside repository and do it for each repo rather than creating an interface for Store, like so `type PRepo struct { s Store }`? Assuming I defined `type Store interface { Query()... }`."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-21T11:36:42.210",
"Id": "253739",
"ParentId": "253730",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-21T03:31:46.567",
"Id": "253730",
"Score": "3",
"Tags": [
"object-oriented",
"go",
"api",
"rest"
],
"Title": "Golang Rest API"
}
|
253730
|
<p>I have a markdown editor in View A which is showing the result in the current View. I'm trying to pass a result to another page which is View B. In the View A, a button exist to share the markdown result to View B. I'm using texarea for typing text and I have vue-markdown which converts the textarea input to markdown result. My plan is to pass the same vue-markdown result into View B.</p>
<p>View A</p>
<pre><code> <template>
<div class="boxA">
<form id="add-form" >
<div>
<button class="btn-share"@click="shareToPublic()">
Share To View B</button>
</div>
<div>
<input type="text" v-model:value="saveNotes.title">
</div>
<textarea v-model:value="saveNotes.text" name="content"></textarea>
</form>
<vue-markdown :source="saveNotes.text" >
</vue-markdown>
</div>
</template>
<script lang="ts">
import VueMarkdown from 'vue-markdown';
import {Component, Vue} from 'vue-property-decorator';
@Component({
components: {
VueMarkdown,
}
})
export default class MarkdownNotePad extends Vue {
noteList: any[] = [];
saveNotesDefault: NoteType = {
title: '',
text: '',
};
shareToPublic(){
const routData = this.$router.resolve({name:'ViewB'});
window.open(routData.href, 'viewB')
}
</script>
</code></pre>
<p>View B</p>
<pre><code><template>
<div class="container">
<div>
{{ View A markdown result }}
</div>
</div>
</template>
<script lang="ts">
import {Component, Vue} from "vue-property-decorator";
@Component
export default class SharePublic extends Vue {
}
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-21T04:39:10.727",
"Id": "253731",
"Score": "1",
"Tags": [
"typescript",
"vue.js"
],
"Title": "Passing value/data from a page to another page using Vue.js and Typescript"
}
|
253731
|
<p>I'm currently writing an API for our codebase that allows us to use an Arduino Leonardo for our tests. This code is uploaded to the Arduino, and we read through the analog for work.</p>
<p>As stated in the docstring, this function calls a passed function once a threshold has been met. However, I need there to be a delay between function calls, as signals read from the analog can fluctuate and cause the <code>callback</code> function to be called more than expected. So, I devised a solution that requires the signals to depreciate 1/10 of the <code>threshold</code> value in order for <code>callback</code> to be executed again. The <code>secondFactor</code> is if the user wants to define their own limit of when they want the function to be called again. For example:</p>
<pre><code>NeuroBoard board;
board.setTriggerOnEvenlope(700, Serial.println("Reached!");
</code></pre>
<p>This executes the statement once <code>700</code> is reached. Then once <code>630</code> is reached (<code>700 - (700 x .10)</code>), it set a boolean flag so that once <code>700</code> is reached <em>again</em>, it will be called. For another example:</p>
<pre><code>NeuroBoard board;
board.setTriggerOnEnvelope(700, Serial.println("Reached!"), 500);
</code></pre>
<p>Same as above, however the boolean flag will only be set once the signals reach <code>500</code>.</p>
<p>I hope I've explained everything so that it's easily understandable. If anything is unclear, please leave a comment and I'll address it! Below is the code:</p>
<p><strong>NeuroBoard.hpp</strong> (code omitted for brevity)</p>
<pre><code>class NeuroBoard {
private:
bool thresholdMet = false;
public:
/**
* Calls the passed function when the envelope value is greater
* than the passed threshold.
*
* @param threshold Threshold for envelope value.
* @param callback Function to call when threshold is reached.
* @param secondFactor Optional parameter for the second threshold the data must pass.
*
* @return void.
**/
void setTriggerOnEnvelope(const unsigned int& threshold, void callback(), const unsigned int& secondFactor=0);
}
</code></pre>
<p><strong>NeuroBoard.cpp</strong> (code omitted for brevity)</p>
<p>The <code>ISR</code> is basically a timer that runs on the Arduino. I've configured it so every second I get about ~50,000 readings from the analog per second. The <code>envelopeValue</code> is the highest reading recorded, then subtracted by one every time a reading isn't equal to or greater than it.</p>
<pre><code>int envelopeValue;
ISR (TIMER1_COMPA_vect) {
int reading = analogRead(channel);
envelopeValue = (reading >= envelopeValue) ? reading : envelopeValue - 1;
}
void NeuroBoard::setTriggerOnEnvelope(const unsigned int& threshold, void callback(), const unsigned int& secondFactor=0) {
// TODO: Call callback when passed threshold is met by envelope value.
const int THRESHOLD_SCALE_FACTOR = threshold / 10;
int secondThreshold = secondFactor;
if (secondFactor == 0) {
secondThreshold = threshold - THRESHOLD_SCALE_FACTOR;
}
if (envelopeValue >= threshold) {
if (!this->thresholdMet) {
this->thresholdMet = true;
callback();
}
} else {
if (envelopeValue <= secondThreshold) {
this->thresholdMet = false;
}
}
}
</code></pre>
<p><em>Note: Because this code is for an Arduino, I cannot use any standard library functions or imports. However, because this section of our code is pure <code>c++</code>, I don't think it will be an issue. But please consider that if you decide to write an answer. Thanks!</em></p>
|
[] |
[
{
"body": "<p>Pass small trivial types by value.</p>\n<pre><code>void f(unsigned ui); // GOOD\nvoid f(const unsigned& ui); // WORSE\n</code></pre>\n<hr />\n<p>C and C++ don't do parameters of function type; they do parameters of <em>function pointer</em> type.</p>\n<pre><code>void f(void callback()); // BAD\nvoid f(void (*callback)()); // GOOD\n</code></pre>\n<p>See <a href=\"https://lkml.org/lkml/2015/9/3/428\" rel=\"nofollow noreferrer\">Linus Torvalds' take on "parameters of array type"</a>, and then apply the same attitude to "parameters of function type." Don't write them. Write what you mean, instead.</p>\n<hr />\n<p>Prefer signed <code>int</code> over <code>unsigned int</code>, unless you're doing bit-twiddling. Especially in your case, where the user might legitimately pass in a <code>secondThreshold</code> of zero or negative. See <a href=\"https://quuxplusone.github.io/blog/2018/03/13/unsigned-for-value-range/#the-original-design-for-the-stl\" rel=\"nofollow noreferrer\">"The <code>unsigned</code> for value range antipattern"</a> (2018-03-13).</p>\n<hr />\n<p><a href=\"https://quuxplusone.github.io/blog/2020/04/18/default-function-arguments-are-the-devil/\" rel=\"nofollow noreferrer\">Default function arguments are the devil.</a> Prefer overloading:</p>\n<pre><code>void setTriggerOnEnvelope(int threshold, void (*cb)(), int cooldown);\n\nvoid setTriggerOnEnvelope(int threshold, void (*cb)()) {\n return setTriggerOnEnvelope(threshold, cb, threshold - threshold/10);\n}\n</code></pre>\n<p>Notice how I just shortened your original code by about 7 lines, because now you don't need all those helper variables (<code>secondFactor</code>, <code>THRESHOLD_SCALE_FACTOR</code>) and you don't need any mutation.</p>\n<hr />\n<p>In fact, you should consider giving those two functions <em>different names</em>. Right now, it is much too easy for a careless programmer or refactorer to write</p>\n<pre><code>board.setTriggerOnEnvelope(700, [](){ Serial.println("Reached!"); });\n</code></pre>\n<p>when they actually meant</p>\n<pre><code>board.setTriggerOnEnvelope(700, [](){ Serial.println("Reached!"); }, 350);\n</code></pre>\n<p>If the two-argument version were named <code>setTriggerOnEnvelopeWithDefaultCooldown</code>, it'd be a lot harder for the programmer to run into a bug by forgetting the right number of arguments. See <a href=\"https://quuxplusone.github.io/blog/2020/10/09/when-to-derive-and-overload/#when-should-i-put-two-functions-into-an-overload-set\" rel=\"nofollow noreferrer\">"Inheritance is for sharing an interface (and so is overloading)"</a> (2020-10-09).</p>\n<hr />\n<pre><code>// TODO: Call callback when passed threshold is met by envelope value.\n</code></pre>\n<p>This TODO comment seems "done", doesn't it? Anyway, you should certainly not have any TODO comments left in code that you're posting to the CodeReview Stack Exchange, because we explicitly don't review non-working code.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-23T05:39:33.933",
"Id": "500503",
"Score": "0",
"body": "Thanks for the answer! The TODO comments are just a little reminder what the function needs to do so I don't have to keep flipping back to the documentation. The overloading tip works great, thanks!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-23T15:21:11.280",
"Id": "500532",
"Score": "1",
"body": "IIUC, you're saying that you habitually write comments of the form `// TODO: Find the mean of the inputs` where a typical programmer would write `// Find the mean of the inputs`? Don't do that! Reserve `TODO` (and also `FIXME`) for commenting on things that are actually _to do_ in the codebase, like `// TODO: find an algorithm that handles overflow better`. (Imagine you woke up to find your spouse had gone out for the day and left behind a list of tasks labeled \"TO DO\"... but it was mostly stuff they'd already done. Confusing, right?)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-22T15:09:59.727",
"Id": "253779",
"ParentId": "253735",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "253779",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-21T08:51:53.340",
"Id": "253735",
"Score": "1",
"Tags": [
"c++",
"arduino"
],
"Title": "Calling a function once a threshold is met"
}
|
253735
|
<p>Currently I'm working on a way to handle resources in my game engine. It is my first iteration and I would like to expand on it in the future like asynchronous loading of resources. I am looking for some feedback and advice in order to improve it.</p>
<p>The API consists of the following classes.</p>
<p><strong>identifier</strong><br />
Is responsible for creating unique identifiers from a string for usage in the cache(unordered_map). This is done at compile time by hashing a string to an unique int by using the fn1a algorithm</p>
<p><strong>resource_cache</strong><br />
Responsibe for managing the cache, by loading/unloading resources and giving out handles to the resources.</p>
<p><strong>resource_loader</strong><br />
An interface implemented by the user to load an specific resource.</p>
<p><strong>resource_handle</strong><br />
Handle to an specific resource, could be containing a nullptr resource if the specific resource has not been loaded.</p>
<p><strong>Questions</strong><br />
I am looking for some feedback and advice on the following topics.</p>
<ul>
<li>Any potential memory leaks?</li>
<li>Is the API clear and concise</li>
</ul>
<p>There is also one potential issue with dangling pointers I have yet to find an answer to. This happens when a resource is loaded and then erased, all handles given out in between will have an dangling pointer that could result in potential issues for users. I could use shared pointers but I would like to make sure a resource is unloaded once unload is called instead of keeping the resource intact till all handles are destroyed. Reference counting might sound as a nice feature but when managing large resources I would prefer to be able to unload a resource at any specific time and just reset the resource to nullptr. I might implement a specific cache for smaller resources that will implement reference counting in the future though.</p>
<p><strong>Code</strong><br />
<strong>identifier.h</strong></p>
<pre class="lang-cpp prettyprint-override"><code>#pragma once
#include <utils/string_hash.h>
#include <cstring>
namespace engine
{
namespace resources
{
struct identifier
{
using string_hash = engine_core::utils::fnv1a<uint32_t>;
constexpr identifier(const char* identifier)
: hash(string_hash::hash(identifier)), data(identifier)
{
}
constexpr bool operator==(const identifier& rhs) const
{
return hash == rhs.hash;
}
constexpr bool operator==(const uint32_t key) const
{
return hash == key;
}
const bool operator==(const char* key) const
{
return strcmp(data, key) == 0;
}
const uint32_t hash;
const char* data;
};
}
}
</code></pre>
<p><strong>resource_loader.h</strong></p>
<pre class="lang-cpp prettyprint-override"><code>#pragma once
#include "identifier.h"
namespace engine
{
namespace resources
{
template<typename T>
class resource_cache;
template<typename T, typename... Args>
class resource_loader
{
friend class resource_cache<T>;
virtual const T load(const identifier& key, Args... args) const = 0;
};
}
}
</code></pre>
<p><strong>resource_handle.h</strong></p>
<pre class="lang-cpp prettyprint-override"><code>#pragma once
#include <assert.h>
namespace engine
{
namespace resources
{
template<typename T>
class resource_handle
{
public:
resource_handle() = default;
resource_handle(T& resource)
: m_resource(&resource)
{
}
~resource_handle() = default;
[[nodiscard]] T& get()
{
assert(m_resource != nullptr);
return *m_resource;
}
[[nodiscard]] const T& get() const
{
assert(m_resource != nullptr);
return *m_resource;
}
[[nodiscard]] explicit operator const bool() const
{
return static_cast<const bool>(m_resource);
}
private:
T* m_resource = nullptr;
};
}
}
</code></pre>
<p><strong>resource_cache.h</strong></p>
<pre class="lang-cpp prettyprint-override"><code>#pragma once
#include "identifier.h"
#include <utility>
#include <unordered_map>
#include <cstdint>
#include <string>
#include <type_traits>
namespace engine
{
namespace resources
{
template<typename T, typename... Args>
struct resource_loader;
template<typename T>
struct resource_handle;
template<typename T>
class resource_cache
{
public:
template<typename Loader, typename... Args>
resource_handle<T> load(const identifier& identifier, Args&&... args)
{
static_assert(std::is_base_of<resource_loader<T, Args...>, Loader>::value, "Loader needs to be of type resource_loader");
static Loader loader{};
return resource_handle<T>((m_cache.emplace(identifier.hash, std::move(loader.load(identifier, std::forward<Args>(args)...))).first)->second);
};
void unload(const identifier& identifier)
{
typename std::unordered_map<uint32_t, T>::iterator it = m_cache.find(identifier.hash);
m_cache.erase(identifier.hash);
}
void clear()
{
m_cache.clear();
}
[[nodiscard]] resource_handle<T> get_handle(const identifier& identifier)
{
typename std::unordered_map<uint32_t, T>::iterator it = m_cache.find(identifier.hash);
if (it == m_cache.end())
return resource_handle<T>();
return resource_handle<T>(it->second);
}
[[nodiscard]] uint64_t size()
{
return m_cache.size();
}
private:
std::unordered_map<uint32_t, T> m_cache;
};
}
}
</code></pre>
<p><strong>string_hash.h</strong><br />
Not really looking for a review on this but is needed in order to run the rest of the code.</p>
<pre class="lang-cpp prettyprint-override"><code>#pragma once
#include <cstdint>
namespace engine_core
{
namespace utils
{
template<typename T> struct fnv_internal;
template <typename T> struct fnv1;
template <typename T> struct fnv1a;
template <> struct fnv_internal<uint32_t>
{
constexpr static uint32_t default_offset_basis = 0x811C9DC5;
constexpr static uint32_t prime = 0x01000193;
};
template <> struct fnv1<uint32_t> : public fnv_internal<uint32_t>
{
constexpr static inline uint32_t hash(char const* const aString, const uint32_t val = default_offset_basis)
{
return (aString[0] == '\0') ? val : hash(&aString[1], (val * prime) ^ uint32_t(aString[0]));
}
};
template <> struct fnv1a<uint32_t> : public fnv_internal<uint32_t>
{
constexpr static inline uint32_t hash(char const* const aString, const uint32_t val = default_offset_basis)
{
return (aString[0] == '\0') ? val : hash(&aString[1], (val ^ uint32_t(aString[0])) * prime);
}
};
}
}
</code></pre>
<p><strong>Possible implementation</strong></p>
<pre class="lang-cpp prettyprint-override"><code>#include <iostream>
struct loader : public engine::resources::resource_loader<int, int>
{
const int load(const engine::resources::identifier& key, int value) const override
{
return test;
}
};
int main(int argc, char** argv)
{
engine::resources::resource_cache<int> cache;
auto handle = cache.load<loader>(engine::resources::identifier("test_identifier_is_mostly_an_file_path"), 2);
if (handle)
std::cout << handle.get() << "\n";
cache.unload(engine::resources::identifier("test_identifier_is_mostly_an_file_path"));
// possible issue is unloaded and points to dangling pointer
if(handle)
std::cout << handle.get() << "\n";
}
</code></pre>
|
[] |
[
{
"body": "<h1>Enable compiler warnings and fix all warnings</h1>\n<p>My compiler produced some valid warnings about your code. In particular, if you return by value, you shouldn't make the return type <code>const</code>. It has no effect, other than to confuse you. So for example:</p>\n<pre><code>const bool operator==(const char *key) const\n</code></pre>\n<p>Should become:</p>\n<pre><code>bool operator==(const char *key) const\n</code></pre>\n<p>There are more instances of this. There is also a warning about the unused variable <code>it</code> in <code>engine::resources::resource_cache::unload()</code>.</p>\n<h1>Why is there a <code>namespace engine_core</code>?</h1>\n<p>Why is there a separate namespace for the utility functions? Why not put them inside <code>namespace engine</code>?</p>\n<h1>Avoid repeating names</h1>\n<p>There's <code>engine::resources::resource_cache</code>. The word "resource" is repeated twice. It is unnecessary, you could just name it <code>engine::resources::cache</code>. The same goes for <code>resource_handle</code> and <code>resource_loader</code>.</p>\n<h1>Avoid unnecessary casts and use more <code>auto</code></h1>\n<p>There are several places where you unnecessarily cast things, and there are places where you use long type names that can easily be deduced by the compiler. For example, in <code>resource_cache::get_handle()</code> you have:</p>\n<pre><code>typename std::unordered_map<uint32_t, T>::iterator it = m_cache.find(identifier.hash);\n\nif (it == m_cache.end())\n return resource_handle<T>();\n\nreturn resource_handle<T>(it->second);\n</code></pre>\n<p>This can be replaced with:</p>\n<pre><code>auto it = m_cache.find(identifier.hash);\n\nif (it == m_cache.end())\n return {};\n\nreturn it->second;\n</code></pre>\n<p>In the above, the <code>return {}</code> statement works because the compiler already knows the return type, and the empty initializer list <code>{}</code> matches the default constructor or the retun type. This also works for functions arguments, for example here:</p>\n<pre><code>auto handle = cache.load<loader>(engine::resources::identifier("test_identifier_is_mostly_an_file_path"), 2);\n</code></pre>\n<p>The compiler knows that the first argument has to be an <code>engine::resources::identifier</code>, so instead of explicitly creating such a type, you can also provide another argument that matches that of a constructor of <code>engine::resources::identifier</code>. Therefore, you can replace the above with:</p>\n<pre><code>auto handle = cache.load<loader>("test_identifier_is_mostly_an_file_path", 2);\n</code></pre>\n<h1>Replace <code>resource_handle</code> with a bare or a smart pointer</h1>\n<p><code>class resource_haldle</code> is a well written wrapper around a pointer, but it doesn't do anything else besides holding a pointer and giving access to the pointer. So it can just be replaced by a bare pointer instead. What would be better is to determine what kind of ownership semantics the pointer should have that is returned by <code>resource_cache::load()</code>. If, as you mentioned in the comments in <code>main()</code>, you are worried that a handle can turn into a dangling pointer, then you should consider using <a href=\"https://en.cppreference.com/w/cpp/memory/shared_ptr\" rel=\"nofollow noreferrer\"><code>std::shared_ptr</code></a>, or possibly use <code>std::shared_ptr</code> internally and have <code>load()</code> return a <a href=\"https://en.cppreference.com/w/cpp/memory/weak_ptr\" rel=\"nofollow noreferrer\"><code>std::weak_ptr</code></a>.</p>\n<p>For example, in <code>class resource_cache</code>, do the following:</p>\n<pre><code>template<typename T>\nclass resource_cache\n{\npublic:\n template<...>\n std::weak_ptr<T> load(...) {\n ...\n return m_cache.emplace(identifier.hash, loader.load(...)).first->second;\n }\n\nprivate:\n std::unordered_map<uint32_t, std::shared_ptr<T>>;\n};\n</code></pre>\n<p>This requires <code>loader.load()</code> to return a <code>std::shared_ptr<T></code>. Then you can use it like so:</p>\n<pre><code>engine::resources::resource_cache<int> cache;\n\nauto handle = cache.load<loader>("test_identifier_is_mostly_an_file_path", 2);\n \nif (auto resource = handle.lock())\n std::cout << *resource << "\\n";\nelse\n std::cerr << "resource no longer in cache\\n";\n</code></pre>\n<h1>Pass the loader as a function parameter</h1>\n<p>It is a bit weird that you have to pass the loader as a template parameter, and that the instantiation of the template <code>resource_cache::load<>()</code> will create a static variable of that type. This takes away control over the lifetime of the loader from the caller. This is why it would be better to pass the loader as a function parameter, like so:</p>\n<pre><code>template<typename Loader, typename... Args>\nstd::weak_ptr<T> load(Loader &loader, const identifier& identifier, Args&&... args) {\n static_assert(...);\n return m_cache.emplace(identifier.hash, loader.load(...)).first->second;\n};\n</code></pre>\n<p>So you can call it like:</p>\n<pre><code>loader ldr;\nauto handle = cache.load(ldr, "identifier", 2);\n</code></pre>\n<p>Or if you only need a one-shot loader:</p>\n<pre><code>auto handle = cache.load(loader{}, "identifier", 2);\n</code></pre>\n<p>This form also allows the loader to have a constructor that takes arguments, because it's no longer <code>resource_cache</code>'s responsibility to create an instance of the loader.</p>\n<h1>Consider decoupling the loader from the cache</h1>\n<p>The above still looks like there is too tight a coupling between the loader and the resource cache. The only responsibility of the cache should be to store and retrieve items, nothing more. So instead of<code>load()</code> and<code> unload()</code> member functions, I would just have <code>insert()</code> and <code>erase()</code> member functions, like so:</p>\n<pre><code>std::weak_ptr<T> insert(const identifier& identifier, std::shared_ptr<T> handle)\n{\n return m_cache.emplace(identifier.hash, handle).first->second;\n};\n\nvoid erase(const identifier& identifier)\n{\n m_cache.erase(identifier.hash);\n}\n</code></pre>\n<p>And use it like so:</p>\n<pre><code>loader ldr;\nauto handle = cache.insert("identifier", ldr.load(2));\n</code></pre>\n<p>Of course, now <code>resource_cache</code> is basically reduced to a simple wrapper around <code>std::unordered_map</code>, the only extra thing it does is to get the hash of the identifier. And even that is unnecessary:</p>\n<h1>Let <code>std::unordered_map</code> do the hashing for you</h1>\n<p>It's actually very silly to create a hash of an identifier and pass that as the key to a <code>std::unordered_map</code>, when the latter is already implemented as a hash table, and thus will hash the key itself! And it knows how to hash <code>std::string</code>s, so you can replace the cache with:</p>\n<pre><code>template<typename T>\nclass resource_cache\n{\npublic:\n std::weak_ptr<T> insert(const char *identifier, std::shared_ptr<T> handle)\n {\n return m_cache.emplace(identifier, handle).first->second;\n };\n\n ...\nprivate:\n std::unordered_map<std::string, std::shared_ptr<T>> m_cache;\n};\n</code></pre>\n<p>This will also prevent any issues from cache collisions, which your class suffers from.</p>\n<h1>Make it an actual cache</h1>\n<p>You call it a cache, but it has none of the properties of a cache. Caches transparently load and unload resources for you, while your <code>resource_cache</code> has just manual functions to insert and remove items from a container. I would expect the following functionality:</p>\n<ul>\n<li>A single <code>get()</code> function that either returns the value from the cache, or if it doesn't exist, will load it for me.</li>\n<li>The cache will automatically remove (the oldest) items once a certain size is reached.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-21T17:32:22.940",
"Id": "253747",
"ParentId": "253737",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "253747",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-21T09:29:47.610",
"Id": "253737",
"Score": "2",
"Tags": [
"c++"
],
"Title": "Resource management in c++ game engine"
}
|
253737
|
<p>This program calculates the sum of all integers in the range <span class="math-container">\$[1, 1000)\$</span> which are multiples of either 3 or 5 or both.</p>
<p>Inspired by <a href="https://codereview.stackexchange.com/questions/253680/x86-64-assembly-sum-of-multiples-of-3-or-5">x86-64 Assembly - Sum of multiples of 3 or 5</a> the other day, and also drawing from some of what I learned through <a href="https://codereview.stackexchange.com/questions/253721/calculate-the-centroid-of-a-collection-of-complex-numbers">Calculate the centroid of a collection of complex numbers</a> I decided to try to tackle this using C++20 ranges. By heavy use of <code>constexpr</code>, I had hoped to find a solution that would calculate everything at compile time, and indeed this does as you can see if you try it <a href="https://gcc.godbolt.org/z/x8zcK8" rel="noreferrer">online</a>.</p>
<p>This version is inspired by this talk <a href="https://www.youtube.com/watch?v=d_E-VLyUnzc" rel="noreferrer">C++20 Ranges in Practice - Tristan Brindle - CppCon 2020</a>.</p>
<p>I'm interested in general improvements.</p>
<h2>euler1.cpp</h2>
<pre><code>#include <iostream>
#include <concepts>
#include <ranges>
#include <iterator>
#include <functional>
#include <numeric>
template <std::ranges::input_range R,
typename Init = std::ranges::range_value_t<R>>
constexpr Init accumulate(R&& rng, Init init = Init{})
{
return std::reduce(std::ranges::begin(rng), std::ranges::end(rng),
std::move(init));
}
int main() {
constexpr auto div3_or_5 = [](int i){ return i % 3 == 0 || i % 5 == 0; };
std::cout << accumulate(std::ranges::iota_view{1, 1000}
| std::views::filter(div3_or_5)
| std::views::common)
<< '\n';
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-24T11:24:59.477",
"Id": "500614",
"Score": "0",
"body": "That hat really does have your name on it.... `:_)`"
}
] |
[
{
"body": "<p>I see you already solved your own questions from before your latest edit. Just two very minor things that can be improved: you can omit repeating the type name <code>Init</code> in two places:</p>\n<pre><code>template <std::ranges::input_range R, typename Init = std::ranges::range_value_t<R>>\nconstexpr auto accumulate(R&& rng, Init init = {}) \n{\n return std::reduce(std::ranges::begin(rng), std::ranges::end(rng), std::move(init));\n}\n</code></pre>\n<p>And you don't need to use <code>std::views::common</code> in <code>main()</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-22T00:06:28.940",
"Id": "253763",
"ParentId": "253742",
"Score": "4"
}
},
{
"body": "<p>The optional <code>init</code> argement is never used, so we could omit that for this application, and use the two-argument form of <code>std::reduce()</code>.</p>\n<p>That would solve the other issue neatly - failure to include <code><utility></code> before using <code>std::move()</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-24T11:00:26.710",
"Id": "253866",
"ParentId": "253742",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "253866",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-21T16:17:18.397",
"Id": "253742",
"Score": "5",
"Tags": [
"c++",
"programming-challenge",
"functional-programming",
"c++20"
],
"Title": "sum of multiples by 3 or 5 using ranges"
}
|
253742
|
<p>Hello I need help to optimize this code. I have a radar and it gets the enemies from a list and adds an image to their location to track them. I use Update to remove the images and LateUpdate to add the images. Is there any way I can do this without costing performance. I have a list of all the Enemies. I have a pool of over 40 images to use as tracking for the radar. Enemy is always moving. Any ideas?</p>
<pre><code>private void Update()
{
if (statsView_Panel.activeInHierarchy)
{
if (showIndicators_Enemies)
{
if (!enemyListHolder.activeInHierarchy)
{
enemyListHolder.SetActive(true);
}
Remove_PositionIndicatorOnEnemies();
}
}
}
private void LateUpdate()
{
if (showIndicators_Enemies)
{
if (!enemyListHolder.activeInHierarchy)
{
enemyListHolder.SetActive(true);
}
Add_PositionIndicatorOnEnemies();
}
}
private void Add_PositionIndicatorOnEnemies()
{
// Do if ListHolder is Active
if (enemyListHolder.activeInHierarchy)
{
// Run if 1 or more Enemies
if (EnemiesManager.Count > 0)
{
// Check All Enemies
for (int i = 0; i < EnemiesManager.Count; i++)
{
// Check All Indicators
for (int s = 0; s < enemyIndicList.Count; s++)
{
// Choose Indicator that is not active *****BUG: Will Add All Deactivated Indicators to Active Enemies*****
if (enemyIndicList[s].gameObject.activeInHierarchy == false)
{
// Activate Indicator and Reposition
enemyIndicList[s].gameObject.SetActive(true);
Vector3 aLocatorPos;
aLocatorPos = theCam.WorldToScreenPoint(satManager.GetByIndex(i).transform.position);
aLocatorPos.z = 0;
enemyIndicList[s].transform.position = aLocatorPos;
// Break from Loop
break;
}
}
}
}
}
}
private void Remove_PositionIndicatorOnEnemies()
{
// Do if ListHolder is Active
if (enemyListHolder.activeInHierarchy)
{
// Run if 1 or more Enemies
if (EnemiesManager.Count > 0)
{
// Check All Indicators
for (int s = 0; s < enemyIndicList.Count; s++)
{
// Choose Indicator that is active
if (enemyIndicList[s].gameObject.activeInHierarchy == true)
{
// Deactivate Indicator
enemyIndicList[s].gameObject.SetActive(false);
}
}
}
}
}
</code></pre>
|
[] |
[
{
"body": "<p>Let's review the code from bottom to top.</p>\n<h2>Remove_PositionIndicatorOnEnemies</h2>\n<ul>\n<li>Having an underscore in a method name doesn't fit with the <a href=\"https://msdn.microsoft.com/en-us/library/ms229002.aspx\" rel=\"nofollow noreferrer\">.NET naming guidelines</a>.</li>\n<li>By reverting the first <code>if</code> condition you can return early if <code>enemyListHolder.activeInHierarchy</code> is <code>false</code> which saves you one level of indentation.</li>\n<li>The next <code>if</code> condition can be omitted because that check is done inside the loop condition.</li>\n<li>Instead of using a <code>for</code> loop I would prefer a <code>foreach</code> loop and would restrict the items to only them where <code>activeInHierarchy</code> is true by a <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.linq.enumerable.where?view=net-5.0#System_Linq_Enumerable_Where__1_System_Collections_Generic_IEnumerable___0__System_Func___0_System_Boolean__\" rel=\"nofollow noreferrer\">Where()</a> clause.</li>\n</ul>\n<p>Implementing the mentioned changes will lead to</p>\n<pre><code>private void RemovePositionIndicatorOnEnemies()\n{\n if (!enemyListHolder.activeInHierarchy) { return; }\n\n foreach (var enemy in enemyIndicList.Where(e=> e.gameObject.activeInHierarchy))\n {\n enemy.gameObject.SetActive(false);\n }\n} \n</code></pre>\n<h2>Add_PositionIndicatorOnEnemies</h2>\n<p>Here, the first three points from above apply as well.</p>\n<ul>\n<li>The inner <code>for</code> loop can be replaced by <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.linq.enumerable.firstordefault?view=net-5.0#System_Linq_Enumerable_FirstOrDefault__1_System_Collections_Generic_IEnumerable___0__System_Func___0_System_Boolean__\" rel=\"nofollow noreferrer\">FirstOrFDefault()</a> which is more readable.</li>\n</ul>\n<p>Implementing the mentioned changes will lead to</p>\n<pre><code>private void Add_PositionIndicatorOnEnemies()\n{\n if (!enemyListHolder.activeInHierarchy) {return; }\n\n for (int i = 0; i < EnemiesManager.Count; i++)\n {\n var enemy = enemyIndicList.FirstOrDefault(e=> !e.gameObject.activeInHierarchy);\n if (enemy != null)\n {\n enemy.gameObject.SetActive(true);\n Vector3 aLocatorPos = theCam.WorldToScreenPoint(satManager.GetByIndex(i).transform.position);\n aLocatorPos.z = 0;\n enemy.transform.position = aLocatorPos;\n }\n }\n} \n</code></pre>\n<h2>LateUpdate</h2>\n<ul>\n<li>Again returning early will save one level of indentation.</li>\n</ul>\n<p>Implementing the mentioned changes will lead to</p>\n<pre><code>private void LateUpdate()\n{\n if (!showIndicators_Enemies) { return; }\n\n if (!enemyListHolder.activeInHierarchy)\n {\n enemyListHolder.SetActive(true);\n }\n\n Add_PositionIndicatorOnEnemies();\n} \n</code></pre>\n<h2>Update</h2>\n<ul>\n<li>Here we can save two levels of indentation by reverting and combining the first two <code>if</code> conditions.</li>\n</ul>\n<p>Implementing the mentioned changes will lead to</p>\n<pre><code>private void Update()\n{\n if (!statsView_Panel.activeInHierarchy || !showIndicators_Enemies) { return; }\n\n if (!enemyListHolder.activeInHierarchy)\n {\n enemyListHolder.SetActive(true);\n }\n\n Remove_PositionIndicatorOnEnemies();\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-22T15:45:26.767",
"Id": "500461",
"Score": "0",
"body": "Thank you so much, so what I took from this is try to save as many indentations as you can as its more calculations and use more Linq which is meant for the performance of Lists and Arrays. I will be studying more Linq!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-22T12:17:51.593",
"Id": "253774",
"ParentId": "253744",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "253774",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-21T16:30:10.730",
"Id": "253744",
"Score": "0",
"Tags": [
"c#",
"unity3d"
],
"Title": "Unity C# - Radar works but performance is horrible (Update & LateUpdate)"
}
|
253744
|
<p>There is a web page I visit which I would like to print. However, I only want to print a couple of things on it, not everything.</p>
<p>So, I am making a bookmarklet that I can use whenever I visit the page to hide everything from the printer except what I want to print.</p>
<p>The site already has a class, 'd-print-none', to hide an element from the printer.</p>
<p>The following code is the javascript I made to base my bookmarklet on.</p>
<p>My idea is to first apply the 'd-print-none' class to everything. Then selectively remove it.</p>
<p>I remove the class from the element that contains what I would like to print as well as any of its children.</p>
<p>Then I recursively remove it from the parents until I reach the document element.</p>
<pre><code>function removeClass(t_selector, t_class){
document.querySelectorAll(t_selector + ' *').forEach(x=>x.classList.remove(t_class))
node = document.querySelector(t_selector)
while (node && node.nodeType != Node.DOCUMENT_NODE) {
node.classList.remove.(t_class);
node = node.parentNode;
}
}
document.querySelectorAll( '*' ).forEach(x=>x.classList.add('d-print-none'))
removeClass('app-flex-chart', 'd-print-none')
removeClass('app-flex-grid', 'd-print-none')
</code></pre>
<p>Adding the class to all elements was pretty straightforward and succinct as was removing it from all of the target element's children.</p>
<p>Climbing the tree to apply it to the element itself and any of its parents was more verbose and error prone. Sadly, there appears to be no css selector to find all parents of an element.</p>
<p>I paired the loop down to be as succinct and readable as I could.</p>
<p>I am looking for ideas on how to make it more robust, succinct, or readable. Open to any and all suggestions and criticisms.</p>
<p>For that while loop, I had to check if the node I was on existed and check to make sure it wasn't the document node, either case would cause an error.</p>
<p>EDIT: To show generic structure of page</p>
<pre><code><html>
<head>...</head>
<body>
<many>
<nested>
<tags>
<app-flex-chart>
<many-more-nested-tags>Actual Content</many-more-nested-tags>
</app-flex-chart>
</tags>
</nested>
</many>
</body>
</html>
</code></pre>
<p>The app-flex-chart tag is the only unique piece along the chain to the content. All other classes and tags seem to be reused throughout the page.</p>
|
[] |
[
{
"body": "<p><strong>Declare variables before using them</strong> - your <code>node</code> variable is never declared. Use <code>let node =</code> instead.</p>\n<p><strong>Typo?</strong> <code>node.classList.remove.(t_class)</code> should be <code>node.classList.remove(t_class);</code></p>\n<p><strong>Variable casing</strong> The vast majority of professional JavaScript uses <code>camelCase</code> for most variables, including parameters. There are a few exceptions (like <code>ALL_CAPS</code> for things like constant magic numbers, and <code>PascalCase</code> for constructors and namespaces).</p>\n<p><strong>Variable names</strong> It's not entirely clear on the initial encounter of <code>removeClass</code> what the parameters mean. Maybe change:</p>\n<ul>\n<li><code>t_selector</code> -> <code>selectorToShow</code></li>\n<li><code>t_class</code> -> <code>hiddenClassName</code></li>\n</ul>\n<p>or something similar.</p>\n<p><strong>Always use strict equality</strong>, avoid sloppy equality to avoid readers of the code having to understand <a href=\"https://stackoverflow.com/questions/359494/which-equals-operator-vs-should-be-used-in-javascript-comparisons\">coercion weirdness</a> to be 100% confident of what the code is doing.</p>\n<p><strong>Semicolons</strong> Either use semicolons when appropriate, or (if you don't like them <em>and</em> you're an expert who can avoid the pitfalls of <a href=\"https://stackoverflow.com/questions/2846283/what-are-the-rules-for-javascripts-automatic-semicolon-insertion-asi\">ASI</a>) don't. To be stylistically consistent, choose one style and stick with it. Consider <a href=\"https://eslint.org/docs/rules/semi\" rel=\"nofollow noreferrer\">a linting rule</a>.</p>\n<p><strong>Relying on a site's classes is unreliable</strong>, especially for sites that are being actively maintained and developed. Many of those who write bookmarks and userscripts are familiar with this issue. The site may change their CSS, resulting in <code>d-print-none</code> doing nothing. Bookmarklets and userscripts are prone to requiring updates when a site changes regardless - but reducing the chance of needing maintenance when a change occurs is good.</p>\n<p>Whatever <code>d-print-none</code> does currently, I'd append another <code><style></code> tag that inserts your own class (or data attribute) that does the same thing, eg:</p>\n<pre><code>const style = document.body.appendChild(document.createElement('style'));\nstyle.textContent = `\n@media print\n{ \n .melted-bookmarklet-print-none, .melted-bookmarklet-print-none *\n {\n display: none !important;\n }\n}\n`;\n</code></pre>\n<p>Then toggle <em>that</em> class instead (and do <code>style.remove()</code> at the end if you want).</p>\n<p>(You might be tempted to iterate through the elements and apply the style directly to elements, but that could break the site's built-in display properties if it happens to have styles already applied directly to elements.)</p>\n<p>Or, <strong>you could use CSS alone instead of iterating through elements</strong>. How exactly to do this depends on where the <code>app-flex-chart</code> and <code>app-flex-grid</code> are located on the page, but it could look something like this, if they're both descendants of the <code><body></code>:</p>\n<pre><code>const style = document.body.appendChild(document.createElement('style'));\nstyle.textContent = `\n@media print\n{ \n body > *:not(app-flex-chart):not(app-flex-grid),\n body > *:not(app-flex-chart):not(app-flex-grid) * {\n display: none !important;\n }\n}\n`;\n</code></pre>\n<p>(feel free to engineer to be more flexible and less repetitive if you think it'd be helpful)</p>\n<p>This way, all elements which are not the <code>.app-flex-chart</code> nor <code>.app-flex-grid</code> will be hidden, without any intermediate classes or element iteration.</p>\n<p><strong>Or save a reference to the two elements you want to print, remove everything, then append the two back</strong>:</p>\n<pre><code>const elms = ['app-flex-chart', 'app-flex-grid'].map(s => document.querySelector(s));\ndocument.body.textContent = '';\nfor (const elm of elms) {\n document.body.appendChild(elm);\n // if needed to put them on separate lines:\n document.body.appendChild(document.createElement('div'));\n}\n</code></pre>\n<p>That's the version I'd prefer, if feasible. You may have to insert intermediate elements for the page's styles to apply. (If that gets too complicated, use a different approach.) If you want the original page to remain interactable, you could open a <em>new</em> window which gets populated with the content of <code>elms</code> instead. (You'll also have to append <code><style></code> and CSS link tags from the original page)</p>\n<p><strong>Bookmarklet or userscript?</strong> You're currently using this as a bookmarklet. It depends how you're managing them, but if you aren't using a special utility for it, I think userscripts are more maintainable, due to a few factors:</p>\n<ul>\n<li><p>Userscript editor interfaces are <em>meant</em> to be usable as code editors. In contrast, a bookmarklet, when installed, isn't very user-friendly to edit:</p>\n<p><a href=\"https://i.stack.imgur.com/TzaMN.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/TzaMN.png\" alt=\"enter image description here\" /></a></p>\n</li>\n<li><p>Userscripts can be saved in separate external files, rather than existing in the browser's internal ether.</p>\n</li>\n<li><p>Userscripts are more flexible in when they're run. Most importantly, they can run automatically without requiring a click. You may find this helpful.</p>\n</li>\n</ul>\n<p>If you want to try this out as a userscript, try <a href=\"https://www.tampermonkey.net/\" rel=\"nofollow noreferrer\">Tampermonkey</a>.</p>\n<p>Depending on how you're using the printed page and how often you're printing, you can consider using <a href=\"https://stackoverflow.com/a/57218292\">Puppeteer</a> in Node to scrape and print the elements completely automatically.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-21T19:38:37.113",
"Id": "500372",
"Score": "0",
"body": "I am still digesting your answer. However, I most like your suggestion to use css alone. However, when I use your example code, everything becomes hidden."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-21T19:45:50.973",
"Id": "500373",
"Score": "0",
"body": "You'll have to tweak the code depending on the layout of the site in question. Working demo here: https://jsfiddle.net/wza6x9mr/"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-21T20:10:32.147",
"Id": "500377",
"Score": "0",
"body": "Ah, I see the issue now, but don't know the solution. The elements to be shown are nested within other elements. These other parent elements need to be shown as well or the children remain hidden. See demo: https://jsfiddle.net/m0cyqr28/"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-21T20:34:11.423",
"Id": "500381",
"Score": "0",
"body": "If they're not on the same level, it'll be more tedious: https://jsfiddle.net/5f3xvwb0/ I'd prefer a different method"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-21T20:45:00.553",
"Id": "500383",
"Score": "0",
"body": "The two tags are nested 9 and 10 levels deep."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-21T20:47:55.487",
"Id": "500384",
"Score": "0",
"body": "Regarding user script vs bookmarklet, part of my end game is to make something my non-code saavy coworkers can reproduce. My plan is to tell them to take the code to bookmarkleter and follow the (simple) directions there. I think that is the best compromise for allowing readability and simplicity. For myself, I'll just keep the code as a snippet to run and debug from the console."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-21T18:02:05.310",
"Id": "253748",
"ParentId": "253745",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-21T17:02:19.613",
"Id": "253745",
"Score": "2",
"Tags": [
"javascript",
"css",
"query-selector",
"bookmarklet"
],
"Title": "Selectively printing elements on web page using a bookmarklet"
}
|
253745
|
<p>I built upon a previous beginners' class' hangman game to do graphics with Turtle. It should work with any .txt list of words in whatever location you specify at the top of the code (in my case on Windows, E:/My Documents/Programming/Projects/Hangman/words.txt). Alternatively you can uncomment the commented line containing <code>#COMMENT AFTER TESTING</code> and comment the line containing <code>#UNCOMMENT AFTER TESTING</code> at the start of Main to use <code>test</code> as the word to be guessed.</p>
<p>How did I do? What can/should I improve upon?</p>
<p>EDIT to add: I neglected to mention which code was borrowed from the lesson. I've added a comment where the code becomes mine.</p>
<pre><code>import random
WORDLIST_FILENAME = "E:/My Documents/Programming/Projects/Hangman/words.txt"
def loadWords():
"""
Returns a list of valid words. Words are strings of lowercase letters.
"""
print("Loading word list from file...")
# inFile: file
inFile = open(WORDLIST_FILENAME, 'r')
# line: string
line = inFile.readline()
# wordlist: list of strings
wordlist = line.split()
print(" ", len(wordlist), "words loaded.")
return wordlist
def chooseWord(wordlist):
"""
wordlist (list): list of words (strings)
Returns a word from wordlist at random
"""
return random.choice(wordlist)
</code></pre>
<h2>end of lecturer's code</h2>
<pre><code>def isWordGuessed(secretWord, lettersGuessed):
'''
secretWord: string, the word the user is guessing
lettersGuessed: list, what letters have been guessed so far
returns: boolean, True if all the letters of secretWord are in lettersGuessed;
False otherwise
'''
secretWordList = list(secretWord)
return all(elem in lettersGuessed for elem in secretWordList)
def getGuessedWord(secretWord, lettersGuessed):
'''
secretWord: string, the word the user is guessing
lettersGuessed: list, what letters have been guessed so far
returns: string, comprised of letters and underscores that represents
what letters in secretWord have been guessed so far.
'''
secretWordList = list(secretWord)
lettersGuessedList = list(set(lettersGuessed))
for letter in secretWordList:
if letter not in lettersGuessedList:
secretWordList[secretWordList.index(letter)] = '_ '
return ''.join(map(str, secretWordList))
def getAvailableLetters(lettersGuessed):
'''
lettersGuessed: list, what letters have been guessed so far
returns: string, comprised of letters that represents what letters have not
yet been guessed.
'''
import string
alphaList = list(string.ascii_lowercase)
for char in lettersGuessed:
if char in alphaList:
alphaList.remove(char)
return ''.join(map(str, alphaList))
#-----Setup-----
import turtle
wordlist = loadWords()
version = "v0.1"
gameTitle = "Basic Hangman "+version
window = turtle.Screen()
window.title(gameTitle)
window.bgcolor("black")
window.setup()
window.tracer(0)
tMessage = "Welcome to "+gameTitle+"!"
bMessage = "Input 'new' for a new game or 'quit' to quit."
font = ("Share Tech Mono", 24, "normal")
#TopText
tText = turtle.Turtle()
tText.speed(0)
tText.color("darkgreen")
tText.penup()
tText.hideturtle()
tText.goto(0,-260)
tText.write(tMessage, align="center", font=(font))
#BottomText
bText = turtle.Turtle()
bText.speed(0)
bText.color("darkgreen")
bText.penup()
bText.hideturtle()
bText.goto(0,-290)
bText.write(bMessage, align="center", font=(font))
#Creating the noose
noose = turtle.Turtle()
noose.width(10)
noose.hideturtle()
noose.color("darkgreen")
noose.penup()
#Drawing the noose
def drawNoose():
noose.penup()
noose.goto(-200,-200)
noose.pendown()
noose.goto(200,-200)
noose.goto(150,-200)
noose.goto(100,-150)
noose.goto(50,-200)
noose.penup()
noose.goto(100,-200)
noose.pendown()
noose.goto(100,200)
noose.goto(0,200)
noose.penup()
window.update()
#Creating the man
man = turtle.Turtle()
man.width(10)
man.hideturtle()
man.color("darkgreen")
man.penup()
#Drawing the man
def newLimb(limbs):
if limbs == 6: #Draw rope
man.goto(0,200)
man.pendown()
man.goto(0,150)
man.penup()
elif limbs == 5: #Draw head
man.goto(0,100)
man.pendown()
man.circle(25)
man.penup()
elif limbs == 4: #Draw body
man.goto(0,100)
man.pendown()
man.goto(0,25)
man.penup()
elif limbs == 3: #Draw left leg
man.goto(0,25)
man.pendown()
man.goto(-30,-40)
man.penup()
elif limbs == 2: #Draw right leg
man.goto(0,25)
man.pendown()
man.goto(30,-40)
man.penup()
elif limbs == 1: #Draw left arm
man.goto(0,75)
man.pendown()
man.goto(-30,15)
man.penup()
elif limbs == 0:
#Draw right arm
man.goto(0,75)
man.pendown()
man.goto(30,15)
man.penup()
guessedLetterRaw = turtle.textinput("Input", ' ')
guessedLetter = guessedLetterRaw.lower()
# --- Main ---
while guessedLetter == 'new':
drawNoose()
man.clear()
lettersGuessed = []
#secretWord = "test" #COMMENT AFTER TESTING
secretWord = chooseWord(wordlist).lower() #UNCOMMENT AFTER TESTING
guessesLeft = 7
tText.clear()
bText.clear()
tMessage = "Welcome to "+gameTitle+"!"
while guessesLeft > 0:
# Window Updating
bMessage = 'Remaining letters: ' + getAvailableLetters(lettersGuessed)
window.update()
bText.clear()
bText.write(bMessage, align="center", font=(font))
tText.clear()
tText.write(tMessage, align="center", font=(font))
# Guessing
guessedLetter = turtle.textinput("Input", 'Please guess a letter:')
if guessedLetter in lettersGuessed:
tMessage = "Oops! You've already guessed that letter: " + getGuessedWord(secretWord, lettersGuessed)
else:
lettersGuessed.append(guessedLetter)
if guessedLetter in secretWord:
if isWordGuessed(secretWord, lettersGuessed):
noose.clear()
tText.clear()
man.clear()
for n in range(0, 6):
newLimb(n)
tMessage = 'Congratulations, you won!'
tText.write(tMessage, align="center", font=(font))
guessedLetter = turtle.textinput("Input", "Input 'new' for a new game or 'quit' to quit.")
break
else:
tMessage = 'Good guess: ' + getGuessedWord(secretWord, lettersGuessed)
else:
guessesLeft -= 1
newLimb(guessesLeft)
if guessesLeft < 1:
tText.clear()
tMessage = 'Sorry, you ran out of guesses. The word was ' + secretWord + '.'
tText.write(tMessage, align="center", font=(font))
guessedLetter = turtle.textinput("Input", "Input 'new' for a new game or 'quit' to quit.")
else:
tMessage = 'Oops! That letter is not in my word: ' + getGuessedWord(secretWord, lettersGuessed)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-21T20:05:07.057",
"Id": "500376",
"Score": "0",
"body": "Whereas your lecturer has issues in their code that I've spoken about in my answer, there's a policy about code ownership on Code Review - it has to be yours. Overall I'd say that you have enough of your own code here that this is not off-topic; and hopefully you can derive learning value from the issues in the lecturer's code as well as your own."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-21T20:11:09.653",
"Id": "500378",
"Score": "0",
"body": "All of that is to say - your question is good as-is, but for sure next time it would be good to delineate authorship from the get-go."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-21T21:22:27.250",
"Id": "500400",
"Score": "0",
"body": "Yeah I only included it in order for someone to be able to easily run the entire code on their own without having to put effort into writing loadWords() and chooseWord(). I didn't realize until your corrections that it was not only not helpful but accidentally dishonest; not that anyone's going to be extending a job offer because I did such a great job importing a list from a text document and choosing a random item in a list.\n\nMy main hurdles now are figuring out how best - and why - to encompass the global code in functions. I will reply to your answer in an itemized fashion momentarily."
}
] |
[
{
"body": "<h2>Relative file paths</h2>\n<pre><code>WORDLIST_FILENAME = "E:/My Documents/Programming/Projects/Hangman/words.txt"\n</code></pre>\n<p>should be modified so that it's relative. The easy thing to do is make it relative to the current directory and assume that the current directory is that of the project, but that's a little fragile. The more reliable thing to do is make this relative to the location of the current Python file, for which you can use <code>__file__</code>. Either way, using <code>pathlib</code> will make this relative-operation easy.</p>\n<h2>Context management for file handles</h2>\n<pre><code>inFile = open(WORDLIST_FILENAME, 'r')\n</code></pre>\n<p>first of all, this does not have a corresponding <code>close()</code>, which is important. Beyond that, though, a <code>close</code> as implied by a <code>with open()</code> is safer than an explicit close, so do the latter.</p>\n<h2>File format</h2>\n<p>It seems that your file assumes a word list all on one line, separated by spaces. The more usual, marginally easier, and potentially (?) more performant thing to do is separate by line breaks. Python has more built-in machinery to do this - you can simply treat the file handle itself as an iterable over the file's lines, and would not need a call to <code>split</code>.</p>\n<h2>Formatting</h2>\n<pre><code>print(" ", len(wordlist), "words loaded.")\n</code></pre>\n<p>is probably better-represented as</p>\n<pre><code>print(f'{len(words)} words loaded.')\n</code></pre>\n<p>Also note that <code>words</code> is a slightly simpler name for that variable, and the <code>list</code> part can be conveyed using a type hint. The type hint needn't even be <code>list</code> if you <code>yield</code> from the file handle, i.e.</p>\n<pre><code>def load_words() -> Iterable[str]:\n with open(WORD_LIST_FILENAME) as f:\n yield from f\n</code></pre>\n<h2>Unnecessary casts</h2>\n<pre><code>secretWordList = list(secretWord)\nreturn all(elem in lettersGuessed for elem in secretWordList)\n</code></pre>\n<p>does not need the first line, since it's assumed that <code>secretWord</code> (which should be <code>secret_word</code>) is iterable. Also, this is better-represented by a set:</p>\n<pre><code>def is_word_guessed(secret_word: str, letters_guessed: Set[str]) -> bool:\n return set(secret_word) <= letters_guessed\n</code></pre>\n<h2>getGuessedWord</h2>\n<p>Consider representing this as a <code>join</code> on a generator rather than an intermediate <code>list</code>:</p>\n<pre><code>def get_guessed_word(secret_word: str, letters_guessed: Set[str]) -> str:\n return ''.join(\n c if c in letters_guessed else '_'\n for c in secret_word\n ) \n</code></pre>\n<h2>Avoid local imports</h2>\n<p>Move this import:</p>\n<pre><code>def getAvailableLetters(lettersGuessed):\n import string\n</code></pre>\n<p>to the top of the file.</p>\n<h2>Set subtraction</h2>\n<p>Consider rewriting <code>getAvailableLetters</code> to use set subtraction:</p>\n<pre><code>def get_available_letters(letters_guessed: Set[str]) -> str:\n return ''.join(set(ascii_lowercase) - letters_guessed)\n</code></pre>\n<h2>Global code</h2>\n<p>You have a bunch of it, starting at</p>\n<pre><code>#-----Setup-----\n</code></pre>\n<p>Move this into functions.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-21T21:29:00.603",
"Id": "500403",
"Score": "0",
"body": "The file path was a compatibility issue when writing the original console-based game that Visual Studio Code was unable to fetch the words.txt file in the same folder. Can't remember exactly how it was pulled before but I do remember they had a troubleshooting step-by-step and manually entering the file path like that was the final (and luckily functional) step. I'll have to look in to your suggestions, including how to ensure it'll run on the target machine.\n\nI've heard of the perils of not close()-ing a file - I foolishly trusted the lecturer wrote perfect code and overlooked it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-21T21:37:27.767",
"Id": "500405",
"Score": "0",
"body": "Something I've encountered a lot in my recent outside-of-coursework learning is the use of <= and ->, which you seem to use quite frequently. It was never mentioned in my intro to Python class and I'll have to figure out how and when to use that.\n\nYou mention making getGuessedWord a generator - I thought those were functions that use 'yield'?\n\nWould including that global setup code in a setup() function to be run after defining it be preferable?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-22T21:49:30.033",
"Id": "500476",
"Score": "0",
"body": "_making getGuessedWord a generator_ - not quite. The function uses a generator internally but is not itself a generator. The generator is everything within the `join()`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-22T21:50:37.913",
"Id": "500477",
"Score": "0",
"body": "_Would including that global setup code in a setup() function to be run after defining it be preferable?_ - a new `setup` and `main` at the very least, if not more functions for granularity."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-21T19:41:34.267",
"Id": "253751",
"ParentId": "253746",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "253751",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-21T17:29:09.413",
"Id": "253746",
"Score": "3",
"Tags": [
"python",
"beginner",
"game",
"hangman",
"turtle-graphics"
],
"Title": "Python Beginner - Basic Hangman Game Using Turtle"
}
|
253746
|
<p>I'm designing a Matrix class and I feel like what I've come up with requires too many calls to <code>new</code>. I know it's possible that caring about this is premature, but I already know I need this code to be fast, so I'd like to think about streamlining it now.</p>
<p>Here's a test to show how I intend to use the API:</p>
<pre class="lang-csharp prettyprint-override"><code>[Fact]
public void TranslateFluentAPI()
{
Matrix4 t = Matrix4.Identity().Translate(5, -3, 2);
Point p = new Point(-3, 4, 5);
Assert.True(t * p == new Point(2, 1, 7));
// Same, but use the parameterless c'tor, which is equivalent to
// calling Identity();
Matrix4 t2 = new Matrix4().Translate(5, -3, 2);
Assert.True(t2 * p == new Point(2, 1, 7));
}
</code></pre>
<p>And my code stripped down to the relevant parts (only missing additional matrix math and similar subclasses for Matrix3, Matrix2)</p>
<pre class="lang-csharp prettyprint-override"><code>using System;
using static System.Math;
public abstract class Matrix : IEquatable<Matrix>
{
// 2D array that stores Matrix data.
protected double[,] data;
// Concrete Matrix classes must override a size.
abstract protected int size { get; }
public Matrix(double[,] data)
{
if (data.GetLength(0) != size || data.GetLength(1) != size) {
throw new ArgumentException(
$"The provided 2D array needs to have a length of {size} "+
"in both dimensions.");
}
this.data = data;
}
public Matrix()
{
// Do nothing.
}
// Square bracket getter/setter
public double this[int x, int y] {
get { return this.data[x, y]; }
set { this.data[x, y] = value; }
}
#region Equality
public bool Equals(Matrix other)
{
if (size != other.size) {
throw new ArgumentException(
$"Cannot compare a matrix of size {other.size} to a matrix"+
$"of size {size}.");
}
double epsilon = 0.00001;
for (int x = 0; x < size; x += 1) {
for (int y = 0; y < size; y += 1) {
if (! (Abs(this[x, y] - other[x, y]) < epsilon)) {
// One element is not equal, so matrices are not equal.
return false;
}
}
}
// All elements were equal
return true;
}
public override bool Equals(object obj)
{
return Equals(obj as Matrix);
}
public override int GetHashCode()
{
return data.GetHashCode();
}
public static bool operator ==(Matrix obj1, Matrix obj2)
{
return obj1.Equals(obj2);
}
public static bool operator !=(Matrix obj1, Matrix obj2)
{
return ! obj1.Equals(obj2);
}
#endregion
}
public class Matrix4 : Matrix
{
protected override int size => 4;
public Matrix4(double[,] data) : base(data)
{
// Do nothing, calling base class.
}
public Matrix4() : base()
{
data = Matrix4.Identity().data;
}
public static implicit operator Matrix4(double[,] m) => new Matrix4(m);
public static Matrix4 Identity()
{
return new Matrix4(new double[,] {
{1, 0, 0, 0},
{0, 1, 0, 0},
{0, 0, 1, 0},
{0, 0, 0, 1},
});
}
public static Matrix4 operator *(Matrix4 a, Matrix4 b)
{
double[,] result = new double[4, 4];
for (int x = 0; x < a.size; x += 1) {
for (int y = 0; y < a.size; y += 1) {
result[x, y] =
a[x, 0] * b[0, y] +
a[x, 1] * b[1, y] +
a[x, 2] * b[2, y] +
a[x, 3] * b[3, y];
}
}
return new Matrix4(result);
}
public Matrix4 Translate(double x, double y, double z)
{
Matrix4 t = Matrix4.Identity();
t[0, 3] = x;
t[1, 3] = y;
t[2, 3] = z;
this.data = (t * this).data;
return this;
}
}
</code></pre>
<p>So adding up calls to new:</p>
<pre class="lang-csharp prettyprint-override"><code>// Using the static Identity method:
Matrix4 t = Matrix4.Identity().Translate(5, -3, 2);
// This is 5 calls to new.
// As a convenience I have the parameterless c'tor to return the identity,
// so that you can do this:
Matrix4 t = new Matrix4().Translate(5, -3, 2);
// This is 6 calls to new.
</code></pre>
<p>Premature optimization aside, at the very least <strong>I wish I could make the second form not cost more than the first</strong>, because it feels like a much more intuitive way to use the API.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-23T16:59:35.167",
"Id": "500541",
"Score": "0",
"body": "@Heslacher I'm not sure what you think you're missing. I assure you the implementation of IEquatable, ToString, and a few operators are not at all relevant this question about c'tors. I probably should have posted to SO but they usually downvote for the question being too broad ..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-23T17:10:26.893",
"Id": "500542",
"Score": "0",
"body": "Well at least the implementation of the `*` operator is needed."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-23T17:22:04.510",
"Id": "500543",
"Score": "0",
"body": "@Heslacher ah sure thing, just updated. I believe that code is entirely self-contained now."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-23T17:37:36.893",
"Id": "500547",
"Score": "0",
"body": "Ok, for me it seems sufficient code now. If you don't receive a review I will check it out on monday."
}
] |
[
{
"body": "<p>First let's target your main concern regarding <code>Matrix4 t = new Matrix4().Translate(5, -3, 2);</code> using the same number of ctor calls as <code>Matrix4 t = Matrix4.Identity().Translate(5, -3, 2);</code>.</p>\n<p>This can be easily achieved by extracting the <code>double[,]</code> out of <code>Identity()</code> like so</p>\n<pre><code>private static readonly double[,] identityData = new double[,] {\n {1, 0, 0, 0},\n {0, 1, 0, 0},\n {0, 0, 1, 0},\n {0, 0, 0, 1},\n};\npublic static Matrix4 Identity()\n{\n return new Matrix4(identityData);\n} \n</code></pre>\n<p>now the call to the parameterless ctor will look like so</p>\n<pre><code>public Matrix4() : base()\n{\n data = identityData;\n} \n</code></pre>\n<hr />\n<p>In the <code>Translate()</code> method you are only interested in the <code>data</code> of the multiplied matrixes. You <strong>could</strong> extract the multiplication into a separate <code>Multiply()</code> method which would be called by the <code>Translate()</code> method and in the <code>*</code> operator like so</p>\n<pre><code>public static Matrix4 operator *(Matrix4 a, Matrix4 b)\n{\n return new Matrix4(Multiply(a.data, b.data));\n\n}\nprivate static double[,] Multiply(double[,] a, double[,] b)\n{\n int size = a.GetLength(0);\n double[,] result = new double[size, size];\n\n for (int x = 0; x < size; x += 1)\n {\n for (int y = 0; y < size; y += 1)\n {\n result[x, y] =\n a[x, 0] * b[0, y] +\n a[x, 1] * b[1, y] +\n a[x, 2] * b[2, y] +\n a[x, 3] * b[3, y];\n }\n }\n return result;\n}\npublic Matrix4 Translate(double x, double y, double z)\n{\n Matrix4 t = Matrix4.Identity();\n t[0, 3] = x;\n t[1, 3] = y;\n t[2, 3] = z;\n this.data = Multiply(t.data, this.data);\n return this;\n} \n</code></pre>\n<p>It is only a matter of taste, but I prefer to use e.g <code>x++</code> over <code>x +=1</code>.</p>\n<hr />\n<p>You <strong>could</strong> save one more call to the ctor by just using the <code>identityData</code> inside the <code>Translate()</code> method like so</p>\n<pre><code>public Matrix4 Translate(double x, double y, double z)\n{\n double[,] t = identityData;\n t[0, 3] = x;\n t[1, 3] = y;\n t[2, 3] = z;\n this.data = Multiply(t, this.data);\n return this;\n} \n</code></pre>\n<p>Summing up will lead to</p>\n<pre><code>public class Matrix4 : Matrix\n{\n protected override int size => 4;\n\n public Matrix4(double[,] data) : base(data)\n { } // Do nothing, calling base class.\n\n\n public Matrix4() : base()\n {\n data = identityData;\n }\n\n public static implicit operator Matrix4(double[,] m) => new Matrix4(m);\n\n private static readonly double[,] identityData = new double[,] {\n {1, 0, 0, 0},\n {0, 1, 0, 0},\n {0, 0, 1, 0},\n {0, 0, 0, 1},\n };\n public static Matrix4 Identity()\n {\n return new Matrix4(identityData);\n }\n\n public static Matrix4 operator *(Matrix4 a, Matrix4 b)\n {\n return new Matrix4(Multiply(a.data, b.data));\n\n }\n private static double[,] Multiply(double[,] a, double[,] b)\n {\n int size = a.GetLength(0);\n double[,] result = new double[size, size];\n\n for (int x = 0; x < size; x += 1)\n {\n for (int y = 0; y < size; y += 1)\n {\n result[x, y] =\n a[x, 0] * b[0, y] +\n a[x, 1] * b[1, y] +\n a[x, 2] * b[2, y] +\n a[x, 3] * b[3, y];\n }\n }\n return result;\n }\n public Matrix4 Translate(double x, double y, double z)\n {\n double[,] t = identityData;\n t[0, 3] = x;\n t[1, 3] = y;\n t[2, 3] = z;\n this.data = Multiply(t, this.data);\n return this;\n }\n}\n</code></pre>\n<p>Now <code>Matrix4 t = Matrix4.Identity().Translate(5, -3, 2);</code> and <code>Matrix4 t = new Matrix4().Translate(5, -3, 2);</code> only call the ctor once. <strong>You</strong> need to decide if the code is still readable and maintainable.</p>\n<hr />\n<p>Base class</p>\n<p>The <code>Equals(Matrix)</code> should check for <code>null</code> for the passed <code>Matrix other</code>. Its better to return <code>false</code> if <code>other == null</code> than to get a <code>NullReferenceException</code>.</p>\n<pre><code>public bool Equals(Matrix other)\n{\n if (other == null) { return false; }\n\n if (size != other.size)\n {\n throw new ArgumentException(\n $"Cannot compare a matrix of size {other.size} to a matrix" +\n $"of size {size}.");\n }\n\n double epsilon = 0.00001;\n for (int x = 0; x < size; x += 1)\n {\n for (int y = 0; y < size; y += 1)\n {\n if (!(Abs(this[x, y] - other[x, y]) < epsilon))\n {\n return false;\n }\n }\n }\n\n return true;\n}\n</code></pre>\n<p>Both, the <code>==</code> and <code>!=</code> operator should check for <code>null</code> as well like so</p>\n<pre><code>public static bool operator ==(Matrix obj1, Matrix obj2)\n{\n if (ReferenceEquals(obj1, obj2)) { return true; }\n if (ReferenceEquals(obj1, null)) { return false; }\n if (ReferenceEquals(obj2, null)) { return false; }\n\n return obj1.Equals(obj2);\n}\n\npublic static bool operator !=(Matrix obj1, Matrix obj2)\n{\n return !(obj1 == obj2);\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-30T20:52:14.497",
"Id": "501152",
"Score": "0",
"body": "Awesome thank you @heslacher, I was just working out the need to compare to null, and your equality implementation totally makes sense! Something is funky about the static identityData solution though. See here: https://dotnetfiddle.net/k9aVHW\nI think that's because in the Matrix4 parameterless c'tor you assign `data` to `identityData` which becomes a reference. Then elsewhere, any client that mutates its copy of an identity matrix actually changes the underlying readonly(!) static data. Seems like I want to make a copy of `identityData`, but I'm back to needing another `new` for that ..."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-28T06:32:59.077",
"Id": "253987",
"ParentId": "253749",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-21T18:26:15.107",
"Id": "253749",
"Score": "5",
"Tags": [
"c#",
"performance",
"matrix"
],
"Title": "Optimizing Matrix class with less calls to new"
}
|
253749
|
<p>Some friends and I were playing the game Spot It, which has <code>x</code> cards each with <code>y</code> symbols on them, from a potential of <code>z</code> potential symbols. The trick is every card has exactly 1 of the same symbol as any other card in the deck. We were talking about the numbers <code>y</code> and <code>z</code> effect the total number of possible cards <code>x</code>, and we could not figure out a formula for figuring it out. I decided I would just write a program to brute force it below:</p>
<pre><code>class Program
{
static void Main(string[] args)
{
Console.WriteLine("Number of cards: {0}", getCount(55, 8));
}
static int getCount(int numberOfSymbols, int symbolsPerCard)
{
int[] nextCardArr = new int[symbolsPerCard];
for (int i = 0; i < symbolsPerCard; i++)
{
nextCardArr[i] = i;
}
HashSet<int> potentialCard;
List<HashSet<int>> deck = new List<HashSet<int>>();
while (getNextValidCard(nextCardArr, numberOfSymbols, out potentialCard))
{
if (isValidInDeck(potentialCard, deck))
{
deck.Add(potentialCard);
}
}
return deck.Count;
}
private static bool isValidInDeck(HashSet<int> potentialCard, List<HashSet<int>> deck)
{
bool retVal = true;
foreach (HashSet<int> card in deck)
{
int commonalities = 0;
foreach (int symbol in potentialCard)
{
if (card.Contains(symbol))
{
commonalities++;
}
}
retVal = retVal && commonalities == 1;
commonalities = 0;
}
return retVal;
}
private static bool isValidCard(int[] potentialCard)
{
HashSet<int> tester = new HashSet<int>(potentialCard);
return tester.Count == potentialCard.Length;
}
private static bool getNextValidCard(int[] nextCardArr, int numberOfSymbols, out HashSet<int> potentialCard)
{
potentialCard = new HashSet<int>(nextCardArr);
bool isThereAValidCard = false;
int i = 0;
while(true)
{
if (nextCardArr[i] < numberOfSymbols)
{
nextCardArr[i]++;
if (isValidCard(nextCardArr))
{
isThereAValidCard = true;
break;
}
}
else if (nextCardArr[i] == numberOfSymbols)
{
nextCardArr[i] = 0;
while (!isValidCard(nextCardArr))
{
nextCardArr[i]++;
}
i++;
if (i == nextCardArr.Length)
{
break;
}
}
}
return isThereAValidCard;
}
}
</code></pre>
<p>I'm quite certain the program is working, but it is ridiculously slow because of how it brute forces every potential card and then tests if it can be added to the deck. I'm really at a loss of how to better approach this problem to create a more efficient program, so I thought I'd ask here. I am also not 100% sure it's totally correct as all the decks it creates all match on the same symbol, but I'm thinking that may be ok for calculating 1 possible deck, and the max cards doesn't change if that weren't the case.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-21T22:04:12.107",
"Id": "500408",
"Score": "0",
"body": "I'm pretty sure that, for any given y, there is an optimal z which gives the largest possible number of cards. For example, if y is 2 and z is 3, then x is 3. Changing z to 4 doesn't increase x, but only makes it so that you can generate 4 different decks of size 3. What you need is an expert in combinatorics - there are some peculiar techniques for figuring stuff like this out."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-22T03:22:27.640",
"Id": "500432",
"Score": "1",
"body": "I was going to write an answer but this is best https://math.stackexchange.com/a/36806 basically symbolsPerCard should be prime and `total = symbolsPerCard * symbolsPerCard + symbolsPerCard + 1`, Card range can be total to `total - (symbolsPerCard - 1)`"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-21T20:39:41.973",
"Id": "253754",
"Score": "0",
"Tags": [
"c#",
"algorithm"
],
"Title": "Creating a deck for a card game"
}
|
253754
|
<p>Hello everyone and thanks in advance for taking the time to read my post!!</p>
<p>In the process of learning Ruby, I'm writing a video poker machine that analyzes hands represented by arrays of Cards, like so: <code>[ card, card, card, card, card ]</code></p>
<p>You may know that in draw poker, one can <em>hold</em> certain cards and toss the rest to the dealer, to be replaced by <em>drawing</em> new cards from the deck in the hopes of improving one's hand (hence the name). It's natural to figure that holds would be represented by an array of boolean values. To wit: <code>[ true, true, false, false, false ]</code> would mean holding the first two cards in a five-card hand and discarding the rest. What I'm trying to write is a method that will give me an array of all possible holds (an array of arrays) for a given hand size.</p>
<p>I've found that Ruby is terrific (though a bit slow) for permutations and combinations, i.e., all possible unique hands from a 52-card deck. All I have to do for that is call <code>deck.combination( hand_size ).to_a</code>. But unfortunately neither <code>.permutation</code> nor <code>.combination</code> is really giving me what I need for a method to produce possible holds.</p>
<p>High school math (which I'm terrible at, by the way) tells me that when determining possible unique <code>n</code>-combinations of two possible values, the size of the universe of all possible <code>n</code>-combinations will be two to the power of <code>n</code> - meaning there are 32 possible holds for a five-card poker hand.</p>
<p>After slaughtering a snow-white bull for the gods at midnight under a full moon, I've come up with the following solution using binary numbers. This method loops through a range from <code>0...2 ** hand_size</code>, turns each element of the range into a binary number string with a <code>hand_size</code> number of leading zeroes using <code>.rjust</code>, then <code>.map</code>s each character in the string to an array of <code>hand_size</code> elements using a conditional and ternary; if the character is <code>"1"</code> it maps a <code>true</code> to the array, otherwise the character is a <code>"0"</code> and it maps <code>false</code> to the array.</p>
<pre><code>def possible_holds( hand_size )
result = []
for each_hold in 0...2 ** hand_size do
as_binary = each_hold.to_s( 2 ).rjust( hand_size, "0" )
result << ( 0...hand_size ).to_a.map{ | card | as_binary[ card ] == "1" ? true : false }
end
result
end
</code></pre>
<p>This clunky little method actually works very well, but... it just doesn't seem very <em>rubinic</em>. I would love to hear clever suggestions as to how to improve it. I have this nagging feeling that this can all be done with a neat, simple method/enumerable or two... but no matter how many virgins I sacrifice I just can't seem to come up with anything better.</p>
<p>Thanks in advance for your help and happy coding!!</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-17T00:50:20.347",
"Id": "500385",
"Score": "0",
"body": "If `n = 5`, `a = n.times.to_a.combination(2).to_a #=> [[0, 1], [0, 2], [0, 3], [0, 4], [1, 2], [1, 3], [1, 4], [2, 3], [2, 4], [3, 4]]` are the `10` (`n*(n-1)/2`) ways of holding 2 cards in a 5-card hand. Each element gives the indices of the two cards to be kept. If the hand were `hand = ['4D', 'AS', 'KH', '6C', 'QD']`, the possible pairs of cards to keep would be `a.map { |b| a.values_at(*b) } #=> [[\"4D\", \"AS\"], [\"4D\", \"KH\"], [\"4D\", \"6C\"], [\"4D\", \"QD\"], [\"AS\", \"KH\"], [\"AS\", \"6C\"], [\"AS\", \"QD\"], [\"KH\", \"6C\"], [\"KH\", \"QD\"], [\"6C\", \"QD\"]]`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-17T00:51:20.747",
"Id": "500386",
"Score": "0",
"body": "What's your actual end-goal here? If you want to *manage* the hand, you can simply #pop or #delete the elements you want to remove, and replace them with new cards. I'm not sure what you're gaining by adding a layer of indirection with mapping the cards to boolean values first, or what you're actually trying to calculate."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-17T00:52:28.537",
"Id": "500387",
"Score": "0",
"body": "That's wonderful Cary!!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-17T00:53:37.253",
"Id": "500388",
"Score": "0",
"body": "Hi Todd, eventually I'd like to make a hash with each hold as a key corresponding to a value of the best hand possible with that hold."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-17T01:27:52.540",
"Id": "500389",
"Score": "0",
"body": "Cheers @steenslag that's a great point, I suppose it'd be better to calculate the average of all possible hands for a given hold and pick the highest"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-17T03:08:25.670",
"Id": "500390",
"Score": "0",
"body": "Split the hand into keep vs. discard, then permute only the discard count."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-17T03:12:44.083",
"Id": "500391",
"Score": "0",
"body": "Note: Ruby code really doesn't use `for`, as strange as that may seem. What this code reduces to, as-is, becomes: `(2 ** hand_size).times.map do |i|` where you use `map` to produce the result and can skip the `result=[] ... result` part."
}
] |
[
{
"body": "<p>Here's a demonstration of how you might solve this problem the Ruby way:</p>\n<pre class=\"lang-rb prettyprint-override\"><code>SUITS = %w[ H D C S ]\nFACES = %w[ 2 3 4 5 6 7 8 9 T J Q K A ]\n\nCARDS = SUITS.flat_map { |s| FACES.map { |f| "#{f}#{s}" } }\n\ndef holds(hand)\n hand.length.times.flat_map do |n|\n hand.combination(n).to_a\n end << hand\nend\n\nholds(CARDS.shuffle.take(5))\n</code></pre>\n<p>Where you get results like this:</p>\n<pre><code>[[],\n ["AD"],\n ["5H"],\n ["QS"],\n ["4H"],\n ["5D"],\n ["AD", "5H"],\n ["AD", "QS"],\n ["AD", "4H"],\n ["AD", "5D"],\n ["5H", "QS"],\n ["5H", "4H"],\n ["5H", "5D"],\n ["QS", "4H"],\n ["QS", "5D"],\n ["4H", "5D"],\n ["AD", "5H", "QS"],\n ["AD", "5H", "4H"],\n ["AD", "5H", "5D"],\n ["AD", "QS", "4H"],\n ["AD", "QS", "5D"],\n ["AD", "4H", "5D"],\n ["5H", "QS", "4H"],\n ["5H", "QS", "5D"],\n ["5H", "4H", "5D"],\n ["QS", "4H", "5D"],\n ["AD", "5H", "QS", "4H"],\n ["AD", "5H", "QS", "5D"],\n ["AD", "5H", "4H", "5D"],\n ["AD", "QS", "4H", "5D"],\n ["5H", "QS", "4H", "5D"],\n ["AD", "5H", "QS", "4H", "5D"]]\n</code></pre>\n<p>Personally I'd hold the pair of 5s and the Ace.</p>\n<p>For educational purposes here's a more Ruby-esque form of your original code:</p>\n<pre class=\"lang-rb prettyprint-override\"><code>def possible_holds(hand_size)\n (2 ** hand_size).times.map do |n|\n n.to_s(2).rjust(hand_size, '0').chars.map { |c| c == '1' }\n end\nend\n</code></pre>\n<p>It's kind of messy due to the binary string to boolean conversion.</p>\n<blockquote>\n<p>Tip: Try to avoid "casting a boolean to a boolean" as in patterns like <code>x ? true : false</code> or <code>if x; true; else; false</code> like you had in your code. That reduces down to just <code>x</code>. The <code>x == '1'</code> test already returns a <code>true</code> or <code>false</code> value. There is no <code>maybe</code> or <code>kind_of</code> response.</p>\n</blockquote>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-17T03:44:59.020",
"Id": "500392",
"Score": "1",
"body": "I can't thank you enough for this wonderful response!! I am coming from Java which is shaping my thinking but it seems like I need to shift my thinking from using an array of booleans to picking specific cards by name, since that will enable me to make more powerful use of Ruby's combination method. Your tip about casting boolean to boolean is a priceless pearl of wisdom!! Again and again: THANK YOU"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-31T19:06:21.230",
"Id": "504010",
"Score": "0",
"body": "If you change `hand.length.times` to `0..hand.length` you don't need `<< hand`."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-17T03:17:45.443",
"Id": "253757",
"ParentId": "253756",
"Score": "1"
}
},
{
"body": "<h2>Analyzing a Single Hand with User-Selected Discards</h2>\n<p>I may be completely misunderstanding your problem. I'm sure there's already an algorithm out there somewhere for calculating the odds of a given hand, or you could construct a Monte Carlo simulation. That said, it seems like this <em>might</em> get you where you're trying to go by building a result set of all possible combinations based on the cards remaining in your hand after <em>selecting</em> the ones to discard.</p>\n<p>Using Ruby 2.7.2:</p>\n<pre class=\"lang-rb prettyprint-override\"><code>MAX_HAND_SIZE = 5\n\nsuit = (2..10).to_a + %w[J Q K A]\ndeck = suit * 4\ndeck.shuffle!\n\nhand = deck.pop MAX_HAND_SIZE\n#=> [3, 7, 2, 7, "J"]\n\ndiscards = []\ndiscards +=\n [3, 2, "J"].map { hand.delete_at hand.find_index _1 }\n\ncombos =\n deck.\n combination(MAX_HAND_SIZE - hand.size).\n to_a.\n map { _1.append *hand }.\n uniq\n</code></pre>\n<p>Calling <code>combos.size</code> shows that, with this particular shuffle and this particular starting hand, you have 1,956 unique hands when drawing from the remaining deck. You can then analyze those possible hands for strength or value in whatever way you were planning to do before.</p>\n<p>This approach neatly side-steps the indirection of trying to map your intended discards to a Boolean value, but still allows you to calculate all the potential hands available when refilling from the remaining deck.</p>\n<h2>All Possible Permutations of a Hand</h2>\n<p>If you're trying to do something more complex, like trying to determine all possible variations of a 1..3 card draw or a 0..5 card draw, the problem quickly becomes much more complex. In trying to answer your question, I found myself with what <em>seemed</em> like a good answer until I realized that you would probably have to run something like:</p>\n<pre class=\"lang-rb prettyprint-override\"><code>permuted_hand = (2..4).map { |i| hand.permutation(i).to_a }\n</code></pre>\n<p>on each drawn hand, and then generate potential combinations based on dropping each of the permutations from that hand. This quickly got out of hand (if you'll pardon the pun) both in terms of logic, runtime, and combinations, so I didn't pursue it any further.</p>\n<p>In <a href=\"https://stackoverflow.com/questions/65332930/ruby-possible-poker-holds-for-a-hand-of-length-n#comment115503043_65332930\">comments</a>, you stated:</p>\n<blockquote>\n<p>[E]ventually I'd like to make a hash with each hold as a key corresponding to a value of the best hand possible with that hold.</p>\n</blockquote>\n<p>Even if you were able to calculate that for a given hand in a given shuffled deck, I suspect that this would be hard to generalize outside the current round of play without a very large statistical sample and a lot more math. This sort of work has certainly been done before for other games of chance, so there's bound to be some research out there, but it may be more of a statistical or mathematical modeling question than strictly a programming one. If you don't get a good answer here on Stack Overflow, it may be worth kicking the tires on your mathematical or statistical model on a <a href=\"https://math.stackexchange.com/\">math-related stack</a> instead.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-18T04:12:53.560",
"Id": "500393",
"Score": "0",
"body": "Hi Todd, sorry for my delay in replying but I so appreciate this detailed, thoughtful analysis!!! I actually took a very similar path in getting possible hands from a deck: first:\nhold_cards.each{ | hold_card | deck.delete( hold_card ) }\nto strip the deck of hold cards, then calling\ndeck.combination( hand_size - hold_cards.length ).to_a.map{ | hand | hand.concat( hold_cards ) }\nto generate smaller-sized hand combos and then mapping hold cards to each combo!\nAnd I also found Ruby's ranges wonderful useful for generating decks!! Ruby is a poker fanatic's dream!!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-17T04:10:06.227",
"Id": "253758",
"ParentId": "253756",
"Score": "0"
}
},
{
"body": "<p>This is a variant of @tadman's answer, just to show there are different ways to achieve the same results.</p>\n<pre><code>SUITS = %w[ H D C S ]\nFACES = %w[ 2 3 4 5 6 7 8 9 T J Q K A ]\n</code></pre>\n\n<pre><code>CARDS = SUITS.product(FACES).map { |s,f| "#{f}#{s}" }\n #=> ["2H", "3H", "4H", "5H", "6H", "7H", "8H", "9H", "TH", "JH", "QH", "KH",\n # "AH", "2D", "3D", "4D", "5D", "6D", "7D", "8D", "9D", "TD", "JD", "QD",\n # "KD", "AD", "2C", "3C", "4C", "5C", "6C", "7C", "8C", "9C", "TC", "JC",\n # "QC", "KC", "AC", "2S", "3S", "4S", "5S", "6S", "7S", "8S", "9S", "TS",\n # "JS", "QS", "KS", "AS"]\n</code></pre>\n<p>See <a href=\"https://ruby-doc.org/core-2.7.0/Array.html#method-i-product\" rel=\"nofollow noreferrer\">Array#product</a>.</p>\n<hr />\n<pre><code>def holds(hand)\n hand.repeated_combination(hand.size).map(&:uniq).uniq\nend\n</code></pre>\n\n<pre><code>hand = CARDS.sample(5)\n #=> ["TC", "8S", "4H", "6H", "JD"]\narr = holds(hand)\n #=> [["TC"], ["TC", "8S"],...,["6H"], ["6H", "JD"], ["JD"], []]\n</code></pre>\n<p>We can better see what we have by sorting <code>arr</code> by size:</p>\n<pre><code>arr.sort_by(&:size)\n #=> [[],\n # ["8S"], ["TC"], ["4H"], ["6H"], ["JD"],\n # ["4H", "6H"], ["8S", "4H"], ["8S", "6H"], ["8S", "JD"], ["TC", "JD"],\n # ["TC", "6H"], ["TC", "4H"], ["6H", "JD"], ["4H", "JD"], ["TC", "8S"],\n # ["TC", "8S", "4H"], ["TC", "8S", "JD"], ["TC", "4H", "6H"],\n # ["TC", "4H", "JD"], ["TC", "6H", "JD"], ["8S", "4H", "6H"],\n # ["8S", "4H", "JD"], ["8S", "6H", "JD"], ["4H", "6H", "JD"],\n # ["TC", "8S", "6H"],\n # ["TC", "4H", "6H", "JD"], ["TC", "8S", "4H", "6H"],\n # ["TC", "8S", "6H", "JD"], ["TC", "8S", "4H", "JD"],\n # ["8S", "4H", "6H", "JD"],\n # ["TC", "8S", "4H", "6H", "JD"]]\n</code></pre>\n<p>See <a href=\"https://ruby-doc.org/core-2.7.0/Array.html#method-i-repeated_combination\" rel=\"nofollow noreferrer\">Array#repeated_combination</a> and <a href=\"https://ruby-doc.org/core-2.7.0/Array.html#method-i-sample\" rel=\"nofollow noreferrer\">Array#sample</a>.</p>\n<p>Let's look at the first part of the calculation.</p>\n<pre><code>enum = hand.repeated_combination(hand.size)\n #=> #<Enumerator: ["TC", "8S", "4H", "6H", "JD"]:repeated_combination(5)>\narr = enum.to_a\n #=> [["TC", "TC", "TC", "TC", "TC"], ["TC", "TC", "TC", "TC", "8S"],\n # ... \n # ["TC", "TC", "TC", "8S", "8S"], ["TC", "TC", "TC", "8S", "4H"],\n # ...\n # ["TC", "TC", "8S", "8S", "8S"], ["TC", "TC", "8S", "8S", "4H"],\n # ...\n # ["TC", "8S", "8S", "8S", "8S"], ["TC", "8S", "8S", "8S", "4H"],\n # ...\n # ["8S", "8S", "8S", "8S", "8S"], ["8S", "8S", "8S", "8S", "4H"],\n # ...\n # ["4H", "4H", "4H", "4H", "4H"], ["4H", "4H", "4H", "4H", "6H"],\n # ...\n # ["6H", "6H", "6H", "6H", "6H"], ["6H", "6H", "6H", "6H", "JD"],\n # ["6H", "6H", "6H", "JD", "JD"], ["6H", "6H", "JD", "JD", "JD"],\n # ["6H", "JD", "JD", "JD", "JD"],\n # ["JD", "JD", "JD", "JD", "JD"]]\narr.size\n #=> 126\n</code></pre>\n<p>This becomes:</p>\n<pre><code>arr.map(&:uniq)\n #=> [["TC"], ["TC", "8S"],\n # ... \n # ["TC", "8S"], ["TC", "8S", "4H"],\n # ...\n # ["TC", "8S"], ["TC", "8S", "4H"],\n # ...\n # ["TC", "8S"], ["TC", "8S", "4H"],\n # ...\n # ["8S"], ["8S", "4H"],\n # ...\n # ["4H"], ["4H", "6H"],\n # ...\n # ["6H"], ["6H", "JD"],\n # ["6H", "JD"], ["6H", "JD"],\n # ["6H", "JD"],\n # ["JD"]]\n</code></pre>\n<p>The final <code>.uniq</code> returns an array to which an empty array is appended.</p>\n<p>This is grossly inefficient relative to other calculations that could be performed to achieve the same result, but we are only dealing with hand sizes of <code>5</code>, not <code>10,000</code>, so who cares?</p>\n<hr />\n<p>As for the OP's method <code>possible_holds</code>, we could write it as follows:</p>\n<pre><code>def possible_holds(hand_size)\n (0..2 ** hand_size - 1).map { |n| hand_size.times.map { |i| n[i] == 1 } } \nend\n</code></pre>\n\n<pre><code>arr = possible_holds(5)\n #=> [[false, false, false, false, false], [true, false, false, false, false],\n # [false, true, false, false, false], [true, true, false, false, false],\n # [false, false, true, false, false], [true, false, true, false, false],\n # [false, true, true, false, false], [true, true, true, false, false],\n # [false, false, false, true, false], [true, false, false, true, false],\n # [false, true, false, true, false], [true, true, false, true, false],\n # [false, false, true, true, false], [true, false, true, true, false],\n # [false, true, true, true, false], [true, true, true, true, false],\n # [false, false, false, false, true], [true, false, false, false, true],\n # [false, true, false, false, true], [true, true, false, false, true],\n # [false, false, true, false, true], [true, false, true, false, true],\n # [false, true, true, false, true], [true, true, true, false, true],\n # [false, false, false, true, true], [true, false, false, true, true],\n # [false, true, false, true, true], [true, true, false, true, true],\n # [false, false, true, true, true], [true, false, true, true, true],\n # [false, true, true, true, true], [true, true, true, true, true]]\n</code></pre>\n<p>See <a href=\"https://ruby-doc.org/core-2.7.0/Integer.html#method-i-5B-5D\" rel=\"nofollow noreferrer\">Integer#[]</a>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-31T20:48:38.873",
"Id": "255446",
"ParentId": "253756",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-17T00:09:47.910",
"Id": "253756",
"Score": "0",
"Tags": [
"ruby",
"combinatorics"
],
"Title": "Ruby: possible Poker holds for a hand of length n"
}
|
253756
|
<p>We are working on a complicated math problem, very detailed question with description of the problem is here: <a href="https://codereview.stackexchange.com/questions/252718/c-multi-threaded-determination-of-curling-numbers-in-vectors">C++ multi-threaded determination of curling numbers in vectors</a>.</p>
<p>That code is now converted to use 256-bit registers to store the bit sequences. Profiling pointed to one function taking over 85% of the total CPU time. I have extracted that function into a test project.</p>
<p>The time-critical function is counting repeated bit patterns at the end of a 256-bit sequence. For example, <code>0b1000100010001000</code> have tree <code>0</code> at the end, and four <code>1000</code>. We are looking for a highest frequency, so 4 in this case. We are not interested in the pattern length below 10, or the frequencies over 4. The test case used below is</p>
<pre><code>// sequence with 84 '0' and 1 '1', repeated three times
__m256i seq = _mm256_set_epi64x(0x00000000'00000000, 0x00000400'00000000,
0x00000000'00200000, 0x00000000'00000001);
</code></pre>
<p>The development is done on MS Visual Studio 2019, will possibly also run on Linux.</p>
<p>To speed things up, we are using AVX intrinsics.</p>
<p>We are pre-computing all bit masks for 128-bit registers. Attempted to calculate the mask as needed to avoid going to memory, but it was slower.</p>
<p>Our estimate is that the entire program would solve the problem in weeks, so we are looking for any kind of performance improvement.</p>
<p>Please note that we already utilize all available CPU cores, that run the same function with different arguments.</p>
<pre><code>#include <iostream>
#include <immintrin.h>
#include <chrono>
// ShiftRight is my adaptation from http://notabs.org/lfsr/software/
static void bitShiftRight256ymm(__m256i* data, int count)
{
__m256i innerCarry = _mm256_slli_epi64(*data, 64 - count); // carry outs in bit 0 of each qword
__m256i rotate = _mm256_permute4x64_epi64(innerCarry, 0x39); // rotate ymm right 64 bits
innerCarry = _mm256_blend_epi32(_mm256_setzero_si256(), rotate, 0x3F); // clear upper qword
*data = _mm256_srli_epi64(*data, count); // shift all qwords right
*data = _mm256_or_si256(*data, innerCarry); // propagate carrys
}
// shifts right by exactly 64 bits
static void shiftRight64(__m256i* data) {
*data = _mm256_permute4x64_epi64(*data, 0x39); // rotate ymm right 64 bits
*data = _mm256_blend_epi32(_mm256_setzero_si256(), *data, 0x3F); // clear high qword
}
// handle shifts over 64 bits
static void bitShiftRight256ymm_long(__m256i* data, int count)
{
shiftRight64(data);
if(count > 64)
bitShiftRight256ymm(data, count - 64);
}
// mask of 64 to select smaller parts of the sequence
static const uint64_t mask64[65] = { 0,
0x1, 0x3, 0x7, 0xF, 0x1F, 0x3F, 0x7F, 0xFF,
0x1FF, 0x3FF, 0x7FF, 0xFFF, 0x1FFF, 0x3FFF, 0x7FFF, 0xFFFF,
0x1FFFF, 0x3FFFF, 0x7FFFF, 0xFFFFF, 0x1FFFFF, 0x3FFFFF, 0x7FFFFF, 0xFFFFFF,
0x1FFFFFF, 0x3FFFFFF, 0x7FFFFFF, 0xFFFFFFF, 0x1FFFFFFF, 0x3FFFFFFF, 0x7FFFFFFF, 0xFFFFFFFF,
0x1FFFFFFFF, 0x3FFFFFFFF, 0x7FFFFFFFF, 0xFFFFFFFFF, 0x1FFFFFFFFF, 0x3FFFFFFFFF, 0x7FFFFFFFFF, 0xFFFFFFFFFF,
0x1FFFFFFFFFF, 0x3FFFFFFFFFF, 0x7FFFFFFFFFF, 0xFFFFFFFFFFF, 0x1FFFFFFFFFFF, 0x3FFFFFFFFFFF, 0x7FFFFFFFFFFF, 0xFFFFFFFFFFFF,
0x1FFFFFFFFFFFF, 0x3FFFFFFFFFFFF, 0x7FFFFFFFFFFFF, 0xFFFFFFFFFFFFF, 0x1FFFFFFFFFFFFF, 0x3FFFFFFFFFFFFF, 0x7FFFFFFFFFFFFF, 0xFFFFFFFFFFFFFF,
0x1FFFFFFFFFFFFFF, 0x3FFFFFFFFFFFFFF, 0x7FFFFFFFFFFFFFF, 0xFFFFFFFFFFFFFFF, 0x1FFFFFFFFFFFFFFF, 0x3FFFFFFFFFFFFFFF, 0x7FFFFFFFFFFFFFFF, 0xFFFFFFFFFFFFFFFF,
};
// mask of 128 to select larger parts of the sequence, built at start
static __m128i mask128[129] = {};
void build_mask()
{
for (int i = 0; i < 128; ++i)
mask128[i] = i < 64 ?
_mm_set_epi64x(0, mask64[i % 64]) :
_mm_set_epi64x(mask64[(i - 64) % 64], mask64[64]);
mask128[128] = _mm_set_epi64x(mask64[64], mask64[64]);
}
// check if the last 'length' bits in 'src' and 'target' are equal
bool masked128eq(const __m128i* src, int length, const __m128i* target) {
__m128i neq = _mm_xor_si128(*src, *target);
return (_mm_test_all_zeros(neq, mask128[length]));
}
// count max repeated bit patterns at the end of the sequence
int count_freq(const __m256i& seq) {
int max_freq = 1;
__m128i seq128 = _mm256_castsi256_si128(seq);
unsigned char upper_limit = 256 / (max_freq + 1);
for (int pattern_length = 10; pattern_length <= upper_limit; ++pattern_length) {
int freq = 1;
__m256i temp = seq;
int matching_length = 2 * pattern_length;
while (matching_length <= 256) { // while we are within range of the sequence length
if(pattern_length < 64)
bitShiftRight256ymm(&temp, pattern_length); // shift the copy of sequence by pattern_length bits
else
bitShiftRight256ymm_long(&temp, pattern_length);// shift the copy of sequence by pattern_length bits
__m128i t128 = _mm256_castsi256_si128(temp);
if (!masked128eq(&t128, pattern_length, &seq128)) // check if the two parts are equal
break;
if (++freq > max_freq) {
max_freq = freq;
upper_limit = 256 / (max_freq + 1);
if (max_freq > 3) { // don't care for frequencies over 4
return max_freq;
}
matching_length += pattern_length;
}
}
}
return max_freq;
}
// sequence with 84 '0' and 1 '1', repeated three times
__m256i seq = _mm256_set_epi64x(0x00000000'00000000, 0x00000400'00000000, 0x00000000'00200000, 0x00000000'00000001);
int main() {
build_mask();
auto t1 = std::chrono::high_resolution_clock::now();
int f(0);
for (int i = 0; i < 1'000'000; ++i) {
f += count_freq(seq);
}
auto t2 = std::chrono::high_resolution_clock::now();
std::cout << std::chrono::duration_cast<std::chrono::milliseconds>(t2 - t1).count() << " ms" << std::endl;
return f;
}
</code></pre>
<p><strong>UPDATE</strong></p>
<p>Implemented some micro-optimization, with a modest speed-up:</p>
<ol>
<li>Dropped calls to <code>_mm256_blend_epi32</code> in both shift functions, as we don't care about the garbage "shifted in"; we will only use the "good" part on the right.</li>
<li>Split <code>for (int pattern_length = 10; pattern_length <= upper_limit; ++pattern_length)</code> loop into two identical loops, one going up to 64, and the second - over64, to avoid testing for <code>if(pattern_length < 64)</code> in each iteration.</li>
</ol>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-22T00:57:02.650",
"Id": "500425",
"Score": "3",
"body": "This could use more description of what is the point of your code. \"The function is counting repeated bit patterns at the end of a 256-bit sequence\" — that's better than no description at all, but much worse than it could be. Maybe it would help to explain why on the third line you wrote `max_freq + 1` instead of `2`, for example. Or show some example inputs and outputs — `assert(count_freq(x) == y)` for some known pairs `x,y`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-22T02:18:41.597",
"Id": "500430",
"Score": "0",
"body": "@Quuxplusone - That a fair request. I will work on improving the description. It's always a balance between \"just enough\" and \"too much information\" :) The `max_freq + 1` was used for consistency with the in-loop recalculation. The compiler figured out it's `2` before the loop."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-01T09:46:25.760",
"Id": "501248",
"Score": "0",
"body": "Couldn't you use AVX512?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-03T22:05:55.507",
"Id": "501483",
"Score": "0",
"body": "@ALX23z we sure can; are there any faster bit-shifting instructions available on AVX512? Our sequence at the moment fits into 256 bits."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-06T19:06:43.917",
"Id": "501710",
"Score": "0",
"body": "What's this doing? Counting number of trailing 1s in a `__m256i`? Clearly something more complicated, but it's hard to understand without any surrounding code that would motivate why you want it. Re: AVX512: is `_mm256_lzcnt_epi64` (AVX512CD) a useful building block? https://www.felixcloutier.com/x86/vplzcntd:vplzcntq. Every CPU with AVX512F also has AVX512CD, and SIMD lzcnt runs fast."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-06T19:19:06.593",
"Id": "501711",
"Score": "0",
"body": "@PeterCordes - we are looking for a repeated bit patterns at the end of the bit sequence in `const __m256i& seq`. For example, `0b1000100010001000` have tree `0` at the end, and four `1000`. We are looking for a highest frequency, so 4 in this case. The test case used above is `// sequence with 84 '0' and 1 '1', repeated three times`. I have compressed the problem into this short code fragment; the original, very detailed question is here: https://codereview.stackexchange.com/questions/252718/c-multi-threaded-determination-of-curling-numbers-in-vectors"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-06T19:21:23.797",
"Id": "501712",
"Score": "1",
"body": "ok, good, that's the kind of thing @Quuxplusone was asking for. Edit that into your question in a spot where future readers will see it easily, especially the link to the other code review."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-06T19:25:14.073",
"Id": "501713",
"Score": "0",
"body": "`vplzcntq` could possibly help with this: after xoring with a repeated pattern, you could lzcnt to find the position of the first mismatch: where it stops matching. (If you build a 256-bit lzcnt out of vplzcntq's 64-bit chunks). But IDK if you can create inputs for that method efficiently; it requires broadcasting an n-bit pattern instead of right-shifting repeatedly only when you do actually get a match."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-06T19:46:23.487",
"Id": "501714",
"Score": "0",
"body": "@PeterCordes Are you suggesting to use `vplzcntq` instead of masking here `return (_mm_test_all_zeros(neq, mask128[length]));`? Would I need *trailing* zeroes? Unfortunately, my processor doesn't support AVX512, so I can't test it..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-06T19:53:30.827",
"Id": "501715",
"Score": "1",
"body": "Well you could maybe start from the top bits, since lzcnt naturally starts from that side, otherwise yeah you'd have to bit-reverse the input once so the top is the original bottom. It's not at all a drop-in replacement for anything you're currently doing, you'd want to redesign an algorithm to take advantage of it. But without an easy way to broadcast multiple copies of the low or high `n` bits, there's no easy way to take advantage. If you want to play with it on a computer without AVX512, for eventual deployment on one that does, use Intel's SDE (software development emulator)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-06T19:55:31.853",
"Id": "501716",
"Score": "1",
"body": "Also, your edit to the question still didn't include an example. And the link is missing the https so it's not clickable. Maybe you copy/pasted the formatted text of your comment instead of using the edit link on the question to get the original markdown... You have to proofread for that. Also, you put it in one of many tiny paragraphs where it's kind of buried. The actual purpose and example should be higher up so readers know what this is all about before they get into other details."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "11",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-21T22:12:43.067",
"Id": "253761",
"Score": "6",
"Tags": [
"c++",
"performance",
"x86"
],
"Title": "Optimizing bit-matching performance using AVX compiler intrinsic"
}
|
253761
|
<p>I know it's bad to even use recursive_mutex because of its poor performance, let alone a recursive shared mutex. However, I'm doing this just to practice. Any suggestion will be appreciated!</p>
<blockquote>
<p>recursive_shared_mutex.hpp</p>
</blockquote>
<pre><code>#pragma once
#include <optional>
#include <shared_mutex>
#include <thread>
class recursive_shared_mutex : private std::shared_mutex {
public:
recursive_shared_mutex();
~recursive_shared_mutex() = default;
void lock();
bool try_lock();
void unlock();
/*
* std::shared_mutex's shared locking is recursive by default.
*/
void lock_shared() {
std::shared_mutex::lock_shared();
}
bool try_lock_shared() {
return std::shared_mutex::try_lock_shared();
}
void unlock_shared() {
std::shared_mutex::unlock_shared();
}
private:
std::mutex mtx_;
std::condition_variable cv_;
std::optional<std::thread::id> writer_id_;
std::size_t writer_cnt_;
};
</code></pre>
<blockquote>
<p>recursive_shared_mutex.cpp</p>
</blockquote>
<pre><code>#include "recursive_shared_mutex.hpp"
recursive_shared_mutex::recursive_shared_mutex()
: std::shared_mutex(),
mtx_(),
cv_(),
writer_id_(),
writer_cnt_(0)
{
}
void recursive_shared_mutex::lock() {
std::thread::id this_id = std::this_thread::get_id();
std::unique_lock<std::mutex> ulock(mtx_);
if (this_id == writer_id_) {
// Same thread/writer trying to acquire the shared_mutex again.
// Simply increase writer count.
++writer_cnt_;
}
else {
// Another writer or no writer is holding the shared_mutex.
// It's also likely that some readers are holding
// the shared_mutex.
if (writer_id_.has_value()) {
// If another writer is holding the mutex,
// waiting for it to release.
cv_.wait(ulock, [this] { return writer_cnt_ == 0; });
}
std::shared_mutex::lock();
writer_id_ = this_id;
writer_cnt_ = 1;
}
}
bool recursive_shared_mutex::try_lock() {
// TODO
return false;
}
void recursive_shared_mutex::unlock() {
std::unique_lock<std::mutex> ulock(mtx_);
if (!writer_id_.has_value()) {
// No writer is holding the shared_mutex.
// Call unlock() anyway. UB expected.
std::shared_mutex::unlock();
}
else {
// At this point, the shared_mutex must be held by a writer
// and writer_cnt_ must be greater than 0.
--writer_cnt_;
if (writer_cnt_ == 0) {
// If writer count becomes 0, release the
// underlying shared_mutex.
// It's likely that we are unlocking in a
// different thread from the one where the shared_mutex
// has been acquired.
// Call unlock() anyway. UB expected.
std::shared_mutex::unlock();
writer_id_.reset();
// Manually unlock to let cv notify.
ulock.unlock();
cv_.notify_one();
}
}
}
</code></pre>
|
[] |
[
{
"body": "<p>I strongly recommend <em>not</em> inheriting from standard types, and <em>not</em> using private inheritance even with your own types. If a <code>recursive_shared_mutex</code> IS-A <code>shared_mutex</code>, then announce it publicly; if it IS-NOT-A <code>shared_mutex</code>, then don't use inheritance at all!</p>\n<p>(<a href=\"https://godbolt.org/z/nr3dax\" rel=\"nofollow noreferrer\">Godbolt.</a> <code>D_view</code> here is isomorphic to <code>std::reference_wrapper<D></code>, for what that's worth.)</p>\n<hr />\n<pre><code>std::size_t writer_cnt_;\n</code></pre>\n<p>should be</p>\n<pre><code>std::size_t writer_cnt_ = 0;\n</code></pre>\n<p>so that you don't have to remember to initialize it in the member-initializer-list of the constructor. Once you do that, you can <code>=default</code> your constructor. Even if you don't <code>=default</code> the constructor, please don't do <code>mtx_(), cv_(),</code> and so on. Let default constructors do their jobs; and don't force me to read more code than I need to read.</p>\n<hr />\n<pre><code> // No writer is holding the shared_mutex.\n // Call unlock() anyway. UB expected.\n</code></pre>\n<p>This comment is just completely bogus. If this situation is "should never happen, UB expected," then <strong>assert false already!</strong> Don't just go on and do some random operation like <code>shared_mutex::unlock()</code> when you <strong>know</strong> you're in a bad state. Assert false, and let the programmer detect and fix their bug.</p>\n<p>Again, this follows the mantra "Don't force me to read more code than I have to." Don't make me read a codepath that does <code>shared_mutex::unlock()</code> and returns, when really that codepath is unreachable. In fact, don't even write that <code>if</code> test! Just do this:</p>\n<pre><code>void recursive_shared_mutex::unlock() {\n auto lk = std::unique_lock<std::mutex>(mtx_);\n assert(writer_id_.has_value());\n assert(*writer_id_ == std::this_thread::id());\n assert(writer_cnt_ > 0);\n if (--writer_cnt_ == 0) {\n std::shared_mutex::unlock(); // oops, TODO FIXME\n writer_id_ = std::nullopt;\n lk.unlock();\n cv_.notify_one();\n }\n}\n</code></pre>\n<p>Notice my preferred use of <code>lk</code> for lock-guard variables.\nNotice I'm avoiding the use of ad-hoc named methods like <code>x.reset()</code> in favor of value-semantic operations like <code>x = nullopt</code>.</p>\n<p>You've still got a bug here, which you code-commented — but commenting a bug doesn't make it go away! Frankly, this code is <em>literally</em> off-topic here, because it doesn't work and you know it doesn't work.</p>\n<p>Figure out how to use a semaphore (from the <code><semaphore></code> header in C++20) or an <code>atomic</code>, instead of the <code>shared_mutex</code> which you already know gives you UB.</p>\n<hr />\n<p>I'm 90% sure that there's a deadlock possible between your exclusive <code>lock()</code> and <code>unlock()</code> functions. Suppose Thread A has the mutex exclusive-locked, and Thread B goes to lock it. Then Thread B will enter <code>lock()</code>, take an exclusive lock on <code>mtx_</code>, and block in <code>std::shared_mutex::lock()</code> because Thread B still has it locked. (Assume Thread B drops its lock just long enough to fool the <code>cv_.wait()</code> loop.) Finally, Thread A enters <code>unlock()</code> and blocks in <code>ulock(mtx_)</code> because Thread B still has <code>mtx_</code> locked.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-22T07:29:13.513",
"Id": "500437",
"Score": "0",
"body": "Thank you for your detailed post. I do agree with you on the constructor thing. It makes code more concise if I declare a default ctor. However, I have different opinions on other \"issues\" you've pointed out. I know private inheritance can be problematic but should we really avoid using it under any circumstance? As far as I know, private inheritance means Implemented-In-Terms-Of. In this case, pointer/reference of recursive_shared_mutex can't be converted to pointer/reference of std::shared_mutex, so it's safe to use private inheritance here imo."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-22T07:34:05.880",
"Id": "500438",
"Score": "0",
"body": "As for the UB thing, because my `recursive_shared_mutex` is implemented in terms of `std::shared_mutex`, and in c++ standard, doing such things with `std::shared_mutex` leads to UB, I think it makes more sense to call `std::shared_mutex::unlock()` anyway than fail an assertion."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-22T07:38:31.507",
"Id": "500439",
"Score": "0",
"body": "As for `cv` and its `wait()` method, the thread that calls `wait()` will sleep and `unique_lock` will be unlocked if the lambda is evaluated to be false. So there won't be deadlock. See the below code snippet."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-22T07:40:08.120",
"Id": "500442",
"Score": "0",
"body": "`class Mtx : public mutex {\npublic:\n void lock() {\n mutex::lock();\n cout << \"locked\\n\";\n }\n\n void unlock() {\n mutex::unlock();\n cout << \"unlocked\\n\";\n }\n};\n\nint main(int argc, char **argv) {\n Mtx mtx;\n condition_variable_any cv;\n unique_lock<Mtx> lk(mtx);\n cv.wait(lk, [] { return false; });\n cout << \"after wait\\n\";\n\n return 0;\n}`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-22T07:40:58.797",
"Id": "500444",
"Score": "0",
"body": "output is `locked\nunlocked`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-22T12:52:08.090",
"Id": "500453",
"Score": "0",
"body": "@Einiemand: Re private inheritance, take a look at the Godbolt I posted. Also see https://isocpp.org/wiki/faq/private-inheritance and perhaps https://quuxplusone.github.io/blog/2018/12/11/dont-inherit-from-std-types/ Re the deadlock, I'm still pretty confident it's there. Try to prove to yourself that it _is_ there."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-22T19:11:22.400",
"Id": "500466",
"Score": "0",
"body": "I can't think of an occasion where there would be a deadlock. If code reaches `std::shared_mutex::lock()`, it is guaranteed that the mutex is not held by any other writer."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-22T02:03:11.973",
"Id": "253767",
"ParentId": "253764",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-22T00:33:35.943",
"Id": "253764",
"Score": "2",
"Tags": [
"c++",
"multithreading",
"c++17",
"locking"
],
"Title": "C++ implementation of recursive_shared_mutex"
}
|
253764
|
<pre><code>input:140153(seconds)
output:38:55:53
</code></pre>
<p>I have solved this problem in this way:</p>
<pre><code>#include <stdio.h>
int main(){
int N;
double hour;
double minute;
double seconds;
scanf("%d",&N);
hour=N / 3600.0;
double floating = hour;
double fractional, integer;
//split the floating value(hour) into the integer and decimal
fractional = modf(floating, &integer);
minute=60 * fractional;
double floatingUpdate = minute;
double fractionalUpdate, integerUpdate;
//split the floating value(minute) into the integer and decimal
fractionalUpdate = modf(floatingUpdate,&integerUpdate);
seconds = 60 * fractionalUpdate;
printf ("%g:%g:%g\n", integer, integerUpdate, seconds);
return 0;
}
</code></pre>
<p>Would you propose any simplification for my solution? Would I face any problem with some specific conditions? Is the way I solved this kind of problem efficient or not?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-22T11:23:03.953",
"Id": "500450",
"Score": "1",
"body": "Is that your real indentation - or did it get mangled when you copied it into the question? I recommend you [edit] to fix that up."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-22T13:22:48.767",
"Id": "500454",
"Score": "1",
"body": "Note that C has some standard functions for dealing with time, such as [`gmtime()`](https://en.cppreference.com/w/c/chrono/gmtime), although it's not a perfect fit if you want the hours component to be larger than 23."
}
] |
[
{
"body": "<p>When we write</p>\n<blockquote>\n<pre><code>scanf("%d",&N);\n</code></pre>\n</blockquote>\n<p>it's important not to ignore the return value from <code>scanf()</code> (that indicates how many values were successfully converted). Otherwise, we're working with the uninitialised value <code>N</code>.</p>\n<hr />\n<p>Use of the <code>modf()</code> function requires a declaration:</p>\n<pre><code>#include <math.h>\n</code></pre>\n<p>But we would be better working with integers instead (use the <code>/</code> and <code>%</code> operators).</p>\n<hr />\n<p>Presentation of negative values is strange:</p>\n<blockquote>\n<p>-70:-29:-29</p>\n</blockquote>\n<p>Normally, we'd just print that as <code>-70:29:29</code>.</p>\n<p>I'd be inclined to just work with unsigned values, and get that working well, before extending to negatives.</p>\n<hr />\n<p>Variable naming is inconsistent (singular <code>hour</code> and <code>minute</code>, but plural <code>seconds</code>). <code>N</code> is a poor choice for a variable name - choose something more meaningful and lower-case; convention reserves upper-case for macros.</p>\n<hr />\n<p>We should make the declaration of <code>main()</code> be a prototype. Also, it's permitted to omit the return statement in <code>main()</code>; since we always return success, let's remove that clutter.</p>\n<hr />\n<h1>Modified code</h1>\n<pre><code>#include <stdio.h>\n#include <stdlib.h>\n\nint main(void)\n{\n unsigned long total_secs;\n while (scanf("%lu", &total_secs) != 1) {\n // consume some input\n if (scanf("%*s") == EOF) {\n return EXIT_FAILURE;\n }\n printf("Enter a valid integer: ");\n fflush(stdout);\n }\n\n unsigned long hour = total_secs / 3600;\n unsigned int minute = total_secs / 60 % 60;\n unsigned int second = total_secs % 60;\n\n printf("%lu:%u:%u\\n", hour, minute, second);\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-22T21:31:27.627",
"Id": "500475",
"Score": "1",
"body": "@chux Thanks for edit - should have compiled, even for a small change!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-23T04:14:16.070",
"Id": "500500",
"Score": "0",
"body": "I am going to follow the strategy you proposed. Thank you for your facilitation. Keep up the good work."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-23T05:06:14.077",
"Id": "500502",
"Score": "0",
"body": "if (scanf(\"%*s\") == EOF) {\n return EXIT_FAILURE;\n } please explain this part of code in words."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-23T07:55:54.457",
"Id": "500508",
"Score": "2",
"body": "@ashiful, That part reads (at least some of) the erroneous input from the standard input stream and discards it, so that we can re-try the `scanf(\"%lu\")`. If there's nothing left to read, we don't re-try (which we know would immediately fail), but instead terminate with an error status."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-22T11:48:20.687",
"Id": "253772",
"ParentId": "253769",
"Score": "9"
}
},
{
"body": "<blockquote>\n<p>Would you propose any simplification for my solution?</p>\n</blockquote>\n<p>As code is effectively changing H:M:S --> time and then later time --> H:M:S, this becomes a fine opportunity to consider helper functions.</p>\n<p>This promotes <a href=\"https://en.wikipedia.org/wiki/Divide-and-conquer_algorithm\" rel=\"nofollow noreferrer\">divide and conqueror</a> and makes the sub-steps smaller and easier to maintain.</p>\n<pre><code>// Each returns an error flag.\nbool HMS_to_seconds(int *seconds, int h, int m, int s);\nbool HMS_from_seconds(int *h, int *m, int *s, int seconds);\nbool HMS_to_string(size_t sz, char *hms, int h, int m, int s);\nbool HMS_from_string(int *h, int *m, int *s, const char *hms);\n</code></pre>\n<p>These then become flexible building blocks.</p>\n<p>I'll go deeper into one of them.</p>\n<pre><code>// Convert hour, minute, second into a standard string form.\nbool HMS_to_string(size_t sz, char *hms, int h, int m, int s) {\n if (hms == NULL || sz == 0) {\n return true; // Bad argument\n }\n\n // Bring into primary range (h:int, m:0-59, s:0-59)\n if (m < 0 || m >= 60 || s < 0 ||| s >= 60) { // Could use macros like SECPERMIN 60 ...\n int seconds;\n if (HMS_to_seconds(&seconds, h, m, s) || HMS_from_seconds(&h, &m, &s, seconds)) {\n hms[0] = 0;\n return true; // Range error\n }\n }\n\n int cnt = snprintf(hms, sz, "%d:%02d:%02d", h, m, s);\n if (cnt < 0 || (unsigned) cnt >= sz) {\n hms[0] = 0;\n return true; // Buffer too small;\n }\n\n return false; // No error\n} \n \n</code></pre>\n<p>Make the helper functions as robust as desired.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-23T04:17:28.843",
"Id": "500501",
"Score": "0",
"body": "Thank you for your presence. I am going to try the suggestion you provided."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-22T22:31:10.937",
"Id": "253802",
"ParentId": "253769",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "253772",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-22T04:55:16.317",
"Id": "253769",
"Score": "3",
"Tags": [
"c"
],
"Title": "Convert an integer(seconds) into the format of an hour: minute: seconds in c"
}
|
253769
|
<p>This is a metaclass for facilitating the concept of "inner classes" (as opposed to simple nested classes) in Python. I define an inner class as a nested class that expects an instance of the outer class as
the first argument to <code>__new__</code> and <code>__init__</code>.</p>
<p>This metaclass implements the
descriptor protocol (non-data) for the inner class, such that calling the inner
class through an attribute access on an instance of the outer class will
automatically pass the latter as the first argument to the constructor of the
inner class.</p>
<p>Example:</p>
<pre class="lang-py prettyprint-override"><code>class Car:
class Motor(metaclass=InnerClassMeta):
def __init__(self, car: "Car"):
self.car = car
</code></pre>
<pre class="lang-py prettyprint-override"><code>>>> car = Car()
>>> motor = car.Motor()
>>> motor.car is car
True
</code></pre>
<p>This is similar to Java's inner classes.</p>
<p>I'm mainly concerned with correctness, consistent behaviour, and maintainability. Note: this doesn't attempt to discriminate from which class it is being accessed,
i.e. it doesn't attempt to validate that it is being accessed from the outer class
in which it was defined (if any).</p>
<p>Code:</p>
<pre class="lang-py prettyprint-override"><code>class InnerClassMeta(type):
"""Metaclass for inner classes."""
class BoundInnerClass:
def __init__(self, inner_class, outer_instance):
self.inner_class = inner_class
self.outer_instance = outer_instance
def __repr__(self):
return (
f"<bound inner class {self.inner_class.__name__}"
f" of {self.outer_instance}>"
)
def __call__(self, *args, **kwargs):
return self.inner_class(self.outer_instance, *args, **kwargs)
def __get__(cls, instance, owner):
if instance is None:
return cls # don't bind to classes, just instances
return InnerClassMeta.BoundInnerClass(cls, instance)
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-22T11:56:57.543",
"Id": "253773",
"Score": "2",
"Tags": [
"python",
"object-oriented",
"classes"
],
"Title": "Python metaclass for inner classes"
}
|
253773
|
<p>The code below is my shot at trying to do monte carlo integration of the function sin(x) from 0 to pi in Python 3.
I sample randomly 10000 times a floating number from 0 to pi and do the standard procedure of the monte carlo integration and also take the average of ten results for an even better approximation,i was wondering if there is anything i can do to optimize my code from a time or accuracy standpoint.</p>
<pre><code>import random
import math
def func(n):
return math.sin(n)
integralres=0
for t in range(10):
resf=0
for i in range(10000):
u=random.uniform(0,math.pi)
resf+=func(u)
integralres+=(math.pi)*resf/10000
print(integralres/10)
</code></pre>
|
[] |
[
{
"body": "<h2>Style</h2>\n<p><a href=\"https://pep8.org/\" rel=\"nofollow noreferrer\">PEP8 is the Python style guide</a> and is worth a read to keep your code clear and understandable.</p>\n<h2>Naming</h2>\n<p>You're not using your loop indicies, <code>t</code> and <code>i</code>, it's customary to replace them with <code>_</code> to indicate this.</p>\n<p>The name <code>func</code> for a function doesn't tell you what it does. Names should be as descriptive as possible, in this case <code>sin</code> seems sensible</p>\n<pre class=\"lang-py prettyprint-override\"><code>def sin(x):\n return math.sin(x)\n</code></pre>\n<h2>Functions</h2>\n<p>The function <code>sin</code> doesn't actually give you anything, as is now clearer, and I'd remove it altogether.</p>\n<p>The calculation of you integration <em>is</em> discrete, and might be used separately. I would put that inside a function</p>\n<pre class=\"lang-py prettyprint-override\"><code>def monte_carlo(n):\n resf = 0\n for _ in range(n):\n uniform_rand_no = random.uniform(0, math.pi)\n resf += math.sin(uniform_rand_no)\n return math.pi * resf / 10000\n</code></pre>\n<p>Note that I've:</p>\n<ol>\n<li>Allowed you to pick the number of iterations</li>\n<li>Added spaces around operators</li>\n</ol>\n<p>I'm not really sure what <code>resf</code> means, otherwise I would have renamed that too.</p>\n<h2>Main</h2>\n<p>All your code will execute when you import your file. If you use the following you can gate execution solely to when the file is run:</p>\n<pre class=\"lang-py prettyprint-override\"><code>if __name__ == "__main__":\n for _ in range(10):\n ...\n</code></pre>\n<h2>Everything</h2>\n<p>Putting all this together you would get:</p>\n<pre class=\"lang-py prettyprint-override\"><code>import random\nimport math\n\n\ndef monte_carlo(n):\n resf = 0\n for _ in range(n):\n uniform_rand_no = random.uniform(0, math.pi)\n resf += math.sin(uniform_rand_no)\n return math.pi * resf / 10000\n\n\nif __name__ == "__main__":\n\n integral = 0\n n = 10000\n \n for _ in range(10):\n integral += math.pi * monte_carlo(n) / n\n\n print(integral / 10)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-22T16:00:10.727",
"Id": "500462",
"Score": "0",
"body": "`sin = math.sin` is a lot better declaration than explicit function definition"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-22T22:28:08.880",
"Id": "500482",
"Score": "0",
"body": "Wouldn't you just `from math import sin, pi` rather than declaring that @hjpotter92? (I did forget the `math.` in front of `sin`; I've edited the answer to include it."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-22T15:59:15.933",
"Id": "253782",
"ParentId": "253776",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "253782",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-22T14:14:46.763",
"Id": "253776",
"Score": "2",
"Tags": [
"python",
"performance",
"python-3.x"
],
"Title": "Monte Carlo Integration Optimization"
}
|
253776
|
<p>I have built a quiz app. It is my first project so the purpose is to learn app development at this stage.</p>
<p>There are two key things which I am wondering how to do better (the app is fully functional).</p>
<p>1: Livedata / flow / room</p>
<p>I have the following data class</p>
<pre><code>@Entity
data class SavedScores(
@PrimaryKey(autoGenerate = true) var id: Int,
var difficulty: String?,
var sumtype: String?,
var questioncount: Int?,
var answeredcorrectly: Int?
)
</code></pre>
<p>I have the following DAO query</p>
<pre><code>@Query("SELECT COUNT(*) from SavedScores WHERE difficulty = :DIFFICULTY AND questioncount = :QuestionCount AND answeredcorrectly =:QuestionCount")
fun GetWinsByDifficulty(DIFFICULTY: String,QuestionCount:Int):Flow<Int>
</code></pre>
<p>This is where I start writing a LOT of code and wonder if there are better ways to be letting the data flow. In my room repository I am then calling every instance of that query that I require for a statistics page</p>
<pre><code>val easy5: Flow<Int> = savedScoresDao.GetWinsByDifficulty("Easy", 5)
val easy10: Flow<Int> = savedScoresDao.GetWinsByDifficulty("Easy", 10)
val easy15: Flow<Int> = savedScoresDao.GetWinsByDifficulty("Easy", 15)
val easy20: Flow<Int> = savedScoresDao.GetWinsByDifficulty("Easy", 20)
val easy30: Flow<Int> = savedScoresDao.GetWinsByDifficulty("Easy", 30)
</code></pre>
<p>Then I have my view model</p>
<pre><code>val easy5: LiveData<Int> = repository.easy5.asLiveData()
val easy10: LiveData<Int> = repository.easy10.asLiveData()
val easy15: LiveData<Int> = repository.easy15.asLiveData()
val easy20: LiveData<Int> = repository.easy20.asLiveData()
val easy30: LiveData<Int> = repository.easy30.asLiveData()
</code></pre>
<p>And finally my observer and view setter;</p>
<pre><code>savedScoresViewModel.easy5.observe(this) { newValue ->
tv_easy5.text = newValue.toString()
setView(tv_easy5,newValue)
}
savedScoresViewModel.easy10.observe(this) { newValue ->
tv_easy10.text = newValue.toString()
setView(tv_easy10,newValue)
}
savedScoresViewModel.easy15.observe(this) { newValue ->
tv_easy15.text = newValue.toString()
setView(tv_easy15,newValue)
}
savedScoresViewModel.easy20.observe(this) { newValue ->
tv_easy20.text = newValue.toString()
setView(tv_easy20,newValue)
}
savedScoresViewModel.easy30.observe(this) { newValue ->
tv_easy30.text = newValue.toString()
setView(tv_easy30,newValue)
}
private fun setView(view:TextView,value:Int){
if (value == 0){view.setBackgroundResource(R.drawable.somewrong_icon)
} else {
if (view.text.toString().toInt()==0){
view.setBackgroundResource(R.drawable.somewrong_icon)
} else {view.setBackgroundResource(R.drawable.allcorrect_icon)}
}
}
</code></pre>
<p>The reality is that currently I have 4 levels of difficulty so for each level I am repeating the above. I also 9 different sum types and have even more queries running to capture that information. Is there a simpler way to code each individual query without having to write so many lines of code? Is it bad practise having so many observers?</p>
<p>2: The second aspect to this is my views. Currently to show all of this data I have a huge amount of views. Whilst I have used recycler view in one part of my app (showing a history of games) I dont see how I can use it for this one as I have so many standalone queries to monitor i.e. I get a count and show just that count. Every new item is a standalone query response rather than a list of them</p>
<p>I appreciate this might end of being quite broad but after all this is about improving code not fixing a problem. I understand therefore if responses tend to focus on one element</p>
<p>I am happy to share more of my code as well but didnt want to load it all if not needed</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-31T18:20:46.790",
"Id": "501199",
"Score": "0",
"body": "If anyone reads this it would be good to know if you follow the same suit or not or if you have any improved way to get lots of one shot query results to a users screen"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-22T14:30:51.980",
"Id": "253777",
"Score": "1",
"Tags": [
"android",
"database",
"repository"
],
"Title": "Monitor room repository for livedata changes and update views"
}
|
253777
|
<p>A <code>threading.Thread</code> subclass intended for running an <code>asyncio</code> loop that has the ability to be stopped gracefully from another thread.</p>
<p>I spent a <em>lot</em> of time doing trial and error until it finally worked, but probably it still needs a lot of refinement. Warning to <code>asyncio</code> noobs like me: <code>asyncio</code> is <em>very</em> thread-<em>un</em>safe in general. Don't assume otherwise.</p>
<p>Example:</p>
<pre class="lang-py prettyprint-override"><code>import time
# This is a placeholder for an arbitrary async entry point
async def my_async_main():
...
async_thread = StoppableAsyncioThread(target=my_async_main)
time.sleep(5)
async_thread.stop()
async_thread.join()
</code></pre>
<p>Code:</p>
<pre class="lang-py prettyprint-override"><code>import asyncio
import logging
import threading
from typing import ClassVar, Optional
class StoppableAsyncioThread(threading.Thread):
"""
Stoppable asyncio thread.
The target callable must be a coroutine function that can be executed with
``asyncio.run(target())``.
"""
logger: ClassVar[logging.Logger] = logging.getLogger("threading")
def __init__(self, *args, **kwargs) -> None:
super().__init__(*args, **kwargs)
# These are threading.Thread internals; equivalent to passing in the
# corresponding keyword arguments to __init__. A bit lazy, but it guarantees
# that the arguments and their defaults get handled correctly because
# we delegate everything (*args, **kwargs) to threading.Thread.__init__
self._args = (self._target_wrapper(self._target),)
self._kwargs = {"debug": self.logger.getEffectiveLevel() <= logging.DEBUG}
self._target = asyncio.run
self.loop: Optional[asyncio.AbstractEventLoop] = None
self._target_task = None
def stop(self):
if self.loop is None:
raise RuntimeError("This asyncio thread is not running")
self.logger.debug("Trying to stop %s", self)
# cancelling the root task will be enough for the loop to close, because
# we started it with asyncio.run, which only waits until the given task is done;
# asyncio takes care of cancelling any other tasks
self.loop.call_soon_threadsafe(self._target_task.cancel)
async def _target_wrapper(self, target):
self._target_task = asyncio.current_task()
self.loop = asyncio.get_running_loop()
try:
await target()
except asyncio.CancelledError:
return
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-23T07:33:07.047",
"Id": "500505",
"Score": "0",
"body": "Could you also add the `my_server` function code? :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-23T11:45:24.473",
"Id": "500516",
"Score": "0",
"body": "Oh that's just a dummy example, it's not part of the code. I'd like to focus on the class itself, which should be able to support *any* async entry point passed as `target`."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-22T15:17:22.340",
"Id": "253780",
"Score": "1",
"Tags": [
"python",
"multithreading",
"asynchronous",
"thread-safety",
"async-await"
],
"Title": "Stoppable asyncio thread class"
}
|
253780
|
<h2>Context</h2>
<p>I've started digging into Arduino and different type of sensors which is fun, but I'm worried that that my coding is <em>too explicit</em>. I've lots of experience for coding corporate programs, though it is not in C/C++. I don't consider myself a beginner, but I think something is wrong.</p>
<hr />
<h2>Blocks</h2>
<p>I'd place my code in this section. It is using PING))) sensor to detect how far an object is based on the travel time of an emitted ultra-sonic signal. This sketch is taken from the TinkerCad website which can be found here: tinkercad.com.</p>
<pre class="lang-c prettyprint-override"><code>/*
Ping))) Sensor
This sketch reads a PING))) ultrasonic rangefinder and returns the distance to the closest object in range. To do this, it sends a pulse to the sensor to initiate a reading, then listens for a pulse to return. The length of the returning pulse is proportional to the distance of the object from the sensor.
The circuit:
* +V connection of the PING))) attached to +5V
* GND connection attached to ground
* SIG connection attached to digital pin 7
http://www.arduino.cc/en/Tutorial/Ping
This example code is in the public domain.
*/
const int speedOfSoundInAirInMetersPerSecond = 343;
const float speedOfSoundInAirInCentimeterPerMicrosecond =
speedOfSoundInAirInMetersPerSecond / 10000.0;
const float centimeterToInchRatio = 2.54;
int inches = 0;
int cm = 0;
long readTravelTimeInMicroseconds(int triggerPin, int echoPin)
{
pinMode(triggerPin, OUTPUT); // Clear the trigger
digitalWrite(triggerPin, LOW);
delayMicroseconds(2);
digitalWrite(triggerPin, HIGH);
delayMicroseconds(10);
digitalWrite(triggerPin, LOW);
pinMode(echoPin, INPUT);
// Reads the echo pin, and returns the sound wave travel time in microseconds
return pulseIn(echoPin, HIGH);
}
void setup()
{
Serial.begin(9600);
}
void loop()
{
// I had to divided that speed by 2 because
// I'm only interested in the time which took
// signal to reach an object. I don't need to know
// how much distance we covered by the signal to the object and back.
cm = (speedOfSoundInAirInCentimeterPerMicrosecond / 2)
* readTravelTimeInMicroseconds(7, 7);
inches = (cm / centimeterToInchRatio);
Serial.print(inches);
Serial.print("in, ");
Serial.print(cm);
Serial.println("cm");
delay(100);
}
</code></pre>
<hr />
<h2>My thoughts</h2>
<ul>
<li><p>Am I not being too explicit? I've learnt over the years that it is always better to be<em>explicit</em>. But, am I not going overboard here?</p>
</li>
<li><p>Are there styles and conventions, styles I should follow when working with Arduino or electronics of this type? My question concerns with the technical side of the code.</p>
</li>
</ul>
|
[] |
[
{
"body": "<ul>\n<li><p><code>VeryLongIdentifiersInCamelCase</code> do not make your code explicit. They just add noise.</p>\n</li>\n<li><p>The definition</p>\n<pre><code>const float speedOfSoundInAirInCentimeterPerMicrosecond = \n speedOfSoundInAirInMetersPerSecond / 10000.0;\n</code></pre>\n<p>is very hard to read. <code>10000</code> stands out as weird. After all, there are <code>1000000</code> microseconds in a second. It took me quite a time to realize that two orders of magnitude are hidden in meters-to-centimeters conversion.</p>\n</li>\n<li><p>By default, <code>pulseIn</code> timeouts in 1 second. In reality it means that there is no obstacle within 170 or so meters (aka 500 feet). I seriously doubt your hardware is capable detecting an echo at such distances. It feels safe to shorten the timeout for the sake of better responsiveness.</p>\n</li>\n<li><p>The production quality code must deal with the ambient noise, which will result in false positives. At least, test that the signal you detected is indeed an echo - that is, it is about as long as the ping. You should also special-case <code>inPulse</code> returning 0. Currently, you are returning 0 distance, whist in fact it means the distance is practically infinite.</p>\n</li>\n<li><p>Unless <em>I am seeing things</em>, either the code, or documentation is wrong. According to the <a href=\"https://www.arduino.cc/reference/en/language/functions/advanced-io/pulsein/\" rel=\"nofollow noreferrer\">spec</a></p>\n<blockquote>\n<p>if <code>value</code> is HIGH, <code>pulseIn()</code> waits for the pin to go from LOW to HIGH, starts timing, then waits for the pin to go LOW and stops timing. Returns the length of the pulse in microseconds</p>\n</blockquote>\n<p>which means it returns the duration of the echo, not the turnaround time you are after. Unfortunately, I don't have the hardware to play with.</p>\n<p>Does your code give reasonable results?</p>\n</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-23T07:37:55.847",
"Id": "500506",
"Score": "2",
"body": "1) Understood. What would be _better_ alternative in this case?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-22T22:46:45.980",
"Id": "253805",
"ParentId": "253783",
"Score": "3"
}
},
{
"body": "<blockquote>\n<p>Am I not being to(o) explicit?</p>\n</blockquote>\n<p>Names are not too explicit, but verbose.</p>\n<p>Consider using standard physical units with metric units as the default: "meter, second, Volts, Amps, ...".</p>\n<p>Example, for speed, use all <em>speed</em> data in meters/second (unless otherwise name/commented). Then the names can be shorter.</p>\n<pre><code>// const int speedOfSoundInAirInMetersPerSecond = 343;\nconst int speedOfSoundInAir = 343 /* m/s */\n</code></pre>\n<p>Rather than ratios, use "per" or "p". Use standard <a href=\"https://en.wikipedia.org/wiki/International_System_of_Units\" rel=\"nofollow noreferrer\">SI</a> abbreviations<sup>*1</sup>. For non-SI units, use the word like "inch". Use <code>float</code> constants for <code>float</code> objects - append an <code>f</code>.</p>\n<pre><code>// const float centimeterToInchRatio = 2.54;\nconst float cm_per_inch = 2.54f;\n</code></pre>\n<p>As able, object names should primarily reflect what they are and then maybe, and secondarily, units. Notice how easy it is to read and see the units balance.</p>\n<pre><code>// cm = (speedOfSoundInAirInCentimeterPerMicrosecond / 2) * readTravelTimeInMicroseconds(7, 7);\nint distance_cm = (speedOfSoundInAir_cm_per_us * readTravelTime_us(7, 7))/2;\n\n// inches = (cm / centimeterToInchRatio);\nint distance_inch = distance_cm * inch_per_cm;\n</code></pre>\n<p>Note that OP's <code>speedOfSoundInAirInCentimeterPerMicrosecond / 2</code> effectively lost the last bit of the speed.</p>\n<hr />\n<p>When working with small computing machines and processing time is important, consider the impact of FP math vs. an all <code>int</code> solution. Code may gain performance, yet watch out for overflow.</p>\n<pre><code>const float inch_per_cm = 2.54f; /* inch / cm */\nint distance_inch = distance_cm * inch_per_cm;\n\n// vs all int solution\nconst int inch_per_cm_N = 254; /* inch / cm */\nconst int inch_per_cm_D = 100;\n// Round by adding half denominator (assuming pos values)\nint distance_inch = (distance_cm*inch_per_cm_N + inch_per_cm_D/2)/inch_per_cm_D;\n</code></pre>\n<hr />\n<p><sup>*1</sup> Using <code>u</code> for <a href=\"https://en.wikipedia.org/wiki/Micro-\" rel=\"nofollow noreferrer\">μ</a>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-24T03:56:09.777",
"Id": "253859",
"ParentId": "253783",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "253805",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-22T16:20:15.203",
"Id": "253783",
"Score": "3",
"Tags": [
"c++",
"c",
"arduino"
],
"Title": "Arduino code and PING))) ultrasonic rangefinder"
}
|
253783
|
<p>The code below takes a string that potentially contains a true match for a delimiter. There can be multiple delimiters located anywhere in the string. We need to obtain the indices that are not a match and when the delimiter starts and ends.
The following code achieves this. However, I am unsure if this is the most optimal method. What do you think? Test cases below the code.</p>
<pre><code>String baseText = "%!ABCD%!EF%";
String delimiter = "%";
ArrayList<String> selectedParameters = new ArrayList<>();
int lastNonDelimited = 0;
int i = 0;
while (i < baseText.length()) {
int j = 0;
while (j < delimiter.length()) {
if (j + i == baseText.length() - 1 && j != delimiter.length() - 1) {
lastNonDelimited += 1;
System.out.println(lastNonDelimited);
break;
}
char c = baseText.charAt(i + j);
char d = delimiter.charAt(j);
if (c == d) {
if (j == delimiter.length() - 1) {
lastNonDelimited += delimiter.length();
i += (delimiter.length() - 1);
System.out.println("End" + (i + j));
} else {
System.out.println("Beginnning" + (i + j + 1));
}
} else {
lastNonDelimited += 1;
System.out.println(lastNonDelimited);
break;
}
j += 1;
}
i += 1;
}
</code></pre>
<p>Test case 1:</p>
<pre><code>String %!ABCD%!EF% with %! delimiter results in:
Beginnning1
End2
3
4
5
6
Beginnning7
End8
9
10
11
</code></pre>
<p>Test case 2:</p>
<pre><code>String %!ABCD%!EF%! with %! delimiter results in:
Beginnning1
End2
3
4
5
6
Beginnning7
End8
9
10
Beginnning11
End12
</code></pre>
|
[] |
[
{
"body": "<p>Some off the cuff comments:</p>\n<p>It would help if you provided a compilable class rather than a somewhat misleading snippet.</p>\n<p>Your search would be better as a separate method.</p>\n<p>I don't see why you search in this way when String.indexof(String) and String.substring(int) exist.</p>\n<p>Have you a clear understanding of how you would handle overlapping delimiters? If your delimiter is "!!", how is "abc!!!def" to be interpreted?</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-22T18:58:58.817",
"Id": "253791",
"ParentId": "253785",
"Score": "0"
}
},
{
"body": "<p>Following code part can be changed.\nThere is no use with in the code for char c & char d. Hence following code can be removed</p>\n<pre><code>char c = baseText.charAt(i + j);\nchar d = delimiter.charAt(j);\n</code></pre>\n<p>And if can be used like</p>\n<pre><code>if (baseText.charAt(i + j) == delimiter.charAt(j)) \n</code></pre>\n<p>One More way to implement this could be like this, a bit more small and possible easy to manage.</p>\n<pre><code>{\n String baseText = "%!ABCD%!EF%!";\n String delimiter = "%!";\n int i = 0;\n int length = baseText.length();\n String replaceMent = "";\n while (i < length) {\n if (i < baseText.indexOf(delimiter) || !baseText.contains(delimiter)) {\n System.out.println(i + 1);\n i++;\n continue;\n }\n System.out.println("Beginning" + (baseText.indexOf(delimiter) + 1));\n System.out.println("End" + (baseText.indexOf(delimiter) + delimiter.length()));\n for (int j = 0; j < delimiter.length(); j++) {\n if (replaceMent.length() == 0) {\n replaceMent = " ";\n } else {\n replaceMent = replaceMent + " ";\n }\n }\n baseText = baseText.replaceFirst(delimiter, replaceMent);\n replaceMent = "";\n i = i + delimiter.length();\n }\n\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-23T14:00:14.160",
"Id": "253824",
"ParentId": "253785",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-22T17:28:29.580",
"Id": "253785",
"Score": "1",
"Tags": [
"java",
"algorithm",
"strings"
],
"Title": "Identifying indices of non-delimited characters in a string, supporting greater than 1 length of delimiters"
}
|
253785
|
<p>I'd like to have a review on my 2D-array container. Any criticism is welcome!
I based this on std::array implementation. Hopefully I didn't do too many bad stuff here.</p>
<pre><code>#ifndef 2DARRAY
#define 2DARRAY
#include <iostream>
#include <exception>
#include <initializer_list>
#include <cassert>
#include <stdexcept>
namespace container {
template<typename T, std::size_t rows, std::size_t columns>
class array_2d
{
static_assert(rows != 0, "error: first array size cannot be 0");
static_assert(columns != 0, "error: second array size cannot be 0");
private:
T m_array2d[rows][columns]{};
public:
// Aliases
using size_type = std::size_t;
using nested_init_list_type = std::initializer_list<std::initializer_list<T>>;
using pointer = T*;
using const_pointer = const T*;
using reference = T&;
using const_reference = const T&;
using reverse_iterator = std::reverse_iterator<pointer>;
using const_reverse_iterator = std::reverse_iterator<const_pointer>;
// Avoids having to type 3 braces, allows 2 braces only
// Note: 2 braces are always needed even for one single element
explicit array_2d(nested_init_list_type array2d_list) {
assert(array2d_list.size() <= rows && "Wrong number of rows [1st index] inserted");
size_type row{ 0 };
size_type column{ 0 };
for (auto& currentBrace : array2d_list) {
assert(currentBrace.size() <= columns && "Wrong number of columns [2nd index] inserted");
for (auto& currentValue : currentBrace) {
m_array2d[row][column++] = currentValue;
}
++row;
column = 0;
}
}
// Accessors (No bound checking)
constexpr pointer operator[](size_type index) { return m_array2d[index]; }
constexpr const_pointer operator[](size_type index) const { return m_array2d[index]; }
constexpr reference back() noexcept { return m_array2d[rows-1][columns-1]; }
constexpr const_reference back() const noexcept { return m_array2d[rows-1][columns-1]; }
constexpr pointer data() noexcept { return m_array2d[0]; }
constexpr const_pointer data() const noexcept { return m_array2d[0]; }
constexpr reference front() noexcept { return *(data()); }
constexpr const_reference front() const noexcept { return *(data()); }
// Accessors (With bound checking)
constexpr reference at(size_type rowIndex, size_type columnIndex)
{ return (rowIndex < rows && columnIndex < columns) ? m_array2d[rowIndex][columnIndex] : throw std::out_of_range("Error: Index out of range"); }
constexpr const_reference at(size_type rowIndex, size_type columnIndex) const
{ return (rowIndex < rows && columnIndex < columns) ? m_array2d[rowIndex][columnIndex] : throw std::out_of_range("Error: Index out of range"); }
// Size related
constexpr size_type size() const noexcept { return rows * columns; }
constexpr size_type row_size() const noexcept { return rows; }
constexpr size_type column_size() const noexcept { return columns; }
// Miscellaneous
void fill(const size_type& value) noexcept {
for (auto& element : m_array2d)
for (auto& current : element)
current = std::move(value);
}
void swap(array_2d& other) noexcept { std::swap(m_array2d, other.m_array2d); }
// Iterators - Missing reverse iterators
constexpr pointer begin() noexcept { return std::begin(m_array2d); }
constexpr const auto begin() const noexcept { return std::begin(m_array2d); }
constexpr const auto cbegin() const noexcept { return std::begin(m_array2d); }
constexpr auto end() noexcept { return std::end(m_array2d); }
constexpr const auto end() const noexcept { return std::end(m_array2d); }
constexpr const auto cend() const noexcept { return std::end(m_array2d); }
};
}
#endif
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-23T11:48:40.180",
"Id": "500517",
"Score": "1",
"body": "`#define 2DARRAY` - that's not valid."
}
] |
[
{
"body": "<p>Preprocessor macro identifiers can't begin with a digit, so the include guard name must be changed.</p>\n<p>There's no reason to include <code><iostream></code> header.</p>\n<p>A common convention for template parameters is to use <code>PascalCase</code> to distinguish them from members and local variables.</p>\n<p>Here's a <strong>bug</strong>:</p>\n<blockquote>\n<pre><code> for (auto& current : element) \n current = std::move(value);\n</code></pre>\n</blockquote>\n<p>The second and subsequent iterations of the loop use the moved-from <code>value</code>, which is probably not what we want. We shouldn't even be able to move from a const ref anyway. Just replace with <code>current = value;</code> or (better!) replace the whole loop with a call to <code>std::fill()</code>.</p>\n<p>On the other hand, I believe we can safely move from the <code>initializer_list</code> in the constructor. Remember to include <code><utility></code> to declare <code>std::move</code>.</p>\n<p>Well done for providing the usual type aliases. However, some are missing (e.g. <code>iterator</code>, <code>value_type</code>), and others are inconsistent with the implementation.</p>\n<hr />\n<p>I think the real problem you have here is that we're not really clear what the element type is. I recommend making our <code>value_type</code> be <code>T[columns]</code>, consistent with our <code>begin()</code> and <code>end()</code>, but also providing a <em>view</em> class onto all the elements as a flat array.</p>\n<p>That would look something like</p>\n<pre><code>private:\n T m_array2d[rows*columns]{};\n\npublic:\n iterator begin() { return m_array2d; }\n iterator end() { return m_array2d + rows*columns; }\n // etc\n T[rows*columns]& data();\n T[rows*columns] const& data() const;\n</code></pre>\n<p>Then <code>fill()</code> becomes much simpler, using <code>std::fill()</code> on the flat view:</p>\n<pre><code>void fill(const size_type& value)\n{\n using std::begin; // for argument-dependent lookup\n using std::end;\n auto& d = data();\n std::fill(begin(d), end(d), value);\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-26T13:59:00.997",
"Id": "500770",
"Score": "0",
"body": "Thanks for your insightful comment. This was really on point and improved the code quite a lot!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-23T15:09:33.313",
"Id": "253825",
"ParentId": "253786",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "253825",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-22T17:48:32.207",
"Id": "253786",
"Score": "3",
"Tags": [
"c++",
"array"
],
"Title": "(Beginner) Implementation of 2-dimensional array container"
}
|
253786
|
<p><strong>Task</strong></p>
<p>Input - integer number (year)</p>
<p>Print one number - the next year, in which all digits are pairwise different, and there are no digits 2 and 0. If there will never be such a year, print <code>-1</code>.</p>
<p><strong>My solution</strong> (correct)</p>
<p>Could you please recommend time / space complexity optimizations?</p>
<pre><code>vector<char> toVec(int n) {
vector<char> res;
while (n > 0) {
res.push_back((n % 10) + '0');
n /= 10;
}
return res;
}
int main(){
int year;
cin >> year;
for (int i = year + 1; i < pow(10, 8); ++i) {
vector<char> v = toVec(i);
if (find(begin(v), end(v), '2') == v.end() and
find(begin(v), end(v), '0') == v.end()) {
set<char> temp(v.begin(), v.end());
if (v.size() == temp.size()) {
cout << i;
return 0;
}
}
}
cout << -1;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-23T20:50:42.657",
"Id": "500567",
"Score": "0",
"body": "pow() is a floating-point function, and should generally avoid them when you can. More importantly, it gets called every iteration of the loop; you should probably precompute and store the result in a variable and use that variable in the loop."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-23T23:08:17.330",
"Id": "500582",
"Score": "0",
"body": "@Ilkhd gcc actually optimizes `i < pow(10, 8)` to the equivalent of `i < 100000000`, but I agree you shouldn't rely on that."
}
] |
[
{
"body": "<p>You seem to be missing some headers (<code><vector></code>, <code><iostream></code>, <code><cmath></code> and <code><set></code>), and also to be assuming the standard names are in the global namespace, rather than <code>std</code>.</p>\n<p>After attempting to read from <code>std::cin</code>, it's important to ensure the read was successful before attempting to use the result. (E.g. <code>if (!(std::cin >> year)) { std::cerr << "Input failure\\n"; return EXIT_FAILURE; }</code>).</p>\n<p>A linear search will be inefficient, especially as we may have to skip long runs containing the banned digits <code>0</code> and <code>2</code>. It would be better to construct the result using the available digits than to consider and test every possible number. The search is flawed anyway, since <code>std::pow(10, 8)</code> could be larger than the maximum <code>int</code>, leading to overflow (which is Undefined Behaviour).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-24T00:07:40.873",
"Id": "500584",
"Score": "0",
"body": "On what kind of hardware is INT_MAX < 10^8 ? A mic microcontroller? ;-)\n\nAgree about composing from digits."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-24T08:42:26.963",
"Id": "500599",
"Score": "0",
"body": "`INT_MAX` must be at least 32767, which is significantly less than 10⁸; I wouldn't want to enumerate all platforms, but certainly 8-bit microcontrollers are likely to tend towards the smaller values."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-22T21:28:40.303",
"Id": "253795",
"ParentId": "253792",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-22T19:22:42.590",
"Id": "253792",
"Score": "1",
"Tags": [
"c++",
"c++11"
],
"Title": "Find the next number with all different digits, and no 0 or 2"
}
|
253792
|
<p>This is a follow-up question for <a href="https://codereview.stackexchange.com/q/253556/231235">A recursive_transform Template Function Implementation with <code>std::invocable</code> concept in C++</a>, <a href="https://codereview.stackexchange.com/q/251823/231235">A recursive_transform Template Function with Execution Policy</a>, <a href="https://codereview.stackexchange.com/q/253665/231235">A recursive_transform Template Function Implementation with std::invocable Concept and Execution Policy in C++</a>, <a href="https://codereview.stackexchange.com/q/252488/231235">std::array and std::vector Type Arbitrary Nested Iterable Generator Functions Implementation in C++</a> and <a href="https://codereview.stackexchange.com/q/253032/231235">A Various Container Type Arbitrary Nested Iterable Generator Function Implementation in C++</a>. Thanks to <a href="https://codereview.stackexchange.com/a/253697/231235">G. Sliepen's answer</a>. In the parallel execution part, <a href="https://en.cppreference.com/w/cpp/algorithm/for_each" rel="nofollow noreferrer"><code>std::for_each()</code></a> structure is used instead of <code>std::back_inserter()</code> usage. With <a href="https://www.boost.org/doc/libs/1_72_0/libs/test/doc/html/index.html" rel="nofollow noreferrer">Boost.Test</a> tool, the transform operation for each element in nested <code>std::deque</code> and nested <code>std::vector</code> (nested level less than 16) is tested as below.</p>
<p><strong>The experimental implementation</strong></p>
<ol>
<li>Nested ranges comparison</li>
</ol>
<p>In order to compare two <code>std::ranges::input_range</code> things is equal or not, the operator <code>==</code> overloading implementation is as below.</p>
<pre><code>// Equal operator for std::ranges::input_range
template<std::ranges::input_range Range1, std::ranges::input_range Range2>
bool operator==(const Range1& input1, const Range2& input2)
{
if (input1.size() != input2.size())
{
return false;
}
for (size_t i = 0; i < input1.size(); i++)
{
if (input1.at(i) != input2.at(i))
{
return false;
}
}
return true;
}
// Not equal operator for std::ranges::input_range
template<std::ranges::input_range Range1, std::ranges::input_range Range2>
bool operator!=(const Range1& input1, const Range2& input2)
{
if (input1.size() != input2.size())
{
return true;
}
for (size_t i = 0; i < input1.size(); i++)
{
if (input1.at(i) != input2.at(i))
{
return true;
}
}
return false;
}
</code></pre>
<p>Note: I've check <a href="https://stackoverflow.com/a/12648810/6667035">this</a> and the usage <code>(test_result == expected_result)</code> as below should be compiled without any error. However, the error like <code>binary '==': no operator found which takes a left-hand operand of type 'std::vector<std::vector<char,std::allocator<char>>,std::allocator<std::vector<char,std::allocator<char>>>>' (or there is no acceptable conversion)</code> occurred so that I write my own equal operator for <code>std::ranges::input_range</code>. Maybe this is caused by the design of test case template with automated registration, but I am not quite sure.</p>
<ol start="2">
<li>Nested <code>std::deque</code> test cases</li>
</ol>
<pre><code>BOOST_AUTO_TEST_CASE_TEMPLATE(deque_lambda_with_auto_0dimension, TestType, test_types)
{
constexpr size_t dim_num = 0;
auto test_object = n_dim_container_generator<dim_num, std::deque, TestType>(static_cast<TestType>(2), 3);
auto test_result = recursive_transform(std::execution::par, test_object, [](auto& element) { return element * 2; });
auto expected_result = n_dim_container_generator<dim_num, std::deque, TestType>(static_cast<TestType>(2) * 2, 3);
// Content comparison
if (test_result == expected_result)
{
BOOST_TEST(true);
}
else
{
BOOST_TEST(false);
}
}
BOOST_AUTO_TEST_CASE_TEMPLATE(deque_lambda_with_auto_1dimension, TestType, test_types)
{
constexpr size_t dim_num = 1;
auto test_object = n_dim_container_generator<dim_num, std::deque, TestType>(static_cast<TestType>(2), 3);
auto test_result = recursive_transform(std::execution::par, test_object, [](auto& element) { return element * 2; });
auto expected_result = n_dim_container_generator<dim_num, std::deque, TestType>(static_cast<TestType>(2) * 2, 3);
// Content comparison
if (test_result == expected_result)
{
BOOST_TEST(true);
}
else
{
BOOST_TEST(false);
}
}
BOOST_AUTO_TEST_CASE_TEMPLATE(deque_lambda_with_auto_2dimension, TestType, test_types)
{
constexpr size_t dim_num = 2;
auto test_object = n_dim_container_generator<dim_num, std::deque, TestType>(static_cast<TestType>(2), 3);
auto test_result = recursive_transform(std::execution::par, test_object, [](auto& element) { return element * 2; });
auto expected_result = n_dim_container_generator<dim_num, std::deque, TestType>(static_cast<TestType>(2) * 2, 3);
// Content comparison
if (test_result == expected_result)
{
BOOST_TEST(true);
}
else
{
BOOST_TEST(false);
}
}
BOOST_AUTO_TEST_CASE_TEMPLATE(deque_lambda_with_auto_3dimension, TestType, test_types)
{
constexpr size_t dim_num = 3;
auto test_object = n_dim_container_generator<dim_num, std::deque, TestType>(static_cast<TestType>(2), 3);
auto test_result = recursive_transform(std::execution::par, test_object, [](auto& element) { return element * 2; });
auto expected_result = n_dim_container_generator<dim_num, std::deque, TestType>(static_cast<TestType>(2) * 2, 3);
// Content comparison
if (test_result == expected_result)
{
BOOST_TEST(true);
}
else
{
BOOST_TEST(false);
}
}
BOOST_AUTO_TEST_CASE_TEMPLATE(deque_lambda_with_auto_4dimension, TestType, test_types)
{
constexpr size_t dim_num = 4;
auto test_object = n_dim_container_generator<dim_num, std::deque, TestType>(static_cast<TestType>(2), 3);
auto test_result = recursive_transform(std::execution::par, test_object, [](auto& element) { return element * 2; });
auto expected_result = n_dim_container_generator<dim_num, std::deque, TestType>(static_cast<TestType>(2) * 2, 3);
// Content comparison
if (test_result == expected_result)
{
BOOST_TEST(true);
}
else
{
BOOST_TEST(false);
}
}
BOOST_AUTO_TEST_CASE_TEMPLATE(deque_lambda_with_auto_5dimension, TestType, test_types)
{
constexpr size_t dim_num = 5;
auto test_object = n_dim_container_generator<dim_num, std::deque, TestType>(static_cast<TestType>(2), 3);
auto test_result = recursive_transform(std::execution::par, test_object, [](auto& element) { return element * 2; });
auto expected_result = n_dim_container_generator<dim_num, std::deque, TestType>(static_cast<TestType>(2) * 2, 3);
// Content comparison
if (test_result == expected_result)
{
BOOST_TEST(true);
}
else
{
BOOST_TEST(false);
}
}
BOOST_AUTO_TEST_CASE_TEMPLATE(deque_lambda_with_auto_6dimension, TestType, test_types)
{
constexpr size_t dim_num = 6;
auto test_object = n_dim_container_generator<dim_num, std::deque, TestType>(static_cast<TestType>(2), 3);
auto test_result = recursive_transform(std::execution::par, test_object, [](auto& element) { return element * 2; });
auto expected_result = n_dim_container_generator<dim_num, std::deque, TestType>(static_cast<TestType>(2) * 2, 3);
// Content comparison
if (test_result == expected_result)
{
BOOST_TEST(true);
}
else
{
BOOST_TEST(false);
}
}
BOOST_AUTO_TEST_CASE_TEMPLATE(deque_lambda_with_auto_7dimension, TestType, test_types)
{
constexpr size_t dim_num = 7;
auto test_object = n_dim_container_generator<dim_num, std::deque, TestType>(static_cast<TestType>(2), 3);
auto test_result = recursive_transform(std::execution::par, test_object, [](auto& element) { return element * 2; });
auto expected_result = n_dim_container_generator<dim_num, std::deque, TestType>(static_cast<TestType>(2) * 2, 3);
// Content comparison
if (test_result == expected_result)
{
BOOST_TEST(true);
}
else
{
BOOST_TEST(false);
}
}
BOOST_AUTO_TEST_CASE_TEMPLATE(deque_lambda_with_auto_8dimension, TestType, test_types)
{
constexpr size_t dim_num = 8;
auto test_object = n_dim_container_generator<dim_num, std::deque, TestType>(static_cast<TestType>(2), 3);
auto test_result = recursive_transform(std::execution::par, test_object, [](auto& element) { return element * 2; });
auto expected_result = n_dim_container_generator<dim_num, std::deque, TestType>(static_cast<TestType>(2) * 2, 3);
// Content comparison
if (test_result == expected_result)
{
BOOST_TEST(true);
}
else
{
BOOST_TEST(false);
}
}
BOOST_AUTO_TEST_CASE_TEMPLATE(deque_lambda_with_auto_9dimension, TestType, test_types)
{
constexpr size_t dim_num = 9;
auto test_object = n_dim_container_generator<dim_num, std::deque, TestType>(static_cast<TestType>(2), 3);
auto test_result = recursive_transform(std::execution::par, test_object, [](auto& element) { return element * 2; });
auto expected_result = n_dim_container_generator<dim_num, std::deque, TestType>(static_cast<TestType>(2) * 2, 3);
// Content comparison
if (test_result == expected_result)
{
BOOST_TEST(true);
}
else
{
BOOST_TEST(false);
}
}
BOOST_AUTO_TEST_CASE_TEMPLATE(deque_lambda_with_auto_10dimension, TestType, test_types)
{
constexpr size_t dim_num = 10;
auto test_object = n_dim_container_generator<dim_num, std::deque, TestType>(static_cast<TestType>(2), 3);
auto test_result = recursive_transform(std::execution::par, test_object, [](auto& element) { return element * 2; });
auto expected_result = n_dim_container_generator<dim_num, std::deque, TestType>(static_cast<TestType>(2) * 2, 3);
// Content comparison
if (test_result == expected_result)
{
BOOST_TEST(true);
}
else
{
BOOST_TEST(false);
}
}
BOOST_AUTO_TEST_CASE_TEMPLATE(deque_lambda_with_auto_11dimension, TestType, test_types)
{
constexpr size_t dim_num = 11;
auto test_object = n_dim_container_generator<dim_num, std::deque, TestType>(static_cast<TestType>(2), 3);
auto test_result = recursive_transform(std::execution::par, test_object, [](auto& element) { return element * 2; });
auto expected_result = n_dim_container_generator<dim_num, std::deque, TestType>(static_cast<TestType>(2) * 2, 3);
// Content comparison
if (test_result == expected_result)
{
BOOST_TEST(true);
}
else
{
BOOST_TEST(false);
}
}
BOOST_AUTO_TEST_CASE_TEMPLATE(deque_lambda_with_auto_12dimension, TestType, test_types)
{
constexpr size_t dim_num = 12;
auto test_object = n_dim_container_generator<dim_num, std::deque, TestType>(static_cast<TestType>(2), 3);
auto test_result = recursive_transform(std::execution::par, test_object, [](auto& element) { return element * 2; });
auto expected_result = n_dim_container_generator<dim_num, std::deque, TestType>(static_cast<TestType>(2) * 2, 3);
// Content comparison
if (test_result == expected_result)
{
BOOST_TEST(true);
}
else
{
BOOST_TEST(false);
}
}
BOOST_AUTO_TEST_CASE_TEMPLATE(deque_lambda_with_auto_13dimension, TestType, test_types)
{
constexpr size_t dim_num = 13;
auto test_object = n_dim_container_generator<dim_num, std::deque, TestType>(static_cast<TestType>(2), 3);
auto test_result = recursive_transform(std::execution::par, test_object, [](auto& element) { return element * 2; });
auto expected_result = n_dim_container_generator<dim_num, std::deque, TestType>(static_cast<TestType>(2) * 2, 3);
// Content comparison
if (test_result == expected_result)
{
BOOST_TEST(true);
}
else
{
BOOST_TEST(false);
}
}
BOOST_AUTO_TEST_CASE_TEMPLATE(deque_lambda_with_auto_14dimension, TestType, test_types)
{
constexpr size_t dim_num = 14;
auto test_object = n_dim_container_generator<dim_num, std::deque, TestType>(static_cast<TestType>(2), 3);
auto test_result = recursive_transform(std::execution::par, test_object, [](auto& element) { return element * 2; });
auto expected_result = n_dim_container_generator<dim_num, std::deque, TestType>(static_cast<TestType>(2) * 2, 3);
// Content comparison
if (test_result == expected_result)
{
BOOST_TEST(true);
}
else
{
BOOST_TEST(false);
}
}
BOOST_AUTO_TEST_CASE_TEMPLATE(deque_lambda_with_auto_15dimension, TestType, test_types)
{
constexpr size_t dim_num = 15;
auto test_object = n_dim_container_generator<dim_num, std::deque, TestType>(static_cast<TestType>(2), 3);
auto test_result = recursive_transform(std::execution::par, test_object, [](auto& element) { return element * 2; });
auto expected_result = n_dim_container_generator<dim_num, std::deque, TestType>(static_cast<TestType>(2) * 2, 3);
// Content comparison
if (test_result == expected_result)
{
BOOST_TEST(true);
}
else
{
BOOST_TEST(false);
}
}
</code></pre>
<ol start="3">
<li>Nested <code>std::vector</code> test cases</li>
</ol>
<pre><code>BOOST_AUTO_TEST_CASE_TEMPLATE(vector_lambda_with_auto_0dimension, TestType, test_types)
{
constexpr size_t dim_num = 0;
auto test_object = n_dim_vector_generator<dim_num, TestType>(static_cast<TestType>(2), 3);
auto test_result = recursive_transform(std::execution::par, test_object, [](auto& element) { return element * 2; });
auto expected_result = n_dim_vector_generator<dim_num, TestType>(static_cast<TestType>(2) * 2, 3);
// Content comparison
if (test_result == expected_result)
{
BOOST_TEST(true);
}
else
{
BOOST_TEST(false);
}
}
BOOST_AUTO_TEST_CASE_TEMPLATE(vector_lambda_with_auto_1dimension, TestType, test_types)
{
constexpr size_t dim_num = 1;
auto test_object = n_dim_vector_generator<dim_num, TestType>(static_cast<TestType>(2), 3);
auto test_result = recursive_transform(std::execution::par, test_object, [](auto& element) { return element * 2; });
auto expected_result = n_dim_vector_generator<dim_num, TestType>(static_cast<TestType>(2) * 2, 3);
// Content comparison
if (test_result == expected_result)
{
BOOST_TEST(true);
}
else
{
BOOST_TEST(false);
}
}
BOOST_AUTO_TEST_CASE_TEMPLATE(vector_lambda_with_auto_2dimension, TestType, test_types)
{
constexpr size_t dim_num = 2;
auto test_object = n_dim_vector_generator<dim_num, TestType>(static_cast<TestType>(2), 3);
auto test_result = recursive_transform(std::execution::par, test_object, [](auto& element) { return element * 2; });
auto expected_result = n_dim_vector_generator<dim_num, TestType>(static_cast<TestType>(2) * 2, 3);
// Content comparison
if (test_result == expected_result)
{
BOOST_TEST(true);
}
else
{
BOOST_TEST(false);
}
}
BOOST_AUTO_TEST_CASE_TEMPLATE(vector_lambda_with_auto_3dimension, TestType, test_types)
{
constexpr size_t dim_num = 3;
auto test_object = n_dim_vector_generator<dim_num, TestType>(static_cast<TestType>(2), 3);
auto test_result = recursive_transform(std::execution::par, test_object, [](auto& element) { return element * 2; });
auto expected_result = n_dim_vector_generator<dim_num, TestType>(static_cast<TestType>(2) * 2, 3);
// Content comparison
if (test_result == expected_result)
{
BOOST_TEST(true);
}
else
{
BOOST_TEST(false);
}
}
BOOST_AUTO_TEST_CASE_TEMPLATE(vector_lambda_with_auto_4dimension, TestType, test_types)
{
constexpr size_t dim_num = 4;
auto test_object = n_dim_vector_generator<dim_num, TestType>(static_cast<TestType>(2), 3);
auto test_result = recursive_transform(std::execution::par, test_object, [](auto& element) { return element * 2; });
auto expected_result = n_dim_vector_generator<dim_num, TestType>(static_cast<TestType>(2) * 2, 3);
// Content comparison
if (test_result == expected_result)
{
BOOST_TEST(true);
}
else
{
BOOST_TEST(false);
}
}
BOOST_AUTO_TEST_CASE_TEMPLATE(vector_lambda_with_auto_5dimension, TestType, test_types)
{
constexpr size_t dim_num = 5;
auto test_object = n_dim_vector_generator<dim_num, TestType>(static_cast<TestType>(2), 3);
auto test_result = recursive_transform(std::execution::par, test_object, [](auto& element) { return element * 2; });
auto expected_result = n_dim_vector_generator<dim_num, TestType>(static_cast<TestType>(2) * 2, 3);
// Content comparison
if (test_result == expected_result)
{
BOOST_TEST(true);
}
else
{
BOOST_TEST(false);
}
}
BOOST_AUTO_TEST_CASE_TEMPLATE(vector_lambda_with_auto_6dimension, TestType, test_types)
{
constexpr size_t dim_num = 6;
auto test_object = n_dim_vector_generator<dim_num, TestType>(static_cast<TestType>(2), 3);
auto test_result = recursive_transform(std::execution::par, test_object, [](auto& element) { return element * 2; });
auto expected_result = n_dim_vector_generator<dim_num, TestType>(static_cast<TestType>(2) * 2, 3);
// Content comparison
if (test_result == expected_result)
{
BOOST_TEST(true);
}
else
{
BOOST_TEST(false);
}
}
BOOST_AUTO_TEST_CASE_TEMPLATE(vector_lambda_with_auto_7dimension, TestType, test_types)
{
constexpr size_t dim_num = 7;
auto test_object = n_dim_vector_generator<dim_num, TestType>(static_cast<TestType>(2), 3);
auto test_result = recursive_transform(std::execution::par, test_object, [](auto& element) { return element * 2; });
auto expected_result = n_dim_vector_generator<dim_num, TestType>(static_cast<TestType>(2) * 2, 3);
// Content comparison
if (test_result == expected_result)
{
BOOST_TEST(true);
}
else
{
BOOST_TEST(false);
}
}
BOOST_AUTO_TEST_CASE_TEMPLATE(vector_lambda_with_auto_8dimension, TestType, test_types)
{
constexpr size_t dim_num = 8;
auto test_object = n_dim_vector_generator<dim_num, TestType>(static_cast<TestType>(2), 3);
auto test_result = recursive_transform(std::execution::par, test_object, [](auto& element) { return element * 2; });
auto expected_result = n_dim_vector_generator<dim_num, TestType>(static_cast<TestType>(2) * 2, 3);
// Content comparison
if (test_result == expected_result)
{
BOOST_TEST(true);
}
else
{
BOOST_TEST(false);
}
}
BOOST_AUTO_TEST_CASE_TEMPLATE(vector_lambda_with_auto_9dimension, TestType, test_types)
{
constexpr size_t dim_num = 9;
auto test_object = n_dim_vector_generator<dim_num, TestType>(static_cast<TestType>(2), 3);
auto test_result = recursive_transform(std::execution::par, test_object, [](auto& element) { return element * 2; });
auto expected_result = n_dim_vector_generator<dim_num, TestType>(static_cast<TestType>(2) * 2, 3);
// Content comparison
if (test_result == expected_result)
{
BOOST_TEST(true);
}
else
{
BOOST_TEST(false);
}
}
BOOST_AUTO_TEST_CASE_TEMPLATE(vector_lambda_with_auto_10dimension, TestType, test_types)
{
constexpr size_t dim_num = 10;
auto test_object = n_dim_vector_generator<dim_num, TestType>(static_cast<TestType>(2), 3);
auto test_result = recursive_transform(std::execution::par, test_object, [](auto& element) { return element * 2; });
auto expected_result = n_dim_vector_generator<dim_num, TestType>(static_cast<TestType>(2) * 2, 3);
// Content comparison
if (test_result == expected_result)
{
BOOST_TEST(true);
}
else
{
BOOST_TEST(false);
}
}
BOOST_AUTO_TEST_CASE_TEMPLATE(vector_lambda_with_auto_11dimension, TestType, test_types)
{
constexpr size_t dim_num = 11;
auto test_object = n_dim_vector_generator<dim_num, TestType>(static_cast<TestType>(2), 3);
auto test_result = recursive_transform(std::execution::par, test_object, [](auto& element) { return element * 2; });
auto expected_result = n_dim_vector_generator<dim_num, TestType>(static_cast<TestType>(2) * 2, 3);
// Content comparison
if (test_result == expected_result)
{
BOOST_TEST(true);
}
else
{
BOOST_TEST(false);
}
}
BOOST_AUTO_TEST_CASE_TEMPLATE(vector_lambda_with_auto_12dimension, TestType, test_types)
{
constexpr size_t dim_num = 12;
auto test_object = n_dim_vector_generator<dim_num, TestType>(static_cast<TestType>(2), 3);
auto test_result = recursive_transform(std::execution::par, test_object, [](auto& element) { return element * 2; });
auto expected_result = n_dim_vector_generator<dim_num, TestType>(static_cast<TestType>(2) * 2, 3);
// Content comparison
if (test_result == expected_result)
{
BOOST_TEST(true);
}
else
{
BOOST_TEST(false);
}
}
BOOST_AUTO_TEST_CASE_TEMPLATE(vector_lambda_with_auto_13dimension, TestType, test_types)
{
constexpr size_t dim_num = 13;
auto test_object = n_dim_vector_generator<dim_num, TestType>(static_cast<TestType>(2), 3);
auto test_result = recursive_transform(std::execution::par, test_object, [](auto& element) { return element * 2; });
auto expected_result = n_dim_vector_generator<dim_num, TestType>(static_cast<TestType>(2) * 2, 3);
// Content comparison
if (test_result == expected_result)
{
BOOST_TEST(true);
}
else
{
BOOST_TEST(false);
}
}
BOOST_AUTO_TEST_CASE_TEMPLATE(vector_lambda_with_auto_14dimension, TestType, test_types)
{
constexpr size_t dim_num = 14;
auto test_object = n_dim_vector_generator<dim_num, TestType>(static_cast<TestType>(2), 3);
auto test_result = recursive_transform(std::execution::par, test_object, [](auto& element) { return element * 2; });
auto expected_result = n_dim_vector_generator<dim_num, TestType>(static_cast<TestType>(2) * 2, 3);
// Content comparison
if (test_result == expected_result)
{
BOOST_TEST(true);
}
else
{
BOOST_TEST(false);
}
}
BOOST_AUTO_TEST_CASE_TEMPLATE(vector_lambda_with_auto_15dimension, TestType, test_types)
{
constexpr size_t dim_num = 15;
auto test_object = n_dim_vector_generator<dim_num, TestType>(static_cast<TestType>(2), 3);
auto test_result = recursive_transform(std::execution::par, test_object, [](auto& element) { return element * 2; });
auto expected_result = n_dim_vector_generator<dim_num, TestType>(static_cast<TestType>(2) * 2, 3);
// Content comparison
if (test_result == expected_result)
{
BOOST_TEST(true);
}
else
{
BOOST_TEST(false);
}
}
</code></pre>
<p></p>
Full Testing Code
<p>
<p>The full testing code:</p>
<pre><code>#include <algorithm>
#include <array>
#include <cassert>
#include <chrono>
#include <complex>
#include <concepts>
#include <deque>
#include <execution>
#include <exception>
#include <functional>
#include <iostream>
#include <iterator>
#include <list>
#include <map>
#include <mutex>
#include <numeric>
#include <optional>
#include <stdexcept>
#include <string>
#include <thread>
#include <type_traits>
#include <utility>
#include <variant>
#include <vector>
#include <boost/utility.hpp>
//#define USE_BOOST_MULTIDIMENSIONAL_ARRAY
#ifdef USE_BOOST_MULTIDIMENSIONAL_ARRAY
#include <boost/multi_array.hpp>
#include <boost/multi_array/algorithm.hpp>
#include <boost/multi_array/base.hpp>
#include <boost/multi_array/collection_concept.hpp>
#endif
#define BOOST_TEST_MODULE tests_for_recursive_transform
#include <boost/test/included/unit_test.hpp>
#include <boost/test/test_tools.hpp>
#include <boost/mpl/list.hpp>
template<typename T>
concept is_inserterable = requires(T x)
{
std::inserter(x, std::ranges::end(x));
};
#ifdef USE_BOOST_MULTIDIMENSIONAL_ARRAY
template<typename T>
concept is_multi_array = requires(T x)
{
x.num_dimensions();
x.shape();
boost::multi_array(x);
};
#endif
template<std::ranges::input_range Range>
Range recursive_print(const Range& input, const int level = 0)
{
Range output = input;
std::cout << std::string(level, ' ') << "Level " << level << ":" << std::endl;
std::transform(input.cbegin(), input.cend(), output.begin(),
[level](auto& x)
{
std::cout << std::string(level, ' ') << x << std::endl;
return x;
}
);
return output;
}
template<std::ranges::input_range Range>
requires std::ranges::input_range<std::ranges::range_value_t<Range>>
Range recursive_print(const Range& input, const int level = 0)
{
Range output = input;
std::cout << std::string(level, ' ') << "Level " << level << ":" << std::endl;
std::transform(input.cbegin(), input.cend(), output.begin(),
[level](auto& element)
{
return recursive_print(element, level + 1);
}
);
return output;
}
// recursive_transform implementation
template<class T, class F>
constexpr auto recursive_transform(const T& input, const F& f)
{
return f(input);
}
// specific case for std::array
template<class T, std::size_t S, class F>
constexpr auto recursive_transform(const std::array<T, S>& input, const F& f)
{
using TransformedValueType = decltype(recursive_transform(*input.cbegin(), f));
std::array<TransformedValueType, S> output;
std::transform(input.cbegin(), input.cend(), output.begin(),
[&f](auto&& element)
{
return recursive_transform(element, f);
}
);
return output;
}
template<template<class...> class Container, class Function, class... Ts>
requires (is_inserterable<Container<Ts...>> && !std::invocable<Function, Container<Ts...>>)
constexpr auto recursive_transform(const Container<Ts...>& input, const Function& f)
{
using TransformedValueType = decltype(recursive_transform(*input.cbegin(), f));
Container<TransformedValueType> output;
std::transform(input.cbegin(), input.cend(), std::inserter(output, std::ranges::end(output)),
[&](auto&& element)
{
return recursive_transform(element, f);
}
);
return output;
}
#ifdef USE_BOOST_MULTIDIMENSIONAL_ARRAY
template<is_multi_array T, class F>
requires(!std::invocable<F, T>)
constexpr auto recursive_transform(const T& input, const F& f)
{
boost::multi_array output(input);
for (decltype(+input.shape()[0]) i{}; i != input.shape()[0]; ++i)
{
output[i] = recursive_transform(input[i], f);
}
return output;
}
#endif
// recursive_transform implementation (with execution policy)
template<class ExPo, class T, class F>
requires (std::is_execution_policy_v<std::remove_cvref_t<ExPo>>)
constexpr auto recursive_transform(ExPo execution_policy, const T& input, const F& f)
{
return f(input);
}
// specific case for std::array
template<class ExPo, class T, std::size_t S, class F>
requires (std::is_execution_policy_v<std::remove_cvref_t<ExPo>>)
constexpr auto recursive_transform(ExPo execution_policy, const std::array<T, S>& input, const F& f)
{
using TransformedValueType = decltype(recursive_transform(execution_policy, *input.cbegin(), f));
std::array<TransformedValueType, S> output;
std::transform(input.cbegin(), input.cend(), output.begin(),
[execution_policy, &f](auto&& element)
{
return recursive_transform(execution_policy, element, f);
}
);
return output;
}
template<class ExPo, template<class...> class Container, class Function, class... Ts>
requires (std::is_execution_policy_v<std::remove_cvref_t<ExPo>>) && (is_inserterable<Container<Ts...>> && !std::invocable<Function, Container<Ts...>>)
constexpr auto recursive_transform(ExPo execution_policy, const Container<Ts...>& input, const Function& f)
{
using TransformedValueType = decltype(recursive_transform(execution_policy, *input.cbegin(), f));
Container<TransformedValueType> output(input.size());
std::mutex mutex;
std::for_each(execution_policy, input.cbegin(), input.cend(),
[&](auto&& element)
{
auto result = recursive_transform(execution_policy, element, f);
std::lock_guard lock(mutex);
output.emplace_back(std::move(result));
}
);
return output;
}
#ifdef USE_BOOST_MULTIDIMENSIONAL_ARRAY
template<class ExPo, is_multi_array T, class F>
requires (std::is_execution_policy_v<std::remove_cvref_t<ExPo>>) && (!std::invocable<F, T>)
constexpr auto recursive_transform(const T& input, const F& f)
{
boost::multi_array output(input);
for (decltype(+input.shape()[0]) i{}; i != input.shape()[0]; ++i)
{
output[i] = recursive_transform(execution_policy, input[i], f);
}
return output;
}
#endif
template<std::size_t dim, class T>
constexpr auto n_dim_vector_generator(T input, std::size_t times)
{
if constexpr (dim == 0)
{
return input;
}
else
{
auto element = n_dim_vector_generator<dim - 1>(input, times);
std::vector<decltype(element)> output(times, element);
return output;
}
}
template<std::size_t dim, std::size_t times, class T>
constexpr auto n_dim_array_generator(T input)
{
if constexpr (dim == 0)
{
return input;
}
else
{
auto element = n_dim_array_generator<dim - 1, times>(input);
std::array<decltype(element), times> output;
std::fill(std::begin(output), std::end(output), element);
return output;
}
}
template<std::size_t dim, class T>
constexpr auto n_dim_deque_generator(T input, std::size_t times)
{
if constexpr (dim == 0)
{
return input;
}
else
{
auto element = n_dim_deque_generator<dim - 1>(input, times);
std::deque<decltype(element)> output(times, element);
return output;
}
}
template<std::size_t dim, class T>
constexpr auto n_dim_list_generator(T input, std::size_t times)
{
if constexpr (dim == 0)
{
return input;
}
else
{
auto element = n_dim_list_generator<dim - 1>(input, times);
std::list<decltype(element)> output(times, element);
return output;
}
}
template<std::size_t dim, template<class...> class Container = std::vector, class T>
constexpr auto n_dim_container_generator(T input, std::size_t times)
{
if constexpr (dim == 0)
{
return input;
}
else
{
return Container(times, n_dim_container_generator<dim - 1, Container, T>(input, times));
}
}
template<typename T>
struct recursive_iter_value_t_detail
{
using type = T;
};
template <std::ranges::range T>
struct recursive_iter_value_t_detail<T>
: recursive_iter_value_t_detail<std::iter_value_t<T>>
{ };
template<typename T>
using recursive_iter_value_t = typename recursive_iter_value_t_detail<T>::type;
// Equal operator for std::ranges::input_range
template<std::ranges::input_range Range1, std::ranges::input_range Range2>
bool operator==(const Range1& input1, const Range2& input2)
{
if (input1.size() != input2.size())
{
return false;
}
for (size_t i = 0; i < input1.size(); i++)
{
if (input1.at(i) != input2.at(i))
{
return false;
}
}
return true;
}
// Not equal operator for std::ranges::input_range
template<std::ranges::input_range Range1, std::ranges::input_range Range2>
bool operator!=(const Range1& input1, const Range2& input2)
{
if (input1.size() != input2.size())
{
return true;
}
for (size_t i = 0; i < input1.size(); i++)
{
if (input1.at(i) != input2.at(i))
{
return true;
}
}
return false;
}
typedef boost::mpl::list<char, int, short, long, long long int, unsigned char, unsigned int, unsigned short int, unsigned long int, float, double, long double> test_types;
BOOST_AUTO_TEST_CASE_TEMPLATE(vector_lambda_with_auto_0dimension, TestType, test_types)
{
constexpr size_t dim_num = 0;
auto test_object = n_dim_vector_generator<dim_num, TestType>(static_cast<TestType>(2), 3);
auto test_result = recursive_transform(std::execution::par, test_object, [](auto& element) { return element * 2; });
auto expected_result = n_dim_vector_generator<dim_num, TestType>(static_cast<TestType>(2) * 2, 3);
// Content comparison
if (test_result == expected_result)
{
BOOST_TEST(true);
}
else
{
BOOST_TEST(false);
}
}
BOOST_AUTO_TEST_CASE_TEMPLATE(vector_lambda_with_auto_1dimension, TestType, test_types)
{
constexpr size_t dim_num = 1;
auto test_object = n_dim_vector_generator<dim_num, TestType>(static_cast<TestType>(2), 3);
auto test_result = recursive_transform(std::execution::par, test_object, [](auto& element) { return element * 2; });
auto expected_result = n_dim_vector_generator<dim_num, TestType>(static_cast<TestType>(2) * 2, 3);
// Content comparison
if (test_result == expected_result)
{
BOOST_TEST(true);
}
else
{
BOOST_TEST(false);
}
}
BOOST_AUTO_TEST_CASE_TEMPLATE(vector_lambda_with_auto_2dimension, TestType, test_types)
{
constexpr size_t dim_num = 2;
auto test_object = n_dim_vector_generator<dim_num, TestType>(static_cast<TestType>(2), 3);
auto test_result = recursive_transform(std::execution::par, test_object, [](auto& element) { return element * 2; });
auto expected_result = n_dim_vector_generator<dim_num, TestType>(static_cast<TestType>(2) * 2, 3);
// Content comparison
if (test_result == expected_result)
{
BOOST_TEST(true);
}
else
{
BOOST_TEST(false);
}
}
BOOST_AUTO_TEST_CASE_TEMPLATE(vector_lambda_with_auto_3dimension, TestType, test_types)
{
constexpr size_t dim_num = 3;
auto test_object = n_dim_vector_generator<dim_num, TestType>(static_cast<TestType>(2), 3);
auto test_result = recursive_transform(std::execution::par, test_object, [](auto& element) { return element * 2; });
auto expected_result = n_dim_vector_generator<dim_num, TestType>(static_cast<TestType>(2) * 2, 3);
// Content comparison
if (test_result == expected_result)
{
BOOST_TEST(true);
}
else
{
BOOST_TEST(false);
}
}
BOOST_AUTO_TEST_CASE_TEMPLATE(vector_lambda_with_auto_4dimension, TestType, test_types)
{
constexpr size_t dim_num = 4;
auto test_object = n_dim_vector_generator<dim_num, TestType>(static_cast<TestType>(2), 3);
auto test_result = recursive_transform(std::execution::par, test_object, [](auto& element) { return element * 2; });
auto expected_result = n_dim_vector_generator<dim_num, TestType>(static_cast<TestType>(2) * 2, 3);
// Content comparison
if (test_result == expected_result)
{
BOOST_TEST(true);
}
else
{
BOOST_TEST(false);
}
}
BOOST_AUTO_TEST_CASE_TEMPLATE(vector_lambda_with_auto_5dimension, TestType, test_types)
{
constexpr size_t dim_num = 5;
auto test_object = n_dim_vector_generator<dim_num, TestType>(static_cast<TestType>(2), 3);
auto test_result = recursive_transform(std::execution::par, test_object, [](auto& element) { return element * 2; });
auto expected_result = n_dim_vector_generator<dim_num, TestType>(static_cast<TestType>(2) * 2, 3);
// Content comparison
if (test_result == expected_result)
{
BOOST_TEST(true);
}
else
{
BOOST_TEST(false);
}
}
BOOST_AUTO_TEST_CASE_TEMPLATE(vector_lambda_with_auto_6dimension, TestType, test_types)
{
constexpr size_t dim_num = 6;
auto test_object = n_dim_vector_generator<dim_num, TestType>(static_cast<TestType>(2), 3);
auto test_result = recursive_transform(std::execution::par, test_object, [](auto& element) { return element * 2; });
auto expected_result = n_dim_vector_generator<dim_num, TestType>(static_cast<TestType>(2) * 2, 3);
// Content comparison
if (test_result == expected_result)
{
BOOST_TEST(true);
}
else
{
BOOST_TEST(false);
}
}
BOOST_AUTO_TEST_CASE_TEMPLATE(vector_lambda_with_auto_7dimension, TestType, test_types)
{
constexpr size_t dim_num = 7;
auto test_object = n_dim_vector_generator<dim_num, TestType>(static_cast<TestType>(2), 3);
auto test_result = recursive_transform(std::execution::par, test_object, [](auto& element) { return element * 2; });
auto expected_result = n_dim_vector_generator<dim_num, TestType>(static_cast<TestType>(2) * 2, 3);
// Content comparison
if (test_result == expected_result)
{
BOOST_TEST(true);
}
else
{
BOOST_TEST(false);
}
}
BOOST_AUTO_TEST_CASE_TEMPLATE(vector_lambda_with_auto_8dimension, TestType, test_types)
{
constexpr size_t dim_num = 8;
auto test_object = n_dim_vector_generator<dim_num, TestType>(static_cast<TestType>(2), 3);
auto test_result = recursive_transform(std::execution::par, test_object, [](auto& element) { return element * 2; });
auto expected_result = n_dim_vector_generator<dim_num, TestType>(static_cast<TestType>(2) * 2, 3);
// Content comparison
if (test_result == expected_result)
{
BOOST_TEST(true);
}
else
{
BOOST_TEST(false);
}
}
BOOST_AUTO_TEST_CASE_TEMPLATE(vector_lambda_with_auto_9dimension, TestType, test_types)
{
constexpr size_t dim_num = 9;
auto test_object = n_dim_vector_generator<dim_num, TestType>(static_cast<TestType>(2), 3);
auto test_result = recursive_transform(std::execution::par, test_object, [](auto& element) { return element * 2; });
auto expected_result = n_dim_vector_generator<dim_num, TestType>(static_cast<TestType>(2) * 2, 3);
// Content comparison
if (test_result == expected_result)
{
BOOST_TEST(true);
}
else
{
BOOST_TEST(false);
}
}
BOOST_AUTO_TEST_CASE_TEMPLATE(vector_lambda_with_auto_10dimension, TestType, test_types)
{
constexpr size_t dim_num = 10;
auto test_object = n_dim_vector_generator<dim_num, TestType>(static_cast<TestType>(2), 3);
auto test_result = recursive_transform(std::execution::par, test_object, [](auto& element) { return element * 2; });
auto expected_result = n_dim_vector_generator<dim_num, TestType>(static_cast<TestType>(2) * 2, 3);
// Content comparison
if (test_result == expected_result)
{
BOOST_TEST(true);
}
else
{
BOOST_TEST(false);
}
}
BOOST_AUTO_TEST_CASE_TEMPLATE(vector_lambda_with_auto_11dimension, TestType, test_types)
{
constexpr size_t dim_num = 11;
auto test_object = n_dim_vector_generator<dim_num, TestType>(static_cast<TestType>(2), 3);
auto test_result = recursive_transform(std::execution::par, test_object, [](auto& element) { return element * 2; });
auto expected_result = n_dim_vector_generator<dim_num, TestType>(static_cast<TestType>(2) * 2, 3);
// Content comparison
if (test_result == expected_result)
{
BOOST_TEST(true);
}
else
{
BOOST_TEST(false);
}
}
BOOST_AUTO_TEST_CASE_TEMPLATE(vector_lambda_with_auto_12dimension, TestType, test_types)
{
constexpr size_t dim_num = 12;
auto test_object = n_dim_vector_generator<dim_num, TestType>(static_cast<TestType>(2), 3);
auto test_result = recursive_transform(std::execution::par, test_object, [](auto& element) { return element * 2; });
auto expected_result = n_dim_vector_generator<dim_num, TestType>(static_cast<TestType>(2) * 2, 3);
// Content comparison
if (test_result == expected_result)
{
BOOST_TEST(true);
}
else
{
BOOST_TEST(false);
}
}
BOOST_AUTO_TEST_CASE_TEMPLATE(vector_lambda_with_auto_13dimension, TestType, test_types)
{
constexpr size_t dim_num = 13;
auto test_object = n_dim_vector_generator<dim_num, TestType>(static_cast<TestType>(2), 3);
auto test_result = recursive_transform(std::execution::par, test_object, [](auto& element) { return element * 2; });
auto expected_result = n_dim_vector_generator<dim_num, TestType>(static_cast<TestType>(2) * 2, 3);
// Content comparison
if (test_result == expected_result)
{
BOOST_TEST(true);
}
else
{
BOOST_TEST(false);
}
}
BOOST_AUTO_TEST_CASE_TEMPLATE(vector_lambda_with_auto_14dimension, TestType, test_types)
{
constexpr size_t dim_num = 14;
auto test_object = n_dim_vector_generator<dim_num, TestType>(static_cast<TestType>(2), 3);
auto test_result = recursive_transform(std::execution::par, test_object, [](auto& element) { return element * 2; });
auto expected_result = n_dim_vector_generator<dim_num, TestType>(static_cast<TestType>(2) * 2, 3);
// Content comparison
if (test_result == expected_result)
{
BOOST_TEST(true);
}
else
{
BOOST_TEST(false);
}
}
BOOST_AUTO_TEST_CASE_TEMPLATE(vector_lambda_with_auto_15dimension, TestType, test_types)
{
constexpr size_t dim_num = 15;
auto test_object = n_dim_vector_generator<dim_num, TestType>(static_cast<TestType>(2), 3);
auto test_result = recursive_transform(std::execution::par, test_object, [](auto& element) { return element * 2; });
auto expected_result = n_dim_vector_generator<dim_num, TestType>(static_cast<TestType>(2) * 2, 3);
// Content comparison
if (test_result == expected_result)
{
BOOST_TEST(true);
}
else
{
BOOST_TEST(false);
}
}
</code></pre>
<p>If the enough memory and compile time / run time resource is available, the test output is like:</p>
<pre><code>Running 192 test cases...
*** No errors detected
</code></pre>
</p>
<p><a href="https://godbolt.org/z/jv39Yo" rel="nofollow noreferrer">A Godbolt link is here.</a></p>
<p>All suggestions are welcome.</p>
<p>The summary information:</p>
<ul>
<li><p>Which question it is a follow-up to?</p>
<p><a href="https://codereview.stackexchange.com/q/253556/231235">A recursive_transform Template Function Implementation with <code>std::invocable</code> concept in C++</a>,</p>
<p><a href="https://codereview.stackexchange.com/q/251823/231235">A recursive_transform Template Function with Execution Policy</a>,</p>
<p><a href="https://codereview.stackexchange.com/q/253665/231235">A recursive_transform Template Function Implementation with std::invocable Concept and Execution Policy in C++</a>,</p>
<p><a href="https://codereview.stackexchange.com/q/252488/231235">std::array and std::vector Type Arbitrary Nested Iterable Generator Functions Implementation in C++</a> and</p>
<p><a href="https://codereview.stackexchange.com/q/253032/231235">A Various Container Type Arbitrary Nested Iterable Generator Function Implementation in C++</a></p>
</li>
<li><p>What changes has been made in the code since last question?</p>
<p>I am trying to design some unit test cases as complete as possible in various usage scenarios.</p>
</li>
<li><p>Why a new review is being asked for?</p>
<p>About the part of <em>Nested ranges comparison</em>, I am not sure if it is a good idea to compare each element in two nested ranges in the way above. If there is any possible improvement, please let me know.</p>
</li>
</ul>
|
[] |
[
{
"body": "<h1>Avoid code duplication</h1>\n<p>You can implement <code>operator!=</code> in terms of <code>operator==</code>, or the other way around, like so:</p>\n<pre><code>template<std::ranges::input_range Range1, std::ranges::input_range Range2>\nbool operator!=(const Range1& input1, const Range2& input2)\n{\n return !(input1 == input2);\n}\n</code></pre>\n<h1>Make use of <a href=\"https://en.cppreference.com/w/cpp/algorithm/ranges/mismatch\" rel=\"nofollow noreferrer\"><code>std::ranges::mismatch</code></a></h1>\n<p>There is a already a function in the standard library to compare two ranges to each other, and find the first element that differs. You can make use of that:</p>\n<pre><code>template<std::ranges::input_range Range1, std::ranges::input_range Range2>\nbool operator==(const Range1& input1, const Range2& input2)\n{\n auto [in1, in2] = std::ranges::mismatch(input1, input2);\n return in1 == std::end(input1) && in2 == std::end(input2);\n}\n</code></pre>\n<h1>Consider whether you want to overload <code>operator==</code> this way</h1>\n<p>One problem of your code is that there is already an <code>operator==</code> for STL containers, but you are introducing an overload that now accepts two containers with a different value type. For example, the following gives an error without your overload:</p>\n<pre><code>std::array<int, 3> a{1, 2, 3};\nstd::array<float, 3> b{1, 2, 3};\nreturn a == b;\n</code></pre>\n<p>Whereas it compiles and returns <code>true</code> with your overload. Maybe that is convenient for you, but consider that other templated code might depend on the fact that <code>a == b</code> is ill-formed.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-25T20:09:25.797",
"Id": "253910",
"ParentId": "253793",
"Score": "1"
}
},
{
"body": "<p>You are correct in your intuition that this isn’t really the best way to do this with Boost.Test. In fact, Boost.Test has about a half-dozen better ways to handle this, but I’ll focus on the one that I think will be of the most use for you.</p>\n<p>Normally I try to review the code as written, but in this case, it’s actually much easier to start from scratch and build up toward what you have, showing you alternatives along the way.</p>\n<h1>The set up</h1>\n<p>I’ll pretend you have a single header file with your algorithm, <code>recursive_transform.hpp</code>, and absolutely nothing else:</p>\n<pre><code>// recursive_transform.hpp\n\n#ifndef RECURSIVE_TRANSFORM_INC\n#define RECURSIVE_TRANSFORM_INC\n\n#include <algorithm>\n#include <array>\n#include <concepts>\n#include <execution>\n#include <iterator>\n#include <mutex>\n#include <ranges>\n#include <utility>\n\n//#define USE_BOOST_MULTIDIMENSIONAL_ARRAY\n\n#ifdef USE_BOOST_MULTIDIMENSIONAL_ARRAY\n# include <boost/multi_array.hpp>\n#endif\n\ntemplate<typename T>\nconcept is_inserterable = requires(T x)\n{\n std::inserter(x, std::ranges::end(x));\n};\n\n#ifdef USE_BOOST_MULTIDIMENSIONAL_ARRAY\ntemplate<typename T>\nconcept is_multi_array = requires(T x)\n{\n x.num_dimensions();\n x.shape();\n boost::multi_array(x);\n};\n#endif\n\n// recursive_transform implementation\ntemplate<class T, class F>\nconstexpr auto recursive_transform(const T& input, const F& f)\n{\n return f(input);\n}\n\n// specific case for std::array\ntemplate<class T, std::size_t S, class F>\nconstexpr auto recursive_transform(const std::array<T, S>& input, const F& f)\n{\n using TransformedValueType = decltype(recursive_transform(*input.cbegin(), f));\n\n std::array<TransformedValueType, S> output;\n std::transform(input.cbegin(), input.cend(), output.begin(), \n [&f](auto&& element)\n {\n return recursive_transform(element, f);\n }\n );\n return output;\n}\n\ntemplate<template<class...> class Container, class Function, class... Ts>\nrequires (is_inserterable<Container<Ts...>> && !std::invocable<Function, Container<Ts...>>)\nconstexpr auto recursive_transform(const Container<Ts...>& input, const Function& f)\n{\n using TransformedValueType = decltype(recursive_transform(*input.cbegin(), f));\n Container<TransformedValueType> output;\n\n std::transform(input.cbegin(), input.cend(), std::inserter(output, std::ranges::end(output)),\n [&](auto&& element)\n {\n return recursive_transform(element, f);\n }\n );\n\n return output;\n}\n\n#ifdef USE_BOOST_MULTIDIMENSIONAL_ARRAY\ntemplate<is_multi_array T, class F>\nrequires(!std::invocable<F, T>)\nconstexpr auto recursive_transform(const T& input, const F& f)\n{\n boost::multi_array output(input);\n for (decltype(+input.shape()[0]) i = 0; i < input.shape()[0]; i++)\n {\n output[i] = recursive_transform(input[i], f);\n }\n return output;\n}\n#endif\n\n// recursive_transform implementation (with execution policy)\ntemplate<class ExPo, class T, class F>\nrequires (std::is_execution_policy_v<std::remove_cvref_t<ExPo>>)\nconstexpr auto recursive_transform(ExPo execution_policy, const T& input, const F& f)\n{\n return f(input);\n}\n\n// specific case for std::array\ntemplate<class ExPo, class T, std::size_t S, class F>\nrequires (std::is_execution_policy_v<std::remove_cvref_t<ExPo>>)\nconstexpr auto recursive_transform(ExPo execution_policy, const std::array<T, S>& input, const F& f)\n{\n using TransformedValueType = decltype(recursive_transform(execution_policy, *input.cbegin(), f));\n\n std::array<TransformedValueType, S> output;\n std::transform(input.cbegin(), input.cend(), output.begin(), \n [execution_policy, &f](auto&& element)\n {\n return recursive_transform(execution_policy, element, f);\n }\n );\n return output;\n}\n\ntemplate<class ExPo, template<class...> class Container, class Function, class... Ts>\nrequires (std::is_execution_policy_v<std::remove_cvref_t<ExPo>>) && (is_inserterable<Container<Ts...>> && !std::invocable<Function, Container<Ts...>>)\nconstexpr auto recursive_transform(ExPo execution_policy, const Container<Ts...>& input, const Function& f)\n{\n using TransformedValueType = decltype(recursive_transform(execution_policy, *input.cbegin(), f));\n Container<TransformedValueType> output(input.size());\n std::mutex mutex;\n\n std::for_each(execution_policy, input.cbegin(), input.cend(),\n [&](auto&& element)\n {\n auto result = recursive_transform(execution_policy, element, f);\n std::lock_guard lock(mutex);\n output.emplace_back(std::move(result));\n }\n );\n\n return output;\n}\n\n#ifdef USE_BOOST_MULTIDIMENSIONAL_ARRAY\ntemplate<class ExPo, is_multi_array T, class F>\nrequires (std::is_execution_policy_v<std::remove_cvref_t<ExPo>>) && (!std::invocable<F, T>)\nconstexpr auto recursive_transform(ExPo execution_policy, const T& input, const F& f)\n{\n boost::multi_array output(input);\n for (decltype(+input.shape()[0]) i = 0; i < input.shape()[0]; i++)\n {\n output[i] = recursive_transform(execution_policy, input[i], f);\n }\n return output;\n}\n#endif\n\n#endif // include guard\n</code></pre>\n<h1>The first test</h1>\n<p>Now the first thing you should do with a header like this is create a paired source file. Yes, even if that source file is going to be completely empty (which is actually quite common with template code). The reason why is to test whether this header is actually self-contained. All you need is this:</p>\n<pre><code>// recursive_transform.cpp\n\n#include <recursive_transform.hpp>\n</code></pre>\n<p>That’s it. It should be able to compile (but not link!). Using <code>g++</code> as an example:</p>\n<pre class=\"lang-shell prettyprint-override\"><code>$ g++ --std=c++20 --pedantic -Wall -Wextra -c recursive_transform.cpp\n$ \n</code></pre>\n<p>Note that I’m enabling a bunch of warnings. You <em>really</em> want to do that when testing.</p>\n<p>So it compiles. If it didn’t, then there are either errors in the header, or you have forgotten to include a necessary header. (In my case, in my first attempt, I got an error about <code>std::is_execution_policy_v</code>, because I’d forgotten to include <code><execution></code>.)</p>\n<p>Though this isn’t using a test framework, it <em>is</em> a test. It’s a very basic pass/fail compile test to check whether the header is valid and complete on its own. When you actually compile your test executable, it’s usually free and harmless to do this at the same time and link it in, so you might as well.</p>\n<h1>Starting with Boost.Test</h1>\n<p>Okay, the biggest problem with your existing test code, in my opinion, is that is <em>ABSURDLY</em> slow. Like… criminally slow. I was awestruck that both the compilation and running brought my 8-core beast to its knees.</p>\n<p>That’s simply not acceptable. Tests should be fairly quick… no more than a couple seconds, ideally. Why? Two reasons:</p>\n<ol>\n<li>Because you should be running them often. In fact, my own development cycle is basically:\n<ol>\n<li>Look over code to see what changes are needed.</li>\n<li>Make the changes.</li>\n<li>Compile/run the tests.</li>\n<li>If the previous step takes more than 5 or so seconds, go back to looking over the code in anticipation of the <em>next</em> iteration.</li>\n<li>Check the test results.\nIn other words, I’m running the tests dozens, if not hundreds of times during a decent coding session. If they took <em>minutes</em> to run each time… that would not only slow down my progress to a crawl, it would break my concentration every time I had to wait.</li>\n</ol>\n</li>\n<li>Because you will probably want to use a continuous integration facility—like, say, Travis CI—and those services run on tiny servers and will often just timeout and die when a compile/test job takes too long.</li>\n</ol>\n<p>Especially for something like a generic algorithm like this (which, I mean, <code>recursive_transform()</code> <em>should</em> be fast, shouldn’t it? so why would the tests be slow?), there’s no real justification for a test suite that takes several <em>minutes</em> to run.</p>\n<p>One thing you can do to <em>really</em> speed up Boost.Test is to use the shared libraries, rather than the header-only variant. Boost.Test itself recommends this. If you doubt whether this is really that important, try compiling and running this:</p>\n<pre><code>#define BOOST_TEST_MODULE tests_for_recursive_transform\n#include <boost/test/included/unit_test.hpp>\n\nBOOST_AUTO_TEST_CASE(test)\n{\n BOOST_TEST(1 == 1);\n}\n\n// g++ --std=c++20 --pedantic -Wall -Wextra -c test.cpp\n// g++ --std=c++20 --pedantic -Wall -Wextra test.o\n</code></pre>\n<p>… versus this:</p>\n<pre><code>#define BOOST_TEST_MODULE tests_for_recursive_transform\n#define BOOST_TEST_DYN_LINK\n#include <boost/test/unit_test.hpp>\n\nBOOST_AUTO_TEST_CASE(test)\n{\n BOOST_TEST(1 == 1);\n}\n\n// g++ --std=c++20 --pedantic -Wall -Wextra -c test.cpp\n// g++ --std=c++20 --pedantic -Wall -Wextra test.o -lboost_unit_test_framework\n</code></pre>\n<p>On my machine, the latter is over 5× faster, and the test executable is over 30× smaller. And that speed difference gets <em>really</em> important when you have more tests, and more complicated test structures.</p>\n<p>(Actually, when I code, I quite often have a process where a single command triggers a <code>make</code> of the entire project with all unit tests <em>THREE TIMES</em>; once with GCC, once with Clang, and once with Clang using libc++ rather than libstdc++. This all happens lightning fast, generally (and in parallel), so my process is to edit some code, make and run the tests, grab a sip of my drink and a nibble of my snack, and by the time I look at the screen again, the tests are already complete… and, hopefully, have all passed… and I’m ready for the next iteration. This turnaround needs to be fast to work, and that means the tests have to build and run in mere seconds.)</p>\n<p>You can get the best of both worlds by doing this:</p>\n<pre><code>// recursive_transform.test.cpp\n\n#define BOOST_TEST_MODULE tests_for_recursive_transform\n#ifdef BOOST_TEST_DYN_LINK\n# include <boost/test/unit_test.hpp>\n#else\n# include <boost/test/included/unit_test.hpp>\n#endif // BOOST_TEST_DYN_LINK\n\nBOOST_AUTO_TEST_CASE(test)\n{\n BOOST_TEST(1 == 1);\n}\n</code></pre>\n<p>If you want to use the header-only variant, you do:</p>\n<pre class=\"lang-shell prettyprint-override\"><code>$ g++ --std=c++20 --pedantic -Wall -Wextra -c recursive_transform.cpp\n$ g++ --std=c++20 --pedantic -Wall -Wextra -c recursive_transform.test.cpp\n$ g++ --std=c++20 --pedantic -Wall -Wextra recursive_transform.test.o recursive_transform.o\n$ ./a.out\nRunning 1 test case...\n\n*** No errors detected\n$ \n</code></pre>\n<p>… but normally, you’ll want to do:</p>\n<pre class=\"lang-shell prettyprint-override\"><code>$ g++ --std=c++20 --pedantic -Wall -Wextra -DBOOST_TEST_DYN_LINK -c recursive_transform.cpp\n$ g++ --std=c++20 --pedantic -Wall -Wextra -DBOOST_TEST_DYN_LINK -c recursive_transform.test.cpp\n$ g++ --std=c++20 --pedantic -Wall -Wextra recursive_transform.o recursive_transform.test.o -lboost_unit_test_framework\n$ ./a.out\nRunning 1 test case...\n\n*** No errors detected\n$ \n</code></pre>\n<h1>The first tests</h1>\n<p>Now, you use test case <em>templates</em>, that get instantiated with a <em>dozen</em> types:</p>\n<ul>\n<li><code>char</code></li>\n<li><code>int</code></li>\n<li><code>short</code></li>\n<li><code>long</code></li>\n<li><code>long long int</code></li>\n<li><code>unsigned char</code></li>\n<li><code>unsigned int</code></li>\n<li><code>unsigned short int</code></li>\n<li><code>unsigned long int</code></li>\n<li><code>float</code></li>\n<li><code>double</code></li>\n<li><code>long double</code></li>\n</ul>\n<p>… so each test case gets instantiated a <em>dozen</em> times, even though each instantiation is basically a completely identical test. This is really just getting carried away. You can’t possibly test <em>EVERY</em> type your algorithms are going to get instantiated with; even <em>TRYING</em> to do that is just quixotic. What you want to do is consider the <em>MINIMAL</em> set of types you really need to test the algorithm with, based on which types are likely to trigger different behaviour. Put another way, consider the following two usages of the algorithm:</p>\n<pre><code>// with int:\nauto v1 = vector<vector<int>>{\n { 1, 2, 3 },\n { 4, 5 },\n};\n\nauto r1 = recursive_transform(execution::par, v1, [](int v) { return v * 2; });\n\n// with double:\nauto v2 = vector<vector<double>>{\n { 1, 2, 3 },\n { 4, 5 },\n};\n\nauto r2 = recursive_transform(execution::par, v2, [](double v) { return v * 2; });\n</code></pre>\n<p>… is there <em>ANY</em> plausible reason to suspect that the function call in the two cases will behave differently (other than one returning a nested <code>int</code> vector while the other returns a nested <code>double</code> vector… and if you’re concerned about testing the return type, you should do just that; it can be done at compile time with no need to actually run the function)? I can’t see any. If there ever comes a time where you suspect that there <em>is</em> a difference, well, then you can add a test case to consider that. But with no reason to suspect that there will be any practical difference between <code>int</code> and <code>double</code> (or <code>long</code> or <code>short</code> or <code>unsigned</code> or…), don’t waste everyone’s time with pointless tests. They just become a maintenance burden.</p>\n<p>So let’s just throw all that template junk out and write some straightforward test cases.</p>\n<p>Let’s start with the simplest case: not only non-recursive, but not even the range version at all:</p>\n<pre><code>// recursive_transform.test.cpp\n\n#define BOOST_TEST_MODULE tests_for_recursive_transform\n#ifdef BOOST_TEST_DYN_LINK\n# include <boost/test/unit_test.hpp>\n#else\n# include <boost/test/included/unit_test.hpp>\n#endif // BOOST_TEST_DYN_LINK\n\n#include <recursive_transform.hpp>\n\nBOOST_AUTO_TEST_CASE(simple_int)\n{\n auto const input = 42;\n\n auto const result = recursive_transform(std::execution::par, input, [](auto&& v) { return v + 27; });\n\n BOOST_TEST(result == 69);\n}\n</code></pre>\n<p>Compile and run, and…:</p>\n<pre class=\"lang-shell prettyprint-override\"><code>$ g++ --std=c++20 --pedantic -Wall -Wextra -DBOOST_TEST_DYN_LINK -c recursive_transform.cpp\n$ g++ --std=c++20 --pedantic -Wall -Wextra -DBOOST_TEST_DYN_LINK -c recursive_transform.test.cpp\nIn file included from recursive_transform.test.cpp:8:\n./recursive_transform.hpp: In instantiation of ‘constexpr auto recursive_transform(ExPo, const T&, const F&) [with ExPo = __pstl::execution::v1::parallel_policy; T = int; F = simple_int::test_method()::<lambda(auto:24&&)>]’:\nrecursive_transform.test.cpp:18:104: required from here\n./recursive_transform.hpp:92:41: warning: unused parameter ‘execution_policy’ [-Wunused-parameter]\n 92 | constexpr auto recursive_transform(ExPo execution_policy, const T& input, const F& f)\n | ~~~~~^~~~~~~~~~~~~~~~\n$ g++ --std=c++20 --pedantic -Wall -Wextra recursive_transform.o recursive_transform.test.o -lboost_unit_test_framework\n$ ./a.out\nRunning 1 test case...\n\n*** No errors detected\n</code></pre>\n<p>… and you can see now why turning all the warnings on is important. The test compiled and passed, but there’s a warning because the execution policy isn’t used in the non-range variant. An easy fix.</p>\n<h1>Discovering, diagnosing, and dealing with a critical defect</h1>\n<p>Okay, now let’s add a test case for a non-recursive range:</p>\n<pre><code>BOOST_AUTO_TEST_CASE(empty_1d_int_vector)\n{\n auto const input = std::vector<int>{};\n\n auto const result = recursive_transform(std::execution::par, input, [](auto&&) { return -1; });\n\n BOOST_TEST(result.empty());\n}\n</code></pre>\n<p>Compile and and…:</p>\n<pre class=\"lang-shell prettyprint-override\"><code>$ g++ --std=c++20 --pedantic -Wall -Wextra -DBOOST_TEST_DYN_LINK -c recursive_transform.cpp\n$ g++ --std=c++20 --pedantic -Wall -Wextra -DBOOST_TEST_DYN_LINK -c recursive_transform.test.cpp\nIn file included from /opt/boost_1_75_0/include/boost/test/test_tools.hpp:52,\n from /opt/boost_1_75_0/include/boost/test/unit_test.hpp:18,\n from recursive_transform.test.cpp:3:\nrecursive_transform.test.cpp: In member function ‘void empty_1d_int_vector::test_method()’:\nrecursive_transform.test.cpp:28:23: error: request for member ‘empty’ in ‘result’, which is of non-class type ‘const int’\n 28 | BOOST_TEST(result.empty());\n | ^~~~~\n/opt/boost_1_75_0/include/boost/test/tools/interface.hpp:41:47: note: in definition of macro ‘BOOST_TEST_BUILD_ASSERTION’\n 41 | (::boost::test_tools::assertion::seed()->*P) \\\n | ^\n/opt/boost_1_75_0/include/boost/test/tools/interface.hpp:134:5: note: in expansion of macro ‘BOOST_TEST_TOOL_ET_IMPL’\n 134 | BOOST_TEST_TOOL_ET_IMPL( P, level ) \\\n | ^~~~~~~~~~~~~~~~~~~~~~~\n/opt/boost_1_75_0/include/boost/test/detail/pp_variadic.hpp:27:51: note: in expansion of macro ‘BOOST_TEST_TOOL_UNIV’\n 27 | # define BOOST_TEST_INVOKE_VARIADIC( tool, ... ) tool (__VA_ARGS__)\n | ^~~~\n/opt/boost_1_75_0/include/boost/test/detail/pp_variadic.hpp:35:5: note: in expansion of macro ‘BOOST_TEST_INVOKE_VARIADIC’\n 35 | BOOST_TEST_INVOKE_VARIADIC( \\\n | ^~~~~~~~~~~~~~~~~~~~~~~~~~\n/opt/boost_1_75_0/include/boost/test/tools/interface.hpp:155:45: note: in expansion of macro ‘BOOST_TEST_INVOKE_IF_N_ARGS’\n 155 | #define BOOST_TEST( ... ) BOOST_TEST_INVOKE_IF_N_ARGS( \\\n | ^~~~~~~~~~~~~~~~~~~~~~~~~~~\nrecursive_transform.test.cpp:28:5: note: in expansion of macro ‘BOOST_TEST’\n 28 | BOOST_TEST(result.empty());\n | ^~~~~~~~~~\n$ \n</code></pre>\n<p>What? The return type of <code>recursive_transform(std::execution::par, std::vector<int>{}, [](auto&&) { return -1; })</code> is <code>int</code>? But… how?</p>\n<p>Well, this review is not about the algorithm itself (I think I mentioned in a previous review that trying to deduce the returned container type is a broken, hopeless endeavour), so I’ll just spill the beans. The issue here is the interaction between the lambda <code>[](auto&&) { return -1; }</code> and the <code>requires</code> clause. Specifically, the <code>!std::invocable<Function, Container<Ts...>></code> check. That lambda <em>IS</em> invocable with a <code>std::vector<int></code>… it’s invocable with literally <em>ANYTHING</em>. And no matter what you give it, it will return a… you guessed it… <code>int</code>. Specifically <code>-1</code>.</p>\n<p>You’ll get a similar error if you actually tried to do anything useful in the lambda, like <code>[](auto&& element) { return element * 2; }</code> (that will give you “can’t multiply <code>std::vector<int></code> by 2!”).</p>\n<p>One way to “fix” this problem by rewriting the lambda to explicitly take an <code>int</code>: <code>[](int) { return -1; }</code>. But that’s only a bandage. The problem is still there.</p>\n<p>Which leads to the million-dollar question: Why didn’t you detect this problem in your existing tests?</p>\n<p>Let’s take a look at your existing tests. Let’s pick out the analogous test:</p>\n<pre><code>BOOST_AUTO_TEST_CASE_TEMPLATE(vector_lambda_with_auto_1dimension, TestType, test_types)\n{\n constexpr size_t dim_num = 1;\n auto test_object = n_dim_vector_generator<dim_num, TestType>(static_cast<TestType>(2), 3);\n auto test_result = recursive_transform(std::execution::par, test_object, [](auto& element) { return element * 2; });\n\n auto expected_result = n_dim_vector_generator<dim_num, TestType>(static_cast<TestType>(2) * 2, 3);\n \n // Content comparison\n if (test_result == expected_result)\n {\n BOOST_TEST(true);\n }\n else\n {\n BOOST_TEST(false);\n }\n}\n</code></pre>\n<p>And now take a look at the two lambdas side-by-side:</p>\n<pre><code>[](auto&& element) { return element * 2; } // doesn't work\n[](auto& element) { return element * 2; } // works\n</code></pre>\n<p>See the difference?</p>\n<p>As for what’s going on here… that’s complicated. It stems from this constraint: <code>!std::invocable<Function, Container<Ts...>></code>.</p>\n<p>For simplicity, let’s ignore the negation, and just say <code>std::invocable<Function, Container<Ts...>></code> must be <code>false</code>. But if <code>Function</code> takes <code>auto&&</code>, then <code>std::invocable<Function, Container<Ts...>></code> will <em>NEVER</em> be <code>false</code>. The <code>auto</code> allows it to take any type, and the <code>&&</code> allows it to take it in any configuration: lvalue, rvalue, <code>const</code> lvalue, etc.. So if you use a lambda with <code>auto&&</code>, the constraint will <em>ALWAYS</em> fail.</p>\n<p>But it works with <code>auto&</code>! … sort of. It doesn’t <em>actually</em> work; it only appears to. Why? Because if the lambda takes an <code>auto&</code> it will work with any type (because of <code>auto</code>)… but <em>not every configuration</em>. <code>auto&</code> will bind to lvalues… but not to rvalues. Which means, that if <code>F</code> refers to a lambda that takes an <code>auto&</code>:</p>\n<div class=\"s-table-container\">\n<table class=\"s-table\">\n<thead>\n<tr>\n<th>Check</th>\n<th>Result</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td><code>invocable<F, T></code></td>\n<td><code>false</code></td>\n</tr>\n<tr>\n<td><code>invocable<F, T&></code></td>\n<td><code>true</code></td>\n</tr>\n<tr>\n<td><code>invocable<F, T const&></code></td>\n<td><code>true</code></td>\n</tr>\n<tr>\n<td><code>invocable<F, T&&></code></td>\n<td><code>false</code></td>\n</tr>\n</tbody>\n</table>\n</div>\n<p>And now note that the first line in that table is the way the constraint is written in the <code>requires</code> clause: <code>std::invocable<Function, Container<Ts...>></code></p>\n<p>Which means that:</p>\n<ul>\n<li>If the lambda takes <code>auto&&</code>, then <code>std::invocable<Function, Container<Ts...>></code> will <em>NEVER</em> be <code>false</code>.</li>\n<li>If the lambda takes <code>auto&</code>, then <code>std::invocable<Function, Container<Ts...>></code> will <em>ALWAYS</em> be <code>false</code>.</li>\n</ul>\n<p>Which means that all the checking you <em>think</em> is happening… isn’t.</p>\n<ul>\n<li><code>[](auto&&) { /* ... */ }</code> doesn’t work because the <code>invocable</code> check <em>ALWAYS</em> passes, which when negated, always fails.</li>\n<li><code>[](auto&) { /* ... */ }</code> “works” because the <code>invocable</code> check <em>ALWAYS</em> fails, which when negated, always passes.</li>\n</ul>\n<p>In other words, your deduction scheme just doesn’t work with generic lambdas. You need to always give the actual type.</p>\n<p>That means all of your existing tests are broken. They are passing, but only by fluke because of the way you happened to write the lambdas. If you didn’t use <code>auto&</code>—if you used literally <em>anything else</em>, like <code>auto const&</code> or <code>auto&&</code> or even just <code>auto</code>—then they would break.</p>\n<p>Oof, terrible news, right?</p>\n<p>So this is what the test code we have so far should look like:</p>\n<pre><code>#define BOOST_TEST_MODULE tests_for_recursive_transform\n#ifdef BOOST_TEST_DYN_LINK\n# include <boost/test/unit_test.hpp>\n#else\n# include <boost/test/included/unit_test.hpp>\n#endif // BOOST_TEST_DYN_LINK\n\n#include <recursive_transform.hpp>\n\n#include <vector>\n\nBOOST_AUTO_TEST_CASE(simple_int)\n{\n auto const input = 42;\n\n auto const result = recursive_transform(std::execution::par, input, [](int v) { return v + 27; });\n\n BOOST_TEST(result == 69);\n}\n\nBOOST_AUTO_TEST_CASE(empty_1d_int_vector)\n{\n auto const input = std::vector<int>{};\n\n auto const result = recursive_transform(std::execution::par, input, [](int) { return -1; });\n\n BOOST_TEST(result.empty());\n}\n</code></pre>\n<h1>Testing types</h1>\n<p>Okay, but we skipped a very important issue. Your tests are broken (as were mine, before that last code block)… but they passed. What could we have done to detect this problem?</p>\n<p>Well, one option would be to test that the return types are what you expected. Normally you don’t bother to test the return types of functions because, normally, they’re tautologically obvious, and there’s no point in testing things that are functionally impossible to be wrong. For example, the return type of <code>std::copy(InputIterator, InputIterator, OutputIterator) -> OutputIterator</code> is going to be <code>OutputIterator</code>. The function is literally declared that way; it can’t be wrong.</p>\n<p>But <code>recursive_transform()</code> is doing some complicated gymnastics to determine the return type. “Complicated” = “potential to fail”, thus this is something you should test.</p>\n<p>But how?</p>\n<p>Let’s build it up step-by-step. First we fake a <code>recursive_transform()</code> call using <code>declval()</code>. We’ll just use an <code>int</code> as the type, and give it a function that will transform it into a <code>double</code>:</p>\n<pre><code>recursive_transform(\n std::execution::par,\n std::declval<int>(),\n std::declval<double (*)(int)>()\n)\n</code></pre>\n<p>Then we get the return type of that call:</p>\n<pre><code>decltype(\n recursive_transform(\n std::execution::par,\n std::declval<int>(),\n std::declval<double (*)(int)>()\n )\n)\n</code></pre>\n<p>… which should be <code>double</code>:</p>\n<pre><code>std::is_same_v<\n decltype(\n recursive_transform(\n std::execution::par,\n std::declval<int>(),\n std::declval<double (*)(int)>()\n )\n ),\n double\n>\n</code></pre>\n<p>Now let’s pull out the concrete types, and use placeholders instead:</p>\n<pre><code>using Container = int;\nusing Function = double (*)(int);\nusing Result = double;\n\nstd::is_same_v<\n decltype(\n recursive_transform(\n std::execution::par,\n std::declval<Container>(),\n std::declval<Function>()\n )\n ),\n Result\n>\n</code></pre>\n<p>Already we can use this to make a test:</p>\n<pre><code>BOOST_AUTO_TEST_CASE(return_type)\n{\n using Container = int;\n using Function = double (*)(int);\n using Result = double;\n\n BOOST_TEST((\n std::is_same_v<\n decltype(\n recursive_transform(\n std::execution::par,\n std::declval<Container>(),\n std::declval<Function>()\n )\n ),\n Result\n >\n ));\n}\n</code></pre>\n<p>But let’s do better by taking advantage of templated test cases, and tuples:</p>\n<pre><code>using return_type_test_types = std::tuple<\n // Container, Func, Result\n std::tuple<int, double (*)(int), double>\n>;\n\nBOOST_AUTO_TEST_CASE_TEMPLATE(return_type, Types, return_type_test_types)\n{\n using Container = std::tuple_element_t<0, Types>;\n using Function = std::tuple_element_t<1, Types>;\n using Result = std::tuple_element_t<2, Types>;\n\n BOOST_TEST((\n std::is_same_v<\n decltype(\n recursive_transform(\n std::execution::par,\n std::declval<Container>(),\n std::declval<Function>()\n )\n ),\n Result\n >\n ));\n}\n</code></pre>\n<p>Now it’s trivial to add more tests for different variations on the types:</p>\n<pre><code>using return_type_test_types = std::tuple<\n // Container Function Result\n std::tuple<int, double (*)(int), double>, // Basic non-range variant\n std::tuple<int, double (*)(int const&), double>, // Func works with const&\n std::tuple<int const, double (*)(int const&), double>, // Can be called with a const value...\n std::tuple<int&, double (*)(int const&), double>, // ... or lvalue ...\n std::tuple<int const&, double (*)(int const&), double>, // ... or const lvalue ...\n std::tuple<int&&, double (*)(int const&), double> // ... or rvalue\n>;\n</code></pre>\n<p>You don’t need to use just <code>int</code>s and <code>double</code>s. In fact you could replace any of those with basically any other type. It might even be smart to mix it up, and throw in some <code>char</code>, some custom types, or whatever.</p>\n<p>And with pretty much no extra work, you can also test the range variants as well:</p>\n<pre><code> // Non-recursive array.\n std::tuple<std::array<double, 5>, int (*)(double), std::array<int, 5>>,\n // Non-recursive vector.\n std::tuple<std::vector<char>, unsigned (*)(char), std::vector<unsigned>>,\n</code></pre>\n<p>And even the <em>recursive</em> range variants:</p>\n<pre><code> // Recursive array.\n std::tuple<std::array<std::array<int, 3>, 4>, char (*)(int), std::array<std::array<char, 3>, 4>>,\n //std::tuple<std::array<std::vector<int>, 4>, char (*)(int), std::array<std::vector<char>, 4>>, //???\n std::tuple<std::vector<std::array<int, 3>>, char (*)(int), std::vector<std::array<char, 3>>>,\n // Recursive vector.\n std::tuple<std::vector<std::vector<int>>, char (*)(int), std::vector<std::vector<char>>>,\n std::tuple<std::vector<std::vector<std::vector<int>>>, char (*)(int), std::vector<std::vector<std::vector<char>>>>,\n</code></pre>\n<p>And so on….</p>\n<p>(Note that the line marked <code>???</code> doesn’t compile. I can’t be bothered to figure out why, because I’m reviewing the test code, not the algorithm.)</p>\n<p>So:</p>\n<pre><code>using return_type_test_types = std::tuple<\n // Container Function Result\n // Non-range.\n std::tuple<int, double (*)(int), double>, // Basic non-range variant\n std::tuple<int, double (*)(int const&), double>, // Func works with const&\n std::tuple<int const, double (*)(int const&), double>, // Can be called with a const value...\n std::tuple<int&, double (*)(int const&), double>, // ... or lvalue ...\n std::tuple<int const&, double (*)(int const&), double>, // ... or const lvalue ...\n std::tuple<int&&, double (*)(int const&), double>, // ... or rvalue\n // Non-recursive array.\n std::tuple<std::array<double, 5>, int (*)(double), std::array<int, 5>>,\n // Non-recursive vector.\n std::tuple<std::vector<char>, unsigned (*)(char), std::vector<unsigned>>,\n // Recursive array.\n std::tuple<std::array<std::array<int, 3>, 4>, char (*)(int), std::array<std::array<char, 3>, 4>>,\n //std::tuple<std::array<std::vector<int>, 4>, char (*)(int), std::array<std::vector<char>, 4>>, //???\n std::tuple<std::vector<std::array<int, 3>>, char (*)(int), std::vector<std::array<char, 3>>>,\n // Recursive vector.\n std::tuple<std::vector<std::vector<int>>, char (*)(int), std::vector<std::vector<char>>>,\n std::tuple<std::vector<std::vector<std::vector<int>>>, char (*)(int), std::vector<std::vector<std::vector<char>>>>\n>;\n\nBOOST_AUTO_TEST_CASE_TEMPLATE(return_type, Types, return_type_test_types)\n{\n using Container = std::tuple_element_t<0, Types>;\n using Function = std::tuple_element_t<1, Types>;\n using Result = std::tuple_element_t<2, Types>;\n\n BOOST_TEST((\n std::is_same_v<\n decltype(\n recursive_transform(\n std::execution::par,\n std::declval<Container>(),\n std::declval<Function>()\n )\n ),\n Result\n >\n ));\n}\n</code></pre>\n<p>You can also add tests with <code>std::list</code>, and maybe <code>std::forward_list</code>, and so on.</p>\n<p>Another variant of this technique is to add not only the expected result type, but the actual result type, to the test type tuple, like so:</p>\n<pre><code>template <typename Container, typename Function, typename Expected>\nusing return_type_test_type = std::tuple<\n Container,\n Function,\n Expected,\n decltype(recursive_transform(std::execution::par, std::declval<Container>(), std::declval<Function>()))\n>;\n\nusing return_type_test_types = std::tuple<\n // Container Function Result\n // Non-range.\n return_type_test_type<int, double (*)(int), double>,\n return_type_test_type<int, double (*)(int const&), double>,\n // ... and so on...\n>;\n\nBOOST_AUTO_TEST_CASE_TEMPLATE(return_type, Types, return_type_test_types)\n{\n //using Container = std::tuple_element_t<0, Types>;\n //using Function = std::tuple_element_t<1, Types>;\n using Expected = std::tuple_element_t<2, Types>;\n using Result = std::tuple_element_t<3, Types>;\n\n BOOST_TEST((std::is_same_v<Expected, Result>));\n}\n</code></pre>\n<p>The benefit of this is that you not only get the test failure message, you also get both the expected and actual result types named in the error message.</p>\n<p>So generic lambdas don’t work with the current design, but assuming they did, how would you test them? Well, one way is to simply write a test case for them:</p>\n<pre><code>BOOST_AUTO_TEST_CASE(generic_lambdas)\n{\n BOOST_TEST((std::is_same_v<\n decltype(recursive_transform(std::execution::par, int{}, [](auto&&) { return 0.0; })),\n double\n >));\n\n // ... and so on with different lamdba and container types\n}\n</code></pre>\n<p>Another way is to note that:</p>\n<pre><code>[](auto&& x) { return x + 1; }\n</code></pre>\n<p>is simply:</p>\n<pre><code>struct unnameable\n{\n template <typename T>\n auto operator()(T&& x) { return x + 1; }\n};\n</code></pre>\n<p>So all you need to do is create some testing function objects:</p>\n<pre><code>struct generic_function_object_byval\n{\n\n template <typename T>\n auto operator()(T) { return 0.0; }\n}\n\nstruct generic_function_object_bylref\n{\n\n template <typename T>\n auto operator()(T&) { return 0.0; }\n}\n\nstruct generic_function_object_byclref\n{\n\n template <typename T>\n auto operator()(T const&) { return 0.0; }\n}\n\nstruct generic_function_object_byrref\n{\n\n template <typename T>\n auto operator()(T&&) { return 0.0; }\n}\n</code></pre>\n<p>Then you can simply add new tuples to the <code>return_type_test_types</code>:</p>\n<pre><code>using return_type_test_types = std::tuple<\n // ...\n return_type_test_type<int, generic_function_object_byval, double>,\n return_type_test_type<int, generic_function_object_bylref, double>,\n return_type_test_type<std::vector<int>, generic_function_object_byval, std::vector<double>>,\n // ... and so on...\n>;\n</code></pre>\n<h1>Comparing containers</h1>\n<p>After all that we finally get to the actual question, about comparing whether two ranges are equal. As I mentioned at the start, Boost.Test has easily a half-dozen or more ways to handle this nicely.</p>\n<p>Perhaps the easiest is to use the per-element modifier with <code>BOOST_TEST()</code>. For example:</p>\n<pre><code>BOOST_AUTO_TEST_CASE(simple_1d_int_vector)\n{\n auto const input = std::vector<int>{1, 2, 3, 4};\n auto const expected = std::vector<int>{5, 6, 7, 8};\n\n auto const result = recursive_transform(std::execution::par, input, [](int i) { return i + 4; });\n\n BOOST_TEST(result == expected, boost::test_tools::per_element());\n}\n</code></pre>\n<p>Compile and run the tests…:</p>\n<pre class=\"lang-shell prettyprint-override\"><code>$ g++ --std=c++20 --pedantic -Wall -Wextra -DBOOST_TEST_DYN_LINK -c recursive_transform.cpp\n$ g++ --std=c++20 --pedantic -Wall -Wextra -DBOOST_TEST_DYN_LINK -c recursive_transform.test.cpp\n$ g++ --std=c++20 --pedantic -Wall -Wextra recursive_transform.o recursive_transform.test.o -lboost_unit_test_framework\n$ ./a.out\nRunning 15 test cases...\nrecursive_transform.test.cpp(80): error: in "simple_1d_int_vector": check result == expected has failed\nCollections size mismatch: 8 != 4\n\n*** 1 failure is detected in the test module "tests_for_recursive_transform"\n$ \n</code></pre>\n<p>… and, oh, look, we’ve already found a bug.</p>\n<p>What’s causing this? Well, in the generic range-based <code>recursive_transform()</code> with an execution policy, you create the output container like this:</p>\n<pre><code>Container<TransformedValueType> output(input.size());\n</code></pre>\n<p>… which creates a <code>vector<int></code> initialized with 4 <code>int</code>s. And then you add more <code>int</code>s to the end of that vector with <code>emplace_back()</code> in the loop:</p>\n<pre><code>output.emplace_back(std::move(result));\n</code></pre>\n<p>Thus you end up with a vector twice the size of the input vector, with the last half being the actual output you want.</p>\n<p>Anywho, moving on. Another option to test containers is to use <code>BOOST_CHECK_EQUAL_COLLECTIONS()</code> (or <code>BOOST_WARN_EQUAL_COLLECTIONS()</code> or <code>BOOST_REQUIRE_EQUAL_COLLECTIONS()</code>, if necessary):</p>\n<pre><code>BOOST_AUTO_TEST_CASE(simple_1d_int_vector)\n{\n auto const input = std::vector<int>{1, 2, 3, 4};\n auto const expected = std::vector<int>{5, 6, 7, 8};\n\n auto const result = recursive_transform(std::execution::par, input, [](int i) { return i + 4; });\n\n BOOST_CHECK_EQUAL_COLLECTIONS(result.begin(), result.end(), expected.begin(), expected.end());\n}\n</code></pre>\n<p>This does basically the same thing as the per-element modifier, except it gives you more control (you can compare sub-ranges), and more information:</p>\n<pre class=\"lang-shell prettyprint-override\"><code>$ g++ --std=c++20 --pedantic -Wall -Wextra -DBOOST_TEST_DYN_LINK -c recursive_transform.cpp\n$ g++ --std=c++20 --pedantic -Wall -Wextra -DBOOST_TEST_DYN_LINK -c recursive_transform.test.cpp\n$ g++ --std=c++20 --pedantic -Wall -Wextra recursive_transform.o recursive_transform.test.o -lboost_unit_test_framework\n$ ./a.out\nRunning 15 test cases...\nrecursive_transform.test.cpp(80): error: in "simple_1d_int_vector": check { result.begin(), result.end() } == { expected.begin(), expected.end() } has failed. \nMismatch at position 0: 0 != 1\nMismatch at position 1: 0 != 2\nMismatch at position 2: 0 != 3\nMismatch at position 3: 0 != 4\nCollections size mismatch: 8 != 4\n\n*** 1 failure is detected in the test module "tests_for_recursive_transform"\n$ \n</code></pre>\n<p>Okay, but you have a unique situation in which you want to test containers <em>recursively</em>. Unsurprisingly, Boost.Test doesn’t come with that functionality built it. So you’re going to have to roll your own.</p>\n<p><em>NORMALLY</em> you should avoid writing any <code>if</code> tests or loops in a test. Anything other than a straight, one-way through path is just asking for trouble; the more complexity you add to your tests, the more likely they are to break, and you <em>really</em> don’t want to get into a situation where you have to test your test code.</p>\n<p><em>BUT</em> this is a special case, because you’re specifically testing recursive algorithms… so you kinda need to do some recursion to test the data structures. I say again, this is <em>NOT</em> something you should consider “normal” for writing tests… but you’re probably going to need to write some nested loops to do proper testing:</p>\n<pre><code>BOOST_AUTO_TEST_CASE(simple_3d_int_vector)\n{\n auto const input = std::vector<std::vector<std::vector<int>>>{\n {\n {1, 1, 2},\n {3, 5, 8}\n },\n {\n {10, 9, 8, 7, 6, 5, 4, 3, 2, 1}\n },\n {\n {0, -1},\n {1, -1},\n {420}\n }\n };\n\n auto const expected = std::vector<std::vector<std::vector<int>>>{\n {\n {2, 2, 4},\n {6, 10, 16}\n },\n {\n {20, 18, 16, 14, 12, 10, 8, 6, 4, 2}\n },\n {\n {0, -2},\n {2, -2},\n {840}\n }\n };\n\n auto const result = recursive_transform(std::execution::par, input, [](int i) { return i + 4; });\n\n auto index_1 = std::size_t{0};\n auto index_2 = std::size_t{0};\n\n auto result_next_1 = result.begin();\n auto result_last_1 = result.end();\n auto expected_next_1 = expected.begin();\n auto expected_last_1 = expected.end();\n\n while (result_next_1 != result_last_1 and expected_next_1 != expected_last_1)\n {\n BOOST_TEST_INFO_SCOPE("element[" << index_1 << "]");\n\n auto result_next_2 = result_next_1->begin();\n auto result_last_2 = result_next_1->end();\n auto expected_next_2 = expected_next_1->begin();\n auto expected_last_2 = expected_next_1->end();\n\n BOOST_TEST((result_next_2 != result_last_2));\n BOOST_TEST((expected_next_2 != expected_last_2));\n\n while (result_next_2 != result_last_2 and expected_next_2 != expected_last_2)\n {\n BOOST_TEST_INFO_SCOPE("element[" << index_1 << "][" << index_2 << "]");\n\n BOOST_CHECK_EQUAL_COLLECTIONS(result_next_2->begin(), result_next_2->end(), expected_next_2->begin(), expected_next_2->end());\n\n ++result_next_2;\n ++expected_next_2;\n ++index_2;\n }\n\n if (result_next_2 != result_last_2 or expected_next_2 != expected_last_2)\n {\n auto size_1 = index_2;\n auto size_2 = index_2;\n if (result_next_2 != result_last_2)\n size_1 += std::distance(result_next_2, result_last_2);\n else\n size_2 += std::distance(expected_next_2, expected_last_2);\n\n BOOST_ERROR("size mismatch: " << size_1 << " != " << size_2);\n }\n\n ++result_next_1;\n ++expected_next_1;\n ++index_1;\n }\n\n if (result_next_1 != result_last_1 or expected_next_1 != expected_last_1)\n {\n auto size_1 = index_1;\n auto size_2 = index_1;\n if (result_next_1 != result_last_1)\n size_1 += std::distance(result_next_1, result_last_1);\n else\n size_2 += std::distance(expected_next_1, expected_last_1);\n\n BOOST_ERROR("size mismatch: " << size_1 << " != " << size_2);\n }\n}\n</code></pre>\n<p>(This test will fail, of course, because <code>recursive_transform()</code> is currently broken.)</p>\n<p>This is <em>NOT</em> what a normal test case should look like. But this kind of complexity is unavoidable for testing nested structures recursively. It <em>MIGHT</em> be worthwhile to create a <code>RECURSIVE_CHECK_EQUAL_COLLECTIONS(first1, last1, first2, last2, n)</code> test tool that works like <code>BOOST_CHECK_EQUAL_COLLECTIONS(first1, last1, first2, last2)</code>, except recursively down to <code>n</code> levels, or maybe spelled <code>recursive_check_equal_collections<size_t n>(first1, last1, first2, last2)</code> where it’s just <code>BOOST_CHECK_EQUAL_COLLECTIONS()</code> when <code>n</code> is <code>1</code>. (Do be careful about handling input iterators carefully when doing any of this. In the code above I could just get the sizes of the two containers with <code>.size()</code> or even <code>distance(begin, end)</code>… but neither of those strategies would work for an input range, so I did it a different way.)</p>\n<p>You should generally not need to add too much extra junk to your testing code like that… but again, you’re dealing with recursive structures, so some amount of additional test code complexity is unavoidable. Just don’t go too far.</p>\n<p>Now, what you’ve done—defining <code>operator==</code> for <em>ANY</em> input range—is not a great idea. One thing you should carefully avoid when testing is changing the interface of the stuff being tested. You don’t want different behaviour when testing than when not testing; that would be bad. Adding equality comparisons between types that don’t have it is changing their public interface. That’s a no-no.</p>\n<p>If you want to compare objects that don’t have <code>operator==</code>, then you can use <a href=\"https://www.boost.org/doc/libs/release/libs/test/doc/html/boost_test/testing_tools/custom_predicates.html\" rel=\"noreferrer\">a custom predicate</a>.</p>\n<h1>Summary</h1>\n<p>I think that should be a deep enough review of your testing code. There are couple key issues I think need looking at.</p>\n<ol>\n<li><p>The testing code is <em>FAR</em> too slow (both to compile and run). And worse, it’s completely unnecessarily slow. Slow testing code means:</p>\n<ol>\n<li>the tests won’t be run as often, which defeats the purpose; and</li>\n<li>the tests may fail to run in constrained environments… which, unfortunately, often includes CI servers.</li>\n</ol>\n</li>\n<li><p>Related to the previous point, the vast majority of the tests are completely pointless. If the algorithm works for <code>vector<int></code>, there’s no reason to assume it won’t work for <code>vector<unsigned int></code> or <code>vector<short></code>. Sure you could imagine contrived scenarios where the person writing the algorithm is being deliberately silly or malicious, and might create problems like this, but that’s not really the mindset you should approach testing with. You’re looking for mistakes, not monsters. You’re looking for Murphy, not Machiavelli. You can test pretty much every conceivable form of your algorithm by checking 0- to 3-dimensional input ranges… there’s no need to check all the way up to <em>15-dimensional</em> ranges. If a 3D range works, a 15D or 150D range will work as well. (And if you have a reason to think it won’t <em>THEN</em> you write those tests.)</p>\n<p>And not only the are tests unnecessary by being redundant, they don’t actually test everything you should really be testing. I wrote 4 tests (well, 3 + 1 templated test that has a dozen or so instantiations), in a total of less than 100 lines, and I found bugs and errors missed by those ~200 tests that delve into 15-dimensional ranges. Having more tests isn’t a good thing if those tests are superfluous, and it might even be a bad thing because it slows compilation and running.</p>\n</li>\n<li><p>Test code should be as simple as possible. Ideally there should be no control flow at all: no loops, no <code>if</code>s, no function calls, no nothing. Just:</p>\n<ol>\n<li>set up</li>\n<li>do thing being tested; then</li>\n<li>check results.</li>\n</ol>\n<p>That’s 1, 2, 3, in order, no breaks, branches, or cycles. And everything should be right there in the test case, self-contained, easy to process. If you need to stop and think about what a test is doing, then you’ve failed somehow.</p>\n<p><em>IF</em> your test <em>NEEDS</em> to be more complex—which is <em>almost</em> never true, but sorta-kinda is in your case because you’re interested in recursive data structures—then you should make it <em>MINIMALLY</em> complex. If testing code needs to be tested, then you’ve failed somehow.</p>\n</li>\n</ol>\n<p>I would toss out all of your testing code for everything higher than 3 dimensions; I don’t see a purpose to it. I would also throw out at least 3⁄4 of your type list, if not the whole thing; if it works for <code>int</code>, why wouldn’t it work for <code>short</code>? That alone should speed up your tests by several orders of magnitude, and make them worthwhile to run frequently.</p>\n<p>Because you’re generating the return types in a non-trivial way, you should make some tests that use type traits to check that everything works the way you expect. For example, you could make sure the return type of <code>recursive_transform(execution::par, vector<string>{"abc", "123"}, [](string const& s) { return size_t(s.size()); })</code> returns a <code>vector<size_t></code>. You can use <code>declval<T>()</code> to really control the types explicitly, because <code>declval<string>()</code> and <code>declval<string const&>()</code> are two very different things.</p>\n<p>Rather than just throwing everything you can think of into the tests, you should take the time to carefully consider the <em>SUBSTANTIVELY</em> different use cases of the algorithm, and where the sharp edges might be. Like, you know there’s no reason to think that if the algorithm works for <code>vector<double></code>, that it might not work for <code>vector<int></code>. So don’t bother to test that. But it might work for <code>vector<double></code> but fail for <code>vector<string></code> (with a lambda that takes a string)! So test <em>that</em>! And you don’t need to test for every container in the standard library. You can test <code>vector</code> (because it should always be your default), <code>array</code> (because you have it special-cased), and then, maybe, <code>list</code> (for bidirectional iterators) or <code>forward_list</code> (for forward iterators). (There are no containers in the standard with input iterators, but you can slap one together by using <code>istream_iterators</code> and <code>ranges::subrange</code>. Not that it matters because the algorithm won’t work with ranges with input iterators.)</p>\n<p>I won’t tell you <em>exactly</em> how to test your algorithm—because it’s your algorithm, and all of this is pretty subjective—but here’s what I’d consider testing if I were writing the tests for it:</p>\n<ol>\n<li><p>I’d test non-range inputs. This need be only one or two tests at most, to verify that the output type is correct, and that the transform is done.</p>\n</li>\n<li><p>I’d test 1D ranges—that is, <code>vector<int></code>, <code>forward_list<double></code>, or <code>deque<custom_type></code>. I would check <em>at least</em> <code>std::array</code> with a couple different sizes and value types, <code>std::vector</code> with a couple different value types, and then a range type that isn’t random-access, like <code>std::forward_list</code> (that was my go-to for testing more restricted iterator types in the past, because it is the only standard container with forward iterators). In each case, I’d check the return type, and that the result value is kosher.</p>\n</li>\n<li><p>I’d test 1D ranges with a <code>string</code> or <code>string_view</code> value type, where the transform function handles strings (or string views). Why? Because this is one of the sharp edges of the algorithm, where it could easily get confused between a 1D range of strings and a 2D range of ranges of characters.</p>\n</li>\n<li><p>I’d test 2D ranges, because this is the third option in the algorithm—0D ranges are covered by the first overload, and 1D ranges just degrade to <code>std::transform()</code>; 2D ranges are where the algorithm first becomes recursive. I’d check arrays of arrays, arrays of vector, vectors of arrays (all of the previous to trigger the array special case, and ensure it works), vectors of vectors, and then maybe a more exotic option or two, like a <code>deque<forward_list<int>></code>.</p>\n</li>\n<li><p>I’d test 3D ranges, because this is where the recursion really gets tested. If it can properly handle doing “3D recursive → 2D recursive → 1D non-recursive → 0D value”, then there’s no reason to suspect it can’t keep adding additional levels of recursion to the beginning there.</p>\n</li>\n</ol>\n<p>And that’s it. I probably wouldn’t bother testing 4D or greater, or if I did, it would be as a single case, just for the hell of it.</p>\n<p>As for how I’d organize all this, I’d break it into 0D, 1D, 2D, and 3D tests.</p>\n<p>The 0D tests are simple. I probably wouldn’t even bother to use templates or data-driven tests. I’d just make a couple of simple test cases, and do very basic tests, like the <code>simple_int</code> test I wrote above.</p>\n<p>The 1D tests I’d use templated tests. I’d set up a tuple of tuples with the input range type, and the expected output range type, and maybe the actual output range type. Then I might do:</p>\n<ul>\n<li>1 templated test case that checks that the expected and actual output types are the same</li>\n<li>1 templated test case that creates an empty instance of the input range, runs a dummy transform function, and then check that the output range is empty; and</li>\n<li>1 templated test case that creates an instance of the input range filled with a set of values like “1, 2, 3”, and then runs a simple transform like doubling or squaring, and then check that the output range is as expected.</li>\n</ul>\n<p>I’d also include special tests for arrays and vectors (and maybe a list or forward list) of strings with a string transform function, to make sure that they’re treated like a 1D range of strings and not a 2D range of chars. Both arrays and vectors need to be checked, because arrays are special cased. (You should also check Boost’s multi-array if that’s special-cased as well.)</p>\n<p>The logic for the 2D and 3D tests is basically identical. To actually test that the output range is as expected, you will probably need to write a custom predicate to do the comparison. (Or you can do it inline, as I did above… but that’s not a great idea.) You don’t need to write a predicate that can support arbitrarily recursive structures. You can just write one for 2D structures, and one for 3D structures. (And if you want to test a 4D or greater structure, well, then you can write one for that, too, I suppose. Though if there’s only a single test, it might be better do that one inline.)</p>\n<p>Remember that with testing, more is better, but with test <em>code</em>, less is more.</p>\n<ul>\n<li><p>Test code should be simple, clear, self-contained, idempotent, quick, and with no complicated or hidden logic. If you have to <em>think</em> about what a test is doing, something has gone horribly wrong. (As always, this is a rule of thumb, not a rule. If you <em>need</em> a complicated test… well, then you need it. C’est la vie.)</p>\n</li>\n<li><p>Test anything that might fail. Your tests check that the transform worked, and that’s good, but that’s not the only thing <code>recursive_transform()</code> does. It also deduces the return type, and can construct a rather complicated structure within the return value, and you never test whether any of that works. Those should be their own test case(s). For <code>recursive_transform()</code>, there are basically three things you need to check:</p>\n<ul>\n<li>is the return <em>type</em> correct?</li>\n<li>is the return value’s <em>structure</em> correct (that is, if it’s a 3D vector of vector of vectors, are the sizes of all the vectors and sub-vectors correct)?; and</li>\n<li>is the return <em>value</em> correct (that is, are all the recursively-contained values correct)?</li>\n</ul>\n<p>I’m simplifying because there are other possible things you could check, like whether the transform function is called the correct number of times, and so on; those are esoteric concerns that should be checked separately (and, honestly, I wouldn’t bother in a first pass of writing the code… maybe if the algorithm became <em>heavily</em> used or really important to some core facility). But basically, the three things above are what you want to check, and should <em>ideally</em> all be checked separately. (In practice, I’d just check the latter two at the same time, because meh, why not?)</p>\n</li>\n<li><p>Don’t needlessly repeat tests. If you tested with <code>int</code> and it worked, there’s almost never a reason to test with <code>short</code> or <code>long</code> (for example). Unless you know or suspect there <em>might</em> be different behaviour between two cases, just test one of them. There is something to be said for fuzz testing to really slam your algorithm with every kind of input imaginable, but that should really be done separately, not as part of your standard unit test that you run repeatedly during the development cycle.</p>\n</li>\n<li><p>And finally, turn all warnings on, especially for testing. You’ll find a <em>lot</em> little bullshit with warnings—most of it is harmless, but some of it shines a light on things you missed or didn’t consider.</p>\n</li>\n</ul>\n<p>Note that I’ve focused this review on the testing code, not so much on the algorithm code itself (though some issues in the algorithm code did come up during the testing discussion, of course). I gather there are separate reviews on the algorithm code, so I won’t belabour the points they make.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-26T09:22:13.150",
"Id": "500752",
"Score": "0",
"body": "This is absolute devotion."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-26T11:28:12.507",
"Id": "500755",
"Score": "0",
"body": "Need more people like this on code review @SE !"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-25T22:51:19.517",
"Id": "253916",
"ParentId": "253793",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "253916",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-22T19:30:24.173",
"Id": "253793",
"Score": "3",
"Tags": [
"c++",
"recursion",
"lambda",
"boost",
"c++20"
],
"Title": "Nested std::deque and std::vector Type Test Cases for recursive_transform Template Function in C++"
}
|
253793
|
<p>I need to smooth a noisy signal. I think that the <a href="https://en.wikipedia.org/wiki/Moving_average" rel="nofollow noreferrer">moving average</a> algorithm would be fine. However, I want the following conditions to be satisfied:</p>
<ol>
<li>The total integral (the sum of all values) before and after the moving average filtering is kept unchanged</li>
<li>The number of points before and after the moving average filtering is kept unchanged</li>
</ol>
<h1>Implementation</h1>
<p>The implementation is based on the answer to <a href="https://dsp.stackexchange.com/questions/52337/moving-average-algorithm-that-conserves-integral">this</a> post. The main question here is <em>how to process the edges of a signal</em>. The idea is to "reflect" the signal at the edges:</p>
<p><span class="math-container">$$a_{-i} = a_{i-1},\, i > 0\quad \text{at the beginning of a signal},$$</span>
<span class="math-container">$$a_{L+i} = a_{L-i-1},\, i\geq 0\quad \text{at the end of a signal},$$</span>
where <em>L</em> denotes the length of the signal.</p>
<h2>Note</h2>
<p>To produce more or less appropriate results this algorithm should be used with the signals which start and end with relatively flat waveform (the length of "flatness" depends on the size of the window used).</p>
<h2>Algorithm</h2>
<pre><code>#include <vector>
#include <iostream>
//Input :
// in : the original signal
// w : the size of the window of the moving average
//Output :
// out : the filtered signal
void MovingAverage( const std::vector<float>& in, std::vector<float>& out, int w )
{
//****** PREPARATION ******/
out.clear();
//Make the window size odd
w += (w % 2) ? 0 : 1;
if( (w < 1) or (in.size() < w) )
{
std::cerr << "Bad input!" << std::endl;
return;
}
//****** ALGORITHM ******/
int i = 0; //the current position
//Firstly, average the head
for( ; i < w/2; i++ )
{
float averagedValue = 0.;
for( int j = -w/2; j < (w/2 + 1); j++ )
{
averagedValue += (i + j >= 0) ? in[i + j] :
in[-(i + j) - 1];//(i + j) is negative here
}
out.push_back( averagedValue / w );
}
//The middle is averaged normally
for( ; i + w/2 < in.size(); i++ )
{
float averagedValue = 0.;
for( int j = -w/2; j < (w/2 + 1); j++ )
{
averagedValue += in[i + j];
}
out.push_back( averagedValue / w );
}
//Finally, average the tail
for( ; i < in.size(); i++ )
{
float averagedValue = 0.;
for( int j = -w/2; j < (w/2 + 1); j++ )
{
//(i + j) is not negative here
averagedValue += (i + j < in.size()) ? in[i + j] :
in[in.size() - (i + j - in.size()) - 1];//(i + j - in.size()) is not negative here
}
out.push_back( averagedValue / w );
}
}
</code></pre>
<h1>Test</h1>
<p><a href="https://i.stack.imgur.com/0jixA.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/0jixA.png" alt="enter image description here" /></a></p>
|
[] |
[
{
"body": "<ul>\n<li><p>Where you make the window length odd: <code>w += (w % 2) ? 0 : 1;</code> I would prefer the conditional part to be something like <code>((w % 2) != 0)</code>. Others will no doubt disagree with me, but I personally prefer conditionals to be boolean.</p>\n<p>But even better, you can get rid of the conditional entirely: <code>w |= 0x1;</code>. Maybe this makes some kind of not-guaranteed-to-be-fully-portable assumptions? But I'd be comfortable using it.</p>\n</li>\n<li><p>Using the same index <code>i</code> in the multiple consecutive loops makes me think a little. On the one hand, it's really good how it doesn't duplicate code that calculates where the loops start and end. On the other hand, one doesn't normally expect a loop index, particularly one named <code>i</code>, to be used after the end of a loop. What if some future maintainer doesn't realize this, and inserts some other loop in here that uses <code>i</code> as its index? Possibly you could rename <code>i</code> to something else, but that might make your subsequent calculations harder to follow. In the end, I'd probably at least put a comment by the declaration of <code>i</code> warning that it is re-used through multiple loops.</p>\n</li>\n<li><p>I don't like something that is purely DSP to write to <code>std::cerr</code>. Either return a status value, or throw an exception when you encounter invalid parameters. I think a status return value is preferable, but an exception may be OK if this <em>really</em> is an exceptional case.</p>\n</li>\n<li><p>You use <code>float</code> to hold the intermediate <code>averagedValue</code>. In most cases this is fine, but depending on the nature of your data and your window size, it is possible that you'd benefit from using <code>double</code> for the intermediate variable.</p>\n</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-23T11:24:59.827",
"Id": "500514",
"Score": "0",
"body": "Given that `i` is used as loop index those three times, I'd be inclined to compute \"end-of-head\" and \"start-of-tail\" constants, and then write three normal `for` loops using those constants."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-23T17:31:33.977",
"Id": "500546",
"Score": "0",
"body": "@TobySpeight Excellent idea."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-23T04:36:31.533",
"Id": "253810",
"ParentId": "253794",
"Score": "4"
}
},
{
"body": "<p>Unless the middle, flat, part of the window is very small, consider changing the algorithm to maintain the state of that flat part between calls. The flat part is easily updated, by adding in the next new value and subtracting the oldest value; only the shoulders of the window need updating from scratch. That would reduce that part of the algorithm from <em>O(n✕m)</em>` down to just <em>O(n)</em>.</p>\n<p>I would recommend abstracting out the element access, so we can use a single loop once we've populated the initial sum.</p>\n<p>There's undefined behaviour if <code>w/2</code> is greater than <code>in.size()</code> - we end up accessing outside the valid range of <code>in</code>.</p>\n<p>Consider returning the output vector as a value, rather than passing in a modifiable vector. And be sure to <code>reserve()</code> space for the entries we'll be adding.</p>\n<p>Use an unsigned type as the window width, to avoid having to check for negative values. And perhaps if we're passed <code>0</code> or <code>1</code>, we could just return a copy of the input, unfiltered.</p>\n<p>Try to avoid comparing signed values with unsigned ones - e.g. <code>for( ; i < in.size(); i++ )</code>.</p>\n<hr />\n<p>Here's my version of the same algorithm, addressing the points above, and also those in <a href=\"/253810/75307\">Eric's answer</a>. As there's no unit tests, I haven't verified this; watch out for off-by-one errors!</p>\n<pre><code>#include <iostream>\n#include <numeric>\n#include <type_traits>\n#include <vector>\n\n//Input :\n// in : the original signal\n// w : window size for the moving average\n//Output :\n// return : the filtered signal\nstd::vector<float> moving_average(const std::vector<float>& in, unsigned int w)\n{\n using Index = std::make_signed_t<size_t>;\n\n if (w < 2) {\n // tiny window - no filtering\n return in;\n }\n\n // Make the window size odd\n w |= 1;\n // We use half the window at each end\n auto const h = w/2;\n\n auto const len = static_cast<Index>(in.size());\n if (h >= len) {\n // window too big for data\n throw std::invalid_argument("w");\n }\n\n std::vector<float> out;\n out.reserve(in.size());\n\n auto const get_element\n = [len,w,&in](Index i){return i < 0 ? in[-i] : i < len ? in[i] : in[2*len-1-i]; };\n\n double rolling_sum = in[0] + 2 * std::accumulate(in.begin(), in.begin()+h, 0.0);\n for (Index i = 0; i < len; ++i) {\n out.push_back(static_cast<float>(rolling_sum / w));\n rolling_sum -= get_element(i-h);\n rolling_sum += get_element(i+h);\n }\n\n return out;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-23T13:28:32.603",
"Id": "500524",
"Score": "1",
"body": "Yes, I agree about the updating the \"rolling sum\" in this way. It really reduces the computations. However, the problem (?) here that you're doing all those comparison (in the lambda) every time for each point, while I need to do this only for the head and tail. By the way, why returning a vector by value is a good idea? Isn't the fact it copies then?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-23T13:35:27.090",
"Id": "500527",
"Score": "0",
"body": "Without the test data, I can't tell whether the comparisons have a performance impact. A good compiler may be capable of splitting the loop into the three sections that you did by hand, to eliminate the comparisons - it's worth looking at the generated assembly, with different optimisation settings, to see what it's doing. Returning a vector by value incurs no extra overhead, due to **[copy elision](https://en.cppreference.com/w/cpp/language/copy_elision)**."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-23T12:33:25.537",
"Id": "253822",
"ParentId": "253794",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-22T20:19:10.063",
"Id": "253794",
"Score": "5",
"Tags": [
"c++",
"algorithm",
"array",
"signal-processing"
],
"Title": "Moving average algorithm that preserves the integral and number of points"
}
|
253794
|
<p>I've implemented the 3 variants of the modulo operation described on this <a href="https://en.wikipedia.org/wiki/Modulo_operation#Variants_of_the_definition" rel="nofollow noreferrer">Wikipedia page</a>.<br />
The goal is to have fully defined behavior for all inputs.</p>
<h1>Code</h1>
<h2>Implementation with truncated division (result has the same sign as the dividend)</h2>
<pre class="lang-c prettyprint-override"><code>int32_t rem(int32_t x, int32_t y) {
if (y == 0) exit(-1);
if (y == -1) return 0;
return x % y;
}
</code></pre>
<p>This one is the simplest since it's already how the <code>%</code> operator is implemented in C.<br />
We have to take care of two edge cases though:</p>
<ul>
<li>If <code>y == 0</code> it's an invalid operation; <code>exit(-1)</code>.</li>
<li><code>INT32_MIN % -1</code> is undefined behavior, so I've hard-coded the result for <code>y == -1</code>.</li>
</ul>
<h2>Implementation with floored division (result has the same sign as the divisor)</h2>
<pre class="lang-c prettyprint-override"><code>int32_t mod(int32_t x, int32_t y) {
if (y == 0) exit(-1);
if (y == -1) return 0;
return x - y * (x / y - (x % y && (x ^ y) < 0));
}
</code></pre>
<p>This one is a bit trickier.</p>
<p>We still have to handle the two previous edge cases.
However, the modulo is computed differently: <code>x - y * floor(x / y)</code>.
We can't use <code>floor</code> here because we're working with integers, so the formula looks like this:</p>
<p><code>x - y * (x / y - {1 if x isn't a multiple of y and the result of x / y is negative, 0 else})</code><br />
<code>x - y * (x / y - {1 if x % y and the result of x / y is negative, 0 else})</code><br />
<code>x - y * (x / y - {1 if x % y and (x or y, but not both, is negative), 0 else})</code><br />
<code>x - y * (x / y - {1 if x % y and (x ^ y) < 0, 0 else})</code><br />
<code>x - y * (x / y - (x % y && (x ^ y) < 0))</code></p>
<h2>Implementation with Euclidean division (result is always positive)</h2>
<h3>Portable implementation</h3>
<pre><code>int32_t euc1(int32_t x, int32_t y) {
if (y == 0) exit(-1);
if (y == -1) return 0;
if (y == INT32_MIN) return x >= 0 ? x : INT32_MAX + x + 1;
y = abs(y);
return x - y * (x / y - (x < 0 && x % y));
}
</code></pre>
<p>It's basically the same implementation as the previous one, except that we use the absolute value of <code>y</code>.
Also, <code>(x ^ y) < 0</code> was simplified to <code>x < 0</code> because <code>y</code> is always positive (we use the absolute value).
However <code>abs(INT32_MIN)</code> is undefined behavior (because <code>abs(INT32_MIN) = INT32_MAX + 1</code> which is not representable) so we have to take care of this special case:</p>
<ul>
<li>If <code>x >= 0</code>, we have <code>x % (INT32_MAX + 1) = x</code> because <code>x</code> is always inferior to <code>INT32_MAX + 1</code>.</li>
<li>If <code>x < 0</code>, we have <code>x % (INT32_MAX + 1) = INT32_MAX + 1 + x</code>, then we reorder operations to avoid overflow on signed integers which is undefined behavior: <code>INT32_MAX + x + 1</code> (remember that <code>x</code> is negative).</li>
</ul>
<h3>GCC implementation</h3>
<pre><code>int32_t euc2(int32_t x, int32_t y) {
if (y == 0) exit(-1);
if (y == -1) return 0;
if (y != INT32_MIN) y = abs(y);
int32_t tmp = x / y - (x < 0 && x % y);
__builtin_mul_overflow(y, tmp, &tmp);
__builtin_sub_overflow(x, tmp, &tmp);
return tmp;
}
</code></pre>
<p>This implementation is the same as the portable one, except for the handling of the <code>y = INT32_MIN</code> edge case: there is less conditional logic, making it potentially easier to optimize.</p>
<p>If <code>y == INT32_MIN</code> we don't compute the absolute value because it's undefined behavior, then we continue the execution as nothing happened. A multiplication and a subtraction were replaced by their <a href="https://gcc.gnu.org/onlinedocs/gcc/Integer-Overflow-Builtins.html#Integer-Overflow-Builtins" rel="nofollow noreferrer">built-in functions</a> counterparts to avoid undefined behavior on overflow.
Because of black magic it works:</p>
<ul>
<li>If <code>x >= 0</code> we have <code>x / INT32_MIN - (x < 0 && x % INT32_MIN) = 0</code>, then <code>INT32_MIN * 0 = 0</code>, then <code>x - 0 = x</code>, so the result is <code>x</code> as expected.</li>
<li>If <code>INT32_MIN < x < 0</code> we have <code>x / INT32_MIN - (x < 0 && x % INT32_MIN) = -1</code>, then <code>INT32_MIN * -1 = INT32_MIN</code> (built-in function defined behavior), then <code>x - INT32_MIN = INT32_MAX + x + 1</code> (built-in function defined behavior), so the result is <code>INT32_MAX + x + 1</code> as expected.</li>
<li>If <code>x == INT32_MIN</code> we have <code>INT32_MIN / INT32_MIN - (INT32_MIN < 0 && INT32_MIN % INT32_MIN) = 1</code>, then <code>INT32_MIN * 1 = INT32_MIN</code>, then <code>INT32_MIN - INT32_MIN = 0</code>, so the result is <code>0</code> as expected.</li>
</ul>
<h1>Questions</h1>
<p>Is there an error somewhere, something that i missed? Like a set of inputs that don't give the right result.</p>
<p>If this code really undefined behavior free?</p>
<p>Can it be simplified?</p>
|
[] |
[
{
"body": "<blockquote>\n<p>Is there an error somewhere, something that i missed? Is there an error somewhere, something that i missed?</p>\n</blockquote>\n<p>Certainly have most of main street covered.</p>\n<p><code>if (y == -1) return 0;</code> is a nice trick.</p>\n<p><code>y = abs(y);</code> fails 32-bit math when <code>int</code> is 16-bit. Could use <code>labs()</code> or conditional code or an <code>if()</code> block. (Only real portability bug I see.)</p>\n<p>Pedantic: <code>int32_t</code> is an optional type. It is missing and code fails to compile on select (<a href=\"https://codereview.stackexchange.com/q/215113/29485\">dinosaur</a>) machines that do not have 32-bit unpadded 2's complement.</p>\n<p>Pedantic: On a select (unicorn) machine where <code>int</code> is 64-bit and <code>int32_t</code> exist, promotions occur. I do not <em>see</em> a problem though.</p>\n<p>Pedantic: Usage of <code>x ^ y</code> obliges 2's complement encoding for correct functionality which is the case with <code>intN_t</code> here , but not <em>all</em> integers on <em>all</em> machines.</p>\n<hr />\n<p>Adding a test harness would help.</p>\n<hr />\n<blockquote>\n<p>Can it be simplified?</p>\n</blockquote>\n<p>A shot at simplifying <a href=\"http://en.wikipedia.org/wiki/Euclidean_division\" rel=\"nofollow noreferrer\">Euclidean division</a> (result is always non-negative). Similar code may apply to the other 2 cases.</p>\n<pre><code>// Substitute `int` for `int32_t`, `long long`, etc.\nint modulo_Euclidean(int x, int y) {\n if (y == 0) exit(-1);\n if (y == -1) return 0;\n int m = x % y;\n if (m < 0) {\n m = (y < 0) ? m - y : m + y;\n }\n return m;\n}\n</code></pre>\n<p>Does not require <code>intN_t</code> math<sup>*</sup>, 2's complement, no padding, range constants, nor extended math.</p>\n<hr />\n<p>It would be interesting to see if 64-bit math was really slower or a reasonable candidate.</p>\n<pre><code>int32_t mod_rem_or_euc(int32_t x, int32_t y) {\n if (y == 0) exit(-1);\n int_fast64_t m = (int_fast64_t) x % y;\n ...\n}\n</code></pre>\n<hr />\n<p><sup>*</sup> <code>intN_t</code> types are 2's complement, no padding.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-23T12:31:12.590",
"Id": "500518",
"Score": "1",
"body": "Thanks for this review. I like your Euclidean modulo simplification because it gets rid of the `abs` function that can cause problem when fed with int32_t."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-23T07:20:20.613",
"Id": "253814",
"ParentId": "253799",
"Score": "4"
}
},
{
"body": "<p>The code <em>may</em> be free of undefined behavior, but it relies on <em>implementation-defined behavior</em> because of the <code>exit(-1)</code>. Read its definition in the C standard, not in POSIX or even Linux. Of these, the C standard gives the fewest guarantees.</p>\n<p>Your code is definitely missing a test suite that demonstrates all the edge cases. Without such a test suite, it's not apparent how much thought you invested into this code.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-23T08:19:45.433",
"Id": "253815",
"ParentId": "253799",
"Score": "4"
}
},
{
"body": "<blockquote>\n<p>Is there an error somewhere, ... Like a set of inputs that don't give the right result.</p>\n</blockquote>\n<p>Code lacks basic tests to answer that.</p>\n<p>Sample test harness. (It lacks <code>% 0</code> tests.)</p>\n<p>OP's <code>euc1()</code> tested successfully on a 32-bit <code>int</code> machine.</p>\n<pre><code>#include <assert.h>\n#include <limits.h>\n#include <stdint.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\nint32_t euc1(int32_t x, int32_t y) {\n if (y == 0) exit(-1);\n if (y == -1) return 0;\n if (y == INT32_MIN) return x >= 0 ? x : INT32_MAX + x + 1;\n y = abs(y);\n return x - y * (x / y - (x < 0 && x % y));\n}\n\nint32_t euc1_ref(int32_t x, int32_t y) {\n if (y == 0) return -1;\n int64_t m = (int64_t) x % y;\n if (m < 0) {\n if (y < 0) m -= y;\n else m += y;\n }\n assert(m >= 0);\n assert(m <= INT32_MAX);\n return (int32_t) m;\n}\n\nint test_euc(int32_t x, int32_t y) {\n int32_t m1 = euc1_ref(x, y);\n int32_t m2 = euc1(x, y);\n if (m1 != m2) {\n printf("(%ld, %ld) --> %ld, %ld\\n", (long) x, (long) y, (long) m1, (long) m2);\n return -1;\n }\n return 0;\n}\n\n// Could make this a little more efficient, but something to get things started.\nint32_t rand_int32(void) {\n union {\n uint32_t u;\n int32_t i;\n } x;\n x.u = (unsigned) rand();\n x.u = (x.u << 15) ^ (unsigned) rand();\n x.u = (x.u << 15) ^ (unsigned) rand();\n return x.i;\n}\n \nint tests_euc(void) {\n int32_t t[] = { INT32_MIN, INT32_MIN + 1, -2, -1, 0, 1, 2, INT32_MAX - 1,\n INT32_MAX };\n size_t n = sizeof t / sizeof t[0];\n for (size_t yi = 0; yi < n; yi++) {\n int32_t y = t[yi];\n if (y == 0)\n continue;\n for (size_t xi = 0; xi < n; xi++) {\n int32_t x = t[xi];\n int retval = test_euc(x, y);\n if (retval) {\n return retval;\n }\n }\n }\n n = 1000u*1000*1000; // Number of random tests\n while (n) {\n int32_t y = rand_int32();\n if (y == 0) {\n continue;\n }\n int32_t x = rand_int32();\n int retval = test_euc(x, y);\n if (retval) {\n return retval;\n }\n n--;\n }\n return 0;\n}\n\nint main() {\n tests_euc();\n puts("Done");\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-23T17:53:08.873",
"Id": "253832",
"ParentId": "253799",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "253814",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-22T22:17:35.693",
"Id": "253799",
"Score": "6",
"Tags": [
"c",
"gcc"
],
"Title": "4 different implementations of modulo with fully defined behavior"
}
|
253799
|
<p>I want to load 2 files and show this data in 2 strings. I trying to do it like this and it works fine. But I think it is not the best solution... How to do more elegant solution?</p>
<pre><code>var saleNumber1 = ""
var saleNumber2 = ""
override func viewDidLoad() {
super.viewDidLoad()
sale1()
sale2()
}
func sale1() {
let url = URL(string: "http://example.com/folder/sale1.txt")!
let task = URLSession.shared.dataTask(with: url) {(data, response, error) in
guard let data = data else { return }
saleNumber1 = "\(String(data: data, encoding: .utf8)!)"
}
task.resume()
}
func sale2() {
let url = URL(string: "http://example.com/folder/sale2.txt")!
let task = URLSession.shared.dataTask(with: url) {(data, response, error) in
guard let data = data else { return }
saleNumber2 = "\(String(data: data, encoding: .utf8)!)"
}
task.resume()
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-22T22:55:17.710",
"Id": "500484",
"Score": "1",
"body": "Welcome to CodeReview@SE. What is the second thing crossing your mind when you look at the code and ponder *good enough? Or needs improvement?*, what has been the first?"
}
] |
[
{
"body": "<p>Time to learn how to DRY off your WET code!</p>\n<p>(DRY -> "Don't Repeat Yourself"; WET -> "Write Everything Twice")</p>\n<p>Note how the only difference between your two functions is a URL and a change in data, effectively "changing input results in changing output." Consider consolidating the two into one generic function that takes a variable url in as input and returns data which can be store in a variable of your choice.</p>\n<pre><code>var saleNumber1 = ""\nvar saleNumber2 = ""\n\noverride func viewDidLoad() {\n super.viewDidLoad()\n \n saleNumber1 = sale("http://example.com/folder/sale1.txt")\n saleNumber2 = sale("http://example.com/folder/sale2.txt")\n}\n\nfunc sale(path: String) -> String {\n let url = URL(string: path)!\n let saleNumber = ""\n let task = URLSession.shared.dataTask(with: url) {(data, response, error) in\n guard let data = data else { return }\n saleNumber = "\\(String(data: data, encoding: .utf8)!)"\n }\n\n task.resume()\n\n return saleNumber\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-23T21:52:30.053",
"Id": "500578",
"Score": "1",
"body": "There are two problems with your suggestion: First, it does not compile because `let saleNumber` defines a *constant.* The bigger problem is that `URLSession.shared.dataTask` works *asynchronously,* i.e. the method returns immediately, and calls the closure later, when the data has been retrieved. In other words, chances are high that the function will return an empty string."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-24T01:16:39.577",
"Id": "500587",
"Score": "0",
"body": "agh my fault for not looking up swift declarations first, my js lizard brain jumped right to `let == scope lifetime var`."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-23T19:03:46.670",
"Id": "253838",
"ParentId": "253801",
"Score": "0"
}
},
{
"body": "<p>At the very least, you should:</p>\n<ul>\n<li><p>Have a single routine that performs the network request and fetches the string;</p>\n</li>\n<li><p>This routine should use a completion handler closure, so the caller can supply code to be called when the asynchronous network request finishes;</p>\n</li>\n<li><p>You should look at the <a href=\"https://en.wikipedia.org/wiki/List_of_HTTP_status_codes\" rel=\"nofollow noreferrer\">HTTP status code</a> and make sure it is <a href=\"https://en.wikipedia.org/wiki/List_of_HTTP_status_codes#2xx_success\" rel=\"nofollow noreferrer\">2xx</a>, to make sure the request succeeded (which is especially important when your web service is only returning a string ... but it is also useful when you start using more structured responses);</p>\n</li>\n<li><p>If you are writing a utility method to perform the request, you probably should return the related <code>URLSessionTask</code> in case the caller might want to cancel the request ... You might not be using it at this point, so you might declare it as a <code>@discardableResult</code>, indicating that you are returning this information, but that it is OK if the caller does not avail itself of this task object at this point. But it is very useful to get in the habit of returning this <code>URLSessionTask</code> so the caller can cancel it if it needs to (e.g. the user dismisses the view; the user supplies new query parameters that invalidate the need for the initial request; etc.).</p>\n</li>\n<li><p>We want to disentangle the network request code from the updating of some model object. So the function performing the network request should not be updating the model objects, itself, but rather supply the returned information via the aforementioned completion handler.</p>\n</li>\n<li><p>It is a minor point, but one should probably refrain from using the forced unwrapping operator, <code>!</code>, when parsing server responses. When writing client code, you want to gracefully handle any server-side errors, but a forced unwrapping operator will crash your app if it fails.</p>\n</li>\n</ul>\n<p>So, pulling that all together:</p>\n<pre class=\"lang-swift prettyprint-override\"><code>enum NetworkError: Error {\n case failure(Data?, URLResponse?)\n}\n\n@discardableResult\nfunc fetch(from url: URL, queue: DispatchQueue = .main, completion: @escaping (Result<String, Error>) -> Void) -> URLSessionTask {\n let task = URLSession.shared.dataTask(with: url) { data, response, error in\n guard\n error == nil,\n let responseData = data,\n let httpResponse = response as? HTTPURLResponse,\n 200 ..< 300 ~= httpResponse.statusCode,\n let responseString = String(data: responseData, encoding: .utf8)\n else {\n queue.async {\n completion(.failure(error ?? NetworkError.failure(data, response)))\n }\n return\n }\n\n queue.async {\n completion(.success(responseString))\n }\n }\n\n task.resume()\n\n return task\n}\n</code></pre>\n<p>Then, your two routines could (a) adopt a similar completion handler pattern; and (b) call this common routine:</p>\n<pre class=\"lang-swift prettyprint-override\"><code>func sale1(completion: @escaping (Result<String, Error>) -> Void) {\n let url = URL(string: "http://example.com/folder/sale1.txt")!\n fetch(from: url, completion: completion)\n}\n\nfunc sale2(completion: @escaping (Result<String, Error>) -> Void) {\n let url = URL(string: "http://example.com/folder/sale2.txt")!\n fetch(from: url, completion: completion)\n}\n</code></pre>\n<p>And the caller might do:</p>\n<pre><code>sale1 { [weak self] result in\n switch result {\n case .success(let value): self?.saleNumber1 = value\n case .failure(let error): print(error)\n }\n}\n</code></pre>\n<p>And, if you wanted to do something when the two requests finish:</p>\n<pre><code>let group = DispatchGroup()\n\ngroup.enter()\nsale1 { [weak self] result in\n ...\n group.leave()\n}\n\ngroup.enter()\nsale2 { [weak self] result in\n ...\n group.leave()\n}\n\ngroup.notify(queue: .main) { [weak self] in\n // do whatever you want when both are finished (e.g. trigger UI update)\n}\n</code></pre>\n<p>A few other observations:</p>\n<ol>\n<li><p>Generally, we do not just have web services return a string. Usually we would use structured responses from our web services, such as JSON, and then our Swift code would use <code>JSONDecoder</code> to parse the response out.</p>\n<p>This offers two capabilities: First, if a request failed for some reason, the web service might want to return meaningful error information (above and beyond a simple HTTP status code). If you are treating the response just as a string, it becomes harder to do elegant error handling. Second, right now you are apparently only returning a single string, but in the future, you might want more structured responses (e.g. a image URL, an identifier, and a string; or perhaps an array of them, etc.).</p>\n</li>\n<li><p>It is beyond the scope of this question, but <a href=\"https://developer.apple.com/documentation/combine\" rel=\"nofollow noreferrer\">Combine</a> offers elegant alternatives for parsing network requests, determining when they all finish, etc.</p>\n</li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-30T16:55:03.417",
"Id": "254098",
"ParentId": "253801",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-22T22:26:42.187",
"Id": "253801",
"Score": "0",
"Tags": [
"swift",
"ios"
],
"Title": "How to load and get data from 2 files"
}
|
253801
|
<p>I have a set of tables that I want to execute a <code>LEFT JOIN</code> on and bring back "excluded" rows. In addition, I would like the left table's ID included as part of the results set. Here's some sample data:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Table1_ID</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
</tr>
<tr>
<td>3</td>
</tr>
<tr>
<td>5</td>
</tr>
</tbody>
</table>
</div><div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Table2_ID</th>
<th>Table2_Val</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>a</td>
</tr>
<tr>
<td>2</td>
<td>b</td>
</tr>
<tr>
<td>3</td>
<td>c</td>
</tr>
<tr>
<td>4</td>
<td>d</td>
</tr>
<tr>
<td>5</td>
<td>c</td>
</tr>
</tbody>
</table>
</div>
<p>A simple left join would look like this</p>
<pre><code>SELECT t1.Table1_ID, t2.Table2_Val
FROM Table2 t2
LEFT JOIN Table1 t1 ON t2.Table2_ID = t1.Table1_ID
WHERE t1.Table1_ID IS NULL
</code></pre>
<p>And yields the following table</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Table1_ID</th>
<th>Table2_Val</th>
</tr>
</thead>
<tbody>
<tr>
<td>NULL</td>
<td>b</td>
</tr>
<tr>
<td>NULL</td>
<td>d</td>
</tr>
</tbody>
</table>
</div>
<p>However, my desired result is to have for each ID in Table2 that is missing in Table1, return the set of values in Table2 paired with the existing values in table 1. Like so:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Table1_ID</th>
<th>Table2_Val</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>b</td>
</tr>
<tr>
<td>1</td>
<td>d</td>
</tr>
<tr>
<td>3</td>
<td>b</td>
</tr>
<tr>
<td>3</td>
<td>d</td>
</tr>
<tr>
<td>5</td>
<td>b</td>
</tr>
<tr>
<td>5</td>
<td>d</td>
</tr>
</tbody>
</table>
</div>
<p>So far, the best I've been able to come up with is through using a <code>CROSS JOIN</code> to accomplish this, but I'd like to know if there's a better/more efficient way to handle this. Here's the code I'm curious about improving:</p>
<pre><code>WITH cte (T1_ID, T2_ID, T2_Value)
AS
(
SELECT t1.Table1_ID, t2.Table2_ID, t2.Table2_Val
FROM Table1 t1 CROSS JOIN Table2 t2
GROUP BY t1.Table1_ID, t2.Table2_ID, t2.Table2_Val
)
SELECT
cte.Table1_ID,
t2.Table2_Val
FROM Table2 t2
INNER JOIN cte ON t2.Table2_ID = cte.T2_ID
LEFT JOIN Table1 t1 ON t2.Table2_ID = t1.Table1_ID
WHERE t1.Table1_ID IS NULL
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-23T21:33:07.847",
"Id": "500577",
"Score": "0",
"body": "Is it not efficient?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-30T16:17:52.813",
"Id": "501117",
"Score": "0",
"body": "Right now it performs well enough to be usable, but the `CROSS JOIN` has me worried about scaling this solution."
}
] |
[
{
"body": "<p>You already have the <code>table2_val</code>s you need.\nJust <code>cross join</code> them with table1. No need for long nested stuff and <code>group by</code>:</p>\n<pre><code>select t1x.Table1_Id,q.Table2_Val\nfrom\n Table1 t1x\n cross join\n (\n SELECT t2.Table2_Val \n FROM Table2 t2 \n LEFT JOIN Table1 t1 ON t2.Table2_ID = t1.Table1_ID \n WHERE t1.Table1_ID IS NULL\n )q\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-25T11:18:20.180",
"Id": "256435",
"ParentId": "253804",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-22T22:32:09.453",
"Id": "253804",
"Score": "0",
"Tags": [
"sql-server",
"t-sql"
],
"Title": "SQL Query to perform a \"reverse exclusion\" on a LEFT JOIN with a select from the left side table"
}
|
253804
|
<p>For educational purposes, I have implemented the <a href="https://en.wikipedia.org/wiki/Advanced_Encryption_Standard" rel="noreferrer">AES</a> block cipher in python. I decided to follow the interface for block cipher modules as defined in <a href="https://www.python.org/dev/peps/pep-0272/" rel="noreferrer">PEP 272</a>. The implementation consists of two python files, <code>aes.py</code> and <code>block_cipher.py</code></p>
<p><strong>aes.py</strong> (~300 lines of code)</p>
<pre><code># coding: utf-8
"""
Advanced Encryption Standard.
The implementations of mix_columns() and inv_mix_columns() use cl_mul with
hardcoded factors in order to prevent side channel attacks
"""
from block_cipher import BlockCipher, BlockCipherWrapper
from block_cipher import MODE_ECB, MODE_CBC, MODE_CFB, MODE_OFB, MODE_CTR
__all__ = [
'new', 'block_size', 'key_size',
'MODE_ECB', 'MODE_CBC', 'MODE_CFB', 'MODE_OFB', 'MODE_CTR'
]
SBOX = (
0x63, 0x7c, 0x77, 0x7b, 0xf2, 0x6b, 0x6f, 0xc5,
0x30, 0x01, 0x67, 0x2b, 0xfe, 0xd7, 0xab, 0x76,
0xca, 0x82, 0xc9, 0x7d, 0xfa, 0x59, 0x47, 0xf0,
0xad, 0xd4, 0xa2, 0xaf, 0x9c, 0xa4, 0x72, 0xc0,
0xb7, 0xfd, 0x93, 0x26, 0x36, 0x3f, 0xf7, 0xcc,
0x34, 0xa5, 0xe5, 0xf1, 0x71, 0xd8, 0x31, 0x15,
0x04, 0xc7, 0x23, 0xc3, 0x18, 0x96, 0x05, 0x9a,
0x07, 0x12, 0x80, 0xe2, 0xeb, 0x27, 0xb2, 0x75,
0x09, 0x83, 0x2c, 0x1a, 0x1b, 0x6e, 0x5a, 0xa0,
0x52, 0x3b, 0xd6, 0xb3, 0x29, 0xe3, 0x2f, 0x84,
0x53, 0xd1, 0x00, 0xed, 0x20, 0xfc, 0xb1, 0x5b,
0x6a, 0xcb, 0xbe, 0x39, 0x4a, 0x4c, 0x58, 0xcf,
0xd0, 0xef, 0xaa, 0xfb, 0x43, 0x4d, 0x33, 0x85,
0x45, 0xf9, 0x02, 0x7f, 0x50, 0x3c, 0x9f, 0xa8,
0x51, 0xa3, 0x40, 0x8f, 0x92, 0x9d, 0x38, 0xf5,
0xbc, 0xb6, 0xda, 0x21, 0x10, 0xff, 0xf3, 0xd2,
0xcd, 0x0c, 0x13, 0xec, 0x5f, 0x97, 0x44, 0x17,
0xc4, 0xa7, 0x7e, 0x3d, 0x64, 0x5d, 0x19, 0x73,
0x60, 0x81, 0x4f, 0xdc, 0x22, 0x2a, 0x90, 0x88,
0x46, 0xee, 0xb8, 0x14, 0xde, 0x5e, 0x0b, 0xdb,
0xe0, 0x32, 0x3a, 0x0a, 0x49, 0x06, 0x24, 0x5c,
0xc2, 0xd3, 0xac, 0x62, 0x91, 0x95, 0xe4, 0x79,
0xe7, 0xc8, 0x37, 0x6d, 0x8d, 0xd5, 0x4e, 0xa9,
0x6c, 0x56, 0xf4, 0xea, 0x65, 0x7a, 0xae, 0x08,
0xba, 0x78, 0x25, 0x2e, 0x1c, 0xa6, 0xb4, 0xc6,
0xe8, 0xdd, 0x74, 0x1f, 0x4b, 0xbd, 0x8b, 0x8a,
0x70, 0x3e, 0xb5, 0x66, 0x48, 0x03, 0xf6, 0x0e,
0x61, 0x35, 0x57, 0xb9, 0x86, 0xc1, 0x1d, 0x9e,
0xe1, 0xf8, 0x98, 0x11, 0x69, 0xd9, 0x8e, 0x94,
0x9b, 0x1e, 0x87, 0xe9, 0xce, 0x55, 0x28, 0xdf,
0x8c, 0xa1, 0x89, 0x0d, 0xbf, 0xe6, 0x42, 0x68,
0x41, 0x99, 0x2d, 0x0f, 0xb0, 0x54, 0xbb, 0x16,
)
INV_SBOX = (
0x52, 0x09, 0x6a, 0xd5, 0x30, 0x36, 0xa5, 0x38,
0xbf, 0x40, 0xa3, 0x9e, 0x81, 0xf3, 0xd7, 0xfb,
0x7c, 0xe3, 0x39, 0x82, 0x9b, 0x2f, 0xff, 0x87,
0x34, 0x8e, 0x43, 0x44, 0xc4, 0xde, 0xe9, 0xcb,
0x54, 0x7b, 0x94, 0x32, 0xa6, 0xc2, 0x23, 0x3d,
0xee, 0x4c, 0x95, 0x0b, 0x42, 0xfa, 0xc3, 0x4e,
0x08, 0x2e, 0xa1, 0x66, 0x28, 0xd9, 0x24, 0xb2,
0x76, 0x5b, 0xa2, 0x49, 0x6d, 0x8b, 0xd1, 0x25,
0x72, 0xf8, 0xf6, 0x64, 0x86, 0x68, 0x98, 0x16,
0xd4, 0xa4, 0x5c, 0xcc, 0x5d, 0x65, 0xb6, 0x92,
0x6c, 0x70, 0x48, 0x50, 0xfd, 0xed, 0xb9, 0xda,
0x5e, 0x15, 0x46, 0x57, 0xa7, 0x8d, 0x9d, 0x84,
0x90, 0xd8, 0xab, 0x00, 0x8c, 0xbc, 0xd3, 0x0a,
0xf7, 0xe4, 0x58, 0x05, 0xb8, 0xb3, 0x45, 0x06,
0xd0, 0x2c, 0x1e, 0x8f, 0xca, 0x3f, 0x0f, 0x02,
0xc1, 0xaf, 0xbd, 0x03, 0x01, 0x13, 0x8a, 0x6b,
0x3a, 0x91, 0x11, 0x41, 0x4f, 0x67, 0xdc, 0xea,
0x97, 0xf2, 0xcf, 0xce, 0xf0, 0xb4, 0xe6, 0x73,
0x96, 0xac, 0x74, 0x22, 0xe7, 0xad, 0x35, 0x85,
0xe2, 0xf9, 0x37, 0xe8, 0x1c, 0x75, 0xdf, 0x6e,
0x47, 0xf1, 0x1a, 0x71, 0x1d, 0x29, 0xc5, 0x89,
0x6f, 0xb7, 0x62, 0x0e, 0xaa, 0x18, 0xbe, 0x1b,
0xfc, 0x56, 0x3e, 0x4b, 0xc6, 0xd2, 0x79, 0x20,
0x9a, 0xdb, 0xc0, 0xfe, 0x78, 0xcd, 0x5a, 0xf4,
0x1f, 0xdd, 0xa8, 0x33, 0x88, 0x07, 0xc7, 0x31,
0xb1, 0x12, 0x10, 0x59, 0x27, 0x80, 0xec, 0x5f,
0x60, 0x51, 0x7f, 0xa9, 0x19, 0xb5, 0x4a, 0x0d,
0x2d, 0xe5, 0x7a, 0x9f, 0x93, 0xc9, 0x9c, 0xef,
0xa0, 0xe0, 0x3b, 0x4d, 0xae, 0x2a, 0xf5, 0xb0,
0xc8, 0xeb, 0xbb, 0x3c, 0x83, 0x53, 0x99, 0x61,
0x17, 0x2b, 0x04, 0x7e, 0xba, 0x77, 0xd6, 0x26,
0xe1, 0x69, 0x14, 0x63, 0x55, 0x21, 0x0c, 0x7d,
)
round_constants = (0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36)
block_size = 16
key_size = None
def new(key, mode, IV=None, **kwargs) -> BlockCipherWrapper:
if mode in (MODE_CBC, MODE_CFB, MODE_OFB) and IV is None:
raise ValueError("This mode requires an IV")
cipher = BlockCipherWrapper()
cipher.block_size = block_size
cipher.IV = IV
cipher.mode = mode
cipher.cipher = AES(key)
if mode == MODE_CFB:
cipher.segment_size = kwargs.get('segment_size', block_size * 8)
elif mode == MODE_CTR:
counter = kwargs.get('counter')
if counter is None:
raise ValueError("CTR mode requires a callable counter object")
cipher.counter = counter
return cipher
class AES(BlockCipher):
def __init__(self, key: bytes):
self.key = key
self.Nk = len(self.key) // 4 # words per key
if self.Nk not in (4, 6, 8):
raise ValueError("invalid key size")
self.Nr = self.Nk + 6
self.Nb = 4 # words per block
self.state: list[list[int]] = []
# raise NotImplementedError
# key schedule
self.w: list[list[int]] = []
for i in range(self.Nk):
self.w.append(list(key[4*i:4*i+4]))
for i in range(self.Nk, self.Nb*(self.Nr+1)):
tmp: list[int] = self.w[i-1]
q, r = divmod(i, self.Nk)
if not r:
tmp = self.sub_word(self.rot_word(tmp))
tmp[0] ^= round_constants[q-1]
elif self.Nk > 6 and r == 4:
tmp = self.sub_word(tmp)
self.w.append(
[a ^ b for a, b in zip(self.w[i-self.Nk], tmp)]
)
def encrypt_block(self, block: bytes) -> bytes:
self.set_state(block)
self.add_round_key(0)
for r in range(1, self.Nr):
self.sub_bytes()
self.shift_rows()
self.mix_columns()
self.add_round_key(r)
self.sub_bytes()
self.shift_rows()
self.add_round_key(self.Nr)
return self.get_state()
def decrypt_block(self, block: bytes) -> bytes:
self.set_state(block)
self.add_round_key(self.Nr)
for r in range(self.Nr-1, 0, -1):
self.inv_shift_rows()
self.inv_sub_bytes()
self.add_round_key(r)
self.inv_mix_columns()
self.inv_shift_rows()
self.inv_sub_bytes()
self.add_round_key(0)
return self.get_state()
@staticmethod
def rot_word(word: list[int]):
# for key schedule
return word[1:] + word[:1]
@staticmethod
def sub_word(word: list[int]):
# for key schedule
return [SBOX[b] for b in word]
def set_state(self, block: bytes):
self.state = [
list(block[i:i+4])
for i in range(0, 16, 4)
]
def get_state(self) -> bytes:
return b''.join(
bytes(col)
for col in self.state
)
def add_round_key(self, r: int):
round_key = self.w[r*self.Nb:(r+1)*self.Nb]
for col, word in zip(self.state, round_key):
for row_index in range(4):
col[row_index] ^= word[row_index]
def mix_columns(self):
for i, word in enumerate(self.state):
new_word = []
for j in range(4):
# element wise cl mul with constants 2, 3, 1, 1
value = (word[0] << 1)
value ^= (word[1] << 1) ^ word[1]
value ^= word[2] ^ word[3]
# polynomial reduction in constant time
value ^= 0x11b & -(value >> 8)
new_word.append(value)
# rotate word in order to match the matrix multiplication
word = self.rot_word(word)
self.state[i] = new_word
def inv_mix_columns(self):
for i, word in enumerate(self.state):
new_word = []
for j in range(4):
# element wise cl mul with constants 0xe, 0xb, 0xd, 0x9
value = (word[0] << 3) ^ (word[0] << 2) ^ (word[0] << 1)
value ^= (word[1] << 3) ^ (word[1] << 1) ^ word[1]
value ^= (word[2] << 3) ^ (word[2] << 2) ^ word[2]
value ^= (word[3] << 3) ^ word[3]
# polynomial reduction in constant time
value ^= (0x11b << 2) & -(value >> 10)
value ^= (0x11b << 1) & -(value >> 9)
value ^= 0x11b & -(value >> 8)
new_word.append(value)
# rotate word in order to match the matrix multiplication
word = self.rot_word(word)
self.state[i] = new_word
def shift_rows(self):
for row_index in range(4):
row = [
col[row_index] for col in self.state
]
row = row[row_index:] + row[:row_index]
for col_index in range(4):
self.state[col_index][row_index] = row[col_index]
def inv_shift_rows(self):
for row_index in range(4):
row = [
col[row_index] for col in self.state
]
row = row[-row_index:] + row[:-row_index]
for col_index in range(4):
self.state[col_index][row_index] = row[col_index]
def sub_bytes(self):
for col in self.state:
for row_index in range(4):
col[row_index] = SBOX[col[row_index]]
def inv_sub_bytes(self):
for col in self.state:
for row_index in range(4):
col[row_index] = INV_SBOX[col[row_index]]
def print_state(self):
# debug function
for row_index in range(4):
print(' '.join(f'{col[row_index]:02x}' for col in self.state))
print()
def main():
key = bytes.fromhex('2b 7e 15 16 28 ae d2 a6 ab f7 15 88 09 cf 4f 3c')
cipher = new(key, MODE_ECB)
plain_text = bytes.fromhex('32 43 f6 a8 88 5a 30 8d 31 31 98 a2 e0 37 07 34')
print(plain_text)
cipher_text = cipher.encrypt(plain_text)
print(cipher_text)
print(cipher.decrypt(cipher_text))
if __name__ == '__main__':
main()
</code></pre>
<p><strong>block_cipher.py</strong> (~200 lines of code)</p>
<pre><code># coding: utf-8
"""
this module provides the following classes:
BlockCipher
Counter
BlockCipherWrapper
"""
MODE_ECB = 1
MODE_CBC = 2
MODE_CFB = 3
MODE_PGP = 4 # optional
MODE_OFB = 5
MODE_CTR = 6
class BlockCipher:
def encrypt_block(self, block: bytes) -> bytes:
raise NotImplementedError
def decrypt_block(self, block: bytes) -> bytes:
raise NotImplementedError
# <removed lines of code>
class Counter:
def __init__(self, nonce: bytes, block_size: int, byte_order='big'):
self.nonce = nonce
self.counter_size = block_size - len(nonce)
self.byte_order = byte_order
self.counter = 0
def __call__(self) -> bytes:
out = self.nonce + self.counter.to_bytes(
self.counter_size, self.byte_order
)
self.counter += 1
return out
class BlockCipherWrapper:
def __init__(self):
"""initiate instance attributes."""
# PEP 272 required attributes
self.block_size: int = NotImplemented # measured in bytes
self.IV: bytes = NotImplemented # initialization vector
# other attributes
self.mode: int = NotImplemented
self.cipher: BlockCipher = NotImplemented
self.counter: Counter = NotImplemented
self.segment_size: int = NotImplemented
def encrypt(self, byte_string: bytes) -> bytes:
if self.mode == MODE_CFB and len(byte_string) * 8 % self.segment_size:
raise ValueError("message length doesn't match segment size")
if self.mode == MODE_CFB and self.segment_size & 7:
raise NotImplementedError
if self.mode != MODE_CFB and len(byte_string) % self.block_size:
raise ValueError("message length doesn't match block size")
blocks = [
byte_string[i:i+self.block_size]
for i in range(0, len(byte_string), self.block_size)
]
if self.mode == MODE_ECB:
return b''.join([
self.cipher.encrypt_block(block) for block in blocks
])
elif self.mode == MODE_CBC:
cipher_blocks = [self.IV]
for block in blocks:
cipher_blocks.append(
self.cipher.encrypt_block(
self.xor(block, cipher_blocks[-1])
)
)
return b''.join(cipher_blocks[1:])
elif self.mode == MODE_CFB:
s = self.segment_size >> 3
cipher = b''
current_input = self.IV
while byte_string:
cipher += self.xor(
byte_string[:s],
self.cipher.encrypt_block(current_input)[:s]
)
byte_string = byte_string[s:]
current_input = current_input[s:] + cipher[-s:]
return cipher
elif self.mode == MODE_PGP:
raise NotImplementedError
elif self.mode == MODE_OFB:
last_output = self.IV
cipher_blocks = [self.IV]
for block in blocks:
last_output = self.cipher.encrypt_block(last_output)
cipher_blocks.append(self.xor(block, last_output))
return b''.join(cipher_blocks[1:])
elif self.mode == MODE_CTR:
cipher_blocks = []
for block in blocks:
ctr = self.counter()
if len(ctr) != self.block_size:
raise ValueError("counter has the wrong size")
cipher_blocks.append(
self.xor(self.cipher.encrypt_block(ctr), block)
)
return b''.join(cipher_blocks)
else:
raise NotImplementedError("This mode is not supported")
def decrypt(self, byte_string: bytes) -> bytes:
if self.mode == MODE_CFB and len(byte_string) * 8 % self.segment_size:
raise ValueError("message length doesn't match segment size")
if self.mode == MODE_CFB and self.segment_size & 7:
raise NotImplementedError
if self.mode != MODE_CFB and len(byte_string) % self.block_size:
raise ValueError("message length doesn't match block size")
# split up into blocks
blocks = [
byte_string[i:i+self.block_size]
for i in range(0, len(byte_string), self.block_size)
]
if self.mode == MODE_ECB:
return b''.join([
self.cipher.decrypt_block(block)
for block in blocks
])
elif self.mode == MODE_CBC:
plain_blocks = []
blocks.insert(0, self.IV)
for i in range(1, len(blocks)):
plain_blocks.append(self.xor(
self.cipher.decrypt_block(blocks[i]), blocks[i-1]
))
return b''.join(plain_blocks)
elif self.mode == MODE_CFB:
s = self.segment_size >> 3
plain = b''
current_input = self.IV
while byte_string:
plain += self.xor(
byte_string[:s],
self.cipher.encrypt_block(current_input)[:s]
)
current_input = current_input[s:] + byte_string[:s]
byte_string = byte_string[s:]
return plain
elif self.mode == MODE_PGP:
raise NotImplementedError("PGP mode is not supported")
elif self.mode == MODE_OFB:
return self.encrypt(byte_string)
elif self.mode == MODE_CTR:
return self.encrypt(byte_string)
else:
raise ValueError("unknown mode")
def xor(self, block1, block2):
size = (
self.segment_size >> 3
if self.mode == MODE_CFB
else self.block_size
)
if not (len(block1) == len(block2) == size):
raise ValueError(str(size))
return bytes([block1[i] ^ block2[i] for i in range(size)])
def main():
pass
if __name__ == '__main__':
main()
</code></pre>
|
[] |
[
{
"body": "<p>That is a <em>lot</em> of code to review, so this review will only touch on more superficial things.</p>\n<ol>\n<li>I'm not familiar with the pattern of modifying <code>__all__</code>, but it seems like using an underscore at the start of names which should not be available from the outside would be a less "magic" way of achieving the same thing.</li>\n<li><a href=\"https://pypi.org/project/black/\" rel=\"nofollow noreferrer\">black</a> and <a href=\"https://pypi.org/project/isort/\" rel=\"nofollow noreferrer\">isort</a> can help make the files more idiomatic, even if that means the very long lists will be linearized.</li>\n<li>Stricter <a href=\"https://docs.python.org/3/library/typing.html\" rel=\"nofollow noreferrer\">type annotations</a> (for all parameters and late-initialized variables) would make the code more self-documenting.</li>\n<li><a href=\"https://pypi.org/project/pylint/\" rel=\"nofollow noreferrer\">pylint</a> and <a href=\"https://pypi.org/project/flake8/\" rel=\"nofollow noreferrer\">flake8</a> can notify you of other non-idiomatic code, such as top-level variable names which are not all uppercase.</li>\n<li><code>key_size</code> doesn't seem to be used for anything. Edit: Since it's required by PEP 272, I would suggest adding a comment to this effect. Otherwise it's pretty likely to be removed by the next developer unless its presence is actually enforced by commit hooks and/or CI.</li>\n<li>Some of the variable and field names are not useful, like all the single letter ones and <code>tmp</code>.</li>\n<li>Does "inv" in <code>INV_SBOX</code> stand for "inverse"? If so, can this variable be generated from <code>SBOX</code>?</li>\n<li>Several things here could usefully be <code>enum</code>s, such as <code>SBOX</code> and the modes.</li>\n<li><code>@staticmethod</code> is a code smell (for anyone tempted to comment, that doesn't <em>always</em> mean it's a bad thing). Often it's done because the IDE suggests it, but in my experience this is usually not helpful. Either because there's no reason to ever call it directly or because it is such a generic piece of code (often idempotent input transformation) that it really belongs outside the class. In this case, <code>rot_word</code> and <code>sub_word</code> are not actually called on the class. Whether they belong as functions or internal methods would depend on how they are likely to be used and reused.</li>\n<li><code>set_state</code> and <code>get_state</code> both transform the state. I would normally expect only one of them to actually transform it.</li>\n<li>The stuff in aes.py's <code>main</code> function belongs in a test case. I would expect <code>main</code> to parse arguments and to dispatch an action for the rest of the code.</li>\n<li>The <code>BlockCipher</code> class doesn't do anything, and there is only one child class, so it looks like it can be removed without losing anything.</li>\n<li><code>xor</code> seems like a strange name for a method which doesn't just <code>return first ^ second</code>. Is there a name which more closely says what it actually does?</li>\n<li>block_cipher.py has a no-op <code>main</code> function. I'm sure it's meant to eventually contain something, but I would normally reject that as part of a merge request because it's effectively dead code.</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-23T21:06:17.967",
"Id": "500571",
"Score": "0",
"body": "thanks for your answer! you're right, `key_size` isn't used for anything but PEP 272 requires it for compatibility with other cipher modules / implementations. thanks for the tool recommendations, I'll check them out"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-24T16:14:20.373",
"Id": "500654",
"Score": "0",
"body": "`xor` does just return `first^second` after some checking."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-23T20:54:54.927",
"Id": "253847",
"ParentId": "253808",
"Score": "4"
}
},
{
"body": "<blockquote>\n<p>Advanced Encryption Standard.</p>\n</blockquote>\n<p>Please simply include a well defined reference to the standard (it's FIPS 197 by NIST). If you do use any of the standard notations in there, indicate that as well, it will make your code much easier to understand.</p>\n<blockquote>\n<pre><code>'MODE_ECB', 'MODE_CBC', 'MODE_CFB', 'MODE_OFB', 'MODE_CTR'\n</code></pre>\n</blockquote>\n<p>Modes of operation are not part of the block cipher itself. I'm not that familiar with the Python language, but if possible the import of these modes should be avoided for the block cipher implementation itself.</p>\n<blockquote>\n<p>INV_SBOX = (</p>\n</blockquote>\n<p>The blocks are nicely formed and well named. But I wonder why there are so many double empty lines before some statements, and this one is missing a single one.</p>\n<blockquote>\n<p>def new(key, mode, IV=None, **kwargs) -> BlockCipherWrapper:</p>\n</blockquote>\n<p>There should be no need to repeat this for each and every cipher you implement. Also, the more modes are added, the more this will expand. What about CCM, EAX, GCM, SIV, disk modes? This is where you can have a <code>Mode</code> class and perform the initialization within the implementations of that class.</p>\n<blockquote>\n<pre><code> if self.Nk not in (4, 6, 8):\n</code></pre>\n</blockquote>\n<p>Better define constants for 128, 192 and 256 and then use a divide by <code>BYTE_SIZE</code> or just <code>8</code> if you think that's obvious enough.</p>\n<blockquote>\n<pre><code> # key schedule\n</code></pre>\n</blockquote>\n<p>Here you could point to the right chapter in the standard. The code is clear in this section when it comes to <strong>how</strong> the algorithm is implemented, but you're not really explaining <strong>what</strong> you are doing (apart from performing the key schedule, obviously).</p>\n<hr />\n<p>The AES implementation itself is nice and well structured enough. The names are fine, the code looks fine. I'd add a few more lines about the "what", but since it is unlikely to change much and the function of these methods is well understood, you can be excused for not including it.</p>\n<hr />\n<p>Generally I would take a look at when you are including empty lines. The empty line directly after a method declaration doesn't look good to me, especially since you yourself choose to ignore it for comments. This makes the code look slightly unbalanced to me. I'd just directly start after the method declaration myself, less is more.</p>\n<hr />\n<blockquote>\n<p>MODE_PGP = 4 # optional</p>\n</blockquote>\n<p>What's optional? Optional for who?</p>\n<blockquote>\n<p>def encrypt(self, byte_string: bytes) -> bytes:</p>\n</blockquote>\n<p>Here and during decrypt you are falling in the same trap. Use separate classes and maybe defer to them, but please do not implement all modes in a single method. Check for instance how the Bouncy Castle lightweight API is implemented.</p>\n<p>Also, it isn't clear to me if you need to handle a full message at once or not.</p>\n<blockquote>\n<p>elif self.mode == MODE_PGP:\nraise NotImplementedError</p>\n</blockquote>\n<p>Either leave it out or implement it, but don't leave it hanging. Note that there doesn't seem to be any way to test if the implementation is available. What about returning a set of enumerations to see which modes are available?</p>\n<blockquote>\n<pre><code>def xor(self, block1, block2):\n</code></pre>\n</blockquote>\n<p>This is a bit of a mixed bag method. You should at the very least make it private (<code>__xor</code>).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-31T14:55:48.690",
"Id": "254135",
"ParentId": "253808",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "253847",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-22T23:37:26.707",
"Id": "253808",
"Score": "6",
"Tags": [
"python",
"reinventing-the-wheel",
"cryptography",
"aes"
],
"Title": "AES implementation in python"
}
|
253808
|
<h1>Cryptarithms</h1>
<p>Cryptarithms, or <a href="https://en.wikipedia.org/wiki/Verbal_arithmetic" rel="nofollow noreferrer">Verbal arithmetic</a>, are substitution puzzles where letters represent unique digits:</p>
<pre class="lang-none prettyprint-override"><code> S E N D
+ M O R E
=========
M O N E Y
</code></pre>
<p>The goal is to find the digit-letter mapping which will translate the puzzle into a valid mathematical computation.</p>
<p>My goal was to write a Python script which will find the solution(s).</p>
<h1>Method</h1>
<p>Using the above puzzle, the solution finder breaks the puzzle down into a series of digit-sum columns. Starting at the left (carry in & carry out from columns not shown)</p>
<pre class="lang-none prettyprint-override"><code> 0 = M
S + M = O
E + O = N
N + R = E
D + E = Y
</code></pre>
<p>Starting at the 1's column (<code>D+E=Y</code>), the solver tries <code>D=0</code> and <code>E=1</code>, and computes <code>Y=1</code>. This solution is discarded, since duplicate <code>1</code> is already used by <code>E</code>. After several more iterations, it eventual tries <code>D=1</code>, <code>E=2</code> and directly computes <code>1+2=Y</code> and determines <code>Y=3</code> with no carry into the tens column.</p>
<p>With a valid ones column digit-sum, it advances to the tens column: <code>N+R=E</code>. Since <code>E</code> has already been assigned a value from the ones-column, it is "known". The first available digit for <code>N</code> is <code>4</code>, so the column solver evaluates <code>4+R=2</code>, and determines <code>R=8</code> with a carry of <code>1</code> into the hundreds column.</p>
<p>It descends deeper into the hundreds column, and possibly deeper still to the thousands column, as it continues its exploration. When it reaches impossibilities, it unwinds the stack, and explores different branches.</p>
<p>Since the solution is generated using <code>yield</code> and <code>yield from</code> statements, when the first solution is found, it returns that solution, and pauses the search, until the next solution is requested.</p>
<p>The test code actually tries to generate all solutions, to ensure the solutions to the given puzzles are unique. Some of the example puzzles are taken from <a href="http://www.cryptarithms.com" rel="nofollow noreferrer">Cryptarithms.com</a>.</p>
<h1>Code</h1>
<p>All feedback welcome.</p>
<pre class="lang-py prettyprint-override"><code>import re
from collections import Counter
from time import perf_counter
from typing import Callable, Iterator, NewType
Term = NewType('Term', str)
Operator = NewType('Operator', str)
Solution = dict[str, int]
Solver = Callable[[set[int]], Iterator[Solution]]
TRACE = False
#===============================================================================
class CryptArithm:
"""
Solver for a "word math" puzzle
S E N D 9 5 6 7
+ M O R E + 1 0 8 5
========= =========
M O N E Y 1 0 6 5 2
"""
SUPPORTED_OPS = {'=', '+', '-'}
#---------------------------------------------------------------------------
class Variable:
"""
A letter-variable in the word-math puzzle.
Holds the letter, the allowed digits for the letter, and its
current candidate value.
"""
__slots__ = ('_letter', '_allowed', '_value')
def __init__(self, solver: 'CryptArithm', letter: str):
self._letter = letter
self._allowed = set(solver._digits)
self._value = 0
def exclude(self, *values):
"""
Specified one or more verboten values for the variable.
Used primarily to prevent terms with leading zeros.
"""
self._allowed -= set(values)
def solver(self, solver: Solver) -> Solver:
"""
The solver for a variable simply tries each allowable digit,
in turn, provided the digit is not currently used by another
letter.
For each valid possible digit, yield solutions from the
next solver, passed in as an argument.
"""
def solve(used: set[int]) -> Iterator[Solution]:
"""
The solve for a variable by trying each allowable digit,
in turn, provided the digit is not currently in use.
Digits in use are passed as an argument
For each valid possible digit, yield solutions from the
next solver, passed in as an argument to the wrapper.
"""
for digit in self._allowed - used:
self._value = digit
yield from solver(used | {digit})
return solve
def __str__(self):
value = self._value
if value is None:
value = '{' + ''.join(map(str, self._allowed)) + '}'
return f"{self._letter}={value}"
def __repr__(self):
return f"<{self._letter}>"
#---------------------------------------------------------------------------
class Column:
"""
A digit-sum column in the word-puzzle.
For example, with SEND+MORE=MONEY, the last column of digits
expresses the digit sum D+E=Y.
A digit-sum will include a carry-in from a "smaller" column, if
present, and a carry-out to a "larger" column, if present.
"""
def __init__(self, solver: 'CryptArithm', result: 'Variable'):
self._base = solver._base
self._addends = Counter()
self._result = result
self._carry_in = None
self._carry_to = None
self._carry = 0
def add(self, var: 'Variable') -> None:
"""
Add a digit addend to the digit sum.
"""
self._addends[var] += 1
def sub(self, var: 'Variable') -> None:
"""
Subtract a digit subtrahend from the digit sum.
"""
self._addends[var] -= 1
def carry_from(self, other: 'Column') -> None:
"""
Indicate this digit-sum has a carry-in from another column.
"""
self._carry_in = other
other._carry_to = self
def __str__(self):
exp = f"{self._result._letter}=" if self._result else "0="
if self._carry_in:
exp += "carry"
for var, count in self._addends.items():
if count == 1:
exp += f"+{var._letter}"
elif count == -1:
exp += f"-{var._letter}"
elif count != 0:
exp += f"{count:+d}{var._letter}"
return exp
def __repr__(self):
return f"Col[{self}]"
def unknowns(self, knowns: set['Variable']) -> list['Variable']:
"""
Given a set of known variables, determine the list of
unknown variables in this digit-sum column, ordered in
decreasing usage.
"""
unknowns = Counter(self._addends)
if self._result:
unknowns[self._result] -= 1
unknowns = [(var, abs(count)) for var, count in unknowns.items()]
unknowns = sorted(unknowns, key=lambda vc: vc[1], reverse=True)
return [var for var, _ in unknowns if var not in knowns]
def validator(self, solver: Solver) -> Solver:
"""
When all digits are "known" in a digit-sum column, verify the
correct result digit is obtained and compute the carry to the
next column. If the digit-sum is correct, and a carry out is
allowed or the carry is determined to be zero, yield solutions
from the next solver, passed in as an argument.
"""
def validate(used: set[int]) -> Iterator[Solution]:
"""
When all digits are "known" in a digit-sum column, verify the
correct result digit is obtained and compute the carry to the
next column. If the digit-sum is correct, and a carry out is
allowed or the carry is determined to be zero, yield solutions
from the next solver, passed in as an argument to the wrapper.
"""
result = sum(count * var._value
for var, count in self._addends.items())
if self._carry_in:
result += self._carry_in._carry
carry, result = result // self._base, result % self._base
if (result == self._result._value and
(carry == 0 or self._carry_to)):
self._carry = carry
yield from solver(used)
return validate
def _solve_for_result(self, solver: Solver) -> Solver:
"""
When all digits but the result digit are known in a digit-sum
column, compute the result digit and carry to the next column.
If the result digit is allowed (and not currently used by
another variable), yield solutions from the next solver,
passed in as an argument.
"""
def solve(used: set[int]) -> Iterator[Solution]:
"""
When all digits but the result digit are known in a digit-sum
column, compute the result digit and carry to the next column.
If the result digit is allowed (and not in the used set),
yield solutions from the next solver, passed in as an argument
to the wrapper function.
"""
result = sum(count * var._value
for var, count in self._addends.items())
if self._carry_in:
result += self._carry_in._carry
carry, digit = result // self._base, result % self._base
allowed = self._result._allowed - used
if digit in allowed and (carry == 0 or self._carry_to):
self._result._value = digit
self._carry = carry
yield from solver(used | {digit})
return solve
def _solve_for_addend(self, addend: 'Variable'):
"""
One unknown digit in the digit-sum column, but not the digit-sum's
result digit.
Use modular arithmetic to compute the unique digit that satisfies
the digit-sum column. If the digit is allowed (and not used),
yield solutions from the subsequent solver.
"""
def solver(solver: Solver) -> Solver:
def solve(used: set[int]) -> Iterator[Solution]:
addend._value = 0
result = sum(count * var._value
for var, count in self._addends.items())
if self._carry_in:
result += self._carry_in._carry
multiplier = self._addends[addend] # +/- 1
digit = (self._result._value - result) * multiplier
digit %= self._base
result += digit * multiplier
carry = result // self._base
allowed = addend._allowed - used
if digit in allowed and (carry == 0 or self._carry_to):
addend._value = digit
self._carry = carry
yield from solver(used | {digit})
return solve
return solver
def solver(self, unknown: 'Variable'):
"""
Determine which specialized solver to used for a digit sum column.
If the only unknown is the result digit,
use the solve_for_result solver.
If the only unknown is not a repeated digit,
use the solve_for_addend solver.
Returns None if no specialized solver exists.
"""
if unknown == self._result:
if self._addends[unknown] == 0:
return self._solve_for_result
elif abs(self._addends[unknown]) == 1:
return self._solve_for_addend(unknown)
return None
#---------------------------------------------------------------------------
def __init__(self, puzzle: str, base: int = 10, leading_zeros: bool = False):
self._puzzle = puzzle
self._base = base
self._leading_zeros = leading_zeros
self._digits = range(base)
self._variables = self._create_variables(puzzle)
self._columns = self._create_columns(puzzle)
def _create_variables(self, puzzle: str) -> dict[str, Variable]:
"""
Create a variable for each unique letter in the puzzle.
"""
letters = set(ch for ch in puzzle if ch.isalpha())
if len(letters) > self._base:
raise ValueError(f"Puzzle has too many variables for base-{base}")
return {letter: self.Variable(self, letter) for letter in letters}
@classmethod
def _parse(cls, puzzle: str) -> tuple[list[Operator], list[Term]]:
"""
Parse the puzzle into tokens.
* Remove all spaces
* Replace multiple equal signs with a single equals character
* Split into word and non-word tokens
* Validate proper term/operator sequence
* Return operators and terms separately.
"""
equation = re.sub('=+', '=', re.sub(r'\s+', '', puzzle))
tokens = re.split(r'(\W+)', equation)
terms = [token for token in tokens if token.isalpha()]
operators = [token for token in tokens if not token.isalpha()]
# Validation
if len(tokens) < 5 or len(terms) != len(operators) + 1:
raise ValueError("Expected 'term op term op term [op term]...'")
if (unsupported := set(operators) - cls.SUPPORTED_OPS):
raise NotImplementedError(f"Unsupported: {repr(unsupported)[1:-1]}")
if operators.count('=') != 1:
raise ValueError("Only one equals operator allowed")
if operators[-1] != '=':
raise ValueError("Last operator expected to be equals")
return operators, terms
def _create_columns(self, puzzle: str) -> list[Column]:
"""
Parse the puzzle into a list of digit-sum columns.
"""
operators, terms = self._parse(puzzle)
# Leading zeros are not allowed
if not self._leading_zeros:
for term in terms:
if len(term) > 1:
self._variables[term[0]].exclude(0)
num_columns = max(map(len, terms)) # Maximum columns
terms = [term[::-1] for term in terms] # Reverse individual terms
operators.insert(0, '+') # First term is "added"
result = terms.pop() # Extract result
operators.pop() # Discard "=" operator
# Extract into columns
columns = []
for col_num in range(num_columns):
if col_num < len(result):
var = self._variables[result[col_num]]
else:
var = None
column = self.Column(self, var)
for op, term in zip(operators, terms):
if col_num < len(term):
var = self._variables[term[col_num]]
if op == '+':
column.add(var)
elif op == '-':
column.sub(var)
else:
raise RuntimeError(f"Unexpected operator: {op}")
columns.append(column)
for to, frm in zip(columns[1:], columns[:-1]):
to.carry_from(frm)
return columns
def _strategize(self):
"""
Determine a solving strategy.
Returns a list of strategy functions.
"""
strategies = []
knowns = set()
# For each column, starting at the ones-column...
for column in self._columns:
unknowns = column.unknowns(knowns)
if TRACE:
print(f"{column}: {unknowns}")
# If the column has unknowns...
if unknowns:
# if it has more than one uknown ...
for var in unknowns[:-1]:
strategies.append(var.solver)
# For the last unknown, attempt to find a specialized solver
last = unknowns[-1]
solver = column.solver(last)
if solver:
strategies.append(solver)
else:
# Failing that, try every possible value ...
strategies.append(last.solver)
# ... and validate the column
strategies.append(column.validator)
knowns |= set(unknowns)
else:
# No unknowns! Just validate the column
strategies.append(column.validator)
return strategies
def solutions(self) -> Iterator[Solution]:
"""
Create a solver strategy, and then generate all possible
solutions.
"""
strategies = self._strategize()
solver = self._emitter()
for strategy in reversed(strategies):
solver = strategy(solver)
yield from solver(set())
def solve(self) -> Solution:
"""
Find the unique solution to the puzzle.
"""
solutions = self.solutions()
try:
solution = next(solutions)
except StopIteration:
raise ValueError("No solution found") from None
try:
solution = next(solutions)
raise ValueError("Multiple solutions!")
except StopIteration:
return solution
def _emitter(self) -> Solver:
def solver(used: set[int]) -> Iterator[Solution]:
yield {var._letter: var._value for var in self._variables.values()}
return solver
def substitute(self, solution: dict[str, int]) -> str:
"""
Translate the puzzle using the given solution, into a numeric
version of the puzzle.
"""
if self._base > 10:
raise NotImplementedError("Not yet implemented.")
puzzle = self._puzzle
for key, val in solution.items():
puzzle = puzzle.replace(key, str(val))
return puzzle
#===============================================================================
if __name__ == '__main__':
puzzles = [
"""\
S E N D
+ M O R E
=========
M O N E Y""",
"""\
F O R T Y
+ T E N
+ T E N
=========
S I X T Y""",
"""\
T I L E S
+ P U Z Z L E S
===============
P I C T U R E""",
"""\
D O U B L E
+ D O U B L E
+ T O I L
=============
T R O U B L E""",
"""\
T H R E E
+ T H R E E
+ T W O
+ T W O
+ O N E
===========
E L E V E N""",
"""\
SO+MANY+MORE+MEN+SEEM+TO+SAY+THAT+
THEY+MAY+SOON+TRY+TO+STAY+AT+HOME+
SO+AS+TO+SEE+OR+HEAR+THE+SAME+ONE+
MAN+TRY+TO+MEET+THE+TEAM+ON+THE+
MOON+AS+HE+HAS+AT+THE+OTHER+TEN
=TESTS
"""
]
for puzzle in puzzles:
start = perf_counter()
ca = CryptArithm(puzzle)
solution = ca.solve()
stop = perf_counter()
print(f"{stop-start:.3f} sec")
print(ca.substitute(solution))
print()
</code></pre>
<h1>Output</h1>
<pre class="lang-none prettyprint-override"><code>0.006 sec
9 5 6 7
+ 1 0 8 5
=========
1 0 6 5 2
0.007 sec
2 9 7 8 6
+ 8 5 0
+ 8 5 0
=========
3 1 4 8 6
0.003 sec
9 1 5 4 2
+ 3 0 7 7 5 4 2
===============
3 1 6 9 0 8 4
0.002 sec
7 9 8 0 6 4
+ 7 9 8 0 6 4
+ 1 9 3 6
=============
1 5 9 8 0 6 4
0.007 sec
8 4 6 1 1
+ 8 4 6 1 1
+ 8 0 3
+ 8 0 3
+ 3 9 1
===========
1 7 1 2 1 9
3.398 sec
31+2764+2180+206+3002+91+374+9579+
9504+274+3116+984+91+3974+79+5120+
31+73+91+300+18+5078+950+3720+160+
276+984+91+2009+950+9072+16+950+
2116+73+50+573+79+950+19508+906
=90393
</code></pre>
|
[] |
[
{
"body": "<h2>Bugs</h2>\n<p>This code will crash:</p>\n<pre><code> raise ValueError(f"Puzzle has too many variables for base-{base}")\n</code></pre>\n<p>since <code>base</code> is not defined. You likely meant to write <code>self._base</code>.</p>\n<h2>Quality of life</h2>\n<p>Consider expressing your output durations in milliseconds instead of seconds and include one or two decimals for more precision; and showing the original puzzle along with its output.</p>\n<h2>Scoped main</h2>\n<p>It's not enough to have a <code>__main__</code> guard - all of those symbols are still going to be in global scope and visible to the rest of your <code>CryptArithm</code> code unless you move the main code into a function.</p>\n<p>Such namespace pollution can have surprising effects, so it's best to avoid it altogether and limit the scope of your main symbols.</p>\n<h2>Early constraints</h2>\n<p>I think you're doing the right thing by declaring <code>leading_zeros</code> as a constructor argument defaulting to <code>False</code>. I find it odd, however, that at one point during construction the instance is effectively in an incorrect/inconsistent state, because the leading variable's <code>_allowed</code> still includes zero. It's possible to prune zero from this variable on construction without requiring storage of the <code>leading_zeros</code> member. That said, this is somewhat chicken-and-egg, because you're setting up your variables before you parse. If you set up your variables during or after parse this inconsistency can be avoided.</p>\n<h2>Alternate algorithms</h2>\n<p>I wrote an alternate approach to this that:</p>\n<ul>\n<li>Forms a linear discrete system of polynomial order 1</li>\n<li>Attempts to solve the system with a recursive root-finding loop</li>\n<li>Performs tree pruning based on the knowledge that the polynomial, when sorted in decreasing order of its coefficients, will produce a monotonically increasing sum given a lexicographically sorted permutation</li>\n</ul>\n<p>This approach scales quite differently from yours. In most cases it's slower, but in others it's able to yield a result very quickly.</p>\n<pre><code>\ndef by_coeff(kv):\n return kv[1]\n\n\nclass CryptRoots:\n __slots__ = ('puzzle_desc', 'coeffs', 'names', 'zero_pos')\n\n RE_WS = re.compile('\\s*')\n RE_EQN = re.compile(\n r'^([^=]+?)'\n r'=+'\n r'([^=]+?)$'\n )\n RE_TERMS = re.compile(\n r'([+-])\\s*([ A-Z]+)'\n )\n\n def __init__(self, puzzle_desc: str):\n self.puzzle_desc = puzzle_desc\n puzzle_desc = self.RE_WS.sub('', puzzle_desc)\n left, right = self.RE_EQN.search(puzzle_desc).groups()\n variables = defaultdict(int)\n terms = self.RE_TERMS.findall('+' + left)\n\n for op, term in terms:\n fac = 10**(len(term) - 1)\n if op == '-':\n fac = -fac\n\n for c in term:\n variables[c] += fac\n fac //= 10\n\n fac = 10**(len(right) - 1)\n for c in right:\n variables[c] -= fac\n fac //= 10\n\n variables = sorted(variables.items(), key=by_coeff, reverse=True)\n self.coeffs = tuple(v for name, v in variables)\n self.names = tuple(name for name, v in variables)\n self.zero_pos = next(i for i, v in enumerate(self.coeffs) if v <= 0)\n\n def recurse(\n self,\n remain: Tuple[int, ...],\n chosen: Tuple[int, ...],\n total: int=0,\n depth: int=0,\n ) -> Iterable[Tuple[int, ...]]:\n global node_visits\n node_visits += 1\n\n coeffs = self.coeffs[depth:]\n coeff = coeffs[0]\n n = len(coeffs)\n\n # We have a certain total that we need to reduce to zero\n # If the current total plus the potential upper and lower bounds does\n # not produce an interval that covers zero, reject this candidate\n # t+lb <= 0 <= t+ub\n # lb <= -t <= ub\n\n if coeff != 0:\n x_needed = -total / coeff\n\n if n == 1:\n x_int = int(x_needed)\n if 0 <= x_int < 10 and x_needed == x_int:\n yield chosen + (x_int,)\n return\n\n remain_asc = sorted(remain)\n zero_pos = self.zero_pos - depth\n\n if zero_pos > 0:\n upper_x = remain_asc[-1: -zero_pos-1: -1] + remain_asc[n-zero_pos-1:: -1]\n else:\n upper_x = remain_asc[n-1::-1]\n\n # This is effectively np.dot, but numpy arrays are much slower in this\n # method - possibly due to the number of appends and deletes\n upper = sum(\n x*c for x, c in zip(upper_x, coeffs)\n )\n if -total > upper:\n return\n\n if zero_pos > 0:\n lower_x = remain_asc[:zero_pos] + remain_asc[zero_pos-n:]\n else:\n lower_x = remain_asc[-n:]\n\n lower = sum(\n x*c for x, c in zip(lower_x, coeffs)\n )\n if lower > -total:\n return\n\n # We can sort in order of increasing error from x_needed, but that ends\n # up offering no performance advantage\n\n for i, x in enumerate(remain):\n yield from self.recurse(\n remain[:i] + remain[i+1:],\n chosen + (x,),\n total + x*coeff,\n depth+1,\n )\n\n def solve(self) -> Tuple[int, ...]:\n return next(self.recurse(tuple(range(10)), ()))\n\n def substitute(self, solution: Tuple[int, ...]) -> str:\n res = self.puzzle_desc\n for value, name in zip(solution, self.names):\n res = res.replace(name, str(value))\n return res\n\n\ndef main():\n puzzles = [\n """\\\n F O R T Y\n + T E N\n + T E N\n =========\n S I X T Y""",\n\n """\\\n S E N D\n + M O R E\n =========\n M O N E Y""",\n\n """\\\n T I L E S\n + P U Z Z L E S\n ===============\n P I C T U R E""",\n\n """\\\n D O U B L E\n + D O U B L E\n + T O I L\n =============\n T R O U B L E""",\n\n """\\\n T H R E E\n + T H R E E\n + T W O\n + T W O\n + O N E\n ===========\n E L E V E N""",\n\n """\\\n SO+MANY+MORE+MEN+SEEM+TO+SAY+THAT+\n THEY+MAY+SOON+TRY+TO+STAY+AT+HOME+\n SO+AS+TO+SEE+OR+HEAR+THE+SAME+ONE+\n MAN+TRY+TO+MEET+THE+TEAM+ON+THE+\n MOON+AS+HE+HAS+AT+THE+OTHER+TEN\n =TESTS\n """\n ]\n\n for i, puzzle in enumerate(puzzles):\n for solver in (CryptArithm, CryptRoots):\n global node_visits\n node_visits = 0\n start = perf_counter()\n ca = solver(puzzle)\n solution = ca.solve()\n stop = perf_counter()\n\n print(f"{i}. {solver.__name__}: {1e3*(stop - start):.1f} ms, {node_visits} nodes")\n\n print()\n</code></pre>\n<p>On my "nothing-special" laptop this yields</p>\n<pre class=\"lang-none prettyprint-override\"><code>0. CryptArithm: 4.4 ms, 2204 nodes\n0. CryptRoots: 508.8 ms, 285762 nodes\n\n1. CryptArithm: 3.0 ms, 356 nodes\n1. CryptRoots: 18.7 ms, 12774 nodes\n\n2. CryptArithm: 2.0 ms, 1365 nodes\n2. CryptRoots: 32.4 ms, 16883 nodes\n\n3. CryptArithm: 1.1 ms, 153 nodes\n3. CryptRoots: 1091.3 ms, 659674 nodes\n\n4. CryptArithm: 4.6 ms, 1870 nodes\n4. CryptRoots: 209.4 ms, 122197 nodes\n\n5. CryptArithm: 2719.1 ms, 832613 nodes\n5. CryptRoots: 25.4 ms, 13305 nodes\n</code></pre>\n<p>Since I was focusing on performance exploration and not cleanliness, this doesn't validate the input as thoroughly as yours.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-26T05:42:39.327",
"Id": "500749",
"Score": "1",
"body": "Good catch with the `self._base`. Fair point about the scoped main. I'll have to give some more thought to the early constraint point. Regarding quality of life's seconds & milliseconds, the 3 second case at the end would not benefit from sub-millisecond resolution, but if you've got performance ideas, it would definitely be required for comparison purposes for the other cases; I look forward to seeing them."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-30T21:49:45.583",
"Id": "501156",
"Score": "1",
"body": "@AJNeufeld Alternate posted. If I figure out some Diophantine fanciness I might have another alternate coming."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-31T17:34:36.253",
"Id": "501196",
"Score": "1",
"body": "Interesting alternative, cool! I see you're cheating by finding only the first solution, and not exhaustively checking if there are multiple solutions. If I do that (`solution = next(ca.solutions())`), my solution times range from 0.6ms (`THREE+THREE+TWO+TWO+ONE=ELEVEN` and `TILES+PUZZLE=PICTURE`) to 4.8ms (`SEND+MORE=MONEY`), with 204.9ms for the last puzzle. Still your solution is eight times faster for the last puzzle and mine is eight times faster for the second last; for a programming contest, the ideal solution would need to choose between the strategies somehow. Interesting problem."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-25T20:47:49.457",
"Id": "253911",
"ParentId": "253813",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "253911",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-23T06:15:00.347",
"Id": "253813",
"Score": "7",
"Tags": [
"python",
"python-3.x",
"generator"
],
"Title": "A cryptarithm solver"
}
|
253813
|
<p>So I semi-wrote directory size checker by copying some parts from Stackoverflow.</p>
<p>It works as follows:</p>
<ol>
<li>Select a directory you want to check the size of subdirectories inside.</li>
<li>It goes scans all the directories inside the chosen directory. If there are also just files, that's not a problem the recursive function can deal with that as well.</li>
<li>It goes through every subdirectory and checks for the file size. If there's a permission problem, it returns -1 (this way we can easily tell which directories caused acces issues).</li>
<li>The directory name and it's "mass" gets stored in a dictionary.</li>
<li>The whole dictionary gets sorted.</li>
<li>Items that are +1GB get the "GB" tag, while the ones between 0 and 1 get the "MB" tag, just for better precision.
(I like to change between directories faster, so I added an option to give "r" as an input to scan for a second time. Closing the script and reopening it takes time imo)</li>
</ol>
<p>Now I can see which folder is the biggest and which ones are empty, I don't know why but in Windows I need to go 1:1 and check each folder size individually, which I dislike a lot. This way I can check folders that contain hundreds of gigabytes in seconds.</p>
<p>I would like to know what I could have done better or what was obnoxious.</p>
<pre><code>import os
from tkinter import *
from tkinter.filedialog import askdirectory
def Main():
Tk().withdraw() # use to hide tkinter window
Dir = askdirectory(title="Select Folder") # shows dialog box and return the path
print("LOADING...") # Sometimes it takes long to output results, this just indicates that the program is working and not broken
sort_dict = Sorter(Dir) # Give the directory as an input
print("\n-SORTED-\n")
for i in sort_dict:
if i[1] > 1: # continues using gigabytes
fixed_float = float("{:.3f}".format(i[1]))
data_type = "GB: "
elif i[1] < 0: # no acces
print(f"NO ACCES : {i[0]}")
continue
else: # convert to megabytes
mega_float = i[1] * 1024
fixed_float = float("{:.3f}".format(mega_float))
data_type = "MB: "
dflt_white_space = 8
white_space = " " * (dflt_white_space - len(str(fixed_float)))
print(f"{fixed_float} {white_space + data_type + i[0]}")
if input("\nPress 'r' to retry, press anything else to exit\n") == "r":
Main()
def get_dir_size(Dir): # Returns the `directory` size in bytes.
total = 0
try:
for entry in os.scandir(Dir): # print("[+] Getting the size of", directory)
if entry.is_file(): # if it's a file, use stat() function
total += entry.stat().st_size
elif entry.is_dir(): # if it's a directory, recursively call this function
total += get_dir_size(entry.path)
except NotADirectoryError: # if `directory` isn't a directory, get the file size
return os.path.getsize(Dir)
except PermissionError: # if for whatever reason we can't open the folder, return -1
return -1 # returns a negative size that will be visible (to use conditions) after the conversion
return total
def get_subdirs(Dir):
dir_array = []
for x in os.listdir(Dir):
dir_array.append(x)
return dir_array
def Sorter(Dir):
Dict = {}
dir_array = get_subdirs(Dir)
for x in range(len(dir_array)):
file_size = float(get_dir_size(Dir + "\\" + dir_array[x])) / 1073741824 # Converts the bytes to GB
Dict[dir_array[x]] = file_size
sort_dict = sorted(Dict.items(), key=lambda x: x[1], reverse=True)
return sort_dict
if __name__ == "__main__":
Main()
</code></pre>
|
[] |
[
{
"body": "<p><strong>Function equal to built-in</strong></p>\n<pre><code>def get_subdirs(Dir):\n dir_array = []\n for x in os.listdir(Dir):\n dir_array.append(x)\n return dir_array\n</code></pre>\n<p>This is exactly the same as <code>os.listdir</code>, so just use it instead of the whole function.</p>\n<p><strong>Iterate simpler</strong></p>\n<pre><code>for x in range(len(dir_array)):\n file_size = float(get_dir_size(Dir + "\\\\" + dir_array[x])) / 1073741824 # Converts the bytes to GB\n\n Dict[dir_array[x]] = file_size\n</code></pre>\n<p>Can become:</p>\n<pre><code>for dir in dir_array:\n file_size = float(get_dir_size(Dir + "\\\\" + dir)) / 1073741824 # Converts the bytes to GB\n\n Dict[dir] = file_size\n</code></pre>\n<p><strong>Constants at the start</strong></p>\n<p>Putting constants at the start of the code is better than putting them inside, so at the start:</p>\n<pre><code>BYTES_IN_GIGABYTE = 1073741824 \n</code></pre>\n<p><strong>User message</strong></p>\n<p>Your code works for files so:</p>\n<pre><code>Dir = askdirectory(title="Select Folder")\n</code></pre>\n<p>becomes:</p>\n<pre><code>Dir = askdirectory(title="Select Folder or File:")\n</code></pre>\n<p><strong>Fancy progressbar</strong></p>\n<p>A fancy way to signify that the program is working can be found <a href=\"https://stackoverflow.com/questions/33768577/tkinter-gui-with-progress-bar\">here</a></p>\n<p><strong><code>-1</code> lost in code</strong></p>\n<p>You return -1 sometimes from <code>get_dir_size</code> but you never check for it.</p>\n<p><strong>One comment on the logic</strong></p>\n<pre><code>for i in sort_dict:\n if i[1] > 1: # continues using gigabytes\n</code></pre>\n<p>I would rename <code>i</code> to <code>dir</code> and add a comment saying what <code>i[1]</code> is.</p>\n<p><strong>Cross platform compatibility</strong></p>\n<p>As suggested by @s.dallapalma avoid concatenating paths with the plus (+) sign, and use <code>os.path.join</code> or <code>pathlib</code> instead. Thus, the code can work on different OS.</p>\n<p>I liked the attention to handling of exception and the new clean format strings.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-23T11:22:49.883",
"Id": "500512",
"Score": "0",
"body": "I felt 2x dumber, when I saw what I did with the \"os.listdir\"."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-23T11:24:22.983",
"Id": "500513",
"Score": "2",
"body": "@Betrax coding is hard ;)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-24T09:04:06.523",
"Id": "500603",
"Score": "1",
"body": "I would suggest to add another section to point out to avoid concatenating paths with the plus (+) sign, and use os.path.join or pathlib instead. Thus, the code can work on different OS."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-23T11:19:32.213",
"Id": "253819",
"ParentId": "253817",
"Score": "6"
}
},
{
"body": "<p>If I understood correctly, you would like to have a straight function that, given a directory to analyze, returns its size and the size of every sub-directory.\nYou want the function to return a dictionary like the following:</p>\n<pre><code>{\n 'dir': int,\n 'dir/subdir1': int,\n 'dir/subdir1/subsubdir1': int,\n 'dir/subdir2': int,\n ... \n}\n</code></pre>\n<p>where the values are the size of the directories in bytes. Afterward, you sort the dictionary to check which folders are the biggest and which the smallest (or empty).</p>\n<p>If so, I have written the following code snippet, that can be further improved depending on your needs:</p>\n<pre class=\"lang-py prettyprint-override\"><code>import os\n\ndef get_dir_size(path_to_dir: str):\n """Return a dictionary <str, int> where the key is the name of the directory\n or subdirectory, and the value is the sum of their files' size in bytes.\n\n Parameters\n ----------\n path_to_dir : str\n The path to the directory to analyze\n\n Returns\n -------\n Dict[str, int]\n The dictionary containig the size (in bytes) of each subdirectory\n \n """\n \n dir_size_map = {}\n\n for root, _, filenames in os.walk(path_to_dir):\n for filename in filenames:\n path_to_file = os.path.join(root, filename)\n size = os.path.getsize(path_to_file)\n dir_size_map[root] = dir_size_map.get(root, 0) + size \n\n return dir_size_map\n</code></pre>\n<p>You can call it on the desired directory, say <code>path/to/some/dir</code>:</p>\n<pre class=\"lang-py prettyprint-override\"><code>dir_info = get_dir_size('path/to/some/dir')\n</code></pre>\n<p>And analyze the resulting dictionary:</p>\n<pre class=\"lang-py prettyprint-override\"><code># Sort items in descending order of size\ndir_info = dict(sorted(dir_info.items(), key=lambda item: item[1], reverse=True))\n\n# List the subdirectories size in MB\nfor name, size in dir_info.items():\n print(name, (size/1024/1024), 'MB')\n\n# Calculate the total size\ntotal_bytes = sum([size for _, size in dir_info])\nprint('Total size:', total_bytes)\n</code></pre>\n<p>Regarding the format size, I recommend you to store the information as single unit, that is, bytes instead of mixing up MB and GB.\nThen, you can convert them in KB (/1024), MB (/1024^2), GB (/1024^3) when needed, for example, when displaying them.</p>\n<h1>Alternative using Counter</h1>\n<p>As pointed out by <a href=\"https://codereview.stackexchange.com/users/98493/graipher\">Graipher</a>, an alternative would use a Counter, instead of a raw dictionary.\nIn that case, the code can be written as follows:</p>\n<pre class=\"lang-py prettyprint-override\"><code>import os\n\nfrom collections import Counter\n\ndef get_dir_size(path_to_dir: str):\n \n dir_size_counter = Counter()\n\n for root, _, filenames in os.walk(path_to_dir):\n for filename in filenames:\n path_to_file = os.path.join(root, filename)\n dir_size_counter[root] += os.path.getsize(path_to_file)\n\n return dir_size_counter\n\ndir_info = get_dir_size('path/to/some/dir')\n\nfor name, size in dir_info.most_common():\n print(name, size)\n</code></pre>\n<p>It allows you to simply write <code>dir_size_counter[root] += size</code> and to sort the dictionary using the <code>most_common()</code> method.\nThis is a valid alternative. Personally, I believe the choice depends on your coding style and preferences.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-23T12:38:33.703",
"Id": "500519",
"Score": "1",
"body": "You can use a `collections.defaultdict(int)` or even a `collections.Counter` instead of a dictionary. Both allow you to simply write `dir_size_map[root] += size`, while with the latter you can (ab)use `dir_size_map.most_common()` to get a sorted version."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-23T13:06:49.747",
"Id": "500522",
"Score": "1",
"body": "Also, `dir` is a reserved function name in Python. And doing `d = {}` instead of `d = dict()` saves you a bit over typing overhead"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-23T13:26:28.413",
"Id": "500523",
"Score": "1",
"body": "Thanks for pointing this out. I modified the answer accordingly!"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-23T11:41:37.947",
"Id": "253820",
"ParentId": "253817",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "253819",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-23T10:22:55.793",
"Id": "253817",
"Score": "5",
"Tags": [
"python",
"file-system"
],
"Title": "Directory size checker"
}
|
253817
|
<p>I have a simple async/await function which gets data from a firebase endpoint. I would like to know if there is any room for improvement performance wise.</p>
<pre><code>async function getDataById(id) {
const snapshot = await admin
.firestore()
.collection("collection")
.where("id", "==", id)
.get();
const documents = [];
snapshot.forEach((doc) => {
documents.push(doc.data());
});
return documents;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-23T13:03:06.240",
"Id": "500520",
"Score": "1",
"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)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-27T07:24:51.350",
"Id": "500816",
"Score": "1",
"body": "I'm no firebase expert, but from what I understand from this code, there are no glaring issues. Did you have any specific concerns with this function that is making you think there might be a performance issue going on?"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-23T10:36:48.210",
"Id": "253818",
"Score": "1",
"Tags": [
"javascript",
"firebase"
],
"Title": "JavaScript async/await function performance improvement"
}
|
253818
|
<p>Is this an efficient way to get the largest prime factor of a given number? Other solutions I found involved nested algorithms.</p>
<pre><code>function largestPrimeFactor(number) {
const factors = []
for(let i = 2; i <= number; i++){
if(number % i === 0){
factors.push(i);
number = number / i;
i = 1;
}
}
return factors.pop()
}
</code></pre>
|
[] |
[
{
"body": "<p>A short review;</p>\n<p>this looks great to me</p>\n<ul>\n<li>The last statement could use a semi-colon</li>\n<li>There is no reason to keep all the factors, just keep the last one you find;</li>\n</ul>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function largestPrimeFactor(number) {\n let factor;\n for(let i = 2; i <= number; i++){\n if(number % i === 0){\n factor = i;\n number = number / factor;\n i = 1;\n }\n }\n return factor;\n}\n\nconsole.log(largestPrimeFactor(1));\nconsole.log(largestPrimeFactor(7));\nconsole.log(largestPrimeFactor(60));</code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-23T15:22:35.970",
"Id": "253826",
"ParentId": "253821",
"Score": "1"
}
},
{
"body": "<p>Let's consider a few possible ways to speed this up.</p>\n<h3>Only look for prime factors</h3>\n<p>First of all, we know that even numbers (other than 2) are all composites, not primes. So, once we check for 2 as a factor, we can ignore all the other even numbers.</p>\n<pre><code>if (number % 2 == 0)\n factors.push(2);\n\nfor (int i=3; i<limit; i+=2) {\n if (number % i == 0)\n factors.push(i);\n}\n</code></pre>\n<p>This will normally approximately double speed in return for minimal effort.</p>\n<h3>Limit the search for factors</h3>\n<p>Note that in the loop above, I've specified the upper limit on the loop as <code>limit</code> rather than <code>number</code>. There's a reason for that. If two numbers multiply to give a third number, at least one of the factors must be less than or equal to the square root of the result. If it's a perfect square, then both of those can be the square root of the number. Otherwise, one is smaller than the square root, and the other is larger than the square root.</p>\n<p>But we don't have to conduct a long search for the second number--once we know the factor that's smaller than the square root, simple division tells us the other factor.</p>\n<p>So, we can search only for factors less than or equal to the square root, and using them, we can directly find the factors that are larger than the square root.</p>\n<p>Also note one other point: there can only be (at most) one prime factor larger than the square root.</p>\n<h3>Consider using a sieve</h3>\n<p>Taking the two preceding points together, we can see another possibility. In particular, we can start by searching for primes less than or equal to the input number. Then we can test whether the number is divisible by them (and not any composites).</p>\n<p>There's a really fast algorithm for finding all the primes up to some limit called the Sieve of Eratosthenes. It doesn't involve doing an division (which is a slow operation for computers). Instead, consider starting with a table of all the numbers up to the limit you care about. Starting from 2, add 2 to your list of primes numbers, then cross off all the multiples of 2. The look for the next number that isn't crossed off (3 in this case). Add it to the list of primes, then cross off all the multiples of 3. Then repeat--look for the next number that isn't crossed off (5), add it to the list of primes, and cross off all of its multiples.</p>\n<p>When you've gone through the whole table that way, you have a list of all the prime numbers up to the limit you care about. Then in your original loop turns into something like:</p>\n<pre><code>for (int i=0; i<numberOfPrimes; i++)\n if (number % primes[i] == 0)\n factors.push(primes[i]);\n</code></pre>\n<p>Although it's written in C++ rather than JavaScript, I posted <a href=\"https://stackoverflow.com/a/61154767/179910\">some code to implement this algorithm</a> on SO some years ago. Most of the code isn't very specific to C++ though, so converting to JavaScript should be fairly easy.</p>\n<p>This may fall within what you're referring to as a "nested algorithm" though--I'm not entirely sure what you mean by that.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-23T19:13:31.097",
"Id": "253839",
"ParentId": "253821",
"Score": "3"
}
},
{
"body": "<h2>Which algorithm to use?</h2>\n<p>These types of question often become a list of algorithms rather than a code reviews. If you are after alternative solutions there are dozens online in every language to pick from.</p>\n<p><a href=\"https://github.com/trekhleb/javascript-algorithms\" rel=\"nofollow noreferrer\">JavaScript Algorithms and Data Structures</a> is a very well documented list of Javascript implementations of many of the most common algorithms (and not so common) including source code (though they use a rather long form style). A handy reference for any coder.</p>\n<h2>Review</h2>\n<ul>\n<li><p><strong>Storage</strong> Using an array to store only the last processed value is rather wasteful. You need only store the last factor as a number, not push it to an array.</p>\n</li>\n<li><p><strong>Iteration</strong> The use of a <code>for</code> loop should be reserved to iteration of constant sequential interval. Use <code>while</code> loops when this is not so as they give you better control over the counter. (For loops force incrementer update often resulting in more iterations than needed).</p>\n</li>\n<li><p><strong>Style</strong> Spaces help readability. Generally</p>\n<ul>\n<li>Spaces after flow control tokens (flow are words like <code>while</code>, <code>for</code>, <code>if</code>, <code>else</code>, and so on).</li>\n<li>Spaces between operators <code>+</code>, <code>-</code> etc... which you have done.</li>\n<li>Spaces between code delimiter tokens like <code>) {</code>,</li>\n</ul>\n</li>\n<li><p><strong>Short form</strong> Use the short form where possible. Over time programming languages tend to work like natural languages with common oft used words and phrases becoming shorter. JavaScript had the advantage of a late starter ~1994 and came with many of these already built in.</p>\n<ul>\n<li><p>Always try to use the shortened form of a programming statement or expression. For example <code>number = number / i;</code> is the same as <code>number /= i;</code></p>\n</li>\n<li><p>Unlike many compiled languages JavaScript execution order is always known letting you craft even shorter expressions. See example Note that I group the compound expression <code>num /= factor = i, i = 2</code> using <code>()</code> which is strictly not needed but put there for clarity of intent.</p>\n</li>\n<li><p>Use common abbreviations when you can. Eg <code>number</code> can be <code>num</code> we all know what it means. If you have control of the function name maybe use <code>max</code> rather than <code>largest</code> <code>largestPrimeFactor</code> becomes <code>maxPrimeFactor</code></p>\n</li>\n<li><p>In the example I use a ternary operator <code>?</code>. It is debatable whether to use the shorter positive statement <code>i % 0</code> over <code>i % 0 === 0</code> as the shorter form relies on the coercion of the statement's expression result to a boolean, while the longer form the boolean is implied and execution is a little quicker. Maybe the longer form is worth while if you are expecting inputs of very large values > 40 bits</p>\n</li>\n</ul>\n</li>\n</ul>\n<h2>The rewrite</h2>\n<p>The rewrite uses the same algorithm with only some style and storage changes.</p>\n<p>There is a performance gain mostly due to the removal of the array. And a little by removal of the <code>for</code> loop incrementer allowing the counter to be reset to 2 rather than 1</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>console.log([10, 11, 12, 17, 42, 81, 119, -133, 5.2].map(maxPrimeFactor) + \"\");\n\n\n \nfunction maxPrimeFactor(num) { // num is expected as an unsigned integer\n var factor, i = 2;\n while (i <= num) {\n num % i ? i++ : (num /= factor = i, i = 2);\n }\n return factor;\n}\n\n//Personally I always collapse single line blocks. Keeping the block delimiters {}\nfunction maxPrimeFactor(num) {\n var factor, i = 2;\n while (i <= num) { num % i ? i++ : (num /= factor = i, i = 2) }\n return factor;\n}\n\n// As i have been accused in the comments of abusing ternaries you can also \n// use a short circuit expression \nfunction maxPrimeFactor(num) {\n var factor, i = 2;\n while (i <= num) { (num % i && i++) || (num /= factor = i, i = 2) }\n return factor;\n}</code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-24T17:03:52.297",
"Id": "500662",
"Score": "0",
"body": "You are abusing a ternary though, this is considered bad by every lint program and is discouraged by every JS style guide. Both solutions look worse than the original :/"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-24T17:41:00.647",
"Id": "500665",
"Score": "1",
"body": "abusing??? I thought I was rather gentle with it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-24T18:49:11.590",
"Id": "500668",
"Score": "0",
"body": "The moment you ignore the output of a ternary, you should use an `if`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-24T19:14:03.323",
"Id": "500669",
"Score": "0",
"body": "@konijn why is that? Let me guess, Because adding unneeded noise to code is a good thing? That adding lines to code decreases my consistent bugs per line rate? Or Because the code monkey god thinks JS coders are all idiots and without an `if` they wont know what `else` to do? To soon for right handed only expressions? CR javascript reviews should be kept at pre school level and leave the grown up stuff to the real low level coders? Or is it just Because!?. I will not treat readers of my answers as idiots. Coding is hard and dumbing it down does nothing towards making it easier."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-23T20:30:05.983",
"Id": "253845",
"ParentId": "253821",
"Score": "0"
}
},
{
"body": "<p>No, it's not efficient.</p>\n<p>Let's look at your loop, just cleaned up as suggested already:</p>\n<pre><code> for (let i = 2; i <= n; i++) {\n if (n % i === 0) {\n factors.push(i);\n n /= i;\n i = 1;\n }\n }\n</code></pre>\n<p>Let's say you get to the prime <code>i = 97</code> and find that it's a factor. Why do you then go back to <code>i = 2</code> (via <code>i = 1</code> and <code>i++</code>)? Makes no sense. You only got to <code>i = 97</code> because all smaller <code>i</code> weren't factors. So why check them again? They don't magically become factors.</p>\n<p>You could do <code>i--</code> instead, so that you check the factor again, in case it divides the given number multiple times. Or just use <code>while</code> instead of <code>if</code>, and don't interfere with the <code>for</code>-loop's managing of <code>i</code>.</p>\n<p>It's enough to search until <span class=\"math-container\">\\$\\sqrt{n}\\$</span>, and that's much faster. If <span class=\"math-container\">\\$i > \\sqrt{n}\\$</span> divides <span class=\"math-container\">\\$n\\$</span>, then <span class=\"math-container\">\\$n/i\\$</span> also does. And it's smaller than <span class=\"math-container\">\\$i\\$</span>, so you would've found it and divided it out of <span class=\"math-container\">\\$n\\$</span> already. Well, unless <span class=\"math-container\">\\$i = n\\$</span>, because then <span class=\"math-container\">\\$n/i\\$</span> is <span class=\"math-container\">\\$1\\$</span>, and the search only started at <span class=\"math-container\">\\$2\\$</span>. So after searching only as long as <span class=\"math-container\">\\$i \\le \\sqrt{n}\\$</span>, the remaining <span class=\"math-container\">\\$n\\$</span> itself is also a candidate.</p>\n<p>For example, for n=1,000,000,007 your code takes several seconds. The improved solution only takes about a millisecond:</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function largestPrimeFactor(n) {\n result = null;\n for (let i = 2; i <= n / i; i++) {\n while (n % i === 0) {\n result = i;\n n /= i;\n }\n }\n return n > 1 ? n : result;\n}\n\nt0 = performance.now();\nresult = largestPrimeFactor(1000000007);\nt1 = performance.now();\nconsole.log(t1 - t0, \"ms\");\nconsole.log(result);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-24T22:08:40.410",
"Id": "500672",
"Score": "0",
"body": "`for (let i = 2; i <= n / i; i++) {` is a **huge** efficiency improvement - this is the right answer."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-24T04:15:07.863",
"Id": "253861",
"ParentId": "253821",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-23T12:20:49.953",
"Id": "253821",
"Score": "3",
"Tags": [
"javascript",
"algorithm",
"primes",
"complexity"
],
"Title": "Is this an efficient/correct way to get largest Prime factor?"
}
|
253821
|
<p>Inspired by this <a href="https://www.youtube.com/watch?v=MdtYi0vvct0" rel="noreferrer">cppcon talk from Fedor Pikus about design patterns</a> and some real-world need I implemented a library that allows the user to add a generic visitor pattern capabilities to class hierarchies based on vanilla C++ runtime polymorphism with virtual functions. There were 2 requirements I wanted to follow:</p>
<ol>
<li>Generic return type, the same as when using <code>std::visit</code> on a <code>std::variant</code>.</li>
<li>Allow as much forward declarations as reasonably possible, to decouple the client from any code (i.e. concrete implementations) that one doesn't need to know.</li>
</ol>
<p>The code is on my github: <a href="https://github.com/ldrozdz93/cpp-visitor-pattern" rel="noreferrer">https://github.com/ldrozdz93/cpp-visitor-pattern</a>.</p>
<p>I'll also paste it here, as it's quite short.</p>
<p>The test file:</p>
<pre><code>#include <string>
#include <type_traits>
#include "catch.hpp"
#include "vstor/vstor.hpp"
namespace {
using vstor::Overloaded;
using vstor::VisitableFor;
using vstor::VisitableImpl;
using vstor::VisitableListVariant;
// NOTE: below code order is important from the testing POV
// GIVEN a forward-declared list of visitables,
struct VisitablesVariant;
// WHEN creating a visitable base,
// THEN it can be declared with an incomplete type
struct Base : VisitableFor<VisitablesVariant> {
};
// AND list of visitables can be any template list
template <typename...>
struct AnyList;
struct D1;
struct D2;
using ListOfVisitables = AnyList<D1, D2>;
// AND require complete type only when visitation is used
struct VisitablesVariant : VisitableListVariant<ListOfVisitables> {
using VisitableListVariant<ListOfVisitables>::VisitableListVariant;
};
template <typename Impl>
struct BaseImpl : VisitableImpl<Impl, Base> {
};
struct D1 : BaseImpl<D1> {
};
struct D2 : BaseImpl<D2> {
};
TEST_CASE("Visitor")
{
using std::string;
GIVEN("Polymorphic class hierarchy")
{
D2 d2{};
WHEN("object is mutable")
{
Base& b = d2;
THEN("can be visited")
{
string res =
b.visit_by(Overloaded{[](D1&) { return "D1"; }, [](D2&) { return "D2"; }});
REQUIRE(res == "D2");
}
}
WHEN("object is const")
{
const Base& b = d2;
THEN("can be visited")
{
string res = b.visit_by(
Overloaded{[](const D1&) { return "D1"; }, [](const D2&) { return "D2"; }});
REQUIRE(res == "D2");
}
}
WHEN("object is rvalue")
{
THEN("can be visited")
{
// TODO: should non-const references be allowed to bind to rvalues?
string res =
D1{}.visit_by(Overloaded{[](D1&) { return "D1"; }, [](D2&) { return "D2"; }});
REQUIRE(res == "D1");
}
}
// TODO: will constexpr ever work here?
// WHEN("object is constexpr")
// {
// constexpr const D1 d1{};
// THEN("can be visited")
// {
// constexpr int res = d1.visit_by(
// overloaded{[](const D1&) { return 1; }, [](const D2&) { return 2; }});
// STATIC_REQUIRE(res == "D2");
// }
// }
}
}
TEST_CASE("Utilities")
{
SECTION("Overloaded")
{
// TODO: add better tests.
using namespace std::string_literals;
auto sut = vstor::detail::Overloaded{
[](char) { return "char"s; },
[](int) { return "int"s; },
[](float) { return "float"s; },
};
REQUIRE("char" == sut(char{}));
REQUIRE("int" == sut(int{}));
REQUIRE("float" == sut(float{}));
}
}
} // namespace
</code></pre>
<p>And the implementation file:</p>
<pre><code>#ifndef VSTOR_HPP
#define VSTOR_HPP
#include <type_traits>
#include <variant>
namespace vstor {
namespace detail {
/**
* A commonly used template for creating lambda-based callable overload sets.
*
* @todo add possibility to set a fixed required return type
* */
template <class... Ts>
class Overloaded : public Ts... {
public:
using Ts::operator()...;
};
#if __cpp_deduction_guides < 201907L // if CTAD for aggregates and aliases not supported
template <class... Ts>
Overloaded(Ts...) -> Overloaded<Ts...>;
#endif
// TODO: implement concept: invocable_with_each_variant_option<F, VisitablesVariant>
/**
* A tag class for marking every VisitableFor<...> instance. Used instead of clunky sfinae for
* checking if a given type is a subclass of an instantiation of VisitableFor<...> template.
* */
struct VisitableFor_BaseTag {
};
template <typename T>
concept AnyVisitableFor = std::is_base_of_v<VisitableFor_BaseTag, T>;
/**
* A base class for all Visitable classes, that perform the double dispatch of the visitor pattern.
* The concrete implementations of this base participate in the first dispatch by virtual functions.
* The second dispatch is performed as a std::visit visitation of possible visitables.
*
* @tparam Variant - a maybe-incomplete class, that at the point of instantiation must be a class
* derived from VisitableListVariant<...>. Note it's not checked by any concept, because that would
* require an eager instantiation of the list of possible visitable variants, which is not intended.
* */
template <typename Variant>
class VisitableFor : public VisitableFor_BaseTag {
public:
using VisitableVariant = Variant;
virtual VisitableVariant as_variant() const noexcept = 0;
/**
* Performs visitation on 'this' by the same rules as std::visit does.
*/
template <typename Visitor>
// requires invocable_with_each_variant_option<Visitor, VisitableVariant>
decltype(auto) visit_by(Visitor&& visitor);
template <typename Visitor>
// requires invocable_with_each_variant_option<Visitor, VisitableVariant>
decltype(auto) visit_by(Visitor&& visitor) const;
};
template <typename Variant>
template <typename Visitor>
decltype(auto) VisitableFor<Variant>::visit_by(Visitor&& visitor)
{
auto invoke_visitor_after_dereference_and_deconst = [&](auto&& v) -> decltype(auto) {
// NOTE: it's safe to const_cast, because the pointee of the pointer inside the visitable
// variant is in fact 'this', so it has the same cv-qualification
using NonConstVisitable = std::remove_cvref_t<decltype(*std::forward<decltype(v)>(v))>;
return std::invoke(std::forward<Visitor>(visitor),
const_cast<NonConstVisitable&>(*std::forward<decltype(v)>(v)));
};
// NOTE: the whole pattern cannot be noexcept friendly due to std::visit possibly throwing
return std::visit(invoke_visitor_after_dereference_and_deconst, as_variant().as_std_variant());
}
template <typename Variant>
template <typename Visitor>
decltype(auto) VisitableFor<Variant>::visit_by(Visitor&& visitor) const
{
auto invoke_visitor_after_dereference = [&](auto&& v) -> decltype(auto) {
return std::invoke(std::forward<Visitor>(visitor), *std::forward<decltype(v)>(v));
};
return std::visit(invoke_visitor_after_dereference, as_variant().as_std_variant());
}
/**
* Base class for the concrete visitable implementation.
*
* @tparam CrtpImpl - CRTP class that must be a part of the previously-defined VisitableVariant.
* It's incomplete due to CRTP usage.
*
* @tparam Base - The concrete VisitableFor<...> base class this implementation is based on.
* */
template <typename CrtpImpl, AnyVisitableFor Base>
class VisitableImpl : public Base {
public:
using VisitableVariant = typename Base::VisitableVariant;
/**
* This method is const, without any non-const overload for the following reason: the
* return value can be incomplete until used. The return value for a non-const overload would
* need to differ from the const overload. Doing that with type traits would require a complete
* VisitableVariant class, which we want to avoid, so the end user would need to provide 2
* incomplete VisitableVariants that would differ from each other only with the possible variant
* being const. Instead, we const_cast the const away in case we know the instance being worked
* with is in fact non-const.
*
* @returns 'this' as one of the possible variant options.
* */
VisitableVariant as_variant() const noexcept final
{
return VisitableVariant{static_cast<const CrtpImpl*>(this)};
}
};
template <typename... Args>
using StdVariantBase = std::variant<const Args* const...>;
/**
* Base class for aggregating maybe-incomplete classes possible for visitation.
*
* @tparam Visitables - a variadic list of maybe-incomplete visitables.
* */
template <typename... Visitables>
class VisitableListVariant : private StdVariantBase<Visitables...> {
public:
using VariantBase = StdVariantBase<Visitables...>;
using VariantBase::VariantBase;
VariantBase& as_std_variant() & noexcept { return *this; }
const VariantBase& as_std_variant() const& noexcept { return *this; }
};
/**
* Specialization of VisitableListVariant that unfolds any list-like template into a proper
* VisitableListVariant. It's intended to be used in case the user is keeping the visitable classes
* as some templated list for any reason.
*
* @tparam AnyList - any template in a form of TemplateName<T1, T2, ...>,
* ex: 'std::variant<T1, T2>' or 'boost::mpl::list<T1, T2>'
* */
template <template <typename...> typename AnyList, typename... Visitables>
class VisitableListVariant<AnyList<Visitables...>> : public VisitableListVariant<Visitables...> {
public:
using VisitableListVariant<Visitables...>::VisitableListVariant;
};
} // namespace detail
using detail::Overloaded;
using detail::VisitableFor;
using detail::VisitableImpl;
using detail::VisitableListVariant;
} // namespace vstor
#endif // VSTOR_HPP
</code></pre>
<p>I'd value any concrete feedback.</p>
|
[] |
[
{
"body": "<pre><code>// Specialization of VisitableListVariant that unfolds any list-like template\n</code></pre>\n<p>You don't want this. Imagine what happens when someone inherits from <code>VisitableListVariant<std::string, int></code> versus when they inherit from <code>VisitableListVariant<std::string></code> alone. (Recall that <code>std::string</code> is of the form <code>TT<char, std::char_traits<char>, std::allocator<char>></code>; so it will match this specialization.)</p>\n<p>You don't need this specialization — parameter packs can be passed around without wrapping, just fine. And it's harmful. So eliminate it.</p>\n<p>Your test code is <em>crazy</em> convoluted. With all the comments removed, it's like this:</p>\n<pre><code>struct VisitablesVariant;\nstruct Base : VisitableFor<VisitablesVariant> {};\ntemplate <typename...> struct AnyList;\nstruct D1;\nstruct D2;\nusing ListOfVisitables = AnyList<D1, D2>;\n\nstruct VisitablesVariant : VisitableListVariant<ListOfVisitables> {\n using VisitableListVariant<ListOfVisitables>::VisitableListVariant;\n};\n\ntemplate <typename Impl> struct BaseImpl : VisitableImpl<Impl, Base> {};\nstruct D1 : BaseImpl<D1> {};\nstruct D2 : BaseImpl<D2> {};\n</code></pre>\n<p>Disentangled, IIUC, it'd be like this:</p>\n<pre><code>struct D1;\nstruct D2;\nstruct Base : VisitableFor<VisitableListVariant<D1, D2>> {};\nstruct D1 : VisitableImpl<D1, Base> {};\nstruct D2 : VisitableImpl<D2, Base> {};\n</code></pre>\n<p>And I would rather see something like this:</p>\n<pre><code>struct D1;\nstruct D2;\nstruct Base : Visitable<D1, D2> {};\nstruct D1 : Base {};\nstruct D2 : Base {};\n</code></pre>\n<p>Implementation of this "cleaner" design is left as an exercise for the reader.</p>\n<hr />\n<p>If you're using this <em>only</em> for visiting polymorphic hierarchies, you might be interested in this alternative design: <a href=\"https://quuxplusone.github.io/blog/2020/09/29/oop-visit/\" rel=\"nofollow noreferrer\">https://quuxplusone.github.io/blog/2020/09/29/oop-visit/</a></p>\n<pre><code>struct Base { virtual ~Base() = default; };\nstruct D1 : Base {};\nstruct D2 : Base {};\n\nconst Base& b = d2;\nstd::string_view sv = my::visit<D1, D2>(b, Overloaded{\n [](const D1& d1) { return "d1"; },\n [](const D2& d2) { return "d2"; },\n});\nassert(sv == "d2");\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-28T12:33:10.103",
"Id": "500898",
"Score": "0",
"body": "Thanks for the feedback!\nThat's a valid point about list-like specializations being harmful."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-28T12:36:07.530",
"Id": "500899",
"Score": "0",
"body": "> Disentangled, IIUC, it'd be like this:\n> ```\n> ...\n> struct Base : VisitableFor<VisitableListVariant<D1, D2>> {};\n> ...\n> ```\nI'm afraid you've not understood that correctly. Such a design would require the base declaration to know the full declaration of the list of all its visitables, which is not intended. That's why `VisitablesVariant` is forward-declared for the `Base` declaration. The test comments are clunky, but try to state that requirement. It's hard to express the requirements of physical design in unit tests, but I might improve it, so thanks for showing it's not obvious."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-28T14:12:04.143",
"Id": "500915",
"Score": "0",
"body": "Thanks for linking the blog post. Great stuff. I'll compare to your approach. From the first look, from the physical design perspective your solution looks as decoupled as I wanted it to be in the call site. However, you allow for cast errors in runtime, which I wanted disallowed by compilation."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-28T14:13:18.563",
"Id": "500916",
"Score": "0",
"body": "I'm also interested how the performance would compare between your and mine approach. I'll add some tests when I find a minute."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-28T18:47:35.070",
"Id": "500938",
"Score": "1",
"body": "Okay, I've played with it in Godbolt a bit. https://godbolt.org/z/ofq986 Take a look at my rearranging of the test's pieces (I still think your way is \"tangled\" and I'm \"disentangling\" it), and also IMO I've improved the indentation on the `Overloaded` stuff. (I also had to `#include <functional>`, and declare the deduction guide unconditionally for GCC's benefit.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-30T11:34:13.370",
"Id": "501085",
"Score": "0",
"body": "Thank you for your time. I'll apply your suggestions on github. Regards!"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-28T05:28:45.947",
"Id": "253985",
"ParentId": "253827",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-23T15:36:36.553",
"Id": "253827",
"Score": "5",
"Tags": [
"c++",
"design-patterns",
"library",
"c++20",
"visitor-pattern"
],
"Title": "Generic Visitor pattern library for polymorphic virtual class hierarchies"
}
|
253827
|
<p>I want to create a script that displays the rating of movie directors for a user on IMDB.</p>
<p>After some research, I realized that there is no free API for making such a list.</p>
<p>The only option is to export a list of users rating for every movie, TV show etc.</p>
<p>The initial list is in CSV, in the script. I make some calculations and write the list to file in XLSX format.</p>
<p>I've been working with Python for 2-3 years now.</p>
<p>I'm trying to follow 100 symbols per line convention. I'm following the 4-space indent convention and it looks much clearer.</p>
<p>Using Java 8.</p>
<p>Sample input - <a href="https://yadi.sk/d/pHZA_-jBo1TK6A" rel="nofollow noreferrer">https://yadi.sk/d/pHZA_-jBo1TK6A</a>
Sample output - <a href="https://yadi.sk/i/sXUk8VaH7c3HAg" rel="nofollow noreferrer">https://yadi.sk/i/sXUk8VaH7c3HAg</a></p>
<pre><code>package directors;
import java.awt.Desktop;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.*;
import com.opencsv.CSVReader;
import com.opencsv.exceptions.CsvValidationException;
class App {
private static final List<String> XLS_COLUMNS =
Stream.of("director", "adjustedRating", "count", "ratingsSum", "movies", "averageRating")
.collect(Collectors.toList());
private static final List<String> KEYS =
Stream.of("myRating", "title", "titleType", "directorsName").collect(Collectors.toList());
private static final List<Integer> VALUES = Stream.of(1, 3, 5, 12).collect(Collectors.toList());
private static final Map<String, Integer> CSV_COLUMNS = createMap(KEYS, VALUES);
private static final String ENCODING = "cp1252",
INPUT_FILENAME = "files/ratings.csv",
MOVIE_TITLE_TYPE = "movie",
OUTPUT_FILENAME = "workbook.xlsx",
SHEET_NAME = "new sheet",
SORT_BY = "adjustedRating";
private static final Integer NUMBER_OF_HEADER_ROWS = 1;
private static final Double COEFFICIENT_ONE = 2.0;
private static final Double COEFFICIENT_TWO = 4.0;
private static final int[] COLUMN_WIDTHS = {40*256, 15*256, 15*256, 15*256, 50*256, 15*256};
private static final Map<String, Integer> createMap(List<String> keys, List<Integer> values) {
Map<String, Integer> map = new HashMap<>();
Integer count = 0;
for (String key : keys) {
map.put(key, values.get(count));
count += 1;
}
return Collections.unmodifiableMap(map);
}
public static Map<String, Map<String, Object>> parseCsvToMap() throws FileNotFoundException,
UnsupportedEncodingException,
CsvValidationException,
IOException {
CSVReader csvFile =
new CSVReader(new InputStreamReader(new FileInputStream(INPUT_FILENAME), ENCODING));
Map<String, Map<String, Object>> directorsRating = new TreeMap<String, Map<String, Object>>();
String [] nextLine;
while ((nextLine = csvFile.readNext()) != null) {
Map<String, Object> innerMap = new LinkedHashMap<String, Object>();
if (nextLine[CSV_COLUMNS.get("titleType")].equals(MOVIE_TITLE_TYPE)) {
String directorsName = nextLine[CSV_COLUMNS.get("directorsName")];
if (directorsRating.containsKey(directorsName)) {
innerMap = directorsRating.get(directorsName);
Integer numberOfMovies = (Integer) innerMap.get(XLS_COLUMNS.get(2));
numberOfMovies++;
innerMap.put(XLS_COLUMNS.get(2), numberOfMovies);
Integer ratingsSum = (Integer) innerMap.get(XLS_COLUMNS.get(3));
ratingsSum += Integer.parseInt(nextLine[CSV_COLUMNS.get("myRating")]);
innerMap.put(XLS_COLUMNS.get(3), ratingsSum);
List<String> movies = (List<String>) innerMap.get(XLS_COLUMNS.get(4));
movies.add(nextLine[CSV_COLUMNS.get("title")]);
innerMap.put(XLS_COLUMNS.get(4), movies);
directorsRating.put(directorsName, innerMap);
} else {
innerMap.put(XLS_COLUMNS.get(1), 0.0);
innerMap.put(XLS_COLUMNS.get(2), 1);
innerMap.put(XLS_COLUMNS.get(3),
Integer.parseInt(nextLine[CSV_COLUMNS.get("myRating")]));
List<String> movies = new ArrayList<String>();
movies.add(nextLine[CSV_COLUMNS.get("title")]);
innerMap.put(XLS_COLUMNS.get(4), movies);
innerMap.put(XLS_COLUMNS.get(5), 0.0);
directorsRating.put(directorsName, innerMap);
}
}
}
return directorsRating;
}
public static void calculateRatings(Map<String, Map<String, Object>> directorsRating) {
Iterator<Map.Entry<String, Map<String, Object>>> iterator =
directorsRating.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String, Map<String, Object>> entry = iterator.next();
Map<String, Object> value = entry.getValue();
Integer ratingsSum = (Integer) value.get("ratingsSum");
Double count = ((Number) value.get("count")).doubleValue();
Double averageRating = ratingsSum / count;
Double adjustedRating;
Double coefficient;
if (count > 2) {
coefficient = COEFFICIENT_ONE;
if (count > 4) {
coefficient = COEFFICIENT_TWO;
}
Double adjustment = averageRating * ((count * coefficient) / 100);
adjustedRating = averageRating + adjustment;
} else {
adjustedRating = 0.0;
iterator.remove();
}
value.put(XLS_COLUMNS.get(5), round(averageRating, 2));
value.put(XLS_COLUMNS.get(1), round(adjustedRating, 2));
}
}
public static List<Object> getHeaders(Map<String, Map<String, Object>> directorsRating) {
List<String> keysList = getKeysList(directorsRating);
List<Object> headers = new ArrayList<Object>(directorsRating.get(keysList.get(0)).keySet());
headers.add(0, XLS_COLUMNS.get(0));
return headers;
}
public static List<String> getKeysList(Map<String, Map<String, Object>> directorsRating) {
List<String> keysList = new ArrayList<String>(directorsRating.keySet());
return keysList;
}
public static List<List<Object>> mapToNestedList(Map<String, Map<String, Object>> directorsRating) {
Integer totalRows = directorsRating.size() + NUMBER_OF_HEADER_ROWS;
List<String> keysList = getKeysList(directorsRating);
List<List<Object>> directorsRatingList = new ArrayList<List<Object>>(totalRows);
Integer count = 0;
for (Map<String, Object> value : directorsRating.values()) {
directorsRatingList.add(new ArrayList<Object>());
List<Object> innerList = directorsRatingList.get(count);
innerList.add(keysList.get(count));
count += 1;
for (Object innerValue : value.values()) {
if (innerValue instanceof List) {
innerValue = String.join(", ", (List<String>) innerValue);
}
innerList.add(innerValue);
}
}
return directorsRatingList;
}
public static void sortList(List<List<Object>> directorsRatingList) {
Integer sortByColNumber = XLS_COLUMNS.indexOf(SORT_BY);
Collections.sort(directorsRatingList, Collections.reverseOrder(Comparator.comparing(innerList ->
(Double) innerList.get(sortByColNumber))));
};
public static void writeToXlsx (List<List<Object>> directorsRatingList) throws IOException,
FileNotFoundException {
Integer rows = directorsRatingList.size();
Integer columns = directorsRatingList.get(0).size();
Workbook workbook = new XSSFWorkbook();
Sheet sheet = workbook.createSheet(SHEET_NAME);
for(int row = 0; row < rows; row++) {
sheet.createRow(row);
for(int column = 0; column < columns; column++) {
sheet.setColumnWidth(column, COLUMN_WIDTHS[column]);
sheet.getRow(row).createCell(column);
String cellValue = directorsRatingList.get(row).get(column).toString();
sheet.getRow(row).getCell(column).setCellValue(cellValue);
}
}
try (OutputStream outputFile = new FileOutputStream(OUTPUT_FILENAME)) {
workbook.write(outputFile);
}
}
public static void openFile (String filename) throws IOException {
File file = new File(filename);
Desktop.getDesktop().open(file);
}
public static double round(double value, int places) {
if (places < 0) throw new IllegalArgumentException();
BigDecimal bigDecimalValue = BigDecimal.valueOf(value);
bigDecimalValue = bigDecimalValue.setScale(places, RoundingMode.HALF_UP);
return bigDecimalValue.doubleValue();
}
public static void main(String[] args) {
Map<String, Map<String, Object>> directorsRating;
try {
directorsRating = parseCsvToMap();
} catch (CsvValidationException e) {
System.err.println("This CSV file is invalid");
return;
} catch (UnsupportedEncodingException e) {
System.err.println("The encoding is not valid");
return;
} catch (FileNotFoundException e) {
System.err.println("Please provide a filename for an existing file");
return;
} catch (IOException e) {
System.err.println("Error happened while reading CSV file");
return;
}
calculateRatings(directorsRating);
List<List<Object>> directorsRatingList = mapToNestedList(directorsRating);
sortList(directorsRatingList);
directorsRatingList.add(0, getHeaders(directorsRating));
try {
writeToXlsx(directorsRatingList);
} catch (FileNotFoundException e) {
System.err.println("Please provide a filename for an existing file");
return;
} catch (IOException e) {
System.err.println("This workbook can't be written to the output stream");
return;
}
try {
openFile(OUTPUT_FILENAME);
} catch (IOException e) {
System.err.println("File has no associated application or the application fails to be launched");
return;
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-23T21:14:07.080",
"Id": "500573",
"Score": "0",
"body": "Could you please add some sample input and output?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-24T08:40:23.223",
"Id": "500598",
"Score": "0",
"body": "@JeremyHunt Added"
}
] |
[
{
"body": "<ol>\n<li><p>Avoid using star imports. They tend to make your code fragile.</p>\n</li>\n<li><p>Strictly observe the 80 character line limit. For a start, >we< cannot read your code on Code Review without adjusting the horizontal scroll bar in the viewer.</p>\n<p>(Now if it was only you reading your code, that wouldn't matter. But you asked us to read it, so it does matter.)</p>\n</li>\n<li><p>It is better to use <code>Arrays.asList(...)</code> rather than <code>Stream.of(...).collect(...)</code> to populate a list that you don't intend to change.</p>\n</li>\n<li><p>In fact, you could then wrap it using <code>Collections.unmodifiableList</code> to avoid <em>any</em> unintentional modifications.</p>\n</li>\n<li><p>However, looking at the rest of the code, it may have need simpler if you had used arrays rather than lists for some or all of <code>XLS_COLUMNS</code>, <code>KEYS</code> and <code>VALUES</code>.</p>\n</li>\n<li><p>Use of <code>Map<String, Object></code> is a bit "code smell". The code would probably be better if that was a custom class:</p>\n<ul>\n<li>The code would probably be simpler and easier to understand.</li>\n<li>The code that uses the map could be made statically type-safe.</li>\n</ul>\n</li>\n<li><p>There are simpler ways to round to 2 decimal places than using <code>BigDecimal</code>.</p>\n</li>\n<li><p>The error messages in <code>main</code> are not particularly helpful. Depending on who the intended user is, you may be better off printing the exception message. Cases in point:</p>\n<ul>\n<li>"This CSV file is invalid" ... gives no clues as to why it is invalid.</li>\n<li>"The encoding is not valid" ... what encoding?</li>\n<li>and so on.</li>\n</ul>\n</li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-31T10:32:55.893",
"Id": "254125",
"ParentId": "253828",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "254125",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-23T15:54:02.100",
"Id": "253828",
"Score": "2",
"Tags": [
"java",
"csv"
],
"Title": "Script that makes a rating of movie directors for a user of IMDB"
}
|
253828
|
<p>Here is the problem: Verilog code and testbench for detecting the range of the input given number. If input number is between 12 to 49 then output is '1' else '0'. Range should be easily programmable.</p>
<p>I'm using EDA playground, cadence xcelium 20.09 simulator and EP wave is also present. Is it the appropriate code for the question asked? and also-</p>
<p>Does Verilog read integers normally? for example if I'm inputting a binary number then I should mention the number of bits and then the binary bit like 4b'0011. I directly inputted 12 in the if loop, so it automatically detects that it is an integer?</p>
<p>Here is the link: <a href="https://www.edaplayground.com/x/7sQM" rel="nofollow noreferrer">https://www.edaplayground.com/x/7sQM</a></p>
<h2>Design</h2>
<pre><code>module range_detect(y,x);
input [9:0]x;
output reg y;
always @(x)
begin
if(x>=12 && x<=49)
begin
y=1;
$display("Input: %d lies between 12 and 49",x);
end
else
begin
y=0;
$display("Input: %d does not lie between 12 and 49",x);
end
end
endmodule
</code></pre>
<h2>Testbench</h2>
<pre><code>module testbench;
reg [9:0]in;
wire out;
range_detect rd(out,in);
initial
begin
$dumpfile("dump.vcd");
$dumpvars(1,testbench);
in=12;
#2 in=11;
#2 in=51;
#2 in=34;
#2 in=61;
#2 in=19;
#2 in=18;
#2 $stop;
end
endmodule
</code></pre>
|
[] |
[
{
"body": "<p>Verilog is flexible with how it interprets integers. It interprets <code>5</code> and <code>4'b0101</code> as the same numeric value. Yes, it interprets <code>12</code> as an integer in the <code>if</code> statement.</p>\n<p>Your code simulates properly on <code>edaplayground</code>, and you have done a good job of separating the design code from the testbench. Here are some specific recommendations.</p>\n<p>If you want your design code to be synthesizable, it would be best to move the <code>$display</code> statements into the testbench. This requires you to replicate the logic in the testbench as well, but this is necessary when you create a testbench checker anyway.</p>\n<p>For debugging purposes, it is helpful to display the simulation time as well: <code>$time</code>.</p>\n<p>Also for debugging, it is better to dump signals throughout the hierarchy. Currently, you just dump the testbench signals. If you call <code>$dumpvars</code> without arguments, you will also get the design variables dumped to your VCD file.</p>\n<p>An alternate approach to driving specific values to your input (12, 11, 51, etc.) is to drive random values in a <code>repeat</code> loop. This allows you to easily change the number of values you drive and the range. The code <code>{$random} % 60</code> below returns a value in the range 0-59.</p>\n<p>Your <code>rd</code> instance uses connections-by-position, which is fine for a small number of ports (2), like you have. But, it is preferable to use connections-by-name to make the code more readable and to help prevent connection errors. For example: <code>.x (in)</code></p>\n<p>In your design, it is preferable to use ANSI style port declarations to cut down on duplicate port names.</p>\n<p>It is preferable to use an implicit sensitivity list <code>always @*</code> because it automatically triggers the block when the appropriate signals change. This avoids a common Verilog problem where people forget to add or remove signals from the list when they change the code body.</p>\n<p>To make the range programmable, one common way to do it is to use <code>parameter</code>s. They can be declared in both the design and the testbench. For example, you can use <code>MIN</code> and <code>MAX</code> instead of 12 and 49 (all caps is a convention). It is also helpful to add comments describing the legal values for the parameters.</p>\n<p>Here is an alternate way to code everything:</p>\n<pre><code>module range_detect (\n input [9:0] x,\n output reg y\n);\n\nparameter MIN = 12;\nparameter MAX = 49;\n\nalways @* begin\n if ((x>=MIN) && (x<=MAX)) begin\n y = 1;\n end else begin\n y = 0;\n end\nend\nendmodule\n\n\nmodule testbench;\n reg [9:0] in;\n wire out;\n\n // MIN must be smaller than MAX.\n // MAX must be smaller than 1024.\n parameter MIN = 12;\n parameter MAX = 49;\n\n range_detect #(\n .MIN (MIN),\n .MAX (MAX)\n )\n rd (\n .x (in),\n .y (out)\n );\n\n always @* begin\n if ((in>=MIN) && (in<=MAX)) begin\n $display($time, " Input: %0d lies between %0d and %0d", in, MIN, MAX);\n end else begin\n $display($time, " Input: %0d does not lie between %0d and %0d", in, MIN, MAX);\n end\n end\n\n initial begin\n $dumpfile("dump.vcd");\n $dumpvars;\n repeat (10) #2 in = {$random} % 60;\n #2;\n end\nendmodule\n</code></pre>\n<p>You can simply change the <code>parameter</code> values in the testbench and they will propagate into the design.</p>\n<hr />\n<p>I use 4-space indentation because I think it is easier to see the different levels of your code's logic.</p>\n<p>I add parentheses around terms like <code>(x>=MIN)</code> so that I never have to think about which operators have higher precedence, and it also helps me visually parse the code.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-23T18:24:05.827",
"Id": "253834",
"ParentId": "253829",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "253834",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-23T16:09:40.333",
"Id": "253829",
"Score": "4",
"Tags": [
"verilog"
],
"Title": "Range checking function"
}
|
253829
|
<p><strong>The Goal</strong> <br>
Basically, what I'm looking for is the ability to click a region below an image to trigger a <code>click()</code> event which will scroll the window to the following image.</p>
<p><strong>The Question</strong><br>
Is there a better way to do this? I've achieved the result I want, but with a whole ton of <code><divs></code>? I know there are some plugins out there but I'd like to do it without including a large library.</p>
<p><strong>The progress...</strong><br>
I've done this by placing several "invisible" <code><div></code> elements around the image which are bound to click events. Later on I'll try to work through left, right, and top scrolling.</p>
<p>A live preview is available <a href="http://t0scale.github.io/brute-learning" rel="nofollow noreferrer">here</a>.</p>
<p>Here is the code:</p>
<pre><code>...
<div id="projimgarray">
<div class="main-proj">
<div class="topclick"></div>
<div class="bottomclick"></div>
<div class="leftclick"></div>
<div class="rightclick"></div>
<imG class="main-proj-img" src="https://picsum.photos/800/600">
</div>
<div class="main-proj">
<div class="topclick"></div> // these are the "invisible divs"
<div class="bottomclick"></div>
<div class="leftclick"></div>
<div class="rightclick"></div>
<img class="main-proj-img" src="https://picsum.photos/801/600">
</div>
</code></pre>
<pre><code>$("document").ready(function() {
$(".bottomclick").click(function() {
console.log("Scroll jquery is working");
$( this ).parent().addClass("activeproj");
let $target = $(".activeproj").next(".main-proj");
if ($target.length == 0 )
$target = $(".main-proj:first");
$([document.documentElement, document.body]).animate({
scrollTop: $($target).offset().top
}, 2000);
$('.activeproj').removeClass('activeproj');
});
});
</code></pre>
|
[] |
[
{
"body": "<p>I think the overall approach of having lots of <code><div></code>s to act as clickable areas is just fine. An alternative is to dynamically calculate the position of a click on <code>main-proj</code> and see if it's sufficiently in one of the directions to count as an intent to scroll, but that's more complicated and more prone to breakage than having separate divs.</p>\n<p>Don't be afraid of WET HTML markup in the rendered output. It's perfectly normal and isn't inelegant or indicative of a problem. It's true that having huge numbers of DOM nodes on a page can slow things down, but 4 extra <code><div></code>s for each image isn't incredibly likely to be a tipping point for that - and if it does turn out to be one, consider changing the page so that only a reasonable number of <code>.main-proj</code>s are rendered at a time, like 50 or 100, but not much more than that.</p>\n<p>That said, it would be good to avoid WET HTML in your <em>source code</em> if possible, if feasible given your setup - you don't want to copy-paste those 7 lines of</p>\n<pre><code><div class="main-proj">\n <div class="topclick"></div>\n ...\n</code></pre>\n<p>over and over again every time you want to add an image. It'll make understanding the code at a glance harder, and can make refactoring more difficult. To only write the template for such a section <em>once</em>, you can either do it server-side with a template engine, or client-side with something like React, or even with vanilla DOM methods like <code>document.createElement</code>.</p>\n<p>Another thing to consider - if the different clickable divs result in different functionality depending on which was clicked, that would be a great thing to indicate to the user. For example, you might want to change the color of a hovered div, perhaps with an arrow or something, to give the user a visual indicator of what will happen when clicked. This is trivial to achieve with separate <code><div></code>s, but annoyingly complicated without it. (If you <em>don't</em> give the user a visual indicator of the difference between clicks on different sections of <code>.main-proj</code>, it's probably not as user-friendly as it should be.)</p>\n<p>Other suggestions regarding your code:</p>\n<p><strong>Use <code>const</code>, avoid <code>let</code></strong> - see <a href=\"https://softwareengineering.stackexchange.com/questions/278652/how-much-should-i-be-using-let-vs-const-in-es6\">here</a>. It's good to indicate to future readers of the code (often including yourself) that a variable will not be reassigned.</p>\n<p><strong>Don't re-select elements you already have a reference to</strong> - you don't need to select the <code>.activeproj</code> again, select the <em>parent</em> again instead, or save it in a variable:</p>\n<pre><code>const $thisProj = $(this).parent();\n// do you want to remove .activeproj from other elements at this point?\n// or, if activeproj isn't used in the CSS, you could remove it completely\n$thisProj.addClass('.activeproj');\nconst $target = $thisProj.next('.main-proj');\n// ...\n</code></pre>\n<p>Unless you have other kinds of children in this <code>projimgarray</code> (I think you shouldn't), you can also omit the parameter to <code>.next</code>.</p>\n<p><strong>No need to wrap a jQuery object in jQuery again</strong> This:</p>\n<pre><code>scrollTop: $($target).offset().top\n</code></pre>\n<p>can be</p>\n<pre><code>scrollTop: $target.offset().top\n</code></pre>\n<p><strong><code>projimgarray</code>?</strong> Arrays are a JavaScript construct. DOM elmements aren't really arrays. Perhaps call it something more precise, and use <code>dashed-case</code> per convention (and to make the word separations easier to understand at a glance) - maybe something like <code>all-projects</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-25T02:32:24.107",
"Id": "253887",
"ParentId": "253837",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-23T18:54:15.393",
"Id": "253837",
"Score": "2",
"Tags": [
"javascript",
"jquery",
"html"
],
"Title": "Better way to work with clickable regions of window"
}
|
253837
|
<p>If I want to "push" an array into my object inside of a property, I must first assure that this property exists - it works the same way for arrays too. However, what is the smoothest way of doing this?</p>
<p>Currently, I am first assigning the property it's first initial value so it gets made: then, since the property exists, I can push data into it.</p>
<pre><code>const result = {};
const data = [{
name: "John Doe"
},
{
name: "Doe John"
}];
const key = "helloworld";
if(result.hasOwnProperty(key)) {
result[key].push(data);
} else {
Object.assign(result, {
[key]: data
});
}
console.log(result);
</code></pre>
<p>Which gives me the following object.</p>
<pre><code>{
helloworld: [
{
name: "John Doe"
},
{
name: "Doe John"
}
]
}
</code></pre>
<p>What is the smoothest/better way to do this, if there is such a way?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-23T19:36:47.373",
"Id": "500557",
"Score": "0",
"body": "If the property already exists on the outer object, would you want the new array items to be alongside the already existing array items? Eg `{\n name: \"John Doe\"\n }, \n {\n name: \"Doe John\"\n }, { name: 'something else' }`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-23T19:43:29.720",
"Id": "500558",
"Score": "0",
"body": "@CertainPerformance Yes, that would be the idea."
}
] |
[
{
"body": "<p>The overall approach looks fine - check if the property exists on the object, and then either create the collection or append the data to the existing collection. While there are other methods than yours that achieve the same thing, none of them is <em>clearly</em> smoother or more semantically appropriate - the tools to do this more concisely just don't exist in vanilla JS yet (though there are libraries like Lodash and Underscore that implement the same sort of logic under the hood).</p>\n<p>But, <strong>your current code has a bug</strong>: if the property already exists on the object, the <code>data</code> will be pushed to the existing array <em>as a subarray</em>, rather than pushing <em>all elements of <code>data</code></em> to the existing array:</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const result = {\n helloworld: [{\n alreadyExistingProp: 'alreadyExistingVal'\n }]\n};\nconst data = [{\n name: \"John Doe\"\n},\n{\n name: \"Doe John\"\n}];\n\nconst key = \"helloworld\";\n\nif(result.hasOwnProperty(key)) {\n result[key].push(data);\n} else {\n Object.assign(result, {\n [key]: data\n });\n}\n\nconsole.log(result);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>You want a flat structure instead. Change</p>\n<pre><code>result[key].push(data);\n</code></pre>\n<p>to</p>\n<pre><code>result[key].push(...data);\n</code></pre>\n<p>A couple other pointers:</p>\n<p><strong><code>hasOwnProperty</code>?</strong> Since it sounds like the values of the object will always be truthy, you can consider making a truthy test instead of using <code>hasOwnProperty</code>:</p>\n<pre><code>if (result[key]) {\n</code></pre>\n<p><strong><code>Object.assign</code> is unnecessary when setting just a single property</strong> This:</p>\n<pre><code>Object.assign(result, {\n [key]: data\n});\n</code></pre>\n<p>can be</p>\n<pre><code>result[key] = data;\n</code></pre>\n<p><strong>Mutation worries?</strong> Note that the approach used so far will <em>mutate</em> the <code>result</code> object and the <code>data</code> array. Mutation may cause unexpected behavior and bugs elsewhere if other parts of the script have a reference to the object that gets modified. If this is something to worry about, either clone the <code>data</code> before assigning it, or immutably update the <code>result</code> variable (like how state is updated in React).</p>\n<p>For a short contrived example of how accidental mutation might result in a bug:</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const result = {};\nconst addData = (data) => {\n const key = \"helloworld\";\n if(result.hasOwnProperty(key)) {\n result[key].push(...data);\n } else {\n result[key] = data;\n }\n};\n\nconst dataFromUser = [{\n name: \"John Doe\"\n},\n{\n name: \"Doe John\"\n}];\naddData(dataFromUser);\naddData([{ name: 'Default Name' }]);\n\n\n// now the `result` object contains all the data\n// but the dataFromUser now contains an extra object, which may be a mistake:\nfor (const item of dataFromUser) {\n console.log('Name from dataFromUser:', item.name);\n}</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>This may well not be a problem for your situation, but variable contents changing unexpectedly due to mutation by code elsewhere is quite a common source of bugs in my experience.</p>\n<p>Of course, if you understand well how references to objects work, and have no problem with (or <em>like</em>) the mutation that will occur, feel free to use it.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-24T00:40:08.183",
"Id": "500585",
"Score": "0",
"body": "The *\"Mutation worries?\"* Would be valid if the OP had tagged the question with \"functional\". However in JavaScript changing an instance's state is an important powerful technique. Blanket advise against (vague cons), without the pros, of using such techniques is poor advice."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-24T00:52:29.243",
"Id": "500586",
"Score": "0",
"body": "I can't count the number of times I've seen a question on Stack Overflow with the problem stemming from the accidental mutation of an object that was expected to stay unchanged. I think it's a reasonable thing to warn to be careful about."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-24T01:23:46.427",
"Id": "500589",
"Score": "0",
"body": "Hiding a technique behind \"DO NOT USE\" does nothing to change the status quo, nor should the status quo dictate the validity of a technique.Without an unbiased explanation of the pros and cons it is just indoctrination based on subjective rather than objective reasoning, I too deal with many SO posts that do not understand references, particularly in the prevalent attitudes of \"Mutation is Evil\" preventing people from learning by using (experience)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-24T17:04:24.117",
"Id": "500663",
"Score": "0",
"body": "I am aware of the issue with mutation, especially in React - which is why I tend to go for immutable objects. Your points are completely right and I agree with them, I could just use a truthy statement instead of `hasOwnProperty` method - it's much safer indeed and all this is something I will consider in the future. As for the question, while you did come with really solid points, I feel like the other answer had more detailed explanation on the reasoning behind it."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-23T21:08:49.843",
"Id": "253849",
"ParentId": "253840",
"Score": "1"
}
},
{
"body": "<h2>Code as function</h2>\n<p>You have given code as an example. But even so always write functions as it make you think about what it is doing, and avoids experiments becoming a rambling mess.</p>\n<h2>Polymorphism</h2>\n<p>Adding properties as needed is handy in javascript as it is particularly good at polymorphism. One of its best features. It can go a long way in reducing memory overheads, reducing code complexity by avoiding the need to define inheritance, and improve productivity as a coder.</p>\n<p>This does come with additional problems that in the long run can make using this pattern counter productive.</p>\n<p>For example each time you want to access the property using this pattern forces you to repeat the predicate "Does property exist?" which becomes annoying, adds unneeded complexity and and slows down the code.</p>\n<p>For example if you want to iterate the object <code>result.helloworld</code> you will need to write</p>\n<pre><code>if (result.helloworld) {\n //...iterate\n}\n</code></pre>\n<p>While if the object came with <code>helloworld: []</code> there is no need to do the test.</p>\n<h2>Ambiguity of intent</h2>\n<p>The code is written in such a way as to make your intent impossible to know.</p>\n<p>You have added a prototype chain test <code>result.hasOwnProperty(key))</code> which indicates that you do not trust the object's state.</p>\n<p>There is no reason you have to assume all objects are in an untrusted state.</p>\n<p>Just test <code>if (obj[key])</code> rather than the verbose <code>if (obj.hasOwnProperty(key)) { </code></p>\n<p>If your intent is that of modifying an untrusted object, requiring you use <code>result.hasOwnProperty(key))</code></p>\n<p>Then if the property exists you can not then assume trust. The property as an <code>Array</code> which without trust is unknown. Calling <code>push</code> may throw an error</p>\n<p>If the object does not have the own property but rather it is further up the prototype chain adding the new property to the object will make access to an existing property difficult, forcing all code that used the existing property to check which property to use.</p>\n<h2>Rewrite</h2>\n<p>Assuming that the object is trusted.</p>\n<p>As a function</p>\n<pre><code>function addToArray(obj, name, ...data) {\n (obj[name] ?? (obj[name] = [])).push(...data);\n}\n</code></pre>\n<p>Or</p>\n<pre><code>const addToArray = (obj, name, ...data) => {\n (obj[name] ?? (obj[name] = [])).push(...data);\n}\n</code></pre>\n<p>call with</p>\n<pre><code>const o = {};\nconst data = [{A;1},{B:2}];\naddArrayToObj(o, "foo", ...data);\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-24T17:07:21.747",
"Id": "500664",
"Score": "0",
"body": "When it's possible I agree that it's good to have pre-defined properties so you don't get that issue - however, there are also cases where you're dealing with user input and you don't actually know what they're going to pass in their object; which should always be checked either way. Which brings us to the intent of the untrusted object, and I completely agree. I think the explanations you gave helped me to understand it all on a deeper level, so I don't do the same mistake in the future."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-24T02:23:57.203",
"Id": "253858",
"ParentId": "253840",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "253858",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-23T19:23:07.460",
"Id": "253840",
"Score": "0",
"Tags": [
"javascript"
],
"Title": "Pushing an array into an object with an undefined/non-existing property"
}
|
253840
|
<p>This is from a high performance server that needs to block anyone who is doing more than <code>limit</code> requests per <code>seconds</code> seconds.</p>
<p>You call <code>check</code> and if it returns true you process the request, otherwise you block it.</p>
<p>It maintains a circular queue, initialized to 0, of the last times the event was triggered.</p>
<p>I use <code>time()</code> because it is faster, in my tests, (on ubuntu) than any other clock measuring function I know of (including all of the C++ timing mechanisms), and 1 second resolution is good enough.</p>
<p>It will be wrong for a few seconds after the 1970 epoch, but I'm not terribly worried about that.</p>
<pre><code>class RateController {
int n, seconds;
time_t* q;
int i;
void push(time_t t) {
q[i] = t;
i = (i + 1) % n;
}
public:
RateController(int limit, int seconds): n(limit), seconds(seconds) {
q = new time_t[n];
memset(q, 0, sizeof(time_t) * n);
i = 0;
}
~RateController() {
delete[] q;
}
bool check() {
time_t t = time(0);
push(t);
return (t - q[i]) >= seconds;
}
};
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-23T20:14:15.890",
"Id": "500559",
"Score": "6",
"body": "This is not really c++. Basically C with a class to tie the functions together. In C++ you would/should use a `std::array` (if size known at compile time) or a `std::vector` with `reserve`. Maybe a FIFO queue is in fact what you need? ie `std::queue`\n\nYour code is probably faster, because it's basically \"raw C\". But it would be \"safer and easier\" with C++'s abstractions."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-23T20:23:34.647",
"Id": "500560",
"Score": "2",
"body": "@OliverSchönrock There is no explicit requirement to not use the C equivalents when the C++ alternative provides no tangible advantage"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-23T20:25:19.033",
"Id": "500561",
"Score": "7",
"body": "@OliverSchönrock Everything that compiles by a C++ compiler and does not compile with a C compiler is \"real C++\" IMO. We should not be dogmatic and force a specific style."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-23T20:27:56.230",
"Id": "500562",
"Score": "5",
"body": "I didn't mean to be dogmatic. And yes of course it's valid. I was simply making the point that if I had used C++ to write that I might have started by using a `std::queue` and seeing if it's \"fast enough\". If it is, leave it. If I had used C, I might have written something very similar to the above. My comment was merely meant to thought provoking, not critical."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-23T20:34:16.643",
"Id": "500564",
"Score": "2",
"body": "similarly use of `unique_ptr[]` instead of `new`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-23T20:43:18.253",
"Id": "500565",
"Score": "0",
"body": "You seem concerned about performance (use of time_t and raw arrays). Yet if your time resolution is only 1sec, and say n = 1000 and s =1. Then if you get >1000 requests per second, then the whole circular queue will fill with the same time. Then block, then when `time()` returns the next second, then the floodgates will open for another 1000 requests. Is this what you want? If it's a lot less then 1000req/s then why are worried about performance? Surely the overhead of any time call would be insignificant?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-23T20:51:16.993",
"Id": "500568",
"Score": "1",
"body": "Also consider this https://stackoverflow.com/a/2204380/1087626 instead of `memset`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-23T20:57:13.913",
"Id": "500569",
"Score": "1",
"body": "If I get 1000 requests in 1 millisecond, that is OK, and then 1000 requests in 1 millisecond, the next second, that is OK. In practice, the \"limit\" values are typically closer to 20, and the \"seconds\" values are larger than 1. I see your point regarding unnecessary optimization, but then why use a complicated setup when something smaller and simpler is available that works?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-23T20:59:04.737",
"Id": "500570",
"Score": "0",
"body": "and finally: unique_ptr[] and value (ie zero) initalisation together in one statement: https://stackoverflow.com/a/21377382/1087626\n\n`std::make_unique<time_t[]>(n);` which also removes the need for the destructor/delete."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-24T02:32:36.547",
"Id": "500590",
"Score": "3",
"body": "The reason to use C++ concepts is that they are less error prone and should not introduce any significant (or any) overhead. Using `std::vector` or `std::array` above introduces no overhead but automatically fixes several bugs that your code already has (such not obeying the rule of five)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-24T02:50:08.320",
"Id": "500591",
"Score": "0",
"body": "How does the rate controller know which user they are checking. Or do you create one per user?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-24T12:52:15.617",
"Id": "500631",
"Score": "0",
"body": "Yes, each user has its own rate controller object"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-25T06:52:39.323",
"Id": "500682",
"Score": "2",
"body": "@CaptainCodeman One may not be obliged to use C++ tools rather than C ones, but one must admit the C-ish nature of this code. Were I to see this code at work, I would *instantly* assume that it was written by a C developer who had to use C++ to fit into a larger system. I would then look for classic C pitfalls because I knew that C++ didn't have my back like it usually does."
}
] |
[
{
"body": "<p>Overall I'm going to side with Oliver's comment that</p>\n<blockquote>\n<p>This is not really c++ [...] it would be "safer and easier" with C++'s abstractions.</p>\n</blockquote>\n<p>At your scale, you haven't shown any data convincing me that performance will influence choosing "old-style C++" over new, idiomatic C++; and anyway that shouldn't be your first consideration: your first consideration should be for correctness, robustness and testability. All of those have suffered given the use of unmanaged pointers.</p>\n<p>My advice - which falls short of recommending specific C++(17|20) constructs since I'm not strong in that area - is to make it right-first, not fast-first. Write this in a style that has safe memory management practices and has solid unit test coverage, then profile it. If the performance is good enough (and I would be surprised if it isn't, but I've been wrong before) then leave it. If the performance suffers <em>and</em> it's the fault of your use of idiomatic C++ <em>and</em> reverting to unsafe memory management solves the problem, then fine - revert the slow pieces.</p>\n<p>Put another way, you're either going to pay the cost of using newer C++ abstractions to play with memory safely, or you're going to pay in engineering time poring over Valgrind dumps.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-24T14:40:36.183",
"Id": "500646",
"Score": "0",
"body": "Thank you for your valuable suggestions. I have switched to vector. I am curious, though, you mentioned \"unchecked allocation\"; does C++ throw an exception if vector allocation fails?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-26T11:37:47.393",
"Id": "500758",
"Score": "0",
"body": "You should expect the same `std::bad_alloc` as from `new` if vector allocation fails, so no need to change the exception handling in the calling code. I'm not sure what this review is referring to by \"unchecked allocation\", either."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-26T14:25:49.350",
"Id": "500772",
"Score": "0",
"body": "@TobySpeight Poor wording; I've dropped that phrase."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-23T21:47:22.193",
"Id": "253851",
"ParentId": "253841",
"Score": "8"
}
},
{
"body": "<p>First of all, I'd at least consider doing this a bit differently. Since multiple requests per second is entirely possible, I'd at least consider keeping a count of the number of requests in a given second:</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>struct count { \n std::time_t t;\n std::size_t count;\n};\n</code></pre>\n<p>With this, I'd probably also keep a running count of the number of requests in the last N seconds. Anytime you get a <code>time_t</code> different from the most recent on record, you add a new <code>count</code> record to your list, and check whether you have any old records to remove from the list. If so, subtract the count for each of them from your current count as you remove them.</p>\n<p>But a bit here depends on how fast you really expect to receive requests. If you could have multiple incoming requests per second, this is likely to be a useful optimization. If you're expecting more on the order of multiple seconds between requests, it may be a waste of time.</p>\n<p>Assuming we ignore that and stick to some variant of the current design, I'd start by observing that your class really has two rather separate responsibilities. One is keep track of time and timeouts and figuring out whether a request is allowed or not. The other is maintaining a circular buffer you use to implement that.</p>\n<p>I'd try to decouple those, such as using a relatively generic circular buffer, and then a class to enforce the timeout that's implemented using the circular buffer.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-24T14:26:47.797",
"Id": "500641",
"Score": "0",
"body": "The problem with this is that you may have to clear N records in one go, if some time has passed since the last request. (Unless I misunderstood?)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-23T21:51:53.183",
"Id": "253852",
"ParentId": "253841",
"Score": "4"
}
},
{
"body": "<p>As per my comments under your question, I would suggest that you use some C++ abstractions to do the "heavy" lifting for you. eg don't do your own memory allocation with <code>new</code> nor your own initialisation with <code>memset</code>.</p>\n<p>Consider using a standard container. If in doubt use <code>std:vector</code>. You could also use <code>std::make_unique</code> to initialise an array, but why? Either way you now don't need a destructor. That's a bigger gain than it seems, because without the destructor, you can comply with the "Rule of zero". With the destructor (ie doing your own resource mgmt) you really need to comply with the "Rule of five", and your current code does not, causing potentially serious bugs as @henje nicely demonstrates below.</p>\n<p>Use <code>std::chrono</code>: it's really powerful, makes for easy to read code and allows you to easily adjust the resolution of your <code>RateController</code>. The overhead is unlikely to be an issue unless you are talking millions of requests per seconds per <code>RateController</code>.</p>\n<p>While testing I found that your code has a bug: in <code>check()</code> you need to test if the comparison is true before calling <code>push()</code>, or you constantly overwrite your circular buffer and block the system.</p>\n<p>For style designate your member variables by postfixing them with <code>_</code> or similar so they are easy to identify. I like to put the public interface first in a class, but it's getting heavily subjective now.</p>\n<p>Suggested use of C++ abstractions:</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>#include <chrono>\n#include <vector>\n\nclass RateController {\n using clk_t = std::chrono::system_clock;\n using time_point_t = std::chrono::time_point<clk_t>;\n\npublic:\n RateController(unsigned limit, unsigned long milliseconds)\n : n_(limit), milliseconds_(milliseconds),\n q(n_, time_point_t()) {}\n\n bool check() {\n time_point_t t = clk_t::now();\n bool allowed = t - q[i_] >= std::chrono::milliseconds(milliseconds_);\n if (allowed) push(t);\n return allowed;\n }\n\nprivate:\n unsigned n_;\n unsigned long milliseconds_;\n unsigned i_ = 0;\n\n std::vector<time_point_t> q;\n\n void push(time_point_t t) {\n q[i_] = t;\n i_ = (i_ + 1) % n_;\n }\n};\n</code></pre>\n<p>Algorithmically, your circular buffer idea could certainly work well, but it's quite a lot of storage, if you have many requests per interval. It depends on your use case.</p>\n<p>If you have many throusands of clients and therefore many <code>RateController</code> instances then perhaps you don't want to store 1000 x 8byte <code>unsigned long</code>s (8k) for each one? In that case you could just divide time into predetermined slots (say every 10 minutes) and for each client just keep the time of last request and the number of requests in the current time slice. That would be ~500x less storage? This is similar to what @JerryCoffin was suggesting.</p>\n<p>Below is a version which uses the <code>time_slice</code> idea. It basically revolves around an integer division. No more <code>vector</code> or other circular buffer. The behaviour is not identical, but I prefer this one.</p>\n<p>If you are concerned that thousands of these RateController instances will all unblock at the same time when the new time slice starts and hence cause a load spike, you can address that too. Just generate a random offset in the range [0, time_slice_seconds) during construction and add it to the current time before doing the integer division. If you do this, I can no longer see the advantage of the circular buffer.</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>#include <chrono>\n\nclass RateController {\n using clk_t = std::chrono::system_clock;\n\npublic:\n RateController(unsigned limit, long time_slice_seconds)\n : n_(limit), time_slice_(time_slice_seconds) {}\n\n bool check() {\n auto duration_since_epoch = clk_t::now().time_since_epoch();\n long curr_time_slice =\n std::chrono::duration_cast<std::chrono::seconds>(duration_since_epoch).count() /\n time_slice_; // integer division!\n\n if (curr_time_slice != last_time_slice_) {\n last_time_slice_ = curr_time_slice;\n count_ = 0;\n }\n ++count_;\n return (count_ <= n_);\n }\n\nprivate:\n unsigned n_;\n long time_slice_;\n long last_time_slice_ = 0;\n unsigned count_ = 0;\n ;\n};\n\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-24T09:53:12.730",
"Id": "500605",
"Score": "4",
"body": "I don't recommend those names beginning with `_`, as they are reserved for the implementation in many contexts."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-24T10:09:39.953",
"Id": "500607",
"Score": "0",
"body": "I think it's fine for member variables if single underscore is followed by a lower case letter, which it always is for me. But I am still looking for the \"ultimate convention\" on this. Unfortunately there seems to be little consensus on this. What do you use?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-24T10:15:32.447",
"Id": "500608",
"Score": "1",
"body": "@TobySpeight I changed it to postfix underscore. Is that better?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-24T10:24:19.130",
"Id": "500609",
"Score": "1",
"body": "In personal projects, I don't do Hungarian-style markers (it's a good incentive to keep things simple). At work, I inherited a project that uses `m_` prefix, so my new code there is consistent with the existing. The real danger of course is `_` followed by uppercase, or `__` anywhere in the identifier - implementations can use those for any purpose, including macros."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-24T14:35:55.840",
"Id": "500643",
"Score": "1",
"body": "Thank you very much for your detailed analysis and excellent suggestions; I have already incorporated most of them. I will say, however, that maintaining a queue is necessary to be able to correctly support short bursts which would otherwise overflow a strictly count-based algorithm. Even nginx uses a queue for rate limiting (it maintains a separate queue per remote IP)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-24T14:37:31.083",
"Id": "500645",
"Score": "1",
"body": "Curious, in the constructor, is there a reason to write `q(std::vector<time_point_t>(n_, time_point_t()))` instead of `q(n_, time_point_t())` ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-24T16:17:21.210",
"Id": "500656",
"Score": "0",
"body": "yes, the behaviour is not the same, the queue may work better for your use, ...and yes, that's my bad the initalisation list item for `q` can take the constructor arguments directly, I will ammend. It makes little perf differeny (due to move constructor), but certainly cleaner the way you suggest."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-09T13:48:36.763",
"Id": "501920",
"Score": "0",
"body": "@CaptainCodeman Reviewing this answer and the comments I do not understand what you mean by \"maintaining a queue is necessary to be able to correctly support short bursts which would otherwise overflow a strictly count-based algorithm\". Can you explain? Note that I have added a paragraph above on random offsets for the timeslices."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-10T14:20:40.243",
"Id": "501956",
"Score": "0",
"body": "@OliverSchönrock For instance, you want to allow a user to make 2 requests / second on average, but when loading a page they will make 20 requests in one second."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-10T18:37:52.657",
"Id": "501965",
"Score": "0",
"body": "@CaptainCodeman OK, but how does the circular buffer do something here which the time_slice does not? In both cases the page load will be spread over 20s, right?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-12T13:14:01.013",
"Id": "502098",
"Score": "0",
"body": "@OliverSchönrock There will be slight differences in behavior; for example you want to limit the rate to 15/minute so your time slice is 60 seconds and the limit/slice is 15. You could have 10 requests come in at 0:59 and then 10 more requests come in, 2 seconds later at 0:01, so you will allow 20 requests within 3 seconds and that technically breaks the 15/minute rate -- the queue version would handle this correctly. (Arguably it perhaps does not matter for most purposes, but if you must absolutely adhere to some exact rate for some reason, the timeslice method can be incorrect)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-12T16:08:02.070",
"Id": "502111",
"Score": "0",
"body": "@CaptainCodeman Yes correct. However, this is unrealistic on average. Much more likely that (on average across many clients) the ones that are hungry will take up their quota at start of slice. With randomised start you will get a uniform load distribution.\n\nIf your goal is to \"smooth load peaks\" and get a \"steady work load\" and if you have more than 100 clients, then (assuming you randomise) statistics will ensure that your load is just as smooth as for the circular buffer.\n\nThe case for \"over those 2 seconds it's too much\", seems pedantic because over 2 mins it's correct."
}
],
"meta_data": {
"CommentCount": "12",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-23T23:03:27.760",
"Id": "253856",
"ParentId": "253841",
"Score": "7"
}
},
{
"body": "<p>This looks more like C code than C++. I echo the other reviewers: use the abstractions that are available to you (and understand how they work, to have a grasp on the performance characteristics).</p>\n<p>However, if you <em>are</em> using C functions in your C++ code, prefer to use the native C++ headers <code><ctime></code> and <code><cstring></code> rather than <code><time.h></code> and <code><string.h></code>. Then you get neatly namespaced versions of the identifiers you use:</p>\n<ul>\n<li><code>std::time_t</code></li>\n<li><code>std::time()</code></li>\n<li><code>std::memset()</code></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-25T11:22:50.703",
"Id": "500698",
"Score": "0",
"body": "<ctime> is allowed to dump the same identifiers in the global namespace as well, and most implementations do.So your advice doesn't help. Actually, a better advice is to use a C++ container and the C++ <chrono> header, as other answers say."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-26T11:31:51.917",
"Id": "500756",
"Score": "0",
"body": "It is indeed *allowed* to to so. But it's foolish (needlessly non-portable) to assume all targets will do that. Yes, using `<chrono>` is obviously better for the time stuff (and perhaps `std::fill()` rather than `std::memset()`), but this advice applies to all of the C standard library."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-24T10:31:16.540",
"Id": "253864",
"ParentId": "253841",
"Score": "2"
}
},
{
"body": "<p><code>time()</code> and <code>std::chrono::system_clock</code> use system time, which can change. This can cause small issues if, say, NTP changes your clock. But you'll also find that everything dies once a year in the fall when daylight saving time sends you an hour into the past. (At least if your system uses local time zones.)</p>\n<p><code>std::chrono::steady_clock</code> should avoid such issues and is likely a better choice for timing things instead of getting the actual "human" time.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-25T11:24:40.410",
"Id": "500699",
"Score": "0",
"body": "This is more a comment on another answer. However, I notice that your reputation doesn't allow you to comment and it's a helpful comment, so you are forgiven in this case :) Welcome to this site!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-25T14:02:43.987",
"Id": "500713",
"Score": "0",
"body": "That was kind of my thought process too @Sjoerd "
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-26T15:08:17.273",
"Id": "500773",
"Score": "0",
"body": "What you're alluding to is the use of a \"monotonic\" clock, called different things depending on what OS you're calling into."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-24T18:54:54.533",
"Id": "253878",
"ParentId": "253841",
"Score": "5"
}
},
{
"body": "<p>"This RateController seems handy, I can use it in my function, great!"</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>bool use_controller(RateController rate_ctr) {\n return rate_ctr.check();\n}\n\nint main() {\n RateController rate_ctr{10, 1};\n bool check = use_controller(rate_ctr);\n return rate_ctr.check() || check;\n}\n</code></pre>\n<p>"Let me just run it in my debug build, and ..., woah"</p>\n<pre><code>=================================================================\n==1==ERROR: AddressSanitizer: heap-use-after-free on address 0x607000000028 at pc 0x0000004fa54f bp 0x7fffce7fed80 sp 0x7fffce7fed78\nREAD of size 8 at 0x607000000028 thread T0\n...\n0x607000000028 is located 8 bytes inside of 80-byte region [0x607000000020,0x607000000070)\nfreed by thread T0 here:\n #0 0x4f7710 (/app/output.s+0x4f7710)\n #1 0x4fa508 (/app/output.s+0x4fa508)\n\npreviously allocated by thread T0 here:\n #0 0x4f6d48 (/app/output.s+0x4f6d48)\n #1 0x4fa4e0 (/app/output.s+0x4fa4e0)\n</code></pre>\n<p>On a more serious note, you have a bug in your code. This scenario might seem a little contrived but, in general, libraries should be easy to use and hard to misuse. One can easily misuse the controller like in my example code.</p>\n<p>The class you are implementing handles a resource and has to implement a copy-constructor and operator= to deal with copies gracefully. Alternatively, you could delete these functions to at least raise a compiler error, when the class is misused.</p>\n<p>This could have been prevented by using a more idiomatic C++ solution, like other answers have provided. Implementing a resource-handling class is not trivial and in most cases not necessary because library classes exist to handle most cases.</p>\n<p>One way to avoid this bug is to use <code>std::unique_ptr</code> which is not copyable and would make your class non-copyable as well. When you use a <code>std::vector</code> like in Oliver Schönrock's answer, the vector handles copying and allocates a new buffer for you. Then again you might want to be able to copy a controller but refer to the same queue. In this case you could use a <code>std::shared_ptr</code>.</p>\n<p>You might want to look into the rule of zero/three/five as it helps with gotchas of custom types. In general, the best way is to use library types which remove the need for you to implement special functions at all.</p>\n<p>You can try my test code <a href=\"https://godbolt.org/z/rbojEj\" rel=\"nofollow noreferrer\">here</a>. I recommend to use tools like AddressSanitizer (UBSAN, TSAN, vagrant) for catching subtle bugs.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-04T08:13:48.023",
"Id": "501507",
"Score": "0",
"body": "Thank you for your comment, you are correct, the original code doesn't handle copying correctly."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-24T21:19:57.197",
"Id": "253881",
"ParentId": "253841",
"Score": "3"
}
},
{
"body": "<p>I want to add to Oliver Schönrock's answer, and specifically address the comment you made:</p>\n<blockquote>\n<p>I will say, however, that maintaining a queue is necessary to be able to correctly support short bursts which would otherwise overflow a strictly count-based algorithm.</p>\n</blockquote>\n<p>You can support bursts without maintaining a queue, by implementing a <a href=\"https://en.wikipedia.org/wiki/Leaky_bucket\" rel=\"nofollow noreferrer\">leaky bucket</a>:</p>\n<pre><code>#include <chrono>\n\nclass RateController {\n using clock_t = std::chrono::steady_clock;\n using time_point_t = clock_t::time_point;\n using duration_t = clock_t::duration;\n\npublic:\n RateController(unsigned limit, duration_t interval)\n : limit_(limit), interval_(interval) {}\n\n bool check() {\n // Try to drain the bucket\n if (count_) {\n auto now = clock_t::now();\n auto time_passed = now - last_update_;\n auto drained = time_passed / interval_;\n\n if (drained) {\n count_ -= drained < count_ ? drained : count_;\n last_update_ = now;\n }\n }\n\n if (count_ < limit_) {\n ++count_;\n return true;\n } else {\n return false;\n }\n }\n\nprivate:\n const unsigned limit_;\n const duration_t interval_;\n time_point_t last_update_ = clock_t::now();\n unsigned count_ = 0;\n};\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-10T14:22:27.237",
"Id": "501957",
"Score": "0",
"body": "Good catch, yes you are right."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-09T17:07:10.093",
"Id": "254490",
"ParentId": "253841",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "253856",
"CommentCount": "13",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-23T19:26:55.730",
"Id": "253841",
"Score": "6",
"Tags": [
"c++"
],
"Title": "C++ Rate Controller"
}
|
253841
|
<p>C++ is not aware of the console and it's behaviour / features / options, only its <code>std::cout</code> stream. To do more than stream we need to be platform aware.</p>
<h1>Aim</h1>
<p>To conveniently write console applications which use "clear screen" and "cursor position" in a way that works correctly across *nix and Windows (MacOS is extra, but probably much the same as *nix).</p>
<p>The same function with simple signature should be callable for each feature and the correct cross-platform code will be compiled. No <code>#ifdef _WIN32</code> in main code.</p>
<h1>Questions</h1>
<ul>
<li>Feedback on code style / API / encapsulation and abstractions. The functionalily is clearly very simple.</li>
<li>"Most appropriate" error handling technique? Return <code>bool</code> for success from each API function? (see TODOs)</li>
<li>Once fleshed out, is this actually useful? Is there some public library available that I have missed?</li>
</ul>
<h1>Known TODOs</h1>
<ul>
<li>Expand functionality to colours and other display attributes</li>
<li>Error handling in the win32 code</li>
</ul>
<p><code>includes/xos/console.hpp</code></p>
<pre class="lang-cpp prettyprint-override"><code>namespace xos::console {
void move_cursor_relative(int dx, int dy);
void clear_screen();
void move_cursor_absolute(int x, int y);
} // namespace xos::console
</code></pre>
<p><code>includes/xos/console.cpp</code></p>
<pre class="lang-cpp prettyprint-override"><code>#include "console.hpp"
#include <iostream>
#include <string_view>
#ifdef _WIN32
#include <windows.h>
#endif
namespace xos::console {
namespace impl {
namespace ansi {
// ANSI Control sequences for *nix consoles
const std::string_view csi = "\x1B["; // "Control Sequence Introducer"
const std::string_view cursor_up = "A";
const std::string_view cursor_down = "B";
const std::string_view cursor_forward = "C";
const std::string_view cursor_backward = "D";
const std::string_view clear_screen = "2J";
const std::string_view home = "H";
const std::string_view cursor_pos = "H";
} // namespace ansi
// only try to compile the non-standard win32 code on windows
#ifdef _WIN32
void win32_move_cursor_relative(int dx, int dy) {
HANDLE console = GetStdHandle(STD_OUTPUT_HANDLE);
CONSOLE_SCREEN_BUFFER_INFO screen;
GetConsoleScreenBufferInfo(console, &screen);
COORD cursorPos = screen.dwCursorPosition;
cursorPos.X += dx;
cursorPos.Y += dy;
SetConsoleCursorPosition(console, cursorPos);
}
void win32_console_clear_screen() {
COORD topLeft = {0, 0};
HANDLE console = GetStdHandle(STD_OUTPUT_HANDLE);
CONSOLE_SCREEN_BUFFER_INFO screen;
DWORD written;
GetConsoleScreenBufferInfo(console, &screen);
FillConsoleOutputCharacterA(console, ' ', screen.dwSize.X * screen.dwSize.Y, topLeft, &written);
FillConsoleOutputAttribute(console, FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE,
screen.dwSize.X * screen.dwSize.Y, topLeft, &written);
SetConsoleCursorPosition(console, topLeft);
}
#endif
void nix_move_cursor_relative(int dx, int dy) {
if (dx != 0) {
std::cout << ansi::csi;
if (dx > 0)
std::cout << dx << ansi::cursor_forward;
else
std::cout << -dx << ansi::cursor_backward;
}
if (dy != 0) {
std::cout << ansi::csi;
if (dy > 0)
std::cout << dy << ansi::cursor_down; // +ve == down for consistency with win32
else
std::cout << -dy << ansi::cursor_up;
}
}
} // namespace impl
/**
* @brief platform independent console cursor relative movement
* @details works on *nix, macOS and Windows
* @param int dx +ve is right
* @param int dy +ve is down
*/
void move_cursor_relative(int dx, int dy) {
#ifdef _WIN32
impl::win32_move_cursor_relative(dx, dy);
#else
impl::nix_move_cursor_relative(dx, dy);
#endif
}
/**
* @brief platform independent console cursor absolute movement
* @details works on *nix, macOS and Windows
* @param int x 0 is top leftmost column
* @param int y 0 is top row
*/
void move_cursor_absolute(int x, int y) {
#ifdef _WIN32
HANDLE console = GetStdHandle(STD_OUTPUT_HANDLE);
COORD cursorPos = {x, y};
SetConsoleCursorPosition(console, cursorPos);
#else
// ansi code is 1 based - stick to zero based for consistency
std::cout << impl::ansi::csi << (y + 1) << ';' << (x + 1) << impl::ansi::cursor_pos;
#endif
}
/**
* @brief platform independent console clear screen
* @details clear visible console (not scrollback) and moves home (1, 1)
*/
void clear_screen() {
#ifdef _WIN32
impl::win32_console_clear_screen();
#else
std::cout << impl::ansi::csi << impl::ansi::clear_screen;
std::cout << impl::ansi::csi << impl::ansi::home;
#endif
}
} // namespace xos::console
</code></pre>
<p><code>main.cpp</code></p>
<pre class="lang-cpp prettyprint-override"><code>#include xos/console.hpp
#include <iostream>
int main() {
xos::console::clear_screen();
xos::console::move_cursor_relative(2, 2); // relative(2 right, 2 down)
std::cout << "hello";
xos::console::move_cursor_absolute(20, 4); // @(20 right, 4 down)
std::cout << "there";
return EXIT_SUCCESS;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-24T06:33:46.593",
"Id": "500594",
"Score": "0",
"body": "hmm, Windows version requires console creation, no? Also this really could benefit from defunctionalization for sake of reducing number of calls."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-24T10:01:41.740",
"Id": "500606",
"Score": "0",
"body": "Not sure what you mean on console creation. It runs fine on windows and *nix for me. Is MSVC hiding some magic from me? Re call graph: I thought about that, but went for readibility, given any I/O is super slow anyway and the compiler should inline redundant calls for me?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-24T10:32:25.170",
"Id": "500610",
"Score": "2",
"body": "Is Curses or Termcap not already available on the platforms you care about? Even if not, I recommend using it where available, so you don't need to inspect `$TERM` to choose the correct escape sequences yourself. Remember that console need not be a local terminal!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-25T17:04:30.123",
"Id": "500718",
"Score": "0",
"body": "redunant api call won't be optimized, they are calls to .dll with side-effects on each. The console would work only if app is run from console. If you wan't it be standalone, you have to create console window (certain types of VS projects elide that requirement). Note, only one active console window per process is allowed"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-25T18:14:54.747",
"Id": "500720",
"Score": "0",
"body": "@Swift I think the double call within the object file (or .dll if you want to call it that) will be inlined with any decent compiler. The external call will not, but that's always the case? \n\nWill look at the VS magic that's obviously going on (I know almost nothing about it)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-25T18:18:12.453",
"Id": "500721",
"Score": "0",
"body": "@TobySpeight See discussion under accepted answer re curses flavours. I have used curses before but not tried to compile against a different flavour of curses per target platform. Is that commonly done?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-26T00:13:44.437",
"Id": "500732",
"Score": "0",
"body": "@OliverSchonrock .dll is shared linkable object separate from program. By \"as if\" rule that's not possible, it's equivalent of acess to volatile variables\\IO operations. Every call to GetStdHandle and such is separate call, etc. Within module that's different and depends how compilation units designed, but same rules apply, no magic there . Inlining isn't replacement of double calls , it's elision of creating new frame, it's not always beneficial (essentially called function gets merged into caller if possible and they have small footprint- they must be in same unit, etc)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-26T12:48:22.627",
"Id": "500765",
"Score": "0",
"body": "@Swift Yes, it's equivalent to a `.so` (shared object) in *nix/ELF, and I know all that. TBH: It's really irrelevant for me. Premature optimisation, IMO. If it ever became important it could be easily addressed within the `.so`/`.dll`"
}
] |
[
{
"body": "<p>There's an excellent article about <a href=\"https://www.cplusplus.com/articles/4z18T05o/\" rel=\"nofollow noreferrer\">clearing the screen</a> on cplusplus.com. It looks like what you are doing is what they recommend, if clearing the screen and moving the cursor are the only two things you want to do. Otherwise, one should use an existing library like (a modern version of) <a href=\"https://en.wikipedia.org/wiki/Curses_(programming_library)\" rel=\"nofollow noreferrer\">curses</a>.</p>\n<h1>Answers to your questions</h1>\n<blockquote>\n<p>Feedback on code style / API / encapsulation and abstractions. The functionalily is clearly very simple.</p>\n</blockquote>\n<p>The API is fine. However, I don't particularly think the namespaces are done right or used consistently. Why is <code>move_cursor_relative()</code> calling <code>impl::</code> functions, but <code>move_cursor_absolute()</code> is doing things directly?</p>\n<p>I would rather organize the code like so:</p>\n<pre><code>namespace impl {\n#ifdef _WIN32\nvoid console_clear_screen() {/* Windows implementation here */}\nvoid move_cursor_absolute(int x, int y) {...}\nvoid move_cursor_relative(int dx, int dy) {...}\n#else\nvoid console_clear_screen() {/* Unix implementation here */}\nvoid move_cursor_absolute(int x, int y) {...}\nvoid move_cursor_relative(int dx, int dy) {...}\n#endif\n}\n</code></pre>\n<p>Or just forget about <code>namespace impl</code>, and put all the code directly into the API functions inside <code>console.cpp</code>, since I don't think the <code>impl</code> namespace is adding any value here. Maybe if the code gets more complex, but until then: <a href=\"https://en.wikipedia.org/wiki/You_aren%27t_gonna_need_it\" rel=\"nofollow noreferrer\">YAGNI</a>.</p>\n<p>Note that I do like that you put the API in its own namespace, this avoids polluting the global namespace of course, and users can always do <code>using namespace xos::console</code> if they want.</p>\n<blockquote>\n<p>"Most appropriate" error handling technique? Return bool for success from each API function? (see TODOs)</p>\n</blockquote>\n<p>You could indeed add a <code>bool</code> return value, or consider the fact that not being able to output to the screen is so exceptional that you should... throw an exception. As a user, I probably won't care about the screen not clearing properly, by that time there are bigger problems. I wouldn't want to add error handling for each call to these functions. The only time I want to be really conscious about this is when you really want to clear the screen because there is some sensitive information on it, and then you don't want the error condition to be accidentily ignored. So I would lean towards using exceptions here.</p>\n<blockquote>\n<p>Once fleshed out, is this actually useful? Is there some public library available that I have missed?</p>\n</blockquote>\n<p>Yes, this is very useful, and in fact there are the various curses libraries that are out there that solve exactly this issue, as well as the colour and display attributes mentioned in your list of TODOs, and many more things.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-24T11:28:31.843",
"Id": "500615",
"Score": "0",
"body": "Thanks. I am aware of ncurses and have used it. Very old style C-API. Is there a \"properly modern\" one? Like actually C++? \n\nAlso ncurses may be overkill for the more minimalist use-case I had in mind.\n\nI did debate the namespace hierarchy, and appreciate your thoughts."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-24T11:41:49.617",
"Id": "500616",
"Score": "0",
"body": "You say \"minimalist use-case\" but then have colour and attributes in your TODO :) Ncurses comes with a C++ interface, although it's just slapping `class`es on top of the C API as expected. A quick search shows that there are several C++ wrappers around ncurses out there, [this one](https://github.com/skyrich62/ncursespp) seems like a good one."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-24T11:56:59.843",
"Id": "500618",
"Score": "0",
"body": "thanks, at first glance, that does look better than the ones I found. \ncolours are easy compared to the stuff that ncurses does. ;-)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-24T12:01:49.460",
"Id": "500620",
"Score": "0",
"body": "Are you sure colours are easy? Because there is a wild variation in what colours a terminal supports and how they interact with other attributes, how colours propagate when you reach the end of the line or screen, and so on."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-24T12:09:02.943",
"Id": "500622",
"Score": "0",
"body": "Agreed. It's messy. Yet nurses is the kitchen sink with panels etc."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-24T13:11:53.853",
"Id": "500634",
"Score": "1",
"body": "Ncurses has the panels, forms and menus in separate `.so` files."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-24T13:15:28.200",
"Id": "500635",
"Score": "0",
"body": "`ncurses` doesn't seem to support the windows `cmd` prompt? only `cygwin`/`mingw` ? Is that the same? (I know very little about windows). The point of my `xos::console` was to support `cmd` which requires calling `windows.h` API."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-24T13:31:11.000",
"Id": "500636",
"Score": "0",
"body": "I'm not sure about ncurses, but [PDCurses](https://pdcurses.org/) definitely supports the Windows console."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-24T13:44:53.640",
"Id": "500637",
"Score": "0",
"body": "Yes I saw that, but `PDCurses` looks like Windows only (with an \"X11 port\" to make \"X11 Apps\", which are not the standard console)? My effort was supposed to compile natively on for BOTH the *nix and Windows native consoles. Maybe it does have purpose?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-24T13:53:06.503",
"Id": "500638",
"Score": "0",
"body": "I would just code my program against the standard curses interface, and then have it link to whatever library is best for the platform."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-24T14:03:56.370",
"Id": "500639",
"Score": "0",
"body": "That would work fine, if `Ncurses` (or a c++ warpper of the same) and `PDcurses` have a compatible source or binary API. Do they?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-24T14:08:17.273",
"Id": "500640",
"Score": "1",
"body": "For sure their API is the same for the standard curses functionality, but I'm not sure about the ABI."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-25T17:25:32.897",
"Id": "500719",
"Score": "2",
"body": "@G.Sliepen you don't need to bother about ABI cross-platform. Each platform got own ABI anyway (especially the unique snowflake Windows). That's why defunctionalization can be preferred - create adapters between your API and various library ones"
}
],
"meta_data": {
"CommentCount": "13",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-24T10:59:24.027",
"Id": "253865",
"ParentId": "253842",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "253865",
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-23T19:45:02.417",
"Id": "253842",
"Score": "0",
"Tags": [
"c++",
"console"
],
"Title": "Cross-platform console abstraction"
}
|
253842
|
<p>I'm using this Game Messenger as an instant messaging tool in my game. Just wondering peoples on thoughts on it.</p>
<p>Thank you!</p>
<pre><code> enum class eGameMessageType
{
AddItemGUI = 0,
RemoveItemGUI,
UpdateSelectionBoxGUI,
UpdateItemQuantityGUI,
DestroyCubeSetPosition,
DestroyCubeReset,
SelectedCubeSetPosition,
SelectedCubeSetActive,
SpawnPickup,
PlayerDisgardPickup,
AddToPlayerInventory,
Max = AddToPlayerInventory
};
struct Listener : private NonCopyable
{
Listener(const std::function<void(const void*)>& fp, const void* ownerAddress)
: m_listener(fp),
m_ownerAddress(ownerAddress)
{
assert(ownerAddress);
}
Listener(Listener&& rhs) noexcept
: m_listener(rhs.m_listener),
m_ownerAddress(rhs.m_ownerAddress)
{
rhs.m_listener = nullptr;
rhs.m_ownerAddress = nullptr;
}
Listener& operator=(Listener&& rhs) noexcept
{
m_listener = rhs.m_listener;
m_ownerAddress = rhs.m_ownerAddress;
rhs.m_listener = nullptr;
rhs.m_ownerAddress = nullptr;
return *this;
}
std::function<void(const void*)> m_listener;
const void* m_ownerAddress;
};
class GameMessenger : private NonCopyable, private NonMovable
{
public:
static GameMessenger& getInstance()
{
static GameMessenger instance;
return instance;
}
template <typename GameMessage>
void subscribe(const std::function<void(const GameMessage&)>& gameMessage, const void* ownerAddress)
{
auto& listeners = m_listeners[static_cast<int>(GameMessage::getType())];
assert(!isOwnerAlreadyRegistered(listeners, GameMessage::getType(), ownerAddress));
listeners.emplace_back(reinterpret_cast<std::function<void(const void*)> const&>(gameMessage), ownerAddress);
}
template <typename GameMessage>
void unsubscribe(const void* ownerAddress)
{
auto& listeners = m_listeners[static_cast<int>(GameMessage::getType())];
assert(isOwnerAlreadyRegistered(listeners, GameMessage::getType(), ownerAddress));
auto iter = std::find_if(listeners.begin(), listeners.end(), [ownerAddress](const auto& listener)
{
return listener.m_ownerAddress == ownerAddress;
});
assert(iter != listeners.end());
listeners.erase(iter);
}
template <typename GameMessage>
void broadcast(GameMessage gameMessage)
{
const auto& listeners = m_listeners[static_cast<int>(GameMessage::getType())];
for (const auto& listener : listeners)
{
reinterpret_cast<std::function<void(const GameMessage&)> const&>(listener.m_listener)(gameMessage);
}
}
private:
GameMessenger() {}
std::array<std::vector<Listener>, static_cast<size_t>(eGameMessageType::Max) + 1> m_listeners;
bool isOwnerAlreadyRegistered(const std::vector<Listener>& listeners, eGameMessageType gameMessageType, const void* ownerAddress) const
{
assert(ownerAddress != nullptr);
if (!listeners.empty())
{
auto result = std::find_if(listeners.cbegin(), listeners.cend(), [ownerAddress](const auto& listener)
{
return listener.m_ownerAddress == ownerAddress;
});
return result != listeners.cend();
}
else
{
return false;
}
}
};
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-24T12:38:45.687",
"Id": "500628",
"Score": "1",
"body": "Is this program made using a game engine?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-24T14:37:27.800",
"Id": "500644",
"Score": "0",
"body": "It's from a little Minecraft clone that I made a while ago. It's only a pet project - am a student currently."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-24T16:43:30.300",
"Id": "500660",
"Score": "1",
"body": "The thing is we don't have the definition of the class you derive from"
}
] |
[
{
"body": "<h1>Move <code>struct Listener</code> into <code>class GameMessenger</code></h1>\n<p>The <code>struct Listener</code> is just an implementation detail of <code>GameMessenger</code>, you can move it into <code>class GameMessenger</code> like so:</p>\n<pre><code>class GameMessenger: ...\n{\n struct Listener: ...\n {\n ...\n };\n\n ...\n};\n</code></pre>\n<p>Now that it is <code>private</code>, I would also keep <code>Listener</code> very simple, and just have it hold the two member variables, without adding any member functions.</p>\n<h1>Pass messages as <code>const</code> references</h1>\n<p>The actual message handler functions take a <code>const</code> reference to the message, but your <code>GameMessenger::broadcast()</code> takes it by value, making an unnecessary copy. Change it to:</p>\n<pre><code>void broadcast(const GameMessage &gameMessage) {...}\n</code></pre>\n<h1>Naming things</h1>\n<p>Some names could be improved. For example, <code>struct Listener</code> has a member variable <code>m_listener</code>. Combined with the <code>std::vector<Listener></code>, you get the word <code>listener</code> repeated a lot, like in <code>GameMessenger::broadcast()</code>, where there's even a <code>listener.m_listener</code>. Consider renaming <code>m_listener</code> to <code>m_handler</code> or <code>m_callback</code>.</p>\n<p>Some names are a bit longer than necessary. I suggest these changes:</p>\n<pre><code>- `typename GameMessage` -> `typename Message`\n- `isOwnerAlreadyRegistered()` -> `isRegistered()`\n</code></pre>\n<h1>Make <code>class GameMessenger</code> a template</h1>\n<p>With <code>void</code> pointers you throw type-safety overboard, and requires you to <code>reinterpret_cast<>()</code> things. I can't say much about <code>m_ownerAddress</code>, however\nthe main problem here is that you have a non-templated <code>class GameMessenger</code>. Apart from the constructor, all the public member functions are <code>template <typename GameMessage></code>. Instead of having one <code>GameMessenger</code> object being responsible for all possible message types, consider making the class templated itself, and only be responsible for one specific message type.</p>\n<p>If you implement it this way, there will be one <code>GameMessenger</code> object per message type. That means there is no longer a need to have a <code>std::array</code> for each of the possible message types, and in fact <code>enum eGameMessageType</code> is no longer necessary.</p>\n<p>Here is an example of how it might look:</p>\n<pre><code>template <typename Message>\nclass GameMessenger: private NonCopyable, private NonMovable \n{\n struct Listener {\n const std::function<void(const Message &)> m_handler;\n const void *m_ownerAddress;\n };\n\npublic:\n static GameMessenger& getInstance()\n {\n static GameMessenger instance;\n return instance;\n }\n\n void subscribe(const std::function<void(const Message&)>& handler, const void* ownerAddress)\n {\n assert(!isRegistered(ownerAddress));\n listeners.emplace_back(handler, ownerAddress);\n }\n\n template <typename Message>\n void unsubscribe(const void* ownerAddress)\n {\n auto iter = std::find_if(m_listeners.begin(), m_listeners.end(), [ownerAddress](const auto& listener)\n {\n return listener.m_ownerAddress == ownerAddress;\n });\n\n assert(iter != listeners.end());\n listeners.erase(iter);\n }\n\n void broadcast(const Message &message)\n {\n for (const auto& listener: m_listeners)\n {\n listener.m_handler(message);\n }\n }\n\nprivate:\n std::vector<Listener> m_listeners;\n\n bool isRegistered(const void* ownerAddress) const\n {\n assert(ownerAddress != nullptr);\n\n auto result = std::find_if(listeners.cbegin(), listeners.cend(), [ownerAddress](const auto& listener)\n {\n return listener.m_ownerAddress == ownerAddress;\n });\n\n return result != listeners.cend();\n }\n};\n</code></pre>\n<p>So how do you use it? Instead of writing:</p>\n<pre><code>void handleSpawnPickup(const SpawnPickupMessage &message) {...}\nvoid *ownerAddress = ...;\n\nauto messenger = GameMessenger.getInstance();\nmessenger.subscribe(handleSpawnPickup, ownerAddress);\n</code></pre>\n<p>You replace the last two lines with:</p>\n<pre><code>auto messenger = GameMessenger<SpawnPickupMessage>.getInstance();\nmessenger.subscribe(handleSpawnPickup, ownerAddress);\n</code></pre>\n<p>If you want to avoid having to explicitly mention the type when getting the messenger instance, consider writing an out-of-class function that subscribes to the right instance for you:</p>\n<pre><code>template<typename Message>\nvoid subscribeToMessenger(const std::function<void(const Message&)>& handler, const void* ownerAddress)\n{\n GameMessenger<Message>::getInstance().subscribe(handler, ownerAddress);\n}\n</code></pre>\n<p>So that you can just write:</p>\n<pre><code>subscribeToMessenger(handleSpawnPickup, ownerAddress);\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-27T14:19:34.303",
"Id": "500830",
"Score": "0",
"body": "Hi there, thank you! I have responded with a follow up question."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-27T02:16:43.807",
"Id": "253944",
"ParentId": "253846",
"Score": "1"
}
},
{
"body": "<p>Thank you @G. Sliepen I have rectified the code but now have an issue where I have the public functions in GameMessenger that I'd like to make private or remove entirely - so the caller can only use the functions outside of class.</p>\n<p>Just wondering the best way to do this? Thanks.</p>\n<pre><code> template <typename Message>\n class GameMessenger : private NonCopyable, private NonMovable\n {\n struct Listener\n { \n Listener(const std::function<void(const Message&)>& callback, const void* ownerAddress)\n : callback(callback),\n ownerAddress(ownerAddress)\n {}\n \n std::function<void(const Message&)> callback;\n const void* ownerAddress;\n };\n \n public:\n static GameMessenger<Message>& getInstance()\n {\n static GameMessenger<Message> instance;\n return instance;\n }\n \n void subscribe(const std::function<void(const Message&)>& callback, const void* ownerAddress)\n {\n assert(!isRegistered(ownerAddress));\n m_listeners.emplace_back(callback, ownerAddress);\n } \n \n void unsubscribe(const void* ownerAddress)\n {\n assert(isRegistered(ownerAddress));\n auto listener = std::find_if(m_listeners.begin(), m_listeners.end(), [ownerAddress](const auto& listener)\n {\n return listener.ownerAddress == ownerAddress;\n });\n assert(listener != m_listeners.cend());\n m_listeners.erase(listener);\n }\n \n void broadcast(const Message& message) const\n {\n assert(!m_listeners.empty());\n for (const auto& listener : m_listeners)\n {\n listener.callback(message);\n }\n }\n \n private:\n GameMessenger() {}\n \n std::vector<Listener> m_listeners;\n \n bool isRegistered(const void* ownerAddress) const\n {\n auto listener = std::find_if(m_listeners.cbegin(), m_listeners.cend(), [ownerAddress](const auto& listener)\n {\n return listener.ownerAddress == ownerAddress;\n });\n \n return listener != m_listeners.cend();\n }\n };\n \n template <typename Message>\n void subscribeToMessenger(const std::function<void(const Message&)>& callback, const void* ownerAddress)\n {\n GameMessenger<Message>::getInstance().subscribe(callback, ownerAddress);\n }\n \n template <typename Message>\n void unsubscribeToMessenger(const void* ownerAddress)\n {\n GameMessenger<Message>::getInstance().unsubscribe(ownerAddress);\n }\n \n template <typename Message>\n void broadcastToMessenger(const Message& message)\n {\n GameMessenger<Message>::getInstance().broadcast(message);\n }\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-27T15:08:57.723",
"Id": "500832",
"Score": "1",
"body": "You can make everything in `GameMessenger` `private`, and add the following: `friend substribeToMessenger<>(const std::function<void(const Message&)>& callback, const void* ownerAddress);` And similar `friend` function definitions for `unsubscribeToMessenger()` and `broadcastToMessenger()`. This will allow the out-of-class functions to access the `private` member fucntions."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-27T15:28:07.483",
"Id": "500833",
"Score": "0",
"body": "Doesn't seem to work for some reason doing it like that. \n\nI can't access them with 'GameMessenger<Message>::getInstance().m_listeners' either."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-27T15:37:23.317",
"Id": "500834",
"Score": "1",
"body": "It might be best to ask this on [StackOverflow](https://stackoverflow.com/) with a minimum reproducible example of what you tried."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-27T14:19:37.870",
"Id": "253957",
"ParentId": "253846",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "253944",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-23T20:47:44.207",
"Id": "253846",
"Score": "2",
"Tags": [
"c++",
"game"
],
"Title": "Event Messenger C++ Game Programming"
}
|
253846
|
<p>I am trying to authenticate / authorise users with graphql, nexus, passport, prisma, graphql-shield and fastify for REST with JWT</p>
<p>To answer possible questions: I am using passport because it handles the callbacks for me in a nice way, I could create something fully tied to my mutations and remove everything REST related but it's not going to look pretty, also I need to support apple auth, SMS and email so writing custom auth flows for them will be a lot of code</p>
<p>In the frontend I would use apollo graphql and use the refresh token to get a access token from the refresh_token route, the refresh token would be saved in a variable</p>
<p>This is a single API to serve a React website that uses the currently implemented google auth and a React native app for the other auth methods I mentioned earlier, I would implement the other auth options in a similar way</p>
<p>I am not asking for a review on code style, I would love feedback on the auth flow and know for sure that this is a safe way of doing auth</p>
<pre><code>// index.ts
import "./passport"
const main = () => {
const server = fastify({ logger })
const prisma = new PrismaClient()
const apolloServer = new ApolloServer({
schema: applyMiddleware(schema, permissions),
context: (request: Omit<Context, "prisma">) => ({ ...request, prisma }),
tracing: __DEV__,
})
server.register(fastifyCookie)
server.register(apolloServer.createHandler())
server.register(fastifyPassport.initialize())
server.get(
"/auth/google",
{
preValidation: fastifyPassport.authenticate("google", {
scope: ["profile", "email"],
session: false,
}),
},
// eslint-disable-next-line @typescript-eslint/no-empty-function
async () => {}
)
server.get(
"/auth/google/callback",
{
preValidation: fastifyPassport.authorize("google", { session: false }),
},
async (request, reply) => {
// Store user in database
// const user = existingOrCreatedUser
// sendRefreshToken(user, reply)
// const accessToken = createAccessToken(user)
// reply.send({ accessToken, user })
}
)
server.get("/refresh_token", async (request, reply) => {
const token = request.cookies.fid
if (!token) {
return reply.send({ accessToken: "" })
}
let payload
try {
payload = verify(token, secret)
} catch {
return reply.send({ accessToken: "" })
}
const user = await prisma.user.findUnique({
where: { id: payload.userId },
})
if (!user) {
return reply.send({ accessToken: "" })
}
if (user.tokenVersion !== payload.tokenVersion) {
return reply.send({ accessToken: "" })
}
sendRefreshToken(user, reply)
return reply.send({ accessToken: createAccessToken(user) })
})
server.listen(port)
}
</code></pre>
<pre><code>// passport.ts
import fastifyPassport from "fastify-passport"
import { OAuth2Strategy } from "passport-google-oauth"
fastifyPassport.registerUserSerializer(async (user) => user)
fastifyPassport.registerUserDeserializer(async (user) => user)
fastifyPassport.use(
new OAuth2Strategy(
{
clientID: process.env.GOOGLE_CLIENT_ID,
clientSecret: process.env.GOOGLE_CLIENT_SECRET,
callbackURL: "http://localhost:4000/auth/google/callback",
},
(_accessToken, _refreshToken, profile, done) => done(undefined, profile)
)
)
</code></pre>
<pre><code>// permissions/index.ts
import { shield } from "graphql-shield"
import { rules } from "./rules"
export const permissions = shield({
Mutation: {
createOneShopLocation: rules.isAuthenticatedUser,
},
})
</code></pre>
<pre><code>// permissions/rules.ts
import { rule } from "graphql-shield"
import { Context } from "../context"
export const rules = {
isAuthenticatedUser: rule()(async (_parent, _args, ctx: Context) => {
const authorization = ctx.request.headers.authorization
if (!authorization) {
return false
}
try {
const token = authorization.replace("Bearer", "")
const payload = verify(token, secret)
// mutative
ctx.payload = payload
return true
} catch {
return false
}
}),
}
<span class="math-container">```</span>
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-23T21:20:45.037",
"Id": "253850",
"Score": "1",
"Tags": [
"node.js",
"authentication",
"authorization",
"jwt",
"graphql"
],
"Title": "Secure auth with Node.js, GraphQL, Nexus and passport with JWT's"
}
|
253850
|
<p>I am new to Python.</p>
<p>Currently developing an application, whose purpose is to accept a directory path from user and create a file(sha_generated_file.txt)
with SHA256 of each file name inside the passed directory subfolders except those mentioned in ignored list.</p>
<p>Sample entry in sha_generated_file.txt is
<code>SHA256(out_configuration/PRC/afile.bin)= 3c62546a67921acbd4e85c70af794270c095177213781e7d6d1000762d849100</code></p>
<p>Once the sha_generated_file.txt is generated it will be sent for signing(by invoking another tool, that is not in the scope).</p>
<p>The resultant of signing is a Sample.p7s file, which is parsed using <code>ASN1PARSE</code> and other <code>OpenSSL</code> commands to get some
certificates out of p7s file.</p>
<p>Finally the certificates will be copied to some designated location.</p>
<p>You may not be able to execute the entire program , but individual functions can be executed with minimal modifications ( Sorry I could not possibly come up with version that be run by you, becuase it has dependency of openssl, third party tool etc)</p>
<p><strong>Process goes like this:</strong></p>
<p>The ideal folder structure of of input path is</p>
<pre><code> --configuration
|__PRC
|
|__QRC
|
|__RRC
|
|__XRC
</code></pre>
<p>Out of this, i want SHA256 of all the files(only file names, not the contents) from all directories except XRC.</p>
<p><strong>Note</strong>: There is a condition for ordering of files in the resultant sha_generated_file.txt</p>
<p>All the files in required directories should be sorted alphabetically (following ascii values)
( This part of code can be found in <code>create_sha_signer_dir</code>,<code>create_sha_file</code>,<code>make_file_list</code>,<code>make_sha_format</code>,<code>fetch_sub_directory_contents</code> etc. )</p>
<p>But before proceeding for SHA calculation, I need to setup some most frequently used directories for temporary processing purpose during the run time of my application.
( This particular code can be found in <code>setup_tool_envdirs</code>)</p>
<p>I have also handled the cases where only parent directory is passed as input or till the required directory is passed (code can be found in <code>check_path_is_valid_config</code>)</p>
<p>There are other set of functions implemented for miscellanios purpose likes extracting bytes from certain offsets and converting different file types(crl to pem etc)</p>
<p>The application has to run in <code>Python2.7</code> and <code>Python3</code>, It currently works with 2.7 and also mostly it works with <code>Python3</code> (few errors for byte string conversions etc. )</p>
<p>I am looking for optimizing the code in all possible ways ( optimization/reduce number of lines/correct usage/stanadard/speed/memory/ etc. )</p>
<p><strong>code</strong></p>
<pre><code>import os
import sys
import hashlib
import string
from ctypes import windll
from os.path import dirname, abspath
from shutil import copyfile
import logging
ignored = {"XRC"}
#constants to replaced
OUT_CONFIGURATION = 'out_configuration'
CONTAINS_CONFIG = 'contains_config'
PARENT_HAS_CONFIG = 'parent_has_config'
SHA256_FILE_NAME = 'sha_generated_file.txt'
P7S_FILE_NAME = 'Sample.p7s'
OPENSSL_EXE_PATH = 'C:\\Users\\Documents\\Installs\\openssl.exe'
OFFSETS_LENGTH_FILE = 'crl_offset_n_lengths.txt'
config_dir_path = ''
parent_of_config_dir = ''
signature_file_path = ''
sha_file_path = ''
g_crl_dir_path = ''
# tells whether the input path has(only till parent is passed ) or contains(full path passed)
config_dir_path_flag = ''
def copy_pem_files_to_config_crl():
global g_crl_dir_path
global sha_file_path
crl_dir = sha_file_path
config_crl = g_crl_dir_path
filelist = [ f for f in os.listdir(crl_dir) if f.endswith(".pem") ]
print ( "number of files in crl dir are: {}".format(len(filelist) ))
if len(filelist) > 0:
for f in filelist:
copyfile(os.path.join(crl_dir, f),ref_config_crl+"\\"+f)
return True
else:
return False
def convert_crl_to_pem():
#openssl crl -inform DER -in crl3.crl -outform PEM -out crl3_pem.pem
crl_dir = sha_file_path
filelist = [ f for f in os.listdir(crl_dir) if f.endswith(".crl") ]
logging.info ( "number of files in crl dir are: {}".format(len(filelist)))
if len(filelist) > 0:
for f in filelist:
crl_file = os.path.join(crl_dir, f)
logging.info ( "crl_file = %s", crl_file )
fnamepos = crl_file.find(".crl")
pem_file = crl_file[:fnamepos]
pem_file = pem_file+".pem"
logging.info ( "pem_file = %s", pem_file )
CRL_TO_PEM_CMD = OPENSSL_EXE_PATH + " crl -inform DER -in " + crl_file + " -outform PEM -out " + pem_file
#logging.info ( f"CRL_TO_PEM_CMD ={CRL_TO_PEM_CMD}" )
logging.info ( "CRL_TO_PEM_CMD = %s" + CRL_TO_PEM_CMD )
os.system(CRL_TO_PEM_CMD)
return True
else:
logging.error("There are not CRL files present in %s ",crl_dir)
return False
#sample lines for below 3 functions
#2286:depth=4 hl=4 l=5321 cons: next
def get_length(line):
return int (line.split(':')[1].split(']')[0])
def get_offset(line):
return int (line.split(':')[0].split('[')[1])
def extract_crl(offset,length):
crl_file = '';
#checking this just to avoid creating files with length 4 and below
if length > 4:
crl_file = sha_file_path + "crl_" + str(offset) + ".crl"
logging.info ( "%s created" ,crl_file)
with open(crl_file, 'wb') as fw , open(signature_file_path+P7S_FILE_NAME, 'rb') as fr:
try:
logging.info ( "file open success" )
fr.seek(offset)
crl_content = fr.read(length)
logging.info ( "length of crl_content = %d", len(crl_content))
fw.write(crl_content);
fw.close()
fr.close()
except IOError:
logging.error ( "file open failed %s",crl_file )
return
def create_crls():
olaf = sha_file_path+OFFSETS_LENGTH_FILE
if os.path.exists(olaf):
with open(olaf, 'r') as f:
try:
logging.info ( "file open success" )
line = f.readline()
while len(line.strip()) != 0 :
offset = get_offset(line)
length = get_length(line)
extract_crl(offset,length)
line = f.readline()
f.close();
except IOError:
logging.error ( "file open failed %s",olaf )
else:
logging.error ( "file does not exist %s",olaf )
#get offset and length file
'''
sample contents parse_txt are
2282:depth=3 hl=4 l=12096 cons: start_indi
2286:depth=4 hl=4 l=5321 cons: next
2290:depth=5 hl=4 l=4785 cons: next
extract as long as this condition satifies
next_offset = prev_offset + prev_length
'''
def create_offset_and_length_file(parse_txt):
o_l_f = sha_file_path+OFFSETS_LENGTH_FILE
with open(o_l_f, 'w') as fw:
try:
logging.info ( "file open success" )
except IOError:
logging.error ( "file open failed" )
fo = open(parse_txt);
line = fo.readline()
while len(line.strip()) != 0 :
if "cont [ 1 ]" in line:
line = fo.readline()
offset = line.split(':')[0]
length = line.split('=')[3].split()[0]
length_i = int (length) + 4
offset_i = int (offset)
output = "["+ offset + ":" + str (length_i) + "]"+"\n"
fw.write(output);
line = fo.readline()
while len(line.strip()) != 0 :
if " " + str(offset_i + length_i) + ':' in line:
offset = line.split(':')[0]
length = line.split('=')[3].split()[0]
length_i = int (length) + 4
offset_i = int (offset)
output = "["+ offset + ":" + str (length_i) + "]"+"\n"
fw.write(output);
if str(offset_i + length_i) + ':' in line:
offset = line.split(':')[0]
length = line.split('=')[3].split()[0]
length_i = int (length) + 4
offset_i = int (offset)
output = "["+ offset + ":" + str (length_i) + "]"+"\n"
fw.write(output);
line = fo.readline()
line = fo.readline()
fw.close()
def create_parse_txt(p7sdest_path):
global sha_file_path
cmd = OPENSSL_EXE_PATH
cmd = cmd + " asn1parse -inform DER -in " + p7sdest_path + " >> " + sha_file_path + "parse.txt"
logging.info ( "parse command is %s", cmd )
result = os.system(cmd)
logging.info ( "create_parse_txt result = %d", result )
return result
def copy_signed_p7s():
global sha_file_path
global parent_of_config_dir
global config_dir_path
global signature_file_path
p7s_file_src = sha_file_path + "Sample.p7s"
p7s_file_dest = signature_file_path
logging.info ( "p7s_file_src= %s", p7s_file_src )
logging.info ( "p7s_file_dest=%s", p7s_file_dest )
if os.path.exists(p7s_file_src) == True and os.path.exists(p7s_file_dest) == True:
logging.info ( "both path exists" )
#copyfile should have full path including filename as destination and its blocking so no need to collect return value
if os.path.isfile(p7s_file_src) == True:
copyfile(p7s_file_src, p7s_file_dest+"Sample.p7s")
return True
else:# This should not be reached
logging.error ( "not file" )
else:
logging.error ( " one of the paths does not exist" )
return False
def create_signingP7S_file():
curr_dir = os.getcwd()
logging.info ( "os.getcwd()=%s", curr_dir )
BAT_PATH = "C:\\XXX\\YYY\\Tool\\Test\\"
batdir = os.chdir(BAT_PATH)
logging.info ( "os.getcwd2()= %s", os.getcwd())
TOOL_SCN_PATH = "scenes\\sign_temp.config"
ret = os.system("tool_test.bat"+' -prop_file='+TOOL_SCN_PATH)
if ret == 0:
logging.info ( "Creation of P7S Success" )
if True == copy_signed_p7s():
logging.info ( "p7s copy success" )
return True
else:
logging.error ( "p7s copy failed" )
else:
logging.error ( "Creation of P7S Failed" )
os.chdir(curr_dir)
print ( os.getcwd() )
def write_sha_entry_to_file(sha_entry):
global sha_file_path
sha_file = open(sha_file_path+SHA256_FILE_NAME, "ab")
logging.info (" sha_entry = {}".format(sha_entry))
sha_file.write(str(sha_entry))
sha_file.close()
def calc_hash256(filename):
with open(filename,"rb") as f:
bytes = f.read() # read entire file as bytes
readable_hash = hashlib.sha256(bytes).hexdigest();
return (readable_hash)
def make_sha_format(file):
'''
make the filename format as require by sha file
'''
config_pos = file.find('\\'+OUT_CONFIGURATION)+1
config_path_sha = file[config_pos:]
config_path_sha = config_path_sha.replace("\\","/")
shakey = calc_hash256(file)
shakey_fmt = "SHA256("+config_path_sha+")= "+str(shakey)+'\n'
write_sha_entry_to_file(shakey_fmt)
return shakey_fmt
def fetch_sub_directory_contents(sPath):
for sChild in sorted(os.listdir(sPath)):
if sChild not in ignored:
sChildPath = os.path.join(sPath,sChild)
if os.path.isdir(sChildPath):
fetch_sub_directory_contents(sChildPath)
else:
sChildPath = make_sha_format(sChildPath)
else:
logging.info ( "%s present in ignored list", sChild )
def make_file_list(cwd_rc):
'''
makes the sorted file list from out_configuration directory
'''
logging.info ( cwd_rc )
sorted_list = []
listOfFiles = sorted(os.listdir(cwd_rc))
logging.info ( listOfFiles )
for entry in listOfFiles:
if entry not in ignored:
sorted_list.append(cwd_rc+'\\'+entry)
else:
logging.info ( "%s present in ignored list",entry)
logging.info ( "sorted_list" )
logging.info ( sorted_list )
for entry in sorted_list:
if os.path.isfile(entry):
entry = make_sha_format(entry)
elif os.path.isdir(entry):
fetch_sub_directory_contents(entry)
return True
def create_sha_file(config_dir):
return make_file_list(config_dir)
def get_drives():
drives = []
bitmask = windll.kernel32.GetLogicalDrives()
for letter in string.ascii_uppercase:
if bitmask & 1:
drives.append(letter)
bitmask >>= 1
return drives
def create_sha_signer_dir():
'''
Function to create the directory for SHA256 file of input path
Scans the window system for existing drives and takes the first drive it finds and creates a "temp" folder there
If "temp" is not present it will be created, else checks whether sha256 file is present, if present deletes it and creates new one.
:return the SHA256 path excluding the file name
'''
drives = []
drives = get_drives()
sha_signer_path = drives[0]+':\\temp\\'
if not os.path.exists(sha_signer_path):
print ( " creating ", sha_signer_path )
os.makedirs(sha_signer_path)
else:
print ( sha_signer_path + " already exists, deletes sha file if present" )
isExist = os.path.exists(sha_signer_path+SHA256_FILE_NAME)
if isExist == True:
os.remove(sha_signer_path+SHA256_FILE_NAME)
return sha_signer_path
def startSign():
global config_dir_path
global sha_file_path
global signature_file_path
global parent_of_config_dir
logging.info ("config_dir_path = %s", config_dir_path)
logging.info ("parent_of_config_dir =%s", parent_of_config_dir)
temp_sha_file_path = create_sha_signer_dir()
sha_file_path = temp_sha_file_path
logging.info ( "sha_file_path = %s", sha_file_path )
result = create_sha_file(config_dir_path)
if True == result:
logging.info ( "SHA creation success" )
result = create_signingP7S_file()
if result == True:
logging.info ( "p7s creation success" )
result = create_parse_txt(signature_file_path+P7S_FILE_NAME)
if result == 0:
logging.info ( "parse success" )
create_offset_and_length_file(sha_file_path + "parse.txt")
create_crls()
if convert_crl_to_pem() == True:
copy_pem_files_to_config_crl()
result = True
else:
result = False
else:
logging.error ( "parse failed" )
result = False
else:
logging.error ( "p7s creation failed" )
result = False
else:
logging.error ( "SHA creation failed" )
result = False
return result
def remove_existing_crl_files(crl_dir):
filelist = [ f for f in os.listdir(crl_dir) if f.endswith(".pem") ]
logging.info ( "number of files in crl dir are: {}".format(len(filelist)))
if len(filelist) > 0:
for f in filelist:
os.remove(os.path.join(crl_dir, f))
return True
else:
return False
def create_crl_path(crl_path):
if not os.path.exists(crl_path):
logging.info ( " creating %s", crl_path)
os.makedirs(crl_path)
else:
logging.info ( crl_path + " already exists, deletes crl files if present" )
result = remove_existing_crl_files(crl_path)
if result == True:
logging.info ( "existing crls deleted")
else:
logging.info ( "crl dir is empty")
return crl_path
def create_signature_dir(sign_path):
if not os.path.exists(sign_path):
print ( " creating ", sign_path )
os.makedirs(sign_path)
else:
print ( sign_path + " already exists, deletes p7s file if present" )
isExist = os.path.exists(sign_path+P7S_FILE_NAME)
if isExist == True:
os.remove(sign_path+P7S_FILE_NAME)
return sign_path
def check_path_has_configuration(ipath):
if ipath.endswith("\\"):
config_path = ipath + OUT_CONFIGURATION
else:
config_path = ipath + '\\'+OUT_CONFIGURATION
if os.path.exists(config_path) == True and os.path.isdir(config_path) == True:
return config_path
else:# This should not hit in any case
print (" **parent does not have out_configuration dir** ")
return ''
def get_config_dir(ipath):
global config_dir_path_flag
logging.info ("config_dir_path_flag =%s", config_dir_path_flag)
if config_dir_path_flag == CONTAINS_CONFIG:
return ipath
elif config_dir_path_flag == PARENT_HAS_CONFIG:
config_path = check_path_has_configuration(ipath)
if config_path:
return config_path
else:
return ''
def get_parent_of_config_dir(config_dir):
return dirname(abspath(config_dir))
#input path will be checked for whether it contains out_configuration directory or its parent, in that case returns True
#if none then returns False
def check_path_is_valid_config(ipath):
global config_dir_path_flag
result = ipath.endswith('\\'+OUT_CONFIGURATION) == True or ipath.endswith('\\'+OUT_CONFIGURATION+'\\') == True
if(result == True):
logging.info ("input path contains out_configuration : ")
config_dir_path_flag = CONTAINS_CONFIG
logging.info ("config_dir_path_flag = %s", config_dir_path_flag)
return result
else:
logging.info ("input path looks like parent of out_configuration, checking for out_configuration")
if ipath.endswith("\\"):
config_path = ipath + OUT_CONFIGURATION
else:
config_path = ipath + '\\'+OUT_CONFIGURATION
logging.info (" the created config_path = %s", config_path)
if os.path.exists(config_path) == True and os.path.isdir(config_path) == True:
logging.info ("parent has out_configuration ")
config_dir_path_flag = PARENT_HAS_CONFIG
logging.info ("config_dir_path_flag = %s", config_dir_path_flag)
return True
else:
logging.warning ("out_configuration dir not present for signing")
return False
def setup_tool_envdirs(rc_path):
global config_dir_path
global parent_of_config_dir
global signature_file_path
global g_crl_dir_path
# check for validity of input path
if True == check_path_is_valid_config(rc_path):
config_dir_path = get_config_dir(rc_path)
if config_dir_path:
parent_of_config_dir = get_parent_of_config_dir(config_dir_path)
signature_file_path = config_dir_path + "\\signature\\"
sign_file_path = create_signature_dir(signature_file_path)
crl_files_path = create_crl_path(signature_file_path+"crl");
g_crl_dir_path = crl_files_path
logging.info ( "crl_files_path = %s", crl_files_path )
logging.info ("config_dir_path = %s", config_dir_path)
logging.info ("parent_of_config_dir = %s", parent_of_config_dir)
logging.info ("signature_file_path = %s", signature_file_path)
logging.info ("sign_file_path = %s", sign_file_path)
return True
else:#This part should not be hit
logging.error ("Looks like some corruption in configuration")
return False
else:
logging.error ( "configuration is not present in input path: %s" + ipath )
return False
def parse_cmdline_params():
nargs = len(sys.argv)
logging.info ( "Number of CMD Args:{}".format(nargs) )
if nargs <= 1:
logging.warning ("please pass desired path while running Tool - example: < tool.py path of desired location >")
return False
else:
return True
#tool main entry function
def main_entry():
result = parse_cmdline_params()
if True == result:
input_path = sys.argv[1]
logging.info ("The input path is : %s", input_path)
#First setup the freqently used directory paths
if setup_tool_envdirs(input_path) == True:
logging.info ("setup is successful ")
if startSign() == True:
return True
else:
return False
else:
logging.info ("setup is unsuccessful ")
return False
else:
return
if __name__ == "__main__":
logging.basicConfig(filename='debug_tool.log', encoding='utf-8', level=logging.DEBUG)
if True == main_entry():
print ("**Successful**")
else:
logging.error ("**UnSuccessful**")
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-24T16:28:08.677",
"Id": "500657",
"Score": "0",
"body": "_The application has to run in Python2.7_ - why?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-25T09:01:31.103",
"Id": "500684",
"Score": "0",
"body": "Currently that is what the requirement, I know it is out dated and will not be supported in future, that is the reason i want it to support pyhton3 so that we have future support."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-25T13:09:42.480",
"Id": "500704",
"Score": "0",
"body": "It's not in the future. It's now. Python 2 is no longer supported. https://python3statement.org/"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-25T14:57:25.503",
"Id": "500716",
"Score": "0",
"body": "@Reinderien, yeah , I have already read that Python2.7 support is stopping from next year January, I have already informed my people about this. Can you please help me in improving it. I am able to make it work some how, I know it can be improved a lot. I can google it and do, but I want it to be reviewed from larger professional audience and take suggestions."
}
] |
[
{
"body": "<h2>Python versions</h2>\n<p>As we discussed in the comments, Python 2 is no longer supported. It's time to move on.</p>\n<h2>Hard-coded configuration</h2>\n<p>These:</p>\n<pre><code>SHA256_FILE_NAME = 'sha_generated_file.txt'\nP7S_FILE_NAME = 'Sample.p7s'\nOPENSSL_EXE_PATH = 'C:\\\\Users\\\\Documents\\\\Installs\\\\openssl.exe'\nOFFSETS_LENGTH_FILE = 'crl_offset_n_lengths.txt'\n</code></pre>\n<p>should not be hard-coded. They should be accepted as command-line arguments, environmental variables or configuration entries. The first, second and fourth can take those values as defaults, but the third cannot have a default - that path needs to be parametric.</p>\n<h2>Globals</h2>\n<p>Try to stop using them. Pass data around as member variables on a class, or function arguments. Only constants should generally stay global.</p>\n<h2>Pathlib</h2>\n<p>Consider replacing <code>os.listdir</code> and <code>endswith</code> with <code>pathlib</code> equivalents. Also, for the determination of <code>filelist</code>, consider using <code>pathlib</code> to verify that the entries are all normal files.</p>\n<p>Note that pathlib is only available in Python 3.4+.</p>\n<h2>Logic inversion</h2>\n<p>Do the easy thing first: consider rearranging</p>\n<pre><code>if len(filelist) > 0:\n for f in filelist:\n crl_file = os.path.join(crl_dir, f)\n logging.info ( "crl_file = %s", crl_file )\n fnamepos = crl_file.find(".crl")\n pem_file = crl_file[:fnamepos]\n pem_file = pem_file+".pem"\n logging.info ( "pem_file = %s", pem_file )\n CRL_TO_PEM_CMD = OPENSSL_EXE_PATH + " crl -inform DER -in " + crl_file + " -outform PEM -out " + pem_file\n #logging.info ( f"CRL_TO_PEM_CMD ={CRL_TO_PEM_CMD}" )\n logging.info ( "CRL_TO_PEM_CMD = %s" + CRL_TO_PEM_CMD )\n os.system(CRL_TO_PEM_CMD)\n return True\nelse:\n logging.error("There are not CRL files present in %s ",crl_dir)\n return False\n</code></pre>\n<p>to</p>\n<pre><code> if len(filelist) < 1:\n logging.error("There are not CRL files present in %s ",crl_dir)\n return False\n\n for f in filelist:\n crl_file = os.path.join(crl_dir, f)\n logging.info ( "crl_file = %s", crl_file )\n fnamepos = crl_file.find(".crl")\n pem_file = crl_file[:fnamepos]\n pem_file = pem_file+".pem"\n logging.info ( "pem_file = %s", pem_file )\n CRL_TO_PEM_CMD = OPENSSL_EXE_PATH + " crl -inform DER -in " + crl_file + " -outform PEM -out " + pem_file\n #logging.info ( f"CRL_TO_PEM_CMD ={CRL_TO_PEM_CMD}" )\n logging.info ( "CRL_TO_PEM_CMD = %s" + CRL_TO_PEM_CMD )\n os.system(CRL_TO_PEM_CMD)\n\n return True\n</code></pre>\n<h2>Make some unit tests</h2>\n<p>It's good that you made note of example data here:</p>\n<pre><code>#2286:depth=4 hl=4 l=5321 cons: next\n</code></pre>\n<p>This would be a great sample input for a unit test.</p>\n<p>That said, your example above does not match what you're attempting to parse:</p>\n<pre><code>return int (line.split(':')[1].split(']')[0])\n</code></pre>\n<p>since you're looking for a bracket that does not exist in your sample input data.</p>\n<h2>We're not in C anymore</h2>\n<p>Drop your semicolon here:</p>\n<pre><code>crl_file = '';\n</code></pre>\n<h2>Fail early, fail noisily</h2>\n<p>Why does this:</p>\n<pre><code>#checking this just to avoid creating files with length 4 and below\n</code></pre>\n<p>fail silently on insufficient length? Shouldn't you throw an exception, or at least log a warning?</p>\n<h2>Explicit closure</h2>\n<p>Delete these lines:</p>\n<pre><code> fw.close()\n fr.close()\n</code></pre>\n<p>Those files are closed when the context managers are exited.</p>\n<h2>Redundant return</h2>\n<p>Delete this:</p>\n<pre><code>return\n</code></pre>\n<h2>Formatting instead of concatenation</h2>\n<p>Replace</p>\n<pre><code> output = "["+ offset + ":" + str (length_i) + "]"+"\\n"\n</code></pre>\n<p>with a <code>format</code> call.</p>\n<h2>subprocess rather than os</h2>\n<p>Replace your calls to <code>os.system</code> with calls to <code>subprocess</code>.</p>\n<h2>Redundant initialization</h2>\n<p>Delete the first line here:</p>\n<pre><code>drives = []\ndrives = get_drives()\n</code></pre>\n<h2>Temporary directories</h2>\n<p>Hard-coding to only support Window drives, and attempting to make a stand-alone temporary directory in <code>create_sha_signer_dir</code>, are both bad ideas. Use <code>tempfile</code> instead and just let it use the default system-assigned temporary directory.</p>\n<h2>Exceptions-to-booleans</h2>\n<p>Resist the urge to sabotage the exception system, as in <code>startSign</code>. Do not convert exceptions to booleans. From <code>convert_crl_to_pem</code>, raise exceptions; and catch them where it makes sense.</p>\n<h2>Boolean comparisons</h2>\n<p>Do not do this:</p>\n<pre><code>if True == main_entry():\n</code></pre>\n<p>instead, just</p>\n<pre><code>if main_entry():\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-26T04:33:15.487",
"Id": "500747",
"Score": "0",
"body": "Thanks Reinderien for the comments & suggestions. I am going to come up the modified code as per your comments, and regarding using `subprocess` instead of `system` I tried , but got some problems, but anyway will go around it and fix now."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-26T04:46:27.163",
"Id": "500748",
"Score": "0",
"body": "Great. Please be sure to post your modified code in a new question, not this one."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-26T05:45:58.927",
"Id": "500750",
"Score": "0",
"body": "_the third cannot have a default - that path needs to be parametric_, how can we make that as parametric, do I have to find out installed path at runtime and use it ? And i forgot to mention i need to make an EXE (using pyinstaller) out of this program and run"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-25T18:32:42.003",
"Id": "253902",
"ParentId": "253854",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-23T22:26:00.680",
"Id": "253854",
"Score": "2",
"Tags": [
"python"
],
"Title": "An OpenSSL Signing Application"
}
|
253854
|
<p>This is my first project using the tkinter library. It's a basic calculator that supports the four basic arithmetic operations. It also supports inputting digits and symbols via the keyboard.</p>
<p>I'm looking for any sort of feedback. Are my comments sufficient for understanding the algorithm? Are there redundant comments or code? Is the program written well overall?</p>
<pre><code>import tkinter as tk
from functools import partial
def insert_value(value):
"""Insert value into input entry widget
if value is an operator, add spacing on each side of it
value: value to add to widget"""
global acceptable_inputs, interchangeable_operators
value = convert_to_int(value)
cur_text = str(result_lbl["text"])
if cur_text == "Error":
result_lbl["text"] = f"{value}"
elif isinstance(value, int) or len(cur_text) == 0 or value in ("(", ")", "."): #don't add additional spacing
result_lbl["text"] = f"{cur_text}{value}"
else: #add spacing in between provided value (only if value is an arithmetic operator)
for s in interchangeable_operators:
if s[1] in value:
value = replace_operators(value, s[1], s[0]) #change typed "/" to "÷" and/or "*" to "×"
result_lbl["text"] = f"{cur_text} {value} "
def convert_to_int(d):
"""Convert data to integer; returns provided data as integer if the data can be converted; else returns unmodified data
d: data to convert"""
try:
return int(d)
except ValueError:
return d
def insert_in_string(s, index, value):
"""Insert value into string at index
s: string
index: index of insertion
value: value to insert into string"""
return s[:index] + value + s[index:]
def adjust_adjacent_parentheses_int(s):
"""Check if provided string contains adjacent integer and parenthesis, if it does, insert an astrik in between them; returns modified string
s: string"""
#find indices where astrik should be inserted
indices = []
for i in range(len(s)):
if isinstance(convert_to_int(s[i]), int):
if i+1 < len(s) and s[i+1] == "(": #if ( is immediately after an integer, plan to insert astrik
indices.append(i+1)
elif i-1 >= 0 and s[i-1] == ")": #if ) is immediately before an integer, plan to insert astrik
indices.append(i)
#insert astriks in their respective indices
if indices:
for i in range(len(indices)):
s = insert_in_string(s, indices[i]+i, "*")
return s
def replace_operators(s, symbol, operator):
"""Change symbol in provided string to its corresponding operator; returns modified string
s: string
symbol: symbol to change
operator: operator to replace with symbol"""
return s.replace(symbol, operator)
def calculate_result():
"""Print calculated result into entry widget"""
global parentheses, interchangeable_operators
result = str(result_lbl["text"])
if not result:
return
else:
result_lbl["text"] = ""
#modify string so it can be appropriately evaluated by the eval() function
for s in interchangeable_operators:
if s[0] in result:
result = replace_operators(result, s[0], s[1])
#insert astriks in between parentheses and integers
if any(c in parentheses for c in result):
result = adjust_adjacent_parentheses_int(result)
try:
result = eval(result)
except (SyntaxError, NameError) as e:
result_lbl["text"] = "Error"
return
#convert evaluation to integer form if the float only has trailing 0s
if isinstance(result, float) and result-int(result) == 0:
result = convert_to_int(result)
result_lbl["text"] = result
def key_bindings(key):
"""Controller for executing corresponding functions related to key input. This function is binded to <Key> from tkinter
key: key object from tkinter binding"""
global acceptable_inputs
if key.char == "\r": #enter key was pressed, calculate expression currently in input
calculate_result()
elif key.keysym == "BackSpace": #delete latest character
cur_text = str(result_lbl["text"])
result_lbl["text"] = cur_text[:len(cur_text)-1]
elif key.char in acceptable_inputs: #insert character from key press into input bar if character is eligible
insert_value(key.char)
def clear_result():
"""Clear all characters contain within the result entry widget"""
result_lbl["text"] = ""
#initialize variables
interchangeable_operators = (("÷", "/"), ("×", "*"))
acceptable_inputs = ("+", "-", "/", "*", "1", "2", "3", "4", "5", "6", "7", "8", "9", "0", ".", "(", ")")
parentheses = ("(", ")")
#initialize window
window = tk.Tk()
window.title("Basic Calculator")
window.geometry("320x180")
#result frame/entry setup
result_frm = tk.Frame(master=window)
result_frm.pack(fill=tk.BOTH, expand=True)
result_lbl = tk.Label(text="", master=result_frm, fg="black", relief=tk.FLAT)
result_lbl.pack(expand=True)
#setup primary button grid/frame
main_btn_frm = tk.Frame(master=window, bg="#CAC8AE")
main_btn_frm.pack(fill=tk.BOTH, expand=True)
main_btn_frm.rowconfigure([0, 1, 2, 3], weight=1)
main_btn_frm.rowconfigure(4, weight=2)
main_btn_frm.columnconfigure([0, 1, 2, 3], weight=1)
#initialize all buttons inside of grid
btn_padding = 1
border_width = 3
tk.Button(master=main_btn_frm, text="1", fg="black", bg="orange", relief=tk.RAISED, bd=border_width, command=partial(insert_value, "1")).grid(row=0, column=0, padx=btn_padding, pady=btn_padding, sticky="nsew")
tk.Button(master=main_btn_frm, text="2", fg="black", bg="orange", relief=tk.RAISED, bd=border_width, command=partial(insert_value, "2")).grid(row=0, column=1, padx=btn_padding, pady=btn_padding, sticky="nsew")
tk.Button(master=main_btn_frm, text="3", fg="black", bg="orange", relief=tk.RAISED, bd=border_width, command=partial(insert_value, "3")).grid(row=0, column=2, padx=btn_padding, pady=btn_padding, sticky="nsew")
tk.Button(master=main_btn_frm, text="+", fg="black", bg="orange", relief=tk.RAISED, bd=border_width, command=partial(insert_value, "+")).grid(row=0, column=3, padx=btn_padding, pady=btn_padding, sticky="nsew")
tk.Button(master=main_btn_frm, text="4", fg="black", bg="orange", relief=tk.RAISED, bd=border_width, command=partial(insert_value, "4")).grid(row=1, column=0, padx=btn_padding, pady=btn_padding, sticky="nsew")
tk.Button(master=main_btn_frm, text="5", fg="black", bg="orange", relief=tk.RAISED, bd=border_width, command=partial(insert_value, "5")).grid(row=1, column=1, padx=btn_padding, pady=btn_padding, sticky="nsew")
tk.Button(master=main_btn_frm, text="6", fg="black", bg="orange", relief=tk.RAISED, bd=border_width, command=partial(insert_value, "6")).grid(row=1, column=2, padx=btn_padding, pady=btn_padding, sticky="nsew")
tk.Button(master=main_btn_frm, text="-", fg="black", bg="orange", relief=tk.RAISED, bd=border_width, command=partial(insert_value, "-")).grid(row=1, column=3, padx=btn_padding, pady=btn_padding, sticky="nsew")
tk.Button(master=main_btn_frm, text="7", fg="black", bg="orange", relief=tk.RAISED, bd=border_width, command=partial(insert_value, "7")).grid(row=2, column=0, padx=btn_padding, pady=btn_padding, sticky="nsew")
tk.Button(master=main_btn_frm, text="8", fg="black", bg="orange", relief=tk.RAISED, bd=border_width, command=partial(insert_value, "8")).grid(row=2, column=1, padx=btn_padding, pady=btn_padding, sticky="nsew")
tk.Button(master=main_btn_frm, text="9", fg="black", bg="orange", relief=tk.RAISED, bd=border_width, command=partial(insert_value, "9")).grid(row=2, column=2, padx=btn_padding, pady=btn_padding, sticky="nsew")
tk.Button(master=main_btn_frm, text="×", fg="black", bg="orange", relief=tk.RAISED, bd=border_width, command=partial(insert_value, "×")).grid(row=2, column=3, padx=btn_padding, pady=btn_padding, sticky="nsew")
tk.Button(master=main_btn_frm, text="0", fg="black", bg="orange", relief=tk.RAISED, bd=border_width, command=partial(insert_value, "0")).grid(row=3, column=0, padx=btn_padding, pady=btn_padding, sticky="nsew", columnspan=2)
tk.Button(master=main_btn_frm, text=".", fg="black", bg="orange", relief=tk.RAISED, bd=border_width, command=partial(insert_value, ".")).grid(row=3, column=2, padx=btn_padding, pady=btn_padding, sticky="nsew")
tk.Button(master=main_btn_frm, text="÷", fg="black", bg="orange", relief=tk.RAISED, bd=border_width, command=partial(insert_value, "÷")).grid(row=3, column=3, padx=btn_padding, pady=btn_padding, sticky="nsew")
tk.Button(master=main_btn_frm, text="(", fg="black", bg="orange", relief=tk.RAISED, bd=border_width, command=partial(insert_value, "(")).grid(row=4, column=0, padx=btn_padding, pady=btn_padding, sticky="nsew")
tk.Button(master=main_btn_frm, text="C", fg="black", bg="red", relief=tk.RAISED, bd=border_width, command=clear_result).grid(row=4, column=1, padx=btn_padding, pady=btn_padding, sticky="nsew")
tk.Button(master=main_btn_frm, text="=", fg="black", bg="green", relief=tk.RAISED, bd=border_width, command=calculate_result).grid(row=4, column=2, padx=btn_padding, pady=btn_padding, sticky="nsew")
tk.Button(master=main_btn_frm, text=")", fg="black", bg="orange", relief=tk.RAISED, bd=border_width, command=partial(insert_value, ")")).grid(row=4, column=3, padx=btn_padding, pady=btn_padding, sticky="nsew")
#binding(s)
window.bind("<Key>", key_bindings)
#main loop
window.mainloop()
</code></pre>
|
[] |
[
{
"body": "<p>First: despite running arbitrary code off of the internet being a Bad Idea, I did, and it works! So congratulations.</p>\n<p>As with most beginner Tk code, this is a big hash of global setup code and global widget references. That needs to change. Some of your functions, namely</p>\n<ul>\n<li><code>convert_to_int</code></li>\n<li><code>insert_in_string</code></li>\n<li><code>adjust_adjacent_parentheses_int</code></li>\n<li><code>replace_operators</code></li>\n</ul>\n<p>should stay global, and basically the rest of the code should be moved into functions or class methods.</p>\n<p>Other bits:</p>\n<ul>\n<li>"astrik" is spelled "asterisk".</li>\n<li>Add a main guard at the bottom.</li>\n<li>Capitalize your global constants.</li>\n<li>Add some type hints. This is difficult for <code>convert_to_int</code> since it would technically work for inputs of <code>str</code>, <code>int</code> or <code>float</code>, and may return any of those - so you would need some large <code>Union</code>s. However, this speaks less to the convenience of the type hint system and more to the fact that this isn't a very safe way to go about passing data around.</li>\n</ul>\n<p>The button setup is a mess. DRY - don't repeat yourself - and make an intermediate function and some loops to help you out.</p>\n<h2>Suggested</h2>\n<pre><code>import tkinter as tk\nfrom functools import partial\n\n\n# initialize variables\nfrom typing import Union, Callable, Optional\n\nINTERCHANGEABLE_OPS = (("÷", "/"), ("×", "*"))\nGOOD_INPUTS = (\n "+", "-", "/", "*",\n "1", "2", "3", "4", "5", "6", "7", "8", "9", "0",\n ".", "(", ")",\n)\nPARENS = ("(", ")")\n\n\ndef convert_to_int(d):\n """Convert data to integer; returns provided data as integer if the data can be converted; else returns unmodified data\n\n d: data to convert"""\n\n try:\n return int(d)\n except ValueError:\n return d\n\n\ndef insert_in_string(s: str, index: int, value: str) -> str:\n """Insert value into string at index\n\n s: string\n index: index of insertion\n value: value to insert into string"""\n\n return s[:index] + value + s[index:]\n\n\ndef adjust_adjacent_parentheses_int(s: str) -> str:\n """Check if provided string contains adjacent integer and parenthesis, if it does, insert an astrik in between them; returns modified string\n\n s: string"""\n\n # find indices where asterisk should be inserted\n indices = []\n for i in range(len(s)):\n if isinstance(convert_to_int(s[i]), int):\n if i + 1 < len(s) and s[i + 1] == "(": # if ( is immediately after an integer, plan to insert astrik\n indices.append(i + 1)\n elif i - 1 >= 0 and s[i - 1] == ")": # if ) is immediately before an integer, plan to insert astrik\n indices.append(i)\n\n # insert asterisks in their respective indices\n if indices:\n for i in range(len(indices)):\n s = insert_in_string(s, indices[i] + i, "*")\n\n return s\n\n\ndef replace_operators(s: str, symbol: str, operator: str) -> str:\n """Change symbol in provided string to its corresponding operator; returns modified string\n\n s: string\n symbol: symbol to change\n operator: operator to replace with symbol"""\n\n return s.replace(symbol, operator)\n\n\nclass Window:\n def __init__(self):\n # initialize window\n self.window = tk.Tk()\n self.window.title("Basic Calculator")\n self.window.geometry("320x180")\n\n # result frame/entry setup\n result_frm = tk.Frame(master=self.window)\n result_frm.pack(fill=tk.BOTH, expand=True)\n\n self.result_lbl = tk.Label(text="", master=result_frm, fg="black", relief=tk.FLAT)\n self.result_lbl.pack(expand=True)\n\n # setup primary button grid/frame\n main_btn_frm = tk.Frame(master=self.window, bg="#CAC8AE")\n main_btn_frm.pack(fill=tk.BOTH, expand=True)\n\n main_btn_frm.rowconfigure([0, 1, 2, 3], weight=1)\n main_btn_frm.rowconfigure(4, weight=2)\n main_btn_frm.columnconfigure([0, 1, 2, 3], weight=1)\n\n # initialize all buttons inside of grid\n btn_padding = 1\n border_width = 3\n\n def button(text: str, row: int, col: int, colspan=1, **kwargs) -> tk.Button:\n button_args = {\n 'text': text,\n 'command': partial(self.insert_value, text),\n 'master': main_btn_frm,\n 'fg': 'black',\n 'bg': 'orange',\n 'relief': tk.RAISED,\n 'bd': border_width,\n }\n button_args.update(kwargs)\n\n return tk.Button(**button_args).grid(\n row=row,\n column=col,\n columnspan=colspan,\n padx=btn_padding,\n pady=btn_padding,\n sticky="nsew",\n )\n\n for row, syms in enumerate((\n '123+',\n '456-',\n '789×',\n )):\n for col, sym in enumerate(syms):\n button(sym, row, col)\n\n button('0', 3, 0, colspan=2)\n button('.', 3, 2)\n button('÷', 3, 3)\n button('(', 4, 0)\n button('C', 4, 1, command=self.clear_result, bg='red')\n button('=', 4, 2, command=self.calculate_result, bg='green')\n button(')', 4, 3)\n\n # binding(s)\n self.window.bind("<Key>", self.key_bindings)\n\n def insert_value(self, value: str):\n """Insert value into input entry widget\n if value is an operator, add spacing on each side of it\n\n value: value to add to widget"""\n\n value = convert_to_int(value)\n cur_text = str(self.result_lbl["text"])\n\n if cur_text == "Error":\n self.result_lbl["text"] = f"{value}"\n elif isinstance(value, int) or len(cur_text) == 0 or value in ("(", ")", "."): # don't add additional spacing\n self.result_lbl["text"] = f"{cur_text}{value}"\n else: # add spacing in between provided value (only if value is an arithmetic operator)\n for s in INTERCHANGEABLE_OPS:\n if s[1] in value:\n value = replace_operators(value, s[1], s[0]) # change typed "/" to "÷" and/or "*" to "×"\n self.result_lbl["text"] = f"{cur_text} {value} "\n\n def calculate_result(self):\n """Print calculated result into entry widget"""\n\n result = str(self.result_lbl["text"])\n\n if not result:\n return\n else:\n self.result_lbl["text"] = ""\n\n # modify string so it can be appropriately evaluated by the eval() function\n for s in INTERCHANGEABLE_OPS:\n if s[0] in result:\n result = replace_operators(result, s[0], s[1])\n\n # insert astriks in between parentheses and integers\n if any(c in PARENS for c in result):\n result = adjust_adjacent_parentheses_int(result)\n\n try:\n result = eval(result)\n except (SyntaxError, NameError):\n self.result_lbl["text"] = "Error"\n return\n\n # convert evaluation to integer form if the float only has trailing 0s\n if isinstance(result, float) and result - int(result) == 0:\n result = convert_to_int(result)\n\n self.result_lbl["text"] = result\n\n def key_bindings(self, key: tk.Event):\n """Controller for executing corresponding functions related to key input. This function is binded to <Key> from tkinter\n\n key: key object from tkinter binding"""\n\n if key.char == "\\r": # enter key was pressed, calculate expression currently in input\n self.calculate_result()\n elif key.keysym == "BackSpace": # delete latest character\n cur_text = str(self.result_lbl["text"])\n self.result_lbl["text"] = cur_text[:len(cur_text) - 1]\n elif key.char in GOOD_INPUTS: # insert character from key press into input bar if character is eligible\n self.insert_value(key.char)\n\n def clear_result(self):\n """Clear all characters contain within the result entry widget"""\n\n self.result_lbl["text"] = ""\n\n def run(self):\n # main loop\n self.window.mainloop()\n\n\nif __name__ == '__main__':\n Window().run()\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-25T13:21:08.690",
"Id": "253894",
"ParentId": "253860",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "253894",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-24T03:57:27.130",
"Id": "253860",
"Score": "3",
"Tags": [
"python",
"python-3.x",
"calculator",
"tkinter"
],
"Title": "Tkinter Basic Calculator"
}
|
253860
|
<p>The code below selects all items that are locked. How can I optimise it?<br />
<code>ShopItemData</code> doesn't contain a field for locked/unlocked.</p>
<p><code>_allItems</code> is a <code>ShopItemData[]</code></p>
<p><code>_codaCommonShopItems</code>, <code>_codaRareShopItems</code>, and <code>_codaEpicShopItems</code> are <code>CodaShopItem[]</code>s.</p>
<pre><code>public class CodaShopItem : MonoBehaviour
{
private Button _itemButton;
private bool _inUse;
private int _itemId;
private CodaShopScreen.ItemRarity _itemRarity;
public int ItemId => _itemId;
public bool Unlocked;
public bool InUse => _inUse;
public CodaShopScreen.ItemRarity ItemRarity => _itemRarity;
}
public class ShopItemData : ScriptableObject
{
public int ItemId;
public Sprite ItemSprite;
public CodaShopScreen.ItemRarity ItemRarity;
public GameObject InGamePrefab;
public GameObject PreviewPrefab;
}
public IEnumerable<ShopItemData> GetLockedItems()
{
var lockedCommonItems = _codaCommonShopItems.Where(item => !item.Unlocked).ToArray();
var lockedRareItems = _codaRareShopItems.Where(item => !item.Unlocked).ToArray();
var lockedEpicItems = _codaEpicShopItems.Where(item => !item.Unlocked).ToArray();
var allLockedItems = new List<ShopItemData>();
var allItemDatas = GetAllItems().ToArray();
for (var i = 0; i < lockedCommonItems.Length; i++)
{
var lockedItemData = allItemDatas.First(item => item.ItemId == lockedCommonItems[i].ItemId && item.ItemRarity == lockedCommonItems[i].ItemRarity);
allLockedItems.Add(lockedItemData);
}
for (var i = 0; i < lockedRareItems.Length; i++)
{
var lockedItemData = allItemDatas.First(item => item.ItemId == lockedRareItems[i].ItemId && item.ItemRarity == lockedRareItems[i].ItemRarity);
allLockedItems.Add(lockedItemData);
}
for (var i = 0; i < lockedEpicItems.Length; i++)
{
var lockedItemData = allItemDatas.First(item => item.ItemId == lockedEpicItems[i].ItemId && item.ItemRarity == lockedEpicItems[i].ItemRarity);
allLockedItems.Add(lockedItemData);
}
return allLockedItems;
}
public IEnumerable<ShopItemData> GetAllItems()
{
return _allItems;
}
</code></pre>
<p>And this is how shop items are created</p>
<pre><code>private void CreateCommonShopItems()
{
var commonItems = Resources.LoadAll<ShopItemData>(ShopItemDataPath).Where(item => item.ItemRarity == ItemRarity.Common);
var commonCategory = _itemCategories.First(item => item.ItemRarity == ItemRarity.Common);
commonCategory.Create(ref _codaCommonShopItems, commonItems.ToArray());
}
</code></pre>
<p>basically I am getting the item datas and passing them into another function which turns them into <code>_codaCommonShopItem</code> and fill their properties</p>
<pre><code>_codaCommonShopItem[i].Init(items[i].ItemId, items[i].ItemRarity, items[i].ItemSprite);
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-24T14:52:11.393",
"Id": "500647",
"Score": "0",
"body": "Please include `GetAllItems` code, and for simplicity, explain the releationship between `_codaCommonShopItems` and `_codaRareShopItems` and `_codaEpicShopItems` (you can provide their models or any related FK between them."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-24T14:53:41.677",
"Id": "500648",
"Score": "0",
"body": "Just for starter, if they have common `FK`, a simple `JOIN` would solve your issue."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-24T15:18:25.330",
"Id": "500649",
"Score": "0",
"body": "Thanks, i have added more details about those classes @iSR5"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-24T15:22:28.597",
"Id": "500651",
"Score": "0",
"body": "I couldn't use join to make it easier, maybe because i am not very familiar with linq queries."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-24T15:31:27.313",
"Id": "500652",
"Score": "0",
"body": "do `_codaCommonShopItems`, `_codaRareShopItems` and `_codaEpicShopItems` use `ShopItemData` as source ? if yes, then you can combine their logic (the `Where` conditions) with `!item.Unlocked` to get all of them from the data-source directly."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-24T15:49:34.000",
"Id": "500653",
"Score": "0",
"body": "Yes ShopItemData is the class that i am using to get the item info then pass it to CodaShopItem class. But the ShopItemData doesn't contain the locked/unlocked property."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-25T04:54:37.983",
"Id": "500681",
"Score": "0",
"body": "Could you show the query of the CodaCommon, CodaRare, and CodaEpic ? I need to see how to get them from ShopItemData."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-25T09:50:19.297",
"Id": "500687",
"Score": "0",
"body": "They are just arrays of CodaShopItem and i am filling their properties from the data i am getting from ShopItemData model class. Added more detail."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-25T10:06:20.763",
"Id": "500689",
"Score": "0",
"body": "Thank you, now it's almost clear to me what's going on. You didn't mention that `ItemRarity` is an `enum` object."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-25T10:06:58.547",
"Id": "500690",
"Score": "0",
"body": "you can replace `GetLockedItems` code with this line `return _allItems.Where(item => !item.Unlocked && (item.ItemRarity == ItemRarity.Common || item.ItemRarity == ItemRarity.Rare || item.ItemRarity == ItemRarity.Epic))?.ToArray();`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-25T10:18:20.210",
"Id": "500691",
"Score": "0",
"body": "Thanks @iSR5 but ShopItemData doesn't have a field for Unlocked thats why i am matching each CodaShopItem with ShopItemData by their item ids."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-26T17:23:40.037",
"Id": "500791",
"Score": "2",
"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)."
}
] |
[
{
"body": "<p>In short terms, you can do this :</p>\n<pre><code>public IEnumerable<ShopItemData> GetLockedItems()\n{\n var allLockedItems = new List<ShopItemData>();\n \n allLockedItems.AddRange(_codaCommonShopItems.Where(item => !item.Unlocked));\n allLockedItems.AddRange(_codaRareShopItems.Where(item => !item.Unlocked));\n allLockedItems.AddRange(_codaEpicShopItems.Where(item => !item.Unlocked));\n \n var result = _allItems\n .Join(allLockedItems, \n items => items.ItemId, \n locked => locked.ItemId,\n (items, locked) => new { AllItems = items, LockedItems = locked })\n .Where(x => x.AllItems.ItemId == x.LockedItems.ItemId && x.AllItems.ItemRarity == x.LockedItems.ItemRarity)\n .Select(x=> new ShopItemData\n {\n ItemId = AllItems.ItemId, \n ItemSprite = AllItems.ItemSprite,\n ItemRarity = AllItems.ItemRarity, \n InGamePrefab = AllItems.InGamePrefab, \n PreviewPrefab = AllItems.PreviewPrefab\n });\n\n return result;\n} \n</code></pre>\n<p>So, you add all unlocked items in the list, then join the new list with the <code>_allItems</code> on the same condition you use.</p>\n<p>What I suggest, is to make a child class that would flatten and combine both objects properties. something like this :</p>\n<pre><code>private class JoinedShopItemData\n{\n public int ItemId { get; set; }\n\n public bool Unlocked { get; set; }\n\n public bool InUse { get; set; }\n\n public CodaShopScreen.ItemRarity ItemRarity { get; set; }\n\n public Sprite ItemSprite { get; set; }\n\n public GameObject InGamePrefab { get; set; }\n\n public GameObject PreviewPrefab { get; set; }\n}\n</code></pre>\n<p>then, you can initialize this object in your constructor, and prepare it to be used as filtered source of <code>_allItems</code> for the current class.</p>\n<p>Something like :</p>\n<pre><code>private IEnumerable<JoinedShopItemData> GetJoinedShopItemData(IEnumerable<CodaShopItem> source)\n{\n foreach(var coda in source)\n {\n foreach(var item in _allItems)\n {\n if(item.ItemId == coda.ItemId && item.ItemRarity == coda.ItemRarity)\n {\n yield return new JoinedShopItemData\n {\n ItemId = AllItems.ItemId, \n ItemSprite = AllItems.ItemSprite,\n ItemRarity = AllItems.ItemRarity, \n InGamePrefab = AllItems.InGamePrefab, \n PreviewPrefab = AllItems.PreviewPrefab, \n Unlocked = LockedItems.Unlocked, \n InUse = LockedItems.InUse \n }; \n }\n }\n }\n}\n</code></pre>\n<p>or use linq (like the first example)\nNow, assuming you'll have a global <code>List<JoinedShopItemData></code> named <code>_joinedShopItemData</code> that will hold <code>GetJoinedShopItemData</code> results.</p>\n<p>In this case, your <code>GetLockedItems</code> method would be :</p>\n<pre><code>public IEnumerable<ShopItemData> GetLockedItems()\n{\n return _joinedShopItemData\n .Where(item => !item.Unlocked && (item.ItemRarity == ItemRarity.Common || item.ItemRarity == ItemRarity.Rare || item.ItemRarity == ItemRarity.Epic))\n .Select(item => new ShopItemData \n {\n ItemId = item.ItemId, \n ItemSprite = item.ItemSprite,\n ItemRarity = item.ItemRarity, \n InGamePrefab = item.InGamePrefab, \n PreviewPrefab = item.PreviewPrefab\n }).ToArray();\n} \n</code></pre>\n<p>This will elemnate the need of creating a separate collection for each property condition (like <code>_codaCommonShopItems</code>, <code>_codaRareShopItems</code> ..etc.). As you will always have a joined object which you can access easily.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-25T15:03:28.770",
"Id": "253899",
"ParentId": "253867",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "253899",
"CommentCount": "12",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-24T11:39:30.970",
"Id": "253867",
"Score": "-1",
"Tags": [
"c#",
"algorithm",
"linq"
],
"Title": "Simplifying for loops that includes conditions with better linq queries"
}
|
253867
|
<p>I wrote a script to list imports of Python projects.
It can print a JSON-ish dict of imported modules (keys) and members (values) as well as only the module names.
It can also optionally exclude certain imports and those from the standard library.</p>
<pre><code>#! /usr/bin/env python3
# lsimports.py - List python project imports
# Copyright (C) 2020 Richard Neumann <mail at richard dash neumann period de>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
"""Lists imports of python modules and packages."""
from argparse import ArgumentParser, Namespace
from collections import defaultdict
from itertools import chain
from json import dumps
from logging import INFO, WARNING, basicConfig, getLogger
from pathlib import Path
from re import fullmatch
from typing import Iterable, Iterator, Set, Tuple
DESCRIPTION = __doc__
FROM_IMPORT = 'from ([\\w\\.]+) import (.*)'
IMPORT = 'import (.*)'
LOG_FORMAT = '[%(levelname)s] %(name)s: %(message)s'
LOGGER = getLogger(Path(__file__).stem)
STDLIB = Path('/usr/lib/python3.9')
def get_imports(filename: Path) -> dict:
"""Lists imports of the given file."""
imports = defaultdict(set)
with filename.open('r') as file:
for line in file:
if not (line := line.strip()):
continue
if (match := fullmatch(FROM_IMPORT, line)) is not None:
module, members = match.groups()
members = set(filter(None, members.split(',')))
elif (match := fullmatch(IMPORT, line)) is not None:
module = match.group(1)
members = set()
else:
continue
imports[module] |= members
return imports
def get_imports_from_files(paths: Iterable[Path]) -> dict:
"""Returns the imports from multiple files."""
imports = {}
for path in paths:
LOGGER.info('Checking: %s', path)
imports.update(get_imports(path))
return imports
def get_module_roots(imports: dict) -> Set[str]:
"""Returns a set of imported module roots."""
roots = set()
for module in imports.keys():
root, *_ = module.split('.')
roots.add(root)
return roots
def lsstdlib(root: Path) -> Iterator[str]:
"""Yields modules and packages of the standard library."""
for path in root.iterdir():
if path.is_file() and path.suffix == '.py' or path.is_dir():
yield path.stem
def iterfiles(path: Path) -> Iterator[Path]:
"""Recursively yields files in a directory."""
if path.is_dir():
for subdir in path.iterdir():
yield from iterfiles(subdir)
elif path.is_file():
yield path
def filterimports(excludes: set, imports: dict) -> Iterator[Tuple[str, set]]:
"""Yields filtered key/value pairs of imports."""
for module, members in imports.items():
root, *_ = module.split('.')
if root not in excludes:
yield (module, members)
def ispyfile(path: Path) -> bool:
"""Checks whether the file is a python file."""
return path.is_file() and path.suffix == '.py'
def jsonify(imports: dict) -> dict:
"""Makes a dict JSON-compliant."""
return {str(key): list(value) for key, value in imports.items()}
def get_args() -> Namespace:
"""Parses and returns the command line arguments."""
parser = ArgumentParser(description=DESCRIPTION)
parser.add_argument('path', nargs='*', type=Path, default=[Path.cwd()],
help='the files and folders to scan for imports')
parser.add_argument('-E', '--exclude-stdlib', action='store_true',
help='exclude imports from the standard library')
parser.add_argument('-e', '--exclude-modules', nargs='+', default=(),
help='exclude the specified imports')
parser.add_argument('-i', '--indent', type=int, metavar='spaces',
help='set indentation for JSON output')
parser.add_argument('-r', '--roots', action='store_true',
help='print only distinct root modules and packages')
parser.add_argument('-s', '--stdlib', type=Path, default=STDLIB,
help='specifies the root of the standard library')
parser.add_argument('-v', '--verbose', action='store_true',
help='print verbose messages')
return parser.parse_args()
def main():
"""Runs the script."""
args = get_args()
basicConfig(format=LOG_FORMAT, level=INFO if args.verbose else WARNING)
files = filter(ispyfile, chain(*map(iterfiles, args.path)))
imports = get_imports_from_files(files)
excludes = set(args.exclude_modules)
if args.exclude_stdlib:
excludes |= set(lsstdlib(args.stdlib))
if excludes:
imports = dict(filterimports(excludes, imports))
if args.roots:
for root in get_module_roots(imports):
print(root)
else:
print(dumps(jsonify(imports), indent=args.indent))
if __name__ == '__main__':
main()
</code></pre>
<p>How can I improve my code?</p>
<p><strong>Update</strong>
Gist: <a href="https://gist.github.com/conqp/cb41511869bba0d7c526e05df431aaf3" rel="nofollow noreferrer">https://gist.github.com/conqp/cb41511869bba0d7c526e05df431aaf3</a></p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-25T01:17:24.860",
"Id": "500678",
"Score": "1",
"body": "This will miss dynamic imports, but that could be quite hard to detect. Or it may be impossible to detect if it executes code that's external or loaded or generated from non-Python files or other sources, although such imports may or may not be considered an import of the project itself."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-27T23:00:06.047",
"Id": "500862",
"Score": "0",
"body": "I think updated version fails on relative imports(import .common # common from same dir). It shows \"Cannot parse \"test.py\" due to syntax error.\" error."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-28T09:20:46.733",
"Id": "500884",
"Score": "0",
"body": "@Vashu This error message is logged when `ast.parse()` throws a `SyntaxError` here: https://gist.github.com/conqp/cb41511869bba0d7c526e05df431aaf3#file-lsimports-py-L97. There's little I can do about that, if `ast` thinks that the code is syntactically incorrect."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-28T09:40:51.040",
"Id": "500885",
"Score": "0",
"body": "@Vashu Thanks for the hint with relative imports, though. I personally never use them, but I updated the script to exclude relative imports now by checking the node level."
}
] |
[
{
"body": "<p><strong>Bug?</strong></p>\n<p>You should probably <code>strip()</code> your values, because I get spurious spaces when I import multiple things from a module:</p>\n<pre><code>from x import y, z\n-> {"x": ["y", " z"]}\n</code></pre>\n<p><strong>Maintainability</strong></p>\n<p>You are currently hard-coding the python version for the built-ins and assume that it can be found in the standard UNIX path. Both of those assumptions might be violated. For the former problem, you could just read the python version:</p>\n<pre><code>import sys\n\nversion = sys.version_info\n\nSTDLIB = Path(f"/usr/lib/python{version.major}.{version.minor}")\n</code></pre>\n<p>But it's probably easier to directly use <code>sys.builtin_module_names</code>:</p>\n<pre><code>('_abc', '_ast', '_bisect', '_blake2', '_codecs', '_collections', '_csv', '_datetime', '_elementtree', '_functools', '_heapq', '_imp', '_io', '_locale', '_md5', '_operator', '_pickle', '_posixsubprocess', '_random', '_sha1', '_sha256', '_sha3', '_sha512', '_signal', '_socket', '_sre', '_stat', '_statistics', '_string', '_struct', '_symtable', '_thread', '_tracemalloc', '_warnings', '_weakref', 'array', 'atexit', 'binascii', 'builtins', 'cmath', 'errno', 'faulthandler', 'fcntl', 'gc', 'grp', 'itertools', 'marshal', 'math', 'posix', 'pwd', 'pyexpat', 'select', 'spwd', 'sys', 'syslog', 'time', 'unicodedata', 'xxsubtype', 'zlib')\n</code></pre>\n<p><strong>Naming</strong></p>\n<p><code>lsstdlib</code> is not a very good name. At least use the python convention (made official in PEP8) of using underscores and call it <code>ls_std_lib</code>.</p>\n<p><strong>Other</strong></p>\n<p>For your <code>iterfiles</code> function, I would use <code>os.walk</code>, even though that is not one of the fancy new <code>Path</code> methods, because it does the recursive descend into sub-directories for you:</p>\n<pre><code>import os\n\ndef iterfiles(path: Path) -> Iterator[Path]:\n """Recursively yields files in a directory."""\n return (Path(os.path.join(dirname, file))\n for dirname, _, files in os.walk(path)\n for file in files)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-24T16:17:20.260",
"Id": "500655",
"Score": "1",
"body": "Thanks for the review. I addressed the problem of the stdlib with `from distutils.sysconfig import get_python_lib` and `STDLIB = Path(get_python_lib(standard_lib=True))`. As for the spaces: Yup, that was a bug, that I did not see. I added stripping: `members = set(filter(None, map(str.strip, members.split(','))))` and also updated the regexes to exclude possible comments: `FROM_IMPORT = '^\\\\s*from ([\\\\w\\\\.]+) import ([^#]*)(?:#.*)?$'` `IMPORT = '^\\\\s*import ([^#]*)(?:#.*)?$'`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-25T00:17:30.453",
"Id": "500675",
"Score": "0",
"body": "`builtin_module_names` lists C extension modules, not all standard library ones - `collections` is missing from it as that module is pure-python."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-25T01:02:36.563",
"Id": "500676",
"Score": "0",
"body": "Thanks for the tip. I already migrated to a static set of standard library modules, as you can see in the latest gist."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-24T16:02:31.700",
"Id": "253873",
"ParentId": "253872",
"Score": "6"
}
},
{
"body": "<p>The biggest issue with this code is that it attempts manual parsing of Python on its own. This is neither the simplest approach nor the most robust. Instead, strongly consider calling into <code>ast</code>:</p>\n<p><a href=\"https://docs.python.org/3.8/library/ast.html#ast-helpers\" rel=\"noreferrer\">https://docs.python.org/3.8/library/ast.html#ast-helpers</a></p>\n<p>which will tell you details about any <code>import</code> statements in code you feed to it. You'll be interested in these:</p>\n<pre><code> | Import(alias* names)\n | ImportFrom(identifier? module, alias* names, int? level)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-24T17:01:11.600",
"Id": "500661",
"Score": "2",
"body": "Thank you for the suggestion of `ast`. I never worked with it, but it turned out to be pretty easy. I refactored the script from the regex approach to using a parsed AST."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-24T16:25:38.590",
"Id": "253874",
"ParentId": "253872",
"Score": "13"
}
},
{
"body": "<h1>Bugs</h1>\n<p><code>FROM_IMPORT = 'from ([\\\\w\\\\.]+) import (.*)'</code></p>\n<p>If code is written as <code>from x import y</code> with more than one space after <code>from</code> or before <code>import</code>, the regex won't match. You should use <code>\\s+</code> in the regex.</p>\n<p>You'll also have problems with accidental matches inside strings:</p>\n<pre class=\"lang-py prettyprint-override\"><code>"""\nExample usage:\n import your_module\n ...\n"""\n</code></pre>\n<p>Use a real Python parser (<code>ast</code>) or actually import the files and look at the modules that actually got imported, which may find imports that were loaded through <code>importlib</code></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-24T16:42:00.043",
"Id": "253875",
"ParentId": "253872",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "253874",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-24T15:36:34.557",
"Id": "253872",
"Score": "6",
"Tags": [
"python",
"python-3.x"
],
"Title": "Script to list imports of Python projects"
}
|
253872
|
<p>Can you please review my Minesweeper implementation in Java?</p>
<pre><code>package com.game;
public class Tile {
private boolean hasMine = false;
private boolean revealed = false;
private int mineCount = 0;
public boolean hasMine() {
return hasMine;
}
public void setHasMine(boolean hasMine) {
this.hasMine = hasMine;
}
public boolean isRevealed() {
return revealed;
}
public void setRevealed(boolean revealed) {
this.revealed = revealed;
}
public int getMineCount() {
return mineCount;
}
public void setMineCount(int mineCount) {
this.mineCount = mineCount;
}
}
</code></pre>
<pre><code>package com.game;
import java.util.Random;
public class Board {
private Tile[][] tiles;
private int N = 0;
private int totalRevealed = 0;
private static int[][] neighbors = {{-1,-1}, {-1,0}, {-1,1}, {0,-1}, {0,1}, {1, 0}, {1, 1}, {1, -1}};
public void initialize(int n, int m) throws Exception {
this.N = n;
tiles = new Tile[n][n];
// If there are more mines to place than the total tiles, throw an exception
if (m > n*n) {
throw new Exception("Invalid mines.");
}
// Initialize each tile in the grid
for (int i=0; i<n; i++) {
for (int j=0; j<n; j++) {
tiles[i][j] = new Tile();
}
}
placeMines(m); // time to place the mines
}
/*
Randomly places mines.
*/
private void placeMines(int m) {
// Need to generate random row and column values to place the mine
Random rand1 = new Random(), rand2 = new Random();
while (m > 0) {
int i = rand1.nextInt(this.N), j = rand2.nextInt(this.N);
//System.out.println("i: " + i + "| j: " + j);
if (!tiles[i][j].hasMine()) {
tiles[i][j].setHasMine(true);
for (int[] nei : neighbors) {
if (i + nei[0] < 0 || j + nei[1] < 0 || i + nei[0] >= this.N || j + nei[1] >= this.N) continue;
if (!tiles[i+nei[0]][j+nei[1]].hasMine()) {
tiles[i+nei[0]][j+nei[1]].setMineCount(tiles[i+nei[0]][j+nei[1]].getMineCount()+1);
}
}
m--;
}
}
}
public void printBoard() {
for (Tile[] tile : tiles) {
for (Tile t : tile) {
if (t.hasMine() && t.isRevealed()){
System.out.print("\t " + "*");
}else {
if (t.isRevealed()) {
System.out.print("\t " + t.getMineCount());
} else {
System.out.print("\t -");
}
}
}
System.out.println();
}
}
/*
* If clicked on a mine, reveal all the mines and then it's game over.
*
* If revealed all the tiles without stepping on a mine, it's game over too.
*/
public boolean click(int i, int j) {
if (tiles[i][j].isRevealed()) return false;
if (tiles[i][j].hasMine()) {
revealAllMines();
return true;
}
reveal(tiles[i][j], i, j);
return totalRevealed == (this.N * this.N);
}
/*
* Reveals all possible neighbors and their neighbors recursively.
*
*/
private void reveal(Tile curr, int i, int j) {
if (curr.getMineCount() == 0) { // reveal neighboring tiles
curr.setRevealed(true);
totalRevealed++;
for (int[] nei : neighbors) {
if (i + nei[0] < 0 || j + nei[1] < 0 || i + nei[0] >= this.N || j + nei[1] >= this.N) continue;
if (!tiles[i+nei[0]][j+nei[1]].hasMine() && !tiles[i+nei[0]][j+nei[1]].isRevealed()) {
//tiles[i+nei[0]][j+nei[1]].revealed = true;
reveal(tiles[i+nei[0]][j+nei[1]], i+nei[0], j+nei[1]);
}
}
} else {
curr.setRevealed(true);
}
}
private void revealAllMines() {
for (Tile[] tile : tiles) {
for (Tile t : tile) {
if (t.hasMine()) {
t.setRevealed(true);
totalRevealed++;
}
}
}
}
}
</code></pre>
<pre><code>package com.game;
import java.util.Scanner;
/*
*
* Implemented Minesweeper game.
*
*/
public class Minesweeper {
public static void main(String[] args) {
Board board = new Board();
try {
Scanner scanner = new Scanner(System.in);
int n = 0, m = 0;
do {
System.out.println("Enter the grid size (less than or equal to 30): ");
n = scanner.nextInt();
System.out.println("Enter the number of mines: ");
m = scanner.nextInt();
} while (n > 30);
board.initialize(n, m);
System.out.println("Initialized board:");
board.printBoard();
boolean gameOver = false;
int row = 0, col = 0;
do {
System.out.println("Row?");
row = scanner.nextInt();
System.out.println("Column?");
col = scanner.nextInt();
if (row == -1 && col == -1) {
System.exit(0);
}
if ((row >= 0 && row < n) && (col >= 0 && col < n)) {
gameOver = board.click(row, col);
if (gameOver) {
System.out.println("\n\nGame Over");
board.printBoard();
System.exit(0);
} else {
System.out.println("\n\n");
board.printBoard();
System.out.println("\n\n");
}
}
} while (!gameOver);
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
</code></pre>
<p>Implemented Minesweeper game without a graphical interface.</p>
<p><strong>Steps to run the game:</strong></p>
<p>I have created Minesweeper.java class. Run it and it will ask you to enter the grid size, mines, row and column on every play.</p>
<p>Currently, you cannot create a grid larger than 30 x 30 tiles.</p>
<p>The total mines cannot exceed the total tiles in the grid.</p>
<p><strong>Rules to play:</strong></p>
<ol>
<li>Create a board of size n x n tiles.</li>
<li>Enter the number of mines to place on the board randomly.</li>
<li>Enter valid row number and column number (0 based index).</li>
<li>If you step on a mine, it's game over and all the mines are revealed.</li>
<li>You can win by not stepping on any mine and reveal all the safe tiles.</li>
</ol>
<p>Please let me know your feedback.</p>
<p>Thanks.</p>
|
[] |
[
{
"body": "<p>Quite nicely done, actually.</p>\n<hr />\n<p>It's interesting regarding how you name things, you either very good names, or useless ones, there is no in-between.</p>\n<pre class=\"lang-java prettyprint-override\"><code> private int N = 0;\n\n //...\n\n public void initialize(int n, int m) throws Exception {\n this.N = n;\n tiles = new Tile[n][n];\n \n // If there are more mines to place than the total tiles, throw an exception\n if (m > n*n) {\n throw new Exception("Invalid mines.");\n }\n \n // Initialize each tile in the grid\n for (int i=0; i<n; i++) {\n for (int j=0; j<n; j++) {\n \n tiles[i][j] = new Tile();\n }\n }\n \n placeMines(m); // time to place the mines\n \n }\n</code></pre>\n<p>So much readability could be gained by using "columns", "rows", "column", "row" or "x" and "y" here is variable names. "m" could be called "mineCount" or similar.</p>\n<p>I have roughly two rules when it comes to naming things:</p>\n<ol>\n<li>Name it after what it does or contains.</li>\n<li>You're only allowed to use single-letter names if you're dealing with dimensions. Yes, that includes loop counters.</li>\n</ol>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code> /*\n Randomly places mines.\n */\n private void placeMines(int m) {\n</code></pre>\n<p><a href=\"https://www.oracle.com/technical-resources/articles/java/javadoc-tool.html\" rel=\"nofollow noreferrer\">Javadoc</a></p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code> // Need to generate random row and column values to place the mine\n Random rand1 = new Random(), rand2 = new Random();\n</code></pre>\n<p>Instead of using two <code>Random</code>s locally here, accept a single <code>long</code> as seed for a single <code>Random</code>. That would allow people to get the seed of the game and replay it, meaning the games are reproducible.</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code> while (m > 0) {\n int i = rand1.nextInt(this.N), j = rand2.nextInt(this.N);\n //System.out.println("i: " + i + "| j: " + j);\n \n if (!tiles[i][j].hasMine()) {\n</code></pre>\n<p>The more mines you have in the game, the more likely you are approaching infinity with this when filling the field.</p>\n<p>Most interestingly, randomly accessing a 2D grid without hitting the same tile twice is an interesting problem that I've been seeing for years. One solution is to push every index of every cell into an array, shuffle it, and use the top "mineCount" index to place the mines. That's called <a href=\"https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle\" rel=\"nofollow noreferrer\">Fisher-Yates shuffle</a>.</p>\n<p>You can actually simplify this, by not only putting the cells into a 2D array for accessing, but by storing an additional reference in a <code>List</code>. Randomly shuffling the <code>List</code> of cells will yield the same result and the time used for placing the mines is always the same.</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code>for (int[] nei : neighbors) {\n</code></pre>\n<p>Again, don't shorten variable names just because you can. It makes the code harder to read, harder to understand and harder to maintain.</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code> for (int[] nei : neighbors) {\n \n if (i + nei[0] < 0 || j + nei[1] < 0 || i + nei[0] >= this.N || j + nei[1] >= this.N) continue;\n \n if (!tiles[i+nei[0]][j+nei[1]].hasMine()) {\n tiles[i+nei[0]][j+nei[1]].setMineCount(tiles[i+nei[0]][j+nei[1]].getMineCount()+1);\n }\n }\n</code></pre>\n<p>It would be much easier if you calculate the count after you've placed all mines. Actually, it might be interesting to do this only at runtime when the player has clicked a cell.</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code> for (Tile[] tile : tiles) {\n \n for (Tile t : tile) {\n</code></pre>\n<p>I'd suggest to always use a int-loop to access the board, that keeps it rather easy to read and is always the same.</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code>public void printBoard() {\n</code></pre>\n<p>Ideally, printing and interacting with the board (getting the user input) would be in another class.</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code>System.out.println("Enter the grid size (less than or equal to 30): ");\n</code></pre>\n<p>Why the arbitrary limitation?</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code>System.exit(0);\n</code></pre>\n<p>Calling <code>System.exit</code> is not a "global return", it's a "okay, let's kill the JVM" kinda thing. Threads will be stopped hard, <code>finally</code> blocks might not be executed and so on. It is a hard stop to all JVM activity and should only be used when you can afford to lose state.</p>\n<p>Which, granted, is the case in this case, but still.</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code>} while (!gameOver);\n</code></pre>\n<p>Inverting the condition would be easier to read.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-25T19:04:16.250",
"Id": "253904",
"ParentId": "253876",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-24T17:24:12.907",
"Id": "253876",
"Score": "5",
"Tags": [
"java",
"minesweeper"
],
"Title": "My Minesweeper implementation in Java"
}
|
253876
|
<p>I wrote a small middleware for redirecting between WWW URLs.</p>
<p>The most important thing that I want to change is to make it super fast.</p>
<p>Here's what it is doing:</p>
<p>If the host is localhost or mywebsite.com without any subdomains and without www, it will redirect to www.localhost or <a href="http://www.mywebsite.com" rel="nofollow noreferrer">www.mywebsite.com</a>.</p>
<p>If the host starts with www. AND has subdomains, it will redirect to a url without www.</p>
<pre class="lang-cs prettyprint-override"><code>using System;
using System.Threading.Tasks;
using System.Text.RegularExpressions;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Extensions;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.Logging;
namespace Website.Middlewares
{
public class WWWRedirectionMiddleware
{
private readonly RequestDelegate _next;
private string _domain;
private int _https_port;
public WWWRedirectionMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task InvokeAsync(HttpContext context)
{
var request = context.Request;
var response = context.Response;
var host = request.Host;
if (Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") == "Development")
{
_domain = "localhost";
_https_port = 5001;
}
else
{
_domain = "seaoftools.com";
_https_port = 80;
}
// Redirect to www domain if url is home page
if (host.Host.Equals(_domain, StringComparison.OrdinalIgnoreCase))
{
host = new HostString("www." + host.Host, _https_port);
var redirectUrl = UriHelper.BuildAbsolute(
"https",
host,
request.PathBase,
request.Path,
request.QueryString);
response.Redirect(redirectUrl, true);
return;
} // Redirect to non-www domain if url is with a subdomain
else if (host.Value.StartsWith("www.", StringComparison.OrdinalIgnoreCase)
&& Regex.Replace(host.Host, @"www.|" + _domain, String.Empty) != String.Empty)
{
host = new HostString(host.Host.Replace("www.", String.Empty), _https_port);
var redirectUrl = UriHelper.BuildAbsolute(
"https",
host,
request.PathBase,
request.Path,
request.QueryString);
response.Redirect(redirectUrl, true);
return;
}
await _next(context);
}
}
}
</code></pre>
<p>What should I change to make the middleware run faster?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-24T20:52:09.143",
"Id": "500671",
"Score": "0",
"body": "Welcome to the Code Review Community. Reviews generally require more code than debugging, please include the entire class in the question."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-25T08:01:54.613",
"Id": "500683",
"Score": "0",
"body": "@pacmaninbw stack exchange shows me an error when I add the full code so I posted only the main part of the code and the full code I posted in a link to paste bin"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-25T10:43:56.837",
"Id": "500692",
"Score": "0",
"body": "“_stack exchange shows me an error when I add the full code_” - what do you mean by “stack exchange”? is that on code review or another site like stack overflow?? what is the error?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-25T10:58:18.527",
"Id": "500694",
"Score": "0",
"body": "the error was “Your post appears to contain code that is not properly formatted” but now it's fixed I added the whole code @SᴀᴍOnᴇᴌᴀ"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-25T12:11:42.780",
"Id": "500702",
"Score": "0",
"body": "To anyone in the close vote queue, @SᴀᴍOnᴇᴌᴀ fixed the problem."
}
] |
[
{
"body": "<p>Quick remarks:</p>\n<ul>\n<li><p><code>_https_port</code>: do not use underscores in variable names etc., except at the start.</p>\n</li>\n<li><p><code>_https_port = 80;</code> The HTTPS port is most definitely not port 80.</p>\n</li>\n<li><p>The logic to fill <code>redirectUrl</code> and then redirect is duplicated. It should be a method that gets called. I'd move the "compile new host value in these specific cases" logic to a method and return the resulting <code>HostString</code>, then compare that <code>HostString</code> to the existing <code>host</code> and execute the redirect if they're different.</p>\n</li>\n<li><p>The string <code>"www."</code> is repeatedly used. It would be better to store it in a <code>const string</code>. Same for <code>"https"</code>.</p>\n</li>\n<li><p>In one if you say <code>host.Host</code>, yet in the other you say <code>host.Value</code>.</p>\n</li>\n<li><p>Microsoft has guidelines against using more than three capital letters in a row. So <code>"WWW"</code> should become <code>"Www"</code> when it is part of a class name or method name etc.</p>\n</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-27T08:40:21.643",
"Id": "500817",
"Score": "0",
"body": "I am wondering if what you desire couldn't be done better through https://docs.microsoft.com/en-us/iis/extensions/url-rewrite-module/creating-rewrite-rules-for-the-url-rewrite-module . Or see https://docs.microsoft.com/en-us/aspnet/core/fundamentals/url-rewriting?view=aspnetcore-5.0 ."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-26T17:47:41.940",
"Id": "253932",
"ParentId": "253879",
"Score": "2"
}
},
{
"body": "<p>If you add <code>IWebHostEnvironment</code> as a dependency to the middleware class, you can simplify the environment check by this:</p>\n<pre class=\"lang-c# prettyprint-override\"><code>if (webHostEnvironment.IsDevelopment())\n{\n \n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-26T23:00:37.683",
"Id": "253941",
"ParentId": "253879",
"Score": "3"
}
},
{
"body": "<p>My final code after all of the optimization:</p>\n<pre class=\"lang-cs prettyprint-override\"><code>using System;\nusing System.Threading.Tasks;\nusing Microsoft.AspNetCore.Builder;\nusing Microsoft.AspNetCore.Http;\nusing Microsoft.AspNetCore.Http.Extensions;\nusing Microsoft.AspNetCore.Hosting;\nusing Microsoft.Extensions.Hosting;\n\nnamespace Website.Middlewares\n{\n public class WwwRedirectionMiddleware\n {\n private readonly RequestDelegate _next;\n\n private string _domain;\n private int _httpsPort;\n\n public WwwRedirectionMiddleware(RequestDelegate next, IWebHostEnvironment webHostEnvironment)\n {\n _next = next;\n\n _domain = webHostEnvironment.IsDevelopment() ? "localhost" : "seaoftools.com";\n _httpsPort = webHostEnvironment.IsDevelopment() ? 5001 : 443;\n }\n\n public async Task InvokeAsync(HttpContext context)\n {\n bool IsRedirectNeeded = false;\n\n var request = context.Request;\n var response = context.Response;\n\n var host = request.Host;\n\n string WwwString = "www.";\n\n string HostWithoutWww = host.Host.Replace(WwwString, String.Empty);\n\n string HostWithWww = WwwString + host.Host;\n\n // Redirect to www domain if url is home page\n if (host.Host.Equals(_domain, StringComparison.OrdinalIgnoreCase))\n {\n host = new HostString(HostWithWww, _httpsPort);\n\n IsRedirectNeeded = true;\n } // Redirect to non-www domain if url is with a subdomain\n else if (host.Host.StartsWith(WwwString, StringComparison.OrdinalIgnoreCase) && host.Host.Split(".").Length > 2)\n {\n host = new HostString(HostWithoutWww, _httpsPort);\n\n IsRedirectNeeded = true;\n }\n\n if (IsRedirectNeeded)\n {\n var redirectUrl =\n UriHelper\n .BuildAbsolute("https",\n host,\n request.PathBase,\n request.Path,\n request.QueryString);\n\n response.Redirect(redirectUrl, true);\n return;\n }\n\n await _next(context);\n }\n }\n}\n<span class=\"math-container\">```</span>\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-27T14:43:35.177",
"Id": "500831",
"Score": "0",
"body": "If this is for general purpose use, consider that hosts can contain \"www.\" in the name itself, for example: http://hostwww.com is a valid host. Will your middleware do the right thing in that case?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-27T11:53:50.547",
"Id": "253952",
"ParentId": "253879",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "253932",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-24T18:57:24.620",
"Id": "253879",
"Score": "1",
"Tags": [
"c#",
"asp.net",
"http",
"asp.net-core"
],
"Title": "C# Asp.net core middleware for redirecting URLs"
}
|
253879
|
<p>In order to reduce the boilerplate code, I decided to write a lightweight database helper, based on the <a href="https://martinfowler.com/eaaCatalog/tableDataGateway.html" rel="nofollow noreferrer">Table Data Gateway pattern</a> (or at least the way I understand it) with the aim of using it for a simple CRUD application.</p>
<p>Writing INSERT and UPDATE queries is always a nuisance, repeating all those ranks of column names, parameter names, binding parameters and such. So I decided to write a simple class that does all the job under the hood, and accepts/returns simple arrays, without going down the rabbit hole of creating a full featured ORM.</p>
<p>My aim was also to make this class as secure as possible, hence the table and field names are always hardcoded.</p>
<p>It consists of one prototype class,</p>
<pre><code>abstract class BasicTableGateway
{
protected $db;
protected $table;
protected $fields;
protected $primary = 'id';
public function __construct(\PDO $db)
{
$this->db = $db;
}
public function listBySQL(string $sql, array $params): array
{
$stmt = $this->db->prepare($sql);
$stmt->execute($params);
return $stmt->fetchAll();
}
public function list(int $page = 1, int $limit = 50): array
{
$page--;
$offset = $page * $limit;
$stmt = $this->db->prepare("SELECT * FROM `$this->table` LIMIT ?,?");
$stmt->execute([$offset,$limit]);
return $stmt->fetchAll();
}
public function read($id): ?array
{
$ret = $this->listBySQL("SELECT * FROM `$this->table` WHERE `$this->primary`=?", [$id]);
return $ret ? reset($ret) : null;
}
public function update(array $data, int $id): void
{
$this->validate($data);
$params = [];
$set = "";
foreach($data as $key => $value)
{
$set .= "`$key` = ?,";
$params[] = $value;
}
$set = rtrim($set, ",");
$params[] = $id;
$sql = "UPDATE `$this->table` SET $set WHERE `$this->primary`=?";
$this->db->prepare($sql)->execute($params);
}
public function insert($data): int
{
$this->validate($data);
$fields = '`'.implode("`,`", array_keys($data)).'`';
$placeholders = str_repeat('?,', count($data) - 1) . '?';
$sql = "INSERT INTO `$this->table` ($fields) VALUES ($placeholders)";
$this->db->prepare($sql)->execute(array_values($data));
return $this->db->lastInsertId();
}
public function delete($id)
{
$sql = "DELETE FROM `$this->table` WHERE `$this->primary`=?";
$this->db->prepare($sql)->execute([$id]);
}
protected function validate($data)
{
$diff = array_diff(array_keys($data), $this->fields);
if ($diff) {
throw new \InvalidArgumentException("Unknown field(s): ". implode($diff));
}
}
}
</code></pre>
<p>and children classes where related properties are set to operate certain tables:</p>
<pre><code>class UserGateway extends BasicTableGateway {
protected $table = 'users';
protected $fields = ['email', 'password', 'name', 'birthday'];
}
</code></pre>
<p>which is then used like this</p>
<pre><code>$data = [
'email' => 'foo@bar.com',
'password' => 'hash',
'name' => 'Fooster',
];
$id = $userGateway->insert($data);
$user = $userGateway->read($id);
echo json_encode($user),PHP_EOL;
$userGateway->update(['name' => 'Wooster'], $id);
$user = $userGateway->read($id);
echo json_encode($user),PHP_EOL;
$users = $userGateway->list();
echo json_encode($users),PHP_EOL;
$userGateway->delete($id);
</code></pre>
<p>The code works all right for a simple CRUD but I'd like to know whether it can be improved or may be there are some critical faults I don't realize.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-24T23:14:58.087",
"Id": "500673",
"Score": "2",
"body": "`list` can internally call `listBySql`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-24T23:25:07.463",
"Id": "500674",
"Score": "0",
"body": "Man, I am totally blind! It was intended to be like that, but remained from the first prototype. I looked at this part many times and completely missed it! Thanks for pointing out!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-25T10:04:26.890",
"Id": "500688",
"Score": "1",
"body": "you can probably add type hints for params and return types on validate(), delete() and insert() methods. Also, class properties can have type hints too."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-25T11:54:53.440",
"Id": "500701",
"Score": "0",
"body": "@user3402600 thank you, good catch! Indeed it's inconsistent and should be fixed"
}
] |
[
{
"body": "<ul>\n<li><p>In <code>list()</code>, because <code>$page</code> is a single-use variable, I don't know that it is worth decrementing. Perhaps write just one line as:</p>\n<pre><code>$offset = ($page - 1) * $limit;\n</code></pre>\n<p>but then again <code>$offset</code> is a single-use variable. If you prefer the declarative coding style, leave it as is. Alternatively, you could just write the arithmetic directly in the <code>execute()</code> call. (either way, don't forget to add the space between <code>offset</code> and <code>limit</code> arguments)</p>\n<pre><code>$stmt->execute([($page - 1) * $limit, $limit]);\n</code></pre>\n<p>or because of precedence, you can pre-decrement to avoid parentheses:</p>\n<pre><code>$stmt->execute([--$page * $limit, $limit]);\n</code></pre>\n<p>or as stated in comments, <em>"list can internally call listBySql"</em> from @hjpotter92:</p>\n<pre><code>public function list(int $page = 1, int $limit = 50): array\n{\n return listBySQL("SELECT * FROM `$this->table` LIMIT ?,?", [--$page * $limit, $limit]);\n}\n</code></pre>\n</li>\n<li><p>Please add the <code>int</code> type declaration to the <code>$id</code> argument in <code>read()</code>. I think that <code>read()</code> can be reduced to this:</p>\n<pre><code>return reset($this->listBySQL("SELECT * FROM `$this->table` WHERE `$this->primary`=?", [$id])) ?: null;\n</code></pre>\n<p>because if <code>fetchAll()</code> delivers an empty array, then <code>reset()</code> will return <code>false</code> in which case the <a href=\"https://stackoverflow.com/a/1993455/2943403\">Elvis operator</a> can return the desired <code>null</code> value. This is more of a style preference alternative rather than a functional gain -- the only real benefit is removing the <code>$ret</code> variable.</p>\n</li>\n<li><p>I would prefer that <code>update()</code> return <code>int</code> instead of <code>void</code> (even if your demo doesn't seek this information). In my projects, I always return the number of affected rows. This is integral in knowing if the query was actually successful in making changes or if there were no changes from the valid query. I find this to be as important as <code>insert()</code> returning the new id.</p>\n</li>\n<li><p>Please add the <code>array</code> type declaration on <code>$data</code> in <code>insert()</code> and remove the blank line after returning the new id in <code>insert()</code>.</p>\n</li>\n<li><p>Please add the <code>int</code> type declaration on <code>$id</code> in <code>delete()</code>.</p>\n</li>\n<li><p>There is some inconsistency regarding when you declare a <code>$sql</code> variable and when you write the sql string directly into the <code>prepare()</code> call. I think you should pick one style or the other. My leanings, of course, bias toward removing single-use variables.</p>\n</li>\n<li><p><code>validate()</code>'s incoming argument should have an <code>array</code> type declaration. The <code>implode()</code> call in the thrown exception could use some glue -- a comma at minimum.</p>\n</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-25T14:09:59.170",
"Id": "500714",
"Score": "0",
"body": "thanks, every item straight to the point!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-25T14:07:28.177",
"Id": "253897",
"ParentId": "253882",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "253897",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-24T22:51:45.923",
"Id": "253882",
"Score": "2",
"Tags": [
"php",
"database",
"crud"
],
"Title": "A lightweight CRUD, based on the Table Data Gateway pattern"
}
|
253882
|
<p>I'm new to programming. I have a question regarding the usage of c++11 random header to generate random numbers.
I tried to learn it, but was unsuccessful.
Recently, I've tried the following approach and it worked. Any advice on how to improve it. Is there a good source to learn more about this?</p>
<p>Here's the code:</p>
<pre><code>#include <iostream>
#include <random>
#include <ctime>
int main()
{
std::default_random_engine random_engine(time(0));
for (int i = 1; i <= 100; i++)
{
std::uniform_int_distribution<int> num(1, 100);
std::cout << i << "==> " << num(random_engine) << std::endl;
}
return 0;
}
</code></pre>
|
[] |
[
{
"body": "<p>First of all, note that <code>std::default_random_engine</code> and <code>std::uniform_int_distribution<int></code> are both non-portable in the same sense as <code>rand()</code> is non-portable: they won't produce the same sequence of numbers on different platforms, because their behavior is implementation-defined. For <code>uniform_int_distribution</code> there effectively <em>is</em> no portable alternative, so it's the best game in town. But for the PRNG itself, I don't think any expert would ever recommend <code>default_random_engine</code>. Just pick a known engine, such as <code>std::mt19937</code>. (Which <a href=\"https://arxiv.org/pdf/1910.06437.pdf\" rel=\"noreferrer\">isn't good</a> but again it's the only game in town at the moment.)</p>\n<p>For seeding: notice that you're giving only 32 bits of seed (and a very predictable seed at that) to the PRNG's constructor. You <em>should</em> be seeding from a <code>random_device</code>, something like this (stolen from <a href=\"https://stackoverflow.com/questions/15509270/does-stdmt19937-require-warmup\">here</a>):</p>\n<pre><code>std::random_device rd;\nint data[624];\nstd::generate_n(data, std::size(data), std::ref(rd));\nstd::seed_seq sseq(data, std::end(data));\nstd::mt19937 g(sseq);\n</code></pre>\n<p>(Of course nobody does this in practice.)</p>\n<hr />\n<pre><code>for (int i = 1; i <= 100; i++)\n</code></pre>\n<p>Prefer</p>\n<pre><code>for (int i = 0; i < 100; ++i)\n</code></pre>\n<p>even if it means you have to refer to <code>i+1</code> inside the loop. Using half-open ranges that start at 0 is good practice for everywhere in C and C++ and every modern language.</p>\n<hr />\n<pre><code>std::uniform_int_distribution<int> num(1, 100);\n</code></pre>\n<p>Personally I'd write this as</p>\n<pre><code>auto dist = std::uniform_int_distribution<int>(1, 100);\n</code></pre>\n<p>to get that nice clear <code>=</code> separation visible at a glance. Also, notice my conventional variable names throughout: <code>rd</code> for the random device, <code>g</code> for the PRNG itself, <code>dist</code> for the distribution. It might make sense to use a more descriptive name than <code>dist</code>... but certainly <code>num</code> is not more descriptive, and <code>num</code> <em>is</em> less truthful — a distribution is <em>not</em> a single number!</p>\n<hr />\n<p>Finally, you don't need that final <code>return 0</code> (<code>main</code> returns 0 on success by default), and you don't need <code>std::endl</code> because <code>'\\n'</code> (or <code>"\\n"</code>) will do just as well.</p>\n<p>But basically you're doing the dance correctly: PRNG created outside the loop, distribution called-like-a-function from inside the loop.</p>\n<p>You could move the variable definition of the distribution outside the loop as well, if you wanted. It probably doesn't matter in practice because <code>uniform_int_distribution</code> is unlikely to have any state worth preserving between iterations. But if it were a <code>std::normal_distribution</code>, say, then destroying and recreating the distribution every time through the loop would be costing you basically 50% of your speed.</p>\n<pre><code>auto dist = std::uniform_int_distribution<int>(1, 100);\nfor (int i = 0; i < 100; ++i) {\n std::cout << (i+1) << "==> " << dist(g) << '\\n';\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-25T11:26:17.720",
"Id": "500700",
"Score": "1",
"body": "Isn't `std::default_random_engine` alias to `std::mt19937`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-25T18:20:13.483",
"Id": "500722",
"Score": "1",
"body": "@ALX23z: In MSVC's STL, yes. In libstdc++, [no, it's an alias to `std::minstd_rand0`.](https://github.com/gcc-mirror/gcc/blob/master/libstdc%2B%2B-v3/include/bits/random.h#L1604) In libc++, [no, it's an alias to `std::minstd_rand`](https://github.com/llvm-mirror/libcxx/blob/master/include/random#L2009) which is **different** from `minstd_rand0`. It's different on every platform, which is why I call it \"non-portable\" in the same sense as the old libc `rand()`. https://godbolt.org/z/1a33nW"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-26T02:35:07.340",
"Id": "500740",
"Score": "0",
"body": "This is a great example of the problems with the C++-11 random number generator: many applications don't need high-quality randomness, they need easy-to-use randomness. Putting a call to `srand(time(NULL))` at program startup is a lot easier than faffing about with the contents of `<random>`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-26T02:50:36.140",
"Id": "500743",
"Score": "0",
"body": "@Mark: FWIW I think we agree on that point. OP's `auto g = std::mt19937(time(nullptr));` (well, that's what OP _should_ have written ;)) will be okay-ish, and `std::random_device rd; auto g = std::mt19937(rd());` would be state-of-the-industry. When I said \"you _should_ be using `seed_seq`...\" followed by \"...of course nobody does this in practice,\" I meant both parts of what I said. ;) `seed_seq` is just _abysmal_ API design."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-25T01:37:13.320",
"Id": "253884",
"ParentId": "253883",
"Score": "7"
}
},
{
"body": "<p>I’m not aware of any sources that give a really good intro to the standard <code><random></code> library, unfortunately. I wrote about it years ago, but that was when it was brand new, and I was mostly just introducing it; it’s not really a comprehensive tutorial.</p>\n<p>However, I can give some advice about the code you’ve got.</p>\n<pre><code>std::default_random_engine random_engine(time(0));\n</code></pre>\n<p>It’s generally unwise to use <code>std::time()</code> to seed a random number generator, for a number of reasons.</p>\n<p>First, there’s no guarantee that the return type can actually be used as a seed, because it might not be convertible to an unsigned integer type. (In practice, I’ve never seen a platform where this is the case, because the return type is a 32-bit signed <code>int</code> on all POSIX platforms).</p>\n<p>Second, the return type is <em>usually</em> (probably almost always) only good to about 1 second. That means that if the program runs twice within a second, it will generate exactly the same “random” sequence.</p>\n<p>Third, it is a predictable value. If I want to control your program, all I have to do is set my clock to a time that generates the sequence I want.</p>\n<p>In practice, the usual way to seed a random engine is with <code>std::random_device</code>. It is <em>usually</em> non-deterministic these days (so, completely unpredictable), but it’s one of those things that isn’t guaranteed to work properly everywhere (though it will almost certainly work properly everywhere most people will ever need it).</p>\n<p>So what you’d do would be this:</p>\n<pre><code>std::random_device rd;\nstd::default_random_engine random_engine(rd());\n\n// or, in one line:\nstd::default_random_engine random_engine(std::random_device{}());\n</code></pre>\n<p>Next:</p>\n<pre><code>for (int i = 1; i <= 100; i++)\n{\n std::uniform_int_distribution<int> num(1, 100);\n std::cout << i << "==> " << num(random_engine) << std::endl;\n}\n</code></pre>\n<p>It might be more efficient to move the distribution out of the loop:</p>\n<pre><code>std::uniform_int_distribution<int> dist(1, 100);\n\nfor (int i = 1; i <= 100; i++)\n{\n std::cout << i << "==> " << dist(random_engine) << '\\n';\n}\n</code></pre>\n<p>Finally, a few quick tips:</p>\n<ol>\n<li>The only engines I have found cause to use are <code>mersenne_twister_engine</code> and <code>linear_congruential_engine</code>. <code>mt19937</code> (which is a <code>mersenne_twister_engine</code>) should be your default choice. I’ve used LCGs in cases like simulations where each entity has its own random number generator, because Mersenne twisters are <em>great</em>… but also <em>huge</em> and relative slow. LCGs are tiny and fast, but don’t produce great randomness… but sometimes that’s okay.</li>\n<li>The only distributions I have found cause to use regularly are <code>uniform_int_distribution</code> and <code>normal_distribution</code>.\n<ul>\n<li>Uniform distributions are for cases where you want a number between two values, and every value between is equally likely—for example, rolling a die or picking a value out of a group (like pulling a name out of a hat).</li>\n<li>Normal distributions are for cases where you want “natural-looking” randomness—for example, the damage done after a hit in a game (the “nominal” damage done by an attack might be 100, then you use normally-distributed randomness to be “thereabouts”, so 99 or 101 is more likely than 95 or 105).\nI have used other distributions, like the <code>bernoulli_distribution</code>, to simulate something that has, say, a 62% chance of succeeding being done over and over. But even for that, I usually just use a normal distribution.</li>\n</ul>\n</li>\n<li>If you need to change the range of a distribution, you can either just assign it with a new value, or use the <code>param()</code> function.</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-25T20:16:56.787",
"Id": "500726",
"Score": "0",
"body": "\"I’m not aware of any sources that give a really good intro\" There are some IMO very good videos from cppcon that gives an intro to the library: https://youtu.be/0Ez-KqDTVXg and https://youtu.be/6DPkyvkMkk8"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-26T02:38:02.320",
"Id": "500741",
"Score": "0",
"body": "In regards to seeding with the current time, most programs aren't started more than once per second, and don't use randomness in security-critical ways. For example, by picking a startup time, you can control the order of random jumps through my photo album -- so what?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-27T04:01:06.997",
"Id": "500814",
"Score": "0",
"body": "It doesn’t need to be “security-critical” to be a bug. For example, a game where you can fiddle with the PRNG will be easy to “cheat”, and you may say “who cares? they’re just spoiling their own fun”… well, maybe, except when it comes to multiplayer play, or speed-running, or the like; you never know. Really, the bottom line is that if you think you can get away with doing things poorly… hey, man, it’s your code, do as you please. Just don’t be surprised when I prefer to buy the app from the coder who does things according to best practices."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-25T01:56:04.550",
"Id": "253885",
"ParentId": "253883",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-24T23:47:03.627",
"Id": "253883",
"Score": "7",
"Tags": [
"c++",
"c++11",
"random"
],
"Title": "Using c++11 random header to generate random numbers"
}
|
253883
|
<p>I trained a DQN agent using tensorflow and <a href="https://github.com/openai/gym" rel="nofollow noreferrer">OpenAI gym</a> Atari environment called <code>PongNoFrameskip-v4</code>, but this code should be compatible with any <code>gym</code> environment that returns the state as an RGB frame. This has been originally the work described in those papers:</p>
<ul>
<li><a href="https://www.cs.toronto.edu/%7Evmnih/docs/dqn.pdf" rel="nofollow noreferrer">Playing Atari with Deep Reinforcement Learning</a></li>
<li><a href="https://deepmind.com/research/publications/human-level-control-through-deep-reinforcement-learning" rel="nofollow noreferrer">Human level control through deep reinforcement learning</a></li>
</ul>
<p><strong>Description</strong></p>
<blockquote>
<p>A DQN, or Deep Q-Network, approximates a state-value function in a Q-Learning framework with a neural network. In the Atari Games case, they take in several frames of the game as an input and output state values for each action as an output.</p>
</blockquote>
<blockquote>
<p>It is usually used in conjunction with Experience Replay, for storing the episode steps in memory for off-policy learning, where samples are drawn from the replay memory at random. Additionally, the Q-Network is usually optimized towards a frozen target network that is periodically updated with the latest weights every k steps (where k is a hyperparameter). The latter makes training more stable by preventing short-term oscillations from a moving target. The former tackles autocorrelation that would occur from on-line learning, and having a replay memory makes the problem more like a supervised learning problem.</p>
</blockquote>
<p><strong>Result</strong></p>
<p>Here's a demonstration of a game using a model I trained and note that training the agent, might require 1 - 2 GPU hours, so for the sake of demonstration, I'll include the necessary files to run the code without needing to train at your end.</p>
<p><strong>PC - Agent</strong></p>
<p><a href="https://i.stack.imgur.com/O0d7v.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/O0d7v.gif" alt="Pong improved model" /></a></p>
<p>You can download the model archive <a href="https://drive.google.com/file/d/1ZrGutHbz3uKU5p9Gr-u0FJoUEsqDucZr/view?usp=sharing" rel="nofollow noreferrer">here</a> ~= 20 mb, which you need to unzip in the same directory as the the 2 modules below <code>utils.py</code> and <code>dqn.py</code>, then just run:</p>
<pre><code>python3 dqn.py
</code></pre>
<p><strong>Things I would like to improve:</strong></p>
<ul>
<li><p>Model convergence speed</p>
</li>
<li><p>An <a href="https://github.com/tensorflow/tensorflow/issues/45546" rel="nofollow noreferrer">issue</a> with tensorflow 2 that does not use the GPU during the training unless I do:</p>
<pre><code> tf.compat.v1.disable_eager_execution()
</code></pre>
</li>
<li><p>Inconsistent convergence speed: sometimes the model converges very fast and the target reward (set at 19 by default) is reached in less than 500,000 steps / ~= 200-250 games and sometimes it may need up to 700,000 steps to reach the same reward without changing hyperparameters.</p>
</li>
<li><p>Anything else that can be improved</p>
</li>
</ul>
<p><code>dqn.py</code></p>
<pre><code>import os
from collections import deque
from time import perf_counter
import cv2
import gym
import numpy as np
import wandb
from tensorflow.keras.layers import Conv2D, Dense, Flatten, Input
from tensorflow.keras.models import Model
from tensorflow.keras.optimizers import Adam
from utils import AtariPreprocessor
class DQN:
def __init__(
self,
env,
replay_buffer_size=10000,
batch_size=32,
checkpoint=None,
reward_buffer_size=100,
epsilon_start=1.0,
epsilon_end=0.01,
frame_skips=4,
resize_shape=(84, 84),
state_buffer_size=2,
):
"""
Initialize agent settings.
Args:
env: gym environment that returns states as atari frames.
replay_buffer_size: Size of the replay buffer that will hold record the
last n observations in the form of (state, action, reward, done, new state)
batch_size: Training batch size.
checkpoint: Path to .tf filename under which the trained model will be saved.
reward_buffer_size: Size of the reward buffer that will hold the last n total
rewards which will be used for calculating the mean reward.
epsilon_start: Start value of epsilon that regulates exploration during training.
epsilon_end: End value of epsilon which represents the minimum value of epsilon
which will not be decayed further when reached.
frame_skips: Number of frame skips to use per environment step.
resize_shape: (m, n) dimensions for the frame preprocessor
state_buffer_size: Size of the state buffer used by the frame preprocessor.
"""
self.env = gym.make(env)
self.env = AtariPreprocessor(
self.env, frame_skips, resize_shape, state_buffer_size
)
self.input_shape = self.env.observation_space.shape
self.main_model = self.create_model()
self.target_model = self.create_model()
self.buffer_size = replay_buffer_size
self.buffer = deque(maxlen=replay_buffer_size)
self.batch_size = batch_size
self.checkpoint_path = checkpoint
self.total_rewards = deque(maxlen=reward_buffer_size)
self.best_reward = -float('inf')
self.mean_reward = -float('inf')
self.state = self.env.reset()
self.steps = 0
self.frame_speed = 0
self.last_reset_frame = 0
self.epsilon_start = self.epsilon = epsilon_start
self.epsilon_end = epsilon_end
self.games = 0
def create_model(self):
"""
Create model that will be used for the main and target models.
Returns:
None
"""
x0 = Input(self.input_shape)
x = Conv2D(32, 8, 4, activation='relu')(x0)
x = Conv2D(64, 4, 2, activation='relu')(x)
x = Conv2D(64, 3, 1, activation='relu')(x)
x = Flatten()(x)
x = Dense(512, 'relu')(x)
x = Dense(self.env.action_space.n)(x)
return Model(x0, x)
def get_action(self, training=True):
"""
Generate action following an epsilon-greedy policy.
Args:
training: If False, no use of randomness will apply.
Returns:
A random action or Q argmax.
"""
if training and np.random.random() < self.epsilon:
return self.env.action_space.sample()
q_values = self.main_model.predict(np.expand_dims(self.state, 0))
return np.argmax(q_values)
def get_buffer_sample(self):
"""
Get a sample of the replay buffer.
Returns:
A batch of observations in the form of
[[states], [actions], [rewards], [dones], [next states]]
"""
indices = np.random.choice(len(self.buffer), self.batch_size, replace=False)
memories = [self.buffer[i] for i in indices]
batch = [np.array(item) for item in zip(*memories)]
return batch
def update(self, batch, gamma):
"""
Update gradients on a given a batch.
Args:
batch: A batch of observations in the form of
[[states], [actions], [rewards], [dones], [next states]]
gamma: Discount factor.
Returns:
None
"""
states, actions, rewards, dones, new_states = batch
q_states = self.main_model.predict(states)
new_state_values = self.target_model.predict(new_states).max(1)
new_state_values[dones] = 0
target_values = np.copy(q_states)
target_values[np.arange(self.batch_size), actions] = (
new_state_values * gamma + rewards
)
self.main_model.fit(states, target_values, verbose=0)
def checkpoint(self):
"""
Save model weights if improved.
Returns:
None
"""
if self.best_reward < self.mean_reward:
print(f'Best reward updated: {self.best_reward} -> {self.mean_reward}')
if self.checkpoint_path:
self.main_model.save_weights(self.checkpoint_path)
self.best_reward = max(self.mean_reward, self.best_reward)
def display_metrics(self):
"""
Display progress metrics to the console.
Returns:
None
"""
display_titles = (
'frame',
'games',
'mean reward',
'best_reward',
'epsilon',
'speed',
)
display_values = (
self.steps,
self.games,
self.mean_reward,
self.best_reward,
np.around(self.epsilon, 2),
f'{round(self.frame_speed)} steps/s',
)
display = (
f'{title}: {value}' for title, value in zip(display_titles, display_values)
)
print(', '.join(display))
def update_metrics(self, episode_reward, start_time):
"""
Update progress metrics.
Args:
episode_reward: Total reward per a single episode (game).
start_time: Episode start time, used for calculating fps.
Returns:
None
"""
self.games += 1
self.checkpoint()
self.total_rewards.append(episode_reward)
self.frame_speed = (self.steps - self.last_reset_frame) / (
perf_counter() - start_time
)
self.last_reset_frame = self.steps
self.mean_reward = np.around(np.mean(self.total_rewards), 2)
self.display_metrics()
def fit(
self,
decay_n_steps=150000,
learning_rate=1e-4,
gamma=0.99,
update_target_steps=1000,
monitor_session=None,
weights=None,
max_steps=None,
target_reward=19,
):
"""
Train agent on a supported environment
Args:
decay_n_steps: Maximum steps that determine epsilon decay rate.
learning_rate: Model learning rate shared by both main and target networks.
gamma: Discount factor used for gradient updates.
update_target_steps: Update target model every n steps.
monitor_session: Session name to use for monitoring the training with wandb.
weights: Path to .tf trained model weights to continue training.
max_steps: Maximum number of steps, if reached the training will stop.
target_reward: Target reward, if achieved, the training will stop
Returns:
None
"""
if monitor_session:
wandb.init(name=monitor_session)
episode_reward = 0
start_time = perf_counter()
optimizer = Adam(learning_rate)
if weights:
self.main_model.load_weights(weights)
self.target_model.load_weights(weights)
self.main_model.compile(optimizer, loss='mse')
self.target_model.compile(optimizer, loss='mse')
while True:
self.steps += 1
self.epsilon = max(
self.epsilon_end, self.epsilon_start - self.steps / decay_n_steps
)
action = self.get_action()
new_state, reward, done, info = self.env.step(action)
episode_reward += reward
self.buffer.append((self.state, action, reward, done, new_state))
self.state = new_state
if done:
if self.mean_reward >= target_reward:
print(f'Reward achieved in {self.steps} steps!')
break
if max_steps and self.steps >= max_steps:
print(f'Maximum steps exceeded')
break
self.update_metrics(episode_reward, start_time)
start_time = perf_counter()
episode_reward = 0
self.state = self.env.reset()
if len(self.buffer) < self.buffer_size:
continue
batch = self.get_buffer_sample()
self.update(batch, gamma)
if self.steps % update_target_steps == 0:
self.target_model.set_weights(self.main_model.get_weights())
def play(self, weights=None, video_dir=None, render=False, frame_dir=None):
"""
Play and display a game.
Args:
weights: Path to trained weights, if not specified, the most recent
model weights will be used.
video_dir: Path to directory to save the resulting game video.
render: If True, the game will be displayed.
frame_dir: Path to directory to save game frames.
Returns:
None
"""
if weights:
self.main_model.load_weights(weights)
if video_dir:
self.env = gym.wrappers.Monitor(self.env, video_dir)
self.state = self.env.reset()
steps = 0
for dir_name in (video_dir, frame_dir):
os.makedirs(dir_name or '.', exist_ok=True)
while True:
if render:
self.env.render()
if frame_dir:
frame = self.env.render(mode='rgb_array')
cv2.imwrite(os.path.join(frame_dir, f'{steps:05d}.jpg'), frame)
action = self.get_action(False)
self.state, reward, done, info = self.env.step(action)
if done:
break
steps += 1
if __name__ == '__main__':
agn = DQN('PongNoFrameskip-v4')
agn.play('model/pong_test.tf', render=True)
</code></pre>
<p><code>utils.py</code></p>
<pre><code>from collections import deque
import cv2
import gym
import numpy as np
class AtariPreprocessor(gym.Wrapper):
"""
gym wrapper for preprocessing atari frames.
"""
def __init__(self, env, frame_skips=4, resize_shape=(84, 84), state_buffer_size=2):
"""
Initialize preprocessing settings.
Args:
env: gym environment that returns states as atari frames.
frame_skips: Number of frame skips to use per environment step.
resize_shape: (m, n) output frame size.
state_buffer_size: State buffer for max pooling.
"""
super(AtariPreprocessor, self).__init__(env)
self.skips = frame_skips
self.frame_shape = resize_shape
self.observation_space.shape = (*resize_shape, 1)
self.observation_buffer = deque(maxlen=state_buffer_size)
def process_frame(self, frame):
"""
Resize and convert atari frame to grayscale.
Args:
frame: Image as numpy.ndarray
Returns:
Processed frame.
"""
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
frame = cv2.resize(frame, self.frame_shape) / 255
return np.expand_dims(frame, -1)
def step(self, action: int):
"""
Step respective to self.skips.
Args:
action: Action supported by self.env
Returns:
(state, reward, done, info)
"""
total_reward = 0
state, done, info = 3 * [None]
for _ in range(self.skips):
state, reward, done, info = self.env.step(action)
total_reward += reward
self.observation_buffer.append(state)
if done:
break
max_frame = np.max(np.stack(self.observation_buffer), axis=0)
return self.process_frame(max_frame), total_reward, done, info
def reset(self, **kwargs):
"""
Reset self.env
Args:
**kwargs: kwargs passed to self.env.reset()
Returns:
Processed atari frame.
"""
self.observation_buffer.clear()
observation = self.env.reset(**kwargs)
self.observation_buffer.append(observation)
return self.process_frame(observation)
</code></pre>
<p><strong>References:</strong></p>
<ul>
<li><a href="https://github.com/PacktPublishing/Deep-Reinforcement-Learning-Hands-On-Second-Edition/tree/master/Chapter06" rel="nofollow noreferrer">Deep reinforcement learning hands-on</a></li>
<li><a href="https://github.com/keon/deep-q-learning" rel="nofollow noreferrer">deep-q-learning</a></li>
<li><a href="https://github.com/openai/baselines" rel="nofollow noreferrer">OpenAI baselines</a></li>
<li><a href="https://paperswithcode.com/method/dqn" rel="nofollow noreferrer">DQN explained</a></li>
</ul>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-25T02:11:28.753",
"Id": "253886",
"Score": "3",
"Tags": [
"python",
"python-3.x",
"machine-learning",
"tensorflow"
],
"Title": "Playing pong (atari game) using a DQN agent"
}
|
253886
|
<p>I have implemented a code to solve following problem. I would like to improve the code efficiency.</p>
<ul>
<li>Pardon if I just printed out the result.</li>
<li>Code has <em>O(N)</em> time and constant space complexity.</li>
</ul>
<blockquote>
<p>Given a singly linked list and an integer <em>k</em>, remove the <em>k</em>th last
element from the list.</p>
<ul>
<li><em>k</em> is guaranteed to be smaller than the length of the list.</li>
<li>The list is very long, so making more than one pass is prohibitively expensive.</li>
<li>Do this in constant space and in one pass.</li>
</ul>
</blockquote>
<p>I used a window with the length of <em>k</em> and 2 pointers to track <em>k</em>th last element in the list. 2 pointers are: (1): previous to the first element, (2): the last element of window:</p>
<pre><code>llnode *prev = llist->head;
llnode *last = llist->head;
</code></pre>
<p>CODE:</p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
typedef struct llnode
{
int value;
struct llnode *next;
} llnode;
typedef struct xllist
{
llnode * head;
llnode * tail;
size_t length;
} xllist;
bool create_node(xllist *list, int value)
{
llnode *node = malloc(sizeof *node);
if(!node)
{
return false;
}
list->length++;
node->value = value;
node->next = NULL;
if(!list->head)
{
list->head = node;
list->tail = node;
}
list->tail->next = node;
list->tail = node;
return true;
}
bool del_element_from_last(xllist *llist, int k)
{
printf("len:%d \n", llist->length);
//window with 2 pointers, length of k
//prev is the prev node to the window
llnode *prev = llist->head;
llnode *last = llist->head;
if(k > (size_t)llist->length)
{
return false;
}
else if (k == (size_t)llist->length)
{
llist->head = llist->head->next;
return true;
}
for(int i=0; i<k; i++)
{
last = last->next;
}
//move window until last reaches end
while(last)
{
prev = prev->next;
last = last->next;
}
//remove first node of the window
printf("deleted element:%d \n", prev->next->value);
prev->next = prev->next->next;
}
int main(void)
{
/*Given a singly linked list and an integer k, remove the kth last element from the list.
k is guaranteed to be smaller than the length of the list.
The list is very long, so making more than one pass is prohibitively expensive.
Do this in constant space and in one pass.*/
xllist llist = {NULL, NULL, 0};
for(int i=0; i<100; i++)
{
if(!create_node(&llist, 100+i))
printf("create fail\n");
}
del_element_from_last(&llist, 15);
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-25T11:14:43.097",
"Id": "500696",
"Score": "2",
"body": "The wording of the task sounds to me like you are only given a linked list with an unknown length (and probably also an unknown tail). In that case, getting the length of the list would require an additional pass (which is not allowed). Therefore, you may be violating the rules of the task by using `llist->length` in the function `del_element_from_last`. If I am interpreting the wording of the task correctly, the function should have the following signature: `bool del_element_from_last(llnode *head, int k)`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-02T08:53:01.703",
"Id": "501325",
"Score": "0",
"body": "@AndreasWenzel Please check revised version here: https://codereview.stackexchange.com/questions/254213/remove-kth-last-element-from-singly-linked-list-follow-up"
}
] |
[
{
"body": "<p>I don't know what OS and compiler you use but running <code>gcc -O2 main.c -o main -Wall -Wextra</code> produces several warnings:</p>\n<pre><code>main.c: In function ‘del_element_from_last’:\nmain.c:41:18: warning: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘size_t’ {aka ‘long unsigned int’} [-Wformat=]\n 41 | printf("len:%d \\n", llist->length);\n | ~^ ~~~~~~~~~~~~~\n | | |\n | int size_t {aka long unsigned int}\n | %ld\nmain.c:47:10: warning: comparison of integer expressions of different signedness: ‘int’ and ‘long unsigned int’ [-Wsign-compare]\n 47 | if(k > (size_t)llist->length)\n | ^\nmain.c:51:16: warning: comparison of integer expressions of different signedness: ‘int’ and ‘long unsigned int’ [-Wsign-compare]\n 51 | else if (k == (size_t)llist->length)\n | ^~\nmain.c:73:1: warning: control reaches end of non-void function [-Wreturn-type]\n 73 | }\n | ^\n</code></pre>\n<p>valgrind reports memory leak:</p>\n<pre><code>$ valgrind ./main\n==10611== Memcheck, a memory error detector\n==10611== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.\n==10611== Using Valgrind-3.16.1 and LibVEX; rerun with -h for copyright info\n==10611== Command: ./main\n==10611==\nlen:100\ndeleted element:186\n==10611==\n==10611== HEAP SUMMARY:\n==10611== in use at exit: 1,600 bytes in 100 blocks\n==10611== total heap usage: 101 allocs, 1 frees, 2,624 bytes allocated\n==10611==\n==10611== LEAK SUMMARY:\n==10611== definitely lost: 32 bytes in 2 blocks\n==10611== indirectly lost: 1,568 bytes in 98 blocks\n==10611== possibly lost: 0 bytes in 0 blocks\n==10611== still reachable: 0 bytes in 0 blocks\n==10611== suppressed: 0 bytes in 0 blocks\n==10611== Rerun with --leak-check=full to see details of leaked memory\n==10611==\n==10611== For lists of detected and suppressed errors, rerun with: -s\n==10611== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)`\n</code></pre>\n<p>Why does this function</p>\n<pre><code>bool del_element_from_last(xllist *llist, int k)\n</code></pre>\n<p>and others return non-zero on success? Usually, functions in C return\n0 on success and non-zero on failure. The current behavior in your\ncode is counter-intuitive.</p>\n<p>You should add a function that prints the entire list.</p>\n<p>If you do this:</p>\n<pre><code>del_element_from_last(&llist, 1);\n</code></pre>\n<p>your code crashes:</p>\n<pre><code>$ ./main\nlen:100\nSegmentation fault\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-25T10:59:58.240",
"Id": "500695",
"Score": "0",
"body": "\"Usually, functions in C return 0 on success and non-zero on failure.\" -- That applies to functions with a return type of `int`. However, with the return type of `bool`, in my opinion, it does make sense to make `true` indicate success. For example, many Windows API functions do this. But I agree that it can be confusing if the meaning is inverted depending on the return type, so maybe you are right that it should not be done."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-02T08:53:35.660",
"Id": "501327",
"Score": "0",
"body": "Revised version here: https://codereview.stackexchange.com/questions/254213/remove-kth-last-element-from-singly-linked-list-follow-up"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-25T10:41:23.933",
"Id": "253893",
"ParentId": "253891",
"Score": "3"
}
},
{
"body": "<p>Here is a pointless cast:</p>\n<blockquote>\n<pre><code>if(k > (size_t)llist->length)\n</code></pre>\n</blockquote>\n<p><code>llist->length</code> is already of type <code>size_t</code>. Perhaps you meant <code>(size_t)k > llist->length</code>? But it would be much simpler (and more correct) to change the interface so that <code>k</code> is a <code>size_t</code> to begin with, I think.</p>\n<hr />\n<p>A singly-linked list should not need a <code>length</code> member. Consider how you might solve this problem (still in constant space and linear time) without knowing the list length in advance.</p>\n<p>Hint: you'll need two pointers, one following <em>k</em> elements behind the other.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-26T20:17:46.693",
"Id": "500806",
"Score": "0",
"body": "They shall do it \"in one pass\", though, and you're suggesting *two* passes (with your two pointers)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-28T08:57:39.233",
"Id": "500882",
"Score": "0",
"body": "I did not notice casting mistake. the reason is, they ask k to be int type. So I did that."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-28T08:57:55.143",
"Id": "500883",
"Score": "0",
"body": "Let me think about length member later on :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-28T14:47:36.453",
"Id": "500919",
"Score": "1",
"body": "@Kelly, you're right, though the two simultaneous passes will have better performance than two distinct passes, due to better memory locality."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-28T14:48:55.850",
"Id": "500920",
"Score": "1",
"body": "@Erdenebat, if you didn't notice the casting problem, perhaps you've not enabled enough warnings from your compiler. E.g. `gcc -Wall -Wextra -Werror`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-29T07:59:48.003",
"Id": "500985",
"Score": "0",
"body": "I use online compiler (https://www.programiz.com/c-programming/online-compiler) since I work from home pc nowadays due to covid. My office laptop has linux vm on it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-29T10:28:22.590",
"Id": "500988",
"Score": "0",
"body": "Oh, that's a terrible interface! I can't see the errors and warnings at all. I really recommend you upgrade your home machine if that's the only alternative..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-02T07:45:03.993",
"Id": "501321",
"Score": "0",
"body": "I have installed cygwin with gcc version 7.4.0 (GCC) ;) Thank you for suggestion."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-02T08:53:21.560",
"Id": "501326",
"Score": "0",
"body": "Please take a look at revised version: https://codereview.stackexchange.com/questions/254213/remove-kth-last-element-from-singly-linked-list-follow-up"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-02T14:58:20.173",
"Id": "501351",
"Score": "1",
"body": "@KellyBundy: I believe the rules of the task description are to be interpreted in such a way that traversing the array simultaneously with two pointers is to be considered a single pass. With your stricter interpretation, there is no solution, as far as I can tell."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-02T18:28:52.197",
"Id": "501365",
"Score": "1",
"body": "@AndreasWenzel Yeah, probably the problem setter doesn't know what they're talking about. LeetCode for example has this problem as well, and [its official solution article](https://leetcode.com/problems/remove-nth-node-from-end-of-list/solution/) calls the two parallel passes \"one pass\". Rather ridiculous."
}
],
"meta_data": {
"CommentCount": "11",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-26T12:37:31.697",
"Id": "253926",
"ParentId": "253891",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "253926",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-25T09:13:26.913",
"Id": "253891",
"Score": "0",
"Tags": [
"c",
"linked-list",
"interview-questions"
],
"Title": "remove kth last element from singly-linked list"
}
|
253891
|
<p>I'm trying to implement a Templated Double Linked List, following Stroustrup's book "Principles and Practice using C++", Chapter 20.4. Instead of raw pointers, I want to use <em>unique pointers</em>.
The code is organized as follows:</p>
<ul>
<li>header Node.h where the struct <code>Node</code> is implemented: a <code>unique_pointer</code> is used for the next node, and a raw one for the previous</li>
<li>header Iterator.h where the <code>Iterator</code> is implemented</li>
<li>header List.h where the class <code>List</code> is implemented</li>
<li>a main.cpp where the methods are tested</li>
</ul>
<p>I've seen that there have been other pretty similar questions, like <a href="https://codereview.stackexchange.com/questions/202333/double-linked-list-using-smart-pointers?rq=1">this one</a> but <strong>I don't know if the design of my insert method: <code>iterator insert(iterator p, const T& x)</code> is okay</strong>. In particular, I obtain a segmentation fault if I call <code>auto it3 = insert(--p,4)</code>. Is this okay, or should I fix this?</p>
<p>Here's my Node.h</p>
<pre class="lang-cpp prettyprint-override"><code>#ifndef Node_h
#define Node_h
#include <algorithm>
#include <iostream>
#include <memory> // std::unique_ptr
#include <utility> // std::move
namespace Node {
template <typename T>
struct Node {
T data;
std::unique_ptr<Node> next;
Node* previous;
Node() noexcept = default;
explicit Node(const T& _data) : data{_data}, next{nullptr},previous{nullptr} {
std::cout << "l-value"<<std::endl;
}
Node(const T& _data, Node* _next, Node* _previous): data{_data}, next{_next}, previous{_previous} {}
explicit Node(T&& x) : data{std::move(x)} {
std::cout << "r-value" << std::endl;
}
Node(T&& x, Node* _next, Node* _previous) : data{std::move(x)}, next{_next}, previous{_previous} {
std::cout << "r-value" << std::endl;
}
explicit Node(const std::unique_ptr<Node> &x) : data{x->data} {
if (x->next){
next.reset(new Node{x->next});
}
// if (x->previous){
// previous.reset(new Node{x->previous});
// }
}
~Node()=default;
//Move semantics, Copy semantics
void printNode(){
std::cout << "Data is: " << data <<"\n";
}
};
} //end namespace
#endif /* Node_h */
</code></pre>
<p>Then, here's the Iterator.h</p>
<pre class="lang-cpp prettyprint-override"><code>#ifndef Iterator_h
#define Iterator_h
#include "Node.h"
#include <iterator>
template <typename T >
struct __iterator {;
using NodeT = Node::Node<T>;
NodeT* current;
//public:
using value_type = T;
using difference_type = std::ptrdiff_t;
using iterator_category = std::forward_iterator_tag;
using reference = value_type&;
using pointer = value_type *;
explicit __iterator(NodeT* p) : current{p} {}
__iterator() noexcept=default;
~__iterator()=default;
reference operator*() const noexcept{
return current->data;
}
pointer operator->() const noexcept{
return &**this;
}
__iterator& operator++() {
current = current->next.get();
return *this;
}
__iterator& operator--(){
current=current->previous; //previous is just a raw pointer
return *this;
}
friend bool operator==(__iterator &a, __iterator &b) {
return a.current == b.current;
}
friend bool operator!=(__iterator &a, __iterator &b) { return !(a == b); }
};
#endif /* Iterator_h */
</code></pre>
<p>Here's the header List.h</p>
<pre class="lang-cpp prettyprint-override"><code>#include "Iterator.h"
#include <cassert>
template <typename T>
class List {
private:
std::unique_ptr<Node::Node<T>> first;
std::unique_ptr<Node::Node<T>> last;
int _size;
public:
using iterator = __iterator<T>;
iterator begin(){return iterator{first.get()};}
iterator end(){return iterator{nullptr};} //one past the last
iterator go_to(const int n){
assert(n>=0);
int i=0;
if (n < _size) {
auto tmp{begin()};
while (i<n) {
++tmp;
++i;
}
return tmp;
}else{
return iterator{nullptr};
}
}
List() : first{nullptr}, last{nullptr},_size{0} {}
~List() noexcept = default;
template <typename O>
void push_front(O &&x) { // forwarding ref. not r-value
first.reset(new Node::Node<T>{std::forward<O>(x),first.release(),nullptr});
if (_size==0) {
last.reset(nullptr);
}
++_size;
}
template <typename O> //forward reference
void push_back(O&& x){
auto tmp = first.get();
auto _node = new Node::Node<T>{std::forward<O>(x)};
if (!tmp) {
first.reset(_node);
return;
}
while (tmp->next) {
tmp = tmp->next.get();
}
tmp->next.reset(_node);
++_size;
}
iterator substitute(iterator p, const T& x){
//_size must not be incremented!
iterator tmp{p};
if(tmp.current){
*tmp = x;
return tmp;
}else{
return iterator{nullptr};
}
}
iterator insert(iterator position,const T& value) {
auto newNode = new Node::Node<T>(value, position.current->next.get(), position.current);
std::cout << position.current << std::endl;
if (position.current == last.get() ) {
last.reset(newNode);
}
position.current->next.release(); //otherwise: "pointer being freed was not allocated"
position.current->next.reset(newNode); //set next of previous node to newNode
++_size;
return position;
}
friend std::ostream& operator<<(std::ostream& os, List& l){
auto itStop = l.end();
os << "The list has " << l._size << " elements"<<"\n";
for (auto it = l.begin(); it!=itStop; ++it) {
os<< *it << " ";
}
return os;
}
};
</code></pre>
<p>Finally, here's the main.cpp file with the tests:</p>
<pre class="lang-cpp prettyprint-override"><code>#include "List.h"
int main() {
List<int> l{};
int i=8;
l.push_front(i); //l-value
l.push_back(4); //r-value
l.push_back(i+2); //r-value
l.push_back(95); //r-value
l.push_front(29); //l-value
l.push_front(i*i); //r-value
std::cout << "My list so far: " << l<<std::endl;
auto p{l.go_to(3)};
auto itt = l.substitute(p, 29);
std::cout << "My list after substitution: \t" << l<<std::endl;
auto pp{l.go_to(2)};
auto it2 = l.insert(pp,98);
std::cout << "My list after insertion: \t" << l<<std::endl;
auto it3= l.insert(--pp,998);
std::cout << "My list after insertion: \t" << l<<std::endl;
return 0;
}
</code></pre>
<p><strong>EDIT</strong>:</p>
<p>Corrected version of <code>push_front</code>:</p>
<pre><code>template <typename O>
void push_front(O&& x) {
auto node = std::make_unique<Node::Node<T>>(std::forward<O>(x));
std::swap(node, first);
first->next = std::move(node);
if (_size == 0) {
assert(!last);
assert(!first->next);
last = first.get();
}else{
first->next->previous = first.get()
}
++_size;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-25T13:48:03.057",
"Id": "500706",
"Score": "0",
"body": "@AryanParekh This is working. The fact is that I don't know if the design should be compatible with a call like tho one I mentioned in the question"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-25T13:53:37.577",
"Id": "500707",
"Score": "0",
"body": "Alright then, my bad. It sounded like that to me when i read it"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-25T13:54:12.177",
"Id": "500708",
"Score": "0",
"body": "@AryanParekh no worries !"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-25T13:56:05.073",
"Id": "500709",
"Score": "4",
"body": "Also, why are you beginning your names with `__`? They are [reserved identifiers](https://stackoverflow.com/questions/228783/what-are-the-rules-about-using-an-underscore-in-a-c-identifier)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-25T13:59:37.750",
"Id": "500711",
"Score": "0",
"body": "I wrote like that because it was the name of my `Iterator` class. Thanks for this suggestion, gonna fix this! @AryanParekh"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-25T14:02:02.467",
"Id": "500712",
"Score": "0",
"body": "Also, in the linked answer (https://codereview.stackexchange.com/questions/202333/double-linked-list-using-smart-pointers?rq=1) I've just seen that in his iterator, when he implements the operator `--`, the OP wrote `node = node->previous.get()` which should be wrong because `previous` was declared as a raw pointer, like I did. The fact is that in this way such a statement like `insert(--p,4)` would not work, right @AryanParekh?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-26T03:20:33.233",
"Id": "500744",
"Score": "0",
"body": "Please refrain from fundamentally changing the question, especially after receiving answers."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-26T11:35:28.850",
"Id": "500757",
"Score": "0",
"body": "@Deduplicator I'm sorry. you're right. Thanks for re-editing everything back :-)"
}
] |
[
{
"body": "<p>I think you should follow C++ standard <code>insert</code> for containers by passing a <code>begin</code> and <code>end</code> iterator, for example</p>\n<pre><code>template<typename T>\nvoid insert(Iterator begin, Iterator begin2, Iterator end2);\nvoid insert(Iterator begin, T value);\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-25T14:43:28.380",
"Id": "500715",
"Score": "0",
"body": "thanks for your answer. But in this case the method is designed so that `iterator(iterator p,T value)` returns an iterator and inserts the value `x` in the list right after `p`. My bigger problem is that if I do something like `insert(--p,4)`, for instance, I got segmentation fault."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-25T14:39:51.577",
"Id": "253898",
"ParentId": "253895",
"Score": "1"
}
},
{
"body": "<p>You have a number of problems with memory management in this linked list. The key thing to remember is that <code>unique_ptr</code> indicates ownership of an object. Use of <code>release</code>, <code>reset</code>, and to a lesser extent <code>get</code> are a code smell: not always wrong, but often an indication that the class is being used incorrectly. Usually you should use <code>swap</code> and move-assignment instead. I'll call these out as I work through the files.</p>\n<p>A quick note: I have not tested or even compiled the following code; it may contain some errors.</p>\n<h2>Node.h</h2>\n<p>This is mostly fine. The "copy" constructor (<code>Node(std::unique_ptr<Node>&)</code>) probably should just be removed. It doesn't really make sense to copy a node and all its descendants. Even if you wanted that behavior, this implementation is buggy. It removes all the previous links, so that you've got a singly linked list that pretends to be a double linked list.</p>\n<h2>Iterator.h</h2>\n<p>Your iterator class is not quite right. It doesn't work as an <code>end</code> iterator. In particular, <code>--l.end()</code> exhibits undefined behavior because it dereferences a null pointer. In practice, iterator classes tend to need a reference to the collection that they come from.</p>\n<p>In addition, this iterator does not meet the requirements of a <a href=\"https://en.cppreference.com/w/cpp/named_req/BidirectionalIterator\" rel=\"noreferrer\">bidirectional iterator</a> (I know you mark this as a forward iterator, but it also does not meet those requirements). In particular, it violates:</p>\n<ul>\n<li>"lvalues of type It satisfy Swappable"; I'm a little rusty here but I'm pretty sure your user-declared destructor prevents the implicitly declared move constructor and move assignment operator from being generated; you must either provide those functions (e.g. using <code>= default</code>) or a <code>swap</code> function.</li>\n<li>It does not support the postfix increment and decrement operators.</li>\n</ul>\n<h2>List.h</h2>\n<p><code>List::last</code> isn't really implemented correctly. As far as I can make out, it's never actually set to anything other than <code>nullptr</code> by the code as is. In any case, this should <em>not</em> be a <code>unique_ptr</code>, because anything it points to is already owned by another <code>unique_ptr</code>.</p>\n<p>So let's change <code>last</code> to a <code>Node::Node<T>*</code>. We have the following invariants that are true before and after each member function exits: If <code>_size == 0</code>, <code>first==last==nullptr</code>. Otherwise,</p>\n<ul>\n<li><code>first</code> points to the first node in the list</li>\n<li><code>first->previous == nullptr</code></li>\n<li>Given a reachable node <code>n</code>, <code>n->next</code> is null or <code>n->next.get() == n->next->previous</code></li>\n<li><code>last</code> points to the last reachable node in the list. <code>last.next</code> is null.</li>\n<li><code>_size</code> nodes are reachable.</li>\n</ul>\n<p>We need to write our member functions so that these invariants remain true.</p>\n<p><code>go_to</code> would usually be achieved through applying <a href=\"https://en.cppreference.com/w/cpp/iterator/next\" rel=\"noreferrer\"><code>std::next</code></a> to the begin iterator. That has a difference of behavior when you're trying to go past the end of the list; using <code>std::next</code> would result in undefined behavior in that case. If you want the current behavior you could implement it with something like</p>\n<pre><code>iterator go_to(const int n) const {\n if (n >= _size) {\n return end();\n } else {\n return std::next(begin(), n);\n }\n}\n</code></pre>\n<p>When you're using <code>unique_ptr</code> to manage memory, you should generally not use <code>new</code>. Instead, use <code>std::make_unique</code> if you're using C++14 or later (and write your own <code>make_unique</code> in C++11). This allows you to improve the exception safety of your code. Try this for <code>push_front</code>:</p>\n<pre><code>template <typename O>\nvoid push_front(O&& x) {\n auto node = std::make_unique<Node::Node<T>>(std::forward<O>(x));\n swap(node, first); // assuming you implement swap or add a "using std::swap;" on the previous line\n first->next = std::move(node);\n if (_size == 0) {\n assert(!last);\n assert(!first->next);\n last = first.get();\n }\n ++_size;\n}\n</code></pre>\n<p>Here, node is created in an exception-safe manner. There is no chance of leaking <code>first</code>, since we do not release it (your code would leak <code>first</code> if the allocation failed or if <code>Node</code>'s constructor threw (due to <code>T</code>'s move constructor throwing)). Assuming your <code>swap</code> and <code>move</code> are no-throw operations, either <code>push_front</code> succeeds, and\nthe new element has been inserted at the beginning, or the allocation fails, <code>push_front</code> throws, and the data structure has not been changed.</p>\n<p>As for <code>push_back</code>, if you're not using <code>last</code> here, there's no reason to have <code>last</code> at all.</p>\n<pre><code>template <typename O>\nvoid push_back(O&& x) {\n auto node = std::make_unique<Node::Node<T>>(std::forward<O>(x));\n if (_size == 0) {\n assert(!last);\n assert(!first);\n first = std::move(node);\n last = node.get();\n _size = 1;\n return;\n }\n assert(!last->next);\n node->previous = last;\n last->next = std::move(node);\n last = last->next.get();\n ++_size;\n}\n</code></pre>\n<p>Again, we ensure that the class's invariants hold, even if we throw while constructing the new node.</p>\n<p>I don't think <code>substitute</code> is a reasonable function. Your list's user should write <code>*it = x;</code> and they should know whether their iterator is valid or not.</p>\n<p>The normal semantics for <code>insert</code> are to insert a value just <em>before</em> the iterator passed in, not just after. This allows <code>insert</code> to insert at any position in the list and it means that <code>insert</code> has sensible semantics when <code>end()</code> is passed as the iterator.</p>\n<pre><code>iterator insert(iterator it, const T& value) {\n auto node = std::make_unique<Node::Node<T>>(value);\n auto prev = it.current ? it.current->previous : last;\n auto ptr = prev ? &first : &prev->next;\n swap(*ptr, node);\n (*ptr)->next = std::move(node);\n (*ptr)->previous = prev;\n ++_size;\n if (!last) last = first.get();\n return iterator(ptr->get());\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-26T00:17:41.113",
"Id": "500733",
"Score": "0",
"body": "Thanks so much for your answer and for all your suggestions: I tried to fix as much as I could, but the your insertion now is puzzling me: it seems to me that you're inserting always at the begin of the list. Indeed, this is what happens if I run my main.cpp (see EDIT). \n\nAlso, it happens that for some value of the iterator `it`I got that `auto prev` is nullptr and hence when I call `std::move` I got segmentation fault. Honestly, I can't understand where's the problem @ruds"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-26T00:36:04.003",
"Id": "500734",
"Score": "0",
"body": "I updated my EDIT with the actual problem: I think there must be a bug in the insertion now, because sometimes it does not work, and when it works it adds the element at the begin of the list"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-26T03:32:41.207",
"Id": "500746",
"Score": "0",
"body": "Apologies. My assignment to ptr is backwards. It should be `auto ptr = prev ? &prev->next : first;`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-26T11:54:42.053",
"Id": "500760",
"Score": "0",
"body": "Thanks so much, but there's still a problem with your fix: let's say that I fill my empy list i`l` in this way: `l.push_front(8)`, `l.push_back(4)`, `l.push_back(10)`, `l.push_back(7)`, `l.push_front(9)`, `l.push_back(5)` (note that `9` has been `push_front`ed)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-26T11:54:53.967",
"Id": "500761",
"Score": "0",
"body": "If now I want to insert an element between the first and the second, it happens that the in the `insert` method `it.current->previous` is equal to `nullptr` and hence the element will be placed at the begin. This is due to the `push_front`: the node after the one you just pushed has no `previous` referring to the new inserted one: in this case, the Node `7` doesn't have `previous` pointing to Node `9`\n I think that your design of `insert` should also support this case, right? @ruds"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-26T11:55:09.393",
"Id": "500762",
"Score": "0",
"body": "`l.insert(l.begin(), 42)` will insert 42 as the new first element of the list. `l.insert(++l.begin(), 42)` will insert it as the new second element."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-26T12:02:32.187",
"Id": "500763",
"Score": "0",
"body": "`l.insert(++l.begin(), 42)` is still inserting it as first element. This is due to the fact that `position.current->previous` is still `nullptr` and hence `auto ptr` is equal to `&first`. I can't understand how to fix this fact. What am I missing? @ruds"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-26T13:35:30.903",
"Id": "500768",
"Score": "0",
"body": "Ah, I see there is a bug in my `push_front`. It does not set `first->next->previous = first.get();`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-26T13:37:16.517",
"Id": "500769",
"Score": "0",
"body": "One way to catch these issues during development is to write a function that checks the class invariants, and to call that function on entry to every member function, and again just before returning."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-26T15:33:30.243",
"Id": "500776",
"Score": "0",
"body": "I got it to work with a slightly modification of your `push_front` I wrote at the and of my original answer (basically I just wrote an `else`). Did you mean to fix it in that way? It works now. If you could confirm it's right, you'll saved my day :-) @ruds"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-26T18:26:10.697",
"Id": "500798",
"Score": "0",
"body": "Yes, that looks right"
}
],
"meta_data": {
"CommentCount": "11",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-25T19:44:36.957",
"Id": "253906",
"ParentId": "253895",
"Score": "6"
}
},
{
"body": "<h1>Move <code>class Node</code> and <code>struct __iterator</code> into <code>class List</code></h1>\n<p>It is very weird to see <code>Node::Node<T></code> inside the code. A <code>Node</code> is an implementation detail of your <code>List</code>, so it should be declared inside <code>class List</code>. The same goes for <code>__iterator</code>. For example:</p>\n<pre><code>template<typename T>\nclass List {\n class Node {\n T data;\n std::unique_ptr<Node> next;\n Node *previous;\n };\n \n std::unique_ptr<Node> first;\n std::unique_ptr<Node> last;\n ...\n\npublic:\n class iterator {\n Node *current;\n\n public:\n using value_type = T;\n ...\n };\n\n iterator begin() {...};\n ...\n};\n</code></pre>\n<p>Notice how all this avoids needing to introduce <code>namespace</code>s or <code>__</code> prefixes (<a href=\"https://stackoverflow.com/questions/228783/what-are-the-rules-about-using-an-underscore-in-a-c-identifier\">which you should avoid</a>) to hide them, and how this reduces the number of times you have to explicitly write <code><T></code>. Of course, now everything has to be declared inside <code>List.h</code>, but I don't see that as a drawback.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-25T19:48:39.747",
"Id": "253907",
"ParentId": "253895",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-25T13:31:29.427",
"Id": "253895",
"Score": "6",
"Tags": [
"c++",
"object-oriented",
"linked-list",
"pointers"
],
"Title": "Double Linked List with smart pointers: problems with insert method"
}
|
253895
|
<p>I've made an application that calculates all the prime numbers between two given numbers and prints then into a .txt document... anything I can improve?</p>
<pre><code>use std::io;
use std::fs::{OpenOptions};
use std::io::{Write, BufWriter};
fn main() {
loop{
let mut format = 1;
let mut input = String::new();
println!("Say a start for the prime loop! ");
io::stdin().read_line(&mut input).unwrap();
let start: u128 = input.trim().parse().unwrap();
let mut input = String::new();
println!("Say an end for the prime loop! ");
io::stdin().read_line(&mut input).unwrap();
let end: u128 = input.trim().parse().unwrap();
let path = "path/to/file.txt";
let f = OpenOptions::new()
.write(true)
.open(path)
.expect("Could not open file");
let mut f = BufWriter::new(f);
for i in start..end{
if prime(i) == true{
f.write_all(i.to_string().as_bytes()).expect("unable to write to file");
f.write_all(b"\t").expect("unable to write to file");
format += 1;
}
if format == 10{
f.write_all(b"\n").expect("unable to write to file");
format = 0;
}
}
}
}
fn prime(x: u128) -> bool {
if x == 4 || x == 6 || x == 8 || x == 9{ //The loop doesnt quite work for numbers below 10 so this is for those numbers
return false;
}
for i in 2..((x as f64).sqrt() as u128){
if x % i == 0 { return false; } //modulo to see if the number is dividable by variable i
}
true
}
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-26T17:42:00.620",
"Id": "500795",
"Score": "0",
"body": "Different algorithms would need to be used depending on the size of the upper bound as well as the size of the interval. It's worth keeping in mind that there are at least 2\\*\\*120 primes between 2\\*\\*127 and 2\\*\\*128."
}
] |
[
{
"body": "<p>The efficiency of the <code>prime</code> function is probably the most interesting aspect of this exercise. You're limiting the search space to up to the square root of the number, which is good, but the fact that you're looking for all primes in a range would make many other prime searching algorithms usable, such as the Sieve of Eratosthenes, which fairly efficiently gets you the primes from 2 through N. The issue is that which algorithm to use in your case depends on runtime inputs: if the user asks for prime numbers between 2 and a large N there are heaps of efficient algorithms. If they instead ask for primes between a large N and N+1 it probably makes much more sense to just look at those two numbers. I'm not a mathematician, but choosing which algorithm to use depending on the range seems like a subject worth studying.</p>\n<p>I don't see why the algorithm would not work for numbers 4, 6, 8 and 9 - that seems like either a subtle bug in the loop or just a misunderstanding. I would add some test cases to <code>prime</code> and verify it with lots of different inputs.</p>\n<p><code>prime</code> takes a <code>u128</code>, but then drops precision when converting it to <code>f64</code> before taking the square root. Since <a href=\"https://github.com/rust-lang/rust/issues/6931\" rel=\"nofollow noreferrer\">Integer -> Float -> Integer conversion can succeed while changing what the value is</a>, I suspect there are corner cases where the range is miscalculated. See also <a href=\"https://internals.rust-lang.org/t/tryfrom-for-f64/9793/13\" rel=\"nofollow noreferrer\">this discussion</a>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-26T01:48:38.490",
"Id": "500737",
"Score": "1",
"body": "I believe the square root function doesn't work so good on low numbers... it messes up the for loop too, I could probably fix that but I should try to work on algorithms like you said, Thanks for the reply! You're one of the first actual nice people on here..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-26T02:22:44.387",
"Id": "500739",
"Score": "0",
"body": "Which one you should work on depends on the goal of the code, but if you really want to support massive numbers like u128 there's probably a lot of work before the code is as stable and performant as possible."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-26T03:21:00.150",
"Id": "500745",
"Score": "2",
"body": "Also, re. nice people, it's a tricky one. Sooo much has been written about this, but I'll just say that text is terrible for communicating feeling, and a lot of users, because they value their time, end up optimizing for terseness when answering. This can often be seen as not very nice, especially when that terseness comes simply in the form of a downvote, close vote, or a quick comment to make the question answerable. On the other hand, experienced users are often triggered by new users not following the guidelines, and effectively wasting everybody's time."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-25T21:27:49.093",
"Id": "253913",
"ParentId": "253900",
"Score": "4"
}
},
{
"body": "<p>In addition to <a href=\"https://codereview.stackexchange.com/a/253913/188857\">l0b0's answer</a>:</p>\n<p>The formatting is inconsistent. You can run <code>cargo fmt</code> to clean it up.</p>\n<p>Personally, I prefer to rewrite the <code>use</code> declaration in a tree-like manner:</p>\n<pre class=\"lang-rust prettyprint-override\"><code>use std::{\n fs::OpenOptions,\n io::{self, BufWriter, Write},\n};\n</code></pre>\n<p>The path can be made into a <code>const</code>:</p>\n<pre class=\"lang-rust prettyprint-override\"><code>const PATH: &str = "path/to/file.txt";\n</code></pre>\n<p><code>format</code> is not a descriptive name.</p>\n<p>A helper function simplifies the input process by eliminating the code duplication.</p>\n<hr />\n<p>Here's a modified version, using the sieve of Eratosthenes:</p>\n<pre class=\"lang-rust prettyprint-override\"><code>use {\n anyhow::Result,\n bitvec::prelude::*,\n itertools::Itertools,\n std::{\n fs::File,\n io::{self, prelude::*},\n ops::Range,\n },\n};\n\nconst PATH: &str = "path/to/file.txt";\nconst N_COLUMNS: usize = 10;\n\nfn main() -> Result<()> {\n let start = input("Enter start of range: ")?;\n let end = input("Enter end of range: ")?;\n\n let table = sieve_to(end);\n\n write_primes(&table, start..end)?;\n\n Ok(())\n}\n\nfn sieve_to(end: usize) -> BitVec {\n let mut table = bitvec![1; end];\n\n // set table[0] and table[1] to false\n for cell in table.iter_mut().take(2) {\n cell.set(false);\n }\n\n // floor(sqrt(end))\n let limit = num::integer::sqrt(end);\n\n for number in 2..limit {\n if !table[number] {\n continue;\n }\n for multiple in (number..end).step_by(number).skip(1) {\n table.set(multiple, false);\n }\n }\n\n table\n}\n\nfn input(message: &str) -> Result<usize> {\n eprint!("{}", message);\n\n let mut line = String::new();\n io::stdin().read_line(&mut line)?;\n\n Ok(line.trim().parse()?)\n}\n\nfn write_primes(table: &BitSlice, range: Range<usize>) -> Result<()> {\n let mut file = File::create(PATH)?;\n\n writeln!(\n file,\n "{}",\n range\n .filter(|&n| table[n])\n .chunks(N_COLUMNS)\n .into_iter()\n .map(|row| row.format("\\t"))\n .format("\\n"),\n )?;\n\n Ok(())\n}\n</code></pre>\n<p><code>Cargo.toml</code>:</p>\n<pre><code>[package]\nname = "prime"\nversion = "0.1.0"\nauthors = ["L. F."]\nedition = "2018"\n\n[dependencies]\nanyhow = "1.0"\nbitvec = "0.20"\nitertools = "0.9"\nnum = "0.3"\n</code></pre>\n<p>I limited the program to one loop per execution, since overwriting the same file again and again does not seem useful to me.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-26T02:54:51.760",
"Id": "253918",
"ParentId": "253900",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "253918",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-25T16:01:34.630",
"Id": "253900",
"Score": "7",
"Tags": [
"primes",
"rust"
],
"Title": "Calculate all the prime numbers between two given numbers"
}
|
253900
|
<p>I created a simple note-taking application, which enables a user to create notes, update them, and delete them. I used local storage for saving the notes. Would Appreciate some feedback on how to improve it.</p>
<p>This is the <code>index.html</code></p>
<pre><code><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Notes-App</title>
</head>
<body>
<h1>Notes App</h1>
<h2>Take notes</h2>
<input id="search-text" type="text" placeholder="Filter Notes" />
<select id="filter-by">
<option value="byEdited">Sort By Last Edited</option>
<option value="byCreated">Sort By Recently Created</option>
<option value="alphabetical">Sort Alphabetically</option>
</select>
<div id="notes"></div>
<button id="create-note">Create Note</button>
<script src="https://unpkg.com/uuid@latest/dist/umd/uuidv4.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment-with-locales.min.js"
integrity="sha512-LGXaggshOkD/at6PFNcp2V2unf9LzFq6LE+sChH7ceMTDP0g2kn6Vxwgg7wkPP7AAtX+lmPqPdxB47A0Nz0cMQ=="
crossorigin="anonymous"></script>
<script src="notes-functions.js"></script>
<script src="notes-app.js"></script>
</body>
</html>
</code></pre>
<p>This is the html for the <code>edit.html</code> page where you can edit the title and body</p>
<pre><code><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Edit Page</title>
<script src="https://unpkg.com/uuid@latest/dist/umd/uuidv4.min.js"></script>
</head>
<body>
<a href="/index.html">Home</a>
<input id="note-title" type="text" placeholder="Note Title" />
<span id="last-edited"></span>
<textarea id="note-body" placeholder="Enter text"></textarea>
<button id="remove-note">Remove Note</button>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment-with-locales.min.js"
integrity="sha512-LGXaggshOkD/at6PFNcp2V2unf9LzFq6LE+sChH7ceMTDP0g2kn6Vxwgg7wkPP7AAtX+lmPqPdxB47A0Nz0cMQ=="
crossorigin="anonymous"></script>
<script src="notes-functions.js"></script>
<script src="notes-edit.js"></script>
</body>
</html>
</code></pre>
<p>This is the <code>notes-app.js</code></p>
<pre><code> let notes = getSavedNotes();
const filters = {
searchText: "",
sortBy: "byEdited",
};
renderNotes(notes, filters);
document.querySelector("#create-note").addEventListener("click", (e) => {
const id = uuidv4();
const timestamp = moment().valueOf();
notes.push({
id,
title: "",
body: "",
createdAt: timestamp,
updatedAt: timestamp,
});
saveNotes(notes);
//redirects user to edit page when new note is created
location.assign(`edit.html#${id}`);
});
document.querySelector("#search-text").addEventListener("input", (e) => {
filters.searchText = e.target.value;
renderNotes(notes, filters);
});
document.querySelector("#filter-by").addEventListener("change", (e) => {
filters.sortBy = e.target.value;
renderNotes(notes, filters);
});
window.addEventListener("storage", (e) => {
if (e.key === "notes") {
notes = JSON.parse(e.newValue);
renderNotes(notes, filters);
}
});
This is the file I created for functions for updating and modifying the notes, called `note-functions.js`
// Read exisiting notes from localstorage
const getSavedNotes = () => {
const notesJSON = localStorage.getItem("notes");
return notesJSON !== null ? JSON.parse(notesJSON) : [];
};
const sortNotes = (notes, sortBy) => {
if (sortBy === "byEdited") {
return notes.sort((a, b) => {
if (a.updatedAt > b.updatedAt) {
return -1;
} else if (a.updatedAt < b.updatedAt) {
return 1;
} else {
return 0;
}
});
} else if (sortBy === "byCreated") {
return notes.sort((a, b) => {
if (a.createdAt > b.createdAt) {
return -1;
} else if (a.createdAt < b.createdAt) {
return 1;
} else {
return 0;
}
});
} else if (sortBy === "alphabetical") {
return notes.sort((a, b) => {
if (a.title.toLowerCase() < b.title.toLowerCase()) {
return -1;
} else if (a.title.toLowerCase() > b.title.toLowerCase()) {
return 1;
} else {
return 0;
}
});
} else {
return notes;
}
};
// Render application notes
const renderNotes = (notes, filters) => {
notes = sortNotes(notes, filters.sortBy);
const filteredNotes = notes.filter((note) => {
return note.title.toLowerCase().includes(filters.searchText.toLowerCase());
});
document.querySelector("#notes").innerHTML = "";
filteredNotes.forEach((note) => {
const noteElement = generateNoteDom(note);
document.querySelector("#notes").appendChild(noteElement);
});
};
//Save Notes
const saveNotes = (notes) => {
localStorage.setItem("notes", JSON.stringify(notes));
};
const removeNote = (id) => {
const noteIndex = notes.findIndex((note) => {
return note.id === id;
});
if (noteIndex > -1) {
notes.splice(noteIndex, 1);
}
};
// Generate the DOM structure for a note
const generateNoteDom = (note) => {
const noteEl = document.createElement("div");
const button = document.createElement("button");
const textEl = document.createElement("a");
//Setup delete button
button.textContent = " x";
noteEl.appendChild(button);
button.addEventListener("click", () => {
removeNote(note.id);
saveNotes(notes);
renderNotes(notes, filters);
});
//Setup note title
if (note.title.length > 0) {
textEl.textContent = note.title;
} else {
textEl.textContent = " Unamed note";
}
//When user clicks on note, it takes them to the edit page with
//Corresponding ID
textEl.setAttribute("href", `edit.html#${note.id}`);
noteEl.appendChild(textEl);
return noteEl;
};
const dataLastEdited = (timestamp) => {
return `Last edited ${moment(timestamp).fromNow()}`;
};
</code></pre>
<p>and finally, this is the <code>note-edit.js</code> file which is responsible for the <code>edit.html</code> page</p>
<pre><code>const noteID = location.hash.substring(1);
const noteTitle = document.querySelector("#note-title");
const noteBody = document.querySelector("#note-body");
const removeEl = document.querySelector("#remove-note");
const lastEdited = document.querySelector("#last-edited");
let notes = getSavedNotes();
let note = notes.find((note) => {
return note.id === noteID;
});
//if note is not found then redirect user to index
if (note === undefined) {
location.assign("/index.html");
}
noteTitle.value = note.title;
noteBody.value = note.body;
lastEdited.textContent = dataLastEdited(note.updatedAt);
noteTitle.addEventListener("input", (e) => {
note.title = e.target.value;
note.updatedAt = moment().valueOf();
lastEdited.textContent = dataLastEdited(note.updatedAt);
saveNotes(notes);
});
noteBody.addEventListener("input", (e) => {
note.body = e.target.value;
note.updatedAt = moment().valueOf();
lastEdited.textContent = dataLastEdited(note.updatedAt);
saveNotes(notes);
});
removeEl.addEventListener("click", () => {
removeNote(note.id);
saveNotes(notes);
location.assign("/index.html");
});
window.addEventListener("storage", (e) => {
if (e.key === "notes") {
notes = JSON.parse(e.newValue);
let note = notes.find((note) => {
return note.id === noteID;
});
//if note is not found then redirect user to index
if (note === undefined) {
location.assign("/index.html");
}
noteTitle.value = note.title;
noteBody.value = note.body;
}
lastEdited.textContent = dataLastEdited(note.updatedAt);
});
</code></pre>
|
[] |
[
{
"body": "<p><strong>Script location</strong> The earlier external resources like <code><script src</code> and <code><link</code> tags come in the DOM, the earlier they'll be parsed by the browser, which means they can be downloaded more quickly by the client. If your scripts aren't written inline, then you can consider putting them in the <code><head></code> so that they're downloaded ASAP. In contrast, if you put a script at the bottom of the body, and the page is large enough that the whole HTML doesn't get downloaded immediately, the script will not even <em>start</em> to download until the <em>final</em> chunk of the HTML is parsed by the client.</p>\n<p>(It very likely doesn't matter much for pages this small, but that could change if you decide to add more HTML content, and it's a good habit to get into regardless IMO)</p>\n<p>To avoid having to wrap the script contents in a DOMContentLoaded listener, and to avoid render-blocking, you can add the <code>defer</code> attribute to all the script tags.</p>\n<p><strong>Concise sorting</strong> When you need to sort based on numeric differences, rather than writing out <code>return 1;</code> or <code>return 0;</code> or <code>return -1</code> depending, you can simply return the <em>difference</em> (which will evaluate to a positive number, 0, or to a negative number, which ia all that's needed).</p>\n<p>When you need to sort by whether a string comes before another alphabetically, use <code>localeCompare</code>:</p>\n<pre><code>const sortNotes = (notes, sortBy) => {\n if (sortBy === "byEdited") {\n return notes.sort((a, b) => b.updatedAt - a.updatedAt);\n } else if (sortBy === "byCreated") {\n return notes.sort((a, b) => b.createdAt - a.createdAt);\n } else if (sortBy === "alphabetical") {\n return notes.sort((a, b) => a.toLowerCase().localeCompare(b.toLowerCase()));\n } else {\n return notes;\n }\n};\n</code></pre>\n<p><strong>Styles?</strong> Adding CSS styles to webpages will help it look a lot less plain.</p>\n<p><strong>Sorting sorts in-place</strong> - when you do</p>\n<pre><code>const renderNotes = (notes, filters) => {\n notes = sortNotes(notes, filters.sortBy);\n</code></pre>\n<p>you reassign <code>notes</code> to the same array it refers to originally. Consider leaving out the reassignment:</p>\n<pre><code>const renderNotes = (notes, filters) => {\n sortNotes(notes, filters.sortBy);\n</code></pre>\n<p><strong>Consider implicit return</strong> I notice that despite using arrow functions, you're never using implicit return. If this is a deliberate style choice, that's fine. If not, consider where it might be worth it - for example, if you so wished, this:</p>\n<pre><code>const noteIndex = notes.findIndex((note) => {\n return note.id === id;\n});\n</code></pre>\n<p>could be</p>\n<pre><code>const noteIndex = notes.findIndex(note => note.id === id);\n</code></pre>\n<p>(If note lookup by ID is a frequent operation, you could consider an object indexed by ID instead of an array in order to look up items faster, though it'd make sorting a bit less natural since you'd have to extract the object values into an array first)</p>\n<p><strong>Variable name</strong> There's <code>const textEl = document.createElement("a");</code>, but text nodes are a <a href=\"https://stackoverflow.com/q/17195868\">separate concept</a>. Maybe call it <code>editLink</code> or <code>editAnchor</code> instead. Also, the function <code>dataLastEdited</code> returns a last edited timestamp string for display, so perhaps call it <code>dateLastEdited</code>.</p>\n<p><strong>Terminate the script on the edit page if a note isn't found</strong> This:</p>\n<pre><code>//if note is not found then redirect user to index\nif (note === undefined) {\n location.assign("/index.html");\n}\n\nnoteTitle.value = note.title;\n// ...\n</code></pre>\n<p>can be</p>\n<pre><code>//if note is not found then redirect user to index\nif (note === undefined) {\n location.assign("/index.html");\n} else {\n noteTitle.value = note.title;\n // ...\n</code></pre>\n<p>or, in a function:</p>\n<pre><code>if (note === undefined) {\n location.assign("/index.html");\n return;\n}\nnoteTitle.value = note.title;\n// ...\n</code></pre>\n<hr />\n<p>You're properly setting values from the user into <code>textContent</code> rather than concatenating into an HTML string or using <code>.innerHTML</code>, which will successfully prevent XSS-related exploits. This is a very common issue that people get wrong, it's nice to see it implemented properly.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-25T19:56:59.807",
"Id": "253909",
"ParentId": "253901",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "253909",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-25T17:04:50.790",
"Id": "253901",
"Score": "2",
"Tags": [
"javascript",
"html"
],
"Title": "Javascript + html: Simple Note App"
}
|
253901
|
<p>I found myself in need of a lock that allows my server to barge the write lock that might be acquired by my users. It would never interrupt them, but it would jump the line so the next time the write lock is available, my server gets it instead. It's quite simple, but I'm wondering if there's something I might have missed. I'm obviously open to feedback on all aspects, because why not, but I'm primarily interested in feedback on correctness and bugs.</p>
<pre><code>/**
* An implementation of a lock with 3 locking levels.
*
* The first level is READ - any number of readers may read concurrently as per
* the specification of {@link ReentrantReadWriteLock}.
*
* The second level is WRITE - only one writer may write at a time, as per the
* specification of {@link ReentrantReadWriteLock}.
*
* The final level is BARGE - a barge request will skip the line to perform an
* operation with write level access with priority over the others. Competing
* barge requests will resolve themselves as per the Write specification of
* {@link ReentrantReadWriteLock} (but they only compete with other Barge
* requests, not Write requests.)
*
* The intended use case is for mission critical work. Consider users making
* requests with read and write privileges and a server that needs periodic
* maintenance routines. The server should not wait in line behind users.
* Certain admin requests may also need to barge to preempt a malicious actor
* from flooding the server. If the admin request had to wait in line behind
* all the malicious requests, untold damage could be done in the meanwhile.
*
*/
public class BargeLock {
/**
* The typical read-write lock. This implentation should, in time, proxy
* many of the methods to this.
*/
private final ReentrantReadWriteLock standard = new ReentrantReadWriteLock(true);
/**
* The barge lock - readers and writers of the standard lock will READ from
* this lock so they all read concurrently. Bargers will write to this, so
* all other users wait behind the barge.
*/
private final ReentrantReadWriteLock barge = new ReentrantReadWriteLock(true);
/**
* Perform some operation within the safety of a read block, concurrently
* with other read operations, and blocked by all write and barge operations.
* @param lambda The operation to perform. Users are responsible for handling
* input and output outside of this method
*/
public void performInsideRead(Runnable lambda) {
try {
barge.readLock().lock();
try {
standard.readLock().lock();
lambda.run();
} finally {
standard.readLock().unlock();
}
} finally {
barge.readLock().unlock();
}
}
/**
* Perform some operation within the safety of a write block, blocking all
* read operations and potentially being blocked by earlier arriving write
* operations, and potentially being blocked by barge operations.
* @param lambda The operation to perform. Users are responsible for
* handling input and output outside of this method
*/
public void performInsideWrite(Runnable lambda) {
try {
barge.readLock().lock();
try {
standard.writeLock().lock();
lambda.run();
} finally {
standard.writeLock().unlock();
}
} finally {
barge.readLock().unlock();
}
}
/**
* Perform an operation with priority over all writes and reads. Blocks
* only from earlier arriving barges.
* @param lambda The operation to perform. Users are responsible for
* handling input and output outside of this method.
*/
public void performInsideBarge(Runnable lambda) {
try {
barge.writeLock().lock();
try {
standard.writeLock().lock();
lambda.run();
} finally {
standard.writeLock().unlock();
}
} finally {
barge.writeLock().unlock();
}
}
}
</code></pre>
|
[] |
[
{
"body": "<p>There's not much to say, it's not much code, it's documented and from reading it I could not find an error in the locking mechanism.</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code>public void performInsideRead(Runnable lambda) {\n</code></pre>\n<p>A better name would be <code>performSafeRead</code> or <code>performRead</code>, as "inside" does not necessarily give any additional meaning.</p>\n<p><code>lambda</code> should be called <code>action</code> or <code>readAction</code>, as it is not necessarily a lambda.</p>\n<p>Having said that, <code>BargeLock</code> might also not be the best name, as it less of a lock, and more of a safe executor.</p>\n<hr />\n<p>Given that there is not much else to review, let's talk API design.</p>\n<pre class=\"lang-java prettyprint-override\"><code>public class BargeLock {\n private final ReentrantReadWriteLock standard;\n private final ReentrantReadWriteLock barge;\n \n public BargeLock();\n public void performInsideRead(Runnable lambda);\n public void performInsideWrite(Runnable lambda);\n public void performInsideBarge(Runnable lambda);\n}\n</code></pre>\n<p>From an API consumer point of view, it is clear how to use it. As said before, naming could be better, something like this maybe:</p>\n<pre class=\"lang-java prettyprint-override\"><code>public class BargeExecutor {\n private final ReentrantReadWriteLock standardLock;\n private final ReentrantReadWriteLock bargeLock;\n \n public BargeExecutor();\n public void runRead(Runnable readAction);\n public void runWrite(Runnable writeAction);\n public void runBarge(Runnable bargeAction);\n}\n</code></pre>\n<p>But if somebody wants to extend that class, it's pretty much impossible. The class is not marked <code>final</code>, so an extension is possible (and maybe wanted in some scenario). But given that only the <code>public</code> methods are accessible, and extension can't do anything useful. You could now make the class <code>final</code>, that would clear that up. However, I <em>hate</em> <code>final</code> classes and methods with a passion, because too often I found myself needing to extend or override <strong>that</strong> method without alternatives (I'm not talking about Java <code>KeyStore</code> or something, but simple library classes).</p>\n<p>So, instead of making it <code>final</code>, it would be interesting if you'd expose the internal state in a half-way safe manner. That can be done by either making <code>standard</code> and <code>barge</code> <code>protected</code>, or by exposing them through <code>protected</code> getters, like this:</p>\n<pre class=\"lang-java prettyprint-override\"><code>public class BargeLock {\n protected final ReentrantReadWriteLock standard;\n protected final ReentrantReadWriteLock barge;\n \n public BargeLock();\n public void performInsideRead(Runnable lambda);\n public void performInsideWrite(Runnable lambda);\n public void performInsideBarge(Runnable lambda);\n}\n</code></pre>\n<pre class=\"lang-java prettyprint-override\"><code>public class BargeLock {\n private final ReentrantReadWriteLock standard;\n private final ReentrantReadWriteLock barge;\n \n public BargeLock();\n public void performInsideRead(Runnable lambda);\n public void performInsideWrite(Runnable lambda);\n public void performInsideBarge(Runnable lambda);\n \n protected final ReentrantReadWriteLock getStandard();\n protected final ReentrantReadWriteLock getBarge();\n}\n</code></pre>\n<p>The getters are <code>final</code> because internally the value of the member is being used, not the getter. So overriding the getter in an extending class would yield the false impression that one can change the internal logic of the "perform" functions.</p>\n<p>Additionally, the documentation should state <em>clearly</em> in what order the locks are acquired, to allow overriding classes to have the same order to avoid deadlocks.</p>\n<p>On another note, currently the executed actions can't throw anything except <code>RuntimeException</code>. You might want to have a custom interface which allows to throw any <code>Exception</code> or <code>Throwable</code> and make it clear that this can happen in your documentation. That would allow a cleaner handling of exceptions in the resulting code:</p>\n<pre class=\"lang-java prettyprint-override\"><code>// Business logic\ntry {\n barge.performInsideWrite(() -> {\n throw new BusinessException("test");\n });\n} catch (BusinessException e) {\n // Handle exception here, assume it's expensive for some reason.\n}\n</code></pre>\n<p>Also, if processing exceptions is expensive for some reason, it would reduce lock time.</p>\n<p>Returning values from the inside might also be of interest, currently that is not that easily possible.</p>\n<pre class=\"lang-java prettyprint-override\"><code>public <TYPE> TYPE performInsideWrite(Action<TYPE> action) {\n // ...\n return action.run();\n // ...\n}\n\nBusinessObject businessObject = barge.performInsideWrite(() -> {\n return new BusinessObject();\n});\n</code></pre>\n<p>So, there's that.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-27T17:36:55.197",
"Id": "500842",
"Score": "0",
"body": "The note about exceptions is really good - after thinking about it I think I'm going to create a result object, which will be good for a couple reasons - first, I can make the lock generic so it can be type safe to return the result value, but the result object might also have a throwable that was caught. - so I'll change the lambda from a Runnable to a Producer. While I'm weary of exposing the locks outside the class, I do want to leave it open to extension, though, so making them protected is an improvement. You are correct about the name - it isn't any more a lock than a door is."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-27T17:38:54.110",
"Id": "500843",
"Score": "0",
"body": "I appreciate the thorough review - I'm pressed for time right now (thanks to the holiday, my weekend, well, isn't... hahaha) but I do intend to consider most of these suggestions, and implement many of them."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-26T08:45:39.830",
"Id": "253921",
"ParentId": "253905",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-25T19:18:41.807",
"Id": "253905",
"Score": "2",
"Tags": [
"java",
"concurrency",
"locking"
],
"Title": "Barging lock in Java"
}
|
253905
|
<p>I wrote C++20 implementation of a simple matrix class and its usage in Strassen's <span class="math-container">\$O(n^{lg_2{7}})\$</span> matrix multiplication algorithm.</p>
<p>Live demo: <a href="https://wandbox.org/permlink/JaSC8fQccFbcl1QY" rel="noreferrer">https://wandbox.org/permlink/JaSC8fQccFbcl1QY</a>
(For n = 64, normal <span class="math-container">\$O(n^3)\$</span> matmul runs in 0ms and Strassen <span class="math-container">\$O(n^{2.81})\$</span> matmul runs in 33ms, hahaha)</p>
<p><code>Matrix</code> is a numerical matrix class and <code>MatrixView</code> is basically a non-owning reference for a submatrix of a <code>Matrix</code>, or <code>Matrix</code> itself.
I hate that there is lots of boilerplate and duplicate code, but I don't know a better way.</p>
<pre class="lang-cpp prettyprint-override"><code>#include <algorithm>
#include <array>
#include <cassert>
#include <chrono>
#include <complex>
#include <concepts>
#include <cstddef>
#include <functional>
#include <initializer_list>
#include <iostream>
#include <iterator>
#include <memory>
#include <numeric>
#include <utility>
#include <random>
#include <ranges>
#include <thread>
namespace crn = std::chrono;
namespace sr = std::ranges;
template <typename T>
concept Scalar = std::is_arithmetic_v<T> || std::is_same_v<T, std::complex<float>>
|| std::is_same_v<T, std::complex<double>> || std::is_same_v<T, std::complex<long double>>;
template <Scalar T>
class MatrixView;
template <Scalar T>
class Matrix {
public:
const std::size_t R;
const std::size_t C;
private:
std::unique_ptr<T[]> data;
public:
friend class MatrixView<T>;
using value_type = T;
using iterator = T*;
using const_iterator = const T*;
iterator begin() { return data.get(); }
[[nodiscard]] const_iterator begin() const { return data.get(); }
[[nodiscard]] const_iterator cbegin() const { return data.get(); }
iterator end() { return data.get() + R * C; }
[[nodiscard]] const_iterator end() const { return data.get() + R * C; }
[[nodiscard]] const_iterator cend() const { return data.get() + R * C; }
Matrix(std::size_t R, std::size_t C) : R {R}, C {C}, data(new T[R * C]) {}
template <Scalar T2>
Matrix(std::initializer_list<std::initializer_list<T2>> il);
Matrix(const Matrix& mat);
Matrix& operator=(const Matrix& mat);
Matrix(Matrix&& mat) noexcept = default;
Matrix& operator=(Matrix&& mat) noexcept = default;
template <Scalar T2>
Matrix(const Matrix<T2>& mat);
template <Scalar T2>
Matrix& operator=(const Matrix<T2>& mat);
template <Scalar T2>
Matrix(const MatrixView<T2>& matview);
template <Scalar T2>
Matrix& operator=(const MatrixView<T2>& matview);
T& operator()(std::size_t r, std::size_t c) {
assert(r < R && c < C);
return data.get()[r * C + c];
}
const T& operator()(std::size_t r, std::size_t c) const {
assert(r < R && c < C);
return data.get()[r * C + c];
}
MatrixView<T> submatrix(std::size_t r1, std::size_t c1, std::size_t r2, std::size_t c2) {
assert(r1 <= r2 && c1 <= c2 && r2 < R && c2 < C);
std::size_t RV = r2 - r1 + 1;
std::size_t CV = c2 - c1 + 1;
std::unique_ptr<std::size_t[]> index(new std::size_t[RV * CV]);
for (std::size_t r = 0; r < RV; r++) {
for (std::size_t c = 0; c < CV; c++) {
index.get()[r * CV + c] = (r1 + r) * C + (c1 + c);
}
}
MatrixView<T> sub(RV, CV, &data.get()[0], std::move(index));
return sub;
}
MatrixView<T> submatrix(std::size_t r1, std::size_t c1, std::size_t r2, std::size_t c2) const {
assert(r1 <= r2 && c1 <= c2 && r2 < R && c2 < C);
std::size_t RV = r2 - r1 + 1;
std::size_t CV = c2 - c1 + 1;
std::unique_ptr<std::size_t[]> index(new std::size_t[RV * CV]);
for (std::size_t r = 0; r < RV; r++) {
for (std::size_t c = 0; c < CV; c++) {
index.get()[r * CV + c] = (r1 + r) * C + (c1 + c);
}
}
MatrixView<T> sub(RV, CV, const_cast<T*>(&data.get()[0]), std::move(index));
return sub;
}
Matrix& operator+=(T val);
Matrix& operator-=(T val);
Matrix& operator*=(T val);
Matrix& operator/=(T val);
template <Scalar T2>
Matrix& operator+=(const Matrix<T2>& rhs);
template <Scalar T2>
Matrix& operator+=(const MatrixView<T2>& rhs);
template <Scalar T2>
Matrix& operator-=(const Matrix<T2>& rhs);
template <Scalar T2>
Matrix& operator-=(const MatrixView<T2>& rhs);
friend std::ostream& operator<<(std::ostream& os, const Matrix<T>& mat) {
os << '{';
for (std::size_t r = 0; r < mat.R; r++) {
os << '{';
for (std::size_t c = 0; c < mat.C; c++) {
os << mat.data[r * mat.C + c];
if (c != mat.C - 1) {
os << ", ";
}
}
if (r == mat.R - 1) {
os << '}';
} else {
os << "},\n";
}
}
os << "}\n";
return os;
}
};
template <Scalar T>
class MatrixView {
T* data_view;
std::unique_ptr<std::size_t[]> index;
friend class Matrix<T>;
public:
const std::size_t R;
const std::size_t C;
MatrixView(std::size_t R, std::size_t C,
T* data_view, std::unique_ptr<std::size_t[]> index)
: data_view {data_view}, index {std::move(index)}, R {R}, C {C} {
}
struct MVIterator {
T* data_view;
std::size_t* index;
using difference_type = std::ptrdiff_t;
using value_type = T;
using pointer = T*;
using reference = T&;
using iterator_category = std::random_access_iterator_tag;
MVIterator(T* data_view, std::size_t* index) : data_view {data_view}, index {index} {}
reference operator*() const {
return data_view[*index];
}
pointer operator->() const {
return data_view + (*index);
}
MVIterator& operator++() {
index++;
return *this;
}
MVIterator& operator--() {
index--;
return *this;
}
MVIterator operator++(int) const {
MVIterator temp = *this;
temp.index++;
return temp;
}
MVIterator operator--(int) const {
MVIterator temp = *this;
temp.index--;
return temp;
}
MVIterator operator+(difference_type n) const {
MVIterator temp = *this;
temp.index += n;
return temp;
}
MVIterator& operator+=(difference_type n) {
index += n;
return *this;
}
MVIterator operator-(difference_type n) const {
MVIterator temp = *this;
temp.index -= n;
return temp;
}
MVIterator& operator-=(difference_type n) {
index -= n;
return *this;
}
reference operator[](difference_type n) const {
return data_view[index[n]];
}
difference_type operator-(const MVIterator& other) const {
return index - other.index;
}
friend auto operator<=>(const MVIterator& it1, const MVIterator& it2) {
return it1.index <=> it2.index;
}
};
using iterator = MVIterator;
iterator begin() {
return iterator(data_view, const_cast<std::size_t*>(index.get()));
}
iterator end() {
return iterator(data_view, const_cast<std::size_t*>(index.get() + R * C));
}
template <Scalar T2>
MatrixView& operator=(const Matrix<T2>& mat);
template <Scalar T2>
MatrixView& operator=(const MatrixView<T2>& matview);
T& operator()(std::size_t r, std::size_t c) {
assert(r < R && c < C);
return data_view[index[r * C + c]];
}
const T& operator()(std::size_t r, std::size_t c) const {
assert(r < R && c < C);
return data_view[index[r * C + c]];
}
friend std::ostream& operator<<(std::ostream& os, const MatrixView<T>& matview) {
os << '{';
for (std::size_t r = 0; r < matview.R; r++) {
os << '{';
for (std::size_t c = 0; c < matview.C; c++) {
os << matview.data_view[matview.index[r * matview.C + c]];
if (c != matview.C - 1) {
os << ", ";
}
}
if (r == matview.R - 1) {
os << '}';
} else {
os << "},\n";
}
}
os << "}\n";
return os;
}
MatrixView<T> submatrix(std::size_t r1, std::size_t c1, std::size_t r2, std::size_t c2) {
assert(r1 <= r2 && c1 <= c2 && r2 < R && c2 < C);
std::size_t RV = r2 - r1 + 1;
std::size_t CV = c2 - c1 + 1;
std::unique_ptr<std::size_t[]> index_(new std::size_t[RV * CV]);
for (std::size_t r = 0; r < RV; r++) {
for (std::size_t c = 0; c < CV; c++) {
index_.get()[r * CV + c] = index.get()[(r1 + r) * C + (c1 + c)];
}
}
MatrixView<T> sub(RV, CV, &data_view[0], std::move(index_));
return sub;
}
MatrixView<T> submatrix(std::size_t r1, std::size_t c1, std::size_t r2, std::size_t c2) const {
assert(r1 <= r2 && c1 <= c2 && r2 < R && c2 < C);
std::size_t RV = r2 - r1 + 1;
std::size_t CV = c2 - c1 + 1;
std::unique_ptr<std::size_t[]> index_(new std::size_t[RV * CV]);
for (std::size_t r = 0; r < RV; r++) {
for (std::size_t c = 0; c < CV; c++) {
index_.get()[r * CV + c] = index.get()[(r1 + r) * C + (c1 + c)];
}
}
MatrixView<T> sub(RV, CV, const_cast<T*>(&data_view[0]), std::move(index_));
return sub;
}
MatrixView& operator+=(T val);
MatrixView& operator-=(T val);
MatrixView& operator*=(T val);
MatrixView& operator/=(T val);
template <Scalar T2>
MatrixView& operator+=(const Matrix<T2>& rhs);
template <Scalar T2>
MatrixView& operator+=(const MatrixView<T2>& rhs);
template <Scalar T2>
MatrixView& operator-=(const Matrix<T2>& rhs);
template <Scalar T2>
MatrixView& operator-=(const MatrixView<T2>& rhs);
};
template <Scalar T>
Matrix<T>::Matrix(const Matrix<T>& mat) : R {mat.R}, C {mat.C}, data (new T[R * C]) {
for (std::size_t i = 0; i < R * C; i++) {
data.get()[i] = mat.data.get()[i];
}
}
template <Scalar T>
Matrix<T>& Matrix<T>::operator=(const Matrix<T>& mat) {
for (std::size_t i = 0; i < R * C; i++) {
data.get()[i] = mat.data.get()[i];
}
}
template <Scalar T>
template <Scalar T2>
Matrix<T>::Matrix(const Matrix<T2>& mat) : R {mat.R}, C {mat.C}, data (new T[R * C]) {
for (std::size_t i = 0; i < R * C; i++) {
data.get()[i] = static_cast<T>(mat.data.get()[i]);
}
}
template <Scalar T>
template <Scalar T2>
Matrix<T>& Matrix<T>::operator=(const Matrix<T2>& mat) {
for (std::size_t i = 0; i < R * C; i++) {
data.get()[i] = static_cast<T>(mat.data.get()[i]);
}
}
template <Scalar T>
template <Scalar T2>
Matrix<T>::Matrix(std::initializer_list<std::initializer_list<T2>> il) : R(il.size()), C(il.begin()->size()), data(new T[R * C]) {
assert(il.size() == R && sr::all_of(il, [this](const auto& il_) {return il_.size() == C;}));
std::size_t index = 0;
for (auto first_il = il.begin(); first_il != il.end(); ++first_il) {
for (auto first_ptr = first_il->begin(); first_ptr != first_il->end(); ++first_ptr) {
data.get()[index++] = *first_ptr;
}
}
}
template <Scalar T>
template <Scalar T2>
Matrix<T>::Matrix(const MatrixView<T2>& matview) : R {matview.R}, C {matview.C}, data (new T[R * C]) {
for (std::size_t i = 0; i < R * C; i++) {
data.get()[i] = matview.data_view[matview.index.get()[i]];
}
}
template <Scalar T>
template <Scalar T2>
Matrix<T>& Matrix<T>::operator=(const MatrixView<T2>& matview) {
for (std::size_t i = 0; i < R * C; i++) {
data.get()[i] = matview.data_view[matview.index.get()[i]];
}
return *this;
}
template <Scalar T>
template <Scalar T2>
MatrixView<T>& MatrixView<T>::operator=(const Matrix<T2>& mat) {
for (std::size_t i = 0; i < R * C; i++) {
data_view[index.get()[i]] = mat.data.get()[i];
}
return *this;
}
template <Scalar T>
template <Scalar T2>
MatrixView<T>& MatrixView<T>::operator=(const MatrixView<T2>& matview) {
for (std::size_t i = 0; i < R * C; i++) {
data_view[index.get()[i]] = matview.data_view[matview.index.get()[i]];
}
return *this;
}
template <Scalar T>
Matrix<T>& Matrix<T>::operator+=(T val) {
for (auto& n : data.get()) {
n += val;
}
return *this;
}
template <Scalar T>
MatrixView<T>& MatrixView<T>::operator+=(T val) {
for (std::size_t i = 0; i < R * C; i++) {
data_view[index.get()[i]] += val;
}
return *this;
}
template <Scalar T>
Matrix<T> operator+(const Matrix<T>& m, T val) {
Matrix<T> res = m;
res += val;
return res;
}
template <Scalar T>
Matrix<T> operator+(const MatrixView<T>& m, T val) {
Matrix<T> res = m;
res += val;
return res;
}
template <Scalar T>
Matrix<T>& Matrix<T>::operator-=(T val) {
for (auto& n : data.get()) {
n += val;
}
return *this;
}
template <Scalar T>
MatrixView<T>& MatrixView<T>::operator-=(T val) {
for (std::size_t i = 0; i < R * C; i++) {
data_view[index.get()[i]] += val;
}
return *this;
}
template <Scalar T>
Matrix<T> operator-(const Matrix<T>& m, T val) {
Matrix<T> res = m;
res -= val;
return res;
}
template <Scalar T>
Matrix<T> operator-(const MatrixView<T>& m, T val) {
Matrix<T> res = m;
res -= val;
return res;
}
template <Scalar T>
Matrix<T>& Matrix<T>::operator*=(T val) {
for (auto& n : data.get()) {
n *= val;
}
return *this;
}
template <Scalar T>
MatrixView<T>& MatrixView<T>::operator*=(T val) {
for (std::size_t i = 0; i < R * C; i++) {
data_view[index.get()[i]] *= val;
}
return *this;
}
template <Scalar T>
Matrix<T> operator*(const Matrix<T>& m, T val) {
Matrix<T> res = m;
res *= val;
return res;
}
template <Scalar T>
Matrix<T> operator*(const MatrixView<T>& m, T val) {
Matrix<T> res = m;
res *= val;
return res;
}
template <Scalar T>
Matrix<T>& Matrix<T>::operator/=(T val) {
for (auto& n : data.get()) {
n /= val;
}
return *this;
}
template <Scalar T>
MatrixView<T>& MatrixView<T>::operator/=(T val) {
for (std::size_t i = 0; i < R * C; i++) {
data_view[index.get()[i]] /= val;
}
return *this;
}
template <Scalar T>
Matrix<T> operator/(const Matrix<T>& m, T val) {
Matrix<T> res = m;
res /= val;
return res;
}
template <Scalar T>
Matrix<T> operator/(const MatrixView<T>& m, T val) {
Matrix<T> res = m;
res /= val;
return res;
}
template <Scalar T>
template <Scalar T2>
Matrix<T>& Matrix<T>::operator+=(const Matrix<T2>& rhs) {
for (std::size_t i = 0; i < R * C; i++) {
data.get()[i] += rhs.data.get()[i];
}
return *this;
}
template <Scalar T>
template <Scalar T2>
Matrix<T>& Matrix<T>::operator+=(const MatrixView<T2>& rhs) {
for (std::size_t i = 0; i < R * C; i++) {
data.get()[i] += rhs.data_view[rhs.index.get()[i]];
}
return *this;
}
template <Scalar T>
template <Scalar T2>
MatrixView<T>& MatrixView<T>::operator+=(const Matrix<T2>& rhs) {
for (std::size_t i = 0; i < R * C; i++) {
data_view[index.get()[i]] += rhs.data.get()[i];
}
return *this;
}
template <Scalar T>
template <Scalar T2>
MatrixView<T>& MatrixView<T>::operator+=(const MatrixView<T2>& rhs) {
for (std::size_t i = 0; i < R * C; i++) {
data_view[index.get()[i]] += rhs.data_view[rhs.index.get()[i]];
}
return *this;
}
template <Scalar T1, Scalar T2, Scalar T3 = std::common_type_t<T1, T2>>
Matrix<T3> operator+(const Matrix<T1>& m1, const Matrix<T2>& m2) {
Matrix<T3> res = m1;
res += m2;
return res;
}
template <Scalar T1, Scalar T2, Scalar T3 = std::common_type_t<T1, T2>>
Matrix<T3> operator+(const Matrix<T1>& m1, const MatrixView<T2>& m2) {
Matrix<T3> res = m1;
res += m2;
return res;
}
template <Scalar T1, Scalar T2, Scalar T3 = std::common_type_t<T1, T2>>
Matrix<T3> operator+(const MatrixView<T1>& m1, const Matrix<T2>& m2) {
Matrix<T3> res = m1;
res += m2;
return res;
}
template <Scalar T1, Scalar T2, Scalar T3 = std::common_type_t<T1, T2>>
Matrix<T3> operator+(const MatrixView<T1>& m1, const MatrixView<T2>& m2) {
Matrix<T3> res = m1;
res += m2;
return res;
}
template <Scalar T>
template <Scalar T2>
Matrix<T>& Matrix<T>::operator-=(const Matrix<T2>& rhs) {
for (std::size_t i = 0; i < R * C; i++) {
data.get()[i] -= rhs.data.get()[i];
}
return *this;
}
template <Scalar T>
template <Scalar T2>
Matrix<T>& Matrix<T>::operator-=(const MatrixView<T2>& rhs) {
for (std::size_t i = 0; i < R * C; i++) {
data.get()[i] -= rhs.data_view[rhs.index.get()[i]];
}
return *this;
}
template <Scalar T>
template <Scalar T2>
MatrixView<T>& MatrixView<T>::operator-=(const Matrix<T2>& rhs) {
for (std::size_t i = 0; i < R * C; i++) {
data_view[index.get()[i]] -= rhs.data.get()[i];
}
return *this;
}
template <Scalar T>
template <Scalar T2>
MatrixView<T>& MatrixView<T>::operator-=(const MatrixView<T2>& rhs) {
for (std::size_t i = 0; i < R * C; i++) {
data_view[index.get()[i]] -= rhs.data_view[rhs.index.get()[i]];
}
return *this;
}
template <Scalar T1, Scalar T2, Scalar T3 = std::common_type_t<T1, T2>>
Matrix<T3> operator-(const Matrix<T1>& m1, const Matrix<T2>& m2) {
Matrix<T3> res = m1;
res -= m2;
return res;
}
template <Scalar T1, Scalar T2, Scalar T3 = std::common_type_t<T1, T2>>
Matrix<T3> operator-(const Matrix<T1>& m1, const MatrixView<T2>& m2) {
Matrix<T3> res = m1;
res -= m2;
return res;
}
template <Scalar T1, Scalar T2, Scalar T3 = std::common_type_t<T1, T2>>
Matrix<T3> operator-(const MatrixView<T1>& m1, const Matrix<T2>& m2) {
Matrix<T3> res = m1;
res -= m2;
return res;
}
template <Scalar T1, Scalar T2, Scalar T3 = std::common_type_t<T1, T2>>
Matrix<T3> operator-(const MatrixView<T1>& m1, const MatrixView<T2>& m2) {
Matrix<T3> res = m1;
res -= m2;
return res;
}
template <Scalar T1, Scalar T2, Scalar T3 = std::common_type_t<T1, T2>>
Matrix<T3> operator*(const Matrix<T1>& m1, const Matrix<T2>& m2) {
std::size_t M = m1.R;
std::size_t K = m1.C;
assert(m2.R == K);
std::size_t N = m2.C;
Matrix<T3> m3 (M, N);
for (size_t m = 0; m < M; m++) {
for (size_t n = 0; n < N; n++) {
m3(m, n) = 0;
for (size_t k = 0; k < K; k++) {
m3(m, n) += m1(m, k) * m2(k, n);
}
}
}
return m3;
}
template <Scalar T1, Scalar T2, Scalar T3 = std::common_type_t<T1, T2>>
Matrix<T3> operator*(const MatrixView<T1>& m1, const Matrix<T2>& m2) {
std::size_t M = m1.R;
std::size_t K = m1.C;
assert(m2.R == K);
std::size_t N = m2.C;
Matrix<T3> m3 (M, N);
for (size_t m = 0; m < M; m++) {
for (size_t n = 0; n < N; n++) {
m3(m, n) = 0;
for (size_t k = 0; k < K; k++) {
m3(m, n) += m1(m, k) * m2(k, n);
}
}
}
return m3;
}
template <Scalar T1, Scalar T2, Scalar T3 = std::common_type_t<T1, T2>>
Matrix<T3> operator*(const MatrixView<T1>& m1, const MatrixView<T2>& m2) {
std::size_t M = m1.R;
std::size_t K = m1.C;
assert(m2.R == K);
std::size_t N = m2.C;
Matrix<T3> m3 (M, N);
for (size_t m = 0; m < M; m++) {
for (size_t n = 0; n < N; n++) {
m3(m, n) = 0;
for (size_t k = 0; k < K; k++) {
m3(m, n) += m1(m, k) * m2(k, n);
}
}
}
return m3;
}
template <Scalar T1, Scalar T2, Scalar T3 = std::common_type_t<T1, T2>>
Matrix<T3> operator*(const Matrix<T1>& m1, const MatrixView<T2>& m2) {
std::size_t M = m1.R;
std::size_t K = m1.C;
assert(m2.R == K);
std::size_t N = m2.C;
Matrix<T3> m3 (M, N);
for (size_t m = 0; m < M; m++) {
for (size_t n = 0; n < N; n++) {
m3(m, n) = 0;
for (size_t k = 0; k < K; k++) {
m3(m, n) += m1(m, k) * m2(k, n);
}
}
}
return m3;
}
template <Scalar T>
Matrix<T> Strassen(const Matrix<T>& A, const Matrix<T>& B) {
std::size_t N = A.R;
assert(A.C == N && B.R == N && B.C == N && (N & (N - 1)) == 0);
if (N == 1) {
return A * B;
}
Matrix<T> C (N, N);
std::size_t H = N / 2;
auto A11 = A.submatrix(0, 0, H - 1, H - 1);
auto A12 = A.submatrix(0, H, H - 1, N - 1);
auto A21 = A.submatrix(H, 0, N - 1, H - 1);
auto A22 = A.submatrix(H, H, N - 1, N - 1);
auto B11 = B.submatrix(0, 0, H - 1, H - 1);
auto B12 = B.submatrix(0, H, H - 1, N - 1);
auto B21 = B.submatrix(H, 0, N - 1, H - 1);
auto B22 = B.submatrix(H, H, N - 1, N - 1);
auto C11 = C.submatrix(0, 0, H - 1, H - 1);
auto C12 = C.submatrix(0, H, H - 1, N - 1);
auto C21 = C.submatrix(H, 0, N - 1, H - 1);
auto C22 = C.submatrix(H, H, N - 1, N - 1);
auto S1 = B12 - B22;
auto S2 = A11 + A12;
auto S3 = A21 + A22;
auto S4 = B21 - B11;
auto S5 = A11 + A22;
auto S6 = B11 + B22;
auto S7 = A12 - A22;
auto S8 = B21 + B22;
auto S9 = A11 - A21;
auto S10 = B11 + B12;
auto P1 = Strassen(A11, S1);
auto P2 = Strassen(S2, B22);
auto P3 = Strassen(S3, B11);
auto P4 = Strassen(A22, S4);
auto P5 = Strassen(S5, S6);
auto P6 = Strassen(S7, S8);
auto P7 = Strassen(S9, S10);
C11 = P5 + P4 - P2 + P6;
C12 = P1 + P2;
C21 = P3 + P4;
C22 = P5 + P1 - P3 - P7;
return C;
}
template <Scalar T>
Matrix<T> Strassen(const MatrixView<T>& A, const Matrix<T>& B) {
std::size_t N = A.R;
assert(A.C == N && B.R == N && B.C == N && (N & (N - 1)) == 0);
if (N == 1) {
return A * B;
}
Matrix<T> C (N, N);
std::size_t H = N / 2;
auto A11 = A.submatrix(0, 0, H - 1, H - 1);
auto A12 = A.submatrix(0, H, H - 1, N - 1);
auto A21 = A.submatrix(H, 0, N - 1, H - 1);
auto A22 = A.submatrix(H, H, N - 1, N - 1);
auto B11 = B.submatrix(0, 0, H - 1, H - 1);
auto B12 = B.submatrix(0, H, H - 1, N - 1);
auto B21 = B.submatrix(H, 0, N - 1, H - 1);
auto B22 = B.submatrix(H, H, N - 1, N - 1);
auto C11 = C.submatrix(0, 0, H - 1, H - 1);
auto C12 = C.submatrix(0, H, H - 1, N - 1);
auto C21 = C.submatrix(H, 0, N - 1, H - 1);
auto C22 = C.submatrix(H, H, N - 1, N - 1);
auto S1 = B12 - B22;
auto S2 = A11 + A12;
auto S3 = A21 + A22;
auto S4 = B21 - B11;
auto S5 = A11 + A22;
auto S6 = B11 + B22;
auto S7 = A12 - A22;
auto S8 = B21 + B22;
auto S9 = A11 - A21;
auto S10 = B11 + B12;
auto P1 = Strassen(A11, S1);
auto P2 = Strassen(S2, B22);
auto P3 = Strassen(S3, B11);
auto P4 = Strassen(A22, S4);
auto P5 = Strassen(S5, S6);
auto P6 = Strassen(S7, S8);
auto P7 = Strassen(S9, S10);
C11 = P5 + P4 - P2 + P6;
C12 = P1 + P2;
C21 = P3 + P4;
C22 = P5 + P1 - P3 - P7;
return C;
}
template <Scalar T>
Matrix<T> Strassen(const MatrixView<T>& A, const MatrixView<T>& B) {
std::size_t N = A.R;
assert(A.C == N && B.R == N && B.C == N && (N & (N - 1)) == 0);
if (N == 1) {
return A * B;
}
Matrix<T> C (N, N);
std::size_t H = N / 2;
auto A11 = A.submatrix(0, 0, H - 1, H - 1);
auto A12 = A.submatrix(0, H, H - 1, N - 1);
auto A21 = A.submatrix(H, 0, N - 1, H - 1);
auto A22 = A.submatrix(H, H, N - 1, N - 1);
auto B11 = B.submatrix(0, 0, H - 1, H - 1);
auto B12 = B.submatrix(0, H, H - 1, N - 1);
auto B21 = B.submatrix(H, 0, N - 1, H - 1);
auto B22 = B.submatrix(H, H, N - 1, N - 1);
auto C11 = C.submatrix(0, 0, H - 1, H - 1);
auto C12 = C.submatrix(0, H, H - 1, N - 1);
auto C21 = C.submatrix(H, 0, N - 1, H - 1);
auto C22 = C.submatrix(H, H, N - 1, N - 1);
auto S1 = B12 - B22;
auto S2 = A11 + A12;
auto S3 = A21 + A22;
auto S4 = B21 - B11;
auto S5 = A11 + A22;
auto S6 = B11 + B22;
auto S7 = A12 - A22;
auto S8 = B21 + B22;
auto S9 = A11 - A21;
auto S10 = B11 + B12;
auto P1 = Strassen(A11, S1);
auto P2 = Strassen(S2, B22);
auto P3 = Strassen(S3, B11);
auto P4 = Strassen(A22, S4);
auto P5 = Strassen(S5, S6);
auto P6 = Strassen(S7, S8);
auto P7 = Strassen(S9, S10);
C11 = P5 + P4 - P2 + P6;
C12 = P1 + P2;
C21 = P3 + P4;
C22 = P5 + P1 - P3 - P7;
return C;
}
template <Scalar T>
Matrix<T> Strassen(const Matrix<T>& A, const MatrixView<T>& B) {
std::size_t N = A.R;
assert(A.C == N && B.R == N && B.C == N && (N & (N - 1)) == 0);
if (N == 1) {
return A * B;
}
Matrix<T> C (N, N);
std::size_t H = N / 2;
auto A11 = A.submatrix(0, 0, H - 1, H - 1);
auto A12 = A.submatrix(0, H, H - 1, N - 1);
auto A21 = A.submatrix(H, 0, N - 1, H - 1);
auto A22 = A.submatrix(H, H, N - 1, N - 1);
auto B11 = B.submatrix(0, 0, H - 1, H - 1);
auto B12 = B.submatrix(0, H, H - 1, N - 1);
auto B21 = B.submatrix(H, 0, N - 1, H - 1);
auto B22 = B.submatrix(H, H, N - 1, N - 1);
auto C11 = C.submatrix(0, 0, H - 1, H - 1);
auto C12 = C.submatrix(0, H, H - 1, N - 1);
auto C21 = C.submatrix(H, 0, N - 1, H - 1);
auto C22 = C.submatrix(H, H, N - 1, N - 1);
auto S1 = B12 - B22;
auto S2 = A11 + A12;
auto S3 = A21 + A22;
auto S4 = B21 - B11;
auto S5 = A11 + A22;
auto S6 = B11 + B22;
auto S7 = A12 - A22;
auto S8 = B21 + B22;
auto S9 = A11 - A21;
auto S10 = B11 + B12;
auto P1 = Strassen(A11, S1);
auto P2 = Strassen(S2, B22);
auto P3 = Strassen(S3, B11);
auto P4 = Strassen(A22, S4);
auto P5 = Strassen(S5, S6);
auto P6 = Strassen(S7, S8);
auto P7 = Strassen(S9, S10);
C11 = P5 + P4 - P2 + P6;
C12 = P1 + P2;
C21 = P3 + P4;
C22 = P5 + P1 - P3 - P7;
return C;
}
int main() {
constexpr std::size_t N = 1u << 6u;
Matrix<int> m1 (N, N);
Matrix<int> m2 (N, N);
std::iota(m1.begin(), m1.end(), 0);
std::iota(m2.begin(), m2.end(), 0);
auto t1 = std::chrono::steady_clock::now();
auto m3 = m1 * m2;
auto t2 = std::chrono::steady_clock::now();
auto dt1 = std::chrono::duration_cast<std::chrono::milliseconds>(t2 - t1);
std::cout << m3;
std::cout << "Elapsed time: " << dt1.count() << "ms\n";
auto t3 = std::chrono::steady_clock::now();
auto m4 = Strassen(m1, m2);
auto t4 = std::chrono::steady_clock::now();
auto dt2 = std::chrono::duration_cast<std::chrono::milliseconds>(t4 - t3);
std::cout << m4;
std::cout << "Elapsed time: " << dt2.count() << "ms\n";
}
</code></pre>
|
[] |
[
{
"body": "<h1>Avoid restricting template types too much</h1>\n<p>You are restricting the value type of the matrix to artithmetic types and complex numbers. But what if I had a custom type that implemented <a href=\"https://en.wikipedia.org/wiki/Fraction\" rel=\"nofollow noreferrer\">fractions</a>, or had some other type for which matrix multiplication would make sense? If you cannot predict all possible valid types, don't attempt to restrict the template type at all, or write a concept that explicitly tests the <em>properties</em> that the type should have, for example that addition and multiplication return a valid result of the same type.</p>\n<h1>Avoid creating namespace aliases in header files</h1>\n<p>While your code as posted here looks like it goes into a single .cpp file, if you were to put the <code>Matrix</code> definitions in a header file, you don't want this header file to unexpectedly add namespaces. You only use <code>sr</code> once, so just replace it with <code>std::ranges</code>, and you never use <code>crn</code> so that namespace alias can be removed completely.</p>\n<h1>Consider moving <code>class MatrixView</code> into <code>class Matrix</code></h1>\n<p>You could move <code>MatrixView</code> into <code>Matrix</code>, and rename it <code>View</code>:</p>\n<pre><code>template <typename T>\nclass Matrix {\npublic:\n class View {\n T* data;\n ...\n };\n ...\n View submatrix(...) {...}\n};\n</code></pre>\n<p>This saves a lot of typing. Users outside <code>class Matrix</code> can still access this class directly by writing <code>Matrix::View</code>, unless you make it <code>private</code> of course.</p>\n<h1>Consider creating a 2D index type</h1>\n<p>Some functions take four parameters; consider if you wanted to implement this for 3D or even higher-dimensional matrices! I would create an index type that holds the indices for all the axes, and then use that wherever you have to pass the indices:</p>\n<pre><code>class Matrix {\npublic:\n struct Index {\n std::size_t r;\n std::size_t c;\n };\n\n const Index size;\n ...\n Matrix(Index size): size(size), data(new T[size.r * size.c]) {}\n T& operator()(Index index) {...}\n View submatrix(Index index1, Index index2) {...}\n</code></pre>\n<p>As a bonus, you can now even define an <code>operator[]</code> that does what you want:</p>\n<pre><code> T& operator[](Index index) {...}\n</code></pre>\n<p>And while you have to use braces to make it work when you use literals for example, it still looks quite natural:</p>\n<pre><code>Matrix<float> foo({3, 3});\nfoo[{1, 2}] = 42;\n</code></pre>\n<h1>Incorrect pre/post-in/decrement operators</h1>\n<p>You have some issues without your <code>++</code> and <code>--</code> operators. For example, in this pre-increment operator:</p>\n<pre><code>MVIterator& operator++() {\n index++;\n return *this;\n}\n</code></pre>\n<p>You should use pre-increment for <code>index</code> as well. Here it doesn't really matter since it's just a pointer and the copy that is made is optimized away by the compiler, but if <code>index</code> were a more complex type this would be bad. Write:</p>\n<pre><code>MVIterator& operator++() {\n ++index;\n return *this;\n}\n</code></pre>\n<p>But more important, your post-increment operator is incorrect:</p>\n<pre><code>MVIterator operator++(int) const {\n MVIterator temp = *this;\n temp.index++;\n return temp;\n}\n</code></pre>\n<p>The post-operators should return a copy of the original iterator before incrementing it, and only increment the original that is not returned, like so:</p>\n<pre><code>MVIterator operator++(int) const {\n MVIterator temp = *this;\n temp.index = index++;\n return temp;\n}\n</code></pre>\n<p>Or you could perhaps write this shorter as:</p>\n<pre><code>MVIterator operator++(int) const {\n return {data_view, index++};\n}\n</code></pre>\n<h1><code>submatrix()</code> is very expensive</h1>\n<p>Creating a <code>submatrix()</code> is hugely expensive, since for every element in the submatrix, you are calculating its index into the original matrix, and storing all those indices in an array. This has a huge memory overhead (the indices are <code>std::size_t</code>, which be even larger than <code>T</code> is, so the submatrix might be larger than the original), and when you want to access an element through a <code>View</code>, you have to do a double indirect dereference to get the value from the original <code>Matrix</code>.</p>\n<p>I suggest redesigning it so that a <code>View</code> only contains a pointer to the original <code>Matrix</code>, plus the indices that define the region of the view, like so:</p>\n<pre><code>class View {\n Matrix &matrix;\n Index from;\n Index to;\n ...\n View(Matrix &matrix): matrix{matrix}, from{}, to{matrix.size} {}\n View(Matrix &matrix, Index from, Index to): matrix{matrix}, from{from}, to{to} {}\n ...\n T& operator[Index index] {\n return matrix[{from.r + index.r, from.c + index.c}];\n }\n ...\n View submatrix(Index from_, Index to_) {\n return {matrix,\n {from.r + from_.r, from.c + from_.c},\n {from.r + to_.r, from.c + to_.c}};\n }\n ...\n};\n</code></pre>\n<p>That already give a huge improvement. Instead of storing a reference to the parent matrix, you could perhaps also just store a pointer to the data elements of the original matrix.</p>\n<p>Also note that this way, you avoid a lot of code duplication, as in <code>class Matrix</code> you can now just write:</p>\n<pre><code>View submatrix(Index from, Index to) {\n return {*this, from, to};\n}\n</code></pre>\n<h1>Avoid code duplication</h1>\n<p>You have four versions of <code>Strassen()</code>, because you need to be able to handle all combinations of <code>Matrix</code> and <code>MatrixView</code> for the parameters. You can avoid that by having only one version that handles only <code>Matrix::View</code>s, and if you allow implicit construction of a <code>Matrix::View</code> from a <code>Matrix</code>, you can avoid writing the three other overloads altogether:</p>\n<pre><code>template <typename T>\nMatrix<T> Strassen(const Matrix<T>::View& A, const Matrix<T>::View& B) {\n ...\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-26T02:47:23.380",
"Id": "500742",
"Score": "0",
"body": "Actually, I'm considering extract out the common part of ```Matrix``` and ```MatrixView``` to ```MatrixBase``` and make ```Matrix``` and ```MatrixView``` as derived classes from ```MatrixBase```. I think doing so would eliminate lots of duplicate overloads (so that most of the functions only take ```MatrixBase``` type parameters), but I'm not sure. Would it be a good idea?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-26T10:34:38.017",
"Id": "500753",
"Score": "0",
"body": "That might work, yes. You can post the new code as a separate question on this site, so you can have it reviewed as well."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-25T21:50:49.190",
"Id": "253915",
"ParentId": "253908",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": "253915",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-25T19:56:01.380",
"Id": "253908",
"Score": "5",
"Tags": [
"c++",
"algorithm",
"matrix",
"c++20"
],
"Title": "2D Matrix in C++20 and Strassen's algorithm"
}
|
253908
|
<p>I'm building a simple chatApp. The UI has just 3 interaction areas: <strong>input</strong>, <strong>submit</strong> and previous messages button.</p>
<p>But I'm not interested in reviewing the app architecture as much as the javascript ideas and general understanding/errors.</p>
<p>I've commented the code, and would like to see if you can point out any bad practice. I'm sure most of the code is bad, but still, the most important errors.</p>
<p>I've also included the UI as a runnable snippet.</p>
<p>Any edits to make it better for reviewers will be done.</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><!doctype html>
<html>
<head>
<title>Socket.IO chat</title>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body { font: 13px Helvetica, Arial; }
form { background: #000; padding: 3px; position: fixed; bottom: 0; width: 100%; }
form input { border: 0; padding: 10px; width: 90%; margin-right: 0.5%; }
form button { width: 9%; background: rgb(130, 224, 255); border: none; padding: 10px; }
#messages { list-style-type: none; margin: 0; padding: 0; }
#messages li { padding: 5px 10px; }
#messages li:nth-child(odd) { background: #eee; }
#wantMore{
position:absolute;
top:0;
right:0;
}
</style>
</head>
<body>
<button id="wantMore">More</button>
<ul id="messages"></ul>
<form action="">
<input id="m" autocomplete="off" /><button>Send</button>
</form>
<script src="mySnippet"></script>
<script src="socket-io.js"></script>
</body>
</html></code></pre>
</div>
</div>
</p>
<pre><code>const prevMsgs = document.querySelector("button#wantMore")
const uri = "http://localhost:3000"
class Msg {
constructor (msg, createdAt){
this.msg = msg
this.createdAt = createdAt
}
static toHTML ({msg, createdAt}) {
// pass object, builds list item.
try{
//in case the date conversion fails.
createdAt = (new Date(createdAt))
.toTimeString()
.substr(0,5)
} catch(e){ console.log(e) }
finally{ createdAt || "" }
return `<li><span>${msg}</span> &nbsp; <span>${createdAt}</span></li>`
}
static put (data) {
$("#messages").prepend(this.toHTML(data))
}
static getMsgs (uri, skip, limit) {
//returns a promise, errors are catch
return fetch(`${uri}/messages/skip/${skip}/limit/${limit}`)
.then(data => data.json())
.then(items => items.forEach(item => this.put(item)))
}
static getLastMsgs (uri) { return this.getMsgs(uri, 0,10) }
}
$(function () { // $(document).ready(
Msg.getLastMsgs(uri).catch(e => console.log(e))
prevMsgs.addEventListener("click", () => {
const msgLen = parseInt($("#messages").children().length)
Msg.getMsgs(uri, msgLen, msgLen+10)
})
const socket = io(); //connects to / origin
$('form').submit(function(e) {
e.preventDefault(); // prevents page reloading
const msg = new Msg($('#m').val(), new Date())
//for the sender, append right away.
$("#messages").append(Msg.toHTML(msg))
// and emit, and broadcast
socket.emit('chat message', msg);
$('#m').val('');
return false;
});
socket.on('chat message', data => {
$("#messages").append(Msg.toHTML(data))
})
})
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-26T17:20:00.340",
"Id": "500787",
"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)."
}
] |
[
{
"body": "<p><strong>Be careful of IDs</strong>, especially those with common names, since they (unfortunately) automatically create properties on the global object when the ID is a valid identifier, which is <a href=\"https://stackoverflow.com/questions/484635/are-global-variables-bad\">not an uncommon source of bugs</a> <a href=\"https://stackoverflow.com/q/29360290\">2</a>. Here, you have <code>#messages</code>, which is probably a pretty common word related to your script. It's not <em>likely</em> to be a problem in most cases, but I'd feel more comfortable using a class instead.</p>\n<p><strong>CSS tweak</strong> Due to positioning, the <code>send</code> button appears to have an unusually thick border on the right. Consider using <code>width: 9.5%;</code> instead of <code>width: 9%;</code>. You could also consider using flex for the <code><form></code> instead, and only set an explicit width of a few % for the button, letting the <code><input></code> horizontally expand to take up the rest of the space automatically, without hard-coding.</p>\n<p><strong>jQuery?</strong> You have a few uses of <code>$</code> that look like uses of jQuery, but it doesn't appear to exist as a <code><script></code> in the HTML. Make sure to include it. If jQuery is included via a build process like Webpack (which is a perfectly reasonable approach) but simply not listed in the code here, consider also including socket.io the same way, for consistency and to reduce the number of requests the client has to make before the page becomes operational.</p>\n<p>If you are indeed intending to use jQuery, then for stylistic consistency, consider using it for DOM selection and event listeners <em>everywhere</em>, rather than sometimes using jQuery and sometimes using <code>querySelector</code> and <code>addEventListener</code>.</p>\n<p><strong>Indentation</strong> Consistent indentation improves readability, when one can understand the <code>{</code> <code>}</code> blocks at a glance. Lots of IDEs have an auto-formatting feature, consider taking advantage of it. Eg</p>\n<pre><code> }\nstatic toHTML ({msg, createdAt}) {\n// pass object, builds list item.\n try{\n</code></pre>\n<p>should be</p>\n<pre><code> }\n static toHTML ({msg, createdAt}) {\n // pass object, builds list item.\n try {\n</code></pre>\n<p><strong>Creation of invalid dates won't throw</strong> - the <code>try</code>/<code>catch</code> won't do anything. Worst case, <code>createdAt</code> will end up containing the string <code>'Inval'</code> (from <code>Invalid Date</code>). The <code>finally</code> has an unused expression too - did you mean to <em>assign</em> to <code>createdAt</code> maybe? To check if the date is invalid, you could either check if the time string is <code>Invalid Date</code> first, or see if <code>getTime</code> returns <code>NaN</code>.</p>\n<p><strong><code>Msg</code> class</strong> That whole class seems odd to me, since it never uses its instance properties and only has static methods. The fact that the structure is a class isn't providing any organizational benefit for the code. Consider either:</p>\n<ul>\n<li>Use at least some prototype methods for the class instead, when the method uses data that should exist on an instance - so, <code>toHTML</code> and <code>put</code>. (<code>put</code> isn't a very informative name, maybe rename to <code>insertIntoDOM</code> or <code>renderMessage</code>)</li>\n<li>Remove the class entirely and use a plain array of objects and plain functions instead</li>\n</ul>\n<p><strong>Be careful when concatenating HTML with user input</strong>, because it can result in arbitrary code execution. With this:</p>\n<pre><code>`<li><span>${msg}</span>...\n</code></pre>\n<p>If <code>msg</code> contains unsafe code (either posted by another user, or if this user has been tricked into entering unsafe code), the current user could have all available sensitive data sent to a malicious third party.</p>\n<p>To fix it, create the <code><span></code> without any content at first, then assign to its <strong>text content</strong> afterwards, maybe something like:</p>\n<pre><code>// createdAt looks like it should always be trustworthy, so interpolation is OK\nconst $li = $(`<li><span></span> &nbsp; <span>${createdAt}</span></li>`);\n$li.find('span').text(msg);\nreturn $li;\n</code></pre>\n<p><strong>Catch errors</strong> If the <code>fetch</code> fails, it will not be caught if initiated from a click. Add a <code>.catch</code> onto <code>Msg.getMsgs(uri, msgLen, msgLen+10)</code>. In both this new <code>.catch</code> and the existing <code>.catch</code> on the <code>getLastMsgs</code> call, when there's an error, it'd be user-friendly to display the fact that there was an error to the user, perhaps in a popup, rather than just logging. After all, while developers look at the console to debug, normal users don't.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-26T16:04:49.993",
"Id": "500778",
"Score": "0",
"body": "I've just downloaded a minified, slim version of webpack from their site, do you think that's a reasonable approach?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-26T16:08:05.003",
"Id": "500779",
"Score": "0",
"body": "also the link to global variables is C/C++ is that what you intended?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-26T16:08:05.560",
"Id": "500780",
"Score": "0",
"body": "Via NPM, I hope? If so, yeah - see https://webpack.js.org/guides/getting-started/ for examples. It's somewhat complicated. It's well worth it in larger projects, or maybe in smaller projects *if you're already familiar with how it works*, but if you haven't used it before I wouldn't bother for something this small."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-26T16:09:35.097",
"Id": "500781",
"Score": "1",
"body": "Despite the question being tagged with C++, the [top answer there](https://stackoverflow.com/a/485020) applies to problems with global variables in most languages."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-26T19:02:40.487",
"Id": "500799",
"Score": "0",
"body": "`<li><span>${msg}</span>` how is this dangerous if it's coming from `input.value` isn't this a string already? i've tried inputting \"console.log(\"hello\")\" for example but no problems."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-26T19:04:46.597",
"Id": "500800",
"Score": "1",
"body": "It is a string, but it may be an unsafe string that contains untrustworthy code. Consider if someone not very tech-savvy gets an email or something saying: \"Copy and paste in the following text into the message box, you won't believe what happens next!\" - and then their personal information and login credentials get stolen. Eg `<img src onerror=\"alert('evil')\">` but with the `alert(\"evil\")` replaced with malicious code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-26T19:08:04.220",
"Id": "500801",
"Score": "0",
"body": "could you give an example I can actually test? (in the current code)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-26T19:11:08.653",
"Id": "500802",
"Score": "0",
"body": "Here's an example https://jsfiddle.net/awgodfsk/ jQuery's `.prepend` has the same vulnerability"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-26T19:24:45.990",
"Id": "500803",
"Score": "0",
"body": "Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/117714/discussion-between-minsky-and-certainperformance)."
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-26T15:43:51.513",
"Id": "253930",
"ParentId": "253912",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "253930",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-25T20:57:57.820",
"Id": "253912",
"Score": "1",
"Tags": [
"javascript",
"socket"
],
"Title": "Implementing classes in Javascript"
}
|
253912
|
<p>I made this code in python using Open Notify API, there is something that I could improve?
Im new to coding and I'm almost 4 hours understanding and coding this program that let you interact by some inputs and it can give you information about how many people are in space now, where is the ISS now and when it will go through a given coordinate.</p>
<pre class="lang-py prettyprint-override"><code>import requests, json, os, datetime
clear = lambda: os.system('cls')
clear ()
def peopleInSpace():
responseAstros = requests.get("http://api.open-notify.org/astros.json")
astros = responseAstros.json()
people = astros['people']
peopleInSpa = []
for d in people:
peopleInSpa.append(d['name'])
print('There are', astros['number'], 'people in space, and their names are:', (', '.join(peopleInSpa)))
def issNowF():
responseIssNow = requests.get('http://api.open-notify.org/iss-now.json')
issNow = responseIssNow.json()
issNowLat = issNow['iss_position']['latitude']
issNowLon = issNow['iss_position']['longitude']
issNowTime = issNow['timestamp']
print('The International Space Station is right now (', datetime.datetime.fromtimestamp(issNowTime), ' GMT -3) on these approximately coordinates:', issNowLat, issNowLon)
def issNextTime():
clear()
lat = input("What is the latitude?")
lon = input('What is the longitude?')
parameters = {"lat":lat, "lon":lon }
responseIssNextTime = requests.get('http://api.open-notify.org/iss-pass.json', params=parameters)
issNextTime = responseIssNextTime.json()['response']
risetimes = []
for d in issNextTime:
time = d['risetime']
risetimes.append(time)
times = []
print("The next 5 times ISS is going to go through the given coordinates is:")
for rt in risetimes:
time = datetime.datetime.fromtimestamp(rt)
times.append(time)
print(time)
clear()
print('Press 1 to see how many people are in space right now')
print('Press 2 for getting the coordinates of the ISS right now')
print('Press 3 for seeing when the ISS will go through certain coordinates')
r = input('')
if r == '1':
clear()
peopleInSpace()
elif r == '2':
clear()
issNowF()
elif r == '3':
clear()
issNextTime()
else:
clear()
print('Please open the program again and press only 1, 2 or 3')
</code></pre>
|
[] |
[
{
"body": "<h1>Cross-platform console clear</h1>\n<p>Instead of <code>clear = lambda: os.system('cls')</code> try to use a more cross-platform solution:</p>\n<pre><code>import os\n\n\ndef cls():\n os.system('cls' if os.name=='nt' else 'clear')\n</code></pre>\n<p>which you can then call as:</p>\n<pre><code>cls()\n</code></pre>\n<h1>Imports</h1>\n<p>Try writing your imports on separate lines and don't forget to remove the ones you're not using:</p>\n<pre><code>import datetime\nimport os\n\nimport requests\n</code></pre>\n<p>As you can see, I've also added an extra new line between <em>stdlib</em> modules and 3rd party modules. It's usually a good idea to do this as it improves readability.</p>\n<h1>Naming</h1>\n<p>In Python, the name of the variables and functions should be <em>snake_case</em>d. Meaning, instead of <code>def peopleInSpace()</code> you'd have <code>def people_in_space()</code> and instead of <code>responseAstros</code> you'd have <code>response_astros</code>.</p>\n<h1>Spacing & line wrapping</h1>\n<p>Try to add two new-lines (instead of one) between each function and try to end your lines somewhere between 79 - 100 chars. (I usually prefer to have more than 79 chars as specified in <a href=\"https://www.python.org/dev/peps/pep-0008/#maximum-line-length\" rel=\"nofollow noreferrer\">PEP8</a>)</p>\n<p>Let's see how your code looks if we take into account all the above suggestions:</p>\n<pre><code>import datetime\nimport os\n\nimport requests\n\n\ndef cls():\n os.system('cls' if os.name=='nt' else 'clear')\n\n\ndef people_in_space():\n response_astros = requests.get("http://api.open-notify.org/astros.json")\n astros = response_astros.json()\n people = astros['people']\n\n people_in_spa = []\n for d in people:\n people_in_spa.append(d['name'])\n \n print(f'There are {astros["number"]} people in space, and '\n f'their names are: {", ".join(people_in_spa)}')\n\n\ndef iss_now_f():\n response_iss_now = requests.get('http://api.open-notify.org/iss-now.json')\n iss_now = response_iss_now.json()\n\n iss_now_lat = iss_now['iss_position']['latitude']\n iss_now_lon = iss_now['iss_position']['longitude']\n iss_now_time = iss_now['timestamp']\n \n print(f'The International Space Station is right now '\n f'({datetime.datetime.fromtimestamp(iss_now_time)} GMT -3) '\n f'on these approximately coordinates: {iss_now_lat} {iss_now_lon}')\n\n\ndef iss_next_time():\n cls()\n \n lat = input("What is the latitude?")\n lon = input('What is the longitude?')\n \n parameters = {"lat":lat, "lon":lon }\n response_iss_next_time = requests.get(\n 'http://api.open-notify.org/iss-pass.json', params=parameters\n )\n \n iss_next_time_resp = response_iss_next_time.json()['response']\n rise_times = []\n for d in iss_next_time_resp:\n time = d['risetime']\n rise_times.append(time)\n \n times = []\n\n print("The next 5 times ISS is going to go through the given "\n "coordinates is:")\n \n for rt in rise_times:\n time = datetime.datetime.fromtimestamp(rt)\n times.append(time)\n print(time)\n\n\ncls()\n\nprint('Press 1 to see how many people are in space right now')\nprint('Press 2 for getting the coordinates of the ISS right now')\nprint('Press 3 for seeing when the ISS will go through certain coordinates')\n\nr = input('')\n\nif r == '1':\n cls()\n people_in_space()\nelif r == '2':\n cls()\n iss_now_f()\nelif r == '3':\n cls()\n iss_next_time()\nelse:\n cls()\n print('Please open the program again and press only 1, 2 or 3')\n</code></pre>\n<p>Looks already a bit nicer, isn't it? ^_^</p>\n<p>Now, let's focus on improvements:</p>\n<p>In <code>people_in_space</code> function, we can use <a href=\"https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions\" rel=\"nofollow noreferrer\">list comprehensions</a> and also wrap that request call into a try / except guard so we can catch any possible request exceptions:</p>\n<pre><code>def people_in_space():\n try:\n response_astros = requests.get(\n "http://api.open-notify.org/astros.json"\n )\n except requests.exceptions.RequestException as req_exception:\n # raise an exception here or do w/e you want\n # I'm just going to exit (import sys module for this to work)\n sys.exit(f'Could not fetch people in space: {str(req_exception)}')\n \n astros = response_astros.json()\n people_in_spa = [d['name'] for d in astros['people']]\n\n print(f'There are {astros["number"]} people in space, and '\n f'their names are: {", ".join(people_in_spa)}')\n</code></pre>\n<p>The above recommendations can also be applied to <code>iss_next_time</code> function:</p>\n<pre><code>def iss_next_time():\n cls()\n\n lat = input("What is the latitude?")\n lon = input('What is the longitude?')\n\n parameters = {"lat": lat, "lon": lon}\n \n try:\n response_iss_next_time = requests.get(\n 'http://api.open-notify.org/iss-pass.json', params=parameters\n )\n except requests.exceptions.RequestException as req_exception:\n # raise an exception here or do w/e you want\n # I'm just going to exit (import sys module for this to work)\n sys.exit(f'Could not fetch next time: {str(req_exception)}')\n\n iss_next_time_resp = response_iss_next_time.json()['response']\n \n print("The next 5 times ISS is going to go through the given "\n "coordinates is:")\n \n for item in iss_next_time_resp:\n print(datetime.datetime.fromtimestamp(item['risetime']))\n</code></pre>\n<p>I've removed the <code>times</code> list since you were appending things to it but didn't use it anywhere else. And I've also saved you some space complexity by directly iterating over the <code>iss_next_time_resp</code>.</p>\n<p>// LE:</p>\n<p>Even if your solution isn't bad at all, this is how I'd do it:</p>\n<pre><code>import datetime\nimport os\nimport sys\n\nimport requests\n\n\ndef clear_screen():\n """\n Clear the console.\n \n Warning: on specific OSs you might need to export the \n TERM env variable.\n \n """\n \n os.system('cls' if os.name == 'nt' else 'clear')\n\n\nclass OpenNotify:\n """\n API client wrapper for open-notify.org.\n """\n \n def __init__(self):\n self.base_url = 'http://api.open-notify.org'\n\n def _get(self, resource, params=None):\n """\n Abstract get method for all subsequent GET requests.\n \n Arguments:\n resource (str): Name of the resource.\n params (dict or None): If provided, dict of GET params.\n \n Returns:\n <requests.Response> object or raises exception\n """\n \n url = f'{self.base_url}/{resource}'\n\n try:\n return requests.get(url, params=params) if params else requests.get(url)\n except requests.exceptions.RequestException as req_exception:\n print(f'Could not retrieve data at url {url} because: '\n f'{str(req_exception)}')\n sys.exit()\n\n @staticmethod\n def _get_json_from_response(response, resource_item=None):\n """\n Decode response to json and get a specific resource \n item if provided.\n \n Arguments:\n response (requests.Response): The response\n resource_item (str or None): The desired resource item or None\n \n Returns:\n json object or raises an exception\n """\n \n try:\n json_data = response.json()\n except ValueError as val_error:\n print(str(val_error))\n sys.exit()\n\n if resource_item:\n return json_data.get(resource_item)\n\n return json_data\n\n\n def _get_astronauts_info(self):\n """\n Get astronauts information.\n \n Returns:\n json object\n """\n \n response = self._get('astros.json')\n return self._get_json_from_response(response)\n\n def _get_iss_data(self):\n """\n Get iss data (latitude, longitude and timestamp in GMT -3).\n \n Returns:\n dict\n """\n \n response = self._get('iss-now.json')\n timestamp = self._get_json_from_response(response, 'timestamp')\n\n return {\n 'latitude': self._get_json_from_response(response, 'iss_position')['latitude'],\n 'longitude': self._get_json_from_response(response, 'iss_position')['longitude'],\n 'timestamp': datetime.datetime.fromtimestamp(timestamp),\n }\n\n def _get_iss_next_position_time(self, latitude, longitude):\n """\n Get iss's next position time given the latitude \n and longitude.\n \n Arguments:\n latitude (str): The desired latitude\n longitude (str): The desired longitude\n \n Returns:\n json object\n """\n \n response = self._get(\n 'iss-pass.json',\n params={'lat': latitude, 'lon': longitude}\n )\n return self._get_json_from_response(response, 'response')\n\n def list_astros_info(self):\n astronauts_info = self._get_astronauts_info()\n astronauts_names = ", ".join([item["name"] for item in astronauts_info["people"]])\n\n print(f'There are {astronauts_info["number"]} people in space, and '\n f'their names are: {astronauts_names}')\n\n def list_iss_info(self):\n iss_info = self._get_iss_data()\n print(f'The International Space Station is right now '\n f'{iss_info["timestamp"]} GMT-3 on these approximately '\n f'coordinates: lat {iss_info["latitude"]} long {iss_info["longitude"]}')\n\n def list_iss_next_position_time(self, latitude, longitude):\n iss_next_position_info = self._get_iss_next_position_time(latitude, longitude)\n\n print('The next 5 times ISS is going to go through the '\n 'given coordinates is:')\n\n for item in iss_next_position_info:\n print(datetime.datetime.fromtimestamp(item['risetime']))\n\n\ndef main():\n print("""Choose from the options below:\n\n 1) See how many people are in space right now.\n 2) Get the coordinates of the ISS right now.\n 3) See when the ISS will go through certain coordinates.\n\n q) Exit\n """)\n\n user_input = input('Please choose an option: ')\n\n open_notify = OpenNotify()\n\n if user_input == '1':\n clear_screen()\n open_notify.list_astros_info()\n elif user_input == '2':\n clear_screen()\n open_notify.list_iss_info()\n elif user_input == '3':\n clear_screen()\n\n latitude = input('Please enter the latitude: ')\n longitude = input('Please enter the longitude: ')\n\n open_notify.list_iss_next_position_time(latitude, longitude)\n else:\n print('Invalid option')\n sys.exit()\n\n\nif __name__ == '__main__':\n main()\n</code></pre>\n<p>A few things to think about:</p>\n<ul>\n<li>There's still room for improvements in regards to user input validation;</li>\n<li>The retrieved API data can change and there're no sanity checks against this;</li>\n<li>The menu can be dynamically created in order to avoid hardcoding future next options;</li>\n<li>The <code>OpenNotify</code> class might be a bit redundant since we're not making changes to any specific state variables but as the API grows and you want to add other functionality to it...this might become helpful.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-27T21:00:18.547",
"Id": "500848",
"Score": "0",
"body": "thanks bro! some things you told on your awnser I dont even know how to use it, like a class, but im learning python and I did this program to understand more how Dictionaries and lists work and how to manage them, thanks for the detailed awnser!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-26T09:49:28.010",
"Id": "253922",
"ParentId": "253919",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "253922",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-26T03:28:20.757",
"Id": "253919",
"Score": "2",
"Tags": [
"python",
"python-3.x",
"api"
],
"Title": "Open Notify simple console application"
}
|
253919
|
<p>Apologies in advance for my english... <br></p>
<p>We have a list of categories and a list of doctors, you need to output as follows: <br></p>
<ul>
<li>category1
<ul>
<li>item1</li>
<li>item2</li>
<li>item3</li>
</ul>
</li>
<li>category2
<ul>
<li>item1</li>
<li>item2</li>
<li>item3</li>
</ul>
</li>
</ul>
<p>Here is what I was able to write:</p>
<pre><code>function renderChatList() {
let xhttp = new XMLHttpRequest();
let categoriesArr = [];
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
categoriesArr = JSON.parse(this.responseText);
categoriesArr.forEach((category) => {
getDoctorsGroup(category.id, category.title);
});
}
};
xhttp.open(
"POST",
"http://localhost/domen/api/readCategories.php",
true
);
xhttp.send();
}
renderChatList();
function getDoctorsGroup(id, title) {
let xhttp = new XMLHttpRequest();
let doctorsArr = [];
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
doctorsArr = JSON.parse(this.responseText);
let html = "";
html += '<div class="members-group">';
html += '<h4 class="members-group_title">';
html += `<span class="text">${title}</span>`;
html += '<span class="icon"><i class="far fa-ellipsis-h-alt"></i></span>';
html += '</h4>';
html += '<div class="members-group_list">';
doctorsArr.forEach(doctor => {
if(doctor.category == id) {
html += '<div class="member">';
html += '<div class="member-image user-image">';
html += `<img src="images/dist/doctors/${doctor.avatar}" alt="${doctor.name}">`;
html += '</div>';
html += '<div class="member-info">';
html += `<h3 class="member-name truncate-text-item">${doctor.name}</h3>`;
html += `<p class="member-job truncate-text-item">${doctor.job}</p>`;
html += '</div>';
html += '</div>';
}
})
html += '</div>';
html += '</div>';
// Insert group into list
const container = document.querySelector(".chat-list_members");
container.insertAdjacentHTML("beforeend", html);
}
}
xhttp.open(
"POST",
"http://localhost/domen/api/readDoctors.php",
true
);
xhttp.send();
}
</code></pre>
<p><strong>is it possible to optimize the code, or improve?</strong></p>
|
[] |
[
{
"body": "<p>There are few improvements which I will recommend:</p>\n<ol>\n<li>Use <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch\" rel=\"nofollow noreferrer\">fetch API</a> instead of XMLHttpRequest. Fetch is supported by almost every major browser and definitely serves as good replacement for XMLHttpRequest.</li>\n<li>Utilize template literals properly. I can see template literals getting used properly at some places, but converting multiple strings into one template literal string will avoid cluttering. Also, instead of creating HTML as string, proper DOM elements can also be created using <code>createElement</code> but I am not sure which one is performant. Maybe someone else will give us some input here.</li>\n<li>Utilize functional nature of JS to avoid cluttering. A lot of code can be broken even further into smaller logical pieces.</li>\n<li>Use <code>id</code> in <code>querySelector</code> at line <code>document.querySelector(".chat-list_members")</code>. The reason being, you can have multiple HTML elements with same classname. This leads to a possibility of bug or wrong element getting selected. Id is a better choice in these cases.</li>\n<li>Do error handling properly. The code seem to be handling cases when api is successful. A good code should also deal with cases when api fails or some error occurs.</li>\n</ol>\n<p>Here is how, I will restructure the code:</p>\n<pre class=\"lang-javascript prettyprint-override\"><code>function renderChatList() {\n fetch('http://localhost/domen/api/readCategories.php', { method: 'POST', })\n .then(response => response.json())\n .then(data => {\n data.forEach((category) => {\n getDoctorsGroup(category.id, category.title);\n });\n })\n .catch(error => {\n // Error handling here like alert/toast/popup etc\n });\n}\n\nrenderChatList();\n\nfunction getMemberHtml(doctorsArr, id){\n let html = ""\n doctorsArr.forEach(doctor => {\n if(doctor.category == id) {\n html += `<div class="member">\n <div class="member-image user-image">\n <img src="images/dist/doctors/${doctor.avatar}" alt="${doctor.name}" />\n </div>\n <div class="member-info">\n <h3 class="member-name truncate-text-item">${doctor.name}</h3>\n <p class="member-job truncate-text-item">${doctor.job}</p>\n </div>\n </div>`;\n }\n })\n return html; \n}\n\nfunction getDoctorsGroup(id, title) {\n fetch('http://localhost/domen/api/readDoctors.php', { method: 'POST', })\n .then(response => response.json())\n .then(data => {\n let html = "";\n html += `<div class="members-group">\n <h4 class="members-group_title">\n <span class="text">${title}</span>\n <span class="icon"><i class="far fa-ellipsis-h-alt"></i></span>\n </h4>\n <div class="members-group_list">\n ${getMemberHtml(data, id)}\n </div>\n </div>`;\n \n // Insert group into list\n const container = document.querySelector("#chat-list_members");\n container.insertAdjacentHTML("beforeend", html);\n })\n .catch(error => {\n // Error handling here like alert/toast/popup etc\n });\n}\n</code></pre>\n<p>Hope it helps. Revert for any doubts/clarifications.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-26T13:16:33.033",
"Id": "500767",
"Score": "0",
"body": "Thank you, I will take your advice under consideration. I am self-taught, so it is important for me that you share your opinion!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-26T11:44:36.923",
"Id": "253925",
"ParentId": "253920",
"Score": "3"
}
},
{
"body": "<p><strong>General Suggestions</strong></p>\n<ul>\n<li>There's no need to put the data type like "arr" into the variable name, it's just clutter. The fact that a variable name is plural should be a good indication that we're dealing with an array (or array-like value). (e.g. change categoriesArr to just categories)</li>\n<li>Prefer <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of\" rel=\"nofollow noreferrer\">for-of</a> over .forEach(). .forEach() came after for-in in helped fix many of the issues that for-in creates. In es6, for-of was introduced which can do everything that .forEach() can do and more, like iterating over any iterator, continue/break, async iteration, etc.</li>\n<li>Prefer the fetch API over XMLHttpRequest - it's meant to replace XMLHttpRequest, and it's more powerful and user-friendly than it's predecesor.</li>\n<li>It looks like each call to getDoctorsGroup() is making the same network request to retrieve a resource. It would be better to either fetch this resource beforehand and pass it in to getDoctorsGroup(), or cache the result. There's no need to fetch the same resource many times. Also note that your code currently has a bug where content will get added to the DOM depending on the order in which these network requests get resolved, so if they're resolved out of order, your categories may render out of order.</li>\n<li>On a related note, if you have control over the backend API, these requests should probably be GET requests, not POST requests, since you're just trying to retrieve a resource, not modify it.</li>\n</ul>\n<p><strong>XSS Concerns</strong></p>\n<p>XSS is one of the most common ways websites get hacked into, likely because it's so easy to slip up and create a vulnerability. While it's possible for an expert to safely use .innerHTML by following <a href=\"https://cheatsheetseries.owasp.org/cheatsheets/Cross_Site_Scripting_Prevention_Cheat_Sheet.html\" rel=\"nofollow noreferrer\">a number of escaping rules</a> to cleans unsafe data before inserting it into a template string (users of languages like PHP do this kind of expert work all the time), it's easier to just stay away from it in Javascript, particularly because alternative, safer tools exist to manipulate the DOM (like <code>document.createElement()</code>).</p>\n<p>You may find that the built-in DOM API isn't very convenient to use. There's nothing wrong with creating a little helper function to make working with the DOM a little nicer. Here's one that I like to use:</p>\n<pre><code>// USAGE:\n// The following javascript...\n// const myNewElement = el('div', { class: 'my-class' }, [\n// el('p', {}, ['Hello World!']),\n// el('hr'),\n// ])\n//\n// ...would produce the following DOM structure:\n// <div class="my-class">\n// <p>Hello World!</p>\n// <hr>\n// </div>\nfunction el(tagName, attrs = {}, children = []) {\n const newElement = document.createElement(tagName);\n for (const [key, value] of Object.entries(attrs)) {\n newElement.setAttribute(key, value);\n }\n newElement.append(...children);\n return newElement;\n}\n</code></pre>\n<p>Even with these precautions, some additional escaping may still be necessary. For example, when settings the src attribute of an image to <code>"images/dist/doctors/${doctor.avatar}"</code>, it might be a good idea to escape <code>doctor.avatar</code> with encodeURIComponent.</p>\n<p>Here's an example of how I might put your code together. I'm using the el() helper function as defined above to showcase one way you might go about replacing .innerHTML with something else.</p>\n<pre><code>// Initialize //\n\nwindow.addEventListener('DOMContentLoaded', async () => {\n document.querySelector('.chat-list_members')\n .append(await createChatList());\n});\n\n\n// Components //\n\nasync function createChatList() {\n const [categories, doctors] = await Promise.all([\n requestCategories(),\n requestDoctors(),\n ]);\n\n return fragment(\n categories.map(({ id, title }) => createCategory({ doctors, id, title })\n ));\n}\n\nfunction createCategory({ doctors, title, id }) {\n return el('div', { class: 'members-group' }, [\n createCategoryHeading({ title }),\n el('div', { class: 'members-group_list' }, [\n ...doctors\n .filter(doctor => doctor.category === id)\n .map(createDoctor)\n ])\n ]);\n}\n\nfunction createCategoryHeading({ title }) {\n return el('h4', { class: 'members-group_title' }, [\n el('span', { class: 'text' }, [title]),\n el('span', { class: 'icon' }, [\n el('i', { class: 'far fa-ellipsis-h-alt' })\n ]),\n ]);\n}\n\nfunction createDoctor({ name, job, avatar }) {\n return el('div', { class: 'member' }, [\n el('div', { class: 'member-image user-image' }, [\n el('img', { src: `images/dist/doctors/${encodeURIComponent(avatar)}`, alt: name }),\n ]),\n el('div', { class: 'member-info' }, [\n el('h3', { class: 'member-name truncate-text-item' }, [name]),\n el('p', { class: 'member-job truncate-text-item' }, [job]),\n ]),\n ]);\n}\n\n\n// Services //\n\nconst requestCategories = () => (\n fetch('http://localhost/domen/api/readCategories.php', { method: 'POST' })\n .then(response => response.json())\n);\n\nconst requestDoctors = () => (\n fetch('http://localhost/domen/api/readDoctors.php', { method: 'POST' })\n .then(response => response.json())\n);\n\n\n// Utilities //\n\n// Warning: Some attributes such as href, src, style, etc can not receive untrusted data without additional cleaning\n// (i.e. because of potential attack values such as href="javascript:maliciousCode()")\nfunction el(tagName, attrs = {}, children = []) {\n const newElement = document.createElement(tagName);\n for (const [key, value] of Object.entries(attrs)) {\n newElement.setAttribute(key, value);\n }\n newElement.append(...children);\n return newElement;\n}\n\nfunction fragment(children = []) {\n const newFragment = new DocumentFragment();\n newFragment.append(...children);\n return newFragment;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-29T07:58:08.203",
"Id": "254019",
"ParentId": "253920",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "253925",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-26T05:40:11.967",
"Id": "253920",
"Score": "3",
"Tags": [
"javascript",
"ajax"
],
"Title": "Display of doctors by category, ajax"
}
|
253920
|
<p>I have a NodeJS/Typescript project.</p>
<p>In <code>server.js</code>, I want to set my environment variables from a <code>.env</code> file. To achieve this, I am using the <a href="https://github.com/motdotla/dotenv#readme" rel="nofollow noreferrer"><code>dotenv</code> npm package</a>.</p>
<p>However, rather than leaving everything hanging in <code>server.ts</code>, I want to encapsulate this code. The solution I've come up is as follows.</p>
<p>The goal is for my project to adhere to SOLID and GRASP principles.</p>
<p>In <code>server.ts</code> I have the following:</p>
<pre><code>import { EnvVarsSetter } from "@server/controllers/env_vars_setter/env_vars_setter";
new EnvVarsSetter().init(".env.development");
</code></pre>
<p>In <code>src/controllers/env_vars_setter/env_vars_setter.ts</code> I have the following:</p>
<pre><code>import path from "path";
export class EnvVarsSetter {
public init(fileName: string): void {
const result = require("dotenv").config({
path: path.resolve(process.cwd(), fileName),
});
if (result.error) {
throw result.error;
}
console.log(`Successfully parsed and loaded env vars`);
}
}
</code></pre>
<p>Is this good design? Any suggestions on how to achieve my goal in a better way?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-27T09:09:18.063",
"Id": "500820",
"Score": "1",
"body": "I would be tempted to export the function directly, unless you have a reason to use a class specifically"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-28T04:25:06.953",
"Id": "500869",
"Score": "0",
"body": "@TedBrownlow I don't have a great reason to use a class other than the fact that I'm trying to use an object oriented approach to designing my entire nodejs app. I'm using a Java approach where everything is a class haha. Curious to get your thoughts on this."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-28T20:59:29.157",
"Id": "500964",
"Score": "1",
"body": "My main thought is just that setupEnvironmentVariables() would be more transparent in its naming. When I see a class being used, I assume there's some sort of state / configuration it can hold, which would give the illusion of something more complicated. Either way though, your abstractions make sense :)"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-26T10:37:08.910",
"Id": "253924",
"Score": "1",
"Tags": [
"javascript",
"object-oriented",
"design-patterns",
"typescript"
],
"Title": "How do I create an \"Environment Variable Setter\"?"
}
|
253924
|
<p>I have a static list of Strings (website urls), I am trying to connect to them and get responses, in syncRequests method, I am using HttpClient in synchronous manner, in asyncRequests method, I am using HttpClient in asynchronous manner. I am seeing some time differences between syncRequests and asyncRequests time, but I have a hunch I maybe doing something wrong or I can do something better.</p>
<p>Fellow stackexchange users, kindly review my code and let me know any changes or improvements that I can make.</p>
<p>Syntax wise I can make some changes related to modularizing the code, but what I want to understand is, improvements in terms of performance related to Completable Future and HttpClient. Below code is sort of a POC to understand CompletableFuture and check for any performance gains on response related processing.</p>
<p>Below is my code.</p>
<p>Thanks in advance.</p>
<p>`</p>
<pre><code> public class ProcessingList {
static List<String> urls = Arrays.asList("https://www.google.com", "https://www.reddit.com", "https://www.yahoo.co.in", "https://www.hackerrank.com", "https://devrant.com",
"https://docs.oracle.com/en/java/javase/11/docs/api/java.net.http/java/net/http/HttpClient.html",
"https://bing.com", "https://xkcd.com", "https://www.facebook.com", "https://www.amazon.co.in",
"https://www.flipkart.com");
public static void main(String[] args) {
long start = System.currentTimeMillis();
List<String> resp1 = syncRequests();
System.out.println("time taken 1:" + (System.currentTimeMillis() - start));
start = System.currentTimeMillis();
List<String> resp2 = asyncRequests();
System.out.println("time taken 1:" + (System.currentTimeMillis() - start));
}
private static List<String> syncRequests() {
HttpClient client = HttpClient.newBuilder()
.followRedirects(HttpClient.Redirect.NORMAL)
.version(HttpClient.Version.HTTP_2)
.build();
return urls.stream().map(url -> {
try {
HttpRequest request = HttpRequest.newBuilder().uri(new URI(url)).build();
HttpResponse<String> resp = client.send(request, HttpResponse.BodyHandlers.ofString());
return resp.body();
} catch (URISyntaxException | InterruptedException | IOException e) {
e.printStackTrace();
}
return "";
}).collect(Collectors.toList());//.forEach(System.out::println);
}
private static List<String> asyncRequests() {
List<CompletableFuture<String>> list = new ArrayList<>();
List<String> responses = new ArrayList<>();
ExecutorService service1 = Executors.newCachedThreadPool();
ExecutorService service2 = Executors.newCachedThreadPool();
HttpClient client = HttpClient.newBuilder()
.followRedirects(HttpClient.Redirect.NORMAL)
.version(HttpClient.Version.HTTP_2)
.build();
urls.parallelStream().forEach(url -> {
try {
HttpRequest request = HttpRequest.newBuilder().uri(new URI(url)).build();
list.add(
client
.sendAsync(request, HttpResponse.BodyHandlers.ofString())
.thenApplyAsync(HttpResponse::body, service1)
.whenCompleteAsync((resp, err) -> {
responses.add(resp);
}, service2)
);
} catch (URISyntaxException e) {
e.printStackTrace();
}
});
list.forEach(cf -> {
responses.add(cf.join());
});
service1.shutdown();
service2.shutdown();
return responses;
}
</code></pre>
<p><span class="math-container">`</span></p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-26T13:11:10.183",
"Id": "253927",
"Score": "2",
"Tags": [
"java",
"asynchronous"
],
"Title": "CompletableFuture in Java, code that gets responses from different websites using HttpClient in Java. What can I do better?"
}
|
253927
|
<p>This code animates sorting algorithms in the browser. I've included all the React components I've used and left out the individual sorting algorithm implementations.</p>
<p>SortingVisualiser.tsx</p>
<pre><code>import React, { useState } from "react";
import { insertionSort } from "../sortingAlgorithms/insertionSort";
import { quickSort } from "../sortingAlgorithms/quickSort";
import { heapSort } from "../sortingAlgorithms/heapSort";
import { selectionSort } from "../sortingAlgorithms/selectionSort";
import { wait, isSorted, randomArray } from "../utils";
import { Bar } from "./Bar";
import { Menu } from "./Menu";
import { bubbleSort } from "../sortingAlgorithms/bubbleSort";
import { fisherYates } from "../shufflingAlgorithms/fisherYates";
import { mergeSort } from "../sortingAlgorithms/mergeSort";
import { ArrayState } from "../arrayState";
import { countingSort } from "../sortingAlgorithms/countingSort";
const MIN_ARRAY_LEN = 100;
const MAX_ARRAY_LEN = 150;
type Algo = (arr: number[]) => ArrayState[];
export const SortingVisualiser = () => {
// Internal representation of the array we're sorting displayed on the screen
const [array, newArray] = useState(generateArray());
// Holds a string representation of the current algorithm user has selected
const [currSortingAlgo, newSortingAlgo] = useState("insertion-sort");
// A flag that is true if an algorithm is currently running, otherwise false
const [running, setRunning] = useState(false);
// User controlled multiplier for delays where lower delays mean faster animations
const [delayMultiplier, newDelayMultiplier] = useState(1);
// Maps the string representation of an algorithm to its implementation
const algoRepresentations = new Map<string, Algo>([
["insertion-sort", insertionSort],
["quick-sort", quickSort],
["heap-sort", heapSort],
["selection-sort", selectionSort],
["bubble-sort", bubbleSort],
["merge-sort", mergeSort],
["counting-sort", countingSort],
["shuffle", fisherYates],
]);
// Some algorithms run faster than others, so this map stores a different delay value for each algo
// Where a lower delay value means a faster animation
const relativeDelays = new Map<string, number>([
["insertion-sort", 1],
["bubble-sort", 1],
["heap-sort", 5],
["counting-sort", 20],
["quick-sort", 50],
["shuffle", 50],
["selection-sort", 50],
["merge-sort", 100],
]);
// Wrapper around newSortingAlgo hook to pass into the Menu component
function updateSortingAlgo(algo: string) {
newSortingAlgo(algo);
}
// Wrapper around newDelayMultiplier hook to pass into the Menu component
function updateDelayMultiplier(updatedDelayMultiplier: number) {
newDelayMultiplier(updatedDelayMultiplier);
}
// Generate an array object
function generateArray() {
const array = randomArray(MIN_ARRAY_LEN, MAX_ARRAY_LEN);
const swappedIndices = [null, null];
return { currArray: array, swappedIndices: swappedIndices };
}
// Generate array and update array state
function createNewArray() {
newArray(generateArray());
}
// Animate the current sorting algorithm the user has selected
function renderSortingAlgo() {
if (isSorted(array.currArray)) {
alert("Array already sorted!");
} else {
renderAlgo(currSortingAlgo);
}
}
// Animate the main shuffling algorithm
function renderShufflingAlgo() {
renderAlgo("shuffle");
}
// Animate the algorithm string represntation passed as a parameter
async function renderAlgo(algoStr: string) {
const algo = algoRepresentations.get(algoStr);
const delay = relativeDelays.get(algoStr);
const states = algo(array.currArray);
for (let i = 0; i < states.length; i++) {
await wait(delay * (1 / delayMultiplier));
newArray(states[i]);
setRunning(true);
}
setRunning(false);
}
return (
<>
<Menu
initialSortingAlgo={currSortingAlgo}
running={running}
sort={renderSortingAlgo}
shuffle={renderShufflingAlgo}
updateSortingAlgo={updateSortingAlgo}
createNewArray={createNewArray}
delayMultiplier={delayMultiplier}
updateDelayMultiplier={updateDelayMultiplier}
/>
<div className="array">
{array.currArray.map((elem, index) => (
<Bar
value={elem}
isSwapped={array.swappedIndices.includes(index)}
isSorted={isSorted(array.currArray)}
key={elem}
/>
))}
</div>
</>
);
};
</code></pre>
<p>Menu.tsx</p>
<pre><code>import React from "react";
interface Props {
initialSortingAlgo: string;
running: boolean;
sort: () => void;
shuffle: () => void;
updateSortingAlgo: (str: string) => void;
createNewArray: () => void;
delayMultiplier: number;
updateDelayMultiplier: (delayMultiplier: number) => void;
}
export const Menu = ({
initialSortingAlgo,
running,
sort,
shuffle,
updateSortingAlgo,
createNewArray,
delayMultiplier,
updateDelayMultiplier,
}: Props) => {
function handleUpdateSortingAlgo(event) {
updateSortingAlgo(event.target.value);
}
function handleUpdateDelayMultiplier(event) {
const delayMultiplierString: string = event.target.value;
const delayMultiplier = delayMultiplierString.slice(
1,
delayMultiplierString.length
);
updateDelayMultiplier(JSON.parse(delayMultiplier));
}
// Renders the same menu as default, but with all options removed
const emptyNavBar = (
<header>
<nav>
<ul id="menu">
<button className="empty-menu-button">-</button>
</ul>
</nav>
</header>
);
const menuNavBar = (
<header>
<nav>
<ul id="menu">
<select
value={initialSortingAlgo}
className="menu-button"
onChange={handleUpdateSortingAlgo}
>
<option value="insertion-sort">Insertion Sort</option>
<option value="quick-sort">Quick Sort</option>
<option value="heap-sort">Heap Sort</option>
<option value="selection-sort">Selection Sort</option>
<option value="bubble-sort">Bubble Sort</option>
<option value="merge-sort">Merge Sort</option>
<option value="counting-sort">Counting Sort</option>
</select>
<div>
<label htmlFor="select-speed" className="menu-text">
Toggle Speed:
</label>
<select
id="select-speed"
value={"x" + delayMultiplier.toFixed(1)}
className="menu-button"
onChange={handleUpdateDelayMultiplier}
>
<option value="x0.1">x0.1</option>
<option value="x0.5">x0.5</option>
<option value="x1.0">x1.0</option>
<option value="x1.5">x1.5</option>
</select>
</div>
<button className="menu-button" onClick={sort}>
Sort
</button>
<button className="menu-button" onClick={shuffle}>
Shuffle
</button>
<button className="menu-button" onClick={createNewArray}>
Create New Array
</button>
</ul>
</nav>
</header>
);
// We only want the user to access the menu when there's no animations running
if (running) {
return emptyNavBar;
} else {
return menuNavBar;
}
};
</code></pre>
<p>Bar.tsx</p>
<pre><code>import React from "react";
import { isWidescreen } from "../utils";
interface Props {
value: number;
isSwapped: boolean;
isSorted: boolean;
}
const HEIGHT_MULTIPLIER = isWidescreen ? 4.5 : 9;
const DEFAULT_COLOR = "rgb(127,219,255)";
const SWAP_COLOR = "rgb(255, 111, 97)";
const SORTED_COLOR = "rgb(0,255,127)";
export const Bar = ({ value, isSwapped, isSorted }: Props) => {
function getBarColor() {
if (isSorted) {
return SORTED_COLOR;
} else if (isSwapped) {
return SWAP_COLOR;
} else {
return DEFAULT_COLOR;
}
}
return (
<div
className="bar"
style={{
height: `${HEIGHT_MULTIPLIER * value}px`,
backgroundColor: getBarColor(),
}}
></div>
);
};
<span class="math-container">```</span>
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-26T15:34:47.243",
"Id": "253929",
"Score": "0",
"Tags": [
"sorting",
"react.js",
"typescript",
"data-visualization"
],
"Title": "Sorting Algorithm Visualiser in React with TypeScript"
}
|
253929
|
<p>I want to create two classes that accept values and perform operations on them. However, one of them is accepting numerical values - RollingStatisticsNumbers; and the other objects - RollingStatisticsObjects, with a specified weight. So they both implement Statistical interface that specifies calculation methods, but they have different add method signatures for adding values, that's why I'm creating two other interfaces that extend the Statistical... So I want for RollingStatisticsNumbers to have a type of Number and for RollingStatisticsObjects just any comparable type. The problem is that it violates Liskov Substitution Principle because of stricter preconditions on children, but I have no idea what other approaches to undertake.</p>
<p>Interfaces:</p>
<pre class="lang-java prettyprint-override"><code>public interface Statistical<T extends Comparable<T>> {
Double getMean();
Double getMedian();
Double getSum();
Double getStandardDeviation();
List<T> getData();
}
</code></pre>
<pre class="lang-java prettyprint-override"><code>public interface StatisticalWithoutWeight<T extends Number & Comparable<T>> extends Statistical<T> {
void add(T value);
}
</code></pre>
<pre class="lang-java prettyprint-override"><code>public interface StatisticalWithWeight<T extends Comparable<T>> extends Statistical<T> {
void add(T value, int weight);
}
</code></pre>
<p>Classes:</p>
<pre class="lang-java prettyprint-override"><code>public class RollingStatisticsNumbers<T extends Number & Comparable<T>> implements StatisticalWithoutWeight<T> {
private List<T> values = new ArrayList<>();
@Override
public void add(T value) {
int left = 0;
int right = values.size() - 1;
if (right == -1) {
values.add(value);
return;
}
int mid = (left + right) / 2;
while (left <= right) {
mid = (left + right) / 2;
if (value.compareTo(values.get(mid)) < 0) right = mid - 1;
else if (value.compareTo(values.get(mid)) > 0) left = mid + 1;
else break;
}
if (value.compareTo(values.get(mid)) > 0) mid += 1;
values.add(mid, value);
}
@Override
public Double getMean() {
BigDecimal mean = new BigDecimal(0);
mean = BigDecimal.valueOf(getSum()).divide(new BigDecimal(values.size()), 2, RoundingMode.FLOOR);
return mean.doubleValue();
}
@Override
public Double getMedian() {
int length = values.size();
if (length % 2 == 0) {
int lowMidIndex = (length / 2) - 1;
BigDecimal low = BigDecimal.valueOf(values.get(lowMidIndex).doubleValue());
BigDecimal high = BigDecimal.valueOf(values.get(lowMidIndex + 1).doubleValue());
BigDecimal median = low.add(high).divide(new BigDecimal(2), 2, RoundingMode.FLOOR);
return median.doubleValue();
}
return values.get(length/2).doubleValue();
}
@Override
public Double getSum() {
BigDecimal sum = new BigDecimal(0);
for (T value: values) {
sum = sum.add(BigDecimal.valueOf(value.doubleValue()));
}
return sum.doubleValue();
}
@Override
public Double getStandardDeviation() {
Double mean = getMean();
BigDecimal deviation = new BigDecimal(0);
for (T value: values) {
BigDecimal e = BigDecimal.valueOf((value.doubleValue() - mean));
e = e.pow(2);
deviation = deviation.add(e);
}
deviation = deviation.divide(new BigDecimal(values.size()), 2, RoundingMode.FLOOR);
MathContext mc = new MathContext(10);
deviation = deviation.sqrt(mc);
return deviation.doubleValue();
}
@Override
public List<T> getData() {
return values;
}
}
</code></pre>
<pre class="lang-java prettyprint-override"><code>public class RollingStatisticsObjects<T extends Comparable<T>> implements StatisticalWithWeight<T> {
private RollingStatisticsNumbers<Integer> rollingStatisticsNumbers = new RollingStatisticsNumbers<>();
private List<T> values = new ArrayList<>();
@Override
public void add(T value, int weight) {
rollingStatisticsNumbers.add(weight);
values.add(value);
}
@Override
public Double getMean() {
return rollingStatisticsNumbers.getMean();
}
@Override
public Double getMedian() {
return rollingStatisticsNumbers.getMedian();
}
@Override
public Double getSum() {
return rollingStatisticsNumbers.getSum();
}
@Override
public Double getStandardDeviation() {
return rollingStatisticsNumbers.getStandardDeviation();
}
@Override
public List<T> getData() {
return values;
}
}
</code></pre>
<p>Example of usage:</p>
<pre class="lang-java prettyprint-override"><code>public class App
{
public static void main( String[] args )
{
StatisticalWithoutWeight<Double> statisticalWithoutWeight = RollingStatistics.getStatisticsObjectNumbers();
statisticalWithoutWeight.add(2.0);
statisticalWithoutWeight.add(2.0);
statisticalWithoutWeight.add(2.0);
statisticalWithoutWeight.add(7.0);
statisticalWithoutWeight.add(3.0);
System.out.println(statisticalWithoutWeight.getData());
System.out.println(statisticalWithoutWeight.getMean());
System.out.println(statisticalWithoutWeight.getMedian());
System.out.println(statisticalWithoutWeight.getSum());
System.out.println(statisticalWithoutWeight.getStandardDeviation());
Person person1 = new Person("John", "male", 25);
Person person2 = new Person("Mia", "female", 27);
Person person3 = new Person("Bob", "male", 21);
StatisticalWithWeight<Person> statisticalWithWeight = RollingStatistics.getStatisticsObject();
statisticalWithWeight.add(person1, person1.getAge());
statisticalWithWeight.add(person2, person2.getAge());
statisticalWithWeight.add(person3, person3.getAge());
System.out.println(statisticalWithWeight.getData());
System.out.println(statisticalWithWeight.getMean());
System.out.println(statisticalWithWeight.getMedian());
System.out.println(statisticalWithWeight.getSum());
System.out.println(statisticalWithWeight.getStandardDeviation());
}
}
public class Person implements Comparable<Person>{
private String name;
private String sex;
private int age;
public Person(String name, String sex, int age) {
this.name = name;
this.sex = sex;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public int compareTo(Person o) {
return this.age - o.age;
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("Person{");
sb.append("name='").append(name).append('\'');
sb.append(", sex='").append(sex).append('\'');
sb.append(", age=").append(age);
sb.append('}');
return sb.toString();
}
}
</code></pre>
<p>output:
[2.0, 2.0, 2.0, 3.0, 7.0]
3.2
2.0
16.0
1.939071943
[Person{name='John', sex='male', age=25}, Person{name='Mia', sex='female', age=27}, Person{name='Bob', sex='male', age=21}]
24.33
25.0
73.0
2.493992783</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-26T16:43:42.600",
"Id": "500784",
"Score": "2",
"body": "[Edit] the question to include the output _as text_, not an image. And, for completeness, include somewhere what the \"LSP\" acronym stands for because not everybody would know."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-26T17:19:39.697",
"Id": "500786",
"Score": "2",
"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)."
}
] |
[
{
"body": "<p><a href=\"https://quuxplusone.github.io/blog/2020/10/09/when-to-derive-and-overload/\" rel=\"nofollow noreferrer\">Inheritance is for sharing an interface.</a> The <em>only</em> reason to create a base class <code>Statistical</code> would be if you're planning to write some polymorphic code</p>\n<pre><code>void doSomeComputation(Statistical stats) {\n Double stddev = stats.getStandardDeviation();\n ...\n}\n</code></pre>\n<p>The code you posted doesn't do any polymorphism; therefore it doesn't need any inheritance relationships. Just make <code>RollingStatisticsNumbers</code> and <code>RollingStatisticsObjects</code> two different classes, with no inheritance at all.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-26T17:47:53.000",
"Id": "253933",
"ParentId": "253931",
"Score": "4"
}
},
{
"body": "<p>I'm a little bit confused by how you decided to structure and approach this.</p>\n<p>From what I can see, <code>StatisticalWithoutWeight</code> and <code>StatisticalWithWeight</code> are actually <em>the same thing</em> but you decided to treat them different for some reason. At least from your example, everything boils down to <code>Number</code>s. So what you very likely want, is a single class, with no interfaces, which accepts a single <code>Object</code> that can tell the class what value to use.</p>\n<pre class=\"lang-java prettyprint-override\"><code>public interface DataPoint {\n public int getStatisticalValue();\n}\n\npublic class Statistical {\n public Double getMean();\n public Double getMedian();\n public Double getSum();\n public Double getStandardDeviation();\n public List<T> getData();\n public void add(DataPoint dataPoint);\n}\n</code></pre>\n<p>With that in place, you can create yourself a convenience <code>DataPoint</code>:</p>\n<pre class=\"lang-java prettyprint-override\"><code>public class ProvidingDataPoint implements DataPoint {\n public <TYPE> ProvidingDataPoint(TYPE instance, IntFunction<TYPE> valueProvider);\n}\n</code></pre>\n<p>That would allow you to do:</p>\n<pre class=\"lang-java prettyprint-override\"><code>statistical.add(new ProvidingDataPoint(person, (person) -> person.getAge()));\n</code></pre>\n<p>Or with a convenience method on statistical itself:</p>\n<pre class=\"lang-java prettyprint-override\"><code>statistical.add(person, Person::getAge);\n</code></pre>\n<p>Of course, that's not perfect. Ideally, <code>DataPoint</code> would return a <code>BigDecimal</code>. Overall, your usage of <code>Double</code> is odd, I'd expect either <code>int</code>s or <code>BigDecimal</code>, given that you do your calculations already in that you might as well provide the user of your class with the more precise values.</p>\n<hr />\n<p>Thinking a little bit more about it, a better alternative would most likely be to have the provider of values added to the <code>Statistical</code> class and specialize it on a single type of value, like this:</p>\n<pre class=\"lang-java prettyprint-override\"><code>public class Statistical<DATAPOINT_TYPE> {\n public Statistical(Function<DATAPOINT_TYPE, BigDecimal> valueProvider);\n public BigDecimal getMean();\n public BigDecimal getMedian();\n public BigDecimal getSum();\n public BigDecimal getStandardDeviation();\n public List<DATAPOINT_TYPE> getData();\n public Statistical<DATAPOINT_TYPE> add(DATAPOINT_TYPE datapoint);\n}\n</code></pre>\n<p>That means that you can use it like this:</p>\n<pre class=\"lang-java prettyprint-override\"><code>Statistical<Person> statistical = new Statistical<>((person) -> person.getAge());\nstatistical.add(personA);\n</code></pre>\n<hr />\n<p>As said before, I'd expose all values as <code>BigDecimal</code> to provide the user of the class with most precision.</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code> public List<T> getData() {\n return values;\n }\n</code></pre>\n<p>You're exposing internal state through this. Somebody can use the returned <code>List</code> to add <code>Object</code>s without having to call <code>add</code>, which might or might not be wanted.</p>\n<p>Ideally, you'd return a <code>Collections.unmodifiableList(values)</code> here, or a copy.</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code>MathContext mc = new MathContext(10);\n</code></pre>\n<p>Unlikely, yes, but could still not be enough depending on what values are being sampled.</p>\n<hr />\n<p>Having talked about that you should not expose internal state and that you should control adding values through the <code>add</code> function, it might be beneficial to cache some of these values when possible, so that multiple calls to the function do not recalculate the values. Otherwise I'd make clear that the operation might be expensive, for example by naming the methods correctly <code>calculateMean</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-29T06:39:10.893",
"Id": "500984",
"Score": "0",
"body": "Nice review! The example `new Statistical<>((person) -> person.getAge())`, requires `Person#getAge` to return a `BigDecimal`, which is not ideal. Maybe you mean `new Statistical<>((p)->new BigDecimal(p.getAge()))`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-29T21:00:17.720",
"Id": "501029",
"Score": "0",
"body": "True, though, I'd go with `BigDecimal.valueOf` to give a cache a chance."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-26T20:06:28.283",
"Id": "253937",
"ParentId": "253931",
"Score": "3"
}
},
{
"body": "<p>Previous answers already deal with code quality, I'll focus on algorithm and performance here.</p>\n<p>If one doesn't need the median, then this class is extremely wasteful and slow. It's O(n) time to add a value because of your sorted insert and it having to move values around in the array list. Not to mention that it's O(n) memory in the number of samples this is limiting it's usability. Using a linked list wouldn't help as you lose O(1) random access and gain O(n) random access which makes the binary search suffer instead. A set wouldn't work either as it would prohibit adding duplicate values which is unreasonable for counting statistics.</p>\n<p>I would split the interface into <code>FastStatistics</code> and <code>MedianStatistics</code> or something similar and for the fast statistics class use the <a href=\"https://en.m.wikipedia.org/wiki/Standard_deviation#Rapid_calculation_methods\" rel=\"nofollow noreferrer\">mean and sum of squares method</a> to compute the mean and variance in O(1) time and memory. And only if the median is needed keep the samples in a list, at indicated by using the median statistics object.</p>\n<p>As for computing the median, I wouldn't insertion sort into the vector, insertion sort is among the slower sorts.</p>\n<p>In fact, if you want the median of n samples, you need to insert n times, meaning you'll have O(n^2) time complexity. If you instead quicksort when calling getmean (possibly keeping a isSorted flag to avoid resorting every time you call it, although quicksort is usually fast on an already sorted array) you'll instead have O(n*log(n)) time complexity which is heaps faster.</p>\n<p>If you need the median frequently, like between each sample the above could possibly be slower. We're talking O(n^2) of insertion sort vs O(n^2*log(n)) of quicksort, quicksort is slower by a little bit but I think the constant factor may play a large role here and depending on your quicksort implementation it might be faster on almost sorted arrays... Benchmarking needed.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-27T13:31:56.223",
"Id": "253955",
"ParentId": "253931",
"Score": "3"
}
},
{
"body": "<p>The others gave excellent answers, here's a little more tweaking.</p>\n<h2>Always add curly braces to <code>loop</code> & <code>if</code></h2>\n<p>In my opinion, it's a bad practice to have a block of code not surrounded by curly braces; I saw so many bugs in my career related to that, if you forget to add the braces when adding code, you break the logic / semantic of the code.</p>\n<h2>Use the constants that <code>java.math.BigDecimal</code> / <code>java.math.BigInteger</code> gives you instead of creating a new instance.</h2>\n<p>Those’s classes expose some of the most uses numbers (<code>BigDecimal.ZERO</code>, ect) that you can use instead of <code>new BigDecimal(0)</code>.</p>\n<h2>Instead of using <code>java.math.BigDecimal#pow(int)</code>, use the multiplication</h2>\n<p>In some cases, the <code>pow</code> method tend to be slower than using the multiplication.</p>\n<p><strong>Before</strong></p>\n<pre class=\"lang-java prettyprint-override\"><code>e = e.pow(2);\n</code></pre>\n<p><strong>After</strong></p>\n<pre class=\"lang-java prettyprint-override\"><code>e.multiply(e);\n</code></pre>\n<h2>RollingStatisticsNumbers class</h2>\n<h3>Extract some of the logic to methods.</h3>\n<p>When you have logic that does the same thing, you can generally move it into a method and reuse it.</p>\n<p>I suggest the following:</p>\n<p>A<code>divideBy</code> method to divide a number and floor it.</p>\n<pre class=\"lang-java prettyprint-override\"><code>private BigDecimal divideBy(BigDecimal number, int size) {\n return number.divide(new BigDecimal(size), 2, RoundingMode.FLOOR);\n}\n</code></pre>\n<p>A <code>getValueOf</code> method to create a new <code>java.math.BigDecimal</code> from the template.</p>\n<pre class=\"lang-java prettyprint-override\"><code>private BigDecimal getValueOf(T t) {\n return BigDecimal.valueOf(t.doubleValue());\n}\n</code></pre>\n<h3>RollingStatisticsNumbers#getMean method</h3>\n<p>The double initialization of the <code>mean</code> variable is useless; you can remove the <code>new BigDecimal(0)</code> since the <code>RollingStatisticsNumbers#divideBy</code> will override the result in all cases.</p>\n<p><strong>Before</strong></p>\n<pre class=\"lang-java prettyprint-override\"><code>@Override\npublic Double getMean() {\n BigDecimal mean = new BigDecimal(0);\n mean = divideBy(BigDecimal.valueOf(getSum()), values.size());\n return mean.doubleValue();\n}\n</code></pre>\n<p><strong>After</strong></p>\n<pre class=\"lang-java prettyprint-override\"><code>@Override\npublic Double getMean() {\n return divideBy(BigDecimal.valueOf(getSum()), values.size()).doubleValue();\n}\n</code></pre>\n<h1>Refactored code</h1>\n<pre class=\"lang-java prettyprint-override\"><code>public class RollingStatisticsNumbers<T extends Number & Comparable<T>> implements StatisticalWithoutWeight<T> {\n\n private List<T> values = new ArrayList<>();\n\n @Override\n public void add(T value) {\n int left = 0;\n int right = values.size() - 1;\n if (right == -1) {\n values.add(value);\n return;\n }\n\n int mid = (left + right) / 2;\n while (left <= right) {\n mid = (left + right) / 2;\n if (value.compareTo(values.get(mid)) < 0) {\n right = mid - 1;\n } else if (value.compareTo(values.get(mid)) > 0) {\n left = mid + 1;\n } else {\n break;\n }\n }\n if (value.compareTo(values.get(mid)) > 0) {\n mid += 1;\n }\n values.add(mid, value);\n }\n\n @Override\n public Double getMean() {\n return divideBy(BigDecimal.valueOf(getSum()), values.size()).doubleValue();\n }\n\n @Override\n public Double getMedian() {\n int length = values.size();\n if (length % 2 == 0) {\n int lowMidIndex = (length / 2) - 1;\n BigDecimal low = getValueOf(values.get(lowMidIndex));\n BigDecimal high = getValueOf(values.get(lowMidIndex + 1));\n BigDecimal median = divideBy(low.add(high), 2);\n return median.doubleValue();\n }\n return values.get(length / 2).doubleValue();\n }\n\n @Override\n public Double getSum() {\n BigDecimal sum = BigDecimal.ZERO;\n for (T value : values) {\n sum = sum.add(getValueOf(value));\n }\n return sum.doubleValue();\n }\n\n @Override\n public Double getStandardDeviation() {\n Double mean = getMean();\n BigDecimal deviation = BigDecimal.ZERO;\n for (T value : values) {\n BigDecimal e = BigDecimal.valueOf((value.doubleValue() - mean));\n e = e.pow(2);\n deviation = deviation.add(e);\n }\n deviation = divideBy(deviation, values.size());\n MathContext mc = new MathContext(10);\n deviation = deviation.sqrt(mc);\n return deviation.doubleValue();\n }\n\n private BigDecimal getValueOf(T t) {\n return BigDecimal.valueOf(t.doubleValue());\n }\n\n private BigDecimal divideBy(BigDecimal number, int size) {\n return number.divide(new BigDecimal(size), 2, RoundingMode.FLOOR);\n }\n\n @Override\n public List<T> getData() {\n return values;\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-28T23:33:16.760",
"Id": "254010",
"ParentId": "253931",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "254010",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-26T15:44:25.317",
"Id": "253931",
"Score": "2",
"Tags": [
"java",
"object-oriented",
"design-patterns"
],
"Title": "statistics classes with number and object inputs"
}
|
253931
|
<p>I made a script that-</p>
<ol>
<li>Reads numbers (nearly 30,000 different numbers) from a list, and applies the numbers to a specific position in the URL.</li>
<li>Then it searches for the value of 'PHE10' mentioned in the script on the website.</li>
<li>Then it stores the result as a .csv file in this format- 'the number from the list,' 'PHE10,' 'the value of PHE10.'</li>
</ol>
<p>A typical information displayed on the website looks like this in a tabular form-
<a href="https://i.stack.imgur.com/yn5Bo.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/yn5Bo.png" alt="enter image description here" /></a></p>
<p>Now, the problem is- I wanted the script to take the value of 'PHE10' from the 'Assgn1' column, but the code is taking values at random from the website.</p>
<p>Any suggestions to improve my code and improve its efficiency?
here's the website's source code- <a href="https://pastebin.com/Xva4q6eM" rel="nofollow noreferrer">https://pastebin.com/Xva4q6eM</a></p>
<p>Here's the autohotkey code-</p>
<pre><code>SetBatchLines, -1
min := 1 ; Course minimum
, max := 0 ; Course maximun
, limit := 0 ; Record limit (Cero means no limit)
, codeList := A_Desktop "\list.txt" ; List of codes
, results := A_Desktop "\phe10.csv" ; Results file
, out := "Code,Course,Assign 1" "`n" ; Headings of the file
, courses := ["PHE10"] ; Courses
, URL := "https://gradecard.ignou.ac.in/gradecardB/Result.asp?eno=#&program=BSC&hidden_submit=OK"
loop, read, % codeList
{
if (limit && A_Index >= limit)
{
break
}
html := getUrl(StrReplace(URL, "#", A_LoopReadline))
for i,code in courses
{
if (RegExMatch(html, "(" code ").+>(\d+)<", match))
{
line := A_LoopReadline ","
if (match)
{
if match2 between %min% and %max%
{
line .= match1 "," match2 "`n"
}
}
out .= line
}
}
}
loop {
if (!fileObj := FileOpen(results, "w-"))
{
MsgBox, 0x40010, ERROR, Could not update the file, please close any open instance of the document and click OK
}
fileObj.Write(out)
if (!ErrorLevel)
{
MsgBox, 0x40040, Finished, Task Completed!
}
fileObj.Close()
} until (!ErrorLevel)
getUrl(URL)
{
whr := ComObjCreate("WinHttp.WinHttpRequest.5.1")
whr.Open("GET", URL, true)
whr.Send()
whr.WaitForResponse()
return whr.ResponseText
}
#SingleInstance, force
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-26T18:34:53.460",
"Id": "253935",
"Score": "1",
"Tags": [
"performance",
"beginner",
"autohotkey"
],
"Title": "(AutoHotkey) Script taking random values from the website"
}
|
253935
|
<p>I have a function with multiple if else statements that I'm trying to simplify in Django</p>
<p>Is there a pattern or maybe a better modeling approach that I could use here?</p>
<p>The idea behind is to have a thumbs up, thumbs down behavior for each blog post</p>
<p>views.py</p>
<pre><code>@login_required
def blog_post_vote(request, slug):
post = get_object_or_404(BlogPost, slug=slug)
if request.method == "POST":
vote = request.POST['vote']
has_user_voted = BlogPostUserVote.objects.filter(blog_post=post, user=request.user).count()
if has_user_voted == 0:
if vote == "yes":
user_vote_yes = BlogPostUserVote(blog_post=post, user=request.user, vote_yes=1)
user_vote_yes.save()
if vote == "no":
user_vote_no = BlogPostUserVote(blog_post=post, user=request.user, vote_no=1)
user_vote_no.save()
else:
has_user_voted_yes = BlogPostUserVote.objects.filter(blog_post=post, user=request.user, vote_yes=1).count()
has_user_voted_no = BlogPostUserVote.objects.filter(blog_post=post, user=request.user, vote_no=1).count()
if vote == "yes" and has_user_voted_yes == 0:
user_vote_yes = BlogPostUserVote(blog_post=post, user=request.user, vote_yes=1)
user_vote_yes.save()
BlogPostUserVote.objects.filter(blog_post=post, user=request.user, vote_no=1).delete()
if vote == "no" and has_user_voted_no == 0:
user_vote_no = BlogPostUserVote(blog_post=post, user=request.user, vote_no=1)
user_vote_no.save()
BlogPostUserVote.objects.filter(blog_post=post, user=request.user, vote_yes=1).delete()
return redirect(request.META['HTTP_REFERER'])
</code></pre>
<p>models.py</p>
<pre><code>class BlogPost(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
image = models.ImageField(upload_to='images/', blank=True, null=True)
title = models.CharField(max_length=500)
# Slug = Short URL Label
slug = models.SlugField(unique=True)
content = models.TextField(null=True, blank=True)
publish_date = models.DateTimeField(
auto_now=False, auto_now_add=False, null=True, blank=True)
timestamp = models.DateTimeField(auto_now=True)
updated = models.DateTimeField(auto_now=True)
@property
def thumbs_up(self):
return BlogPostUserVote.objects.filter(blog_post=self).aggregate(Sum("vote_yes"))['vote_yes__sum']
@property
def thumbs_down(self):
return BlogPostUserVote.objects.filter(blog_post=self).aggregate(Sum("vote_no"))['vote_no__sum']
# This line is very important as it maps the objects to the default manager
objects = BlogPostManager()
# Ordering Newest to Oldest
class Meta:
ordering = ['-publish_date', '-updated', '-timestamp']
def get_absolute_url(self):
return f"/blog/{self.slug}"
class BlogPostUserVote(models.Model):
blog_post = models.ForeignKey(BlogPost, on_delete=models.CASCADE)
user = models.ForeignKey(User, on_delete=models.CASCADE)
vote_yes = models.SmallIntegerField(null=True, blank=True)
vote_no = models.SmallIntegerField(null=True, blank=True)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-26T22:03:26.110",
"Id": "500807",
"Score": "0",
"body": "What are `has_user_voted` and friends? Reading the variable name, I would think a boolean `True`/`False`. But you keep checking if `==0` instead."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-26T22:23:18.740",
"Id": "500808",
"Score": "0",
"body": "Hi, it is a query against the BlogPostUserVote table and if it finds any record with the given filter will return a number greather than 0. Not exactly a boolean though"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-27T08:41:20.097",
"Id": "500818",
"Score": "0",
"body": "Your title is too generic. Please read https://codereview.stackexchange.com/help/how-to-ask ."
}
] |
[
{
"body": "<p>Well finally I ended up with the following, I changed some names to make it more explanatory and the function to respond to an ajax request. However the logic is pretty much the same:</p>\n<pre><code>@login_required\n@csrf_exempt\ndef blog_post_reaction(request, slug):\n post = get_object_or_404(BlogPost, slug=slug)\n if request.is_ajax and request.method == "POST":\n reaction = json.loads(request.body)['vote']\n BlogPostUserReaction.objects.filter(blog_post=post, user=request.user).delete()\n new_user_reaction = BlogPostUserReaction(blog_post=post, user=request.user)\n if reaction == "upvote":\n new_user_reaction.upvote = 1\n if reaction == "downvote":\n new_user_reaction.downvote = 1\n if any((new_user_reaction.upvote, new_user_reaction.downvote)):\n new_user_reaction.save()\n return JsonResponse({'slug': slug, 'upvotes': post.upvote, 'downvotes': post.downvote})\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-27T19:36:01.207",
"Id": "253967",
"ParentId": "253938",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-26T20:48:54.870",
"Id": "253938",
"Score": "-1",
"Tags": [
"python",
"design-patterns",
"django",
"orm"
],
"Title": "django multiple if else refactor"
}
|
253938
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.